body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I was given this problem in an interview. </p>
<blockquote>
<p>Given two words <code>source</code> and <code>target</code>, and a list of words <code>words</code>, find the
length of the shortest series of edits that transforms <code>source</code> to
<code>target</code>. Each edit must change exactly one letter at a time, and each
intermediate word (and the final target word) must exist in <code>words</code>.</p>
<p>If the task is impossible, return <code>-1</code>.</p>
<p><strong>Examples:</strong></p>
<pre><code>source = "bit"
target = "dog"
words = ["but", "put", "big", "pot", "pog", "dog", "lot"]
</code></pre>
<p>Output: <code>5</code></p>
<p>Explanation: <code>bit</code> -> <code>but</code> -> <code>put</code> -> <code>pot</code> -> <code>pog</code> -> <code>dog</code> has 5
transitions.</p>
<pre><code>source = "no"
target = "go"
words = ["to"]
</code></pre>
<p>Output: <code>-1</code></p>
</blockquote>
<pre><code>def one_letter_difference(current_word, next_word):
count = 0
for i in range(len(current_word) -1):
if current_word[i] != next_word[i]:
count += 1;
if count == 1:
return True
else:
return False
def shortestWordEditPath(source, target, words):
"""
@param source: str
@param target: str
@param words: str[]
@return: int
Input: source = "bit", target = "dog"
words = ["but", "put", "big", "pot", "pog", "dog", "lot"]
Output: 5
explanation:
1 -> 1 -> 1 -> 1 -> 1
(source) bit -> but -> put -> pot -> pog -> dog (target)
has minimum of 5 transitions
"""
graph = {}
for i in range(-1, len(words)):
if i == -1:
current_word = source
else:
current_word = words[i]
graph[current_word] = []
for word in range(len(words)):
next_word = words[word]
if one_letter_difference(current_word, next_word):
graph[current_word].append(next_word)
#perform BFS
queue = collections.deque()
seen = set() # visited words
queue.append([source, 1])
seen.add(source)
while len(queue) > 0:
current, distance = queue.popleft()
if current == target: return distance
for neighbor in graph[current]:
if neighbor not in seen:
queue.append([neighbor, distance +1])
seen.add(neighbor)
return -1
source = "bit"
target = "dog"
words = ["but", "put", "big", "pot", "pog", "dog", "lot"]
test = shortestWordEditPath(source, target,words)
print(test)
</code></pre>
| [] | [
{
"body": "<p>Let's start with the good:</p>\n\n<ul>\n<li>You documented your public API!</li>\n<li>You used decently descriptive variable names</li>\n<li>You somewhat have a test case</li>\n<li>Your use of a dictionary is resourceful here. No need for some fancy <code>Node</code> class.</li>\n<li>You separated out some of the functionality to make the algorithm easier to reason about (checking if words are 1 edit distance apart)</li>\n</ul>\n\n<p>Here are some things I noticed that perhaps the interviewer did as well:</p>\n\n<ul>\n<li>Your formatting is inconsistent. PEP8 your code (4 space indents, space around operators).</li>\n<li>You mix <code>snake_case</code> and <code>camelCase</code>. Python typically prefers <code>snake_case</code>.</li>\n<li>You didn't document your internal function (not the end of the world, but it is a nice touch)</li>\n<li>You didn't indicate that your internal function was private by prefixing it with a <code>_</code> (my policy is always if it doesn't have a leading <code>_</code> it must be documented)</li>\n<li><code>if count == 1: return True else: return False</code> would concern me as an interviewer as it demonstrates that you may not understand boolean expressions. <code>return count == 1</code> would work. But this additionally would pose another concern for me. Namely, <code>one_letter_difference</code> could be a short circuited function, but you did not implement it this way. I also would name it differently, <code>one_letter_difference</code> doesn't say what it does. Also, this function does not care about current or next words, so don't call them that. We also typically try to avoid indexing in Python. You should use <code>zip</code> here. And not to pile on, but this function is also probably not correct. You should have test cases for it. I believe that <code>dog</code> to <code>doge</code> should be an edit distance of 1 as well. With that in mind:</li>\n</ul>\n\n\n\n<pre><code>def _is_one_edit_apart(word_a, word_b):\n if abs(len(word_a) - len(word_b)) > 1:\n # It is impossible for words differing by 2 or more letters in length to\n # be just one edit apart\n return False\n\n if len(word_a) != len(word_b):\n shorter_word, longer_word = \\\n (word_a, word_b) if len(word_a) < len(word_b) else (word_b, word_a)\n\n if longer_word.startswith(shorter_word) or longer_word.endswith(shorter_word):\n # The shorter word is a prefix or a suffix of the longer and\n # they differ by 1 character in length, so they are 1 edit apart\n return True\n\n num_edits = 0\n\n # We know that word_a and word_b are the same length, so zip won't truncate\n for a, b in zip(word_a, word_b):\n if a != b:\n num_edits += 1\n if num_edits > 1:\n return False\n\n return num_edits == 1\n</code></pre>\n\n\n\n<p>Note that you could also get clever here and make the edits a bit more succinct: <code>num_edits = sum(1 for a, b in zip(word_a, word_b) if a != b)</code>. This is up to you. This certainly reads better. The approach above likely performs better because it short circuits (stops when it finds more than 1 edit).</p>\n\n<ul>\n<li>Your graph construction is weird. <code>range(-1, len(words))</code> seems like it could lead to trouble if you aren't careful. Generally, prefer <code>for word in words</code>. It seems like you add the edges to your graph for the <code>current_word</code> twice as a result of this.</li>\n<li>Prefer <code>for word in words</code> to <code>for word in range(len(words))</code>. This may indicate to an interviewer that you don't understand Python iterators or common patterns. This could also be a comprehension (and probably should be a tuple since edges can't change): <code>graph[word] = tuple(other_word for other_word in words if _is_one_edit_apart(word, other_word))</code></li>\n<li>You should probably pull your BFS out into a helper function. It is used in your algorithm. It is not <em>part</em> of your algorithm. This way you can test it separately.</li>\n<li>BFS is also probably not the best approach here. Dijkstra's is more suitable because it can find the shortest path between two nodes (we can just assume the edges indicate edit distance and are all cost 1).</li>\n<li><code>queue.append([neighbor, distance +1])</code> should be a tuple not a list. You aren't going to mutate it. This would likely concern an interviewer.</li>\n<li>This is part of the question, but I don't like returning -1 for error. If you forget to handle this, this could lead to a problem (say you try to do math on the distance and assume it's always positive). You should be raising some sort of error. If I was asked to do something this silly, I would probably write my own function that raises and then provide an alternate API for this use case which wraps this function and converts the exception to a -1 out of principle.</li>\n<li><code>unittest</code> your code. Don't just throw a print statement and manually verify! And test all the pieces! This is why you separate out the one edit distance check and the BFS (well, Dijkstra's)</li>\n</ul>\n\n<p>There's another larger problem in my mind, which isn't specified by the question, but it's the kind of question that I'd expect an engineer who encountered this problem to explore: what is the use case? Is this is one off (eg. are we using different word lists with every query)? If the word list is reused, this algorithm is inefficient, because it constructs a graph for <em>each</em> query. If the word list remains the same, then you should build the graph up once and then only do Dijkstra's for each query. I would implement this with a class the encapsulates the built graph and provide external API to query for edit distances. Then you could provide a function that uses this class for a one off query (where the words list is unique--never to be used again) to satisfy this interview question.</p>\n\n<p>There is also an optimization you can make in constructing the graph. It is apparent from my revised <code>_is_one_edit_apart</code>. Namely, words can only be one edit apart if they are the same length or differ in length by only 1 character. So, when building the graph you can take this into account. Take all of the words group them by length. Then to build the part of the graph for length 1 words, you only have to consider length 1 or length 2 words. For length 2 words you have to consider length 1, 2, and 3 words. Etc. You original approach is always <code>O(n^2)</code>. This is still worst case <code>O(n^2)</code> but will average much better than this given a decent distribution of word lengths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:13:01.570",
"Id": "418380",
"Score": "1",
"body": "Oops, indeed I did!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T02:59:01.740",
"Id": "420194",
"Score": "0",
"body": "i am confused by what you did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T03:12:13.073",
"Id": "420196",
"Score": "0",
"body": "I made a math mistake (I believe) and someone pointed it out, but they deleted their comment."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:06:27.797",
"Id": "216230",
"ParentId": "216209",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216230",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T04:46:58.233",
"Id": "216209",
"Score": "4",
"Tags": [
"python",
"interview-questions"
],
"Title": "Find Shortest Word Edit Path in python"
} | 216209 |
<p>I have implemented two related shortest path algorithms for unweighted graphs in C89. My attempt was to learn some more idiomatic C constructs such as genericity (a client programmer should be able to plug in his/her graph data structures to the algorithms). Some questions:</p>
<ol>
<li>Is it a good idea to embed the unit tests of a data type in the same <code>*.c</code> files?</li>
<li>Is it a good idea to do rather explicit type casting in order to make <code>gcc -Wall -pendatic -ansi</code> shut up?</li>
<li>Might the code below rely on an antipattern?</li>
</ol>
<p><strong><em>Code</em></strong></p>
<p><strong>bidirectional_breadth_first_search.c</strong></p>
<pre><code>#include "bidirectional_breadth_first_search.h"
#include "list.h"
#include "queue.h"
#include "utils.h"
#include <limits.h>
#define NEIGHBOR_NODE_ITERATOR_HAS_NEXT child_node_iterator_has_next
#define NEIGHBOR_NODE_ITERATOR_NEXT child_node_iterator_next
typedef child_node_iterator neighbor_node_iterator;
list* bidirectional_breadth_first_search(void* source_node,
void* target_node,
child_node_iterator* child_iterator,
parent_node_iterator* parent_iterator,
size_t (*hash_function)(void*),
int (*equals_function)(void*, void*))
{
queue* queue_a;
queue* queue_b;
unordered_map* parents_a;
unordered_map* parents_b;
unordered_map* distance_a;
unordered_map* distance_b;
size_t dist_a;
size_t dist_b;
size_t best_cost;
void* touch_node;
void* current_node;
void* child_node;
void* parent_node;
if (!source_node
|| !target_node
|| !child_iterator
|| !parent_iterator
|| !hash_function
|| !equals_function)
{
return NULL;
}
queue_a = queue_alloc();
queue_b = queue_alloc();
parents_a = unordered_map_alloc(10,
1.0f,
hash_function,
equals_function);
parents_b = unordered_map_alloc(10,
1.0f,
hash_function,
equals_function);
distance_a = unordered_map_alloc(10,
1.0f,
hash_function,
equals_function);
distance_b = unordered_map_alloc(10,
1.0f,
hash_function,
equals_function);
queue_push_back(queue_a, source_node);
queue_push_back(queue_b, target_node);
unordered_map_put(parents_a, source_node, NULL);
unordered_map_put(parents_b, target_node, NULL);
unordered_map_put(distance_a, source_node, 0);
unordered_map_put(distance_b, target_node, 0);
best_cost = UINT_MAX;
touch_node = NULL;
while (queue_size(queue_a) > 0 && queue_size(queue_b) > 0)
{
dist_a = (size_t) unordered_map_get(distance_a, queue_front(queue_a));
dist_b = (size_t) unordered_map_get(distance_a, queue_front(queue_b));
if (touch_node && best_cost <= dist_a + dist_b)
{
return trace_back_path_bidirectional(touch_node,
parents_a,
parents_b);
}
current_node = queue_pop_front(queue_a);
dist_a = (size_t) unordered_map_get(parents_a, current_node);
dist_b = (size_t) unordered_map_get(parents_b, current_node);
if (unordered_map_contains_key(parents_b, current_node)
&&
best_cost > dist_a + dist_b)
{
best_cost = dist_a + dist_b;
touch_node = current_node;
}
child_iterator->child_node_iterator_init(child_iterator,
current_node);
while (child_iterator->child_node_iterator_has_next(child_iterator))
{
child_node = child_iterator->
child_node_iterator_next(child_iterator);
if (!unordered_map_contains_key(parents_a, child_node))
{
unordered_map_put(parents_a, child_node, current_node);
queue_push_back(queue_a, child_node);
}
}
child_iterator->child_node_iterator_free(child_iterator);
current_node = queue_pop_front(queue_b);
dist_a = (size_t) unordered_map_get(distance_a, current_node);
dist_b = (size_t) unordered_map_get(distance_b, current_node);
if (unordered_map_contains_key(parents_a, current_node)
&&
best_cost > dist_a + dist_b)
{
best_cost = dist_a + dist_b;
touch_node = current_node;
}
parent_iterator->parent_node_iterator_init(parent_iterator,
current_node);
while (parent_iterator->
parent_node_iterator_has_next(parent_iterator))
{
parent_node = parent_iterator->
parent_node_iterator_next(parent_iterator);
if (!unordered_map_contains_key(parents_b, parent_node))
{
unordered_map_put(parents_b, parent_node, current_node);
queue_push_back(queue_b, parent_node);
}
}
parent_iterator->parent_node_iterator_free(parent_iterator);
}
return NULL;
}
</code></pre>
<p><strong>breadth_first_search.c</strong></p>
<pre><code>#include "breadth_first_search.h"
#include "directed_graph_node.h"
#include "queue.h"
#include "list.h"
#include "unordered_map.h"
#include "unordered_set.h"
static list* trace_back_path(void* target_node, unordered_map* parents)
{
list* path = list_alloc(10);
void* node = target_node;
while (node)
{
list_push_front(path, node);
node = unordered_map_get(parents, node);
}
return path;
}
list* breadth_first_search(void* source_node,
void* target_node,
child_node_iterator* child_iterator,
size_t (*hash_function) (void*),
int (*equals_function) (void*, void*))
{
queue* q = queue_alloc();
unordered_map* parent_map =
unordered_map_alloc(10,
1.0f,
hash_function,
equals_function);
void* current_node;
void* child_node;
if (!source_node
|| !target_node
|| !child_iterator
|| !hash_function
|| !equals_function)
{
return NULL;
}
queue_push_back(q, source_node);
unordered_map_put(parent_map, source_node, NULL);
while (queue_size(q) > 0)
{
current_node = queue_pop_front(q);
if (equals_function(current_node, target_node))
{
return trace_back_path(target_node, parent_map);
}
child_iterator->child_node_iterator_init(child_iterator, current_node);
while (child_iterator->child_node_iterator_has_next(child_iterator))
{
child_node = child_iterator->
child_node_iterator_next(child_iterator);
if (!unordered_map_contains_key(parent_map, child_node))
{
unordered_map_put(parent_map, child_node, current_node);
queue_push_back(q, child_node);
}
}
child_iterator->child_node_iterator_free(child_iterator);
}
return NULL;
}
</code></pre>
<p>(The entire repository is <a href="https://github.com/coderodde/c.graph.v2" rel="nofollow noreferrer">here</a>.)</p>
| [] | [
{
"body": "<h3>Distance?</h3>\n<p>In your bidirectional search you have the concepts of distance and cost, but nowhere do you actually insert any distance values to your unordered maps, except to initialize each endpoint with distance zero. Therefore, you will always retrieve a zero distance from <code>distance_a</code> and <code>distance_b</code>, either because you asked for the distance to the endpoint, or because you asked for the distance to any other node, which will not exist in the map (and you will get back <code>NULL</code> which is casted to a zero distance).</p>\n<p>There are a couple of lines that are different than the others, but I think you made a copy paste error:</p>\n<blockquote>\n<pre><code> dist_a = (size_t) unordered_map_get(parents_a, current_node);\n dist_b = (size_t) unordered_map_get(parents_b, current_node);\n</code></pre>\n</blockquote>\n<p>Here, you have the wrong maps. These maps should be <code>distance_a</code> and <code>distance_b</code> instead of <code>parents_a</code> and <code>parents_b</code>. Otherwise the distances you get back will be pointer values (i.e. random addresses) rather than distance values.</p>\n<p>Your function still works because it will return the shortest path (by number of edges), simply because a breadth first search naturally does that. But you should either remove all the distance code if the graph is unweighted, or fix up the distance code if the graph is weighted.</p>\n<h3>Another copy paste error</h3>\n<p>I also think that this line is a copy paste error:</p>\n<blockquote>\n<pre><code> dist_b = (size_t) unordered_map_get(distance_a, queue_front(queue_b));\n</code></pre>\n</blockquote>\n<p>I think <code>distance_a</code> should be <code>distance_b</code> here.</p>\n<h3>Memory leaks</h3>\n<p>None of the queues and maps that you allocate are ever freed, thus causing memory leaks.</p>\n<h3>size_t vs pointer</h3>\n<p>Your unordered maps use <code>void *</code> as the type of the value stored but you often cast the result of a <code>get()</code> to a <code>size_t</code>. <a href=\"https://stackoverflow.com/questions/1464174/size-t-vs-uintptr-t\">According to this</a>, <code>size_t</code> could be larger or smaller than a pointer, which could lead to truncation of values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:20:58.877",
"Id": "418366",
"Score": "0",
"body": "Nice one, sir!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:01:04.887",
"Id": "216223",
"ParentId": "216210",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216223",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T06:09:23.320",
"Id": "216210",
"Score": "2",
"Tags": [
"c",
"library",
"pathfinding",
"c89"
],
"Title": "Uni- and bidirectional pseudo-generic shortest path finders in C89"
} | 216210 |
<p>In this post, I present a hash table -based set data structure written in C89:</p>
<p><strong><code>unordered_set.h</code></strong></p>
<pre><code>#ifndef UNORDERED_SET_H
#define UNORDERED_SET_H
#include <stdlib.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct unordered_set {
struct unordered_set_state* state;
} unordered_set;
typedef struct unordered_set_iterator unordered_set_iterator;
/***************************************************************************
* Allocates a new, empty set with given hash function and given equality *
* testing function. *
***************************************************************************/
unordered_set* unordered_set_alloc(size_t initial_capacity,
float load_factor,
size_t(*p_hash_function)(void*),
int (*p_equals_function)(void*, void*));
/***************************************************************************
* Adds 'p_element' to the set if not already there. Returns true if the *
* structure of the set changed. *
***************************************************************************/
int unordered_set_add(unordered_set* p_set, void* p_element);
/***************************************************************************
* Returns true if the set contains the element. *
***************************************************************************/
int unordered_set_contains(unordered_set* p_set, void* p_element);
/***************************************************************************
* If the element is in the set, removes it and returns true. *
***************************************************************************/
int unordered_set_remove(unordered_set* p_set, void* p_element);
/***************************************************************************
* Removes all the contents of the set. *
***************************************************************************/
void unordered_set_clear(unordered_set* p_set);
/***************************************************************************
* Returns the size of the set. *
***************************************************************************/
size_t unordered_set_size(unordered_set* p_set);
/***************************************************************************
* Checks that the set is in valid state. *
***************************************************************************/
int unordered_set_is_healthy(unordered_set* p_set);
/***************************************************************************
* Deallocates the entire set. Only the set and its nodes are deallocated. *
* The user is responsible for deallocating the actual data stored in the *
* set. *
***************************************************************************/
void unordered_set_free(unordered_set* p_set);
/***************************************************************************
* Returns the iterator over the set. The nodes are iterated in insertion *
* order. *
***************************************************************************/
unordered_set_iterator* unordered_set_iterator_alloc(unordered_set* p_set);
/***************************************************************************
* Returns the number of elements not yet iterated over. *
***************************************************************************/
size_t unordered_set_iterator_has_next(unordered_set_iterator* p_iterator);
/***************************************************************************
* Loads the next element in the iteration order. Returns true if advanced *
* to the next element. *
***************************************************************************/
int unordered_set_iterator_next(unordered_set_iterator* p_iterator,
void** pp_element);
/***************************************************************************
* Returns true if the set was modified during the iteration. *
***************************************************************************/
int unordered_set_iterator_is_disturbed(unordered_set_iterator* p_iterator);
/***************************************************************************
* Deallocates the set iterator. *
***************************************************************************/
void unordered_set_iterator_free(unordered_set_iterator* p_iterator);
/* Contains the unit tests. */
void unordered_set_test();
#ifdef __cplusplus
}
#endif
#endif /* UNORDERED_SET_H */
</code></pre>
<p><strong><code>unordered_set.c</code></strong></p>
<pre><code>#include "my_assert.h"
#include "unordered_set.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
typedef struct unordered_set_entry {
void* key;
struct unordered_set_entry* chain_next;
struct unordered_set_entry* prev;
struct unordered_set_entry* next;
} unordered_set_entry;
typedef struct unordered_set_state {
unordered_set_entry** table;
unordered_set_entry* head;
unordered_set_entry* tail;
size_t (*hash_function)(void*);
int (*equals_function) (void*, void*);
size_t mod_count;
size_t table_capacity;
size_t size;
size_t mask;
size_t max_allowed_size;
float load_factor;
} unordered_set_state;
struct unordered_set_iterator {
unordered_set* set;
unordered_set_entry* next_entry;
size_t iterated_count;
size_t expected_mod_count;
};
static unordered_set_entry* unordered_set_entry_alloc(void* key)
{
unordered_set_entry* entry = malloc(sizeof(*entry));
if (!entry)
{
return NULL;
}
entry->key = key;
entry->chain_next = NULL;
entry->next = NULL;
entry->prev = NULL;
return entry;
}
static const float MINIMUM_LOAD_FACTOR = 0.2f;
static const int MINIMUM_INITIAL_CAPACITY = 16;
static float maxf(float a, float b)
{
return a < b ? b : a;
}
static int maxi(int a, int b)
{
return a < b ? b : a;
}
/*******************************************************************************
* Makes sure that the load factor is no less than a minimum threshold. *
*******************************************************************************/
static float fix_load_factor(float load_factor)
{
return maxf(load_factor, MINIMUM_LOAD_FACTOR);
}
/*******************************************************************************
* Makes sure that the initial capacity is no less than a minimum allowed and *
* is a power of two. *
*******************************************************************************/
static size_t fix_initial_capacity(size_t initial_capacity)
{
size_t ret;
initial_capacity = maxi(initial_capacity, MINIMUM_INITIAL_CAPACITY);
ret = 1;
while (ret < initial_capacity)
{
ret <<= 1;
}
return ret;
}
unordered_set* unordered_set_alloc(size_t initial_capacity,
float load_factor,
size_t(*hash_function)(void*),
int (*equals_function)(void*, void*))
{
unordered_set* set;
if (!hash_function || !equals_function)
{
return NULL;
}
set = malloc(sizeof(*set));
if (!set)
{
return NULL;
}
set->state = malloc(sizeof(*set->state));
load_factor = fix_load_factor(load_factor);
initial_capacity = fix_initial_capacity(initial_capacity);
set->state->load_factor = load_factor;
set->state->table_capacity = initial_capacity;
set->state->size = 0;
set->state->mod_count = 0;
set->state->head = NULL;
set->state->tail = NULL;
set->state->table = calloc(initial_capacity,
sizeof(unordered_set_entry*));
set->state->hash_function = hash_function;
set->state->equals_function = equals_function;
set->state->mask = initial_capacity - 1;
set->state->max_allowed_size = (size_t)(initial_capacity * load_factor);
return set;
}
static void ensure_capacity(unordered_set* set)
{
size_t new_capacity;
size_t new_mask;
size_t index;
unordered_set_entry* entry;
unordered_set_entry** new_table;
if (set->state->size < set->state->max_allowed_size)
{
return;
}
new_capacity = 2 * set->state->table_capacity;
new_mask = new_capacity - 1;
new_table = calloc(new_capacity, sizeof(unordered_set_entry*));
if (!new_table)
{
return;
}
/* Rehash the entries. */
for (entry = set->state->head; entry; entry = entry->next)
{
index = set->state->hash_function(entry->key) & new_mask;
entry->chain_next = new_table[index];
new_table[index] = entry;
}
free(set->state->table);
set->state->table = new_table;
set->state->table_capacity = new_capacity;
set->state->mask = new_mask;
set->state->max_allowed_size = (size_t)(new_capacity * set->state->load_factor);
}
int unordered_set_add(unordered_set* set, void* key)
{
size_t index;
size_t hash_value;
unordered_set_entry* entry;
if (!set)
{
return FALSE;
}
hash_value = set->state->hash_function(key);
index = hash_value & set->state->mask;
for (entry = set->state->table[index]; entry; entry = entry->chain_next)
{
if (set->state->equals_function(entry->key, key))
{
return false;
}
}
ensure_capacity(set);
/* Recompute the index since it is possibly changed by 'ensure_capacity' */
index = hash_value & set->state->mask;
entry = unordered_set_entry_alloc(key);
entry->chain_next = set->state->table[index];
set->state->table[index] = entry;
/* Link the new entry to the tail of the list. */
if (!set->state->tail)
{
set->state->head = entry;
set->state->tail = entry;
}
else
{
set->state->tail->next = entry;
entry->prev = set->state->tail;
set->state->tail = entry;
}
set->state->size++;
set->state->mod_count++;
return true;
}
int unordered_set_contains(unordered_set* set, void* key)
{
size_t index;
unordered_set_entry* p_entry;
if (!set)
{
return false;
}
index = set->state->hash_function(key) & set->state->mask;
for (p_entry = set->state->table[index]; p_entry; p_entry = p_entry->chain_next)
{
if (set->state->equals_function(key, p_entry->key))
{
return true;
}
}
return false;
}
int unordered_set_remove(unordered_set* set, void* key)
{
size_t index;
unordered_set_entry* prev_entry;
unordered_set_entry* current_entry;
if (!set)
{
return false;
}
index = set->state->hash_function(key) & set->state->mask;
prev_entry = NULL;
for (current_entry = set->state->table[index];
current_entry;
current_entry = current_entry->chain_next)
{
if (set->state->equals_function(key, current_entry->key))
{
if (prev_entry)
{
/* Omit the 'p_current_entry' in the collision chain. */
prev_entry->chain_next = current_entry->chain_next;
}
else
{
set->state->table[index] = current_entry->chain_next;
}
/* Unlink from the global iteration chain. */
if (current_entry->prev)
{
current_entry->prev->next = current_entry->next;
}
else
{
set->state->head = current_entry->next;
}
if (current_entry->next)
{
current_entry->next->prev = current_entry->prev;
}
else
{
set->state->tail = current_entry->prev;
}
set->state->size--;
set->state->mod_count++;
free(current_entry);
return true;
}
prev_entry = current_entry;
}
return false;
}
void unordered_set_clear(unordered_set* set)
{
unordered_set_entry* entry;
unordered_set_entry* next_entry;
size_t index;
if (!set)
{
return;
}
entry = set->state->head;
while (entry)
{
index = set->state->hash_function(entry->key) & set->state->mask;
next_entry = entry->next;
free(entry);
entry = next_entry;
set->state->table[index] = NULL;
}
set->state->mod_count += set->state->size;
set->state->size = 0;
set->state->head = NULL;
set->state->tail = NULL;
}
size_t unordered_set_size(unordered_set* set)
{
return set ? set->state->size : 0;
}
int unordered_set_is_healthy(unordered_set* set)
{
size_t counter;
unordered_set_entry* entry;
if (!set)
{
return false;
}
counter = 0;
entry = set->state->head;
if (entry && entry->prev)
{
return false;
}
for (; entry; entry = entry->next)
{
counter++;
}
return counter == set->state->size;
}
void unordered_set_free(unordered_set* set)
{
if (!set)
{
return;
}
unordered_set_clear(set);
free(set->state->table);
free(set);
}
unordered_set_iterator*
unordered_set_iterator_alloc(unordered_set* set)
{
unordered_set_iterator* iterator;
if (!set)
{
return NULL;
}
iterator = malloc(sizeof(*iterator));
if (!iterator)
{
return NULL;
}
iterator->set = set;
iterator->iterated_count = 0;
iterator->next_entry = set->state->head;
iterator->expected_mod_count = set->state->mod_count;
return iterator;
}
size_t unordered_set_iterator_has_next(unordered_set_iterator* iterator)
{
if (!iterator)
{
return 0;
}
if (unordered_set_iterator_is_disturbed(iterator))
{
return 0;
}
return iterator->set->state->size - iterator->iterated_count;
}
int unordered_set_iterator_next(unordered_set_iterator* iterator,
void** key_pointer)
{
if (!iterator)
{
return false;
}
if (!iterator->next_entry)
{
return false;
}
if (unordered_set_iterator_is_disturbed(iterator))
{
return false;
}
*key_pointer = iterator->next_entry->key;
iterator->iterated_count++;
iterator->next_entry = iterator->next_entry->next;
return true;
}
int unordered_set_iterator_is_disturbed(unordered_set_iterator* iterator)
{
if (!iterator)
{
false;
}
return iterator->expected_mod_count != iterator->set->state->mod_count;
}
void unordered_set_iterator_free(unordered_set_iterator* iterator)
{
if (!iterator)
{
return;
}
iterator->set = NULL;
iterator->next_entry = NULL;
free(iterator);
}
static int int_equals(void* a, void* b)
{
int ia = (int)(intptr_t) a;
int ib = (int)(intptr_t) b;
return ia == ib;
}
static size_t int_hash_function(void* i)
{
return (size_t) i;
}
static int str_equals(void* a, void* b)
{
char* ca = (char*) a;
char* cb = (char*) b;
return strcmp(ca, cb) == 0;
}
static size_t str_hash_function(void* p)
{
size_t sum;
char* str;
int i;
sum = 0;
str = (char*) p;
i = 1;
while (*str)
{
sum += *str * i;
str++;
}
return sum;
}
static void unordered_set_test_add()
{
unordered_set* set = unordered_set_alloc(1,
0.5f,
int_hash_function,
int_equals);
int i;
puts(" unordered_set_test_add()");
for (i = 10; i < 20; i++)
{
ASSERT(unordered_set_contains(set, (void*)(intptr_t) i) == FALSE); /*!*/
ASSERT(unordered_set_add(set, (void*)(intptr_t) i));
ASSERT(unordered_set_contains(set, (void*)(intptr_t) i));
ASSERT(unordered_set_is_healthy(set));
}
ASSERT(!unordered_set_contains(set, (void*) 9));
ASSERT( unordered_set_contains(set, (void*) 10));
ASSERT( unordered_set_contains(set, (void*) 19));
ASSERT(!unordered_set_contains(set, (void*) 20));
unordered_set_free(set);
set = unordered_set_alloc(1,
0.45,
str_hash_function,
str_equals);
ASSERT(!unordered_set_contains(set, "hello"));
ASSERT(!unordered_set_contains(set, "world"));
ASSERT(unordered_set_add(set, "world"));
ASSERT(unordered_set_add(set, "hello"));
ASSERT(unordered_set_contains(set, "hello"));
ASSERT(unordered_set_contains(set, "world"));
ASSERT(!unordered_set_contains(set, "bye"));
ASSERT(unordered_set_is_healthy(set));
ASSERT(unordered_set_remove(set, "hello"));
ASSERT(!unordered_set_contains(set, "hello"));
ASSERT(unordered_set_add(set, "repeat"));
ASSERT(!unordered_set_add(set, "repeat"));
}
static void unordered_set_test_contains()
{
unordered_set* set = unordered_set_alloc(3,
0.7f,
int_hash_function,
int_equals);
int i;
puts(" unordered_set_test_contains()");
for (i = 0; i < 100; i++)
{
ASSERT(unordered_set_add(set, (void*)(intptr_t) i));
}
for (i = 99; i >= 0; i--)
{
ASSERT(unordered_set_contains(set, (void*)(intptr_t) i));
}
for (i = 50; i < 100; i++)
{
ASSERT(unordered_set_remove(set, (void*)(intptr_t) i));
ASSERT(!unordered_set_contains(set, (void*)(intptr_t) i));
}
unordered_set_free(set);
}
static void unordered_set_test_remove()
{
unordered_set* set = unordered_set_alloc(3,
0.7f,
int_hash_function,
int_equals);
puts("unordered_set_test_remove()");
ASSERT(unordered_set_add(set, (void*) 1));
ASSERT(unordered_set_add(set, (void*) 2));
ASSERT(unordered_set_add(set, (void*) 3));
ASSERT(3 == unordered_set_size(set));
ASSERT(!unordered_set_add(set, (void*) 2));
ASSERT(3 == unordered_set_size(set));
ASSERT(unordered_set_remove(set, (void*) 2));
ASSERT(!unordered_set_contains(set, (void*) 2));
unordered_set_free(set);
}
static void unordered_set_test_clear()
{
unordered_set* set = unordered_set_alloc(3,
0.7f,
int_hash_function,
int_equals);
int i;
puts("unordered_set_test_clear()");
for (i = 0; i < 100; i++)
{
ASSERT((int) unordered_set_size(set) == i);
unordered_set_add(set, (void*)(intptr_t) i);
}
unordered_set_clear(set);
ASSERT(unordered_set_size(set) == 0);
for (i = -100; i < 200; i++)
{
ASSERT(!unordered_set_contains(set, (void*)(intptr_t) i));
}
unordered_set_free(set);
}
static void unordered_set_test_iterator()
{
unordered_set* set = unordered_set_alloc(
5,
0.6f,
int_hash_function,
int_equals);
unordered_set_iterator* iterator;
int i = 0;
void* p;
puts(" unordered_set_test_iterator()");
for (i = 0; i < 100; i++)
{
unordered_set_add(set, (void*)(intptr_t) i);
}
iterator = unordered_set_iterator_alloc(set);
for (i = 0; i < 100; i++)
{
ASSERT(unordered_set_iterator_has_next(iterator));
ASSERT(unordered_set_contains(set, (void*)(intptr_t) i));
ASSERT(unordered_set_iterator_next(iterator, &p));
ASSERT(i == (intptr_t) p);
}
ASSERT(unordered_set_iterator_has_next(iterator) == FALSE);
}
void unordered_set_test()
{
puts(" unordered_set_test()");
unordered_set_test_add();
unordered_set_test_contains();
unordered_set_test_remove();
unordered_set_test_clear();
unordered_set_test_iterator();
}
</code></pre>
<p>This software belongs to <a href="https://github.com/coderodde/c.graph.v2" rel="nofollow noreferrer">this</a> repository).</p>
| [] | [
{
"body": "<h3>Struct with a single pointer</h3>\n<p>Instead of making your set a struct with a single pointer (presumably to hide the implementation details of your set state), just use a forward struct declaration and force the users to only use a pointer to your set:</p>\n<pre><code>struct unordered_set;\ntypedef struct unordered_set unordered_set;\n</code></pre>\n<p>Now your set can just be what you now call <code>unordered_set_state</code> without the extra level of indirection.</p>\n<h3>Out of memory checks missing</h3>\n<p>You check the return value of <code>malloc/calloc/realloc/unordered_set_entry_alloc</code> in a few places, but there are several places where you don't. Notably, <code>unordered_set_alloc()</code> and <code>unordered_set_add()</code> are missing checks.</p>\n<h3>Potential overflow</h3>\n<p>There is no maximum value for <code>load_factor</code>, so the following line could cause an overflow:</p>\n<blockquote>\n<pre><code>set->state->max_allowed_size = (size_t)(initial_capacity * load_factor);\n</code></pre>\n</blockquote>\n<p>This could lead to <code>max_allowed_size</code> becoming some small value or even zero, which could lead to the set resizing itself on every entry added.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:41:36.500",
"Id": "216227",
"ParentId": "216211",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216227",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T06:14:19.370",
"Id": "216211",
"Score": "3",
"Tags": [
"c",
"hash-map",
"set",
"c89"
],
"Title": "unordered_set: a hash table -based set data structure in C89"
} | 216211 |
<p>I'm using jQuery to create a (hidden) form that redirects people to another page using JavaScript.</p>
<pre><code>// redirect the user to another url
function redirect(options) {
// create the form
$("<form>").attr({
"hidden": true, "action": options.url, "target": (options.new_tab === true) ? "_blank" : "_self"
// create the query inputs and append them to the form
}).append($.map(options.queries || {}, function(name, value) {
return $("<input>").attr({"name": name, "value": value, "hidden": true})[0];
// append the form to the body and submit it
})).appendTo("body").submit();
}
</code></pre>
<p>To simplify this question the form looks like this when broken down:</p>
<pre><code>// redirect the user to another url
function redirect(options) {
// create the form
var form = $("<form>").attr({
"hidden": true,
"action": options.url,
"target": (options.new_tab === true) ? "_blank" : "_self"
});
// create the query inputs and append them to the form
form.append($.map(options.queries || {}, function(name, value) {
return $("<input>").attr({
"name": name,
"value": value,
"hidden": true
})[0];
}));
// append the form to the body and submit it
form.appendTo("body").submit();
}
</code></pre>
<p>How can I simplify the second part of this code?</p>
<pre><code>// create the query inputs and append them to the form
form.append($.map(options.queries || {}, function(name, value) {
return $("<input>").attr({
"name": name,
"value": value,
"hidden": true
})[0];
}));
</code></pre>
| [] | [
{
"body": "<p>You shouldn't need to post (or even have) two versions of the same source code. You should only have one readable version, and use a compressor to create a production version.</p>\n\n<p>And IMO it would be fine to use method chaining in the second (readable) version.</p>\n\n<hr>\n\n<p>Concerning your question: I think the whole code is fine as it is. I'll list some points that one may differently in the second block, but I don't believe they are really needed:</p>\n\n<p>You could avoid the <code>|| {}</code> by validating the <code>options</code> first, or before calling this method, or simply not allow the <code>queries</code> property to be undefined.</p>\n\n<p>You could use an arrow function (if your target systems support it, or by using a ES6 compiler):</p>\n\n<pre><code>form.append($.map(options.queries, (name, value) => \n $(\"<input>\").attr({\n \"name\": name,\n \"value\": value,\n \"hidden\": true\n })[0]\n));\n</code></pre>\n\n<p>And you could use the native JavaScript and more light weight <code>Array.map()</code> method:</p>\n\n<pre><code>form.append(Object.keys(options.queries).map((key, index) => \n $(\"<input>\").attr({\n \"name\": key,\n \"value\": options.queries[key],\n \"hidden\": true\n })[0]\n));\n</code></pre>\n\n<hr>\n\n<p>Expanding on the last point: Now-a-days it's worth considering, if you still need jQuery at all. It was once a big help to bridge incompatibilities between browsers, but current browsers almost compatible to each other.</p>\n\n<p>EDIT: Here's a version without jQuery:</p>\n\n<pre><code>function redirect(options) {\n let form = document.createElement(\"form\");\n form.setAttribute(\"hidden\", \"\");\n form.setAttribute(\"action\", options.url);\n form.setAttribute(\"target\", (options.new_tab === true) ? \"_blank\" : \"_self\");\n\n Object.entries(options.queries || {}).forEach(([name, value]) => {\n let input = document.createElement(\"input\");\n input.setAttribute(\"hidden\", \"\");\n input.setAttribute(\"name\", name);\n input.setAttribute(\"value\", value);\n form.appendChild(input);\n });\n\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:00:00.500",
"Id": "216229",
"ParentId": "216217",
"Score": "2"
}
},
{
"body": "<h2>IE will die, don't die with it.</h2>\n\n<p>Supporting old browsers like IE11 and IE9 via <a href=\"https://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> puts you as a front-end developer at a serious disadvantage. </p>\n\n<p>Javascript as a language is developing rapidly and by not keeping up you are losing important skills that keep you relevant in the workforce.</p>\n\n<p>By the looks of your code you are unaware of ES6+ features such as </p>\n\n<ol>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\">Object.assign</a>, </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Syntax\" rel=\"nofollow noreferrer\">object property syntax</a> (property shorthand), </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a>, </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a>, </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a>,</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export\" rel=\"nofollow noreferrer\">export</a>, </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import\" rel=\"nofollow noreferrer\">import</a>, </li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of</a>,</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a>,</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\">Object.entries</a>.</li>\n</ol>\n\n<p>all that lets you simplify your code and code management.</p>\n\n<p>The following example use all the above listed ES6+ features</p>\n\n<h2>Modern JS version of your code</h2>\n\n<pre><code>// This is a module in a file /modules/redirect.js\nconst createTag = (name, props = {}) => Object.assign(document.createElement(name), props);\nexport default function redirect(options) {\n options = {queries: {}, ...options};\n const hidden = true;\n const form = createTag(\"form\", {\n hidden, \n action: options.url,\n target: options.new_tab ? \"_blank\" : \"_self\"\n });\n for (const [name, value] of Object.entries(options.queries)) {\n form.appendChild(createTag(\"input\", {hidden, name, value}));\n }\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n\n<p>To use the code you import it in the scope you need it</p>\n\n<pre><code>import redirect from \"/modules/redirect.js\"\nredirect(options);\n</code></pre>\n\n<p>For Legacy support use the following, rather than the above</p>\n\n<pre><code>// requires Babel to run in IE\nconst createTag = (name, props = {}) => Object.assign(document.createElement(name),props);\nfunction redirect(options) {\n options = {queries: {}, ...options};\n const hidden = true;\n const form = createTag(\"form\", {\n hidden, \n action: options.url,\n target: options.new_tab ? \"_blank\" : \"_self\"\n });\n for (const [name, value] of Object.entries(options.queries)) {\n form.appendChild(createTag(\"input\", {hidden, name, value}));\n }\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n\n<h2>What to do about legacy</h2>\n\n<p>Use a transpiler, such as <a href=\"https://babeljs.io\" rel=\"nofollow noreferrer\">babel.js</a>, latest <a href=\"https://babeljs.io/docs/en/v7-migration\" rel=\"nofollow noreferrer\">Babel 7</a> for legacy ES6+ support.</p>\n\n<p>For DOM support IE9, IE11 are fairly up to date and you can use a sub set of the DOM API's to cover most of your needs. If you have specific API needs that are not supported in legacy browsers then consider targeted shims to cover the incompatibility.</p>\n\n<h2>Setting DOM Attribute</h2>\n\n<p>When setting attributes of DOM elements you only need to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute\" rel=\"nofollow noreferrer\"><code>setAttribute</code></a> if an attribute is not defined as part of the Javascript DOM interface for a particular element.</p>\n\n<p>It is also important to know that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute\" rel=\"nofollow noreferrer\"><code>setAttribute</code></a> converts the value to a string before assigning or adding it to the element.</p>\n\n<p>There are also other caveats regarding <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute\" rel=\"nofollow noreferrer\"><code>setAttribute</code></a> see the link for more info.</p>\n\n<p>It is recommended that you set defined attributes directly. eg <code>HTMLInputElement.value = newValue</code></p>\n\n<p>You can get a list of defined properties with a simple function, or go to a reference like <a href=\"https://developer.mozilla.org/en-US/\" rel=\"nofollow noreferrer\">MDN</a>. </p>\n\n<p>The next snippet lists properties that can be set directly for the elements <code>form</code> and <code>input</code> It is designed to also show better legacy support via ES6+ and <a href=\"https://babeljs.io\" rel=\"nofollow noreferrer\">babel.js</a>. </p>\n\n<p>Only tested on Edge, FF, and Chrome. Should support IE8 and above. For support down to IE4 you will need a shim for <code>document.createElement</code>. Also note that I have used CSS3 and HTML5 so on older browsers the look will be different.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// define legacy support. With babel this should work all the way back to IE8\n// You will need a shim for document.createElement for support below IE8\nconst text = line.textContent ? \"textContent\" : \"innerText\";\nconst addEvent = (el, name, cb) => {\n (el.attachEvent && el.attachEvent(\"on\" + name, cb)) || el.addEventListener(name, cb);\n}\nconst $ = (name, props = {}) => Object.assign(document.createElement(name), props);\nconst {d10b13a2-8965-459f-9dbc-ba613551ffab}($(\"div\"), $(\"span\", {[text]: named}), $(\"span\", {[text]: type})));\n }\n }\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {font-family: monospace; background:#000; color:#6F6}\nbutton {border: 2px solid #6F6; background: #000; color:#0F0; cursor: pointer}\nbutton:hover {color: #000; background: #0F0}\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Click tag:<span id=\"buttons\">\n <button value=\"form\">Form</button>\n <button value=\"input\">Input</button>\n</span>\n<h3 id=\"elementName\"></h3>\n<div>Attributes that can be set directly have types String, Boolean, or Number<br>\nList excludes functions, objects, and constants</div>\n<div id=\"line\">\n===============================================</div>\n\n<code id=\"info\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup><sub><strong>Note</strong> that I come from a sector that has never needed to support legacy browsers, my views on subject are thus somewhat biased.</sub></sup> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T07:07:09.920",
"Id": "216316",
"ParentId": "216217",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T08:06:38.090",
"Id": "216217",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"form",
"dom"
],
"Title": "jQuery redirect form"
} | 216217 |
<p>I've written a program and it needs a review by skilled programmers.</p>
<p>The programs goal is to change <code>0</code>-s to <code>X</code> and <code>X</code>-s to <code>0</code>. The rule is <code>X</code> or <code>O</code> can move only to an empty place and x or o can only "jump" over one <code>X</code> or <code>O</code>. Program looks like:</p>
<pre><code>------------------
|x|x|x|x| |o|o|o|o|
------------------
</code></pre>
<p>User input</p>
<pre><code>move from? (0-8)
3
move to? (0-8)
4
</code></pre>
<p>Output</p>
<pre><code> -----------------
|x|x|x| |x|o|o|o|o|
------------------
</code></pre>
<p></p>
<pre><code>package tornasz;
import java.util.Scanner;
public class Tornasz {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] table = {'x', 'x', 'x', 'x', ' ', 'o', 'o', 'o', 'o'};
int [] move = new int[2];
int result;
int counter = 0;
do
{
drawPlayfield(table, counter);
move = getValidMove(sc,table,move);
makeMove(table,move);
result = checkWin(table);
counter ++;
}
while (result == 0);
drawPlayfield(table,counter);
displayWinner(result);
}
public static void drawPlayfield(char [] table, int counter){
System.out.println("Lépésszám: "+counter);
System.out.println("------------------");
System.out.println("|"+table[0]+"|"+table[1]+"|"+table[2]+
"|"+table[3]+"|"+table[4]+"|"+table[5]+"|"+table[6]+"|"+table[7]
+"|"+table[8]+"|");
System.out.println("------------------");
counter++;
}
public static int [] getValidMove(Scanner sc, char [] table, int [] move)
{
System.out.println("Melyik mezővel lépsz? (0-8)");
int start = sc.nextInt();
if (start == -1)
{
System.exit(0);
}
System.out.println("Melyik mezőre lépsz? (0-8)");
int destination = sc.nextInt();
if (destination == -1)
{
System.exit(0);
}
while (start < 0 || start > 8 || destination < 0 || destination > 8)
{
System.out.println("Érvénytelen lépés!");
System.out.println("Melyik mezővel lépsz? (0-8)");
start = sc.nextInt();
if (start == -1)
{
System.exit(0);
}
System.out.println("Melyik mezőre lépsz? (0-8)");
destination = sc.nextInt();
if (destination == -1)
{
System.exit(0);
}
}
while (table[destination] != ' ')
{
System.out.println("Érvénytelen lépés!");
System.out.println("Melyik mezővel lépsz? (0-8)");
start = sc.nextInt();
System.out.println("Melyik mezőre lépsz? (0-8)");
destination = sc.nextInt();
}
int [] movement = new int[2];
movement[0] = start;
movement[1] = destination;
return movement;
}
public static void makeMove(char [] table, int [] move)
{
table[move[1]] = table[move[0]];
table[move[0]] = ' ';
}
public static int checkWin(char [] table)
{
if (table[0] == 'o' && table[1] == 'o' && table[2] == 'o' &&
table[3] == 'o' && table[4] == ' ' && table[5] == 'x' &&
table[6] == 'x' && table[7] == 'x' && table[8] == 'x')
{
return 1;
}
return 0;
}
public static void displayWinner(int result)
{
if (result == 1)
{
System.out.println("Gratulálok, vége a játéknak!");
}
}
}
</code></pre>
<p>Now I only need to set the movement rules. I think it will be an another method with boolean.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:23:29.953",
"Id": "418367",
"Score": "2",
"body": "Welcome to Code Review! Code Review is a platform where you can get feedback on *working* code to make it better. As you say, your code does not work as intended. Please read the [how to ask section](https://codereview.stackexchange.com/help/how-to-ask) in the Help Center."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:31:48.583",
"Id": "418369",
"Score": "0",
"body": "I changed the table from String to char because strings comparison is not the == operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:07:07.320",
"Id": "418378",
"Score": "0",
"body": "As far as I can understand your description, each piece has always zero or one possible move, so you needn't ask both questions. However, if you ask the first question only (which piece to move, but not where it has to land), you'd have to devise the appropriate move yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:37:37.003",
"Id": "418385",
"Score": "0",
"body": "The code is incomplete and doesn't look like running and working correctly – the `makeMove` routine can only place \"x\" and not \"o\" into the table, anyway it's never invoked. I'm deleting my answer and voting to migrate the question to StackOverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:46:49.973",
"Id": "418584",
"Score": "0",
"body": "The code seems improved now with all substantial errors fixed. IMHO the question deserves to be reopened."
}
] | [
{
"body": "<ul>\n<li><p><del>The <code>move</code> variable seems unnecessary - you pass it to <code>getValidMove()</code> but never use it inside the function.</del></p></li>\n<li><p>The language has loops for repetitive tasks. In the <code>drawPlayfield()</code> you may do</p>\n\n<pre><code>for(int i=0; i<9; i++)\n System.out.println(\"|\"+table[i]);\nSystem.out.println(\"|\");\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>System.out.println(\"|\"+table[0]+\"|\"+table[1]+\"|\"+table[2]+\n \"|\"+table[3]+\"|\"+table[4]+\"|\"+table[5]+\"|\"+table[6]+\"|\"+table[7]\n+\"|\"+table[8]+\"|\");\n</code></pre>\n\n<p>This costs 10 calls instead of two, but 1) saves strings addition, 2) makes the code easy expandable (you just need to replace the <code>9</code> with another expression).</p></li>\n<li><p><del>The <code>getValidMove()</code> function returns just one <code>int</code> value. Why do you allocate a table for it? declare the return type as <code>int</code> instead of <code>int []</code> and save unnecessary work.</del></p></li>\n<li><p><del>There is some problem with reponsibilities of functions. Function <code>getValidMove()</code> not only gets a valid move, as its name says, but it also removes the chosen piece from the table with assignment <code>table[start] = \" \";</code> That is a part of performing the actual move. However I can't see where the move is completed. Where do you do <code>table[destination] = \"x\";</code> or <code>table[destination] = \"o\";</code>? And where do you store the shape of the piece removed by <code>table[start] = \" \";</code> to be reinserted at <code>destination</code>?</del></p></li>\n</ul>\n\n<p>Critical problems are fixed now - but one important remains:</p>\n\n<ul>\n<li><p>The part to input user's move is unsafe. The first loop tests for both numbers being in the required range and repeats asking for input until data are correct – or until <code>-1</code> appears, which terminates the program. </p>\n\n<p>Then, however, another loop starts, which tests if the chosen destination position is free – and this loop does no longer validate values for being between 1 and 8. It also does not validate data for conforming the game rules (i.e. whether the jump is no more than 2 positions long).</p>\n\n<p>IMHO there should be one loop, looking more or less like this:</p>\n\n<pre><code>do\n{\n do\n {\n System.out.println(\"Input start position (0-8)\");\n start = sc.nextInt();\n if (start == -1)\n {\n System.exit(0);\n }\n } while (start < 0 || start > 8);\n\n do\n {\n System.out.println(\"Input destination position (0-8)\");\n destination = sc.nextInt();\n if (destination == -1)\n {\n System.exit(0);\n }\n } while (destination < 0 || destination > 8);\n\n if (destination == start)\n {\n System.out.println(\"Destination must differ from start!\");\n continue;\n }\n if (destination < start - 2 || destination > start + 2)\n {\n System.out.println(\"Destination must not differ from start more than by 2!\");\n continue;\n }\n\n if (table[destination] != ' ')\n {\n System.out.println(\"The destination position is not empty!\");\n continue;\n }\n} while (false); // the input is OK now\n</code></pre>\n\n<p>Of course the two inner loops are asking for replacing them with a call to some helper function...</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:26:26.777",
"Id": "419367",
"Score": "0",
"body": "The drawPlayfield() method is a requirement in the task thats why I used it and not making a for loop for the task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:36:49.543",
"Id": "419370",
"Score": "0",
"body": "@Falcon83 AFAIK I did _not_ suggest you shouldn't use `drawPlayfield()`. I just proposed to write it in another way, which IMO is a bit more readable and more flexible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:17:04.627",
"Id": "216233",
"ParentId": "216222",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T08:57:11.307",
"Id": "216222",
"Score": "2",
"Tags": [
"java",
"beginner"
],
"Title": "Positional change program in Java"
} | 216222 |
<p>I am trying to find out if a column is binary or not. If a column is only having <code>1</code> or <code>0</code> then I am flagging it as binary, else non binary. Since I have a database background, I tried to achieve it through a SQL like statement. But when the file is big, this code is not giving me good performance.</p>
<p>Could you please suggest how I can improve this code:</p>
<pre><code>input_data=spark.read.csv("/tmp/sample.csv", inferSchema=True,header=True)
input_data.createOrReplaceTempView("input_data")
totcount=input_data.count()
from pyspark.sql.types import StructType,StructField,StringType
profSchema = StructType([ StructField("column_name", IntegerType(), True)\
,StructField("binary_type", StringType(), True)])
fin_df=spark.createDataFrame([],schema=profSchema) ##create null df
for colname in input_data.columns:
query="select {d_name} as column_name,case when sum(case when {f_name} in ( 1,0) then 1 else 0 end) == {tot_cnt} then 'binary' else 'nonbinary'\
end as binary_stat from input_data".format(f_name=colname, d_name="'"+str(colname)+"'",tot_cnt=totcount)
join_df=spark.sql(query)
fin_df=fin_df.union(join_df)
</code></pre>
<p><a href="https://i.stack.imgur.com/49Rsy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/49Rsy.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:03:20.860",
"Id": "418376",
"Score": "0",
"body": "You are talking about \"better performance\". Better than what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:04:47.463",
"Id": "418377",
"Score": "0",
"body": "Better than the current script. If the file is having more column, i am looping it that many times and adding it to the prev data frame."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T11:38:22.143",
"Id": "418390",
"Score": "1",
"body": "Can you add the last part of the image as text (the result of the code being run), then you don't need the image at all anymore. Also add your other imports, please (I guess it is only `import spark`?)."
}
] | [
{
"body": "<p>Spark dataframes (and columns) have a <code>distinct</code> method, which you can use to get all values in that column. Getting the actual values out is a bit more complicated and taken from <a href=\"https://stackoverflow.com/a/39384987/4042267\">this answer</a> to a <a href=\"https://stackoverflow.com/q/39383557/4042267\">similar question on StackOverflow</a>:</p>\n\n<pre><code>from pyspark.sql import SparkSession\n\ndef get_distinct_values(data, column):\n return {x[column] for x in data.select(column).distinct().collect()}\n\nspark = SparkSession \\\n .builder \\\n .appName(\"Python Spark SQL basic example\") \\\n .config(\"spark.some.config.option\", \"some-value\") \\\n .getOrCreate()\n\ninput_data = spark.read.csv(\"/tmp/sample.csv\", inferSchema=True, header=True)\ninput_data.createOrReplaceTempView(\"input_data\")\n\nprint({c: get_distinct_values(input_data, c) == {True, False}\n for c in input_data.columns})\n# {'category': False, 'logged_in': True, 'gid': False, 'pol_id': False, 'subcategory': False}\n</code></pre>\n\n<p>I don't know enough about spark to know how you would cast this back into a spark dataframe, but this should get you at least halfway there and be a bit faster, since it can do the fastest implementation it can to reduce the values to sets.</p>\n\n<hr>\n\n<pre><code># /tmp/sample.csv\npol_id,gid,category,subcategory,logged_in\n1,1,A,a,1\n2,1,A,b,0\n1,2,B,b,1\n2,2,B,a,0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:05:41.693",
"Id": "216242",
"ParentId": "216228",
"Score": "2"
}
},
{
"body": "<p>In my earlier approach, I was taking the count of 1 and 0 of a column also the total record count. If there is a match then I was flagging it as binary else non binary. But as per this approach, I am limiting the distinct record to 3. Then checking if the number of record is 2 and it has 0 or 1</p>\n\n<pre><code>columns_isbinary = []\nfor column_name in input_data.columns:\n column = input_data.select(column_name)\n column_distinct_3 = column.distinct().limit(3).rdd.flatMap(lambda x: x).collect() \n column_distinct_3_str = [str(value) for value in column_distinct_3]\n column_isbinary = len(column_distinct_3) == 2 and\\\n all(value in column_distinct_3_str for value in ('1', '0'))\n columns_isbinary.append((column_name, column_isbinary))\n\nis_binarydf=spark.createDataFrame(columns_isbinary,(\"column_name\",\"isbinary\"))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T18:09:43.273",
"Id": "418989",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:28:13.763",
"Id": "419029",
"Score": "0",
"body": "I am the author. In my earlier approach, I was taking the count of 1 and 0 of a column also the total record count. If there is a match then I was flagging it as binary else non binary. But as per this approach, I am limiting the distinct record to 3. Then checking if the number of record is 2 and it has 0 or 1. Which is a good approach. I hope you might now upgrade the answer. You can down grade if the solution does not work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T01:46:05.420",
"Id": "419161",
"Score": "0",
"body": "Please put that into the post itself."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:44:10.010",
"Id": "216309",
"ParentId": "216228",
"Score": "-1"
}
},
{
"body": "<p>This one is <code>O(1)</code> in terms of pyspark collect operations instead of previous answers, both of which are <code>O(n)</code>, where <code>n = len(input_df.columns)</code>. </p>\n\n<pre><code>def get_binary_cols(input_file: pyspark.sql.DataFrame) -> List[str]:\n distinct = input_file.select(*[collect_set(c).alias(c) for c in input_file.columns]).take(1)[0]\n print(distinct)\n print({c: distinct[c] for c in input_file.columns})\n binary_columns = [c for c in input_file.columns\n if len(distinct[c]) == 2\n and (set(distinct[c]).issubset({'1', '0'}) or set(distinct[c]).issubset({1, 0}))]\n return binary_columns\n</code></pre>\n\n<p>For ~100 columns and 100 rows I've gained around 80x boost in performance. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:33:32.030",
"Id": "419553",
"Score": "0",
"body": "Seems like your alternative approach is missing a `return` statement. Also consider to explain critical parts of your approach a little further. At the moment I would not consider this as a good answer for Code Review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:43:18.950",
"Id": "216911",
"ParentId": "216228",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216911",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:53:44.470",
"Id": "216228",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"apache-spark"
],
"Title": "Binary check code in pyspark"
} | 216228 |
<p>Trying to learn coding in my 30s.</p>
<p>Could anybody review my code and give me some feedback if possible? It works, but I am sure there are better ways to solve this problem.</p>
<p>The problem:</p>
<p>A text is given. Write a program that modifies the casing of letters to uppercase at all places in the text surrounded by <code><upcase></code> and <code></upcase></code> tags. Tags cannot be nested.</p>
<p>Here is what I've come up with:</p>
<pre><code>namespace Task6Casing
{
class Program
{
static void Main(string[] args)
{
Console.Write("Text: ");
string text = Console.ReadLine();
char[] textNew = new char[text.Length];
int i = 0, j = 0, k = 0;
while (i < text.Length)
{
if (text.IndexOf("<upcase>", k) < 0) // check if there is any <upcase> tag
{ // if no, copy everyting
while (i < text.Length)
{
textNew[j++] = text[i++];
}
}
else
{
while (i < text.IndexOf("<upcase>", k)) // if there is an <upcase> tag, copy letters until the tag
{
textNew[j++] = text[i++];
}
i += 8; // move index i to the position right next to the <upcase> tag
k = i;
}
if (text.IndexOf("</upcase>", k) < 0) // check if there is any </upcase> tag
{ // if no, copy everyting in CAPITAL letters
while (i < text.Length)
{
textNew[j++] = Char.ToUpper(text[i++]);
}
}
else
{
while (i < text.IndexOf("</upcase>", k)) // if there is an </upcase> tag, copy letters in CAP letters until the tag
{
textNew[j++] = Char.ToUpper(text[i++]);
}
i += 9; // move index i to the position right next to the </upcase> tag
}
}
foreach(char c in textNew)
{
Console.Write(c);
}
Console.WriteLine();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Your code is easy to understand and very performant.</p>\n\n<p>Some improvements:</p>\n\n<ul>\n<li>String for start / end tag could be stored as constant. That has the advantage that it can be changed on one central location and the length of the string can be accessed like <code>i += START_TAG.Length</code></li>\n<li>When using a <code>StringBuilder</code> instead of of the char array <code>newText</code>, the running variable 'j' can be dropped.</li>\n<li>The 2 code parts</li>\n</ul>\n\n<blockquote>\n<pre><code> if (text.IndexOf(\"<upcase>\", k) < 0) // check if there is\n any <upcase> tag\n { // if no, copy everyting\n while (i < text.Length)\n {\n textNew[j++] = text[i++];\n }\n }\n else \n {\n while (i < text.IndexOf(\"<upcase>\", k)) // if there is an <upcase> tag, copy letters until the tag\n {\n textNew[j++] = text[i++];\n }\n\n i += 8; // move index i to the position right next to the <upcase> tag\n k = i;\n }\n</code></pre>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n<pre><code> if (text.IndexOf(\"</upcase>\", k) < 0) // check if there is any </upcase> tag\n { // if no, copy everyting in CAPITAL letters\n while (i < text.Length)\n {\n textNew[j++] = Char.ToUpper(text[i++]);\n }\n }\n else\n {\n while (i < text.IndexOf(\"</upcase>\", k)) // if there is an </upcase> tag, copy letters in CAP letters until the tag\n {\n textNew[j++] = Char.ToUpper(text[i++]);\n }\n\n i += 9; // move index i to the position right next to the </upcase> tag\n }\n</code></pre>\n</blockquote>\n\n<p>are very simlar. Probably it is possible to create one more generic code fragment that coveres both cases.</p>\n\n<hr>\n\n<p>Since your solution is still understandable for such a simple use case, it will fast become unmaintainable if the use case becomes more complex. Therefore, it makes sense to think about a more abstract OOP concepts to model the solution.</p>\n\n<p>One alternative impl. (that is probably over engineered for the given problem) gives an idea how a more object oriented design could look like:</p>\n\n<pre><code> public class Tag\n {\n private readonly Func<char, char> map;\n public Tag(string start, string end, Func<char, char> map)\n {\n this.Start = start;\n this.End = end;\n this.map = map;\n }\n\n public string Start { get; }\n public string End { get; }\n public char Map(char input) => this.map(input);\n }\n\n public class TagProcessor\n {\n private readonly Tag tag;\n private readonly StringBuilder output = new StringBuilder();\n\n private string input;\n private bool isTagOpen;\n private int index;\n\n public TagProcessor(Tag tag)\n {\n this.tag = tag;\n }\n\n public string Process(string input)\n {\n this.input = input;\n this.index = 0;\n this.isTagOpen = false;\n this.output.Clear();\n\n do\n {\n var tagProcessed = this.TryOpenTag() || this.TryCloseTag();\n if (!tagProcessed)\n {\n this.ApplyCurrentChar();\n }\n }\n while (this.MoveNext());\n\n return output.ToString();\n }\n\n private bool IsEndTag() => input.IndexOf(tag.End, this.index) == this.index;\n\n private bool IsStartTag() => input.IndexOf(tag.Start, this.index) == this.index;\n\n private bool MoveNext()\n {\n index++;\n return index < this.input.Length;\n }\n\n private void ApplyCurrentChar()\n {\n var inputChar = this.input[this.index];\n var transfomed = this.isTagOpen ? tag.Map(inputChar) : inputChar;\n this.output.Append(transfomed);\n }\n\n private bool TryOpenTag()\n {\n if (!isTagOpen && IsStartTag())\n {\n this.index += this.tag.Start.Length - 1;\n this.isTagOpen = true;\n return true;\n }\n\n return false;\n }\n\n private bool TryCloseTag()\n {\n if (isTagOpen && IsEndTag())\n {\n this.index += this.tag.End.Length - 1;\n this.isTagOpen = false;\n return true;\n }\n\n return false;\n }\n }\n\n public static void Main(string[] args)\n {\n var processor = new TagProcessor(new Tag(\"<upcase>\", \"</upcase>\", char.ToUpper));\n\n var test = new[]\n {\n \"abc<upcase>test</upcase>\",\n \"abc<upcase>test\",\n \"abc<upcase></upcase>test\",\n \"abc<upcase>test</upcase>test\",\n \"abc<upcase>te<upcase>st</upcase>test\",\n \"a</upcase>bc<upcase>te<upcase>st</upcase>te</upcase>st\",\n };\n\n foreach (var t in test)\n Console.WriteLine(t + \": \" + processor.Process(t));\n Console.ReadLine();\n }\n</code></pre>\n\n<p>The advantages are, that this solution remains readable if the complexity grows (e.g. more tags were added) and it allows to change / extend the logic without understanding the whole parsing logic. Further more, each method has a single pupose which increases comprehensibleness.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T11:43:55.233",
"Id": "216237",
"ParentId": "216232",
"Score": "7"
}
},
{
"body": "<p>This loop</p>\n\n<pre><code> while (i < text.IndexOf(\"<upcase>\", k))\n {\n ....\n }\n</code></pre>\n\n<p>invokes <code>IndexOf</code> multiple times for nothing. I'd call it just once and use the result:</p>\n\n<pre><code> const int upcasePos = text.IndexOf(\"<upcase>\", k);\n if (upcasePos < 0)\n {\n while (i < text.Length)\n {\n textNew[j++] = text[i++];\n }\n }\n else \n {\n while (i < upcasePos)\n {\n textNew[j++] = text[i++];\n }\n\n ....\n }\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>You can also speed things up by getting rid of char-by-char iteration, and instead processing longer parts of the string at once with standard routines.\nHere's an outline:</p>\n\n<pre><code> StringBuilder sb = new StringBuilder();\n\n for (int k = 0; k < text.length; )\n {\n int tagOpen = text.IndexOf(\"<upcase>\", k));\n if (tagOpen < 0)\n {\n sb.Append(text.Substring(k)); // take the tail\n break;\n }\n\n sb.Append(text.Substring(k, tagOpen - k));\n k = tagOpen + 8; // skip the tag\n\n int tagClose = text.IndexOf(\"</upcase>\", k));\n if (tagClose < 0)\n {\n sb.Append(text.Substring(k).toUpper()); // take the tail in upper case\n break;\n }\n\n sb.Append(text.Substring(k, tagClose - k).toUpper());\n k = tagClose + 9; // skip the tag\n }\n\n result = sb.ToString(); // return this\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:44:53.187",
"Id": "216248",
"ParentId": "216232",
"Score": "4"
}
},
{
"body": "<p>Below is a refactoring of your algorithm with some inline comments.</p>\n\n<pre><code>string Review(string text)\n{\n const string startTag = \"<upcase>\"; // Use declared string rather than string literals\n const string endTag = \"</upcase>\";\n\n // textNew is a somewhat \"backward\" name. result or newText would be better\n char[] result = new char[text.Length];\n // Instantiate each variable on a single line. It's easier to find and maintain\n // Provide some meaningful names instead for i, j and k. (i, j and k may be alright in a lessser complex context, but here they easily lose their meaining through the loop)\n int curIndex = 0;\n int resultIndex = 0;\n int searchIndex = 0;\n\n while (curIndex < text.Length)\n {\n if (text.IndexOf(startTag, searchIndex) < 0) \n { \n while (curIndex < text.Length)\n {\n result[resultIndex++] = text[curIndex++];\n }\n }\n else\n {\n // Repeatedly calling the same function with the same values is inefficient\n int startIndex = text.IndexOf(startTag, searchIndex);\n while (curIndex < startIndex)\n {\n result[resultIndex++] = text[curIndex++];\n }\n\n curIndex += startTag.Length; // Use the length of the tag string instead of a magic number\n searchIndex = curIndex;\n }\n\n if (text.IndexOf(endTag, searchIndex) < 0)\n { \n while (curIndex < text.Length)\n {\n result[resultIndex++] = Char.ToUpper(text[curIndex++]);\n }\n }\n else\n {\n // Repeatedly calling the same function with the same values is inefficient\n int endIndex = text.IndexOf(endTag, searchIndex);\n while (curIndex < endIndex)\n {\n result[resultIndex++] = Char.ToUpper(text[curIndex++]);\n }\n\n curIndex += endTag.Length; // Use the length of the tag string instead of a magic number\n }\n }\n\n // Return the result instead of write it to the console.\n return new string(result.Take(resultIndex).ToArray()); // You have to truncate the char array in order to prevent a trailing new line\n //OR: return new string(textNew).TrimEnd('\\0');\n}\n</code></pre>\n\n<hr>\n\n<p>Below is some other approaches that you may find useful for inspiration:</p>\n\n<pre><code>string ToUpperInTags(string text)\n{\n const string start = \"<upcase>\";\n const string stop = \"</upcase>\";\n\n List<string> fragments = new List<string>();\n int curIndex = 0;\n while (curIndex < text.Length)\n {\n int startIndex = text.IndexOf(start, curIndex);\n if (startIndex >= 0)\n {\n fragments.Add(text.Substring(curIndex, startIndex - curIndex));\n int stopIndex = text.IndexOf(stop, startIndex + start.Length);\n if (stopIndex < 0) throw new InvalidOperationException($\"Unpaired start at {startIndex}\");\n fragments.Add(text.Substring(startIndex + start.Length, stopIndex - (startIndex + start.Length)).ToUpper());\n curIndex = stopIndex + stop.Length;\n }\n else\n {\n fragments.Add(text.Substring(curIndex));\n break;\n }\n }\n\n return string.Join(\"\", fragments);\n}\n\nstring ToUpperInTags2(string text)\n{\n string pattern = @\"(?<start><upcase>)(?<content>[^<>]*)(?<stop></upcase>)?\";\n foreach (Match match in Regex.Matches(text, pattern))\n {\n text = Regex.Replace(text, $\"{match.Groups[\"start\"]}{match.Groups[\"content\"]}{match.Groups[\"stop\"]}\", match.Groups[\"content\"].Value.ToUpper());\n }\n\n return text;\n}\n\nstring ToUpperInTags3(string text)\n{\n string pattern = @\"<upcase>(?<content>[^<>]*)(</upcase>)?\";\n return Regex.Replace(text, pattern, m => m.Groups[\"content\"].Value.ToUpper());\n}\n</code></pre>\n\n<p>They don't all behave exactly as yours, and are just provided for inspiration for further study...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:28:45.797",
"Id": "216261",
"ParentId": "216232",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:13:15.017",
"Id": "216232",
"Score": "15",
"Tags": [
"c#",
"beginner",
"strings",
"console"
],
"Title": "Modify casing of marked letters"
} | 216232 |
<p>I created a program in python that generates an image of the mandelbrot set. The only problem I have is that the program is quite slow, it takes about a quarter of an hour to generate the following image of 2000 by 3000 pixels: </p>
<p><a href="https://i.stack.imgur.com/Z9TqS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z9TqS.png" alt="enter image description here"></a></p>
<p>I first created a matrix of complex numbers using numpy according to amount of pixels. I also created an array for the image generation.</p>
<pre><code>import numpy as np
from PIL import Image
z = 0
real_axis = np.linspace(-2,1,num=3000)
imaginary_axis = np.linspace(1,-1,num=2000)
complex_grid = [[complex(np.float64(a),np.float64(b)) for a in real_axis] for b in imaginary_axis]
pixel_grid = np.zeros((2000,3000,3),dtype=np.uint8)
</code></pre>
<p>Then I check whether each complex number is in the mandelbrot set or not and give it an RGB colour code accordingly.</p>
<pre><code>for complex_list in complex_grid:
for complex_number in complex_list:
for iteration in range(255):
z = z**2 + complex_number
if (z.real**2+z.imag**2)**0.5 > 2:
pixel_grid[complex_grid.index(complex_list),complex_list.index(complex_number)]=[iteration,iteration,iteration]
break
else:
continue
z = 0
</code></pre>
<p>Finally I generate the image using the PIL library.</p>
<pre><code>mandelbrot = Image.fromarray(pixel_grid)
mandelbrot.save("mandelbrot.png")
</code></pre>
<p>I am using jupyter notebook and python 3. Hopefully some of you can help me improve the performance of this program or other aspects of it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:05:58.270",
"Id": "418509",
"Score": "4",
"body": "If you want to skip points that are known to be inside the Mandelbrot set, [the main cardioid and period bulbs can be skipped](https://en.wikipedia.org/wiki/Mandelbrot_set#Main_cardioid_and_period_bulbs). If you skip processing points contained within the main cardioid and the main disk, you can significantly speed up the program. See also [this resource](http://cosinekitty.com/mandel_orbits_analysis.html) for a further analysis of the main cardioid and disk. This optimization becomes less effective as you zoom in on the edges and becomes completely ineffective if these regions are off-screen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:16:08.963",
"Id": "418595",
"Score": "3",
"body": "Please put spaces around your operators and after commas."
}
] | [
{
"body": "<p>This will cover performance, as well as Python style.</p>\n\n<h2>Save constants in one place</h2>\n\n<p>You currently have the magic numbers 2000 and 3000, the resolution of your image. Save these to variables perhaps named <code>X</code>, <code>Y</code> or <code>W</code>, <code>H</code>.</p>\n\n<h2>Mention your requirements</h2>\n\n<p>You don't just rely on Python 3 and Jupyter - you rely on numpy and pillow. These should go in a requirements.txt if you don't already have one.</p>\n\n<h2>Don't save your complex grid</h2>\n\n<p>At all. <code>complex_number</code> should be formed dynamically in the loop based on <code>range</code> expressions.</p>\n\n<p>Disclaimer: if you're vectorizing (which you should do), then the opposite applies - you would keep your complex grid, and lose some loops.</p>\n\n<h2>Don't use <code>index</code> lookups</h2>\n\n<p>You're using <code>index</code> to get your coordinates. Don't do this - form the coordinates in your loops, as well.</p>\n\n<h2>Mandelbrot is symmetrical</h2>\n\n<p>Notice that it's mirror-imaged. This means you can halve your computation time and save every pixel to the top and bottom half.</p>\n\n<p><s>In a bit I'll show some example code accommodating all of the suggestions above.</s> Just do (nearly) what @Alex says and I'd gotten halfway through implementing, with one difference: accommodate the symmetry optimization I described.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T12:52:48.037",
"Id": "216240",
"ParentId": "216235",
"Score": "20"
}
},
{
"body": "<p>I'm going to reuse some parts of the <a href=\"https://codereview.stackexchange.com/a/216197/92478\">answer</a> I recently posted here on Code Review.</p>\n\n<h1>Losing your Loops</h1>\n\n<blockquote>\n <p><strong>(Most) loops are damn slow in Python. Especially multiple nested loops.</strong></p>\n \n <p>NumPy can help to <em>vectorize</em> your code, i.e. in this case that more\n of the looping is done in the C backend instead of in the Python\n interpreter. I would highly recommend to have a listen to the talk\n <a href=\"https://codereview.stackexchange.com/a/216197/92478\">Losing your Loops: Fast Numerical Computing with NumPy</a> by Jake\n VanderPlas.</p>\n</blockquote>\n\n<p>All those loops used to generate the complex grid followed by the nested loops used to iterate over the grid and the image are slow when left to the Python interpreter. Fortunately, NumPy can take quite a lot of this burden off of you.</p>\n\n<p>For example</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>real_axis = np.linspace(-2, 1, num=3000)\nimaginary_axis = np.linspace(1, -1, num=2000)\ncomplex_grid = [[complex(np.float64(a),np.float64(b)) for a in real_axis] for b in imaginary_axis]\n</code></pre>\n\n<p>could become</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>n_rows, n_cols = 2000, 3000\ncomplex_grid_np = np.zeros((n_rows, n_cols), dtype=np.complex)\nreal, imag = np.meshgrid(real_axis, imaginary_axis)\ncomplex_grid_np.real = real\ncomplex_grid_np.imag = imag\n</code></pre>\n\n<p>No loops, just plain simple NumPy.</p>\n\n<p>Same goes for</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for complex_list in complex_grid:\n for complex_number in complex_list:\n for iteration in range(255):\n z = z**2 + complex_number\n if (z.real**2+z.imag**2)**0.5 > 2:\n pixel_grid[complex_grid.index(complex_list),complex_list.index(complex_number)]=[iteration,iteration,iteration]\n break\n else:\n continue\n z = 0\n</code></pre>\n\n<p>can be transformed to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>z_grid_np = np.zeros_like(complex_grid_np)\nelements_todo = np.ones((n_rows, n_cols), dtype=bool)\nfor iteration in range(255):\n z_grid_np[elements_todo] = \\\n z_grid_np[elements_todo]**2 + complex_grid_np[elements_todo]\n mask = np.logical_and(np.absolute(z_grid_np) > 2, elements_todo)\n pixel_grid_np[mask, :] = (iteration, iteration, iteration)\n elements_todo = np.logical_and(elements_todo, np.logical_not(mask))\n</code></pre>\n\n<p>which is just a single loop instead of three nested ones. Here, a little more trickery was needed to treat the <code>break</code> case the same way as you did. <code>elements_todo</code> is used to only compute updates on the <code>z</code> value if it has not been marked as done. There might also be a better solution without this.</p>\n\n<p>I added the following lines</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>complex_grid_close = np.allclose(np.array(complex_grid), complex_grid_np)\npixel_grid_close = np.allclose(pixel_grid, pixel_grid_np)\nprint(\"Results were similar: {}\".format(all((complex_grid_close, pixel_grid_close))))\n</code></pre>\n\n<p>to validate my results against your reference implementation.</p>\n\n<p>The vectorized code is about 9-10x faster on my machine for several <code>n_rows/n_cols</code> combinations I tested. E.g. for <code>n_rows, n_cols = 1000, 1500</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Looped generation took 61.989842s\nVectorized generation took 6.656926s\nResults were similar: True\n</code></pre>\n\n<h2>Lose a dimension</h2>\n\n<p>An aspect I somehow slightly ignored while looking at your code was that you're essentially creating a grayscale image since all of your color channel values are the same. Accounting for this, you can easily reduce the size of data the program has handle to from, in your case, <code>3000x2000x3</code> to <code>3000x2000</code>. This will likely help your program to be more cache efficient, although I'm not an expert in this field.</p>\n\n<hr>\n\n<h2>Edit/Appendix: Further timings</h2>\n\n<p>Including the \"no square root\" optimization as suggested by trichoplax in his <a href=\"https://codereview.stackexchange.com/a/216298/92478\">answer</a> and Peter Cordes in the <a href=\"https://codereview.stackexchange.com/questions/216235/increase-performance-creating-mandelbrot-set-in-python/216241#comment418534_216241\">comments</a> like so</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mask = np.logical_and((z_grid_np.real**2+z_grid_np.imag**2) > 4, elements_todo)\n</code></pre>\n\n<p>will give you about another second and a half for <code>n_rows, n_cols = 1000, 1500</code>, i.e. about 12x the speed of the original solution</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>10 loops, best of 5: 4.98 s per loop\n10 loops, best of 5: 4.28 s per loop (in grayscale, 14x)\n</code></pre>\n\n<p>A quick implementation of <a href=\"https://codereview.stackexchange.com/a/216240/92478\">Reinderien's hint</a> towards the symmetry of the Mandelbrot set will again add a factor of about two to that.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>10 loops, best of 5: 2.54 s per loop (~24x)\n10 loops, best of 5: 2.07 s per loop (in grayscale, ~30x)\n</code></pre>\n\n<p>However, my quick hacking approach did not lead to an output that was completely within the tolerance of <code>np.allclose</code> compared to the original one. Funnily, it seems to be off by one at a single pixel, but visually still the same. Since this post is already quite long, I will leave the reimplementation as an exercise to the reader.</p>\n\n<p>Depending on your needs, you might also go down with the floating point precision from 64bit to 32bit on addition to all the previously mentioned optimizations.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>10 loops, best of 5: 1.49 s per loop (~41x)\n10 loops, best of 5: 1.14 s per loop (in grayscale, ~54x)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:24:22.337",
"Id": "418523",
"Score": "0",
"body": "I have some trouble understanding the numpy based code you posted, possibly because there are a few new commands, but I'll try to have a go at vectorized programming!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T07:02:51.687",
"Id": "418529",
"Score": "2",
"body": "Could you narrow down what part of code/what commands are causing you headache? I would then add further details where needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:01:41.650",
"Id": "418534",
"Score": "0",
"body": "`np.absolute(z_grid_np)` should be replaced with something that avoids the sqrt in the `sqrt(real**2 + imag**2)` formula it uses, unless Python can already do that optimization when comparing against a known-positive constant like `4`. IDK if it's worth considering having separate real and imag arrays and doing the `complex` stuff manually. If it actually loops over your data for each step then that would reduce computational intensity (less work done per time your data is loaded / stored from memory)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:05:29.743",
"Id": "418535",
"Score": "1",
"body": "@Peter Cordes: No ned to have seperate arrays for real and imaginary parts. You can access both parts using `arr.real` and `arr.imag` if you want to do it manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:07:10.767",
"Id": "418536",
"Score": "2",
"body": "Also worth looking at cache-blocking, if `w * h` times 16 bytes per complex-double is more than 32k (L1d size) or 256k (typical L2 cache size): loop over a fraction of the whole array repeatedly. (e.g. 1500 * 1000 * 16 = 24MB, which only fits on L3 cache on a big Xeon, or not at all on a normal desktop CPU.) `1500*16B` = 24kB, so looping repeatedly over 1 row might be a win. (Or as other answers point out, different regions of the problem have different typical iteration counts, so working in square tiles might let you stop after a couple iterations when all pixels hit `|m| > 4`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:11:13.667",
"Id": "418538",
"Score": "0",
"body": "@Alex: Does numpy store the real and imaginary parts separately by default, to make SIMD efficient for calculations like `x*y` or `x.real **2 + x.imag**2`? If it stores interleaved the way C would for `complex double array[1000*1500]`, that sucks for modern CPUs because it requires significant shuffling work to implement multiply with SIMD vectors that are 16 or 32 bytes wide (and thus hold 2 or 4 `double`s at once), but don't support efficient horizontal operations. See [How to square two complex doubles with 256-bit AVX vectors?](//stackoverflow.com/q/39509746) for how much overhead it adds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:15:20.270",
"Id": "418539",
"Score": "0",
"body": "Storing `complex` numbers is a special case of the Array of Structs (bad for SIMD) vs. Struct of Arrays (good for SIMD) issue. If numpy does store them separately, not interleaved, then that's great, and lets it be as efficient as possible internally (especially if compiled with AVX2 + FMA)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:19:15.433",
"Id": "418540",
"Score": "7",
"body": "This gets fairly involved and is IMHO clearly out of focus for this kind of code review and the experience the OP seems to have. Maybe we can continue the discussion somewhere else?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:04:31.443",
"Id": "216241",
"ParentId": "216235",
"Score": "46"
}
},
{
"body": "<h1>Mandelbrot-specific optimisations</h1>\n\n<p>These can be combined with the Python-specific optimisations from the other answers.</p>\n\n<h2>Avoid the redundant square root</h2>\n\n<pre><code>if (z.real**2+z.imag**2)**0.5 > 2:\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>if z.real ** 2 + z.imag ** 2 > 4:\n</code></pre>\n\n<p>(simply square both sides of the original comparison to get the optimised comparison)</p>\n\n<h2>Avoid squaring unless you are using it</h2>\n\n<p>Any points that get further than 2 from the origin will continue to escape towards infinity. So it isn't important whether you check that a point has gone outside a circle of radius 2, or that it has gone outside some other finite shape that fully contains that circle. For example, checking that the point is outside a square instead of a circle avoids having to square the real and imaginary parts. It also means you will need slightly more iterations, but very few and this should be outweighed by having each iteration faster.</p>\n\n<p>For example:</p>\n\n<pre><code>if (z.real**2+z.imag**2)**0.5 > 2: # if z is outside the circle\n</code></pre>\n\n<p>could be replaced by</p>\n\n<pre><code>if not (-2 < z.real < 2 and -2 < z.imag < 2): # if z is outside the square\n</code></pre>\n\n<p>The exception to this suggestion is if the circle is important to your output. If you simply plot points inside the set as black, and points outside the set as white, then the image will be identical with either approach. However, if you count the number of iterations a point takes to escape and use this to determine the colour of points outside the set, then the shape of the stripes of colour will be different with a square boundary than with a circular boundary. The interior of the set will be identical, but the colours outside will be arranged in different shapes.</p>\n\n<p>In your example image, not much is visible of the stripes of colour, with most of the exterior and interior being black. In this case I doubt there would be a significant difference in appearance using this optimisation. However, if you change to displaying wider stripes in future, this optimisation may need to be removed (depending on what appearance you want).</p>\n\n<h2>Hard-code as much of the interior as you can</h2>\n\n<p>The interior of the set takes far longer to calculate than the exterior. Each pixel in the interior takes a guaranteed 255 iterations (or more if you increase the maximum iterations for even higher quality images), whereas each pixel in the exterior takes less than this. The vast majority of the exterior pixels take only a few iterations.</p>\n\n<p>If you want the code to be adaptable for zooming in to arbitrary positions, then you won't know in advance which parts of the image are going to be interior points. However, if you only want this code to generate this one image of the whole set, then you can get a significant improvement in speed by avoiding calculating pixels you know are interior. For example, if you check whether the pixel is in the main cardioid or one of the large circles, you can assign all those pixels an iteration count of 255 without actually doing any iteration. The more you increase the maximum iterations, the more circles it will be worthwhile excluding in advance, as the difference in calculation time between the average exterior pixel and the average interior pixel will continue to diverge dramatically.</p>\n\n<p>I don't know the exact centres and radii of these circles, or an exact equation for the cardioid, but rough estimates that are chosen to not overlap the exterior will still make a big difference to the speed. Even excluding some squares chosen by eye that are entirely in the interior would help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:36:56.117",
"Id": "216298",
"ParentId": "216235",
"Score": "12"
}
},
{
"body": "<p>I'm not a python expert. I <em>am</em> pretty good with Mandlebrot generation (I've spent a <em>lot</em> of time on my custom Julia Set generator.)</p>\n\n<p>So I'll say this: optimize the heck out of stuff that will be running many iterations. Forget about clean-code or nice OOP principles. For lots-of-iterations stuff like this, you want as nitty gritty as possible.</p>\n\n<p>So let's take a look at your interior-most loop:</p>\n\n<pre><code>z = z**2 + complex_number\nif (z.real**2+z.imag**2)**0.5 > 2:\n pixel_grid[complex_grid.index(complex_list),complex_list.index(complex_number)]=[iteration,iteration,iteration]\n break\nelse:\n continue\n</code></pre>\n\n<p>Imagine what's happening behind the scenes in memory with just that very first line. You've got an instance of a complex number. You want to square it... so it has to create another instance of a complex object to hold the squared value. Then, you're adding another complex number to it - which means you're creating another instance of Complex to hold the result of the addition.</p>\n\n<p>You're creating object instances left and right, and you're doing it on an order of 3000 x 2000 x 255 times. Creating several class instances doesn't <em>sound</em> like much, but when you're doing it a billion times, it kinda drags things down.</p>\n\n<p>Compare that with pseudocode like:</p>\n\n<pre><code>px = num.real\npy = num.imag\nwhile\n tmppx = px\n px = px * px - py * py + num.real\n py = 2 * tmppx * py + num.imag\n if condition-for-hitting-escape\n stuff\n if condition-for-hitting-max-iter\n moreStuff\n</code></pre>\n\n<p>No objects are getting created and destroyed. It's boiled down to be as efficient as possible. It's not as nice looking... but when you're doing something a billion times, shaving off even a <em>millionth</em> of a second results in saving 15 minutes.</p>\n\n<p>And as someone else mentioned, you want to simplify the logic so that you don't have to do the square-root operation - and if you're okay with small variations in how the gradient is colored, changing the \"magnitude\" check with \"are x or y within a bounding box\".</p>\n\n<p>Aka, the more things you can remove out of that runs-a-billion-times loop, the better off you'll be.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T00:35:04.680",
"Id": "216304",
"ParentId": "216235",
"Score": "6"
}
},
{
"body": "<p>There are a few tricks you can use to make a Mandelbrot renderer really fly.</p>\n\n<p><strong>Detect cycles</strong></p>\n\n<p>If a point lies inside the Mandelbrot set, successive iterations will cause it to decay into a cycle. The most economical way to detect this, I have found, is to do x iterations, test to see if it is the same as before, then increment x and repeat.</p>\n\n<p><strong>Draw a half resolution version first</strong></p>\n\n<p>That's a 1000x1500 image in your case. Calculate it such that each pixel represents a pixel in the real image. Then if a pixel is entirely surrounded by other pixels with the same iteration count, you can assume that it also has that iteration count and skip calculating it.</p>\n\n<p>This technique can miss fine strands, but it saves an enormous amount of time. You should also use a flood fill style algorithm whenever you calculate an unskippable pixel to find other pixels that may previously have been considered skippable but aren't. This should fix most of the problems.</p>\n\n<p>Also note that this is recursive. Before calculating the 1000x1500 version you should calculate a 500x750 version, before that a 250x375 version etc.</p>\n\n<p><strong>The SuperFractalThing trick</strong></p>\n\n<p>If you want to calculate deep fractals, you need to use high precision, which can be a huge drain on calculation time. However, strictly speaking you only need to use high precision for one pixel.</p>\n\n<p>We start from position <span class=\"math-container\">\\$p_0\\$</span>, and we follow the usual iterative formula:</p>\n\n<p><span class=\"math-container\">\\$p_{x+1}={p_x}^2+p_0\\$</span></p>\n\n<p>We record all the values of <span class=\"math-container\">\\$p_x\\$</span> as regular, double precision complex numbers. Now we calculate <span class=\"math-container\">\\$q\\$</span>, but we do it by calculating <span class=\"math-container\">\\$d\\$</span>, where <span class=\"math-container\">\\$d_x=q_x-p_x\\$</span>:</p>\n\n<p><span class=\"math-container\">\\$d_{x+1} = 2d_xp_x + {d_x}^2 + (q_0-p_0)\\$</span></p>\n\n<p>This is a bit more complicated, but we only need to use double precision numbers, so it is much, much faster when deep zooming.</p>\n\n<p>One issue is that the <span class=\"math-container\">\\$p\\$</span> sequence has to be at least as long as the <span class=\"math-container\">\\$q\\$</span> sequence, and we cannot tell the best <span class=\"math-container\">\\$p\\$</span> sequence in advance. In practice we often have to calculate new <span class=\"math-container\">\\$p\\$</span> sequences using high precision arithmetic as we discover pixels with a longer escape time.</p>\n\n<p><strong>Faster languages</strong></p>\n\n<p>There is no getting around it, Python is slow. NumPy can do the heavy lifting, which can speed it up dramatically, but it's pretty awkward compared to the same code written in C. I suggest learning to use Ctypes and writing a small C library to follow the iterative formula.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:37:08.590",
"Id": "216347",
"ParentId": "216235",
"Score": "3"
}
},
{
"body": "<p>For much more optimization, you might dig into the source for <a href=\"https://en.wikipedia.org/wiki/Fractint\" rel=\"nofollow noreferrer\">Fractint</a>. It was written in the late '80s/early '90s for hardware that was thousands of times slower than modern CPUs (but could generate the image you generated in less than a minute, in 640x480 tiles, of course). One of the \"big deals\" with FractInt was that most of the implementation uses integer math to implement fixed-point arithmetic (a much bigger deal when floating point was either emulated by slow-ish libraries or by means of optional, expensive, external chips (see Intel <a href=\"https://en.wikipedia.org/wiki/Intel_8087\" rel=\"nofollow noreferrer\">8087</a> through <a href=\"https://en.wikipedia.org/wiki/X87#80387\" rel=\"nofollow noreferrer\">80387</a>)).</p>\n\n<p>Another area of improvement : divide the image into squares. Since the Mandelbrot set is connected, if a square has no point of the set on its boundary, it has no point of the set in its interior. This leads to <a href=\"https://en.wikipedia.org/wiki/Mandelbrot_set#Border_tracing_/_edge_checking\" rel=\"nofollow noreferrer\">edge-following</a> as a strategy to vastly reduce the number of pixels that must actually be calculated.</p>\n\n<p>Source as well as MS-DOS and Win 3.x executables are still <a href=\"http://archives.math.utk.edu/software/msdos/fractals/fractint/\" rel=\"nofollow noreferrer\">available</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:18:59.903",
"Id": "418663",
"Score": "2",
"body": "Can you add important points from those links to your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:11:41.097",
"Id": "216398",
"ParentId": "216235",
"Score": "0"
}
},
{
"body": "<h1>Don't use vectorized numpy, use numba jit instead</h1>\n\n<p>Using numpy to calculate the Mandelbrot set is not really a good fit because the same data will be stored and loaded from and to memory repeatedly, thrashing the cache. A better option would be to use a jit compiler to accelerate the critical code path, for example numba jit.</p>\n\n<p>In this case, 4 characters can make the function run 200 times faster. With the function annotation <code>@jit</code> this code runs in 2 seconds instead of 400 seconds at 3000x2000 resolution, without any special tricks.</p>\n\n<pre><code>import numpy as np\nfrom PIL import Image\nfrom numba import jit\n\n@jit\ndef make_mandelbrot(width, height, max_iterations):\n result = np.zeros((height, width))\n\n # for each pixel at (ix, iy)\n for iy in np.arange(height):\n for ix in np.arange(width):\n\n # start iteration at x0 in [-2, 1] and y0 in [-1, 1]\n x0 = ix*3.0/width - 2.0\n y0 = iy*2.0/height - 1.0\n\n x = 0.0\n y = 0.0\n # perform Mandelbrot set iterations\n for iteration in range(max_iterations):\n x_new = x*x - y*y + x0\n y = 2*x*y + y0\n x = x_new\n\n # if escaped\n if x*x + y*y > 4.0:\n # color using pretty linear gradient\n color = 1.0 - 0.01*(iteration - np.log2(np.log2(x*x + y*y)))\n break\n else:\n # failed, set color to black\n color = 0.0\n\n result[iy, ix] = color\n\n return result\n\nmandelbrot = make_mandelbrot(3000, 2000, 255)\n\n# convert from float in [0, 1] to to uint8 in [0, 255] for PIL\nmandelbrot = np.clip(mandelbrot*255, 0, 255).astype(np.uint8)\nmandelbrot = Image.fromarray(mandelbrot)\nmandelbrot.save(\"mandelbrot.png\")\nmandelbrot.show()\n</code></pre>\n\n<p>As a bonus, coloring the Mandelbrot set based on a distance estimate gives a smoother look:</p>\n\n<p><a href=\"https://i.stack.imgur.com/UUXY4.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UUXY4.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:49:36.897",
"Id": "418724",
"Score": "1",
"body": "Thanks a lot, I am definitely going to try and experiment with this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:54:54.100",
"Id": "216399",
"ParentId": "216235",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T11:11:54.330",
"Id": "216235",
"Score": "37",
"Tags": [
"python",
"performance",
"python-3.x",
"image",
"fractals"
],
"Title": "Increase performance creating Mandelbrot set in python"
} | 216235 |
<p>I implemented a word n-gram model using a character ternary search tree. It is intended to be passed a generator that yields a long sequence of words (from a corpus) and its requirements are that it</p>
<ul>
<li>can return frequencies and probabilities for word n-grams</li>
<li>allows providing a vocabulary, such that n-grams containing words not
in the vocabulary are not counted</li>
<li>allows providing a list of
targets, so that only n-grams ending in a target are counted (as
probabilities for these are needed)</li>
</ul>
<p>I find that it works as expected, but it is quite slow and consumes a lot of memory. For n-grams of length 4, trained on a corpus of about 1 billion words, right now it consumes >120GB of memory, despite providing a vocabulary that consists of words with a minimum frequency of 5, and it has been running for nearly 30 already. I know that Python requires a lot of memory, but I'm wondering if I'm missing something that would make it faster and maybe less memory intensive.</p>
<p>File tst.py:</p>
<pre><code>class Node():
def __init__(self, char):
self.char = char
self.count = 0
self.lo = None
self.eq = None
self.hi = None
class TernarySearchTree():
"""Ternary search tree that stores counts for n-grams
and their subsequences.
"""
def __init__(self, splitchar=None):
"""Initializes TST.
Parameters
----------
splitchar : str
Character that separates tokens in n-gram.
Counts are stored for complete n-grams and
each sub-sequence ending in this character
"""
self._root = None
self._splitchar = splitchar
self._total = 0
def insert(self, string):
"""Insert string into Tree.
Parameters
----------
string : str
String to be inserted.
"""
self._root = self._insert(string, self._root)
self._total += 1
def frequency(self, string):
"""Return frequency of string.
Parameters
----------
string : str
Returns
-------
int
Frequency
"""
if not string:
return self._total
node = self._search(string, self._root)
if not node:
return 0
return node.count
def _insert(self, string, node):
"""Insert string at a given node.
"""
if not string:
return node
char, *rest = string
if node is None:
node = Node(char)
if char == node.char:
if not rest:
node.count += 1
return node
else:
if rest[0] == self.splitchar:
node.count += 1
node.eq = self._insert(rest, node.eq)
elif char < node.char:
node.lo = self._insert(string, node.lo)
else:
node.hi = self._insert(string, node.hi)
return node
def _search(self, string, node):
"""Return node that string ends in.
"""
if not string or not node:
return node
char, *rest = string
if char == node.char:
if not rest:
return node
return self._search(rest, node.eq)
elif char < node.char:
return self._search(string, node.lo)
else:
return self._search(string, node.hi)
def __contains__(self, string):
"""Adds "string in TST" syntactic sugar.
"""
node = self._search(string, self._root)
if node:
return node.count
return False
@property
def splitchar(self):
return self._splitchar
</code></pre>
<p>File language_model.py:</p>
<pre><code>from collections import deque
from tst import TernarySearchTree
class ContainsEverything:
"""Dummy container that mimics containing everything.
Has .add() method to mimic set.
"""
def __contains__(self, _):
return True
def add(self, _):
pass
class LanguageModel():
"""N-gram (Markov) model that uses a ternary search tree.
Tracks frequencies and calculates probabilities.
Attributes
----------
n : int
Size of n-grams to be tracked.
vocabulary : set
If provided, n-grams containing words not in vocabulary are skipped.
Can be other container than set, if it has add method.
targets : container
If provided, n-grams not ending in target are counted as
ending in "OOV" (OutOfVocabulary) instead, so probabilities
can still be calculated.
boundary : str
N-grams crossing boundary will not be counted,
e.g. sentence </s> or document </doc> meta tags
splitchar : str
String that separates tokens in n-grams
"""
def __init__(self, n, boundary="</s>", splitchar="#",
vocabulary=None, targets=None):
"""
Parameters
----------
n : int
Size of n-grams to be tracked.
boundary : str
N-grams crossing boundary will not be counted,
e.g. sentence </s> or document </doc> meta tags
splitchar : str
String that separates tokens in n-grams
vocabulary : set
If provided, n-grams with words not in vocabulary are skipped.
Can be other container than set, if it has add method.
targets : container
If provided, n-grams not ending in target are counted as
ending in "OOV" (OutOfVocabulary) instead, so probabilities
can still be calculated.
"""
if not targets:
targets = ContainsEverything()
if not vocabulary:
vocabulary = ContainsEverything()
self._n = n
self._counts = TernarySearchTree(splitchar)
self._vocabulary = vocabulary
self._targets = targets
self._boundary = boundary
self._splitchar = splitchar
def train(self, sequence):
"""Train model on all n-grams in sequence.
Parameters
----------
sequence : iterable of str
Sequence of tokens to train on.
Notes
-----
A sequence [A, B, C, D, E] with n==3 will result in these
n-grams:
[A, B, C]
[B, C, D]
[C, D, E]
[D, E]
[E]
"""
n_gram = deque(maxlen=self.n)
for element in sequence:
if element == self.boundary:
# train on smaller n-grams at end of sentence
# but exclude full n_gram if it was already trained
# on in last iteration
not_trained = len(n_gram) < self.n
for length in range(1, len(n_gram) + not_trained):
self._train(list(n_gram)[-length:])
n_gram.clear()
continue
n_gram.append(element)
if len(n_gram) == self.n:
if element not in self.targets:
self._train(list(n_gram)[:-1])
continue
self._train(n_gram)
# train on last n-grams in sequence
# ignore full n-gram if it has already been trained on
if len(n_gram) == self.n:
n_gram = list(n_gram)[1:]
for length in range(1, len(n_gram) + 1):
self._train(list(n_gram)[-length:])
def probability(self, sequence):
"""Returns probability of the sequence.
Parameters
----------
sequence : iterable of str
Sequence of tokens to get the probability for
Returns
-------
float or list of float
Probability of last element or probabilities of all elements
"""
try:
n_gram = sequence[-self.n:]
# if sequence is generator (cannot slice - TypeError),
# run through it and return probability for final element
except TypeError:
n_gram = deque(maxlen=self.n)
for element in sequence:
n_gram.append(element)
probability = self._probability(n_gram)
return probability
def frequency(self, n_gram):
"""Return frequency of n_gram.
Parameters
----------
n_gram : list/tuple of str
Returns
-------
int
Frequency
"""
n_gram_string = self.splitchar.join(n_gram)
frequency = self._counts.frequency(n_gram_string)
return frequency
def _train(self, n_gram):
# test for OOV words
for idx, word in enumerate(n_gram):
if word not in self.vocabulary:
n_gram = list(n_gram)[:idx]
n_gram_string = self.splitchar.join(n_gram)
self._counts.insert(n_gram_string)
def _probability(self, n_gram):
frequency = self.frequency(n_gram)
if frequency == 0:
return 0
*preceding, target = n_gram
total = self.frequency(preceding)
probability = frequency / total
return probability
def __contains__(self, n_gram):
return n_gram in self._counts
@property
def n(self):
return self._n
@property
def vocabulary(self):
return self._vocabulary
@property
def targets(self):
return self._targets
@property
def boundary(self):
return self._boundary
@property
def splitchar(self):
return self._splitchar
</code></pre>
<p>For testing with random strings:</p>
<pre><code>import random
from string import ascii_letters
from language_model import LanguageModel
def generate_random_strings(num):
random.seed(69)
for i in range(num):
length = random.choice(range(12))
yield "".join(random.choices(ascii_letters, k=length))
lm = LanguageModel(4)
lm.train(generate_random_strings(1000000))
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code>class ContainsEverything:\n\"\"\"Dummy container that mimics containing everything.\nHas .add() method to mimic set.\n\"\"\"\n</code></pre>\n</blockquote>\n\n<p>The indentation is borked here, and needs correcting before the code will run.</p>\n\n<hr>\n\n<p>I profiled with <code>guppy3</code> (inlining everything into one file for my convenience - that explains the <code>__main__</code> below):</p>\n\n<pre><code>lm = LanguageModel(4)\nlm.train(generate_random_strings(10000))\n\nfrom guppy import hpy\nh = hpy(lm)\nprint(h.heap())\n</code></pre>\n\n<p>Nearly all of the memory was accounted for in the top two lines:</p>\n\n<pre><code>Partition of a set of 502128 objects. Total size = 43108362 bytes.\n Index Count % Size % Cumulative % Kind (class / dict of class)\n 0 233701 47 26174512 61 26174512 61 dict of __main__.Node\n 1 233701 47 13087256 30 39261768 91 __main__.Node\n</code></pre>\n\n<p>I'm not entirely sure where the <code>dict of __main__.Node</code> comes from, but clearly <code>Node</code> is the culprit, and each node is contributing 56 bytes inherently and a further 112 bytes indirectly.</p>\n\n<p>However, looking at the use of the tree:</p>\n\n<blockquote>\n<pre><code> self._counts = TernarySearchTree(splitchar)\n ...\n frequency = self._counts.frequency(n_gram_string)\n ...\n self._counts.insert(n_gram_string)\n ...\n return n_gram in self._counts\n</code></pre>\n</blockquote>\n\n<p>I can't see any reason to use a tree. There's no use of internal nodes. As far as I can see, it can easily be replaced by a <code>Counter</code>, whereupon the memory usage drops by 90%:</p>\n\n<pre><code>Partition of a set of 34724 objects. Total size = 4141426 bytes.\n Index Count % Size % Cumulative % Kind (class / dict of class)\n 0 9838 28 884914 21 884914 21 str\n 1 8509 25 613768 15 1498682 36 tuple\n 2 415 1 365544 9 1864226 45 type\n 3 2226 6 320544 8 2184770 53 types.CodeType\n 4 4329 12 309952 7 2494722 60 bytes\n 5 1 0 295024 7 2789746 67 collections.Counter\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:42:27.610",
"Id": "226678",
"ParentId": "216244",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:18:51.573",
"Id": "216244",
"Score": "6",
"Tags": [
"python",
"performance",
"tree",
"memory-optimization",
"natural-language-processing"
],
"Title": "Ternary Search Tree / N-Gram Model in Python"
} | 216244 |
<p><strong>The task</strong>
Given a variable of type long with the number of milliseconds from January 1, 1970 until a later date (CurrentDate). Build a class for get the year, month, day of year, day of month, hour, minute and second of the CurrentDate.</p>
<p><strong>Solution 1:</strong></p>
<pre><code>public class MilisecondToDate {
public final long MILISECONDS_PER_YEAR = 31536000000L;
public final long MILISECONDS_PER_DAY = 86400000L;
public final long MILISECONDS_PER_HOUR = 3600000L;
public final long MILISECONDS_PER_MINUTE = 60000L;
public final long MILISECONDS_PER_SECONDS = 1000L;
public final int FIRST_YEAR = 1970;
public final int DAY_OF_YEAR_IN_END_OF_JANUARY = 31;
public final int DAY_OF_YEAR_IN_END_OF_FEBRUARY = 59;
public final int DAY_OF_YEAR_IN_END_OF_MARCH = 90;
public final int DAY_OF_YEAR_IN_END_OF_APRIL = 120;
public final int DAY_OF_YEAR_IN_END_OF_MAY = 151;
public final int DAY_OF_YEAR_IN_END_OF_JUNE = 181;
public final int DAY_OF_YEAR_IN_END_OF_JULY = 212;
public final int DAY_OF_YEAR_IN_END_OF_AUGUST = 243;
public final int DAY_OF_YEAR_IN_END_OF_SEPTEMBER = 273;
public final int DAY_OF_YEAR_IN_END_OF_OCTOBER = 304;
public final int DAY_OF_YEAR_IN_END_OF_NOVEMBER = 334;
public final int DAY_OF_YEAR_IN_END_OF_DECEMBER = 365;
private long milisecond;
public MilisecondToDate(long milisecond) {
this.milisecond = milisecond;
}
public int getYear() {
return FIRST_YEAR + (int)(milisecond / MILISECONDS_PER_YEAR);
}
public int getDayOfYear() {
long milisecondMinusYears = (milisecond % MILISECONDS_PER_YEAR);
int dayOfYear = (int) ((milisecondMinusYears + MILISECONDS_PER_DAY)/ MILISECONDS_PER_DAY) - getTotalOfLeapYears();
return dayOfYear;
}
public int getHour() {
long milisecondMinusYears = (milisecond % MILISECONDS_PER_YEAR);
long milisecondsMinusDays = (milisecondMinusYears % MILISECONDS_PER_DAY);
return (int) ((milisecondsMinusDays + MILISECONDS_PER_HOUR) / MILISECONDS_PER_HOUR);
}
public int getMinute() {
long milisecondMinusYears = (milisecond % MILISECONDS_PER_YEAR);
long milisecondsMinusDays = (milisecondMinusYears % MILISECONDS_PER_DAY);
long milisecondsMinusHours = (milisecondsMinusDays % MILISECONDS_PER_HOUR);
return (int) (milisecondsMinusHours / MILISECONDS_PER_MINUTE);
}
public int getSecond() {
long milisecondMinusYears = (milisecond % MILISECONDS_PER_YEAR);
long milisecondsMinusDays = (milisecondMinusYears % MILISECONDS_PER_DAY);
long milisecondsMinusHours = (milisecondsMinusDays % MILISECONDS_PER_HOUR);
long milisecondsMinusMinutes = (milisecondsMinusHours % MILISECONDS_PER_MINUTE);
return (int) (milisecondsMinusMinutes / MILISECONDS_PER_SECONDS);
}
private int getTotalOfLeapYears() {
int currentYear = getYear();
int totalLeapYears = 0;
for(int year = FIRST_YEAR; year <= currentYear; year++) {
if(isLeapYear(year)) {
totalLeapYears += 1;
}
}
return totalLeapYears;
}
private int getMonth() {
int dayOfYear = getDayOfYear();
int month = 0;
int leapYear = 0;
if(isLeapYear(getYear())) {
leapYear = 1 ;
}
if(dayOfYear < DAY_OF_YEAR_IN_END_OF_JANUARY) {
month = 1;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_FEBRUARY + leapYear)) {
month = 2;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_MARCH + leapYear)) {
month = 3;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_APRIL + leapYear)) {
month = 4;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_MAY + leapYear)) {
month = 5;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_JUNE + leapYear)) {
month = 6;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_JULY + leapYear)) {
month = 7;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_AUGUST + leapYear)) {
month = 8;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_SEPTEMBER + leapYear)) {
month = 9;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_OCTOBER + leapYear)) {
month = 10;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_NOVEMBER + leapYear)) {
month = 11;
}else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_DECEMBER + leapYear)) {
month = 12;
}else {
throw new Error("An error occurred trying to get the day of the month");
}
return month;
}
private int getDayOfMonth() {
int dayOfYear = getDayOfYear();
int month = getMonth();
int leapYear = 0;
if(isLeapYear(getYear())) {
leapYear = 1 ;
}
switch (month) {
case 1:
break;
case 2:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_JANUARY;
break;
case 3:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_FEBRUARY - leapYear;
break;
case 4:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_MARCH - leapYear;
break;
case 5:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_APRIL - leapYear;
break;
case 6:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_MAY - leapYear;
break;
case 7:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_JUNE - leapYear;
break;
case 8:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_JULY - leapYear;
break;
case 9:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_AUGUST - leapYear;
break;
case 10:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_SEPTEMBER - leapYear;
break;
case 11:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_OCTOBER - leapYear;
break;
case 12:
dayOfYear -= DAY_OF_YEAR_IN_END_OF_NOVEMBER - leapYear;
break;
default:
throw new Error("An error occurred trying to get the day of the month");
}
return dayOfYear;
}
private boolean isLeapYear(int year) {
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
return true;
}else {
return false;
}
}
public String toString() {
String date = "";
date += getYear() + "-";
date += getMonth() + "-";
date += getDayOfMonth() + " ";
date += getHour() + ":";
date += getMinute() + ":";
date += getSecond();
return date;
}
}
</code></pre>
<p>Any suggestion about the code, any idea that why I did</p>
<p>Any idea why I need to add another hour and a day?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:26:04.650",
"Id": "418524",
"Score": "0",
"body": "I probably should flag your post as not-working... but before that you really should watch this video about this exact subject and take to the hart the advice given in the end: https://www.youtube.com/watch?v=-5wpm-gesOY (The Problem with Time & Timezones - Computerphile)"
}
] | [
{
"body": "<blockquote>\n<pre><code>public class MilisecondToDate {\n</code></pre>\n</blockquote>\n\n<p>Millisecond has two 'l's in it. </p>\n\n<pre><code>public class MillisecondToDate {\n</code></pre>\n\n<p>You were consistent in your spelling, so this typo appears a lot. I won't try to correct every instance but will fix it without comment where I happen to be editing code. </p>\n\n<blockquote>\n<pre><code> public final int DAY_OF_YEAR_IN_END_OF_JANUARY = 31;\n public final int DAY_OF_YEAR_IN_END_OF_FEBRUARY = 59;\n public final int DAY_OF_YEAR_IN_END_OF_MARCH = 90;\n public final int DAY_OF_YEAR_IN_END_OF_APRIL = 120;\n public final int DAY_OF_YEAR_IN_END_OF_MAY = 151;\n public final int DAY_OF_YEAR_IN_END_OF_JUNE = 181;\n public final int DAY_OF_YEAR_IN_END_OF_JULY = 212;\n public final int DAY_OF_YEAR_IN_END_OF_AUGUST = 243;\n public final int DAY_OF_YEAR_IN_END_OF_SEPTEMBER = 273;\n public final int DAY_OF_YEAR_IN_END_OF_OCTOBER = 304;\n public final int DAY_OF_YEAR_IN_END_OF_NOVEMBER = 334;\n public final int DAY_OF_YEAR_IN_END_OF_DECEMBER = 365;\n</code></pre>\n</blockquote>\n\n<p>Given how you use this, this would be better written </p>\n\n<pre><code> public final int[] END_DAY_OF_MONTH = new int[] {\n 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };\n</code></pre>\n\n<p>Then </p>\n\n<blockquote>\n<pre><code> int leapYear = 0;\n\n if(isLeapYear(getYear())) {\n leapYear = 1 ;\n }\n\n if(dayOfYear < DAY_OF_YEAR_IN_END_OF_JANUARY) {\n month = 1;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_FEBRUARY + leapYear)) {\n month = 2;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_MARCH + leapYear)) {\n month = 3;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_APRIL + leapYear)) {\n month = 4;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_MAY + leapYear)) {\n month = 5;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_JUNE + leapYear)) {\n month = 6;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_JULY + leapYear)) {\n month = 7;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_AUGUST + leapYear)) {\n month = 8;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_SEPTEMBER + leapYear)) {\n month = 9;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_OCTOBER + leapYear)) {\n month = 10;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_NOVEMBER + leapYear)) {\n month = 11;\n }else if(dayOfYear < (DAY_OF_YEAR_IN_END_OF_DECEMBER + leapYear)) {\n month = 12;\n }else {\n throw new Error(\"An error occurred trying to get the day of the month\");\n }\n</code></pre>\n</blockquote>\n\n<p>becomes </p>\n\n<pre><code> if (dayOfYear <= END_DAY_OF_MONTH[0]) {\n throw new IllegalArgumentException(\"Cannot have non-positive day of year.\");\n }\n\n if (dayOfYear <= END_DAY_OF_MONTH[1]) {\n return 1;\n }\n\n if (isLeapYear(calculateYear())) {\n dayOfYear--;\n }\n\n for (int month = 2; month < END_DAY_OF_MONTH.length; month++) {\n if (dayOfYear <= END_DAY_OF_MONTH[month]) {\n return month;\n }\n }\n\n throw new IllegalArgumentException(\n \"Cannot have day of year more than number of days in year.\");\n</code></pre>\n\n<p>And </p>\n\n<blockquote>\n<pre><code> int dayOfYear = getDayOfYear();\n int month = getMonth();\n int leapYear = 0;\n\n if(isLeapYear(getYear())) {\n leapYear = 1 ;\n }\n\n switch (month) {\n case 1:\n break;\n case 2:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_JANUARY; \n break;\n case 3:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_FEBRUARY - leapYear; \n break;\n case 4:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_MARCH - leapYear; \n break;\n case 5:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_APRIL - leapYear; \n break;\n case 6:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_MAY - leapYear; \n break;\n case 7:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_JUNE - leapYear; \n break;\n case 8:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_JULY - leapYear; \n break;\n case 9:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_AUGUST - leapYear; \n break;\n case 10:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_SEPTEMBER - leapYear; \n break;\n case 11:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_OCTOBER - leapYear; \n break;\n case 12:\n dayOfYear -= DAY_OF_YEAR_IN_END_OF_NOVEMBER - leapYear; \n break;\n default:\n throw new Error(\"An error occurred trying to get the day of the month\");\n }\n\n return dayOfYear;\n</code></pre>\n</blockquote>\n\n<p>becomes </p>\n\n<pre><code> int day = calculateDayOfYear();\n int monthNumber = calculateMonth();\n\n if (monthNumber > Month.FEBRUARY.getNumber() && isLeapYear(calculateYear()) {\n // leap years have an extra day in February, so subtract that out\n // for days after February\n day--;\n }\n\n return day - END_DAY_OF_MONTH[monthNumber - 1];\n</code></pre>\n\n<p>I'm not sure about throwing an <code>IllegalArgumentException</code>. There may be a better one. But I am sure that you should not just throw <code>Error</code>. The second method will throw an <code>ArrayIndexOutOfBounds</code> exception. Perhaps the first one should too. </p>\n\n<p>It's also worth noting that these should never be called, as there should be no way to generate them. There's an argument that they should be left out. Because if you can't write a unit test for it, there's no point in having the code for it. </p>\n\n<p>This requires an <code>enum</code> named <code>Month</code> with the month names as values. It should have a <code>getNumber</code> method that returns the one-indexed month of the year. In particular, it should return a 2 for <code>Month.FEBRUARY</code>. </p>\n\n<p>I changed <code>get</code> to <code>calculate</code> wherever you were not accessing a field. </p>\n\n<p>I disagree with this approach. Note that you have to recalculate each value every time you need it. I would rather calculate all the values once, save them, and just fetch them as needed. To do this, I would create a <code>DateTime</code> class with getters for each field (millisecond, second, minute, hour, day of year, day of month, month, year, etc.). Then your <code>MillisecondToDate</code> class could have have a <code>convert</code> method that would return a <code>DateTime</code> and take an <code>epochMillisecond</code> parameter. I suspect that you would find synergies in the conversion. </p>\n\n<blockquote>\n<pre><code> private int getTotalOfLeapYears() {\n int currentYear = getYear();\n int totalLeapYears = 0;\n for(int year = FIRST_YEAR; year <= currentYear; year++) {\n if(isLeapYear(year)) {\n totalLeapYears += 1;\n }\n }\n return totalLeapYears;\n }\n</code></pre>\n</blockquote>\n\n<p>First, I would call this <code>countLeapYears</code>. </p>\n\n<p>Second, why increment by one? Find the first leap year after <code>FIRST_YEAR</code> (1972) and increment by four. </p>\n\n<p>Third, you shouldn't need to count. You can calculate this. </p>\n\n<pre><code> public final int LEAP_CENTURY_YEAR_COUNT = 400;\n public final int EPOCH_LEAP_CENTURY_COUNT = FIRST_YEAR / LEAP_CENTURY_YEAR_COUNT;\n public final int LEAP_CENTURY_LEAP_YEAR_COUNT = 97;\n\n private calculateLeapYearsUntil() {\n int currentYear = calculateYear();\n if (currentYear < FIRST_YEAR) {\n return 0;\n }\n\n int sinceLeapCenturyCount = currentYear % LEAP_CENTURY_YEAR_COUNT;\n int leapCenturyCount = currentYear / LEAP_CENTURY_YEAR_COUNT - EPOCH_LEAP_CENTURY_COUNT;\n\n int leapYearCount = leapCenturyCount * LEAP_CENTURY_YEAR_COUNT;\n leapYearCount += sinceLeapCenturyCount / 4;\n leapYearCount -= sinceLeapCenturyCount / 100;\n\n return leapYearCount;\n }\n</code></pre>\n\n<p>I haven't tested this, so be careful of off-by-one errors and such. But an approach like this should calculate the number of leap years directly. It won't make much difference if the year is 2019, but if the year is 12019, then this should do significantly fewer calculations. </p>\n\n<p>This solution won't work with years before 1970, but neither did your solution. I did my best to make the return values match yours. </p>\n\n<blockquote>\n<pre><code> if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {\n return true;\n }else {\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>This pattern can be written more briefly and simply as </p>\n\n<pre><code> return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));\n</code></pre>\n\n<blockquote>\n<pre><code> public String toString() {\n String date = \"\";\n\n date += getYear() + \"-\";\n date += getMonth() + \"-\";\n date += getDayOfMonth() + \" \";\n\n date += getHour() + \":\";\n date += getMinute() + \":\";\n date += getSecond();\n\n return date;\n }\n</code></pre>\n</blockquote>\n\n<p>You can use either <code>String.format</code> or <code>StringBuilder</code> here. </p>\n\n<pre><code> public String toString() {\n StringBuilder result = new StringBuilder();\n\n result.append(calculateYear()).append('-')\n .append(calculateMonth()).append('-')\n .append(calculateDayOfMonth()).append(' ');\n\n result.append(calculateHour()).append(':')\n .append(calculateMinute()).append(':')\n .append(calculateSecond());\n\n return result.toString();\n }\n</code></pre>\n\n<p>The best thing that I can say about using <code>+=</code> with strings is that it usually uses <code>StringBuilder</code> behind the scenes. The problem here is that it might use more than one <code>StringBuilder</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:06:46.087",
"Id": "216273",
"ParentId": "216246",
"Score": "2"
}
},
{
"body": "<h3>Bug - doesn't handle leap years</h3>\n<p>I got as far as your first function:</p>\n<blockquote>\n<pre><code>public int getYear() {\n return FIRST_YEAR + (int)(milisecond / MILISECONDS_PER_YEAR);\n}\n</code></pre>\n</blockquote>\n<p>and immediately saw that this wasn't going to work, because the number of milliseconds in a year isn't constant. In leap years, there is an extra day's worth of milliseconds. So for example, if your input value were <code>Dec 31, 1972</code>, your <code>getYear()</code> function would mistakenly return <code>1973</code>. It gets worse the farther you get from 1970.</p>\n<h3>Bug - can return negative day of year</h3>\n<p>Moving on to the second function:</p>\n<blockquote>\n<pre><code>public int getDayOfYear() {\n long milisecondMinusYears = (milisecond % MILISECONDS_PER_YEAR);\n int dayOfYear = (int) ((milisecondMinusYears + MILISECONDS_PER_DAY)/ MILISECONDS_PER_DAY) - getTotalOfLeapYears();\n\n return dayOfYear;\n}\n</code></pre>\n</blockquote>\n<p>Here, there is some attempt to adjust for leap years, but it isn't correct. The first part of the calculation for <code>dayOfYear</code> produces a number in the range <code>1..365</code>, but then you subtract the number of leap years, which could be some large number. Suppose the input year is 2010 and there were 10 leap years since 1970. Your function will return a number in the range <code>-9..355</code>, which is definitely wrong.</p>\n<p>This function should return a value in the range <code>1..365</code> for regular years or <code>1..366</code> for leap years.</p>\n<h3>A strange question</h3>\n<p>I find it odd that you asked this question:</p>\n<blockquote>\n<p>Any idea why I need to add another hour and a day?</p>\n</blockquote>\n<p>If you added that code, I assume you must have had a reason to do it, so wouldn't you already know why? What happens if you don't add the extra hour and day? Did you write this code?</p>\n<h3>In response to comment</h3>\n<p>OK so you tested the current time <code>3/27/19 10:14</code> and your program gave you <code>3/26/19 9:14</code>, so you added a day and an hour to fix the problem. However, you made the fix without actually figuring out why your logic was wrong in the first place, so your fix may not be correct. When bugs occur, you should determine the cause of the problem so that you can apply the correct fix, otherwise you won't know whether you have really fixed the problem.</p>\n<p>One way to do this is to test simple known values and examine the results. For example, if you give the input <code>0</code> to the program, it should refer to <code>1/1/1970 00:00</code> and your program should return <code>1</code> for the day of the year and <code>0</code> for the hour. Prior to your change, your program would give <code>0</code> for the day of the year and <code>0</code> for the hour. After your change, your program correctly gives <code>1</code> for the day of the year but incorrectly <code>1</code> for the hour.</p>\n<p>For the day of year, the reason for the bug is simple. Day of year is supposed to be in the range 1..365 (i.e. one-based, ignoring leap year for now) but your division results in a number in the range 0..364 (i.e. zero-based). Therefore you need to add one to shift from zero-based to one-based. However, note that once you change your result to be one-based, all functions that internally use <code>dayOfYear()</code> need to adjust for that, namely <code>getMonth()</code>.</p>\n<p>For the hour, the reason for the problem is not quite as clear. Assuming you want to return a military time hour (0..23), then the result you calculated is already in the correct range, and in fact, the correct value. I suspect that the reason your hour is one hour off from "now" is that you are on daylight savings time. Again, if you had tested various known times and edge cases, such as <code>12/31/1970 23:59</code>, you would have seen that your current program returned <code>24</code> for the hour, which is not correct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:14:38.170",
"Id": "418548",
"Score": "0",
"body": "Yes, I did, and if I do not add the extra hour and day, and now is 3/27/19 at 10:14, then I get 3/26/19 at 9:14"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:03:29.740",
"Id": "418592",
"Score": "0",
"body": "@Tlaloc-ES Thanks for the explanation. I've added more to my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:11:22.933",
"Id": "216307",
"ParentId": "216246",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:33:12.810",
"Id": "216246",
"Score": "2",
"Tags": [
"java",
"datetime"
],
"Title": "Class to transform milliseconds to current date"
} | 216246 |
<p>I am Displaying mask images & allowing user to upload the custome image inside mask image, now i want to give an option for user to Edit & Delete the Uploaded image.... </p>
<p>Video link : <a href="https://drive.google.com/file/d/158RCO_NaXUg9KWOKSX6_SQ5r0CYF40oK/view" rel="nofollow noreferrer">https://drive.google.com/file/d/158RCO_NaXUg9KWOKSX6_SQ5r0CYF40oK/view</a></p>
<p>For that I need to create Pop up box once user click on Edit button, Also in the pop up i need to give an option to zoom, rotate the uploaded images.... </p>
<p>for these i need to add lot of html code in future inside jquery, so is this is good way ? because i dont want to right more html code inside jquery as it looks bad when reading....</p>
<pre><code> $("<span class=\"pip\">" +
"<br/><span id="open" class=\"edit\">Edit </span>" +
"<br/><span class=\"remove\">Remove </span>" +
"</span>").insertAfter("#fileup");
</code></pre>
<p>Or Is it possible to write Html code outside script ?</p>
<p>Here is full code in pen : <a href="https://codepen.io/kidsdial/pen/drLwVO" rel="nofollow noreferrer">https://codepen.io/kidsdial/pen/drLwVO</a></p>
<p>Here is jsfiddle : <a href="https://jsfiddle.net/kidsdial1/86Leb4gw/3/" rel="nofollow noreferrer">https://jsfiddle.net/kidsdial1/86Leb4gw/3/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";
let jsonData = {
"path" : " newyear collage\/",
"info" : {
"author" : "",
"keywords" : "",
"file" : "newyear collage",
"date" : "sRGB",
"title" : "",
"description" : "Normal",
"generator" : "Export Kit v1.2.8"
},
"name" : "newyear collage",
"layers" : [
{
"x" : 0,
"height" : 612,
"layers" : [
{
"x" : 0,
"color" : "0xFFFFFF",
"height" : 612,
"y" : 0,
"width" : 612,
"shapeType" : "rectangle",
"type" : "shape",
"name" : "bg_rectangle"
},
{
"x" : 160,
"height" : 296,
"layers" : [
{
"x" : 0,
"height" : 296,
"src" : "ax0HVTs.png",
"y" : 0,
"width" : 429,
"type" : "image",
"name" : "mask_image_1"
},
{
"radius" : "26 \/ 27",
"color" : "0xACACAC",
"x" : 188,
"y" : 122,
"height" : 53,
"width" : 53,
"shapeType" : "ellipse",
"type" : "shape",
"name" : "useradd_ellipse1"
}
],
"y" : 291,
"width" : 429,
"type" : "group",
"name" : "user_image_1"
},
{
"x" : 25,
"height" : 324,
"layers" : [
{
"x" : 0,
"height" : 324,
"src" : "hEM2kEP.png",
"y" : 0,
"width" : 471,
"type" : "image",
"name" : "mask_image_2"
},
{
"radius" : "26 \/ 27",
"color" : "0xACACAC",
"x" : 209,
"y" : 136,
"height" : 53,
"width" : 53,
"shapeType" : "ellipse",
"type" : "shape",
"name" : "useradd_ellipse_2"
}
],
"y" : 22,
"width" : 471,
"type" : "group",
"name" : "user_image_2"
}
],
"y" : 0,
"width" : 612,
"type" : "group",
"name" : "newyearcollage08"
}
]
};
$(document).ready(function() {
// upload image onclick
$('.container').click(function(e) {
// filtering out non-canvas clicks
if (e.target.tagName !== 'CANVAS') return;
// getting absolute points relative to container
const absX = e.offsetX + e.target.parentNode.offsetLeft + e.currentTarget.offsetLeft;
const absY = e.offsetY + e.target.parentNode.offsetTop + e.currentTarget.offsetTop;
const $canvasList = $(this).find('canvas');
// moving all canvas parents on the same z-index
$canvasList.parent().css({zIndex: 0});
$canvasList.filter(function () { // filtering only applicable canvases
const bbox = this.getBoundingClientRect()
return (
absX >= bbox.left && absX <= bbox.left + bbox.width &&
absY >= bbox.top && absY <= bbox.top + bbox.height)
}).each(function () { // checking white in a click position
const x = absX - this.parentNode.offsetLeft - e.currentTarget.offsetLeft;
const y = absY - this.parentNode.offsetTop - e.currentTarget.offsetTop;
const pixel = this.getContext('2d').getImageData(x, y, 1, 1).data;
if (pixel[3] === 255) {
$(this).parent().css({zIndex: 2})
target = this.id;
console.log(target);
setTimeout(() => {
$('#fileup').click();
}, 20);
}
})
});
function getAllSrc(layers) {
let arr = [];
layers.forEach(layer => {
if (layer.src) {
arr.push({
src: layer.src,
x: layer.x,
y: layer.y,
name: layer.name
});
} else if (layer.layers) {
let newArr = getAllSrc(layer.layers);
if (newArr.length > 0) {
newArr.forEach(({
src,
x,
y,
name
}) => {
arr.push({
src,
x: (layer.x + x),
y: (layer.y + y),
name: (name)
});
});
}
}
});
return arr;
}
function json(data)
{
var width = 0;
var height = 0;
let arr = getAllSrc(data.layers);
let layer1 = data.layers;
width = layer1[0].width;
height = layer1[0].height;
let counter = 0;
let table = [];
for (let {
src,
x,
y,
name
} of arr) {
$(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
if(name.indexOf('mask_') !== -1){
var imageUrl1 = imageUrl;
}else{
var imageUrl1 = '';
}
var mask = $(".container").mask({
imageUrl: imageUrl1,
maskImageUrl: 'https://i.imgur.com/' + src,
onMaskImageCreate: function(img) {
img.css({
"position": "absolute",
"left": x + "px",
"top": y + "px"
});
},
id: counter
});
table.push(mask);
fileup.onchange = function() {
let mask2 = table[target];
mask2.loadImage(URL.createObjectURL(fileup.files[0]));
document.getElementById('fileup').value = "";
// Below code to Remove image
$("<span class=\"pip\">" +
"<br/><span id=\"myBtn\" class=\"edit\">Edit </span>" +
"<br/><span class=\"remove\">Remove </span>" +
"</span>").insertAfter("#fileup");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
// Remove image code ended here....
};
counter++;
// get the text
}
drawText(data);
}
json(jsonData);
}); // end of document ready
// extempl code - get the text
const fonts = []; // caching duplicate fonts
function drawText(layer) {
if (layer.type === 'image') return;
if (!layer.type || layer.type === 'group') {
return layer.layers.forEach(drawText)
}
if (layer.type === 'text') {
const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;
if (!fonts.includes(url)) {
fonts.push(url);
$("style").prepend("@font-face {\n" +
"\tfont-family: \"" + layer.font + "\";\n" +
"\tsrc: url(" + url + ") format('truetype');\n" +
"}");
}
$('.container').append(
'<div class="txtContainer" ' +
'style="' +
'text-align: ' + layer.justification + '; ' +
'font-family: ' + layer.font + '; ' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' +
'width:' + layer.width + 'px; ' +
'color: ' + layer.color.replace(/^0x/, '#') + '; ' +
'font-size: ' + layer.size + 'px; ' +
'height:' + layer.height + 'px;' +
'">' +
layer.text +
'</div>');
}
}
// extempl code end
// jq plugin
(function($) {
var JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function(div) {},
}, options);
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.onDragStart = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
$(canvas).attr("active", "true");
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
var img = new Image();
evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
evt.originalEvent.dataTransfer.setData('text/plain', 'anything');
}
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
if (pixel[3] === 255) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
clearTimeout(timeout);
timeout = setTimeout(function() {
container.updateStyle();
renderInnerImage();
}, 20);
}
} else {
evt.stopPropagation();
return false;
}
}
};
container.updateStyle = function() {
return new Promise((resolve, reject) => {
context.beginPath();
context.globalCompositeOperation = "source-over";
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function()
{
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({
"width": image.width,
"height": image.height
});
resolve();
};
});
};
function renderInnerImage() {
img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = settings.imageUrl;
img.onload = function() {
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}
// change the draggable image
container.loadImage = function(imageUrl) {
console.log("load");
//if (img)
// img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle().then(renderInnerImage);
};
// change the masked Image
container.loadMaskImage = function(imageUrl, from) {
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
// div.find("canvas").on('touchstart mousedown', function(event)
div.find("canvas").on('dragstart', function(event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({
item: container,
id: settings.id
})
return container;
};
}(jQuery));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.temp {}
.container {
background: gold;
position: relative;
}
.container img {
position:absolute;
top:0;
bottom:250px;
left:0;
right:0;
margin:auto;
z-index:999;
}
.masked-img {
overflow: hidden;
position: relative;
}
.txtContainer{ position:absolute; text-align:center; color:#FFF}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
.edit {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.edit:hover {
background: white;
color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<input id="fileup" name="fileup" type="file" style="display:none" >
<div class="container">
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:53:14.380",
"Id": "418451",
"Score": "1",
"body": "What does this code do? Please tell us. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:02:38.483",
"Id": "418464",
"Score": "0",
"body": "What is your requirement? and what you are trying to do from business/exercise point of view in this code? Your title is vague and therefore your question becomes harder to answer."
}
] | [
{
"body": "<p>You can write your Templates as plain HTML (invisible) and then clone, adapt and insert them as you want.</p>\n\n<p>HTML5 has even an extra template tag: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template</a></p>\n\n<pre class=\"lang-html prettyprint-override\"><code><div id='demoTemplate' style='display: none;'>\n <span class='pip'> \n <br/><span class='edit'>Edit </span>\n <br/><span class='remove'>Remove </span>\n </span>\n</div>\n<!-- or -->\n<template id='demoTemplate'>\n <span class='pip'> \n <br/><span class='edit'>Edit </span>\n <br/><span class='remove'>Remove </span>\n </span>\n</template>\n<input id='fileup' name='fileup' type='file' style='display:none'>\n\n<script>\n // This copies also div-style='display:none', either remove the style or the outer div/template\n $('#demoTemplate').clone().insertAfter('#fileup');\n\n // or even something like this\n $($('#demoTemplate').html()).insertAfter('#fileup');\n</script>\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:23:55.070",
"Id": "418665",
"Score": "0",
"body": "thanks, instead of writing as template, is there any other way i can write the html code outside <Script> tag & still make it work for `editing & deleting uploaded images`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:20:55.260",
"Id": "419451",
"Score": "0",
"body": "can we still use same concept if we have css styles as in this code : https://pastebin.com/EextDCzF , here i included that code in codepen : https://codepen.io/kidsdial/pen/axdgJR"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T13:43:09.517",
"Id": "419569",
"Score": "0",
"body": "also can we use same concept if i have code like this : `\"<br/><span style =\\\"left: layer.x + 'px;'\\\" class=\\\"edit\\\" >Edit </span>\" +` , because i have `left: layer.x + 'px;` , as in html <style> : `left:layer.x` will not work..... how to handle these cases , how to write in better way ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T07:47:38.377",
"Id": "420743",
"Score": "0",
"body": "how to handle these [kind of things](https://stackoverflow.com/questions/55684184/using-template-tag-to-display-popup-next-to-edit-button) ?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:20:22.110",
"Id": "216251",
"ParentId": "216247",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216251",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:40:35.010",
"Id": "216247",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Edit and delete uploaded images code inside script tag"
} | 216247 |
<p>I did a job application to a Unity developer position and i was given a coding challenge which was implementing a Rock Paper Scissors game or a variation of it. I have implemented the game using Unity and C# and the feed back I got was my implementation being "too mathematical" and "lacking object oriented principles". So i am a bit confused so i thought i should ask four your feedback.</p>
<p>I have actually implemented Rock Paper Scissors Lizard Spock from The Big Bang Theory show and had a simple logic having elements in a list and calculating who wins based on these indexes in the list. So it works like this:</p>
<blockquote>
<p>If the absolute difference between Player and Opponent element index is even, then element with smaller index wins and if it is odd, the element with bigger index wins.</p>
</blockquote>
<p>I have two scripts for achieving this, one is attached to all elements(Rock,Paper etc.) in the game which just handle IO operations and send the selected input to <code>GameController</code> like this:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElementController : MonoBehaviour
{
public GameObject Controller;
private Renderer rend;
private GameController GameController;
private Color previousColor;
private List<string> Elements = new List<string>() { "Spock", "Lizard", "Rock", "Paper", "Scissor" };
void Start()
{
rend = gameObject.GetComponent<Renderer>();
previousColor = rend.material.color;
GameController = Controller.GetComponent<GameController>();
}
void OnMouseEnter()
{
rend.material.color = Color.yellow;
previousColor = Color.yellow;
}
void OnMouseExit()
{
rend.material.color = Color.white;
previousColor = Color.white;
}
void OnMouseDown()
{
//Mouse can be clicked only if Coroutine is not running
if (!GameController.isRunning)
{
// Passing the selected element by user to GameController
GameController.Game(Elements.IndexOf(gameObject.name));
rend.material.color = Color.red;
}
}
}
</code></pre>
<p>And then the <code>GameController</code> runs a coroutine and gives the result of each round like this:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
#region UIElements
public Button Restart;
public Text RoundResult;
public Text PlayerScoreText;
private int PlayerScore = 0;
public Text OpponentScoreText;
private int OpponentScore = 0;
#endregion UIElements
[HideInInspector]
public bool isRunning = false;
public GameObject Opponent;
public float flipDuration;
//Indexes are required to calculate winner of each round
private readonly List<string> Elements = new List<string>() { "Spock", "Lizard", "Rock", "Paper", "Scissor" };
private int OppMove;
void Start()
{
Restart.onClick.AddListener(RestartGame);
}
public void Game(int PlayerElement)
{
StartCoroutine(RoundResultCoroutine(PlayerElement));
}
//Coroutine running every round
IEnumerator RoundResultCoroutine(int PlayerElement)
{
//Since Range with integers are not maximally inclusive
OppMove = Random.Range(0, 5);
//Activate child Opponent played
Opponent.transform.GetChild(OppMove).transform.gameObject.SetActive(true);
float t = 0;
//isRunning is used in order to prevent user inteference during each round is held.
isRunning = true;
while (t < flipDuration)
{
t += Time.deltaTime;
Opponent.transform.eulerAngles = Vector3.Lerp(new Vector3(0, 0, 0), new Vector3(0, 180, 0), t / flipDuration);
yield return null;
}
/*
* Player has equal probability of winning or losing since there are odd number of elements.
* From the rules we can infer with the indexing of Spock = 0, Lizard = 1, Rock = 2, Paper = 3, Scissor = 4
* if the absolute difference between Player and opponent element is even, then element with smaller index wins
* if it is odd, the element with bigger index wins. Because as we can see from the graph and imagine it as a directed graph
* an element always wins against the next element and loses against the previous element. Also it wins against next element of its directed
* neighbor. This mathematical solution is implemented in order to eliminate keeping track of all possible Rules between two chosen elements.
* Also this aproach would work with any N = #elements given that N is odd. N should be odd to have same probability for each element in order to
* have a fair game.
*/
if (PlayerElement == OppMove)
{
RoundResult.text = "It is a tie";
RoundResult.GetComponent<Text>().color = Color.white;
}
//Having even absolute difference
else if (Mathf.Abs(OppMove - PlayerElement) % 2 == 0)
{
if (PlayerElement > OppMove)
{
UpdateScore("Opponent", PlayerElement, OppMove);
}
else
{
UpdateScore("Player", PlayerElement, OppMove);
}
}
//Having odd absolute difference
else
{
if (PlayerElement > OppMove)
{
UpdateScore("Player", PlayerElement, OppMove);
}
else
{
UpdateScore("Opponent", PlayerElement, OppMove);
}
}
yield return new WaitForSeconds(flipDuration * 2);
RoundResult.text = " ";
t = 0;
while (t < flipDuration)
{
t += Time.deltaTime;
Opponent.transform.eulerAngles = Vector3.Lerp(new Vector3(0, 180, 0), new Vector3(0, 0, 0), t / flipDuration);
yield return null;
}
Opponent.transform.GetChild(OppMove).transform.gameObject.SetActive(false);
isRunning = false;
}
// Method used for updating score and modifying round result text
private void UpdateScore(string winner, int PlayerMove, int OpponentMove)
{
if (winner == "Player")
{
PlayerScore++;
PlayerScoreText.text = PlayerScore.ToString();
RoundResult.text = Elements[PlayerMove] + " wins against " + Elements[OpponentMove];
RoundResult.GetComponent<Text>().color = Color.green;
}
else if (winner == "Opponent")
{
OpponentScore++;
OpponentScoreText.text = OpponentScore.ToString();
RoundResult.text = Elements[PlayerMove] + " loses against " + Elements[OpponentMove];
RoundResult.GetComponent<Text>().color = Color.red;
}
}
private void RestartGame()
{
if (!isRunning)
{
PlayerScore = 0;
PlayerScoreText.text = PlayerScore.ToString();
OpponentScore = 0;
OpponentScoreText.text = OpponentScore.ToString();
}
}
}
</code></pre>
<p>In general, i wanted to ask you how would i complete this task with better oo handling. Should i have used <code>Singleton</code> for game controller or instead of this mathematical solution have a static list of rules and check from that list.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:02:04.267",
"Id": "418400",
"Score": "3",
"body": "I don't understand, what do they mean by being `Too mathematical` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:04:11.043",
"Id": "418402",
"Score": "0",
"body": "I am not sure. I got the feed back from the recruiter but i am guessing they wanted me to have a static list of rules instead of that mathematical approach for deciding on winner of the round."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:45:02.220",
"Id": "418462",
"Score": "0",
"body": "Could you post complete classes instead of just their content please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:11:17.673",
"Id": "418472",
"Score": "1",
"body": "@t3chb0t I updated the scripts."
}
] | [
{
"body": "<p>I am neither a C# nor Unity coder. With that in mind, here goes:</p>\n\n<p>You don't seem to be following Microsoft's C# coding conventions, and it's not obvious to me what you are following. In the absence of some documented reason, I'd suggest going with the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions\" rel=\"nofollow noreferrer\">industry standard</a>.</p>\n\n<p>I don't understand the logic of keeping <code>rend</code> as a \"global\" variable. </p>\n\n<pre><code>private Renderer rend;\n\n// ...\n\nvoid Start()\n{\n rend = gameObject.GetComponent<Renderer>();\n previousColor = rend.material.color;\n GameController = Controller.GetComponent<GameController>();\n}\n</code></pre>\n\n<p>Why not just make <code>rend</code> a local var:</p>\n\n<pre><code>void Start()\n{\n var rend = gameObject...\n}\n</code></pre>\n\n<p>Since the events being handled are \"human scale\" events, you can afford to repeat the call to <code>GetComponent</code> at the top.</p>\n\n<p>I would suggest that you break your <code>RoundResultCoroutine</code> into smaller pieces: the rule of thumb about subroutines fitting on a single 25-line screen still applies. Certainly it seems like there is a part that makes the opponent's move, which could be a separate function, and a part that determines the outcome of play, which could be a separate function. So that area seems ripe for improvement.</p>\n\n<p>In my opinion (which is worthless, since I'm not involved in your hiring decision) the \"mathematical\" approach to determining the result of play is quite nice. I would definitely suggest that you not change that part! You might want to include a better explanation of how/why it works, and maybe some notes about its efficiency...</p>\n\n<p>There seems to be some other stuff missing. I don't see the declarations of the top-level objects, for instance. That makes it hard to suggest how you could be more OO. But you don't define any classes yourself, so that may be why you got dinged for not OO enough. Perhaps creating some kind of <code>GameResult</code> class would help? I really don't feel like it's needed. Try just cleaning up your non-OO code first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:20:45.477",
"Id": "418473",
"Score": "0",
"body": "Thanks for the recommendations. I used rend as a global variable thinking not to use `GetComponent`repeatedly but you are actually right. I also modified the scripts with full classes. I will definitely dig into C# conventions it was a nice suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T19:52:40.420",
"Id": "436577",
"Score": "0",
"body": "In Unity, `GetComponent` is an expensive call, and while it being called here only in `OnMouseXYZ` methods probably won't have as much gameplay impact as if it were called on every frame, it is conventional to cache the output of `GetComponent` calls whenever the result is expected to be used multiple times."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:38:44.810",
"Id": "216268",
"ParentId": "216249",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>... \"too mathematical\" and \"lacking object oriented principles\"</p>\n</blockquote>\n\n<p>These go hand in hand. An algorithm is what it is. Not that it is or is not too mathematical but that necessarily busy, complex, or obscure code is not wrapped in code that behaves (exposed) in subject/business terms. </p>\n\n<p>For example I think method and variable naming has a distinct algorithmic feel. Also the good start with <code>{\"Spock, \"Lizard\" ...}</code> is not exploited, it's all index referencing.</p>\n\n<h2>--------------</h2>\n\n<p><strong>Object Oriented DNA</strong></p>\n\n<p>The general goal of writing in subject matter terms starts with data structures that can be (indeed must be) exploited in an OO way. Subsequent code layers naturally tend to exhibit OO tendencies when we <em>start</em> with OO. Should technical limitations require \"less robust\" structures like a list of strings (is there anything worse!?), wrapping that in its own class will pay dividends.</p>\n\n<hr>\n\n<pre><code>class Element { \n protected List<string> elements = new List<string>() {\"Spock\"...};\n\n public string Spock { get { return elements[0]; } }\n\n // exposing the low-level, abstract foundation\n // is definitely a code smell\n int indexOf (string thisGuy) { ... }\n</code></pre>\n\n<p>If we really must have a list of strings. Benefits for readability, error avoidance, and ease of use are easy to imagine.</p>\n\n<hr>\n\n<pre><code>enum Element = {Spock, Lizard, ...}\n</code></pre>\n\n<p>has better coding expressive power, avoids all string pitfalls (typos, CasInG), is type safe, and we can work with underlying <code>int</code> values. Also, <code>enum</code> values can be XOR'ed to group them; way cool.</p>\n\n<hr>\n\n<pre><code>Dictionary<Element, Element> Rules = new Dictionary<Element, Element>()\n { Element.Rock, Element.Scissors},\n { Element.Scissors, Element.Paper}, ...\n</code></pre>\n\n<p>This defines \"Rock beats Scissors\", \"Scissors beats Paper\", etc. Since some <code>Element</code>s defeat 2 or more things the dictionary value maybe should be a collection of some kind or even an <code>enum</code> grouping (see XOR comment above).</p>\n\n<p>If the <code>Rules</code> value must be a <code>List<Element></code>, let's say, then a class is probably in order. Client code should not be allowed or required(!) to rifle through <code>Rules</code> objects. </p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T07:32:40.583",
"Id": "418531",
"Score": "0",
"body": "Thanks for your feedback. `Enum` is something i definitely should have considered. I just have one thing to correct. Each element wins against exactly 2 elements and loses against 2 as well to have a fair game. Otherwise, you would go for elements with higher probability of winning."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:46:45.363",
"Id": "216301",
"ParentId": "216249",
"Score": "6"
}
},
{
"body": "<p>Other reviews already cover a lot of ground so this will be a bit wordy.</p>\n\n<p>Software developers create abstractions - at some point, the code will be complicated but it's our job to encapsulate that and make it easier to understand. Remember: you will spend as much time reading code as you will writing it. </p>\n\n<p>Not everyone will be aware of the rules of Rock, Paper, Scissors, Lizard, Spock. How would you go about displaying some help text? Will you type it out by hand or resort to convoluted logic over the array values? Consider how you might fill in this code:</p>\n\n<pre><code>string gameExplanation = \"The rules are: \" + ...\n</code></pre>\n\n<p>With radarbob's suggestion of a dictionary, it's easy:</p>\n\n<pre><code>string gameExplanation = \"The rules are: \" + string.Join(Environment.NewLine, Game.Rules.Select(kvp => $\"{kvp.Key} beats {kvp.Value\");\n</code></pre>\n\n<p>You can see that even this isn't a perfect abstraction because the verb is usually different. E.g. \"Rock <em>crushes</em> Scissors\", \"Paper <em>disproves</em> Spock\". Your list cannot encode this difference. It is already at the limit of what it can describe. Your comment mentions that the rules are a graph. It's probably overkill to model it as a graph but your rules should be first class citizens - not buried in some logic to decide who wins.</p>\n\n<p>I appreciate that this was an example bit of code for an interview so you wouldn't want to spend too much time on it but you also need to show what you can do. If I see a candidate with code that is extensible, even if that extension hasn't been added, I'm going to think that they've thought it through before starting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:01:09.123",
"Id": "418666",
"Score": "0",
"body": "I actually thought of the abstraction you mentioned but my attitude was towards having a more robust solution which will work even with 7, 9 or more odd number of elements. In those cases abstraction would be almost impossible because for example in case of 9, you need 36 rules. I thought of solving this problem by having the rules as graph and as a UI element in the game."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:07:56.770",
"Id": "418668",
"Score": "1",
"body": "What I like about your comment @AliKanat is that you clearly had thought about it (and well) but it's not clear from the code that you had. I realise on second reading that it is a note in your comment but it's buried. Make your thinking and choices obvious to the interviewer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:14:11.297",
"Id": "418669",
"Score": "0",
"body": ":) Thanks i will keep that in mind for next interview."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:46:46.067",
"Id": "216404",
"ParentId": "216249",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:47:31.743",
"Id": "216249",
"Score": "7",
"Tags": [
"c#",
"object-oriented",
"interview-questions",
"unity3d",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors coding challenge"
} | 216249 |
<p>I have a function <code>find_all_intervals_below</code> that iterates through a vector and finds all the index intervals of at least a given length where each element within the interval is below a given threshold.</p>
<pre><code>struct Interval {
int start;
int end;
};
std::vector<Interval>
find_all_intervals_below(const std::vector<int> &v, const int &threshold,
const int &min_length) {
auto start_position { 0 };
auto end_position { 0 };
std::vector<Interval> intervals;
bool found_start { false };
for (auto current_pos = 0; current_pos < v.size(); ++current_pos) {
if (v[current_pos] <= threshold and not found_start) {
start_position = current_pos;
end_position = 0;
found_start = true;
} else if (found_start and v[current_pos] > threshold and end_position == 0) {
end_position = current_pos;
if (end_position - start_position >= min_length) {
Interval interval;
interval.start = start_position;
interval.end = end_position;
intervals.push_back(interval);
}
start_position = 0;
found_start = false;
}
}
if (found_start and end_position == 0 and v.size() - start_position >= min_length) {
end_position = v.size();
Interval interval;
interval.start = start_position;
interval.end = end_position;
intervals.push_back(interval);
}
return intervals;
}
</code></pre>
<p>This function works perfectly fine, I would just like to get some input from others as I imagine there is likely much more succinct ways of doing this. <a href="http://www.cplusplus.com/reference/algorithm/search_n/" rel="nofollow noreferrer"><code>search_n</code></a> from STL looks like it might be a solution but I couldn't figure out how to use it for my case.</p>
<p><strong>EDIT:</strong> I need the solution to be C++11 compatible, unfortunately.</p>
<h3>Test example</h3>
<pre><code>const auto min_len { 3 };
const auto threshold { 3 };
const std::vector<int> v { 4, 2, 1, 1, 4, 1, 2, 4 };
const auto actual { find_all_intervals_below(v, threshold, min_len) };
const std::vector<Interval> expected { Interval(1, 4) };
assert(actual == expected);
</code></pre>
| [] | [
{
"body": "<p>If you want to write concise, idiomatic C++, the best way is to rely on the STL as much as possible, as a tool as well as an inspiration. </p>\n\n<p>So how would this algorithm be implemented in the STL? </p>\n\n<ul>\n<li><p>It probably wouldn't implemented so specifically. It would be more abstract: for instance, being under a threshold is a particular case of a satisfying a predicate; iterating over a vector is a particular case of iterating over a sequence (i.e a pair of iterators). </p></li>\n<li><p>It would also be separated into orthogonal components: finding ranges whose elements satisfy a predicate is a thing, filtering those ranges which aren't long enough another. </p></li>\n<li><p>Finally, complex algorithms are broken into simpler parts when possible (some say that the whole <code><algorithm></code> header is a patient construction of <code>std::sort</code> from its parts).</p></li>\n</ul>\n\n<p>In the light of all this, I suggest:</p>\n\n<ul>\n<li><p>function signatures based on iterators</p></li>\n<li><p>an intermediate algorithm to find consecutive elements satisfying a predicate</p></li>\n<li><p>an algorithm to find all sequences of consecutive elements satisfying a predicate</p></li>\n<li><p>composing the latter algorithm with known STL algorithm to customize its behavior.</p></li>\n</ul>\n\n<p>For instance:</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <vector>\n#include <iostream>\n\n// the intermediate algorithm\ntemplate <typename Iterator, typename Pred>\nstd::pair<Iterator, Iterator> find_range_satisfying(Iterator first, Iterator last, Pred pred) {\n auto f = std::find_if(first, last, pred);\n if (f == last) return {last, last}; // representation of failure. std::optional would have been a good choice also\n return {f, std::find_if(std::next(f), last, std::not_fn(pred))};\n}\n\ntemplate <typename Iterator, typename Pred>\nauto find_all_ranges_satisfying(Iterator first, Iterator last, Pred pred) {\n std::vector<std::pair<Iterator, Iterator>> result;\n while (first != last) {\n auto [b, e] = find_range_satisfying(first, last, pred);\n if (b == last) break;\n result.push_back({b, e});\n first = e;\n }\n return result;\n}\n\nint main() {\n const std::vector<int> v { 4, 2, 1, 1, 4, 1, 2, 4 };\n const auto threshold = 3;\n auto test = find_all_ranges_satisfying(v.begin(), v.end(), [](auto elem) { return elem < 3; });\n // composing with remove_if to obtain the desired behavior\n test.erase(std::remove_if(test.begin(), test.end(), [threshold](auto rng) {\n return std::distance(rng.first, rng.second) < threshold;\n }));\n for (auto [b, e] : test) {\n std::for_each(b, e, [](auto elem) { std::cout << elem << ' '; });\n std::cout << std::endl;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:20:45.047",
"Id": "418423",
"Score": "0",
"body": "I like this implementation. But unfortunately the project I am working on is only C++11"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:25:17.543",
"Id": "418431",
"Score": "0",
"body": "@MichaelHall, at first glance, other than structured bindings, I didn't find anything that C++11 capable compiler couldn't compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:26:18.497",
"Id": "418434",
"Score": "0",
"body": "`std::not_fn` is C++17 https://en.cppreference.com/w/cpp/utility/functional/not_fn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:26:21.310",
"Id": "418435",
"Score": "1",
"body": "@papagaga, by the way, there is `std::erase_if` coming in C++20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:26:55.860",
"Id": "418436",
"Score": "0",
"body": "@MichaelHall, one can replace `std::find_if` with `std::find_if_not`. I believe there is no expressive gained in C++14+ for this problem, but it might reduce the elegance significantly. It is good to include language version tag in the question, but sometimes it is ignored by reviewers."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:58:07.607",
"Id": "216255",
"ParentId": "216250",
"Score": "6"
}
},
{
"body": "<h2>Code Review</h2>\n\n<ol>\n<li><p>This piece</p>\n\n<pre><code> Interval interval;\n interval.start = start_position;\n interval.end = end_position;\n intervals.push_back(interval);\n</code></pre>\n\n<p>can be transformed into</p>\n\n<pre><code>intervals.emplace_back(start_position, end_position);\n</code></pre></li>\n<li><p>Don't accept small objects by reference for read-only purposes. Although it usually doesn't hurt, in most implementations reference (which is implemented as pointer) will take up more space (compiler will probably inline the function or just pass by value though).</p></li>\n<li><p>Algorithm. When there is a state which is represented by combination of flags and some metadata, flags usually go out of hand quickly. I would instead implement something like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>1. Set previous, current to start of the input\n2. previous = current\n3. current = first index of element that is higher than threshold\n4. if current - previous >= minlength, add to result\n5. increment current\n6. Go to 2\n</code></pre>\n\n<p>One could also create it the other way around, e.g. searching for those below threshold.</p></li>\n</ol>\n\n<h2>Alternative implementation</h2>\n\n<pre><code>#include <vector>\n#include <algorithm>\n#include <type_traits>\n\nusing index_type = std::make_signed_t<std::size_t>;\n\nstruct interval {\n index_type first;\n index_type last;\n};\n\nbool operator==(const interval lhs, const interval rhs) {\n return lhs.first == rhs.first && lhs.last == rhs.last;\n}\n\nstd::vector<interval> find_suitable_intervals(const std::vector<int>& input, \n const int threshold, \n const index_type min_length) {\n auto predicate = [threshold](int x) {\n return x <= threshold;\n };\n std::vector<interval> intervals;\n auto first = input.begin();\n auto previous = input.begin();\n auto current = first;\n while (current != input.end()) {\n previous = current;\n current = std::find_if_not(current, input.end(), predicate);\n if (current - previous >= min_length) {\n intervals.push_back({previous - first, current - first});\n }\n if (current == input.end()) {\n break;\n }\n ++current;\n }\n\n return intervals;\n}\n\nint main() {\n const int min_length = 3;\n const int threshold = 3;\n const std::vector<int> v { 4, 2, 1, 1, 4, 1, 2, 4 };\n\n const auto actual = find_suitable_intervals(v, threshold, min_length);\n const std::vector<interval> expected { {1, 4} };\n\n return actual != expected;\n}\n</code></pre>\n\n<p><a href=\"https://wandbox.org/permlink/uNCADTUvLrL5neqL\" rel=\"noreferrer\">Wandbox Demo</a>.</p>\n\n<p>The logic got more \"flat\", but there are culprits of bridging STL style with more traditional style. Also, since incrementing iterator beyond end will cause undefined behavior, I had to put in the condition to check if the loop reached end. Mixing <code>std::size_t</code> and <code>std::distance</code>/difference will cause a warning and will require a cast to get rid of the warning, since one is unsigned and the other is not, thus I created <code>index_type</code>. There are rumors of <code>std::index</code>, but I wouldn't expect it in near future.</p>\n\n<p>One could also make the condition an input into the function, e.g. predicate. Then it would look like this:</p>\n\n<pre><code>find_suitable_intervals(data, min_length, [threshold](auto x) { \n x < threshold;\n});\n</code></pre>\n\n<p>Which is I believe is a bit more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:03:53.853",
"Id": "216258",
"ParentId": "216250",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216258",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:58:13.870",
"Id": "216250",
"Score": "8",
"Tags": [
"c++",
"c++11",
"interval"
],
"Title": "Finding all intervals that match predicate in vector"
} | 216250 |
<p>The task:</p>
<blockquote>
<p>Given a list of points, a central point, and an integer k, find the
nearest k points from the central point.</p>
<p>For example, given the list of points [(0, 0), (5, 4), (3, 1)], the
central point (1, 2), and k = 2, return [(0, 0), (3, 1)].</p>
</blockquote>
<p>My solution:</p>
<pre><code>const lst = [[0, 0], [5, 4], [3, 1]];
const center = [1, 2];
const k = 2;
const findNearestPoints = ({lst, center, k}) => {
// I assume the data are valid; no error checks
const calcHypo = x => Math.sqrt((x[0] - center[0])**2
+ (x[1] - center[1])**2);
const sortPoints = (a,b) => calcHypo(a) - calcHypo(b);
return lst
.sort(sortPoints)
.slice(0,k);
};
console.log(findNearestPoints({lst, center, k}));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:21:26.843",
"Id": "418424",
"Score": "0",
"body": "First thing that popped into my mind is that there actually exists a hypotenuse function in the `Math` global which you could use (`Math.hypot`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:02:30.980",
"Id": "418455",
"Score": "0",
"body": "Computing a square root (or two of them, actually) on every comparison can get expensive. With a thousand points, you're doing 20x more math than necessary. Caching hypotenuse lengths can be a good time-space trade, if speed is more important than memory conservation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T00:17:34.960",
"Id": "418514",
"Score": "0",
"body": "@morbusg `Math.hypot` is multi dimensional \\$O(n)\\$ where n is number of dimensions and as such has a hefty overhead associated with vetting and iterating the argument array. For 2D hypotenuse `(x*x+y*y)**0.5` is much quicker"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T00:20:27.427",
"Id": "418515",
"Score": "1",
"body": "@OhMyGoodness the hypotenuse is not needed, the square of the hypotenuse can be used to compare differences in distance."
}
] | [
{
"body": "<h2>Don't <code>sqrt</code> the distance.</h2>\n\n<p>It is a common mistake when filtering distances to use the complete distance calculation.</p>\n\n<p>Given 2 values <code>a</code> and <code>b</code>, if <code>a</code> < <code>b</code> then it is also true that <code>sqrt(a)</code> < <code>sqrt(b)</code>. Hence you don't need the expensive <code>sqrt</code> calculation to know the if a point is closer than another.</p>\n\n<p>To find the closest the following does not use the <code>sqrt</code> of the distance.</p>\n\n<pre><code>function closestPoint(points, point, dist){\n var x, y, found, min = dist * dist; // sqr distance\n for(const p of points) {\n x = p[0] - point[0];\n y = p[1] - point[1];\n x *= x;\n y *= y;\n if(x + y < min){\n min = x + y;\n if (min === 0) { return p } // early exit\n found = p;\n }\n }\n return found;\n\n}\n</code></pre>\n\n<h2>Not in the sort!!!</h2>\n\n<p>You are doing the distance calculation in the sort DON'T!!!, that means you repeat the same calculations over and over.</p>\n\n<p>To improve you throughput the following will reduce the over all time. The improvement is linear and does not change the complexity.</p>\n\n<p><strong>Note</strong> that in JS <code>a ** 2</code> is slightly slower than <code>a * a</code></p>\n\n<p>A more efficient version of your solution</p>\n\n<pre><code>function findNearestPoints({list, center, k}) {\n const res = [];\n const cx = center[0], cy = center[1]; // alias and reduce indexing overhead\n const distSqr = (x, y) => (x -= cx) * x + (y -= cy) * y;\n const sort = (a, b) => a[1] - b[1];\n\n for (const p of list) { res.push([p, distSqr(p[0], p[1])]) }\n res.sort(sort).length = k;\n return res.map(p => p[0]);\n}\n</code></pre>\n\n<h2>The <code>**</code> operator for roots</h2>\n\n<p><strong>Note</strong> that JS has the <code>**</code> operator. That you can use it to get roots by making the right side the inverse, 1 over the power. Thus the sqrt is <code>**(1/2)</code> the cube root is <code>**(1/3)</code></p>\n\n<p>eg </p>\n\n<pre><code>if 2 ** 2 === 4 then 4 ** (1/2) === 2\nif 2 ** 3 === 8 then 8 ** (1/3) === 2 Don't approximate 8 ** 0.33 !== 2\nif 2 ** 4 === 16 then 16 ** (1/4) === 2\n</code></pre>\n\n<h2>Better sort</h2>\n\n<p>The sort is the bottle neck in this problem.</p>\n\n<p>You can use a binary tree sort as it is the least complex for real numbers (every coder should learn how to implement a binary tree sort)</p>\n\n<h2>Do you need the sort?</h2>\n\n<p>However I think (think means might be, I am going by instinct) that there is a faster solution that does not involve a sort and that is at most <span class=\"math-container\">\\$O(n)\\$</span></p>\n\n<p>Remember that the order of the points is not important, that you need only separate the points in two. It may take a few passes to do, but as long as the number of passes is not related to the number of points or 'k' you will have a <span class=\"math-container\">\\$O(n)\\$</span> solution.</p>\n\n<p>I am not going to give you the solution this time (if there is one) as there is no problem solving experienced gained coping code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T11:15:37.710",
"Id": "418558",
"Score": "0",
"body": "Where did you get the info that `a ** 2` is slightly slower than `a * a`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:51:17.010",
"Id": "418571",
"Score": "0",
"body": "@thadeuszlay I bench-mark it. I just retested on Chrome 73 and its gotten worse. Comparative results `n * n` fastest. n is random number. (The following % are percent as fast as best eg 50% is half the speed). `Math.pow(n, 2)` very close 99% for small ints and same performance for large doubles. `n ** 2` is 36% for random large doubles 0 to \\$2^{51}\\$ and random ints 0 to \\$2^{31}\\$, and 24% for random small ints 0 to \\$2^8\\$. On FF all 3 are the same however all are only 20% as fast as Chromes best."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T00:02:47.407",
"Id": "216303",
"ParentId": "216253",
"Score": "5"
}
},
{
"body": "<p>Use a max-heap of at most <em>k</em> elements. Loop through all of the <em>n</em> points computing their (squared) distances to the central point. If the root of node of the heap is farther from the central point than the <em>i</em>'th of the <em>n</em> points, then discard the root and <code>heapify</code> with the <em>i</em>'th. This has time complexity <code>n*log(k)</code> rather than <code>n*log(n)</code> which is a huge difference if <em>n >> k</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T03:40:54.033",
"Id": "496150",
"Score": "0",
"body": "Welcome to the Code Review Community. It might be good in the future to make meaningful observations about the code as well as suggesting alternate solutions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T23:20:05.390",
"Id": "251926",
"ParentId": "216253",
"Score": "1"
}
},
{
"body": "<p>The answers here are great, especially if you're looking to implement this algorithm in a faster way (which would be very important to do if there could potentially be a lot of points - the current implementation would be slow on large lists).</p>\n<p>...however, I didn't see anything in the problem description about speed being a needed factor. I tend to put code quality first, avoid premature optimizations, and only speed up the code when its needed. (i.e. if there's only ever going to be at most 5 points in the list, then many speed improvements end up becoming overhead that slows the algorithm down instead of speeding it up!)</p>\n<p>With that in mind, I actually really like the way you implemented it. It's clear and easy to understand. I'll just add a couple suggestions:</p>\n<ul>\n<li>Like others have already pointed out, you can use Math.abs()</li>\n<li>I would copy the array of points before sorting them - .sort() modifies the original array, and you generally don't want to modify function parameters.</li>\n</ul>\n<p>Here's my version:</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 distanceBetween = ([x1, y1], [x2, y2]) => Math.hypot(x1 - x2, y1 - y2);\n\nconst findNearestPoints = ({points, center, numberOfResults}) => {\n const distanceFromCenter = p => distanceBetween(p, center);\n return [...points]\n .sort((p1, p2) => distanceFromCenter(p1) - distanceFromCenter(p2))\n .slice(0, numberOfResults);\n};\n\nconsole.log(findNearestPoints({\n points: [[0, 0], [5, 4], [3, 1]],\n center: [1, 2],\n numberOfResults: 2,\n}));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T02:50:49.773",
"Id": "254511",
"ParentId": "216253",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216303",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:31:59.623",
"Id": "216253",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Find nearest k points from the central point"
} | 216253 |
<p>I'm debating with my colleagues which code is better:
<code>user_agent</code> is a class instance. The class itself comes from a third-party library so we don't have any control over it.</p>
<p>1.</p>
<pre><code>def _get_ua_device_type(user_agent):
property_to_type = {'is_mobile': 'mobile', 'is_tablet': 'tablet', 'is_pc': 'pc', 'is_bot': 'bot'}
for prop, type in property_to_type.items():
if get_attr(user_agent, prop) is True:
return type
return 'unknown'
</code></pre>
<p>2.</p>
<pre><code>def _get_ua_device_type(user_agent):
for type in ('mobile', 'tablet', 'pc', 'bot'):
if get_attr(user_agent, f'is_{type}') is True:
return type
return 'unknown'
</code></pre>
<p>3.</p>
<pre><code>def _get_ua_device_type(user_agent):
if user_agent.is_mobile:
return 'mobile'
if user_agent.is_tablet:
return 'tablet'
if user_agent.is_pc:
return 'pc'
if user_agent.is_bot:
return 'bot'
return 'unknown'
</code></pre>
<p>Things we discussed:</p>
<ol>
<li>Static code is easier to understand than dynamic.</li>
<li>Static code is easier to test.</li>
<li>Dynamic code is declarative and more idiomatic than metameric <code>if</code>s.</li>
<li>Dynamic code will be as hard/easy to understand regardless of the number of choices.</li>
<li>It's hard to anticipate the number of choices up-front so why start with a more complex dynamic form?</li>
<li>Assuming that predicate names are derived from type names is bad.</li>
<li>Where is the line when code is spaghetti-like and should be rewritten in a more dynamic way?</li>
<li>What about Zen of Python (“Explicit is better than implicit.“, “Flat is better than nested.“, “Readability counts.”, “Simple is better than complex.”)</li>
</ol>
<p>Do you have your own thoughts/suggestions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:18:46.463",
"Id": "418419",
"Score": "3",
"body": "What is `user_agent`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:23:38.090",
"Id": "418427",
"Score": "0",
"body": "\"`user_agent` is a class instance\" is no more helpful than saying `user_agent` is a variable. What's the name of the 3rd party, and the name of the class this class instance is an instance of?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:25:05.690",
"Id": "418429",
"Score": "0",
"body": "Alternatively, you could just give a dummy implementation (`collections.namedtuple(\"UserAgent\", [\"is_mobile\", \"is_tablet\", \"is_pc\", \"is_bot\"])` for example)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:26:04.567",
"Id": "418433",
"Score": "1",
"body": "@Graipher That's not why I'm asking for its name. The code may already have defined this function. Why recommend new code when you can just use say `user_agent.agent` for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:29:48.920",
"Id": "418437",
"Score": "0",
"body": "@Peilonrayz, I agree it would make most sense if there was `user_agent.agent` but let's assume it doesn't exist and we need to return it in our code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:39:24.227",
"Id": "418440",
"Score": "2",
"body": "@mnowotka: Please add those details to the question, so it is not missing any context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:40:23.373",
"Id": "418444",
"Score": "2",
"body": "Also please don't modify your code after getting answers. Have a look at what you can and cannot do after receiving answers here: https://codereview.stackexchange.com/help/someone-answers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:41:19.867",
"Id": "418445",
"Score": "1",
"body": "@Graipher - sorry about that, I'm still new here. I removed it because this is not the essence of my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:48:01.920",
"Id": "418449",
"Score": "0",
"body": "Fair enough, but I guess you will just have to live with it being there now :) For questions which are not a comparative review, you can always ask a new follow-up question if you feel that there is more improvement left (you can also do that with comparative review questions, but it might be more messy...). But here I would just wait for some more time (allowing at least 24 hours for everyone on the globe to be able to see and answer your question is usually a good idea). Since this point has been included in both answers so far, it will probably not be included in further answers."
}
] | [
{
"body": "<h2>Equivalence considerations</h2>\n\n<p>1 is not the same as 2 or 3 for older versions of Python. In 2 and 3, you have an ordered execution sequence that determines the priority of returned variables. In 1, you have a dictionary whose order is inherently unknown. This might be OK for you, or it might not. If it isn't, a workaround is to use an <code>OrderedDict</code>.</p>\n\n<p>For newer versions of Python (3.6+) this should not be an issue.</p>\n\n<h2>Drop boolean redundancy</h2>\n\n<p>No matter what you do, you should probably stop writing <code>is True</code> if you know that the target variable is already boolean. If the variable can have mixed type (i.e. integer or boolean), which is bad but sadly often possible in Python, and if you care about this, then you need to keep <code>is True</code>.</p>\n\n<h2>Ownership</h2>\n\n<p>Do you control the design of <code>user_agent</code>? If so, then you can enforce a stable interface, and my favourite of your options is 2, simply because it's more concise. If not, then only (3) would work well with static analysis to catch a changing interface.</p>\n\n<h2>Other options</h2>\n\n<pre><code>try:\n return next(type for type in ('mobile', 'tablet', 'pc', 'bot')\n if get_attr(user_agent, f'is_{type}'))\nexcept StopIteration:\n return 'unknown'\n</code></pre>\n\n<h2>The bigger problem</h2>\n\n<p>is that you're representing an idea of a type with multiple booleans when it should be a single enum-style variable. If you can change your user agent to do this, do this. If not, you may want to consider writing a multivariate-boolean-to-single-enum shim class to sanitize the rest of your business logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:37:56.187",
"Id": "418438",
"Score": "1",
"body": "1 is the same as 2 and 3 in Python 3.5+ IIRC and f-strings are available in 3.6+."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:39:13.253",
"Id": "418439",
"Score": "0",
"body": "@Peilonrayz That's a consequence of some implementations that isn't guaranteed pre-Python 3.7. Read https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:39:49.000",
"Id": "418443",
"Score": "0",
"body": "I removed the `is True` part because this is not a point of my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:49:58.930",
"Id": "418450",
"Score": "1",
"body": "@Reinderien: It is guaranteed in cPython 3.6+ and any Python implementation starting from Python 3.7+, as noted in the link you posted and from the question we can only assume any Python 3.6+, so technically you are not wrong. Nevertheless I think making your first point a bit milder might be a good idea. Something like \"1 is not the same as 2 or 3, depending on your Python version and implementation\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:35:40.913",
"Id": "216262",
"ParentId": "216259",
"Score": "4"
}
},
{
"body": "<p>In your first two solutions you compare with <code>is True</code> in <code>if get_attr(user_agent, prop) is True</code> / <code>if get_attr(user_agent, f'is_{type}') is True</code>. Explicitly comparing to <code>True</code>/<code>False</code> is usually frowned upon in Python (contrary to \"Explicit is better than implicit\"), you want to accept any truthy or falsey value. So just do <code>if get_attr(user_agent, f'is_{type}')</code>.</p>\n\n<p>As to which is better, that is indeed a tough call. None of them are really nice, all of them have some disadvantages:</p>\n\n<ol>\n<li><p>I would only choose the first one if the mapping from attribute name to types was less regular.</p></li>\n<li><p>I would personally prefer number two. It is succinct and readable. All three implementations depend on the implementation of the <code>user_name</code> class, anyway, by hardcoding the names, so none of them is more robust in that regard. It also scales more easily with the number of cases, since you only need to add it to the tuple (maybe eventually pulling it out into a separate variable if there are too many).</p></li>\n<li><p>If there were less possibilities, the third one is definitely the most readable version. It is also the one where adding more types is the most tedious, since you copy&paste code around.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:39:43.207",
"Id": "418442",
"Score": "0",
"body": "I removed the `is True` part because this is not a point of my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:42:09.150",
"Id": "418446",
"Score": "2",
"body": "@mnowotka: Nevertheless, I rolled back your edit because it invalidates the answers you already got (see my comment on the question for a link to the help center). Code Review allows answers to comment on any and all aspects of the code (even if that is not exactly what the asker wants to hear)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:42:52.400",
"Id": "418447",
"Score": "0",
"body": "That's pitty because it distracts people from my actual question :("
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:37:22.963",
"Id": "216263",
"ParentId": "216259",
"Score": "1"
}
},
{
"body": "<p>This is a very good question. Thanks for asking.</p>\n\n<hr>\n\n<p><strong>Review</strong></p>\n\n<ul>\n<li>I'm ignoring <code>is True</code> as others have mentioned it.</li>\n<li>Second code piece is reasonably better than first one, since you have further reduced duplicated information.</li>\n<li>I prefer second one over others personally and it's readable for me.</li>\n<li>Third one is too verbose. But it is readable nevertheless.</li>\n</ul>\n\n<p><strong>Boundaries should be clean</strong></p>\n\n<ul>\n<li>If you are using set of similar function to interact with <code>user_agent</code> it would be better to create a wrapper class such as <code>UserAgent</code> in your code.\n\n<ul>\n<li>It is a good practice to wrap third-party behaviour. </li>\n<li>This gives you more control and it becomes easier for you to maintain your code even when you update third-party libraries.</li>\n</ul></li>\n</ul>\n\n<blockquote>\n <p>Code at the boundaries needs clear separation and tests that define\n expectations. We should avoid letting too much of our code know about\n the third-party particulars. It’s better to depend on something you\n control than on something you don’t control, lest it end up\n controlling you.</p>\n \n <p><sub>Clean Code by Robert C. Martin</sub></p>\n</blockquote>\n\n<p><strong>Is explicit better than implicit?</strong></p>\n\n<ul>\n<li>This should be carefully interpreted. It depend on the context. In your scenario even though third piece of code is more explicit it is poorer than other code because it has duplicate information therefore violating <strong>Don't Repeat Yourself</strong>.</li>\n</ul>\n\n<blockquote>\n <p>Duplication (inadvertent or purposeful duplication) can lead to\n maintenance nightmares, poor factoring, and logical contradictions.</p>\n \n <p><sub><a href=\"http://wiki.c2.com/?DontRepeatYourself\" rel=\"nofollow noreferrer\">http://wiki.c2.com/?DontRepeatYourself</a></sub></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:53:30.150",
"Id": "216271",
"ParentId": "216259",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:16:00.673",
"Id": "216259",
"Score": "5",
"Tags": [
"python",
"comparative-review"
],
"Title": "Getting device type from user agent in Python - is explicit better than implicit?"
} | 216259 |
<p>I created simple quicksort algorithm using iterators. I'm happy with implementation but not with its speed. Profiler tells me that the slowest operation here is <code>std::iter_swap</code>. I don't really know how to improve this code. Note that I am not asking for different kind of quicksort algorithm but about improving this one.</p>
<pre><code>#include <iterator>
#include <utility>
#include <functional>
template <typename RandomIt, typename Compare = std::less_equal<>>
void Sort::QuickSort(RandomIt first, RandomIt last, Compare compare = Compare())
{
if (std::distance(first, last) <= 1) return;
RandomIt pivot = Partition(first, last, compare);
QuickSort(first, pivot, compare);
QuickSort(std::next(pivot, 1), last, compare);
}
template <typename RandomIt, typename Compare>
RandomIt Sort::Partition(RandomIt first, RandomIt last, Compare compare)
{
RandomIt pivot = MedianOf3(first, last, compare);
RandomIt i = first;
for (RandomIt j = first; j != pivot; ++j)
if (compare(*j, *pivot)) {
std::iter_swap(i, j);
++i;
}
std::iter_swap(i, pivot);
return i;
}
template <typename RandomIt, typename Compare>
RandomIt Sort::MedianOf3(RandomIt first, RandomIt last, Compare compare)
{
auto collectionSize = std::distance(first, last);
RandomIt middle = std::next(first, collectionSize / 2);
RandomIt targetPivot = std::prev(last, 1);
if (compare(*middle, *first))
std::iter_swap(middle, first);
if (compare(*targetPivot, *first))
std::iter_swap(targetPivot, first);
if (compare(*middle, *targetPivot))
std::iter_swap(middle, targetPivot);
return targetPivot;
}
</code></pre>
<p>For testing I used vectors of 100 000 random elements. This code average sorting time is about 1626 ms on my machine and <code>std::sort</code> on the same set of data performs 10 times better, around 163 ms. I know that <code>std::sort</code> uses introsort but still quicksort shouldn't be 10 times slower.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:09:43.060",
"Id": "418458",
"Score": "0",
"body": "You might get better reviews if you show the test program (if you don't want that part reviewed, just say so) and the necessary headers (at least `<iterator>`; perhaps others?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:15:30.573",
"Id": "418459",
"Score": "0",
"body": "I'd say that your performance problem is that `std::iter_swap()` is called too many times. Try moving `i` forwards from `first` while `*i` is less than `*pivot` and `j` backwards from `last` while `*pivot` is less than `*j`, then, when `*j` < `*pivot` < `*i`, perform the swap. Repeat until `i`==`j`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:51:23.480",
"Id": "418468",
"Score": "0",
"body": "I'll try it, it will definitely improve performance. I will need some time for it, iterators have some edge cases in Hoare's scheme that I need to think about. Another minor question, is it ok to write something like `std::prev(last, 1)` or `last - 1` is better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:58:24.473",
"Id": "418471",
"Score": "0",
"body": "Personally, I find `last - 1` easier to read and should be defined for all `RandomIterator` types. I only use `std::prev()` when I really need a function to pass around. There could be something I missed, so don't just accept my say-so on that!"
}
] | [
{
"body": "<p>To get this code to compile I had to add the <code>Sort</code> namespace definition:</p>\n\n<pre><code>namespace Sort\n{\n template <typename RandomIt, typename Compare = std::less_equal<>>\n void QuickSort(RandomIt first, RandomIt last, Compare compare = Compare());\n\n template <typename RandomIt, typename Compare>\n RandomIt Partition(RandomIt first, RandomIt last, Compare compare);\n\n template <typename RandomIt, typename Compare>\n RandomIt MedianOf3(RandomIt first, RandomIt last, Compare compare);\n}\n</code></pre>\n\n<p>And I had to remove the default argument from the redeclaration of <code>Sort::QuickSort</code>:</p>\n\n<pre><code>template <typename RandomIt, typename Compare = std::less_equal<>>\nvoid Sort::QuickSort(RandomIt first, RandomIt last, Compare compare)\n</code></pre>\n\n<p>Review requests should have issues like that already accounted for.</p>\n\n<hr>\n\n<p>The performance of the <code>Partition()</code> function can be improved by doing fewer swaps. The current loop swaps when <code>*j</code> < <code>*pivot</code>, without considering whether <code>*i</code> is less or greater than <code>*pivot</code>. Instead, we can use two iterators, and advance them towards each other, swapping only when the ascending iterator points to an item greater than pivot <em>and</em> the descending iterator points to one smaller than pivot. The tricky bit is to avoid the iterators passing each other without terminating.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:22:45.643",
"Id": "216281",
"ParentId": "216264",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:57:13.910",
"Id": "216264",
"Score": "3",
"Tags": [
"c++",
"performance",
"reinventing-the-wheel",
"iterator"
],
"Title": "Optimizing quicksort"
} | 216264 |
<p>I'm building a web app using Flask to offer surveys to users. The number of questions on the survey and the type of questions isn't known until runtime. I finally have the code working properly, and would like some feedback on how pythonic the code is and what I can do to improve it.</p>
<p>To account for a single form page that can display multiple types of questions, I have the following in my <code>forms.py</code> file (I'm going with the PEP 8 notation that lines 99 characters long is acceptable for teams that prefer it):</p>
<pre><code>class FieldsRequiredForm(FlaskForm):
class Meta:
def render_field(self, field, render_kw):
render_kw.setdefault('required', True)
return super().render_field(field, render_kw)
</code></pre>
<p>Here is the route code:</p>
<pre><code>@bp.route('/survey/<string:slug>', methods=['GET', 'POST'])
def survey(slug):
class SurveyForm(FieldsRequiredForm):
pass
survey = Survey.query.filter_by(slug=slug).first_or_404()
questions = survey.questions
question_ids = [question.id for question in questions]
if 'answers' not in session:
session['answers'] = json.dumps({id: None for id in question_ids})
form = F()
answers = json.loads(session['answers'])
if request.method == 'POST':
record_submitted_answer()
answers = json.loads(session['answers'])
if None in answers.values():
question = get_next_question()
SurveyForm.question_id = HiddenField(default=question.id)
if question.category == 'word':
SurveyForm.answer = StringField(question.question)
elif question.category == 'likert':
SurveyForm.answer = RadioField(question.question, choices=tuple(likert().items()))
SurveyForm.submit = SubmitField('Submit')
else:
SurveyForm.answer = StringField()
form = F()
if form.validate_on_submit():
if None not in answers.values():
write_answers_to_database(survey=survey)
if survey.ty:
lines = iter(survey.ty.splitlines())
else:
with open('app/static/ty.txt', 'r') as f:
lines = f.readlines()
ty = [line.strip() for line in lines]
return render_template('ty.html', ty=ty)
return redirect(url_for('survey.survey', slug=slug))
return render_template('survey.html', form=form)
</code></pre>
<p>Please, tell me what I did wrong or could have done better.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:25:27.057",
"Id": "216267",
"Score": "2",
"Tags": [
"python",
"flask"
],
"Title": "Generate dynamic surveys using Python Flask"
} | 216267 |
<p>Take this controller for instance. Is there a way I can rip out the constructor and property, extend a base controller class and still have $twig? I feel like this repeitive behaviour can be removed.</p>
<p>I understand that I need to extend a base class, but I'm not 100% sure where to go from there.
<pre><code>namespace App\Controllers;
class Welcome extends {
private $twig;
public function __construct(\Twig_Environment $twig) {
$this->twig = $twig;
}
public function getTemplate() {
return $this->twig->render('/templates/welcome.html', array());
}
}
?>
</code></pre>
<p>When I try and create a base class like this, removing the constructor and property from the Welcome class, I get <code>Undefined property: App\Controllers\Welcome::$twig</code></p>
<pre><code><?php declare(strict_types = 1);
namespace App\Controllers;
class Base {
private $twig;
public function __construct(\Twig_Environment $twig) {
$this->twig = $twig;
}
}
?>
</code></pre>
<p>If I have 100 controllers, that's 100 classes to refactor if I ever change my template engine, surely there must be a way to add some sort of base class to do this? And then extend it in all classes.</p>
| [] | [
{
"body": "<p>You can make a 'getter' method for <code>$twig</code> in your base controller, like this:</p>\n\n<pre><code>class Base {\n private $twig;\n\n public function __construct(\\Twig_Environment $twig) \n {\n $this->twig = $twig;\n }\n\n public function getTwig()\n {\n return $this->twig;\n }\n\n}\n</code></pre>\n\n<p>This would make the <code>getTemplate()</code> method look like this:</p>\n\n<pre><code>public function getTemplate() {\n return $this->getTwig()->render('/templates/welcome.html', array());\n}\n</code></pre>\n\n<p>Or you could make <code>$twig</code> <em>protected</em> instead of <em>private</em>. See: </p>\n\n<p><a href=\"https://www.php.net/manual/en/language.oop5.visibility.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.oop5.visibility.php</a></p>\n\n<p>Your code is far from complete, and so my answer is too. There may be other ways to do things. Always keep in might that ownership of classes should guide your decisions. For instance, if you don't own the twig class you could use the base controller to interface with it. In that case you would not make a getter for <code>$twig</code>, but implement a method for <code>render()</code>, inside the base controllor, which can be used by extended classes. That way you will only ever need to change the base controller if the twig class changes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T19:22:40.123",
"Id": "216284",
"ParentId": "216269",
"Score": "1"
}
},
{
"body": "<p>Lets look at your code</p>\n\n<pre><code>namespace App\\Controllers;\n\nclass Welcome extends {\n private $twig;\n\n public function __construct(\\Twig_Environment $twig) {\n $this->twig = $twig;\n }\n\n public function getTemplate() {\n return $this->twig->render('/templates/welcome.html', array());\n }\n}\n//------------------------\nnamespace App\\Controllers;\n\nclass Base {\n private $twig;\n\n public function __construct(\\Twig_Environment $twig) {\n $this->twig = $twig;\n }\n\n}\n</code></pre>\n\n<p>You have 3 Big issues here:</p>\n\n<ol>\n<li><code>class Welcome extends {</code> - extends what</li>\n<li><code>private $twig;</code> this property is private, which means only the class it's defined in can access it</li>\n<li><code>public function __construct</code></li>\n</ol>\n\n<p>Lets fix these (this simplest way):</p>\n\n<pre><code>namespace App\\Controllers;\nclass Welcome extends Base {\n protected $twig; //use protected - even though private would work this way\n\n public function __construct(\\Twig_Environment $twig) {\n $this->twig = $twig;\n }\n\n public function getTemplate() {\n return $this->twig->render('/templates/welcome.html', array());\n }\n}\n//------------------------\nnamespace App\\Controllers;\n\nclass Base {\n\n /*public function __construct(\\Twig_Environment $twig) {\n parent::__construct($twig); //or omit the constructor all togather\n }*/\n\n}\n</code></pre>\n\n<p>In this simple example, you can just Nuke the guts of the child class as there is nothing specific to that class in the code shown. This happens to be the whole point of inheritance. </p>\n\n<p>I left the constructor in comments, in this minimal example its not needed. But you may want it in the future, so you can use <code>parent</code> to call the parent classes version of any <code>protected/public</code> methods. Regardless if <code>$twig</code> is private we will want to try to re-use as much of the parent code as we can. If it's private you have no choice but to use the parent's version, or set it after the fact.</p>\n\n<p>If you want to keep <code>$twig</code> private for some reason, keep in mind the property is only visible within the <code>Base</code> class. So any work you do directly on it must also be in that same class. This means you can setup a method to return it, or set it in the parent class and call it from the child class. This is rather trivial so I don't think it warrants an example, but if you want one, just let me know.</p>\n\n<p>To be honest I use <code>private</code> about 10% of the time. Only when I have some value only the parent class should \"know\" about. And example would be say you have a base class that connects to the DB. Well the act of connecting and the data needed for that is largely irrelevant to the child classes. They don't (nor should they) care how the DB connection happened as the parent can take care of that without any need for the child to be aware of it. All the child needs is whatever connection resource you get from the act of connecting.</p>\n\n<p>When thinking about OOP, one very good thing to learn is called <code>S.O.L.I.D</code> </p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/SOLID</a></p>\n\n<blockquote>\n <p><strong>Single</strong> responsibility principle[6]\n A class should have only a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</p>\n \n <p><strong>Open architecture</strong> \"Software entities ... should be open for extension, but closed for modification.\"</p>\n \n <p><strong>Liskov substitution principle</strong>\n \"Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.\" See also design by contract.</p>\n \n <p><strong>Interface segregation principle</strong> \"Many client-specific interfaces are better than one general-purpose interface.\"</p>\n \n <p><strong>Dependency</strong> inversion principle\n One should \"depend upon abstractions, [not] concretions.\"</p>\n</blockquote>\n\n<p>By having the template object private, your breaking rule Number2 or the <code>Open architecture</code>. You could make Base an Abstract class (if it doesn't extend a concrete class), this way your not tempted to use it as a concrete Object. That's mostly <code>5</code>. If the parent is \"responsible\" for creating the template, there is no need for the child to take on that responsibility <code>1</code> and some of <code>3</code> (by not duplicating the code, we insure that <code>Welcome</code> can seamlessly replace <code>Base</code> etc... Because this is not 100% code you control, a Controller must meet certain specifications for example, there is only so much you can do. A controller is also generally the end result of a Request so you won't have much need of interfaces etc. Because you can't just load a controller at will and use it. Interfaces are for type hinting your inputs to insure they posses the methods the interface demands. That is the contract for the object.</p>\n\n<p>These are \"general\" guide lines, you should try to use. But that doesn't mean you have to use all of them. For example don't make abstract classes and interfaces just because they are part of SOLID principals, due it because it's the correct thing to do for that object.</p>\n\n<p>Cheers!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:12:06.727",
"Id": "216296",
"ParentId": "216269",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:44:39.430",
"Id": "216269",
"Score": "-1",
"Tags": [
"php"
],
"Title": "Refactoring my controllers with a BaseController to remove repetitive code?"
} | 216269 |
<p>This is my first Go program. I would like to know what could be improved, what is done wrong, and anything else that I should know. The CSV contains 10 questions with the 10 answers separated by a comma. For example:</p>
<pre><code>10+10,20
4+5,32
</code></pre>
<p>If you want the full context this is from <a href="https://gophercises.com/exercises/quiz" rel="noreferrer">gophercises</a> which are some exercises to practice Go.</p>
<pre><code>package main
import (
"encoding/csv"
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
var points int
func main() {
fPtr := flag.String("csv", "problems.csv", "FileName in csv (question, answer)")
tPtr := flag.Int("time", 10, "Time in seconds")
sPtr := flag.Bool("shuffle", true, "shuffle your questions order")
flag.Parse()
questions := readCSV(*fPtr)
fmt.Print("Press enter to start you have ", *tPtr, " seconds")
fmt.Scanln()
askQuestions(&questions, *tPtr, *sPtr)
fmt.Println("You got ", points, " points")
}
func askQuestions(questions *[][]string, time int, s bool) {
go startTimer(time)
for _, i := range shuffle(s, len(*questions)) {
fmt.Println("Question ", (*questions)[i][0], ":")
var a string
fmt.Scan(&a)
a = strings.ToLower(strings.Trim(a, " "))
if a == (*questions)[i][1] {
points++
}
}
}
func shuffle(shuffle bool, sliceLen int) []int {
var r []int
for i := 0; i < sliceLen; i++ {
r = append(r, i)
}
if shuffle {
rand.Seed(time.Now().Unix())
rand.Shuffle(len(r), func(i, j int) {
r[i], r[j] = r[j], r[i]
})
}
return r
}
func readCSV(s string) (questions [][]string) {
f, err1 := os.Open(s)
records, err2 := csv.NewReader(f).ReadAll()
for err1 != nil || err2 != nil {
fmt.Println("Error: ", err1, err2)
fmt.Println("Please re-enter the name of the CSV file: ")
fmt.Scan(&s)
f, err1 = os.Open(s)
records, err2 = csv.NewReader(f).ReadAll()
}
return records
}
func startTimer(seconds int) {
time.Sleep(time.Duration(seconds) * time.Second)
fmt.Println("Time is up! You got ", points, " points")
os.Exit(0)
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-21T09:03:19.933",
"Id": "421456",
"Score": "0",
"body": "Thanks for sharing the exercises resource! Looks nice and useful"
}
] | [
{
"body": "<h2><code>startTimer()</code></h2>\n\n<p>The <code>time</code> package provides timers natively. So rather than using a call to <code>time.Sleep()</code>, you can use <a href=\"https://golang.org/pkg/time/#NewTimer\" rel=\"noreferrer\"><code>time.NewTimer()</code></a>.</p>\n\n<p>Use <code>fmt.Printf()</code> rather than <code>fmt.Println()</code> for printing formatted strings.</p>\n\n<pre><code>func startTimer(seconds int) {\n time.Sleep(time.Duration(seconds) * time.Second)\n fmt.Println(\"Time is up! You got \", points, \" points\")\n os.Exit(0)\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>func startTimer(sec int) {\n timer := time.NewTimer(time.Duration(sec) * time.Second)\n <-timer.C\n fmt.Printf(\"Time is up! You got %d points\\n\", points)\n os.Exit(0)\n}\n</code></pre>\n\n<h2><code>readCSV()</code></h2>\n\n<p>In <code>readCSV()</code>, you have multiple error variables. You can instead use a single error variable as you go along.</p>\n\n<p>I advise against adding file retry logic. It complicates the code, and most users can simply re-run the command upon error. Instead, you should return an error value.</p>\n\n<p>Using a named return (<code>questions</code>) means you should actually use the <code>questions</code> variable. Because I switch to multiple return values, I removed the named parameter.</p>\n\n<p>Also be sure to close the file after you're done reading from it.</p>\n\n<pre><code>func readCSV(s string) (questions [][]string) {\n f, err1 := os.Open(s)\n records, err2 := csv.NewReader(f).ReadAll()\n for err1 != nil || err2 != nil {\n fmt.Println(\"Error: \", err1, err2)\n fmt.Println(\"Please re-enter the name of the CSV file: \")\n fmt.Scan(&s)\n f, err1 = os.Open(s)\n records, err2 = csv.NewReader(f).ReadAll()\n }\n return records\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>func readCSV(name string) ([][]string, error) {\n f, err := os.Open(name)\n\n if err != nil {\n return nil, err\n }\n\n qs, err := csv.NewReader(f).ReadAll()\n\n if err != nil {\n return nil, err\n }\n\n return qs, f.Close()\n}\n</code></pre>\n\n<h2><code>askQuestions()</code></h2>\n\n<p>Again, here you should use <code>fmt.Printf()</code> to print formatted strings. You also use the value <code>i</code> as an index, but with the <code>range</code> keyword you can access the currently indexed value, see <a href=\"https://tour.golang.org/moretypes/16\" rel=\"noreferrer\">here</a>.</p>\n\n<p>You should check the return of <code>fmt.Scan()</code>.</p>\n\n<p>Rather than starting the timer within <code>askQuestions()</code>, I opted to move it to <code>main()</code>. This means we can remove the <code>time</code> argument.</p>\n\n<h2><code>main()</code></h2>\n\n<p>Naming variables like <code>fPtr</code> and <code>sPtr</code> is just extra typing. Documenting the type in the name itself is not very useful.</p>\n\n<ul>\n<li><code>fPtr</code> becomes <code>name</code></li>\n<li><code>tPtr</code> becomes <code>time</code></li>\n<li><code>sPtr</code> becomes <code>shuffle</code></li>\n</ul>\n\n<p><strong>From your updated code with shuffling:</strong></p>\n\n<p>Rather than keeping a second copy of the shuffled questions, just modify the array in-place. You also don't need to seed <code>rand</code> (see <a href=\"https://tip.golang.org/pkg/math/rand/#Shuffle\" rel=\"noreferrer\">this example</a> from the Go docs).</p>\n\n<h2>Conclusion</h2>\n\n<p>Here is the code I ended up with:</p>\n\n<pre><code>package main\n\nimport (\n \"encoding/csv\"\n \"flag\"\n \"fmt\"\n \"log\"\n \"math/rand\"\n \"os\"\n \"time\"\n)\n\nvar points int\n\nfunc main() {\n name := flag.String(\"csv\", \"problems.csv\",\n \"filename in csv (question, answer)\")\n time := flag.Int(\"time\", 10, \"time in seconds\")\n shuffle := flag.Bool(\"shuffle\", true, \"shuffle your question order\")\n\n flag.Parse()\n\n questions, err := readCSV(*name)\n\n if err != nil {\n log.Fatal(err)\n }\n\n if *shuffle {\n rand.Shuffle(len(questions), func(i, j int) {\n questions[i], questions[j] = questions[j], questions[i]\n })\n }\n\n go startTimer(*time)\n\n if err := askQuestions(&questions); err != nil {\n log.Fatal(err)\n }\n\n fmt.Printf(\"You got %d points\\n\", points)\n}\n\nfunc readCSV(name string) ([][]string, error) {\n f, err := os.Open(name)\n\n if err != nil {\n return nil, err\n }\n\n qs, err := csv.NewReader(f).ReadAll()\n\n if err != nil {\n return nil, err\n }\n\n return qs, f.Close()\n}\n\nfunc askQuestions(questions *[][]string) error {\n for i, q := range *questions {\n fmt.Printf(\"Question %d: %s\\n\", i+1, q[0])\n\n var a string\n _, err := fmt.Scan(&a)\n\n if err != nil {\n return err\n }\n\n if a == q[1] {\n points++\n }\n }\n\n return nil\n}\n\nfunc startTimer(sec int) {\n timer := time.NewTimer(time.Duration(sec) * time.Second)\n <-timer.C\n fmt.Printf(\"\\nTime is up! You got %d points\\n\", points)\n os.Exit(0)\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:29:45.503",
"Id": "418474",
"Score": "0",
"body": "Added some notes about your updated shuffling code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:58:42.660",
"Id": "418476",
"Score": "0",
"body": "Thanks for your help, will make the changes. for the range loop in `askQuestions` I chose `i` not to make a copy, wouldn't it be faster? Also do you know any go exercise to practice with go concurrency routines channels?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T19:01:53.743",
"Id": "418477",
"Score": "1",
"body": "@lucarlig The performance difference will be negligible, so I would prefer the most readable code. One resource is the Go [tour of concurrency](https://tour.golang.org/concurrency/1). You can read and page through with live code examples."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:05:57.780",
"Id": "216279",
"ParentId": "216270",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216279",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:48:32.750",
"Id": "216270",
"Score": "7",
"Tags": [
"beginner",
"go",
"concurrency",
"timer",
"quiz"
],
"Title": "Quiz game with timer"
} | 216270 |
<p>I started learning Java not long ago. Quite often, assignments require me to print output in a table. I had some spare time last week, and I wrote a separate class for printing tables. It is working as intended, but I'm not confident the code is "clean". I would like to hear some opinions on what I should improve.</p>
<pre><code>import java.util.List;
import java.util.ArrayList;
/**
* This class is used to print adjustable table. Table will generate vertical collumns in number
* corresponding to the number of of objects in headers list which is first parameter taken by constructor.
* Second parameter is list of lists containing String formated fields user needs printed in a table.
* The table will adjust fields width to be the length of longest String passed to the constructor.
* All fields will be centered. Last parameter of constructor of boolean type determines wether
* user wants to add indexing in first collumn of the table. In such case length of each sublist of
* content passed to the constructor should be one field shorter than headers list. Otherwise both
* lengths should be extacly the same. None of the lists can be empty.
*/
class TablePrinter {
private List < String > headers;
private List < List < String >> content;
private boolean wantIndex;
public TablePrinter(List < String > headers, List < List < String >> content, boolean wantIndex) {
this.headers = headers;
this.content = content;
this.wantIndex = wantIndex;
}
public void printTable() {
checkIfNoProblems();
List < String > table = new ArrayList < > ();
List < List < String >> input = processData();
List < Integer > collumnsWidth = getCollumnsWidth();
String fieldSeparator = "│";
String tableRowSeparator = generateTopMiddleOrBottomLine(collumnsWidth, "rowSeparator");
table.add(generateTopMiddleOrBottomLine(collumnsWidth, "top"));
for (List < String > list: input) {
table.add(fieldSeparator);
for (int index = 0; index < list.size(); index++) {
table.add(centerField(list.get(index), collumnsWidth.get(index)));
table.add(fieldSeparator);
}
table.add(tableRowSeparator);
}
table.set(table.size() - 1, generateTopMiddleOrBottomLine(collumnsWidth, "bottom"));
System.out.println(String.join("", table));
}
private List < Integer > getCollumnsWidth() {
List < Integer > collumnsWidth = new ArrayList < > ();
for (String string: headers) {
collumnsWidth.add(string.length());
}
for (List < String > list: content) {
for (int index = 0; index < list.size(); index++) {
if (collumnsWidth.get(index) < list.get(index).length()) {
collumnsWidth.set(index, list.get(index).length());
}
}
}
return collumnsWidth;
}
private String generateTopMiddleOrBottomLine(List < Integer > collumnsWidth, String modifier) {
List < String > output = new ArrayList < > ();
String start;
String middle;
String end;
switch (modifier) {
case "top":
default:
start = "\n╭";
middle = "┬";
end = "╮\n";
break;
case "rowSeparator":
start = "\n├";
middle = "┼";
end = "┤\n";
break;
case "bottom":
start = "\n╰";
middle = "┴";
end = "╯\n";
break;
}
output.add(start);
for (int number: collumnsWidth) {
int repetitions = number;
while (repetitions > 0) {
output.add("─");
repetitions--;
}
output.add(middle);
}
output.set(output.size() - 1, end);
return String.join("", output);
}
private String centerField(String field, int collumnWidth) {
List < String > centeredField = new ArrayList < > ();
boolean flip = true;
int repetitions = collumnWidth - field.length();
int shift = 1;
centeredField.add(field);
while (repetitions > 0) {
if (flip == true) {
centeredField.add(centeredField.size() - shift, " ");
} else {
centeredField.add(" ");
}
flip = !flip;
shift++;
repetitions--;
}
return String.join("", centeredField);
}
private List < List < String >> injectIndex() {
if (wantIndex) {
List < List < String >> indexedContent = content;
Integer index = 1;
for (List < String > list: indexedContent) {
list.add(0, index.toString());
index++;
}
return indexedContent;
}
return content;
}
private List < List < String >> processData() {
List < List < String >> input = injectIndex();
input.add(0, headers);
return input;
}
private boolean areListsLengthsValid() {
int listsLength = headers.size();
if (wantIndex) {
listsLength--;
}
for (List < String > list: content) {
if (list.size() != listsLength) {
return false;
}
}
return true;
}
private boolean checkIfListsArentEmpty() {
List < List < String >> headersAndContent = new ArrayList < > ();
headersAndContent.add(headers);
for (List < String > list: content) {
headersAndContent.add(list);
}
for (List < String > list: headersAndContent) {
try {
String string = list.get(0);
} catch (IndexOutOfBoundsException e) {
return false;
}
}
return true;
}
private void checkIfNoProblems() {
if (checkIfListsArentEmpty() == false) {
System.out.println("Error, some of lists passed to printer are empty");
System.exit(0);
} else if (areListsLengthsValid() == false) {
System.out.println("Lists lengths are invalid. Amount of items in each sublist of content\nYou wish to print must be the same as amount of items in headers with\nthe exception of situation where you want program to add index. In this\ncase headers should contain 1 more item than each sublist of content to print");
System.exit(0);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:33:00.437",
"Id": "418525",
"Score": "2",
"body": "Your prolific use of whitespace in parameterized types (such as \"List < List < String >>\") is not customary to Java. Use the formatting found in the Java API documentation (e.g. \"List<List<String>>\")"
}
] | [
{
"body": "<p>Because you asked only about whether this is \"clean java\" I won't comment on the flaws of this implementation algorithm-wise.</p>\n\n<hr>\n\n<p>Conventionally methods that check if something is true are named as follows:</p>\n\n<pre><code>boolean isEmpty() // when referring to the object itself\nboolean somethingIsEmpty() // when referring to something within the object\n</code></pre>\n\n<p>It would be more convenient if you renamed methods like <code>checkIfListsArentEmpty()</code> to this format, making it <code>listsAreEmpty()</code> (returning true when they are empty, not the opposite). This would make the code nicer and more readable without double negatives:</p>\n\n<pre><code>if (listsAreEmpty())\n</code></pre>\n\n<p>As opposed to what you have (checking if the lists are not not empty)</p>\n\n<hr>\n\n<pre><code>private String generateTopMiddleOrBottomLine(List < Integer > collumnsWidth, String modifier) {...}\n</code></pre>\n\n<p>You should add documentation for this method to make it clear what values are accepted for <code>modifier</code>. In similar cases with a wider variety of accepted values it'd be even better to use an enum. And again, you use unnecessarily long names.</p>\n\n<hr>\n\n<p>Using <code>System.exit(0)</code> when this class gets an invalid input is bad design. It might be fine for your current purposes, but the proper way to implement it is to throw an exception that can be handled by a try-catch block instead of forcing the program to shut down immediately.</p>\n\n<hr>\n\n<pre><code>private List < Integer > getCollumnsWidth() {...}\n</code></pre>\n\n<p>In such cases it's better to use an array instead of a List of boxed types, since you already know the number of elements to be returned and don't actually need a list of mutable length. It is also better for performance.</p>\n\n<hr>\n\n<p>You pass around the list of column widths from method to method instead of making it a private field that every method can access. The value can be assigned once during the construction of the object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:50:33.743",
"Id": "216302",
"ParentId": "216274",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:20:43.790",
"Id": "216274",
"Score": "1",
"Tags": [
"java"
],
"Title": "Improving my Java class that prints tabular output"
} | 216274 |
<p>I just recently started using AWK and I'm still learning about it. I have solved the problem I'm about to show but I feel it's not the best solution and I'm trying to find a solution to fit within an AWK command rather than keep piping.</p>
<p>I have a bunch of .txt files ending for which I read the header (1st line only).</p>
<pre><code>head -1 *.txt
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>==> anglia.txt <==
String - Anglian
==> carr.txt <==
String - Carr
etc..
</code></pre>
<p>From here I have a case switch where a user inputs 1-9. It's sorted so first line is always Anglian and second is always Carr.. etc
So if a user inputs 1 I know they want to select anglian. But for further process my code I need to extract the String "Anglian".</p>
<pre><code>head -1 *.txt | awk '/[a-z]/&&!/.txt/'
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>String - Anglian
String - Carr
</code></pre>
<p>Here I got rid of the first line that had the filename.</p>
<pre><code>head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk '{print $3}'
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>Anglian
Carr
</code></pre>
<p>Here I selected column 3 which contains the String that I need!</p>
<pre><code>head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk 'NR==1{print $3}'
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>Anglian
</code></pre>
<p>Here I selected the first row which is exactly the output that I want! However I had to use an extra pipe. All I want is a awk command that does all of this in a single command somethings around the lines of:</p>
<pre><code>head -1 *.txt | awk '/[a-z]/&&/.txt/{if(NR==1)print $3}'
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>EMPTY LINE
</code></pre>
<p>This is the problem I'm having. Since I'm having the pattern and NR in 1 command it's selecting the 1st line but the first line is a line that is being hidden by my pattern and it's the <code>==> anglian.txt <==</code> hence</p>
<pre><code>head -1 *.txt | awk '/[a-z]/&&/.txt/{if(NR==2)print $3}'
</code></pre>
<p>Outputs:</p>
<pre class="lang-none prettyprint-override"><code>Anglian
</code></pre>
<p>However this is of no use because only matches Anglian where it is NR==2 and due to my case switch that I have I want it to be NR==1 otherwise the code does not work.</p>
<p>Is this possible? I hope I made myself clear here :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:30:28.543",
"Id": "418466",
"Score": "1",
"body": "I'd like you help you, but you need more information about the files. I think that $3 on line1 is \"Anglican\" or one of the other keys. And that word maps to a line number, and then you want to print $3 from that line number. Is that right? Please demonstrate by including a couple of your files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:55:52.877",
"Id": "418506",
"Score": "0",
"body": "(Welcome to Code Review!) `I just recently started using AWK and I'm still learning about it` ***Why?*** It was quite something when it was new. Then, there was *new awk*, but the world keeps turning: contemporary contenders include Perl (5+), Python (3.3+, 2.7.1 for Jython), Ruby…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:03:53.630",
"Id": "418508",
"Score": "0",
"body": "Please include an example of the output of `head -1 *.txt`. Without that, I can't imagine why `$3` would be printed, and I have a hard time trying to imagine [the code presented works as intended](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:22:07.267",
"Id": "418549",
"Score": "0",
"body": "@greybeard I work for a company that provides the billing system to BT in the UK and we do a lot of data mediation; awk seems to be used quite often for data formatting... So i'm trying to learn it to try and understand some of the scripts we have implemented, etc although some are quite old."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:11:03.647",
"Id": "418563",
"Score": "0",
"body": "So you look at the first line of a file to get a keyword. You use that keyword to get a line number. What file is that line number used for? The same file? Show your input files (or a short representation of them) and your desired output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:12:42.077",
"Id": "418564",
"Score": "0",
"body": "@greybeard awk is a very capable and fast language for processing data. It doesn't matter if it's not the shiniest tool in the box"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:41:17.687",
"Id": "418567",
"Score": "0",
"body": "Stop trying to *describe* the problem and just show the input. In your question where it can be properly formatted, not in comments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:49:31.887",
"Id": "418573",
"Score": "0",
"body": "@glennjackman Hey, I edited the question, I hope it's more clearer now! Thanks"
}
] | [
{
"body": "<p>You can replace this pipeline</p>\n\n<pre><code>head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk '{print $3}'\n</code></pre>\n\n<p>with this one awk command</p>\n\n<pre><code>awk 'FNR == 1 {print $3}' *.txt\n</code></pre>\n\n<p><code>FNR</code> is the <strong>file</strong> record (i.e. line) number. <code>NR</code> is the <em>cumulative</em> record number of all records seen from all files.</p>\n\n<hr>\n\n<p>Now, you can select the user's numeric choice with</p>\n\n<pre><code>awk 'FNR == 1 {print $3}' *.txt | awk -v n=\"$user_selection\" 'NR == n'\n</code></pre>\n\n<p>or, with a single awk:</p>\n\n<pre><code>awk -v n=\"$user_selection\" 'FNR == 1 && ++filenum == n {print $3; exit}' *.txt\n</code></pre>\n\n<hr>\n\n<p>If you're looking for a way to get your users to select a name from one of the files, perhaps some more advanced bash:</p>\n\n<pre><code># read the 3rd word from the 1st line of all txt files into an array\nreadarray -t names < <(awk 'FNR == 1 {print $3}' *.txt)\n\n# get the user to select one of them\nPS3=\"Choose a name: \"\nselect name in \"${names[@]}\"; do\n [ \"$name\" ] && break\ndone\n\necho \"$name\"\n</code></pre>\n\n<hr>\n\n<p>This really isn't a code review. Since you're asking \"how can I do this\", you should have asked on Stack Overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T16:31:43.330",
"Id": "418587",
"Score": "0",
"body": "```awk -v n=\"$user_selection\" 'FNR == 1 && ++filenum == n {print $3; exit}' *.txt``` worked wonders :) many thanks. Also I was in stack overflow but since I had a \"solution\" to the problem they told me to come here. Many thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T18:34:16.917",
"Id": "216282",
"ParentId": "216275",
"Score": "0"
}
},
{
"body": "<p>I'm afraid you can't do this like that, because <code>NR</code> is a number of an input record, not a number of records matched so far. Even if it was, you need to count records matched by the first clause of the condition but actually <em>not</em> yet printed due to the second clause.</p>\n\n<p>Probably the good way to do that is explicit counting:</p>\n\n<pre><code>BEGIN { cnt = N }\n/[a-z]/&&!/.txt/ { if (cnt-- == 0) print $3 }\n</code></pre>\n\n<p>I am not sure, however, how to pass an argument from the command line to the script's variable <code>N</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:19:18.563",
"Id": "418483",
"Score": "0",
"body": "If you do this inline instead of it's own awk script file I think you can just use Bash's variable expansion (but be sure to escape the dollar sign later in the code). Or just hard code it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:09:35.150",
"Id": "216287",
"ParentId": "216275",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "216282",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T17:14:35.040",
"Id": "216275",
"Score": "0",
"Tags": [
"regex",
"awk"
],
"Title": "Select a specific line after matching a pattern"
} | 216275 |
<p>link to original question: <a href="https://codereview.stackexchange.com/questions/216201/simple-media-ingest-script/216245?noredirect=1#comment418430_216245">Simple media ingest script</a></p>
<p>As per answers I have refactored my code and would like to get feedback on the current structure. </p>
<p>The purpose of this tool is to allow someone to copy media from cards (SD cards, CFast, etc) using rsync and to also allow someone to complete incomplete transfer that they have initiated. </p>
<p>I've chosen to use prompts because it's more user friendly for the environment the script will be used in. The intended users are not command line tool friendly. </p>
<p>I'm not very familiar with bash and am quite out of practice with code in general so I would like to check behind myself. I received excellent feedback in the previous post and have addressed several of the points raised. </p>
<pre><code>#!/usr/local/bin/bash
set -e
set -u
# prompt user for input
prompt_user(){
while [[ -z "${!2:-}" ]]
do
read -r -p "$1" "$2"
done
}
# prompt user for additional rsync options
add_rsync_options(){
while true;
do
read -r -p "Add rsync options? [y/n] " add_options
case $add_options in
[Yy]* )
read -r -p $'Enter additional rsync options:\n' rsync_options
break;;
[Nn]* )
break;;
*) echo "Please enter y or no!"
esac
done
}
# make target directory for transfer
make_directory(){
echo $'Follow the prompt to create a project directory.\n'
prompt_user $'Path of target directory?\n' target_directory
prompt_user $'Brand Prefix?\n' brand_prefix
prompt_user $'Project Name?\n' project_name
prompt_user $'Media Type?\n' media_type
prompt_user $'Location?\n' location
prompt_user $'Employee?\n' employee
destination_path=${target_directory}/$(date +'%Y%m%d')_${brand_prefix}_${project_name}_${media_type}_${location}_${employee}
echo "Creating directory: ${destination_path}"
mkdir -p "${destination_path}" "${destination_path}/logs"
}
# run rsync command
run_rsync(){
echo $'Follow the prompt to complete the rsync command.\n'
prompt_user $'Path to source media?\n' source_path
# if partial ingest indicate pre-existing target directory
if [[ "$option" == "2" ]]; then
prompt_user $'Target directory?\n' target_directory
destination_path=$target_directory
fi
add_rsync_options
echo $'Running rsync command:\n'
rsync -r --info=progress2 --log-file="${destination_path}/logs/$(date +'%Y%m%d')_transfer_log.txt" ${rsync_options:-} "${source_path}/" "${destination_path}"
}
# clear terminal for readability
clear
# start
while true
do
# read user input and run appropriate functions
read -r -p $'Enter [1] to start an ingest or [2] to complete a partial ingest.\n' option
case $option in
1 )
make_directory
run_rsync
break;;
2 )
run_rsync
break;;
* )
echo $'Please enter a valid option!\n';;
esac
done
</code></pre>
<p>Error handling is at a minimum still I believe and I'm not too sure what would even be relevant to handle past what's implemented. I'm not very experienced in that regard so resources are appreciated! </p>
<p>Thanks!</p>
| [] | [
{
"body": "<h3>What is <code>$option</code> in <code>run_rsync</code>?</h3>\n\n<p><code>option</code> is read in the global scope to decide if user wants a full ingest or continue a partial ingest. In that loop that reads the prompt, the meaning of <code>option</code> is understandable.</p>\n\n<p>Referring to <code>$option</code> in <code>run_rsync</code> is just too far away. It's not clear anymore where it comes from and what it means. It would be better if the prompt loop passed the decision to <code>run_rsync</code> as a parameter, to make it perfectly clear. For example:</p>\n\n<pre><code>while true\ndo\n read -r -p $'Enter [1] to start an ingest or [2] to complete a partial ingest.\\n' option\n case $option in\n 1 )\n make_directory\n run_rsync full\n break;;\n 2 )\n run_rsync partial\n break;;\n * )\n echo $'Please enter a valid option!\\n';;\n esac\ndone\n</code></pre>\n\n<p>And then in <code>run_rsync</code>:</p>\n\n<pre><code>run_rsync() {\n local ingestType=$1\n\n echo $'Follow the prompt to complete the rsync command.\\n'\n\n prompt_user $'Path to source media?\\n' source_path\n\n if [[ \"$ingestType\" = \"partial\" ]]; then\n prompt_user $'Target directory?\\n' target_directory\n destination_path=$target_directory\n fi\n\n # ...\n</code></pre>\n\n<h3>Inconsistent terminology</h3>\n\n<p>In <code>make_directory</code>, the term \"target directory\" refers to the base directory in which a timestamped sub-directory will be created, with brand name, project name, and so on, also in the name.</p>\n\n<p>In <code>run_rsync</code>, in case of partial ingest the user is prompted for \"target directory\", but here it will mean the full destination path. If would be better to name it as such.</p>\n\n<h3>Inconsistent formatting</h3>\n\n<p>The code uses inconsistent indentation.\nFor example the content of <code>prompt_user</code> is over-indented, compared to other functions.\nThe body of the <code>while</code> loop in the global scope is over-indented,\nand also haphazardly indented.\nIt would be easier to read if indenting was consistent throughout.</p>\n\n<h3>Unnecessary comments</h3>\n\n<p>Most comments in the program state the obvious.\nThey are just noise,\nand it would be better to remove them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T13:20:46.913",
"Id": "418683",
"Score": "0",
"body": "Excellent points! Thanks for the detailed response. \n\nPassing the ingest type to the function makes a lot of sense and did not occur to me at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:40:37.740",
"Id": "216376",
"ParentId": "216286",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:02:59.843",
"Id": "216286",
"Score": "1",
"Tags": [
"bash"
],
"Title": "Revised media ingest script"
} | 216286 |
<p>The following code copy a complete folder (that has 3 folders inside), then check if errors are generated and send email if there's errors, the it proceeds to create 3 different tar files and finally move this tar files to a mounted network drive, every name has been changed or somehow altered in order to comply with my company security policy.</p>
<pre><code>#! /usr/bin/env bash
readonly SUBJECT="BACKUP"
readonly TO="mail@domain.com"
readonly MESSAGE="~/backupMessageError.txt"
readonly TOALL="mail1@domain.com, mail2@domain.com"
readonly MESSAGEALL="~/backupMessageSuccess.txt"
backup () {
if grep -qs '/mount/dir/' /proc/mounts; then
rsync --exclude /a/folder/ -ravz /backup/source /backup/destination/ 2> ~/backupMessageError.txt
if checker $1; then
mail
else
compression
fi
else
mount -o hard,nolock IP:/volume1/folder /mount/dir/ 2> ~/backupMessageError.txt
if checker $1; then
mail
else
rsync --exclude /a/folder/ -ravz /backup/source/ /backup/destination/ 2>> ~/backupMessageError.txt
if checker $1; then
mail
else
compression
fi
fi
fi
}
compression (){
tar -I pigz -cf backupFolder1.tar.gz folder1 2>> ~/backupMessageError.txt
tar -I pigz -cf backupFolder2.tar.gz folder2 2>> ~/backupMessageError.txt
tar -I pigz -cf backupFolder3.tar.gz folder3 2>> ~/backupMessageError.txt
if checker $1; then
mail
else
storage
fi
}
storage (){
mv /a/folder/backupFolder1.tar.gz /mount/dir/ 2>> ~/backupMessageError.txt
mv /a/folder/backupFolder2.tar.gz /mount/dir/ 2>> ~/backupMessageError.txt
mv /a/folder/backupFolder3.tar.gz /mount/dir/ 2>> ~/backupMessageError.txt
if checker $1; then
mail
fi
}
checker (){
if [ "$(wc -l < ~/backupMessageError.txt)" -ge 1 ];then
return 0;
else
return 1;
fi
}
mail () {
if checker $1;then
mail -s "$SUBJECT" "$TO" < $MESSAGE
else
mail -s "$SUBJECT" "$TOALL" < $MESSAGEALL
fi
}
backup
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:24:37.560",
"Id": "418484",
"Score": "2",
"body": "Welcome to CR. Are the folder names completely different in the uncensored version or is it like folder1, folder2, .. (A repeatable pattern)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:29:21.217",
"Id": "418485",
"Score": "2",
"body": "Folders have completely different names. Thank you for welcoming me :)"
}
] | [
{
"body": "<h3>What is <code>$1</code> ?</h3>\n\n<p>All the functions except <code>checker</code> include a call <code>checker $1</code>.\nBut none of those functions are called with a parameter,\nso <code>$1</code> is never actually defined.\nThe only function that is called with a parameter is <code>checker</code>,\nbut it doesn't actually use a parameter.</p>\n\n<p>As such, you could remove all the <code>$1</code> without changing the behavior of the program.</p>\n\n<p>More importantly, when you want to use <code>$1</code> for something,\nit's good to assign it to a variable with a descriptive name.\nThat way the reader can understand the purpose.\nIn the current program it's hard to tell if <code>$1</code> is simple negligence and oversight,\nor a bug waiting to explode.\nIf it had a descriptive name, I could make a more educated guess.</p>\n\n<h3>Always quote variables used in command parameters</h3>\n\n<p>Instead of <code>checker $1</code> always write <code>checker \"$1\"</code>.</p>\n\n<h3>Checking if a file is empty</h3>\n\n<p><code>checker</code> checks if a file is empty by counting lines.\nA simpler way exists using the <code>[ -s ... ]</code> builtin:</p>\n\n<pre><code>checker() {\n [ -s ~/backupMessageError.txt ]\n}\n</code></pre>\n\n<p>Notice that there's no need to write <code>if [ -s ... ]; then return 0; else return 1; fi</code>,\nsince the exit code of a function is the exit code of the last command,\nso we can simply use the command without the <code>if-else</code>.</p>\n\n<h3>Use better names</h3>\n\n<p>The current function names don't help understand what the program is doing.\nIn fact they are all <em>nouns</em>, when the natural choice would be <em>verbs</em>, or <em>questions</em>.\nFor example <code>checker</code> checks if there were any errors.\nA more natural naming would be <code>seenAnyErrors</code>.\nNotice how the code could read like prose:</p>\n\n<pre><code>if seenAnyErrors; then\n sendErrorReport\nelse\n createBackups\nfi\n</code></pre>\n\n<h3>Improve error handling</h3>\n\n<p>The current error handling is not so good. Let's take a closer look at for example:</p>\n\n<blockquote>\n<pre><code>tar -I pigz -cf backupFolder1.tar.gz folder1 2>> ~/backupMessageError.txt\ntar -I pigz -cf backupFolder2.tar.gz folder2 2>> ~/backupMessageError.txt\ntar -I pigz -cf backupFolder3.tar.gz folder3 2>> ~/backupMessageError.txt\n\nif seenAnyErrors; then ...; fi\n</code></pre>\n</blockquote>\n\n<p>What if the first <code>tar</code> command fails?\nIs your intention to continue with the others anyway?</p>\n\n<p>The current way of checking for errors expects that a failing command writes something to <code>stderr</code>. That's not necessarily the case always, therefore it would be fragile to rely on that. A more reliable way is using the exit code.</p>\n\n<p>A better way to write the above, relying on exit code, would be:</p>\n\n<pre><code>failures=0\n\ntar -I pigz -cf backupFolder1.tar.gz folder1 2>> \"$errors\"\n((failures += $?))\n\ntar -I pigz -cf backupFolder2.tar.gz folder2 2>> \"$errors\"\n((failures += $?))\n\ntar -I pigz -cf backupFolder3.tar.gz folder3 2>> \"$errors\"\n((failures += $?))\n\nif [ \"$failures\" != 0 ]; then ...; fi\n</code></pre>\n\n<h3>Don't double-quote <code>~</code></h3>\n\n<p>I believe this is an error:</p>\n\n<blockquote>\n<pre><code>readonly MESSAGE=\"~/backupMessageError.txt\"\n</code></pre>\n</blockquote>\n\n<p>When <code>~</code> is double-quoted, the shell won't expand it to <code>$HOME</code>.\nAs it is, I think the command <code>mail -s \"$SUBJECT\" \"$TO\" < $MESSAGE</code> will fail with \"No such file or directory\" error. That variable definition should have been written as:</p>\n\n<pre><code>readonly MESSAGE=~/backupMessageError.txt\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:08:57.587",
"Id": "216372",
"ParentId": "216288",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216372",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:19:35.930",
"Id": "216288",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Local backup bash"
} | 216288 |
<p>I am new to python3 and tried to solve the task in a very basic way. Please critique my code. I appriciate any suggestions for improvement.</p>
<p>Here is the question:</p>
<blockquote>
<p>The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832.</p>
<p>73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450</p>
<p><strong>Find the thirteen adjacent digits in the 1000-digit number that have
the greatest product. What is the value of this product?</strong></p>
</blockquote>
<p>My Code:</p>
<pre><code>s = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
listem = []
listem2 = []
highest = 1
pp = 13
sonuc = 1
for i in range(1001 - pp + 1):
listem.append(s[i: i+pp])
for digit in listem[i]:
listem2.append(digit)
listem2 = [int(k) for k in listem2]
for q in listem2:
sonuc *= q
if highest < sonuc:
highest = sonuc
sonuc = 1
listem2 = []
print(highest)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:52:16.713",
"Id": "418553",
"Score": "1",
"body": "I'd probably take `highest` to be 0 or -1; in case the dataset contains too many zeros."
}
] | [
{
"body": "<p>Essentially your algorithm</p>\n\n<ul>\n<li><p>partitions a string of integers into integer-sublists of a fixed size</p></li>\n<li><p>iterates over each sublist of integers</p></li>\n<li><p>computes the product for each sublist</p></li>\n<li><p>then updates the maximum-possible-product if the most recent product is larger</p></li>\n</ul>\n\n<p>That's a perfectly logical way to solve the problem. </p>\n\n<p>But there are some algorithmic gains to be had (which I won't code up for you, because you'll gain more from writing it up yourself).</p>\n\n<p>In essence, each time I take the product of 5 integers, I have to do 4 multiplications. So if I wanted to compute the product of the first, and the second, 5 integers in the string <code>624919...</code>, that is, the product of (6,2,4,9,1) and (2,4,9,1,9), is there a more efficient way to do it than to compute the products independently?</p>\n\n<p>It turns out there is. First I compute the product (2,4,9,1), then to get the first answer I multiply this by 6, and to get the second I multiply it by 1. Doing the products independently requires 8 multiplications; doing the products with info about the overlaps requires 5 multiplications.</p>\n\n<p>Think about how you could use a \"sliding window\" approach to more efficiently calculate the 13-mer products. Be careful of the zeros.</p>\n\n<p>From a code-review point of view:</p>\n\n<ul>\n<li><p>1) Separate parsing the input data from processing that data</p>\n\n<ul>\n<li><code>int_string = '12345....'</code></li>\n<li><code>int_list = [int(x) for x in int_string]</code></li>\n</ul></li>\n<li><p>2) Wrap your algorithm in a function (list[int], int) -> int; and call it</p>\n\n<ul>\n<li><code>def largest_p_product(ints, p): ... <copy in your code> ...</code></li>\n<li><code>result = largest_p_product(int_list, 13)</code></li>\n<li><code>print(result)</code></li>\n</ul></li>\n<li><p>3) Consider what might happen with inappropriate data</p>\n\n<ul>\n<li>what if the list[int] is shorter than <code>pp</code></li>\n<li>what if the input string contains non-digit characters?</li>\n<li>what if the list[int] is all zero?</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T22:08:45.287",
"Id": "423803",
"Score": "0",
"body": "I appriciate all your suggestions,,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:24:22.060",
"Id": "216321",
"ParentId": "216289",
"Score": "2"
}
},
{
"body": "<p>The easiest (but not computationally most efficient) way to solve this challenge is to use a brute-force algorithm, like you did. However you can write it a lot more succinctly when using more of the tools available in the Python standard library.</p>\n\n<ul>\n<li><p>Use a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator expression</a> to get all slices:</p>\n\n<pre><code>s = \"...\"\nn = 13\nslices = (s[i:i+n] for i in range(len(s) - n))\nnext(slices)\n# '7316717653133'\n</code></pre></li>\n<li><p><a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a> this string to an iterable of integers:</p>\n\n<pre><code>slices = (s[i:i+n] for i in range(len(s) - n))\nlist(map(int, next(slices)))\n# [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3]\n</code></pre></li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>functools.reduce</code></a> and <a href=\"https://docs.python.org/3/library/operator.html#operator.mul\" rel=\"nofollow noreferrer\"><code>operator.mul</code></a> to get the product of this iterable:</p>\n\n<pre><code>from functools import reduce\nfrom operator import mul\n\nslices = (s[i:i+n] for i in range(len(s) - n))\nreduce(mul, map(int, next(slices)))\n# 5000940\n</code></pre></li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"nofollow noreferrer\"><code>max</code></a> to...get the maximum of those:</p>\n\n<pre><code>slices = (s[i:i+n] for i in range(len(s) - n))\nmax(reduce(mul, map(int, slice)) for slice in slices)\n</code></pre></li>\n<li><p>Finally, wrap the code in functions and the calling code in a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>:</p>\n\n<pre><code>from functools import reduce\nfrom operator import mul\n\ndef prod(x):\n return reduce(mul, x)\n\ndef maximum_product(s, n):\n return max(prod(map(int, s[i:i+n])) for i in range(len(s) - n))\n\nif __name__ == \"__main__\":\n s = \"...\"\n n = 13\n print(max_product(s, n))\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T22:08:00.757",
"Id": "423802",
"Score": "0",
"body": "I appriciate all your suggestions,,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T11:28:14.833",
"Id": "216326",
"ParentId": "216289",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:27:39.540",
"Id": "216289",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler Problem 8 - Largest product in a series"
} | 216289 |
<p>Please review my code for parking lot design.
I am new to OOD concepts, It will be great to have some feedback on OO Structure of the solution.</p>
<p>Requirements considered:</p>
<ol>
<li>The parking lot can have multiple levels.</li>
<li>Each level can have 'compact', 'large', 'bike' and 'electric' spots.</li>
<li>Vehicle should be charged according to spot type, time of parking and duration of parking.</li>
<li>Should be able to add more spots to level.</li>
<li>Show the available number of spots on each level.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>class parkingFloor():
def __init__(self,name):
self.name = name
self.spotTotal = {'compact':0,'large':0,'bike':0,'electric':0}
self.spotTaken = {'compact':0,'large':0,'bike':0,'electric':0}
self.freeSpot = {'compact':set(),'large':set(),'bike':set(),'electric':set()}
self.takenSpot = {'compact':{},'large':{},'bike':{},'electric':{}}
def assignSpot(self,tickt):
if self.spotTaken[tickt.veh.type] >= self.spotTotal[tickt.veh.type]:
return False
for s in self.freeSpot[tickt.veh.type]:
if s.id not in self.takenSpot[tickt.veh.type]:
self.takenSpot[tickt.veh.type][s.id] = tickt
self.spotTaken[tickt.veh.type]+=1
self.freeSpot[tickt.veh.type].remove(s)
tickt.allocateSpot(s)
return True
return False
def addSpot(self,type,v):
for i in range(v):
s = spot(type)
self.freeSpot[type].add(s)
self.spotTotal[type] += v
class entryPanel():
def __init__(self,id):
self.id = id
def printTicket(self,tickt):
print('Vehicle ID ',tickt.veh.id)
print('Spot ID ',tickt.spot.id)
print('Ticket ID ',tickt.id)
print('Date Time',tickt.DateTime)
def display(self,message):
print(message)
class vehicle():
def __init__(self,id,vehType):
self.id = id
self.type = vehType
class spot():
def __init__(self,spotType):
def generateId():
# some mechanism to generate spot id
return 1
self.id = generateId()
self.type = spotType
class ticket():
def __init__(self,v1):
self.id = self.generateId()
self.veh = v1
self.spot = None
self.DateTime = self.getTime()
self.amount = 0
self.status = 'Active'
self.payment = None
def getTime(self):
time = 1234
return time
def generateId(self):
# some mechanism to generate new ticket id
new_ticket = 1
return new_ticket
def allocateSpot(self,spot):
self.spot = spot
def addPayment(self,pay):
self.status = 'Complete'
self.payment = pay
class parkingLot():
def __init__(self,name,address):
self.name = name
self.address = address
self.level = []
def addLevel(self,floor):
self.level.append(floor)
def processEntry(self,t1,gate):
for l in self.level:
if l.assignSpot(t1):
gate.printTicket(t1)
return
gate.display('No Spot Empty')
def processExit(self,tickt,gate):
def getTime():
# Gives the current time
return 3
currTime = getTime()
print('Processing fare',tickt.veh.type,tickt.spot.id,tickt.DateTime,currTime)
amountCalculated = 7
tickt.addPayment(Payment(amountCalculated))
gate.display('Payment Successful')
class Payment():
def __init__(self,amount):
self.id = 'paymentid2'
self.type = 'credit' # debit
self.time = 'paymet time'
class displayBoard():
def show(self,p):
for l in p.level:
print(l.name)
for k in l.spotTotal.keys():
print(k, l.spotTotal[k] - l.spotTaken[k])
P = parkingLot('Savita','Address')
floor1 = parkingFloor('floor1')
P.addLevel(floor1)
floor1.addSpot('compact',5)
board = displayBoard()
board.show(P)
entryPanel1 = entryPanel('1')
v1 = vehicle(1,'compact')
t1 = ticket(v1)
P.processEntry(t1,entryPanel1)
P.processExit(t1,entryPanel1)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:53:33.647",
"Id": "418490",
"Score": "1",
"body": "Welcome to Code Review! You've posted a lot of code to review. Consider giving the reviewers a hint where the focus of the review should be (e.g. style, clarity, OO structure, ...). Also elaborate on what the expected outcome of the provided test code should be."
}
] | [
{
"body": "<p>Overall, this is actually very good, especially considering you're new to the OOP design pattern. There're just a few things I would recommend changing:</p>\n\n<h1>Naming conventions</h1>\n\n<p>There's <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">a list of naming conventions</a> that are widely accepted all throughout the python community. Following these conventions makes it easier to share and develop your code with other developers because everyone's already familiar with the conventions. It also makes your life easier because you have a set of guidelines to follow, and you're more likely to keep your conventions consistent, thus making your code easier to understand.</p>\n\n<p>Your class names don't follow the convention of naming classes in <code>CamelCase</code> starting with a capital letter. So you should change <code>parkingFloor</code> to <code>ParkingFloor</code>, <code>entryPanel</code> to <code>EntryPanel</code>, etc.</p>\n\n<h1>Enums over strings</h1>\n\n<p>In several places, you're using strings where you should be using enums. Enums are basically special classes filled with constants and are preferable in certain situations when you're using the same strings in multiple places. Python does have <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">built-in support for enums</a>, and you should use it.</p>\n\n<p>Your whole <code>ticket</code> class could benefit largely from this. My suggestion is to create a class called <code>TicketStatus</code> extending <code>enum.Enum</code> (thus making it an enum), and create within it the constants <code>ACTIVE</code> and <code>COMPLETE</code>. You can then change these two statements:</p>\n\n<pre><code>self.status = 'Active'\n\nself.status = 'Complete'\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>self.status = TicketStatus.ACTIVE\n\nself.status = TicketStatus.COMPLETE\n</code></pre>\n\n<p>Using enums makes comparisons and debugging easier, and overall makes your code a bit easier to understand.</p>\n\n<h1>Comments/documentation</h1>\n\n<p>Looking through your entire code, you have only 4 comments, 3 of which are placeholders for code you have not yet written. <strong>This is not good documentation.</strong> I can guarantee that if you stop working on your project and come back a month later, you will wish you explained to yourself what your code does and why. Or, if another developer starts working on your project, they won't know what much of the code does.</p>\n\n<p>In general, <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\">you should document almost everything</a>. This makes it easier for both yourself and others who are viewing your code. Docstrings (you may have heard them called \"multiline comments\") should be used when documenting a class, function, module, or method.</p>\n\n<p>Inline comments should be used a little more sparingly. If anyone who has never seen your program before can easily tell what a piece of code does, you do not need to add a comment explaining it. But if the purpose of the statement is not entirely obvious, adding a comment can be useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T04:43:16.277",
"Id": "216458",
"ParentId": "216290",
"Score": "6"
}
},
{
"body": "<p>Pikachu the Purple Wizard's <a href=\"https://codereview.stackexchange.com/a/216458/92478\">answer</a> covers quite a lot of essential style hints and best practices such as using enums.</p>\n\n<p>However, he has not said a lot about the actual classes themselves. Especially <code>displayBoard</code> caught me attention immediately.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class displayBoard():\n def show(self,p):\n for l in p.level:\n print(l.name)\n for k in l.spotTotal.keys():\n print(k, l.spotTotal[k] - l.spotTaken[k])\n</code></pre>\n\n<p>This is kind of a nonsense class. Classes should generally be used to hold variables and methods that would naturally belong together. <code>displayBoard</code> does not hold any data, and has a single function. Unlike Java, Python allows for functions which are not part of a class. So this could easily become</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def displayBoard(p):\n for l in p.level:\n print(l.name)\n for k in l.spotTotal.keys():\n print(k, l.spotTotal[k] - l.spotTaken[k])\n</code></pre>\n\n<p>without losing any functionality, clearity or whatever. As Pickachu said, this function would greatly benefit from documentation, and more expressive variable names (What type of object should <code>p</code> be?). </p>\n\n<p>On the other hand, <code>Payment</code> is as a fully valid candidate for a class. However your code ignores the only input value one might pass to its constructor.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Payment():\n def __init__(self, amount): #<- amount is not used anywhere\n self.id = 'paymentid2' #<- all these values may only be set afterwards, why?\n self.type = 'credit' # debit\n self.time = 'payment time'\n</code></pre>\n\n<p>While reworking your code, also think about whether a string is really a good fit for storing time. E.g. Python has a built-in <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\">datetime</a> module which might be (and probably is) a better fit here.</p>\n\n<p>Another thing sou should change are those nested functions sometimes found in methods or in the constructor of some classes.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class spot():\n def __init__(self,spotType):\n def generateId():\n # some mechanism to generate spot id\n return 1\n self.id = generateId()\n self.type = spotType\n</code></pre>\n\n<p>Should be reworked into</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Spot():\n def __init__(self, spotType):\n self.id = self.generateId()\n self.type = spotType\n\n def generateId(self):\n \"\"\"some mechanism to generate spot id\"\"\"\n return 1\n</code></pre>\n\n<p>which is what you already do, e.g. for <code>class ticket()</code>. If you intend to show that <code>generateId(self)</code> is not supposed to be used outside of the class, prepend it with <code>_</code>. That does not really hide the function from users outside of your class, but it is generally accepted as a convention that this function is only for internal use only and might be changed/removed/... without further notice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T21:48:50.117",
"Id": "216505",
"ParentId": "216290",
"Score": "4"
}
},
{
"body": "<h2><strong>Working code for the above questions -</strong></h2>\n\n<ol>\n<li>Better naming conventions</li>\n<li>Used enums over strings</li>\n</ol>\n\n<h2><strong>A few more changes are there since I added some more functionality like -</strong></h2>\n\n<ol>\n<li>Car / Bike classes extend the Vehicle Base Class</li>\n<li>Ticket has Vehicle, Spot and Payment objects</li>\n<li>Have added unassignSpot() as well</li>\n</ol>\n\n<h2><strong>Other people are welcome to review my code and provide your valuable inputs. Thank you.</strong></h2>\n\n<pre><code>import time\nfrom enum import Enum\n\nclass TicketStatus (enum.Enum) :\n ACTIVE = 1\n COMPLETE = 2\nclass VehicleType (enum.Enum) :\n CAR = 1\n BIKE = 2\nclass SpotType (enum.Enum) :\n FREE = 1\n TAKEN = 2\n\nclass ParkingLot :\n def __init__(self, name, address) :\n self.name = name\n self.address = address\n self.level = []\n def addLevel(self, floor):\n self.level.append(floor)\n def processEntry(self, ticket) :\n for eachlevel in self.level :\n if eachlevel.spots[ticket.veh.type][SpotType.FREE] :\n ticket.spot = eachlevel.assignSpot(ticket)\n print('Entry Completed For : ', ticket.veh.num)\n break;\n def processExit(self, ticket) :\n for eachlevel in self.level :\n if ticket.spot in eachlevel.spots[ticket.veh.type][SpotType.TAKEN] :\n eachlevel.unassignSpot(ticket)\n break;\n ticket.outTime = time.time()\n ticket.spots = None\n ticket.status = TicketStatus.COMPLETE\n ticket.payment = Payment(ticket.inTime, ticket.outTime)\n print('Exit Completed For : ', ticket.veh.num, ' Pay : ', int(ticket.payment.amount))\n\nclass ParkingLevel :\n def __init__(self, name) :\n self.name = name\n self.spots = {VehicleType.CAR : {SpotType.FREE : [], SpotType.TAKEN : []}, \n VehicleType.BIKE : {SpotType.FREE : [], SpotType.TAKEN : []} }\n def assignSpot(self, ticket) :\n if self.spots[ticket.veh.type][SpotType.FREE] != [] :\n spot = self.spots[ticket.veh.type][SpotType.FREE].pop()\n ticket.spot = spot\n self.spots[ticket.veh.type][SpotType.TAKEN].append(spot)\n return ticket.spot\n return False\n def unassignSpot(self, ticket) :\n self.spots[ticket.veh.type][SpotType.FREE].append(ticket.spot)\n self.spots[ticket.veh.type][SpotType.TAKEN].remove(ticket.spot)\n def addSpot(self, type, num) :\n for eachnum in range(num) :\n spot = Spot(type)\n self.spots[type][SpotType.FREE].append(spot) \n\nclass Vehicle :\n def __init__(self, num) :\n self.id = self.generateID()\n self.num = num\n def generateID(self) :\n yield range(100)\n\nclass Car (Vehicle) :\n def __init__(self, num) :\n super().__init__(num)\n self.type = VehicleType.CAR\n\nclass Bike (Vehicle) :\n def __init__(self, num) :\n super().__init__(num)\n self.type = VehicleType.CAR\n\nclass Spot :\n def __init__(self, type) :\n self.id = self.generateID()\n self.type = type\n def generateID(self) :\n yield range(100)\n\nclass Payment :\n def __init__(self, inTime, outTime) :\n self.mode = None\n self.rate = [30, 20, 10]\n self.amount = self.calAmount(inTime, outTime)\n def getRate(self) :\n return self.rate\n def setRate(self, rate) :\n self.rate = rate\n def calAmount(self, inTime, outTime) :\n amount = (outTime - inTime) * self.getRate()[0]\n amount += (outTime - inTime - 60 ) * self.getRate()[1] if outTime - inTime - 60 > 0 else 0\n amount += (outTime - inTime - 120 ) * self.getRate()[2] if outTime - inTime - 120 > 0 else 0\n return amount \n\nclass Ticket :\n def __init__(self, veh) :\n self.veh = veh\n self.status = TicketStatus.ACTIVE\n self.inTime = time.time()\n self.outTime = None\n self.payment = None\n self.spot = None\n def generateID(self) :\n # some ID generation mechanism\n return ID\n\nclass DisplayBoard :\n def show(self, P) :\n for eachlevel in P.level :\n print(P.name , '-' , eachlevel.name, '- Available Parking Spots')\n print('Car : ', len(eachlevel.spots[VehicleType.CAR][SpotType.FREE]))\n print('Bike : ', len(eachlevel.spots[VehicleType.BIKE][SpotType.FREE]))\n\n\nP = ParkingLot('Google Parking Lot', '123, Fort, Mumbai')\nF1 = ParkingLevel('F1')\nF1.addSpot(VehicleType.CAR, 3)\nF1.addSpot(VehicleType.BIKE, 3)\nP.addLevel(F1)\n\nBoard = DisplayBoard()\nBoard.show(P)\n\nT1 = Ticket(Car('MH05 AB 5454'))\nP.processEntry(T1)\n\nT2 = Ticket(Bike('MH05 AB 9000'))\nP.processEntry(T2)\n\ntime.sleep(2) \nP.processExit(T2)\n\nBoard = DisplayBoard()\nBoard.show(P)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T15:59:28.477",
"Id": "436553",
"Score": "1",
"body": "If you want this code reviewed then you should ask a new question and include a link to the question above instead of putting it in an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-16T17:18:41.293",
"Id": "482285",
"Score": "0",
"body": "I appreciate your views, my comment was an answer to the question posted here. And I also welcome other's feedback on my comment, if any."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T15:40:08.527",
"Id": "224970",
"ParentId": "216290",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:33:43.267",
"Id": "216290",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Parking Lot OO Design (Python)"
} | 216290 |
<blockquote>
<p><strong>Problem: Training</strong></p>
<p>As the football coach at your local school, you have been tasked with
picking a team of exactly P students to represent your school. There
are N students for you to pick from. The i-th student has a skill
rating Si, which is a positive integer indicating how skilled they
are.</p>
<p>You have decided that a team is fair if it has exactly P students on
it and they all have the same skill rating. That way, everyone plays
as a team. Initially, it might not be possible to pick a fair team, so
you will give some of the students one-on-one coaching. It takes one
hour of coaching to increase the skill rating of any student by 1.</p>
<p>The competition season is starting very soon (in fact, the first match
has already started!), so you'd like to find the minimum number of
hours of coaching you need to give before you are able to pick a fair
team.</p>
<p><strong>Input</strong></p>
<p>The first line of the input gives the number of test cases, T. T test
cases follow. Each test case starts with a line containing the two
integers N and P, the number of students and the number of students
you need to pick, respectively. Then, another line follows containing
N integers Si; the i-th of these is the skill of the i-th student.</p>
<p><strong>Output</strong></p>
<p>For each test case, output one line containing Case #x: y, where x is
the test case number (starting from 1) and y is the minimum number of
hours of coaching needed, before you can pick a fair team of P
students.</p>
<p><strong>Limits</strong></p>
<ul>
<li>Time limit: 15 seconds per test set.</li>
<li>Memory limit: 1 GB.</li>
<li>1 ≤ T ≤ 100.</li>
<li>1 ≤ Si ≤ 10000, for all i.</li>
<li>2 ≤ P ≤ N.</li>
<li>Test set 1 (Visible)</li>
<li>2 ≤ N ≤ 1000.</li>
<li>Test set 2 (Hidden)</li>
<li>2 ≤ N ≤ 105.</li>
</ul>
<p><strong>Sample</strong></p>
<p>Input</p>
<pre><code>3
4 3
3 1 9 100
6 2
5 5 1 2 3 4
5 5
7 7 1 7 7
</code></pre>
<p>Output</p>
<pre><code>Case #1: 14
Case #2: 0
Case #3: 6
</code></pre>
<p>In Sample Case #1, you can spend a total of 6 hours training the first
student and 8 hours training the second one. This gives the first,
second and third students a skill level of 9. This is the minimum time
you can spend, so the answer is 14.</p>
<p>In Sample Case #2, you can already pick a fair team (the first and
second student) without having to do any coaching, so the answer is 0.</p>
<p>In Sample Case #3, P = N, so every student will be on your team. You
have to spend 6 hours training the third student, so that they have a
skill of 7, like everyone else. This is the minimum time you can
spend, so the answer is 6.</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
void getData(int &p, std::vector<int> &skills) {
int n;
std::cin >> n >> p;
skills.reserve(n);
for (int i = 0; i < n; i++) {
int skill = 0;
std::cin >> skill;
skills.emplace_back(skill);
}
}
int minTrainingTime(std::vector<int> &skills, int p) {
std::sort(skills.begin(), skills.end());
int low = 0, high = p - 1;
int currentResult = 0;
for (int i = 0; i < high; i++) {
currentResult += skills[high] - skills[i];
}
int minResult = currentResult;
int remainingPossibilities = skills.size() - p;
for (int i = 0; i < remainingPossibilities; i++) {
currentResult -= skills[++high] - skills[low++];
currentResult += p * (skills[high] - skills[high - 1]);
minResult = std::min(minResult, currentResult);
}
return minResult;
}
int main() {
int t = 0;
std::cin >> t;
for (int testCase = 0; testCase < t; testCase++) {
int p;
std::vector<int> skills;
getData(p, skills);
std::cout << "Case #" << testCase + 1 << ": " << minTrainingTime(skills, p) << std::endl;
}
}
</code></pre>
<p><strong>Analysis</strong></p>
<p>Time complexity: <span class="math-container">\$O(n\log n)\$</span>, dominated by sorting</p>
<p>Space complexity: <span class="math-container">\$O(1)\$</span>, not counting the original data given by the problem</p>
| [] | [
{
"body": "<p>First of all, this looks good to me! I have some minor comments.</p>\n\n<p><strong>General comments</strong></p>\n\n<ul>\n<li><p>Consider compiling with <code>-Wconversion</code>. It will give you a couple of hints where you implicitly convert between <code>std::vector::size_type</code> (usually <code>std::size_t</code>) and <code>int</code>. Whether you work with <code>unsigned</code> data types for skills and quantities might be a matter of taste, but I think you should be aware of the conversion issue. Also, this compiler flags gives you (on my machine)</p>\n\n<blockquote>\n <p>implicit conversion loses integer precision: <code>unsigned long</code> to <code>int</code> [-Wshorten-64-to-32]</p>\n\n<pre><code>int remainingPossibilities = skills.size() - p;\n</code></pre>\n</blockquote>\n\n<p>which should definitely worth tackling even if the problem description specifies input characteristics that make a digit loss impossible.</p></li>\n<li><p>Not that this will be an issue for this example, but when you want to be as fast as possible, don't use <code><iostream></code>, but <code><cstdio></code> instead.</p></li>\n</ul>\n\n<p><strong>Input handling/parameter types</strong></p>\n\n<ul>\n<li><p>When retrieving the input data, don't pass non-<code>const</code> references, but prefer returning by value instead. (N)RVO will make sure there is no overhead. As you have more than one value, define a small, custom type for this. So, I'd suggest going with</p>\n\n<pre><code>struct TestCaseInput {\n int nToChoose;\n std::vector<int> skills;\n};\n\nTestCaseInput getData();\nint minTrainingTime(TestCaseInput& input);\n</code></pre>\n\n<p>cf. the Core Guidelines on this topic, <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f20-for-out-output-values-prefer-return-values-to-output-parameters\" rel=\"noreferrer\">F.20</a> and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f21-to-return-multiple-out-values-prefer-returning-a-struct-or-tuple\" rel=\"noreferrer\">F.21</a></p></li>\n<li><p><code>std::vector::emplace_back</code> makes sense when you can in-place construct an object with given parameters, but when you pass the already existing object to this function, it's probably clearer to use <code>push_back</code>. In the case of an integral value, it doesn't matter anyhow whether you move-construct or copy it. As an alternative, you could also</p>\n\n<pre><code>std::vector<int> skills(n); // Allocates and set all values to zero\n\nfor (int i = 0; i < n; i++)\n std::cin >> skills[i]; // No temporary variable required\n</code></pre>\n\n<p>And also have a look at the combination of <code>std::copy_n</code> and <code>std::istream_iterator</code> that @papagaga suggests to eliminate the manual loop here.</p></li>\n</ul>\n\n<p><strong>Main function <code>minTrainingTime</code></strong></p>\n\n<ul>\n<li><p>In the first loop, you read <code>skills[high]</code> in every iteration, even though this value doesn't change. Instead, just read it once and save it in a variable. Or, leave it as it is and verify that the compiler optimizes this away anyway.</p></li>\n<li><p>You can also replace this whole first loop by including <code><numeric></code> and using <code>std::accumulate</code> with an initial value <code>high*skills[high]</code> and <code>std::minus<>{}</code> as the binary operation parameter.</p></li>\n<li><p>If you can <code>const</code>-qualify a variable, do so:</p>\n\n<pre><code>const int remainingPossibilities = skills.size() - p;\n</code></pre></li>\n<li><p>But if can alternative reduce the scope of such a variable and by that even eliminate another one (the loop counter <code>i</code>), do so instead (as long as the negative influence on the readability is not too big, which I think is ok here):</p>\n\n<pre><code>// remainingPossibilities is now superfluous, just use the for loop for\n// the initialization and count differently:\nfor (int n = skills.size() - p; n != 0; n--) { /* ... */ }\n</code></pre></li>\n<li><p>You <em>might</em> want to consider an additional level of indirection for the function <code>minTrainingTime</code> here, as it can equally well operate on random access iterators instead of indices. This way, you eliminate the dependency of this function on the actual value type that you are using (which also considerably reduces the number of <code>-Wconversion</code> warnings at one go), as well as the dependency on the container type. Using some of the above hints, the resulting function template looks e.g. like this:</p>\n\n<pre><code>template <class RandomAccesIt, class T>\nauto minTrainingTime(RandomAccesIt first, RandomAccesIt last, T p)\n{\n using value_type = typename RandomAccesIt::value_type;\n auto low = first, high = std::next(first, p - 1);\n const value_type init = std::distance(low, high)*(*high);\n\n value_type currentResult = std::accumulate(first, high, init, std::minus<>{});\n value_type minResult = currentResult;\n\n for (auto n = std::distance(first, std::prev(last, p)); n != 0; --n) {\n currentResult -= *++high - *low++;\n currentResult += p*(*high - *std::prev(high));\n minResult = std::min(minResult, currentResult);\n }\n\n return minResult;\n}\n</code></pre>\n\n<p>and can be deduced and invoked by <code>minTrainingTime(skills.begin(), skills.end(), p)</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:43:21.600",
"Id": "418555",
"Score": "2",
"body": "Excellent, I just want to suggest using `std::copy_n` and an `std:istream_iterator` in `getData` rather than an explicit loop: `auto get_data(int n) {\n std::vector<int> skills(n);\n std::copy_n(std::istream_iterator<int>(std::cin), n, skills.begin());\n return skills;\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:46:29.683",
"Id": "418556",
"Score": "0",
"body": "@papagaga Good suggestion! I'll add a hint to your comment in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:02:21.457",
"Id": "419967",
"Score": "2",
"body": "Good except that advocating `<cstdio>` for performance here is like advocating using `void *` instead of objects; probably a dubious fix to a nonexistent problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:09:20.057",
"Id": "419969",
"Score": "0",
"body": "@Edward I find the comparison a bit drastic, but I do see the point :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:14:28.780",
"Id": "468115",
"Score": "0",
"body": "@papagaga IIRC, it isn't specified whether that reads `n` or `n + 1` integers. So it may corrupt the succeeding test cases."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:28:47.520",
"Id": "216323",
"ParentId": "216292",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "216323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:48:11.730",
"Id": "216292",
"Score": "10",
"Tags": [
"c++",
"performance",
"programming-challenge",
"c++11"
],
"Title": "Google Kickstart Round A 2019 - Training"
} | 216292 |
<p>I am extracting a list of data from a SharePoint library with CSOM, then manipulating the data to give some sort of visible statistic through <a href="https://developers.google.com/chart/" rel="nofollow noreferrer">Google Charts</a>. The data is a list of each parent department in our company and how many pages they printed in the previous week. Some additional information kept is the <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow noreferrer">ISO Week</a>, the current fiscal Quarter based on the <a href="https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_month" rel="nofollow noreferrer">ISO Week</a> and wither or not the entry is in the <strong>Current</strong>, <strong>Previous</strong>, or <strong>Outdated</strong> quarter (where Outdated) is just any date outside the current or previous Quarter.</p>
<p>Everything currently gives the expected output, however it feels very messy and there's repeated code in a few places. Right now we have two Google Charts that give the following statistics:</p>
<ol>
<li>Number of pages printed in the current Quarter (A sum of all entries for each department under "Current Quarter")</li>
<li>Percentage if pages printed relative to the previous quarter: essentially <code>((per-day average this quarter) / (per-day average last quarter) - 1)*100</code></li>
</ol>
<p>Here's an image of what the graphs currently look like: <a href="https://i.stack.imgur.com/5pXUr.png" rel="nofollow noreferrer">Pages printed per SBU</a>. Please note, SBU is our term for "parent department" and the image is relatively large, so I've opted to just post the URL.</p>
<p>First there are 4 'helper' functions I've added to either Date or Array types. These are:</p>
<p><code>Date.prototype.getWeek</code>, <code>Date.prototype.getWeeksInYear</code>, <code>Date.prototype.getWeekQuarter</code>, and <code>Array.prototype.customSort</code> and are outlined at the bottom of the script:</p>
<pre><code>var listTitle = "Printing Stats"
var viewTitle = "Current Stats"
// var dictStats = {}; // For testing
/*
* Get the list's view via CAML request.
* Prepares the body with a new DOM object to put charts in
* Takes no arguments
*/
function retrieveViewQuery() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
this.oView = oList.get_views().getByTitle(viewTitle);
var elem = document.createElement("div");
elem.id = "container";
document.querySelector(".ms-rte-layoutszone-inner").prepend(elem);
clientContext.load(oView);
clientContext.executeQueryAsync(
this.retrieveViewQuerySucceeded.bind(this),
this.onQueryFailed.bind(this)
);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/*
* Get the items from the list via second CAML request.
*/
function retrieveViewQuerySucceeded(sender, args) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle(listTitle);
var query = new SP.CamlQuery();
query.set_viewXml(this.oView.get_viewQuery());
this.items = oList.getItems(query);
clientContext.load(this.items);
clientContext.executeQueryAsync(
this.retrieveItemListSucceeded.bind(this),
this.onQueryFailed.bind(this)
);
}
/*
* Extract the the following parameters from the list:
* - Which quarter is it: "Previous Quarter" or "Current Quarter"
* - Which SBUs are present in the data
* - Extract the cumulative number of pages per quarter
* - Extract the week number of the quarter
*/
function retrieveItemListSucceeded(sender, args) {
var dictStats = {};
var listItemEnumerator = items.getEnumerator();
var oListItem;
while (listItemEnumerator.moveNext()) {
oListItem = listItemEnumerator.get_current().get_fieldValues();
var quarter = oListItem.PreviousOrCurrentQuarter;
var itemTitle = oListItem.Title.replace(/\s*\-\s*ZvL/i, "");
// Prepare datastructure
if (!dictStats[quarter]) {
dictStats[quarter] = {}
}
if (!dictStats[quarter][itemTitle]) {
dictStats[quarter][itemTitle] = [[0, 0]];
}
var tempItem = dictStats[quarter][itemTitle];
dictStats[quarter][itemTitle].push([
parseInt(tempItem[tempItem.length - 1]) + oListItem.TotalPrintedPages,
oListItem.RelevantDate
]);
}
chartStatSpecifications(dictStats);
}
/*
* Prepare the data for the chart views.
* Takes in an object with the following data structure:
* Object >
* Previous Quarter || Current Quarter >
* SBU >
* [ cumulativePageCountInQuarter, WeekOfQuarter]
*/
function chartStatSpecifications(allStats) {
var itemStats = [[], []];
var totalPageCount = 0,
totalDeptAvgLQ = 0;
for (var dept in allStats["Current Quarter"]) {
var deptStats = allStats["Current Quarter"][dept.toString()];
var name = dept.toString().replace("&", "&\r\n");
var deptAvgLQ, deptAvgCQ;
// Calculate average pages printed so far this Quarter
// and overall last quarter based on ISO Weeks
if (allStats["Previous Quarter"] && allStats["Previous Quarter"][dept.toString()]) {
var tmp = allStats["Previous Quarter"][dept.toString()];
tmp = tmp[tmp.length - 1]
var weeks = (new Date(tmp[1])).getWeeksInYear() == 53 ? 14 : 13
deptAvgLQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
console.log(weeks * 7); // For testing
weeks = (new Date(tmp[1])).getWeek() - ((new Date(tmp[1])).getWeekQuarter() - 1) * 13
deptAvgCQ = Math.ceil(parseInt(tmp[0]) / (weeks * 7));
}
// Total number of pages this quarter
itemStats[0].push([
name,
deptStats[deptStats.length - 1][0]
]);
// Percentage above last quarter's average
itemStats[1].push([
name,
Math.floor((deptAvgCQ / deptAvgLQ - 1) * 5000) / 50
]);
totalPageCount += deptStats[deptStats.length - 1][0];
totalDeptAvgLQ += deptAvgCQ;
}
totalPageCount = totalPageCount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
totalDeptAvgLQ = Math.floor(totalDeptAvgLQ / itemStats[1].length * 50) / 50
totalDeptAvgLQ = totalDeptAvgLQ.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
itemStats[0].customSort(['SBU', 'Pages'], function (a, b) {
return (a[1] - b[1])
});
google.charts.setOnLoadCallback(function () {
drawChart('Total Pages this Quarter: ' + totalPageCount, itemStats[0])
});
itemStats[1].customSort(['SBU', '% Above'], function (a, b) {
return a[1] - b[1]
});
google.charts.setOnLoadCallback(function () {
drawChart('Percentage over last quarter\'s average: ', itemStats[1])
// drawChart('Percentage over last quarter\'s average: ' + totalDeptAvgLQ, itemStats[1])
});
}
/*
* Draw the Google Chart.
* Inputs:
* chartTitle :: Title for the chart
* stats :: Prepared data with 2 or more columns
*/
function drawChart(chartTitle, stats) {
var data = google.visualization.arrayToDataTable(stats);
var options = {
title: chartTitle,
legend: 'none',
height: 400
};
// Instantiate and draw the chart.
var elem = document.createElement("div");
document.getElementById('container').appendChild(elem);
var chart = new google.visualization.ColumnChart(elem);
chart.draw(data, options);
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveViewQuery);
/*
* * * * * * Additional Scripting tools * * * * * *
*
* This script is released to the public domain and may be used, modified and
* distributed without restrictions. Attribution not necessary but appreciated.
* Source: https://weeknumber.net/how-to/javascript
*
* Returns the ISO week of the date.
*/
Date.prototype.getWeek = function () {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
3 + (week1.getDay() + 6) % 7) / 7);
}
// Returns the four-digit year corresponding to the ISO week of the date.
Date.prototype.getWeeksInYear = function () {
var date = new Date(this.getTime());
var isLeap = new Date(date.getYear() + 1900, 1, 29).getMonth() === 1;
//check for a Jan 1 that's a Thursday or a leap year that has a
//Wednesday jan 1. Otherwise it's 52
return date.getDay() === 4 || isLeap && date.getDay() === 3 ? 53 : 52
}
// Returns how many weeks are in a date's specified quarter
Date.prototype.getWeekQuarter = function () {
var date = new Date(this.getTime());
weekNum = date.getWeek();
return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);
}
// Takes an array and directly manipulates the object with a specified sort
// prepends a smaller object to the array
Array.prototype.customSort = function (prependItem, customSort) {
this.sort(customSort);
if (prependItem)
this.unshift(prependItem);
return this;
}
</code></pre>
<p>And below is added to the SharePoint page so Google Charts can be loaded:</p>
<pre><code><script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:55:00.347",
"Id": "216294",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"formatting"
],
"Title": "Extract and manipulate date from SharePoint and export into Google Charts"
} | 216294 |
<p>I got this problem during a mock interview, and I would like to get code review for the backtracking solution. I include 7 test cases, and my solution passes 7 out of 7 test cases. <a href="https://codeinterview.io/YGKXWPXMDX" rel="nofollow noreferrer">See the online code compiler here</a> </p>
<blockquote>
<h1><a href="https://leetcode.com/problems/unique-paths/description/" rel="nofollow noreferrer">Robot Paths</a></h1>
<p><strong>Prompt:</strong> Given a matrix of zeroes, determine how many unique paths exist from the top left corner to the bottom right corner</p>
<p><strong>Input:</strong> An Array of Array of Integers (matrix)</p>
<p><strong>Output:</strong> Integer</p>
<p><strong>Examples:</strong></p>
<pre><code>matrix = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
robotPaths(matrix) = 38
</code></pre>
<pre><code>matrix = [[0,0,0],
[0,0,0]]
robotPaths(matrix) = 4
</code></pre>
</blockquote>
<pre><code># Note: From any point, you can travel in the four cardinal directions. I decided to do backtracking approach to solve this problem.
# (north, south, east, west). A path is valid as long as it travels
# from the top left corner to the bottom right corner, does not go
# off of the matrix, and does not travel back on itself
def robot_paths(matrix):
num_of_rows = len(matrix)
num_of_cols = len(matrix[0])
def traverse(row, col):
nonlocal num_of_rows
nonlocal num_of_cols
# is row and col in bounds?
if row < 0 or row >= num_of_rows or col < 0 or col >= num_of_cols:
return 0
# has row, col already been visited?
if matrix[row][col] == 1:
return 0
# is row, col the destination?
if row == num_of_rows - 1 and col == num_of_cols - 1:
return 1
# mark coordinate as visited
matrix[row][col] = 1
# initialize sum of total unique paths to end from that coordinate
s = traverse(row, col + 1) + traverse(row + 1, col) + traverse(row - 1, col) + traverse(row, col - 1)
# backtrack; mark coordinate as unvisited so it can be
matrix[row][col] = 0
return s
return traverse(0, 0)
#############################################
######## DO NOT TOUCH TEST BELOW!!! #######
#############################################
def expect(count, name, test):
if (count == None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
errMsg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
errMsg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if errMsg != None:
print(' ' + errMsg + '\n')
def lists_equal(lst1, lst2):
if len(lst1) != len(lst2):
return False
for i in range(0, len(lst1)):
if lst1[i] != lst2[i]:
return False
return True
print('Robot Paths Tests')
test_count = [0, 0]
def test():
matrix = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
example = robot_paths(matrix)
return example == 38
expect(test_count, 'should work on first example input', test)
def test():
matrix = [[0, 0, 0],
[0, 0, 0]]
example = robot_paths(matrix)
return example == 4
expect(test_count, 'should work on second example input', test)
def test():
matrix = [[0]]
example = robot_paths(matrix)
return example == 1
expect(test_count, 'should work on single-element input', test)
def test():
matrix = [[0, 0, 0, 0, 0, 0]]
example = robot_paths(matrix)
return example == 1
expect(test_count, 'should work on single-row input', test)
def test():
matrix = [[0],
[0],
[0],
[0],
[0]]
example = robot_paths(matrix)
return example == 1
expect(test_count, 'should work on a 5 x 8 matrix input', test)
def test():
matrix = [[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]
print(" Please be patient, test 6 may take longer to run")
example = robot_paths(matrix)
return example == 7110272
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
| [] | [
{
"body": "<p>There are a few things I would like to point out to you.</p>\n\n<h2>Style</h2>\n\n<p>Python has an official style guide called PEP8. Under \"Indendation\" there is the following rule most Python programmers stick to:</p>\n\n<blockquote>\n <p>Use 4 spaces per indentation level.</p>\n</blockquote>\n\n<p>Reference: <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">PEP8 - Indentation</a></p>\n\n<p>This would also make your code consistent with the provided test code.</p>\n\n<p>Though not strictly part of PEP8, most of the tools integrated in Python IDEs would also tell you that <code>s</code> is not a good variable name. Use something that is more descriptive (<code>n_paths</code> maybe?).</p>\n\n<p>While we're at it, you can wrap long lines such as the sum of the four traverse calls on multiple lines to allow better readability in case you have, say two documents next to each other or a small screen. Including the previous note, <code>s = ...</code> could be transformed into, e.g.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>n_paths = traverse(row, col + 1) \\\n + traverse(row + 1, col) \\\n + traverse(row - 1, col) \\\n + traverse(row, col - 1)\n</code></pre>\n\n<h2>The <code>nonlocal</code> keyword</h2>\n\n<p>I suspect you slightly missunderstood what <code>nonlocal</code> does. All variables from an outer scope are automatically available to <em>read from</em> in nested scopes. This means in your case, <code>traverse</code> can see <code>num_of_rows</code> and <code>num_of_cols</code> from <code>robot_paths</code> automatically.</p>\n\n<p>Statements like <code>nonlocal</code> or <code>global</code> only come into play whenever you want to <em>assign to</em> a variable not in your local scope. The Python interpreter would then recognize, that you don't want to create a new local variable with the given name, but instead use an already existing one from an outer scope. <a href=\"https://stackoverflow.com/a/1261961\">This</a> SO answer has a nice example to show you that effect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:52:10.913",
"Id": "216369",
"ParentId": "216295",
"Score": "1"
}
},
{
"body": "<h3>The <code>x < y < z</code> operator</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>if row < 0 or row >= num_of_rows or col < 0 or col >= num_of_cols:\n</code></pre>\n</blockquote>\n\n<p>You can write like this:</p>\n\n<pre><code>if not(0 <= row < num_of_rows and 0 <= col < num_of_cols):\n</code></pre>\n\n<p>Which is not only a bit more compact, but also quite natural to read.</p>\n\n<h3>Modifying the input</h3>\n\n<p>Unless the problem description explicitly allows it,\nit's better not to modify the input.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:14:39.620",
"Id": "216674",
"ParentId": "216295",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:07:16.843",
"Id": "216295",
"Score": "2",
"Tags": [
"python",
"interview-questions"
],
"Title": "Solve Robot Paths using backtracking"
} | 216295 |
<p>I decided to play with F# and found simple task on Codewars.
The task is sounds like "Calculate Sum/Mean/Avarage for selected City".
I decided to calculate only Sum. My solution is horrific. I would be grateful for your advice's how to do this in a right way. Thank you!</p>
<pre><code>let d0 =
"Rome:Jan 81.2,Feb 63.2,Mar 70.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,Aug 27.5,Sep 60.9,Oct 117.7,Nov 111.0,Dec 97.9\n\
London:Jan 48.0,Feb 38.9,Mar 39.9,Apr 42.2,May 47.3,Jun 52.1,Jul 59.5,Aug 57.2,Sep 55.4,Oct 62.0,Nov 59.0,Dec 52.9\n\
Paris:Jan 182.3,Feb 120.6,Mar 158.1,Apr 204.9,May 323.1,Jun 300.5,Jul 236.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7\n\
NY:Jan 108.7,Feb 101.8,Mar 131.9,Apr 93.5,May 98.8,Jun 93.6,Jul 102.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2\n\
Vancouver:Jan 145.7,Feb 121.4,Mar 102.3,Apr 69.2,May 55.8,Jun 47.1,Jul 31.3,Aug 37.0,Sep 59.6,Oct 116.3,Nov 154.6,Dec 171.5\n\
Sydney:Jan 103.4,Feb 111.0,Mar 131.3,Apr 129.7,May 123.0,Jun 129.2,Jul 102.8,Aug 80.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2\n\
Bangkok:Jan 10.6,Feb 28.2,Mar 30.7,Apr 71.8,May 189.4,Jun 151.7,Jul 158.2,Aug 187.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4\n\
Tokyo:Jan 49.9,Feb 71.5,Mar 106.4,Apr 129.2,May 144.0,Jun 176.0,Jul 135.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4\n\
Beijing:Jan 3.9,Feb 4.7,Mar 8.2,Apr 18.4,May 33.0,Jun 78.1,Jul 224.3,Aug 170.0,Sep 58.4,Oct 18.0,Nov 9.3,Dec 2.7\n\
Lima:Jan 1.2,Feb 0.9,Mar 0.7,Apr 0.4,May 0.6,Jun 1.8,Jul 4.4,Aug 3.1,Sep 3.3,Oct 1.7,Nov 0.5,Dec 0.7"
module CalculatorHelper =
let SumByTown (town:string) (input:string) =
let rows = input.Split('\n')
for i in rows do
if (i.Contains(town))
then
let monthes = i.Replace(town + ":","").Split(",")
let sequence = seq { for j in monthes do yield j.Remove(0,4) |> double } |> Seq.sum
printf "%f" sequence
let result = CalculatorHelper.SumByTown "Rome" d0
</code></pre>
| [] | [
{
"body": "<p>You should reduce the use of explicit type declaration as much as possible.</p>\n\n<hr>\n\n<p>A function isn't of much value if it just prints its calculated result. You should return the result to let it be up to the client to handle it.</p>\n\n<p>But you can't break out from a loop via an if-statement in F#. You can overcome that by wrapping the outer for-loop in a <code>seq {...}</code> statement and then <code>yield</code> the one and only result and then take the first element from that sequence. But that is inefficient in that it iterates through all the cities even if the first is the one searched for.</p>\n\n<p>Below I've refactored your algorithm according to the above in order to be able to return the result from the function:</p>\n\n<pre><code>let SumByTown town input =\n let rows = (string input).Split('\\n')\n seq { for row in rows do\n if (row.Contains(town)) then \n let months = row.Replace(town + \":\" , \"\").Split(',')\n let sequence = seq { for j in months do yield j.Remove(0,4) |> double } |> Seq.sum\n yield sequence\n } |> Seq.head\n</code></pre>\n\n<p>But this still doesn't look very functional IMO.</p>\n\n<hr>\n\n<p>For inspiration is here a version that uses the built in higher order functions in a more functional manner:</p>\n\n<pre><code>let calculateCity city data =\n let sum values = values |> Array.sum\n let avg values = values |> Array.average\n let mean values = (values |> Array.sort).[values.Length / 2]\n\n let handleCity cityText = \n let values = Regex.Replace(cityText, \"[^0-9,.]+\", \"\").Split(',') |> Array.map float\n (sum values, avg values, mean values)\n\n (string data).Split('\\n') |> Seq.find (fun s -> s.StartsWith(city)) |> handleCity\n\nlet printCityData (sum, avg, mean) = printfn \"Sum: %.2f, Average: %.2f, Mean: %.2f\" sum avg mean\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>printCityData (calculateCity town data)\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Antoher way to use <code>Regex</code> is to match numbers instead of removing non-numeric chars:</p>\n\n<pre><code>let calculateCity1 city data =\n let sum values = values |> Seq.sum\n let avg values = values |> Seq.average\n let mean values = (values |> Seq.sort).ElementAt((values|> Seq.length)/ 2)\n let extractValues text = Regex.Matches(text, \"\\d+.\\d+\").Cast<Match>() |> Seq.map (fun m -> m.Value)\n\n let handleCity cityText = \n let values = cityText |> extractValues |> Seq.map float\n (sum values, avg values, mean values)\n\n (string data).Split('\\n') |> Seq.find (fun s -> s.StartsWith(city)) |> handleCity\n\nlet printCityData (sum, avg, mean) = printfn \"Sum: %.2f, Average: %.2f, Mean: %.2f\" sum avg mean\n</code></pre>\n\n<p>This requires an <code>open System.Linq</code> at the top of the module</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:18:26.843",
"Id": "216330",
"ParentId": "216297",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216330",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:33:04.590",
"Id": "216297",
"Score": "2",
"Tags": [
"f#"
],
"Title": "F# parse data and calculate sum"
} | 216297 |
<p><strong><a href="https://leetcode.com/problems/reverse-integer/" rel="nofollow noreferrer">LeetCode</a> Problem</strong></p>
<blockquote>
<p>Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.</p>
</blockquote>
<p><strong>Feedback</strong></p>
<p>Optimized from beta code in the <a href="https://codereview.stackexchange.com/questions/216068/reverse-int-within-the-32-bit-signed-integer-range-%E2%88%92231-231-%E2%88%92-1">original question here</a>. Based on <a href="https://leetcode.com/problems/reverse-integer/" rel="nofollow noreferrer">this LeetCode problem.</a>. I'm trying to come up with a good approach that just math operations to iterate a serious of digits using division, almost treating the <code>int</code> like a <code>stack</code> popping using modulus, and pushing using multiplication.</p>
<pre><code>#include <cassert>
#include <climits>
#include <cmath>
#include <iostream>
class Solution
{
public:
int reverse(int i) {
if(i > INT_MAX || i < INT_MIN) {
return 0;
}
int sign = 1;
if(i < 0) {
sign = -1;
i = i*sign;
}
int reversed = 0;
int pop = 0;
while(i > 0) {
pop = i % 10;
reversed = reversed*10 + pop;
i /= 10;
}
std::cout << reversed << '\n';
return reversed*sign;
}
};
int main()
{
Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(1534236469) == 0);
assert(s.reverse(-2147483412) == -2143847412);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:41:55.937",
"Id": "418511",
"Score": "3",
"body": "The problem is ill-posed. If 'the' reverse of `120` is `21`, how can you know whether 'the' reverse of `21` should be `120` or `12`? What makes 'the' reverse of `1` number `1` and not `10000`? How can you tell your code **solves the problem** if the correct **solution is not defined?**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:46:27.647",
"Id": "418513",
"Score": "1",
"body": "That's good feedback CiaPan and I think you raising that as feedback on LeetCode directly would be good next step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T03:22:20.933",
"Id": "418517",
"Score": "3",
"body": "\"but need some help coming up with how to detect and prevent such cases.\" Asking for advice for code not written yet is off-topic for code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:12:30.297",
"Id": "418547",
"Score": "2",
"body": "@greg Sure, but ...I've got no account there, and I don't think I'll create one soon. Feel free to report the ambiguity there yourself. :) This may be not very important in an excercise, but IMHO such omission may be devastating in real software projects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:13:49.203",
"Id": "418612",
"Score": "0",
"body": "I've read a few articles and publications and agree on the that point. I want to make sure I'm writing code that is production ready. Okay thanks for the feedback CiaPan, I'll make LeetCode aware of this."
}
] | [
{
"body": "<p>To prevent overflow, you need to check if <code>reversed*10+pop > INT_MAX</code>. But in order to avoid actually overflowing while checking, rearrange the equation to <code>reversed > (INT_MAX-pop)/10;</code> </p>\n\n<p>Actually, I think you should check against <code>-INT_MIN</code>. Which brings up another point. You could use <code>int64_t</code> for <code>reversed</code>. This both ensures it can hold -INT_MIN before fixing the sign, and lets you do the bounds test only once at the end, instead of at each intermediate step.</p>\n\n<p>I would initialize <code>sign</code> with the correct value: <code>int sign = (i<0)?-1:1; i*=sign;</code> . <code>pop</code> can be loop local and doesn't need the <code>0</code> initialization.</p>\n\n<p>You should multiply <code>reversed</code> by <code>sign</code> before printing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T07:45:59.233",
"Id": "418533",
"Score": "0",
"body": "Also, make the `sign` const while you initialize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:33:14.710",
"Id": "418613",
"Score": "0",
"body": "`int64_t` sounds like a great idea. I'm thinking when fixing the sign I will also need to convert the `int64_t` to `int` since there will be conflicting return types for my function or is this some automatic conversion that happens behind the scenes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:08:42.313",
"Id": "418621",
"Score": "1",
"body": "Assigning an int64_t to a 32 bit int will automatically truncate the high order bits. If you have already done the limit checking to assure they are zero, then this is no problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:30:31.113",
"Id": "418625",
"Score": "1",
"body": "I see, I compare `int64_t` to `-INT_MIN` instead of `INT_MAX` because\n-(-2147483648) wil result in a value greater than `INT_MAX`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:45:07.923",
"Id": "418656",
"Score": "0",
"body": "Be careful rearranging arithmetic like that - how does integer truncation affect the correctness of `reversed > (INT_MAX-pop)/10`? I think that will give false positives. (Of course, your unit tests should stress the boundary conditions...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:09:17.743",
"Id": "418720",
"Score": "0",
"body": "Comment to my earlier comment - the truncation is okay, but it's slightly awkward to prove. It's easier to write unit tests, and they convinced me to use that transformed inequality in my own answer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:42:18.377",
"Id": "216308",
"ParentId": "216300",
"Score": "5"
}
},
{
"body": "<h1>Unused header</h1>\n<p>We use nothing from <code><cmath></code>, so it need not be included.</p>\n<h1>This should be a function, not a class</h1>\n<p>Putting all code into a class suggests you have a background in Java or similar.</p>\n<p>In C++, we can (and should) use ordinary functions for operations that are mathematically functions. In this case, we have a <em>pure</em> function: it has no state, and should always give the same result for any given input.</p>\n<p>If it's part of your program requirements that it must provide this (unhelpfully-named) class, then comment that. I'd recommend that you still write a plain function, and simply provide an <em>adapter</em> to conform to the requirements:</p>\n<pre><code>int reverse_decimal_digits(int i);\n\nclass Solution \n{\n public:\n int reverse(int i) { return reverse_decimal_digits(i); }\n}\n</code></pre>\n<h1>Choice of data type</h1>\n<p>If we're processing a 32-bit integer, then we should be using <code>std::int32_t</code>. Plain <code>int</code> isn't necessarily large enough (it can be any size from <strong>16 bits</strong> upwards).</p>\n<h1>Incorrect test</h1>\n<p>Given <code>int i</code>, then <strong><code>i > INT_MAX || i < INT_MIN</code></strong> is false <em>by definition</em>. The requirement you quote is (my emphasis):</p>\n<blockquote>\n<p>When the <strong>reversed</strong> integer overflows, return 0.</p>\n</blockquote>\n<h1>Not all integers have a negative</h1>\n<p>Beware of overflow here:</p>\n<blockquote>\n<pre><code> if(i < 0) { \n sign = -1;\n i = i*sign;\n }\n</code></pre>\n</blockquote>\n<p>On 2s-complement systems, <code>-1 * INT_MIN</code> is undefined.</p>\n<p>It turns out that we don't need this step, as in modern C++, the <code>%</code> operator can be used predictably with negative numbers to our advantage (see my modified code, below).</p>\n<h1>Don't do I/O from a pure function</h1>\n<p>I guess this is some leftover debugging that should have been removed:</p>\n<blockquote>\n<pre><code> std::cout << reversed << '\\n';\n</code></pre>\n</blockquote>\n<h1>Additional tests</h1>\n<p>It's good that you've included some unit tests - I wish more people would do that!</p>\n<p>Do think about which values to test. Your choice agrees with mine somewhat, but diverges later:</p>\n<ul>\n<li><code>0</code>, <code>1</code> and <code>-1</code> for the three simplest cases.</li>\n<li>positive and negative two-digit numbers (e.g. <code>12</code> and <code>-23</code>).</li>\n<li>smallest and largest allowable <em>input</em> (<code>INT32_MIN</code> and <code>INT32_MAX</code>).</li>\n<li>smallest and largest allowable <em>result</em>, and the first overflow in each direction in first and last digits (±<code>1463847412</code>, ±<code>1463847413</code>, ±<code>1563847412</code>).</li>\n</ul>\n<p>Don't be tempted to over-test. Tests need to be maintained, too, so try to limit the tests to those that exercise the limits within the implementation.</p>\n<h1>Minor improvements</h1>\n<p>The scope of <code>pop</code> can be reduced to within the loop. And perhaps a better name would be <code>digit</code>?</p>\n<h1><code>noexcept</code> and <code>constexpr</code></h1>\n<p>Can we annotate the function with <code>noexcept</code> and <code>constexpr</code>?</p>\n<h1>Future</h1>\n<p>Should the number base be hard-coded to 10? Perhaps there's a use for a reverser that works in arbitrary bases. Certainly, base-16 is convenient for testing.</p>\n<hr />\n<h1>Modified code</h1>\n<p>I've used GoogleTest rather than plain C <code>assert()</code>, so as to get better messages when a test fails, but any testing method is fine.</p>\n<pre><code>#include <cstdint>\n\nconstexpr std::int32_t\nreverse_digits(std::int32_t i, int base = 10) noexcept\n{\n std::int32_t reversed = 0;\n const bool negative = i < 0;\n\n while (negative ? i <= -base : i >= base) {\n auto const digit = i % base; // negative if i < 0\n reversed = reversed * base + digit;\n i /= base;\n }\n\n // final digit may cause overflow\n const bool overflow =\n negative\n ? (reversed < (INT32_MIN - i) / base)\n : (reversed > (INT32_MAX - i) / base);\n if (overflow) {\n return 0;\n }\n\n return reversed * base + i;\n}\n</code></pre>\n\n<pre><code>#include <gtest/gtest.h>\n\nTEST(Reverse, decimal)\n{\n EXPECT_EQ(0, reverse_digits(0));\n EXPECT_EQ(1, reverse_digits(1));\n EXPECT_EQ(-1, reverse_digits(-1));\n\n EXPECT_EQ(21, reverse_digits(12));\n EXPECT_EQ(-32, reverse_digits(-23));\n\n EXPECT_EQ(0, reverse_digits(INT32_MIN));\n EXPECT_EQ(0, reverse_digits(INT32_MAX));\n\n EXPECT_EQ(2147483641, reverse_digits(1463847412));\n EXPECT_EQ(0, reverse_digits(1463847413));\n EXPECT_EQ(0, reverse_digits(1563847412));\n\n EXPECT_EQ(-2147483641, reverse_digits(-1463847412));\n EXPECT_EQ(0, reverse_digits(-1463847413));\n EXPECT_EQ(0, reverse_digits(-1563847412));\n}\n\nTEST(Reverse, hexadecimal)\n{\n EXPECT_EQ(0x7ffffff7, reverse_digits(0x7ffffff7, 16));\n EXPECT_EQ(0, reverse_digits(0x10000008, 16));\n\n EXPECT_EQ(-0x7ffffff7, reverse_digits(-0x7ffffff7, 16));\n EXPECT_EQ(0, reverse_digits(-0x10000008, 16));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:49:56.410",
"Id": "418713",
"Score": "0",
"body": "Good suggestions, although I don't like testing the sign of `i` in every loop. It's one of those minor pessimizations that adds up as your system grows. I also think, but haven't proven to myself, that if the initial value fit in an int, then only the very last reversed digit has the possibility for overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:54:46.980",
"Id": "418715",
"Score": "0",
"body": "Good points in your comment; I think they are easy to address. Proving that only the final digit can overflow is a great idea (hint: start with `base`==2 and it should be obvious), and that saves us a lot of work. I'll edit that in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:40:45.823",
"Id": "216402",
"ParentId": "216300",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "216308",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:11:51.117",
"Id": "216300",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"mathematics",
"integer"
],
"Title": "Reverse int within the 32-bit signed integer range: \\$[−2^{31}, 2^{31} − 1]\\$ Optimized"
} | 216300 |
<p>I am loading some information about the selected vendor using mysql query. I made a method with a List as return type, then created another method to assign values coming from a list. I am wondering if there is a better way of doing things.</p>
<p>P.S. The vendorCrud object is a database helper.</p>
<pre><code> private List<string> GetVendorInformation(string vendorId)
{
crud vendorCrud = new crud();
List<string> columnData = new List<string>();
string query = String.Format("SELECT tin, email_add, fax_no, tel_no, contact.contact_person FROM lib_inv_vendor vendor " +
"LEFT JOIN lib_inv_vendor_contact_person contact ON vendor.vendor_id = contact.vendor_id " +
"WHERE vendor.vendor_id = {0} ORDER BY contact_default DESC LIMIT 1", vendorId);
vendorCrud.load_data(query, Modules.connection.filesetupDB1, CommandType.Text);
foreach (DataRow item in vendorCrud.table.Rows)
{
columnData.Add(item["tin"].ToString());
columnData.Add(item["email_add"].ToString());
columnData.Add(item["fax_no"].ToString());
columnData.Add(item["tel_no"].ToString());
columnData.Add(item["contact_person"].ToString());
}
return columnData;
}
private void SetVendorInformation(List<string> colData)
{
txtVendorTin.EditValue = colData[0];
txtEmail.EditValue = colData[1];
txtFaxNo.EditValue = colData[2];
txtTelNo.EditValue = colData[3];
txtAttention.EditValue = colData[4];
}
private void txtSupplier_EditValueChanged(object sender, EventArgs e)
{
SetVendorInformation(GetVendorInformation(txtSupplier.EditValue.ToString()));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:21:11.137",
"Id": "418541",
"Score": "0",
"body": "Welcome to Code Review! You haven't shown the definition of your table(s), without which it's hard to give a good review. I recommend you include these definitions (preferably as SQL statements, so that reviewers can reproduce your test environment)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T03:15:19.137",
"Id": "216306",
"Score": "1",
"Tags": [
"c#",
"mysql"
],
"Title": "Retrieving information about a vendor using MySQL"
} | 216306 |
<p>I would like any constructive comments regarding the structure of this simple App that takes an API response and then displays on a table view.</p>
<p>The URL is written in a ConstantsAPI file</p>
<pre><code>let baseUrl : String = "https://haveibeenpwned.com/api/v2"
let breachesExtensionURL : String = "/breaches"
</code></pre>
<p>Displayed on a tableviewcontroller</p>
<pre><code>class SitewideTableViewController: UITableViewController, DataManagerDelegate {
var pwnedData = [BreachModel]()
var session: URLSession!
var task: URLSessionDownloadTask!
override func viewDidLoad() {
super.viewDidLoad()
session = URLSession.shared
task = URLSessionDownloadTask()
DataManager.shared.delegate = self
DataManager.shared.fetchBreaches()
}
func didDownloadBreaches() {
DispatchQueue.main.async {
self.pwnedData = DataManager.shared.sortedBreaches()
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pwnedData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Sitewide", for: indexPath)
cell.textLabel?.text = pwnedData[indexPath.row].name
return cell
}
}
</code></pre>
<p>Using the following model</p>
<pre><code>import Foundation
class BreachModel : Codable {
let name : String
let title : String
let domain : String
let breachDate : String
let addedDate : String
let modifiedData : String
let pwnCount : Int
let description: String
private enum CodingKeys: String, CodingKey {
case name = "Name"
case title = "Title"
case domain = "Domain"
case breachDate = "BreachDate"
case addedDate = "AddedDate"
case modifiedData = "ModifiedDate"
case pwnCount = "PwnCount"
case description = "Description"
}
}
</code></pre>
<p>With a Data manager that would manage all of the data</p>
<pre><code>@objc protocol DataManagerDelegate: class {
// optional delegate to practice
@objc optional func didDownloadBreaches() // called when the manager has completed downloading all the breaches
}
class DataManager {
static let shared: DataManager = DataManager()
public weak var delegate: DataManagerDelegate? = nil
private var breaches = [BreachModel]()
func fetchBreaches() {
HTTPManager.shared.get(urlString: baseUrl + breachesExtensionURL, completionBlock: { [weak self] (data: Data?) -> Void in
let decoder = JSONDecoder()
if let data = data{
print(data.count)
do {
self?.breaches = try decoder.decode([BreachModel].self, from: data)
self?.delegate?.didDownloadBreaches?()
} catch let error {
print ("Error in reading data", error)
}
}
}
)
}
func sortedBreaches() -> [BreachModel] {
return breaches.sorted{ a,b in a.name < b.name }
}
}
</code></pre>
<p>That calls a HTTP manager whose only responsibility is to call url's</p>
<pre><code>class HTTPManager {
static let shared: HTTPManager = HTTPManager()
public func get (urlString: String, completionBlock: ((Data?) -> Void)?) {
let url = URL(string: urlString)
if let usableUrl = url {
let request = URLRequest(url: usableUrl)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
completionBlock?(data)
})
task.resume()
}
}
}
</code></pre>
<p>So is this a reasonable extendable structure?
Should I have used dataTask or URLSessionDownloadTask?
Have I unwittingly introduced some memory leaks?</p>
<p>Any comments appreciated, I'm familiar with the Swift book but find other tutorials tend to just show the use of codable or an API and do not talk through the whole structure (at least not at an appropriate level for me). The code above does work, and I'm thinking of building upon it in the future but want to follow some form of best practice (no matter how trivial).</p>
<p>Git link: <a href="https://github.com/stevencurtis/basicnetworking" rel="nofollow noreferrer">https://github.com/stevencurtis/basicnetworking</a></p>
| [] | [
{
"body": "<p>My only major observation is the choice of <code>DataManager</code>:</p>\n\n<ol>\n<li>You’ve made the <code>DataManager</code> a singleton but it has a <code>delegate</code>. That means you can effectively only have one controller acting as the delegate for the <code>DataManager</code>. If you’re only going to have one <code>delegate</code>, then <code>DataManager</code> shouldn't be a singleton (so that every controller can have its own <code>DataManager</code> with its own delegate). Or, if you want to make it a singleton, then perhaps rather than delegate pattern, I might suggest completion handler pattern (which is what I did in my code at the end of this answer).</li>\n</ol>\n\n<p>A few other observations, all fairly trivial in nature:</p>\n\n<ol start=\"2\">\n<li><p>I don’t know why <code>SitewideTableViewController</code> has <code>session</code> and <code>task</code> properties. You’re not using them and they don’t belong in view controller anyway.</p></li>\n<li><p>Even if you had a need for the <code>task</code> property, instantiating it to a blank <code>URLSessionDataTask()</code> is not a good practice.</p></li>\n<li><p>If you are going to make a view controller conform to some delegate protocol, I’d advise doing it in an extension to the class:</p>\n\n<pre><code>class SitewideTableViewController: UITableViewController { ... }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>extension SitewideTableViewController: DataManagerDelegate {\n func didDownloadBreaches() { ... }\n}\n</code></pre>\n\n<p>This keeps your code better organized. That having been said, I wouldn’t even use the delegate-protocol pattern.</p></li>\n<li><p>I’m not sure why the closure to <code>HTTPManager</code>’s <code>get</code> method is optional. You’re not going to be calling <code>get</code> unless you wanted the result passed back in the closure.</p>\n\n<pre><code>class HTTPManager {\n static let shared: HTTPManager = HTTPManager()\n\n public func get(urlString: String, completionBlock: @escaping (Data?) -> Void) {\n guard let url = URL(string: urlString) else { return }\n\n let task = URLSession.shared.dataTask(with: url) { data, _, _ in\n completionBlock(data)\n }\n task.resume()\n }\n}\n</code></pre></li>\n<li><p>Going a step further, with a completion handler closure with a type of <code>Data?</code> you only know if it succeeded or failed, but not why it failed. I’d suggest you have this pass back the <code>Data</code> if successful, but an <code>Error</code> if not successful.</p>\n\n<p>A nice approach to this is to use a <code>Result</code>-based parameter to the closure. This is included in Swift 5, but in prior versions of Swift, you can define it yourself like so:</p>\n\n<pre><code>enum Result<T, U> {\n case success(T)\n case failure(U)\n}\n</code></pre>\n\n<p>Then, rather than returning just <code>Data?</code> (where <code>nil</code> means that there was some error, but you don’t know what the issue was), you can return a <code>Result<Data, Error></code>. I’d also add some validation logic:</p>\n\n<pre><code>class HTTPManager {\n static let shared: HTTPManager = HTTPManager()\n\n enum HTTPError: Error {\n case invalidURL\n case invalidResponse(Data?, URLResponse?)\n }\n\n public func get(urlString: String, completionBlock: @escaping (Result<Data, Error>) -> Void) {\n guard let url = URL(string: urlString) else {\n completionBlock(.failure(HTTPError.invalidURL))\n return\n }\n\n let task = URLSession.shared.dataTask(with: url) { data, response, error in\n guard error == nil else {\n completionBlock(.failure(error!))\n return\n }\n\n guard\n let responseData = data,\n let httpResponse = response as? HTTPURLResponse,\n 200 ..< 300 ~= httpResponse.statusCode else {\n completionBlock(.failure(HTTPError.invalidResponse(data, response)))\n return\n }\n\n completionBlock(.success(responseData))\n }\n task.resume()\n }\n}\n</code></pre>\n\n<p>Then <code>fetchBreaches</code> can do:</p>\n\n<pre><code>func fetchBreaches() {\n HTTPManager.shared.get(urlString: baseUrl + breachesExtensionURL) { [weak self] result in\n switch result {\n case .failure(let error):\n // handle error here\n\n case .success(let data):\n // process `Data` here\n }\n }\n}\n</code></pre></li>\n<li><p>I’d suggest using <code>Date</code> types in <code>BreachModel</code> (which I’d personally just call <code>Breach</code> and make it a <code>struct</code>):</p>\n\n<pre><code>struct Breach: Codable {\n let name: String\n let title: String\n let domain: String\n var breachDate: Date? { return Breach.dateOnlyFormatter.date(from: breachDateString) }\n let breachDateString: String\n let addedDate: Date\n let modifiedDate: Date\n let pwnCount: Int\n let description: String\n\n private enum CodingKeys: String, CodingKey {\n case name = \"Name\"\n case title = \"Title\"\n case domain = \"Domain\"\n case breachDateString = \"BreachDate\"\n case addedDate = \"AddedDate\"\n case modifiedDate = \"ModifiedDate\"\n case pwnCount = \"PwnCount\"\n case description = \"Description\"\n }\n\n static let dateOnlyFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy-MM-dd\"\n return formatter\n }()\n}\n</code></pre>\n\n<p>The only trick here is that this API returns <code>BreachDate</code> as a date-only string, but <code>AddedDate</code> and <code>ModifiedDate</code> as date time strings. So, I’d use the standard ISO8601 date formatter for the decoder’s <code>dateDecodingStrategy</code> (shown below) for the latter two, but lazily decode the <code>BreachDate</code> using a date-only date formatter.</p>\n\n<p>The decoder would then look like:</p>\n\n<pre><code>let decoder = JSONDecoder()\ndecoder.dateDecodingStrategy = .formatted(ApiManager.dateTimeFormatter)\n\ndo {\n let breaches = try decoder.decode([Breach].self, from: data)\n // use `breaches` here\n} catch {\n // handle `error` here\n}\n</code></pre>\n\n<p>where</p>\n\n<pre><code>static let dateTimeFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssX\"\n formatter.timeZone = TimeZone(secondsFromGMT: 0)\n return formatter\n}()\n</code></pre>\n\n<p>But by making the model type use proper <code>Date</code> objects, then you can format them nicely in your UI without littering your UI code with logic to convert the ISO 8601 strings to dates.</p></li>\n<li><p>I’d personally pull the sorting of dates out of the <code>DataManager</code> and put it in <code>Breach.swift</code> in an extension to <code>Array</code> (or <code>RandomAccessCollection</code>):</p>\n\n<pre><code>extension RandomAccessCollection where Element == Breach {\n func sortedByName() -> [Breach] {\n return sorted { a, b in a.name < b.name }\n }\n}\n</code></pre>\n\n<p>Then, when you have your array of breaches, you can just do</p>\n\n<pre><code>self.pwned = breaches.sortedByName()\n</code></pre></li>\n<li><p>I notice that your <code>pwnedData</code> (which I might suggest renaming to <code>pwnedBreaches</code> because it’s an array of <code>Breach</code> objects, not an array of <code>Data</code> objects) is initialized as an empty <code>[BreachModel]</code> before you retrieve the data. It’s not terribly critical in this particular case, but as a general rule, it is useful to distinguish between “this property has not been set” and “it has been set but there are no records.”</p>\n\n<p>Bottom line, I’d suggest making this an optional (where <code>nil</code> means that it hasn’t been set yet, and <code>[]</code> means that it has been set to an empty array).</p></li>\n</ol>\n\n<hr>\n\n<p>So pulling that all together, we end up with something like:</p>\n\n<pre><code>// SitewideTableViewController.swift\n\nclass SitewideTableViewController: UITableViewController {\n var pwnedBreaches: [Breach]?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n ApiManager.shared.fetchBreaches { [weak self] result in\n guard let self = self else { return }\n\n switch result {\n case .failure(let error):\n print(error)\n\n case .success(let breaches):\n self.pwnedBreaches = breaches.sortedByName()\n self.tableView.reloadData()\n }\n }\n }\n}\n\n// MARK: - UITableViewDataSource\n\nextension SitewideTableViewController {\n override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return pwnedBreaches?.count ?? 0\n }\n\n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: \"Sitewide\", for: indexPath)\n cell.textLabel?.text = pwnedBreaches?[indexPath.row].name\n return cell\n }\n}\n\n// Breach.swift\n\nstruct Breach: Codable {\n let name: String\n let title: String\n let domain: String\n var breachDate: Date? { return Breach.dateOnlyFormatter.date(from: breachDateString) }\n let breachDateString: String\n let addedDate: Date\n let modifiedDate: Date\n let pwnCount: Int\n let description: String\n\n private enum CodingKeys: String, CodingKey {\n case name = \"Name\"\n case title = \"Title\"\n case domain = \"Domain\"\n case breachDateString = \"BreachDate\"\n case addedDate = \"AddedDate\"\n case modifiedDate = \"ModifiedDate\"\n case pwnCount = \"PwnCount\"\n case description = \"Description\"\n }\n\n static let dateOnlyFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy-MM-dd\"\n return formatter\n }()\n}\n\nextension RandomAccessCollection where Element == Breach {\n func sortedByName() -> [Breach] {\n return sorted { a, b in a.name < b.name }\n }\n}\n\n// Result.swift\n//\n// `Result` not needed if you are using Swift 5, as it already has defined this for us.\n\nenum Result<T, U> {\n case success(T)\n case failure(U)\n}\n\n// ApiManager.swift\n\nclass ApiManager {\n static let shared = ApiManager()\n\n let baseUrl = URL(string: \"https://haveibeenpwned.com/api/v2\")!\n let breachesExtensionURL = \"breaches\"\n\n static let dateTimeFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ssX\"\n formatter.timeZone = TimeZone(secondsFromGMT: 0)\n return formatter\n }()\n\n func fetchBreaches(completion: @escaping (Result<[Breach], Error>) -> Void) {\n let url = baseUrl.appendingPathComponent(breachesExtensionURL)\n\n HTTPManager.shared.get(url) { result in\n switch result {\n case .failure(let error):\n DispatchQueue.main.async { completion(.failure(error)) }\n\n case .success(let data):\n let decoder = JSONDecoder()\n decoder.dateDecodingStrategy = .formatted(ApiManager.dateTimeFormatter)\n\n do {\n let breaches = try decoder.decode([Breach].self, from: data)\n DispatchQueue.main.async { completion(.success(breaches)) }\n } catch {\n print(String(data: data, encoding: .utf8) ?? \"Unable to retrieve string representation\")\n DispatchQueue.main.async { completion(.failure(error)) }\n }\n }\n }\n }\n}\n\nclass HTTPManager {\n static let shared = HTTPManager()\n\n enum HTTPError: Error {\n case invalidResponse(Data?, URLResponse?)\n }\n\n public func get(_ url: URL, completionBlock: @escaping (Result<Data, Error>) -> Void) {\n let task = URLSession.shared.dataTask(with: url) { data, response, error in\n guard error == nil else {\n completionBlock(.failure(error!))\n return\n }\n\n guard\n let responseData = data,\n let httpResponse = response as? HTTPURLResponse,\n 200 ..< 300 ~= httpResponse.statusCode else {\n completionBlock(.failure(HTTPError.invalidResponse(data, response)))\n return\n }\n\n completionBlock(.success(responseData))\n }\n task.resume()\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:37:36.147",
"Id": "216836",
"ParentId": "216310",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216836",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:52:25.260",
"Id": "216310",
"Score": "5",
"Tags": [
"swift",
"ios"
],
"Title": "Networking structure for Swift iOS app"
} | 216310 |
<h2>Validate IP Address</h2>
<p>I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.</p>
<blockquote>
<p>Validate an IP address (IPv4). An address is valid if and only if it
is in the form "X.X.X.X", where each X is a number from 0 to 255.</p>
<p>For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
"123.235.153.425" are invalid IP addresses.</p>
</blockquote>
<pre><code>Examples:
"""
ip = '192.168.0.1'
output: true
ip = '0.0.0.0'
output: true
ip = '123.24.59.99'
output: true
ip = '192.168.123.456'
output: false
"""
def validateIP(ip):
#split them by '.' , and store them in an array
#check the array if the length is 4 length
arr = ip.split('.')
if len(arr) != 4:
return False
#0 check for special edge cases when non-digit
#1. check if they are digit,
#2. check if check the integer is between 0 and 255
for part in arr:
if len(part) > 1:
if part[0] == '0':
return False
if not part.isdigit():
return False
digit = int(part)
if digit < 0 or digit > 255:
return False
return True
#case#0
ip0="08.0.0.0" # False
test0= validateIP(ip0)
print(test0)
#case#1
ip1 = "192.168.0.1"
test1 = validateIP(ip1)
print(test1)
#case#2
ip2 = '0.0.0.0'
test2 = validateIP(ip2)
print(test2)
#case#3
ip3 = '123.24.59.99'
test3 = validateIP(ip3)
print(test3)
#case#4
ip4 = '192.168.123.456'
test4 = validateIP(ip4)
print(test4)
#case5
ip5 = "255.255.255.255"
test5 = validateIP(ip5)
print(test5)
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>A doc string reads nicer then # blockcomments</p>\n<p>Consider making a doc string of that function, so you can do <code>help(validate_ip)</code> and it will print the doc string in the interpreter.</p>\n</li>\n<li><p>Adhere to PEP8</p>\n<p>Functions and variables should be <code>snake_case</code> ie <code>def validate_ip(ip):</code></p>\n</li>\n<li><p>You could use the <code>all</code> keyword to check if each part is correct; this will return <code>False</code> for the first failure.</p>\n</li>\n<li><p>Make actual tests that ensure validity</p>\n<p>Instead of printing tests, make actual tests either with <code>assert</code> or the modules <code>doctest</code> or <code>unittest</code>.</p>\n</li>\n<li><p>There is a module that does this for you</p>\n<p>Python is often described as "batteries included", and here you could use the <code>ipaddress module</code>, which will validate an IP when you create the <code>IPv4Adress</code> object.</p>\n</li>\n</ol>\n<h1>Reworked code</h1>\n<pre><code>import doctest\n\ndef validate_ip(ip):\n """\n Checks if the ip address is valid\n args:\n ip (str): The IP address\n ret:\n A boolean: True for a a valid IP\n \n >>> validate_ip('08.0.0.0')\n False\n\n >>> validate_ip('192.169.0.1')\n True\n\n >>> validate_ip('0.0.0.0')\n True\n\n >>> validate_ip('192.168.123.456') \n False\n\n >>> validate_ip('oooh.0.0.1')\n False\n """\n ranges = ip.split('.')\n return len(ranges) == 4 \\\n and all(\n r.isdigit() and # Check for digits\n int(r) in range(0, 256) and # Check in range of 0-255\n (r[0] != "0" or len(r) == 1) # Check for leading zero's\n for r in ranges\n )\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n<h1>ipaddress module</h1>\n<pre><code>from ipaddress import IPv4Address\n\ndef is_valid_ip(ip):\n try:\n IPv4Address(ip)\n return True\n except ValueError:\n return False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:04:25.373",
"Id": "216317",
"ParentId": "216311",
"Score": "8"
}
},
{
"body": "<blockquote>\n<pre><code>def validateIP(ip):\n</code></pre>\n</blockquote>\n\n<p>I would expect a name starting <code>is</code> (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. <code>is_valid_IPv4_address</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> #split them by '.' , and store them in an array\n #check the array if the length is 4 length\n arr = ip.split('.')\n if len(arr) != 4:\n return False\n</code></pre>\n</blockquote>\n\n<p>The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> #0 check for special edge cases when non-digit\n #1. check if they are digit, \n #2. check if check the integer is between 0 and 255\n\n for part in arr:\n .. various conditions which return False\n return True\n</code></pre>\n</blockquote>\n\n<p>IMO it would be more Pythonic to use <code>all</code>: I would boil the whole function down to</p>\n\n<pre><code> parts = ip.split('.')\n return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> if len(part) > 1:\n if part[0] == '0':\n return False\n</code></pre>\n</blockquote>\n\n<p>This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if not part.isdigit():\n return False\n</code></pre>\n</blockquote>\n\n<p>This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused <code>validateIP</code> to throw an exception).</p>\n\n<p>What is the expected output for these test cases?</p>\n\n<pre><code>¹.¹.¹.¹\n١.١.١.١\n...\n①.①.①.①\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:30:28.027",
"Id": "419242",
"Score": "0",
"body": "Ah, I see. Good to know, I always thought `str.isdigit` would only return true for `1234567890`. Need to fix an answer I just wrote on another question..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:53:47.583",
"Id": "216319",
"ParentId": "216311",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:57:46.653",
"Id": "216311",
"Score": "7",
"Tags": [
"python",
"interview-questions",
"validation",
"ip-address"
],
"Title": "Validate IP4 address"
} | 216311 |
<p>I tried to solve a merge two sorted list problem in leetcodes:</p>
<blockquote>
<p>Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.</p>
<h3>Example:</h3>
<pre><code>Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
</code></pre>
</blockquote>
<pre><code>class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
Plan:
Compare l1 and l2 and merge the remainders
"""
l3_head = ListNode(0)
l3_cur = l3_head
while l1 and l2: #assert both exist
if l2.val < l1.val:
l3_cur.next = l2 #build l3's node
l2 = l2.next #this is i++
else:
l3_cur.next = l1
l1 = l1.next
l3_cur = l3_cur.next #find the next to build
if l1:
l3_cur.next = l1
if l2:
l3_cur.next = l2
return l3_head.next
</code></pre>
<p>I assumed this is a decent solution but got:</p>
<blockquote>
<p>Runtime: 56 ms, faster than 23.98% of Python3 online submissions for Merge Two Sorted Lists.</p>
<p>Memory Usage: 13.1 MB, less than 5.06% of Python3 online submissions for Merge Two Sorted Lists.</p>
</blockquote>
<p>How could I improve my solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:04:48.150",
"Id": "418554",
"Score": "0",
"body": "I suppose they are not using the 3rd list, in the end, you don't need that since instead of creating new nodes you are re-assigning values of old ones"
}
] | [
{
"body": "<p>You shouldn't need to create a HeadNode, just use one of the ones given to you. Right now you relink every single item. But if one list has many sequential values, you could save time by just advancing to the tail. Also, right now you are checking 2 conditions in every loop even though only 1 changes.</p>\n\n<p>You could try something like this: (after setting cur to the minimum node):</p>\n\n<pre><code>while True:\n while cur.next and cur.next.val <= l2.val:\n cur = cur.next\n cur.next = l2\n if not cur.next: break\n\n while cur.next and l2.val <= l1.val:\n cur = cur.next\n cur.next = l1\n if not cur.next: break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T11:39:10.357",
"Id": "418561",
"Score": "0",
"body": "If you replaced `->` with `.`, `&&` with `and` and `!` with `not `, it would even be valid Python code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:43:00.077",
"Id": "418591",
"Score": "1",
"body": "When you spend 90% of your day in `C`, it's hard not to let its syntax creep into your pseudocode :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T05:45:30.100",
"Id": "216314",
"ParentId": "216312",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T05:01:41.603",
"Id": "216312",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Splice-merge two sorted lists in Python"
} | 216312 |
<p>I'm currently in the process of refactoring an old poker game which violates many of the SOLID principles. </p>
<p>I was trying to use the TDD approach to refactoring and I found myself having to hard code a player's hand every time I wrote a unit test for a specific poker hand check.</p>
<p>For example, here are the unit tests for a one pair poker hand check:</p>
<pre><code> [Test]
public void OnePair_IsLowPair_ReturnsTrue()
{
SuperCard[] testHand =
{
new CardClub(Rank.Ace),
new CardSpade(Rank.Ace),
new CardDiamond(Rank.Five),
new CardHeart(Rank.Jack),
new CardClub(Rank.Three)
};
bool result = PokerHandEvaluator.OnePair(testHand);
Assert.That(result == true);
}
[Test]
public void OnePair_IsLowerMiddlePair_ReturnsTrue()
{
SuperCard[] testHand =
{
new CardClub(Rank.Eight),
new CardSpade(Rank.Ace),
new CardDiamond(Rank.Ace),
new CardHeart(Rank.Jack),
new CardClub(Rank.Three)
};
bool result = PokerHandEvaluator.OnePair(testHand);
Assert.That(result == true);
}
[Test]
public void OnePair_IsHigherMiddlePair_ReturnsTrue()
{
SuperCard[] testHand =
{
new CardClub(Rank.Jack),
new CardSpade(Rank.Queen),
new CardDiamond(Rank.Ace),
new CardHeart(Rank.Ace),
new CardClub(Rank.Three)
};
bool result = PokerHandEvaluator.OnePair(testHand);
Assert.That(result == true);
}
[Test]
public void OnePair_IsHighPair_ReturnsTrue()
{
SuperCard[] testHand =
{
new CardClub(Rank.Jack),
new CardSpade(Rank.Deuce),
new CardDiamond(Rank.Six),
new CardHeart(Rank.Ace),
new CardClub(Rank.Ace)
};
bool result = PokerHandEvaluator.OnePair(testHand);
Assert.That(result == true);
}
</code></pre>
<p>This is what the class diagram (at the project's current stage) looks like:
<a href="https://i.stack.imgur.com/Y4f2w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y4f2w.png" alt="enter image description here"></a></p>
<p>My question is how I should go about extracting a method (or methods) out of the testHand initialization. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T05:51:34.333",
"Id": "418520",
"Score": "1",
"body": "Maybe make a \"CreateHand()\" function that takes a string like \"AcAs5dJh3c\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T05:57:44.770",
"Id": "418521",
"Score": "0",
"body": "A CreateHand() is essentially what I'm trying to go for here but I'm not sure how to implement your idea. Can you please share some pseudocode or code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:55:29.667",
"Id": "418628",
"Score": "2",
"body": "To those who have put this question on hold, could you clarify how it lacks concrete context?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:02:23.480",
"Id": "418717",
"Score": "2",
"body": "@AselS My experience as a moderator is that that reason is a bit abused, I don't see a reason for why it was put on hold for that reason so I have reopened it. The only possible explanation would be that people would like to see more of your PokerHandEvaluator implementation, but to me it's clear that it's your *tests* that are up for review and not the code that you are *testing*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:01:09.227",
"Id": "418730",
"Score": "2",
"body": "Thank you for clarifying Simon. I would have happily included more code if the users who marked the question as on hold, for lack of context, would have clarified which aspects of the code they wanted to see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T06:16:23.223",
"Id": "418768",
"Score": "0",
"body": "It's not allowed to add the improved/reviewed code to the question so I've rolledback your last edit. What you can do instead is to post a self-answer if you want to share your new solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T08:18:09.300",
"Id": "418770",
"Score": "0",
"body": "Should I post a self-answer even though the edit I made wasn't a solution? It was me documenting my attempt at Simon's suggestion. Also, you removed the beginner tag I added as well, is that also against the rules? I'm just curious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:20:53.423",
"Id": "418772",
"Score": "0",
"body": "@AselS I re-added the beginner tag, as a rollback was done it disappeared with the rollback. I would recommend that you post a [*new follow-up question*](https://codereview.meta.stackexchange.com/q/1065/31562) once you have incorporated suggestions from the feedback you got here and want another review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:21:15.840",
"Id": "418773",
"Score": "0",
"body": "Nope, removing the [tag:beginner] tag was a rollback-_accident_ and I haven't noticed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:56:39.103",
"Id": "418831",
"Score": "0",
"body": "Okay, thank you for clarifying on that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T01:40:46.697",
"Id": "418864",
"Score": "0",
"body": "I decided to add a self-answer following t3chb0ts suggestion (for which the rationale is explained in the self-answer). It contains my attempt at your suggestion Simon."
}
] | [
{
"body": "<p>Not sure if there is any advantage of having 4 classes (<code>CardClub, CardSpade, CardHeart, CardDiamond</code>) with one property Rank, </p>\n\n<p>compared to </p>\n\n<p>a <code>Card</code> class with 2 properties, <code>Suit (of Type Suit enum) and Rank (of Type Rank enum)</code>.</p>\n\n<p>Have a <code>CardFactory</code> class, that has a static method </p>\n\n<pre><code>Card CreateCard(Suit suit, Rank rank) => new Card(suit, rank);\n</code></pre>\n\n<p>We could have a <code>HandTestDataGenerator</code> class with a static method for generating test hands:</p>\n\n<pre><code>public static IList<Card> CreateCards(Dictionary<Suit, List<Rank> cards) =>\n cards.SelectMany(x => x.Value.Select(rank => new Card(x.Key, rank));\n</code></pre>\n\n<p>Now for each test data, create a static method in <code>HandTestDataGenerator</code> like:</p>\n\n<pre><code>IList<Card> GenerateLowPairHand()\n{\n var lowPairHand = new Dictionary<Suit, List<Rank>>();\n lowPairHand.Add(Suit.Club, new List<Rank>{ Rank.Ace, Rank.Three });\n //Add other suits and ranks here\n return CreateCards(lowPairHand);\n}\n</code></pre>\n\n<p>From TestMethod, call </p>\n\n<p><code>SuperCard[] testHand = HandTestDataGenerator.GenerateLowPairHand();</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:58:45.327",
"Id": "418629",
"Score": "0",
"body": "I couldn't follow the Dictionary implementation but creating a class with static methods for each test data seems like a good approach. As to why it had four classes for cards with rank, it was a design constraint on an assignment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T22:05:31.030",
"Id": "418631",
"Score": "0",
"body": "For each card, you need a suit and rank. for your testdata you could have Club-Ace and Club-Three; hence thought of having a dictionary with Suit as Key and Ranks as a List."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:08:04.437",
"Id": "418718",
"Score": "0",
"body": "I agree about having one card class with two properties, I disagree about having one static method for each test-data."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:25:42.440",
"Id": "216367",
"ParentId": "216313",
"Score": "0"
}
},
{
"body": "<p>One thing that would help with reducing duplication is to use <a href=\"https://github.com/nunit/docs/wiki/Parameterized-Tests\" rel=\"nofollow noreferrer\">parameterized tests</a>.</p>\n\n<p>Additionally, you might want to have a enum with the different hand types instead of - or in addition to - having one method for each hand type, such as your current <code>PokerHandEvaluator.OnePair</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:49:13.827",
"Id": "418732",
"Score": "0",
"body": "I like this idea but I'm having some difficulty passing in my arrays as parameters. I tried to do [TestCase(new SuperCard[] {new CardClub(Rank.Ace)...} ) ] but I'm getting an error saying that the attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type. How would you construct a single OnePair test with several test cases that accept SuperCard array as parameters? I should mention that I recently got into unit testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:50:37.537",
"Id": "418733",
"Score": "0",
"body": "Also, could you elaborate on why you disagree with Matt's static idea method? Is it because that would also mean repetition? And could you clarify what you mean by having an enum with different hand types? Since I already have a PokerHand class with the various hand types, do you mean to say that I should have the variants of them as well? For example, OneHandLow, OneHandHigh, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:31:41.697",
"Id": "418742",
"Score": "0",
"body": "@AselS You can specify test data other ways: https://github.com/nunit/docs/wiki/TestCaseSource-Attribute . I dislike Matt's static method because I think a parameterized test is better, and because you would need one static method for every test. With different hand types I mean `OnePair`, `TwoPair`, `ThreeOfAKind`, etc. and have one method that returns which hand it is, see `PokerHandType` in [my old poker hand evaluator (Java)](https://codereview.stackexchange.com/q/36916/31562)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:48:38.363",
"Id": "418761",
"Score": "0",
"body": "Thank you for clarifying. I managed to implement the TestCaseSource after looking at some other resources and I edited my post to reflect my attempt. Could you please take a look at it and see whether that is what you had in mind? If not, what would you change further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:54:11.277",
"Id": "418763",
"Score": "0",
"body": "Just to address the poker hand types, I do have a class called PokerHand (which is just an enum) that holds those types, and I do have a method called EvaluatePokerHand() in my PokerHandEvaluator class that returns the enum equivalent of the hand (these are reflected in the class diagram). I have a handful of tests for this method as well, that has the same problem with initializing, which I've posted a link too in my edit."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:07:11.413",
"Id": "216435",
"ParentId": "216313",
"Score": "1"
}
},
{
"body": "<p>IMO I'd join all of your tests into one. <a href=\"https://stackoverflow.com/a/9948241\">And just rotate through them</a>.</p>\n\n<pre><code>private static void Rotate<T>(List<T> list) {\n T first = list[0];\n list.RemoveAt(0);\n list.Add(first);\n}\n\n[Test]\npublic void TestOnePairs()\n{\n List<SuperCard> testHand = new List<SuperCard> {\n new CardClub(Rank.Ace),\n new CardSpade(Rank.Ace),\n new CardDiamond(Rank.Two),\n new CardHeart(Rank.Three),\n new CardClub(Rank.Four)\n };\n\n for (let i=0; i < 5; i++) {\n Assert.That(PokerHandEvaluator.OnePair(testHand.ToArray()));\n Rotate(testHand);\n }\n}\n</code></pre>\n\n<p>If this were Python I'd suggest changing <code>List<SuperCard></code> to <code>List<Tuple<Suit, Rank>></code>. However IIRC C# doesn't like Tuples too much. And so you may want to make them <code>List<Card></code>, but pass both of the enums to the card at instantiation.</p>\n\n<hr>\n\n<p>I should note that this doesn't test all combinations that the pairs can be. And so you should really use something like Pythons <a href=\"https://docs.python.org/3.7/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools.combinations</code></a>.</p>\n\n<p>This is as the following pseudocode of OnePair would be incorrect, but would pass your tests.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def OnePair(values):\n prev = values[-1]\n for curr in values:\n if curr.rank == prev.rank:\n return True\n prev = curr\n return False\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:14:36.533",
"Id": "418737",
"Score": "0",
"body": "I like this idea because it would solve the variant test cases on One Pairs (as well as a few other hands) but that would still leave me with several tests that still have to initialize a unique SuperCard array. Is there a way to solve that issue as well using this method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:16:27.727",
"Id": "418738",
"Score": "1",
"body": "@AselS For me to comment on these other tests, you'd have to provide them to us. And so you'd need to ask a new question with these tests in it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:05:02.503",
"Id": "216448",
"ParentId": "216313",
"Score": "1"
}
},
{
"body": "<p>I decided to post a self-answer as suggested by t3chbot because the following code example is just an attempt at following Simon's suggestion; I haven't fully incorporated the code as I have not managed to resolve my original question. I hope this is okay. </p>\n\n<pre><code>public class OnePairTestDataSource : IEnumerable\n {\n public IEnumerator GetEnumerator()\n {\n yield return new SuperCard[]\n {\n new CardClub(Rank.Ace),\n new CardSpade(Rank.Ace),\n new CardDiamond(Rank.Five),\n new CardHeart(Rank.Jack),\n new CardClub(Rank.Three)\n };\n\n ...\n }\n\n [TestCaseSource(typeof(OnePairTestDataSource))]\n public void OnePair_IsOnePair_ReturnsTrue(SuperCard[] pTestHand)\n {\n bool result = PokerHandEvaluator.OnePair(pTestHand);\n Assert.That(result == true);\n }\n</code></pre>\n\n<p>Even though I like Simon's suggestion of using parameterized tests, I noticed that I still have to do some repetition in order to initialize an array that I want to test. Is this what you had in mind Simon? If not could you clarify with a code example perhaps?</p>\n\n<hr>\n\n<p>I tried using a parameterized test source as well. Here is another implementation which I like better than the one above and my original one, but still leaves me with the same problem:</p>\n\n<pre><code>static IEnumerable<SuperCard[]> GetTestHand(PokerHand pPokerHand)\n{\n if (pPokerHand == PokerHand.OnePair)\n {\n yield return new SuperCard[]\n {\n new CardClub(Rank.Ace),\n new CardSpade(Rank.Ace),\n new CardDiamond(Rank.Five),\n new CardHeart(Rank.Jack),\n new CardClub(Rank.Three)\n };\n\n ...\n }\n}\n\n[TestCaseSource(nameof(GetTestHand), new object[] { PokerHand.OnePair })]\npublic void OnePair_IsOnePair_ReturnsTrue(SuperCard[] pTestHand)\n{\n bool result = PokerHandEvaluator.OnePair(pTestHand);\n Assert.That(result == true);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T01:38:14.537",
"Id": "216514",
"ParentId": "216313",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216435",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T05:39:38.600",
"Id": "216313",
"Score": "4",
"Tags": [
"c#",
"beginner",
"unit-testing",
"nunit"
],
"Title": "Poker Game: Unit testing different poker hands without violating DRY principles"
} | 216313 |
<p>I have this update method which decides whether to update or recreate(same as update but resets the approval_status and create_date) of the building_approval object. I have the <strong>on_progress?</strong> method on building_approval class to check whether it needs to be updated or recreated so no flags are being passed from the view, the problem is I use this <strong>on_progress?</strong> method on view to change some minor UI in the form, so it is being called twice (once in the view for UI and once in the update method in the controller for deciding whether to update or recreate). I have considered passing to_update param from view to the controller so I wouldn't have to run <strong>on_progress?</strong> method twice but it makes my code look ugly</p>
<p>tldr:</p>
<pre><code>def update
return render :edit unless @building_approval.update(param_building_approvals)
if(@building_approval.on_progress?)
@building_approval.reapply
@building_approval.send_reapply_mail(current_member)
notice = @building_approval.has_contract? ? 'messages.warning.building_approval_has_contract' : 'messages.info.approval_reapplied'
else
@building_approval.after_save_by_apply()
@building_approval.send_apply_mail(current_member)
notice = 'messages.info.updated'
end
redirect_to prospective_customer_building_approval_path(@customer.id, @building_approval.id),
notice: t(notice, :name => BuildingApproval.model_name.human)
end
</code></pre>
<p>or</p>
<pre><code>def update
return render :edit unless @building_approval.update(param_building_approvals)
if(params[:to_update] == "false")
@building_approval.reapply
@building_approval.send_reapply_mail(current_member)
notice = @building_approval.has_contract? ? 'messages.warning.building_approval_has_contract' : 'messages.info.approval_reapplied'
else
@building_approval.after_save_by_apply()
@building_approval.send_apply_mail(current_member)
notice = 'messages.info.updated'
end
redirect_to prospective_customer_building_approval_path(@customer.id, @building_approval.id),
notice: t(notice, :name => BuildingApproval.model_name.human)
end
</code></pre>
<p>which one is better ? the first one's cons is it uses <strong>on_progress?</strong> method twice(in view and in controller) , the cons in the second one is it uses on_progress? once but I need to pass hidden_field to_update params to controller and make ugly if statements</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T03:06:24.473",
"Id": "424996",
"Score": "0",
"body": "Any reason not to call that method twice? is it time consuming? you could save the result on a variable if you don't want to call it twice but if it makes sense to call the method twice then I don't see the problem. Adding a hidden field looks like a hack for a problem you don't actually have."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:58:31.640",
"Id": "216315",
"Score": "1",
"Tags": [
"ruby",
"comparative-review",
"ruby-on-rails",
"mvc"
],
"Title": "Rails dynamically changing parts of view but using the same method in controller"
} | 216315 |
<p>I've tried to implement integer partition algorithm as described in blogpost below (author implemented it in Python):
<a href="http://jeromekelleher.net/generating-integer-partitions.html" rel="nofollow noreferrer">Generating integer partitions</a></p>
<p>I'm still trying to learn best practices in producing clean code. I would also be thankful for any performance tips.</p>
<p>My code:</p>
<pre><code>struct NumberPartition {
a: Vec<i32>,
k: i32,
y: i32,
x: i32,
l: i32,
}
impl NumberPartition {
pub fn new(n: i32) -> Self {
NumberPartition {
a: vec![0; (n + 1) as usize],
k: 1,
y: n - 1,
x: 0,
l: 0
}
}
fn partition(&mut self) -> Option<Vec<Vec<i32>>> {
let mut buf: Vec<Vec<i32>> = Vec::new();
while self.k != 0 {
self.x = self.a[(self.k - 1) as usize] + 1;
self.k -= 1;
while 2 * self.x <= self.y {
self.a[self.k as usize] = self.x;
self.y -= self.x;
self.k += 1;
}
self.l = self.k + 1;
while self.x <= self.y {
self.a[self.k as usize] = self.x;
self.a[self.l as usize] = self.y;
buf.push(self.a[..(self.k + 2) as usize].to_vec());
self.x += 1;
self.y -= 1;
}
self.a[self.k as usize] = self.x + self.y;
self.y = self.x + self.y - 1;
buf.push(self.a[..(self.k + 1) as usize].to_vec());
}
Some(buf)
}
}
fn main() {
let b = NumberPartition::new(6).partition();
for i in b.iter() {
println!("{:?}", i);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:12:04.390",
"Id": "418546",
"Score": "1",
"body": "a double yield is painful to implement as an iterator: https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=ff3a2402cbc8155a6b90bdbbd18043fe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T09:34:30.620",
"Id": "418552",
"Score": "0",
"body": "@Stargateur yes indeed, i tried it and had to think of something else. Your code is great! Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:03:47.533",
"Id": "418604",
"Score": "1",
"body": "Various small changes on that iterator: https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=c56efff9af698cb04a54fac3f1cb01c5"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:06:15.023",
"Id": "418605",
"Score": "1",
"body": "Since partitions only deal with positive integers, you should probably use an unsigned type like `u32` or `u64`, and also add a check against `NumberPartiton::new(0)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:02:43.063",
"Id": "419166",
"Score": "1",
"body": "I tried to simplify it further: https://play.integer32.com/?version=stable&mode=release&edition=2018&gist=35e5b00918ef0ccbc4b74d02f79cd545"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:03:34.437",
"Id": "419167",
"Score": "0",
"body": "For what it's worth, I think the performance of internal iteration could be improved here by implementing `try_fold` on the iterator. But it's already really fast."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:27:17.290",
"Id": "216318",
"Score": "6",
"Tags": [
"performance",
"beginner",
"rust",
"iterator"
],
"Title": "Generating integer partitions"
} | 216318 |
<p>I have to create a client-server JavaFX application using MVC which does many operations consisting mainly in messages exchange.
I'd like to know if this way to handle client acceptance and client requests is good or not.</p>
<pre><code>public class ServerOperations {
// other code
public void serverConnection() {
Runnable runnable = new AcceptingClients();
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.start();
}
public class AcceptingClients extends Thread {
static final int PORT = 9090;
private Socket socket = null;
ServerSocket serverSocket = null;
@Override
public void run() {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
while (true) {
try {
socket = serverSocket.accept();
// other code
Runnable runnable = new ClientRequests(socket, inputStream, outputStream);
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.start();
} catch (IOException e) {
System.out.println("I/O error: " + e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServerRequests.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class ClientRequest extends Thread {
// other code
public ClientRequest(Socket socket) throws ClassNotFoundException {
// other code
}
@Override
public void run() {
// handling client requests
}
// other code
}
</code></pre>
<p>I want to focus on few parts of this class ServerOperations: </p>
<p>1) Is good to put all those thread in one class for accepting clients and handling requests or is it bad coding (if not, what a good alternative would be)? Using this way may give me problems if I have a lot of clients connected? </p>
<p>2) If i don't extend the class AcceptingClients with Thread I have problem with JavaFX UI thread, I can't add text in TextArea for example etc. I can't understand from where this interference come from, not even using Platform.runLater() makes me append text or interact with my controller's components.</p>
<p>3) To let everything run I have a method in my model where this method serverConnection() is called. When the Server class starts, the first thing it does is to open the server UI and run this method called from the model. Good or not?!
Note: Server class is different from ServerOperations. ServerOperations is a separate classe which just handle client acceptance and requests.</p>
| [] | [
{
"body": "<p>Note: \nIt is easier to provide a more complete answer when faced with a complete problem. There are several <code>//other code</code> areas that you may be omitting for the sake of brevity, but these could very well be providing more context to the review, and their presence could likely improve the quality of answers received. </p>\n\n<p>I would recommend <strong>posting complete code</strong> as is, <strong>using a more descriptive place holder</strong> of the logic there than <code>//other code</code> and/or perhaps an <strong>explanation of why the missing code is considered irrelevant</strong> to the reviewer</p>\n\n<p>/rant</p>\n\n<hr>\n\n<p><strong>Request for clarification</strong>\nI noticed that in your <code>AcceptingClients</code> Thread you make a call to <code>new ClientRequests(socket, inputStream, outputStream)</code>. However, you also define the similarly named <code>ClientRequest</code> with constructor <code>public ClientRequest(Socket socket)</code>. Are these meant to be the same class, just with the latter being un-implemented? or are these differing classes, in which case I would recommend better names\n<hr>\nOn to your questions 3:</p>\n\n<blockquote>\n <p>1) Is it good to put all those thread in one class</p>\n</blockquote>\n\n<p>Having a class ServerOperations containing each of your Operation threads IMO is actually good design (so long as each operation is reasonably simple). </p>\n\n<p>When it comes to denser and thus more complex logic, I would instead opt for grouping each Operation class into a subdirectory /operations and using ServerOperations like a repository; a layer for accessing your collection of operations, something like ServerOperations.getOperationThread(\"acceptClients\").</p>\n\n<p>The benefit here is readability and maintainability. IMHO It is easier to understand and thus maintain the individual processes if they are in separate class files, but this would only be recommended for a collection of non-trivial Operations. If they are super simple, feel free to group them up like this! </p>\n\n<blockquote>\n <p>Using this way may give me problems if I have a lot of clients connected?</p>\n</blockquote>\n\n<p>Short answer, yes. Based on the present code, I would highly recommend using non-daemon threads for these purposes. <a href=\"https://stackoverflow.com/questions/2213340/what-is-a-daemon-thread-in-java\">This question on SO has a TON of discourse on daemon threads</a> but IMO the most relevant information therein is :</p>\n\n<blockquote>\n <p>Daemon threads are service providers for user threads running in the same process.</p>\n</blockquote>\n\n<p>This means any Thread with setDaemon(true) should be considered a service, something that is running in the background and waiting to service a request from another, non-daemon thread. This leads the most annoying impact:</p>\n\n<blockquote>\n <p>Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.</p>\n</blockquote>\n\n<p>Normally, if your program were ending, it would hang on exiting the JVM until all user threads are complete. As these threads are daemons, the JVM will drop these Threads and exit immediately. This means that in the edge case of a request still processing on shutdown, you will lose requests processing in these daemons.</p>\n\n<p>Without information on how this daemon is used in these <code>//other code</code> sections, I can only conclude that you might not need to use daemonThreads</p>\n\n<hr>\n\n<blockquote>\n <p>2) If i don't extend the class AcceptingClients with Thread I have problem with JavaFX UI thread</p>\n</blockquote>\n\n<p>I am unfamiliar with JavaFX so I won't offer advice I am unqualified to give</p>\n\n<hr>\n\n<blockquote>\n <p>3) To let everything run I have a method in my model where this method serverConnection() is called. [..] Good or not?!</p>\n</blockquote>\n\n<p>If I am understanding this correctly, you are asking if it is good to call this method from the Model at creation (IMO that isn't a bad choice in the general sense). This question is incredibly difficult to answer without having the Model code available for context. </p>\n\n<p>IMHO, this last is a question belonging in a review of the Model, or of the project as a whole, as without seeing the complete context of HOW this method is used, any feedback would basically be personal opinions about the proper use of MVC models</p>\n\n<p>Hope some if not all of this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T15:56:12.140",
"Id": "418888",
"Score": "0",
"body": "Thank you so much for answering, you've been very helpful! I'm sorry for all those //other code but this is part of a school project and I can't post the whole code since it's easy to reach this post and copy!\nThe public ClientRequest(Socket socket) it's a mistake, I think I deleted something while copy/paste. They are the same class anyway!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:53:07.000",
"Id": "216490",
"ParentId": "216324",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216490",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T10:31:52.337",
"Id": "216324",
"Score": "1",
"Tags": [
"java",
"multithreading",
"thread-safety",
"javafx"
],
"Title": "Multithreading to allow multiple clients on to a server and client requests handling"
} | 216324 |
<p>Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.</p>
<p>For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".</p>
<p>I found few solutions online <a href="https://codereview.stackexchange.com/questions/96632/finding-longest-substring-containing-k-distinct-characters">like</a>. I felt they were bit too complex. I have tried to simply the solution. But it still lacks readability. How can i further improve?</p>
<pre><code>public class DailyCodingProblem13 {
public static void main(String args[]) {
String s = "abcba";
int k = 2;
int result = solution(s, k);
System.out.println(result);
s = "aabacbebebe";
k = 2;
result = solution(s, k);
System.out.println(result);
s = "aabbcc";
k = 3;
result = solution(s, k);
System.out.println(result);
}
static int solution(String s, int k) {
int n = s.length();
int max = 0;
String maxLengthString = null;
if (n == 0 || k == 0) {
return max;
} else {
StringBuilder window = new StringBuilder();
Set<Character> set = new HashSet<>();
for (int i = 0; i < n; i++) {
Character ch = s.charAt(i);
// If
if (set.size() == k && !set.contains(ch)) {
// Fetch the last index of the first character at window. Discard the string
// before the last index.
window = new StringBuilder(
window.substring(window.lastIndexOf(Character.toString(window.charAt(0))) + 1));
set.clear();
for (int j = 0; j < window.length(); j++) {
set.add(window.charAt(j));
}
}
set.add(ch);
window.append(ch);
if (window.length() > max) {
max = window.length();
maxLengthString = window.toString();
}
}
}
System.out.println("String with max length is " + maxLengthString.toString());
return max;
}
}
</code></pre>
<p>Note: This is my huumble effort to create a opensource project with best solutions for leetcode problems. This is not for increasing my score in any coding challenges.</p>
<p><a href="https://github.com/macleanpinto/AlgoPractice" rel="nofollow noreferrer">Link to my project.</a></p>
| [] | [
{
"body": "<ul>\n<li><p>Necessary imports are missing.</p></li>\n<li><p>The prefix is discarded too aggressively. In a string <code>abaacccc</code> the entire <code>abaa</code> is discarded, and the result becomes 4 instead of 6.</p></li>\n<li><p>Representing window as a <code>StringBuilder</code> seems excessive. A pair of indices into the original string is enough.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:57:37.420",
"Id": "216356",
"ParentId": "216327",
"Score": "2"
}
},
{
"body": "<p>You've taken away a little bit of readability by creating a variable 'n' for the Strings length.</p>\n\n<p>Either name it sLength, or better yet just use s.length().</p>\n\n<p>This comment does not add any value: \n<code>// If</code></p>\n\n<p>You don't need the variable 'max', since it's just a reference to maxLengthString.length(). (Personally I'd return the longest String. But maybe the challenge said otherwise).</p>\n\n<p>You don't need to toString() maxLengthString, since it's already a String.</p>\n\n<p>Instead of using a main method, you could have Unit Tests.</p>\n\n<p>Lastly Eclipse gives me a warning about array brackets being at an illegal position in your Main method.\nIt should be <code>main(String[] args)</code> instead of <code>main(String args[])</code></p>\n\n<pre><code>@Test\npublic void test()\n{\n String s = \"abcba\";\n int k = 2;\n assertEquals(3, solution(s, k));\n\n s = \"aabacbebebe\";\n k = 2;\n assertEquals(6, solution(s, k));\n\n s = \"aabbcc\";\n k = 3;\n assertEquals(6, solution(s, k));\n\n s = \"\";\n k = 3;\n assertEquals(0, solution(s, k));\n}\n\nstatic int solution(String s, int k) \n{\n String maxLengthString = \"\";\n\n if (s.length() != 0 && k != 0) \n {\n StringBuilder window = new StringBuilder();\n Set<Character> set = new HashSet<>();\n for (int i = 0; i < s.length(); i++) \n {\n char ch = s.charAt(i);\n if (set.size() == k && !set.contains(ch)) \n {\n // Fetch the last index of the first character at window. Discard the string\n // before the last index.\n window = new StringBuilder(\n window.substring(window.lastIndexOf(Character.toString(window.charAt(0))) + 1));\n set.clear();\n for (int j = 0; j < window.length(); j++) \n {\n set.add(window.charAt(j));\n }\n }\n set.add(ch);\n window.append(ch);\n if (window.length() > maxLengthString.length()) \n {\n maxLengthString = window.toString();\n }\n }\n }\n\n System.out.println(\"String with max length is \" + maxLengthString.toString());\n return maxLengthString.length();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:58:33.553",
"Id": "216357",
"ParentId": "216327",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T11:46:40.810",
"Id": "216327",
"Score": "1",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters"
} | 216327 |
<p>I'm looking for an optimum way to join two Dataframes where the same record exists in both. Examples would be:</p>
<pre><code>dat1 = pd.DataFrame({"id": [1,2,3,4,5], "dat1": [34,56,57,45,23]})
dat2 = pd.DataFrame({"id": [2,3,4], "dat2": [19,19,20]})
dat1
id dat1
0 1 34
1 2 56
2 3 57
3 4 45
4 5 23
dat2
id dat2
0 2 19
1 3 19
2 4 20
</code></pre>
<p>With the aim being to create overall_data:</p>
<pre><code>overall_data
id dat1 dat2
0 2 56 19
1 3 57 19
2 4 45 20
</code></pre>
<p>At the moment my method is:</p>
<pre><code>dat3 = dat1['id'].isin(dat2['id'])
dat3 = pd.Dataframe(dat3)
dat3.columns = ['bool']
dat4 = dat1.join(dat3)
overall_data = dat4(dat4['bool'] == True)
</code></pre>
<p>Though this feels very messy. Is there a nicer way to do this?</p>
| [] | [
{
"body": "<p>This is the textbook example of an inner join. The most canonical way to have your <code>id</code> columns being used for the matching, set them as an index first (here using <code>inplace</code> operations to save on extra variable names; depending on your use, you might prefer new copies instead):</p>\n\n<pre><code>dat1.set_index('id', inplace=True)\ndat2.set_index('id', inplace=True)\n</code></pre>\n\n<p>Then, the whole operation becomes this simple <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index\" rel=\"nofollow noreferrer\">join on index</a>:</p>\n\n<pre><code>>>> overall_data = dat1.join(dat2, how='inner')\n>>> overall_data\n\n dat1 dat2\nid\n2 56 19\n3 57 19\n4 45 20\n</code></pre>\n\n<p>If you do <strong>not</strong> want to modify the original DataFrames, you can use utility function <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#brief-primer-on-merge-methods-relational-algebra\" rel=\"nofollow noreferrer\">merge</a> instead, which performs the same operation, but needs the common column name specified explicitely:</p>\n\n<pre><code>>>> pd.merge(dat1, dat2, how='inner', on='id')\n\n id dat1 dat2\n0 2 56 19\n1 3 57 19\n2 4 45 20\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:33:41.147",
"Id": "419193",
"Score": "1",
"body": "@SebSquire: please consider to accept (checkmark symbol below the vote counter of) this answer, if it has answered the question to your satisfaction. ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:55:20.450",
"Id": "216332",
"ParentId": "216329",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:05:30.527",
"Id": "216329",
"Score": "2",
"Tags": [
"python",
"database",
"pandas",
"join"
],
"Title": "Conditional joining Pandas dataframes"
} | 216329 |
<p>I would like to have a function <code>Chain-Paths</code> to accomplish the following: given a base directory (<code>Base</code>) and a location, possibly relative to that given Base (<code>Chained</code>), output the result of joining both paths. If however <code>Chained</code> is already an absolute path, just return that. If both paths are relative, keep the result relative as well.</p>
<p>The above, reformulated in test cases (works if run from a user directory, e.g. <em>C:\Users\ojdo</em>):</p>
<pre><code>$testCases = @(
@{
Base = "..\..\Windows\Fonts"
Chained = "..\system32\notepad.exe"
Expected = "..\..\Windows\system32\notepad.exe"
}
@{
Base = "C:\Windows\Fonts"
Chained = "..\system32\notepad.exe"
Expected = "C:\Windows\system32\notepad.exe"
}
@{
Base = "AppData\Roaming"
Chained = "C:\Windows\system32\notepad.exe"
Expected = "C:\Windows\system32\notepad.exe"
}
)
foreach ($case in $testCases) {
$expectedResult = $case.Expected
$actualResult = (Chain-Paths $case.Base $case.Chained)
$testResult = if($actualResult -eq $expectedResult) {"PASS"} else {"FAIL"}
Write-Host ("{0}: {1} == {2}" -f $testResult, $actualResult, $expectedResult)
}
</code></pre>
<p>This is the function I have come up with:</p>
<pre><code>function Chain-Paths($Base, $Chained)
{
if (Split-Path $Chained -IsAbsolute) {
return $Chained
} else {
$joinedPath = Join-Path $Base $Chained
if (Split-Path $Base -IsAbsolute) {
return (Resolve-Path $joinedPath).Path
} else {
return Resolve-Path $joinedPath -Relative
}
}
}
</code></pre>
<p>My questions:</p>
<ul>
<li>Am I overcomplicating things?</li>
<li>Is there a way to simplify things by using a .net function?</li>
<li>Is the <code>(...).Path</code> really required?</li>
<li>Any stylistic recommendations (apart from missing docstring)?</li>
</ul>
| [] | [
{
"body": "<p>You can use the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">System.IO.Path.Combine Method</a>.</p>\n\n<blockquote>\n <p>This method is intended to concatenate individual strings into a single string that represents a file path. However, if an argument other than the first contains a rooted path, any previous path components are ignored, and the returned string begins with that rooted path component. </p>\n</blockquote>\n\n<pre><code>$combined = [IO.Path]::Combine($Base, $Chained)\n</code></pre>\n\n<p>Also, it seems more natural to use <code>System.IO.Path.IsPathRooted()</code> method instead of <code>Split-Path</code> to see if the path is absolute.</p>\n\n<pre><code>$isRelative = ![IO.Path]::IsPathRooted($combined)\n</code></pre>\n\n<p>There is a way to pass parameter values by appending a colon after the parameter name in cmdlet. You can also pass values to the <code>switch</code> type parameter this way.</p>\n\n<pre><code>Verb-Noun -ParameterName:Value\n</code></pre>\n\n<p><code>Resolve-Path</code> basically outputs a <code>PathInfo</code> object, but when the <code>-Relative</code> switch is set the output will be <code>string</code>.\nBoth types have a <code>ToString ()</code> method, so you can get a path string without using an <code>if</code> statement. (The <code>ToString()</code> method of the <code>PathInfo</code> object outputs the value of the <code>Path</code> property)</p>\n\n<pre><code>function Chain-Path($Base, $Chained) {\n $combined = [IO.Path]::Combine($Base, $Chained)\n $isRelative = ![IO.Path]::IsPathRooted($combined)\n (Resolve-Path $combined -Relative:$isRelative).ToString()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T15:01:29.040",
"Id": "216529",
"ParentId": "216331",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216529",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:45:39.777",
"Id": "216331",
"Score": "1",
"Tags": [
"powershell"
],
"Title": "Joining and resolving two paths while keeping them relative conditionally"
} | 216331 |
<p>I'm a student and this is my first application/project that I made and finished today in C++ using OOP and I want to hear your opinions and suggestions, what I did wrong, what I did good, what should I improve, what should I exclude, about comments, anything that can help me getting better and improve my code.</p>
<p>To test the code you will need to copy the file <a href="https://pastebin.com/raw/P8ye8LfE" rel="nofollow noreferrer"><code>tiles.in</code></a> which contains the tiles for the game.</p>
<p>I made a UML diagram for better understanding of the code: </p>
<p><a href="https://i.stack.imgur.com/n31Ag.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n31Ag.png" alt="UML"></a></p>
<pre><code>#include "pch.h"
#include <conio.h>
#include <exception>
#include <fstream>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define numberOfColumns 11 // number of lines and columns for the game table
#define numberOfLines 21
using namespace std;
class Drawable // abstract class that is used to draw different tiles from the game or coordinates
{
protected:
static short x;
static short y;
public:
static int getX();
static void hidecursor();
static void MoveTo(short _x, short _y); // used to move to a specific coordinate in console
virtual void DeleteDraw() = 0;
virtual void Draw() = 0;
};
short Drawable::x = 5; // represents the coordinates where the game table will be positioning in console
short Drawable::y = 25;
int Drawable::getX()
{
return x;
}
void Drawable::hidecursor()
{
CONSOLE_CURSOR_INFO info = { 100,FALSE };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
}
void Drawable::MoveTo(short _x, short _y)
{
COORD coord = { y + _y,x + _x };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
class Coordinates: public Drawable // class that represents one coordinate in console (x,y)
{
private:
short x;
short y;
static char form; // the form that every piece(point) from every tile will have
public:
Coordinates(short x = 0, short y = 0);
Coordinates& operator =(const Coordinates &coord);
// getter and setter
short getX();
short getY();
static char getForm();
void setX(short x);
void setY(short y);
//functions using coordinates(x,y)
void moveCoordinatesInADirection(char direction); // used to move the coordinates in a specific direction(right, left, down)
// Will be used to move every piece(point) from a tile in a direction
void DeleteDraw() override;
void Draw() override;
};
char Coordinates::form = '*';
Coordinates::Coordinates(short x, short y)
{
this->x = x;
this->y = y;
}
Coordinates& Coordinates::operator=(const Coordinates &coord)
{
if (this != &coord)
{
this->x = coord.x;
this->y = coord.y;
this->form = coord.form;
}
return *this;
}
char Coordinates::getForm()
{
return form;
}
short Coordinates::getX()
{
return x;
}
short Coordinates::getY()
{
return y;
}
void Coordinates::setX(short x)
{
this->x = x;
}
void Coordinates::setY(short y)
{
this->y = y;
}
void Coordinates::moveCoordinatesInADirection(char direction)
{
switch (direction)
{
case 'a': // move left
y--;
break;
case 'd': // move right
y++;
break;
case 's': // move down
x++;
break;
default:
break;
}
}
void Coordinates::DeleteDraw()
{
MoveTo(x + Drawable::x, y + Drawable::y); // Moves to the coordinates (x,y) and deletes a piece(point) from a tile
cout << " ";
}
void Coordinates::Draw()
{
MoveTo(x + Drawable::x, y + Drawable::y); // Moves to the coordinates (x,y) and draw a piece(point) from a tile
cout << form;
}
class Tile: public Drawable // class that represents a tile and all its methods
{
private:
Coordinates coordTile[4]; // any tile is composed of 4 coordinates and a center
short centerOfTile;
public:
Tile& operator=(const Tile &tile);
// getter and setter
short getcenterOfTile(short position);
short getcoordX(short position);
short getcoordY(short position);
void setcenterOfTile(short centerOfTile);
void setcoordX(short position, int x);
void setcoordY(short position, int y);
//methods using a tile
void moveTileInADirection(char direction); // moves the tile in a specific direction(right, left, down)
void rotateTileInADirection(char direction); // rotates the tile in a specific direction(right, left)
void DeleteDraw() override; // overrides function DeleteDraw() from Drawable() and is used to delete the tile from the game table
void Draw() override; // overrides function Draw() from Drawable() and is used to draw the tile in the game table
};
Tile& Tile::operator=(const Tile &tile)
{
if (this != &tile)
{
for (short i = 0; i < 4; i++)
{
this->coordTile[i] = tile.coordTile[i];
}
}
return *this;
}
short Tile::getcoordX(short position)
{
return coordTile[position].getX();
}
short Tile::getcoordY(short position)
{
return coordTile[position].getY();
}
short Tile::getcenterOfTile(short position)
{
return centerOfTile;
}
void Tile::setcoordX(short position, int x)
{
coordTile[position].setX(x);
}
void Tile::setcoordY(short position, int y)
{
coordTile[position].setY(y);
}
void Tile::setcenterOfTile(short centerOfTile)
{
this->centerOfTile = centerOfTile;
}
void Tile::moveTileInADirection(char direction)
{
for (short i = 0; i < 4; i++)
{
coordTile[i].moveCoordinatesInADirection(direction);
}
}
void Tile::rotateTileInADirection(char direction)
{
short dir = 0;
switch (direction)
{
case 'e': // to rotate the tile to the right we need +90* check formula down
dir = 1;
break;
case 'q': // to rotate the tile to the left we need -90* check formula down
dir = -1;
break;
default:
return;
}
if (centerOfTile != -1) // If the tile can be rotated
{
float centerOfTileX = coordTile[centerOfTile].getX();
float centerOfTileY = coordTile[centerOfTile].getY();
float tileX;
float tileY;
for (short i = 0; i < 4; i++) // we rotate every piece(point) from the tile with 90*(to right) or -90*(to left) depends on dir
{
tileX = coordTile[i].getX();
tileY = coordTile[i].getY();
coordTile[i].setX(round((tileX - centerOfTileX)*cos((90 * 3.14*dir) / 180) + (tileY - centerOfTileY)*sin((90 * 3.14*dir) / 180) + centerOfTileX));
coordTile[i].setY(round((centerOfTileX - tileX)*sin((90 * 3.14*dir) / 180) + (tileY - centerOfTileY)*cos((90 * 3.14*dir) / 180) + centerOfTileY));
}
}
}
void Tile::DeleteDraw()
{
for (short i = 0; i < 4; i++)
{
coordTile[i].DeleteDraw(); // Deleting the tile by deleting every piece(point) of it
}
}
void Tile::Draw()
{
for (short i = 0; i < 4; i++)
{
coordTile[i].Draw(); // Drawing the tile by drawing every piece(point) of it
}
}
class Tiles // class that represents the number of tiles the game has and all tiles
{
private:
short numberOfTiles;
Tile *figuri;
public:
Tiles();
Tile getTile(short number);
short getNumberOfTiles();
~Tiles();
};
Tiles::Tiles()
{
ifstream input("tiles.in"); // reading from a file the number of tiles and than the coordinates of each tile and setting the center for every tile
input >> numberOfTiles;
figuri = new Tile[numberOfTiles];
short auxiliaryVar = 0;
short counter = 0;
for (short i = 0; i < numberOfTiles; i++)
{
counter = 0;
for (short j = 0; j < 4; j++)
{
for (short k = 0; k < 4; k++)
{
input >> auxiliaryVar;
if (auxiliaryVar != 0)
{
figuri[i].setcoordX(counter, j);
figuri[i].setcoordY(counter, k);
counter++;
if ((j == 1) && (k == 2))
{
figuri[i].setcenterOfTile(counter - 1);
}
}
}
}
}
figuri[0].setcenterOfTile(2);
figuri[3].setcenterOfTile(-1);
input.close();
}
Tile Tiles::getTile(short number)
{
return figuri[number];
}
short Tiles::getNumberOfTiles()
{
return numberOfTiles;
}
Tiles::~Tiles()
{
delete[] figuri;
}
class Table: public Drawable // class that represents the game table
{
private:
short **table; // the game table= a matrix with 0 if there is nothing draw in that point and 1 if there is something draw
long score;
Tile actualTile; // the tile that moves in the game table(the actual tile)
Tiles allTiles; // the actual tile will be chosen random from all the tiles possible
public:
Table();
long getScore();
void informationAboutGame();
void generateRandomTile();
void deleteLineFromTable(short line); // after a line from the table is completated, it will be deleted from the game table and the score will rise
void moveTileDownAutomatically();
void moveTileInADirection(char direction);
void possibleMoves(short &time); // possible moves of a player (right, left, down)
void positioningTileInTableAfterRotation();
void rotateTileInADirection(char direction);
void start();
void DeleteDraw();
void Draw();
bool belongsToActualTile(short x, short y);
bool checkIfCanMoveInADirection(char direction);
bool checkIfPlayerLost();
~Table();
};
Table::Table()
{
// creating the game table and initialize the table
time_t t;
srand((unsigned)(time(&t)));
score = 0;
table = new short*[numberOfLines];
for (short i = 0; i < numberOfLines; i++)
{
table[i] = new short[numberOfColumns];
}
for (short i = 0; i < numberOfLines; i++)
{
for (short j = 0; j < numberOfColumns; j++)
{
table[i][j] = 0;
}
}
}
long Table::getScore()
{
return score;
}
void Table::informationAboutGame()
{
cout << "\n\n\n\t This is a tetris game.The controls for the game are:\n";
cout << "\n\t a - move the tile left";
cout << "\n\t d - move the tile right";
cout << "\n\t s - move the tile down";
cout << "\n\t e - rotate the tile right";
cout << "\n\t q - rotate the tile left";
cout << "\n\n\t When you are ready, press any key to start the game. Good luck ! ";
_getch();
}
void Table::generateRandomTile()
{
// generating a random tile from all the tiles possible and setting its coordinates for the game table
short randomTile;
randomTile = rand() % allTiles.getNumberOfTiles();
actualTile = allTiles.getTile(randomTile);
actualTile.setcenterOfTile(allTiles.getTile(randomTile).getcenterOfTile(randomTile));
for (short i = 0; i < 4; i++)
{
actualTile.setcoordY(i, numberOfColumns / 2 - actualTile.getcoordY(i) + 2);
}
}
void Table::deleteLineFromTable(short line)
{
// Deleting the line which is completed
// This is done by replacing every line starting that line by the previous one
for (short i = line; i > 0; i--)
{
for (short j = 0; j < numberOfColumns; j++)
{
Drawable::MoveTo(i + Drawable::x, j + Drawable::y);
if (table[i - 1][j] == 0)
{
cout << " ";
}
else {
cout << Coordinates::getForm();
}
table[i][j] = table[i - 1][j];
}
}
for (short i = 0; i < numberOfColumns; i++)
{
Drawable::MoveTo(0 + Drawable::x, i + Drawable::y);
cout << " ";
table[0][i] = 0;
}
}
void Table::moveTileDownAutomatically()
{
//Moving the actual tile down every 0.5s and checking if the player wants to make a move(right, left, down) or rotate(right, left) the tile
actualTile.Draw();
do {
short time = 1;
while (time < 500)
{
if (_kbhit()) // if the player presses a key on keyboard
{
possibleMoves(time);
}
Sleep(1);
time = time + 1;
}
if (checkIfCanMoveInADirection('s'))
{
actualTile.DeleteDraw();
moveTileInADirection('s');
actualTile.Draw();
}
else {
break;
}
} while (true);
}
void Table::moveTileInADirection(char direction)
{
// To move the tile in a direction we need to :
// - delete the previous tile from the game table by putting 0
// - move the tile to the new coordinates
// - actualizate the game table by putting 1 on its coordinates
for (short i = 0; i < 4; i++)
{
table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 0;
}
actualTile.moveTileInADirection(direction);
for (short i = 0; i < 4; i++)
{
table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 1;
}
}
void Table::possibleMoves(short &time)
{
//Possible moves that can be effectuated on a tile ( move and rotate )
char direction = _getch();
if (checkIfCanMoveInADirection(direction))
{
actualTile.DeleteDraw(); // delete old tile
moveTileInADirection(direction); // move the tile in the direction the player wanted
actualTile.Draw(); // draw the new tile
if (direction == 's')
{
time = 1;
}
}
// check if the player wanted to rotate the tile (right, left)
if ((direction == 'e') || (direction == 'q'))
{
actualTile.DeleteDraw();
rotateTileInADirection(direction);
actualTile.Draw();
}
}
void Table::positioningTileInTableAfterRotation()
{
// This method is used to check and correct a tile if it goes out of boundaries of the game table after a rotation
short index = 0;
short ok = 1;
while (index < 4)
{
if (actualTile.getcoordY(index) < 0)
{
// passed left boundary of the game table
for (short j = 0; j < 4; j++)
{
actualTile.setcoordY(j, actualTile.getcoordY(j) + 1);
}
ok = 0;
}
if (actualTile.getcoordY(index) > numberOfColumns - 1)
{
// passed right boundary of the game table
for (short j = 0; j < 4; j++)
{
actualTile.setcoordY(j, actualTile.getcoordY(j) - 1);
}
ok = 0;
}
if (actualTile.getcoordX(index) < 0)
{
// passed top boundary of the game table and there are cases where the player loses
for (short j = 0; j < 4; j++)
{
actualTile.setcoordX(j, actualTile.getcoordX(j) + 1);
}
for (short j = 0; j < 4; j++)
{
if ((actualTile.getcoordX(j) > 0) && (table[actualTile.getcoordX(j)][actualTile.getcoordY(j)] == 1))
{
throw 0;
}
}
ok = 0;
}
if ((actualTile.getcoordX(index) > numberOfLines - 1) ||
(table[actualTile.getcoordX(index)][actualTile.getcoordY(index)] == 1))
{
// passed the down boundary or reached a possition that is occupied
for (short j = 0; j < 4; j++)
{
actualTile.setcoordX(j, actualTile.getcoordX(j) - 1);
}
ok = 0;
}
if (ok == 0)
{
index = 0;
ok = 1;
}
else {
index++;
}
}
}
void Table::rotateTileInADirection(char direction)
{
// To rotate the tile in a direction we need to :
// - delete the previous tile from the game table by putting 0
// - move the tile to the new coordinates and adjust it so it doesnt pass the boundaries of the game table
// - actualizate the game table by putting 1 on its coordinates
for (short i = 0; i < 4; i++)
{
table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 0;
}
actualTile.rotateTileInADirection(direction);
positioningTileInTableAfterRotation();
for (short i = 0; i < 4; i++)
{
table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 1;
}
}
void Table::start()
{
Drawable::hidecursor();
informationAboutGame();
DeleteDraw();
Draw();
short ok = 1;
while (true)
{
// This while will end when the player will lose and the program will end
// checking if there is any line completed and needs to be deleted
for (short i = 0; i < numberOfLines; i++)
{
ok = 1;
for (short j = 0; j < numberOfColumns; j++)
{
if (table[i][j] == 0)
{
ok = 0;
break;
}
}
if (ok)
{
deleteLineFromTable(i);
score++;
}
}
generateRandomTile();
if (checkIfPlayerLost() == 1)
{
moveTileDownAutomatically();
}
else {
Drawable::MoveTo(numberOfLines + 1 + Drawable::x, 0);
cout << "\n" << "Good job, you made " << score * 1000 << " points.\n";
break;
}
}
}
void Table::DeleteDraw()
{
// Method used to delete the table
system("cls");
}
void Table::Draw()
{
// Method used to draw the table
for (short i = -1; i <= numberOfLines; i++)
{
MoveTo(i + Drawable::x, -1 + Drawable::y);
cout << char(219);
MoveTo(i + Drawable::x, numberOfColumns + Drawable::y);
cout << char(219);
}
for (short i = -1; i <= numberOfColumns; i++)
{
Drawable::MoveTo(-1 + Drawable::x, i + Drawable::y);
cout << char(219);
Drawable::MoveTo(numberOfLines + Drawable::x, i + Drawable::y);
cout << char(219);
}
}
bool Table::belongsToActualTile(short x, short y)
{
//Checking if a piece(point) of a tile belonds to the actual tile
for (short i = 0; i < 4; i++)
{
if ((actualTile.getcoordX(i) == x) && (actualTile.getcoordY(i) == y))
{
return 0;
}
}
return 1;
}
bool Table::checkIfCanMoveInADirection(char direction)
{
for (short i = 0; i < 4; i++)
{
switch (direction)
{
// Check if the player can move left
case'a':
if ((actualTile.getcoordY(i) - 1 < 0) ||
((belongsToActualTile(actualTile.getcoordX(i), actualTile.getcoordY(i) - 1)) &&
(table[actualTile.getcoordX(i)][actualTile.getcoordY(i) - 1] == 1)))
{
return 0;
}
break;
// Check if the player can move right
case'd':
if ((actualTile.getcoordY(i) + 1 > numberOfColumns - 1) ||
((belongsToActualTile(actualTile.getcoordX(i), actualTile.getcoordY(i) + 1)) &&
(table[actualTile.getcoordX(i)][actualTile.getcoordY(i) + 1] == 1)))
{
return 0;
}
break;
// Check if the player can move down
case's':
if ((actualTile.getcoordX(i) + 1 > numberOfLines - 1) ||
((belongsToActualTile(actualTile.getcoordX(i) + 1, actualTile.getcoordY(i))) &&
(table[actualTile.getcoordX(i) + 1][actualTile.getcoordY(i)] == 1)))
{
return 0;
}
break;
default:
break;
}
}
return 1;
}
bool Table::checkIfPlayerLost()
{
for (short i = 0; i < 4; i++)
{
if (table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] == 1)
{
return 0;
}
}
return 1;
}
Table::~Table()
{
for (short i = 0; i < numberOfLines; i++)
{
delete[] table[i];
}
delete[] table;
}
int main()
{
Table a;
try {
a.start();
}
catch (...) {
Drawable::MoveTo(numberOfLines + 1 + Drawable::getX(), 0);
cout << "\n" << "Good job, you made " << a.getScore() * 1000 << " points.\n";
}
return 0;
}
</code></pre>
<p><strong>Edit</strong>: I managed to do some changes to the code based on your suggestions @Sandro4912, I hope this changes are good and are making the code more readable and understandable. Made one class per file with separate declaration and implementation, corrected the boolean methods, renamed the define with static contexpr, removed the global variables, used double and int, made comments only on the part that needed, omitted return 0 in main, used better random engine and some other changes. I still used <code>using namespace std;</code> and didn't used namespace only because i though this will make the code less readable, and I stayed with some members as private only because I though not all classes should have access to all other classes. Besides this 2 things I think I managed to modify the code as you suggested and also added some new methods, new members, new classes.
This is the link to the code: <a href="https://github.com/FirescuOvidiu/Tetris-game-for-Windows" rel="nofollow noreferrer">Github tetris game</a>. Sorry it took so long.
<br><strong>Edit 2:</strong> Made a new question with the improved code the link to the new question is: <a href="https://codereview.stackexchange.com/questions/223832/tetris-game-for-windows-improved-version">Tetris game for Windows improved version</a></p>
| [] | [
{
"body": "<p>I don't have the time to analyse all the code. I suggest fixing these issues mentioned here and then reposte the improved version. Then we could take a look at your logic. </p>\n\n<ol>\n<li><p><strong>Don't use <code>using namespace std</code></strong> It is considered bad practice. See:\n <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></p></li>\n<li><p><strong>Use a namespace.</strong> You should wrap your functions and classes in a namespace to\nprevent name clashes if you use other libraries. Like this:</p>\n\n<pre><code>namespace tetris {\n // youre classes and functions\n}\n</code></pre></li>\n<li><strong>One class per File:</strong> You currently put everything into one file. This\nway your separation of functions and classes doesn't help at all.\nIt's recommended to put one class per file.</li>\n<li><strong>Separate declarations and implementations.</strong> Separate\nyour code in header and implementation files. In the header only\ndeclare and include the minimum required. To speed up compilation\nuse forward declaration.</li>\n<li><p><strong>Return as boolean</strong>: This:</p>\n\n<pre><code>bool Table::checkIfPlayerLost()\n{\n for (short i = 0; i < 4; i++)\n {\n if (table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] == 1)\n {\n return 0;\n }\n }\n\n return 1;\n}\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>bool Table::checkIfPlayerLost()\n{\n for (short i = 0; i < 4; i++)\n {\n if (table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] == 1)\n {\n return false;\n }\n }\n\n return true;\n}\n</code></pre></li>\n<li><p><strong>Use <code>constexpr</code> for constants</strong>. This:</p>\n\n<pre><code>#define numberOfColumns 11 \n</code></pre>\n\n<p>Should be this (we are not in C anymore):</p>\n\n<pre><code>static constexpr auto numberOfColumns{11}\n</code></pre></li>\n<li><strong>Don't use global variables</strong>. They are considered a maintenance hazard.\nTry to encapsulate them into a class;</li>\n<li><strong>Don't use <code>float</code> or <code>short</code></strong>. by default you should use <code>double</code> and <code>int</code>.\nHeres a bit about it:\n<a href=\"https://stackoverflow.com/questions/24371077/when-to-use-short-over-int\">https://stackoverflow.com/questions/24371077/when-to-use-short-over-int</a></li>\n<li><p><strong>Don't comment whats clear.</strong> For example this:</p>\n\n<pre><code>#define numberOfColumns 11 // number of lines and columns for the game table\n#define numberOfLines 21\n</code></pre>\n\n<p>Do you see any benefit in this comment? I don't.</p></li>\n<li><strong>public before private</strong>. In C++ it's usually common to put the public\n members before the private ones.</li>\n<li><strong>Omit <code>return 0</code> in main.</strong> Unlike in old C in C++ <code>return 0</code> is\n automatically generated by the compiler at the end of main.</li>\n<li><p><strong>Use C++ container.</strong> This:</p>\n\n<pre><code> class Table : public Drawable // class that represents the game table \n {\n private:\n short **table;\n ....\n }\n\n Table::Table()\n {\n ...\n table[i] = new short[numberOfColumns];\n ...\n }\n\n Table::~Table()\n {\n for (short i = 0; i < numberOfLines; i++)\n {\n delete[] table[i];\n }\n delete[] table;\n }\n</code></pre>\n\n<p>That is so so C. First of all why allocate dynamic arrays here?\n You want a fixed array. So you could just declare a two dimensional\n C array. Since we are in c++ it would be more wise to use\n <code>std::array</code> or <code>std::vector</code> to use as the table representation.\n If you really need to allocate dynamically (here you don't) then\n use smart pointer like <code>std::unique_ptr</code> or <code>std::shared_pointer</code>\n not naked new/delete. They release the memory safely for you</p></li>\n<li><p><strong>Use a better random engine.</strong> Since C++11 you should not use this:</p>\n\n<pre><code> srand((unsigned)(time(&t)));\n</code></pre>\n\n<p>Instead use the better random generator from <code><random></code> Why? \n <a href=\"https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow noreferrer\">https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful</a></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T12:19:37.277",
"Id": "428533",
"Score": "3",
"body": "Thanks @Sandro4912 for your response. I will look into all the issues you pointed out for my code and I will learn so I don't do them anymore and modify and improve the code. I'm in middle of the exams right now so as soon as I can I'm gonna do the improvements and repost the improved code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T16:05:14.670",
"Id": "428559",
"Score": "2",
"body": "take youre time. this website is not going any where. If you have additional questions let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T17:11:40.353",
"Id": "433993",
"Score": "1",
"body": "managed to change the code based on your suggestion and also made some modifications myself to the code. Sorry it took so long I really had a busy month, I can't wait to see your impression and suggestions after you see the improved code. I think it's way better than the original code I posted 1 month ago. Thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T20:14:44.550",
"Id": "434010",
"Score": "1",
"body": "i think is best to post the improved code into a new question and put a link in the top of this question here so both questions are linked together here and anyone can review it. unfortunately now im low on time. but i will take a look when theres time again. probaly someone else will already check it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T20:52:48.057",
"Id": "434012",
"Score": "0",
"body": "I understand I will do so, also I will let a link in this question to the new question. Let me know your thoughts on the code when you get a chance to see it, I think I implemented good the things you pointed out"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T19:06:43.530",
"Id": "221443",
"ParentId": "216333",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "221443",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T12:59:23.180",
"Id": "216333",
"Score": "7",
"Tags": [
"c++",
"object-oriented",
"windows",
"tetris"
],
"Title": "Tetris game for Windows"
} | 216333 |
<p>I have this bash script that adds users to NextCloud from a csv file. It expects to be run from the same directory as the docker-compose.yml file.</p>
<p>I'm pretty new to bash scripting and I'm wondering if I am doing things correctly or if there are pieces that could be improved in terms of efficiency, correctness, style? Any comments are appreciated really.</p>
<p>Thanks in advance!</p>
<pre><code>#!/bin/bash
# Handle printing errors
die () {
printf '%s\n' "$1" >&2
exit 1
}
usage () {
echo ""
echo "batch_users.sh"
echo "SYNOPSIS"
echo "batch_users [-p] [file]"
echo "DESCRIPTION"
echo "The batch_users script adds a batch of users to an instance of NextCloud running inside of a docker container by reading a list from a csv file."
echo ""
echo "-p, --password Set users password. If no option is passed, the default password is nomoremonkeysjumpingonthebed ."
echo ""
echo "csv file should be formatted in one of the following configurations."
echo "username,Display Name,group,email@address.domain,"
echo "username,Display Name,group,"
echo "username,Display Name,"
echo "username,"
echo ""
echo "EXAMPLES"
echo "The command:"
echo "batch_users.sh -p 123password321 foobar.csv"
echo "will add the users from foobar.csv and assign them the password 123password321"
echo "The command:"
echo "batch_users.sh foobar.csv"
echo "will add the users from foobar.csv and assign them the default password."
echo ""
echo "batch_users will return 0 on success and a positive number on failure."
echo ""
}
# flags
password=nomoremonkeysjumpingonthebed
while :; do
case $1 in
-h|-\?|--help)
usage # Display a usage synopsis.
exit
;;
-p|--password)
if [ "$2" ]; then
password=$2
shift
else
die 'Error: "--password" requires a non-empty option argument.'
fi
;;
--password=?*)
password=${1#*=} # Delete everything up to = and assign the remainder.
;;
--password=) # Handle the case of empty --password=
die 'Error: "--password" requires a non-empty option argument.'
;;
--)
shift
break
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
;;
*) # Default case. No more options, so break out of the loop
break
esac
shift
done
# Check to see if there was at least one argument passed.
# If not, print error and exit.
if [[ $# -eq 0 ]]
then
die 'Error: Expected at least one argument, but no arguments were supplied.'
fi
# Check to see if the file passed in exists.
# If not, print error and exit.
if [[ ! -e $1 ]]
then
die "Couldn't find file ${1}."
exit 1
fi
input_file="$1"
while IFS=, read -r f1 f2 f3 f4
do
# check --password flag
# f1, f2, f3 exist?
if [[ -n $f1 && -n $f2 && -n $f3 ]]
then
sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
user:add --password-from-env --display-name=\"${f2}\" --group=\"${f3}\" \"$f1\" " < /dev/null
elif [[ -n $f1 && -n $f2 ]]
then
# f1 and f2
sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
user:add --password-from-env --display-name=\"${f2}\" \"$f1\" " < /dev/null
elif [[ -n $f1 ]]
then
#only f1
sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
user:add --password-from-env \"$f1\" " < /dev/null
else
#error
die "Expected at least one field, but none were supplied."
fi
# If there is a fourth value in the csv, use it to set the user email.
if [[ -z ${f4+x} ]]
then
break
else
sh -c "docker-compose exec -T --user www-data app php occ\
user:setting \"$f1\" settings email \"${f4}\" " < /dev/null
fi
done <"$input_file"
exit 0
</code></pre>
| [] | [
{
"body": "<h1>Review</h1>\n<p>This code looks pretty good. I know very little about the <code>docker-compose</code> command being executed, but I can look at the script style.</p>\n<p>Shellcheck spots no issues, which is always a good start.</p>\n<p>I see nothing in here that really demands Bash rather than standard (POSIX) shell - all those <code>[[</code> can be easily converted to <code>[</code>.</p>\n<p>I recommend setting <code>-u</code> and probably <code>-e</code>. In any case, consider what the effects of any individual command failing should be. Within the loop, I recommend continuing to the next iteration, but remember whether any iteration failed. One way I do that is</p>\n<pre><code>status=true # until a failure\nfor i in ....\ndo\n some_command || status=false\ndone\n\n# terminate with appropriate exit code \nexec $status\n</code></pre>\n<p>Instead of using many <code>echo</code> commands in <code>usage()</code>, it's easier to copy a single here-document:</p>\n<pre><code>usage() {\n cat <<'EOF'\nbatch_users.sh\nSYNOPSIS\n...\nEOF\n}\n</code></pre>\n<blockquote>\n<pre><code>if [[ ! -e $1 ]]\nthen\n die "Couldn't find file ${1}."\n exit 1\nfi\n</code></pre>\n</blockquote>\n<p>Braces not required here for <code>$1</code>, and <code>exit 1</code> is unreachable. Mere existence of the file is insufficient: we need it to be readable. Here's my version:</p>\n<pre><code>[ -r "$1" ] || die "Couldn't find file $1."\n</code></pre>\n<p>We need to be very careful when composing strings to be interpreted by other commands, especially shells:</p>\n<blockquote>\n<pre><code> sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \\\n user:add --password-from-env --display-name=\\"${f2}\\" --group=\\"${f3}\\" \\"$f1\\" " < /dev/null\n</code></pre>\n</blockquote>\n<p><code>$password</code> in particular could contain almost anything (including quote characters), so that's really not safe in the inner <code>sh</code> instance. Do we really need that shell, or can we simply invoke <code>docker-compose</code> directly? The latter is much easier to get right. If we really need the <code>sh</code>, then we'll need to be a lot more careful about constructing that command (I think we need to use a <code>printf</code> that supports <code>%q</code> conversion).</p>\n<p>We can avoid the repetition by using <code>${var+}</code> to conditionally include the optional arguments:</p>\n<pre><code>if [ "$f1" ]\nthen\n docker-compose exec -T --env OC_PASS="$password" \\\n --user www-data app php occ \\\n user:add --password-from-env \\\n ${f2:+"--display-name=$f2"} \\\n ${f3:+"--group=$f3"} \\\n "$f1" \\\n </dev/null \\\n || status=false\nelse\n #error\n echo "Expected at least one field, but none were supplied." >&2\n status=false\n continue\nfi\n</code></pre>\n<p>I think we have an unnecessary password exposure,. <code>--password-from-env</code> allows passing the password in environment, so that it doesn't appear in command-line arguments. But we've immediately lost that advantage when we wrote <code>--env OC_PASS="${password}"</code>. I think the correct thing to do is to put the password into environment before the loop:</p>\n<pre><code>OC_PASS=$password\nexport OC_PASS\n</code></pre>\n<p>And then specify to copy it without giving a new value: <code>--env OC_PASS</code>. We could also ditch <code>$password</code> and assign directly to <code>OC_PASS</code>. It would be worth not setting a default, so that users can use the same environment variable to avoid exposing the password using when invoking the script.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#!/bin/sh\n\nset -eu\n\n# Handle printing errors\ndie () {\n printf '%s\\n' "$1" >&2\n exit 1\n}\n\nusage () {\n cat <<'EOF'\nbatch_users.sh \nSYNOPSIS\nbatch_users [-p] [file]\nDESCRIPTION\nThe batch_users script adds a batch of users to an instance of NextCloud\nrunning inside of a docker container by reading a list from a csv file.\n\n-p, --password Set user password. If no option is passed, the password\n should be passed in the OC_PASS environment variable.\n\ncsv file should be formatted in one of the following configurations:\nusername,Display Name,group,email@address.domain,\nusername,Display Name,group,\nusername,Display Name,\nusername,\n\nEXAMPLES\nThe command:\n batch_users.sh -p 123password321 foobar.csv\nwill add the users from foobar.csv and assign them the password 123password321\nThe command:\n batch_users.sh foobar.csv\nwill add the users from foobar.csv and assign them the default password.\n\nbatch_users will return 0 on success and a positive number on failure.\nEOF\n}\n\n\n# flags\nwhile true\ndo\n case $1 in\n -h|-\\?|--help)\n usage # Display a usage synopsis.\n exit\n ;;\n -p|--password)\n if [ "$2" ]; then\n OC_PASS=$2\n export OC_PASS\n shift\n else\n die 'Error: "--password" requires a non-empty option argument.'\n fi\n ;;\n --password=?*)\n OC_PASS=${1#*=} # Delete everything up to = and assign the remainder.\n export OC_PASS\n ;;\n --password=) # Handle the case of empty --password=\n die 'Error: "--password" requires a non-empty option argument.'\n ;;\n --)\n shift\n break\n ;;\n -?*)\n printf 'WARN: Unknown option (ignored): %s\\n' "$1" >&2\n ;;\n *) # Default case. No more options, so break out of the loop\n break\n esac\n shift\ndone\n\n\n# Was exactly one filename argument passed?\n[ $# -eq 1 ] || die "$0: Expected a filename argument"\n\n# Is the file readable?\n[ -r "$1" ] || die "$1: missing or not readable"\n\n[ "$OC_PASS" ] || die "$0: No password specified. Run with --help for more info."\n\n\n\n\nstatus=true # until a command fails\n\nwhile IFS=, read -r f1 f2 f3 f4\ndo\n if [ "$f1" ]\n then\n docker-compose exec -T --user www-data --env OC_PASS \\\n app php occ \\\n user:add --password-from-env \\\n ${f2:+"--display-name=$f2"} \\\n ${f3:+"--group=$f3"} \\\n "$f1" \\\n </dev/null \\\n || status=false\n else\n echo "Expected at least one field, but none were supplied." >&2\n status=false\n continue\n fi\n\n # If there is a fourth value in the csv, use it to set the user email.\n if [ "$f4" ]\n then\n docker-compose exec -T \\\n --user www-data app php occ \\\n user:setting "$f1" settings email "$f4" \\\n </dev/null \\\n || status=false\n fi\ndone <"$1"\n\nexec $status\n</code></pre>\n<hr />\n<h1>Further suggestions</h1>\n<ul>\n<li>Perhaps it would be useful to add a <code>--verbose</code> option that shows what is to be done for each input line.</li>\n<li>Does the input really need to come from a file? It would be useful to be able to provide it on standard input (so we could filter a list using <code>grep</code>, for example).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:25:24.547",
"Id": "418607",
"Score": "0",
"body": "I had to make a few changes to your script to make it run. In order to get the environment variables into docker, I had to set --env OC_PASS=$OC_PASS. Is this still \"bad\"? Not sure how else I could do it. Also, in the case where $f2 or $f3 are missing, I was getting an error `Call to a member function getGID() on null` which I solved by changing `${f3+\"--group=$f3\"}` to `${f3:+\"--group=$f3\"}`. Thanks for the excellent review. I learned a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:28:30.800",
"Id": "418608",
"Score": "0",
"body": "I always get mixed up between `+` and `:+` in that context - sorry about that. I would expect that there's a way to avoid putting the password on the command-line like that (on many systems, including Linux, command-lines are viewable by anyone; environment variables are private). And I assume you mean `-env OC_PASS=\"$OC_PASS\"` - Shellcheck will catch the missed double-quotes, I expect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:31:12.550",
"Id": "418652",
"Score": "0",
"body": "I read that `docker run` can be passed [`-e` without `=` to use the value from the current environment](//stackoverflow.com/a/30494145). Let me know whether `export OC_PASS; docker-compose exec -e OC_PASS app php occ user:add --password-from-env` works; if so, that's the right way to do it without exposing the password in visible process arguments, and I'll be able to update the answer accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:21:46.017",
"Id": "418678",
"Score": "0",
"body": "Wow, thank you. I don’t know how I missed that in the docs. I’m away from my computer today but I am sure that’s the way to do it. I’ll let you know for sure when I get a chance. Do you want to submit a PR on GitHub since you changed the original script so much? https://github.com/quarterpi/nextcloud-batch-users if so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:43:35.083",
"Id": "418809",
"Score": "0",
"body": "I can confirm that -e is the correct way to pass environment variables from the current environment into docker. I have added a check to ensure that the OC_PASS env var is set. I'm going to re-write the synopsis and remove the -p flag. I'll also most likely add the option for passing in via csv or via stdin. The occ command is pretty verbose so maybe I'll silence it by default and add an option for verbosity. When I update the GitHub page I'll be sure to throw a link in the comments so you get due credit for your edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:48:51.343",
"Id": "418813",
"Score": "1",
"body": "That's great; I've already made the edit, so thanks for confirming it. I don't have a GitHub account, so won't submit a PR, but happy for you to credit/blame me for the changes! ;-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:33:28.707",
"Id": "216345",
"ParentId": "216335",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:23:00.493",
"Id": "216335",
"Score": "5",
"Tags": [
"bash",
"console",
"csv",
"docker"
],
"Title": "Batch upload users to nextcloud on docker with bash csv"
} | 216335 |
<p>I have a quicksort code in java which I want to improve. The improved code should take less time than the quicksort code. However when using my improved code which implement median of 3 partitioning, it takes 400 miliseconds more. Can anybody help me solve this out? if possible, can you suggest me other possible ways to improve my code. I have from 10,000 to 10 million integers to sort. </p>
<p>Quicksort</p>
<pre><code>public void quickSort(int arr[], int begin, int end) {
if (begin < end) {
int partitionIndex = partition(arr, begin, end);
quickSort(arr, begin, partitionIndex-1);
quickSort(arr, partitionIndex+1, end);
}
}
private int partition(int arr[], int begin, int end) {
int pivot = arr[end];
int i = (begin-1);
for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) {
i++;
int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}
int swapTemp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = swapTemp;
return i+1;
}
}
</code></pre>
<p>Improved code</p>
<pre><code>package sorting;
public class improvement {
Clock c = new Clock();
public void quickSort(int[] intArray) {
recQuickSort(intArray, 0, intArray.length - 1);
}
public static void recQuickSort(int[] intArray, int left, int right) {
int size = right - left + 1;
if (size <= 3)
manualSort(intArray, left, right);
else {
double median = medianOf3(intArray, left, right);
int partition = partitionIt(intArray, left, right, median);
recQuickSort(intArray, left, partition - 1);
recQuickSort(intArray, partition + 1, right);
}
}
public static int medianOf3(int[] intArray, int left, int right) {
int center = (left + right) / 2;
if (intArray[left] > intArray[center])
swap(intArray, left, center);
if (intArray[left] > intArray[right])
swap(intArray, left, right);
if (intArray[center] > intArray[right])
swap(intArray, center, right);
swap(intArray, center, right - 1);
return intArray[right - 1];
}
public static void swap(int[] intArray, int dex1, int dex2) {
int temp = intArray[dex1];
intArray[dex1] = intArray[dex2];
intArray[dex2] = temp;
}
public static int partitionIt(int[] intArray, int left, int right, double
pivot) {
int leftPtr = left;
int rightPtr = right - 1;
while (true) {
while (intArray[++leftPtr] < pivot)
;
while (intArray[--rightPtr] > pivot)
;
if (leftPtr >= rightPtr)
break;
else
swap(intArray, leftPtr, rightPtr);
}
swap(intArray, leftPtr, right - 1);
return leftPtr;
}
public static void manualSort(int[] intArray, int left, int right) {
int size = right - left + 1;
if (size <= 1)
return;
if (size == 2) {
if (intArray[left] > intArray[right])
swap(intArray, left, right);
return;
} else {
if (intArray[left] > intArray[right - 1])
swap(intArray, left, right - 1);
if (intArray[left] > intArray[right])
swap(intArray, left, right);
if (intArray[right - 1] > intArray[right])
swap(intArray, right - 1, right);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T07:42:33.610",
"Id": "460081",
"Score": "0",
"body": "This looks an initial attempt; see [elaboration](https://codereview.stackexchange.com/q/216374/93149)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T07:43:17.570",
"Id": "460082",
"Score": "3",
"body": "Does this answer your question? [Median of three partitioning taking more time than standard quicksort in java](https://codereview.stackexchange.com/questions/216374/median-of-three-partitioning-taking-more-time-than-standard-quicksort-in-java)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:31:31.007",
"Id": "216336",
"Score": "1",
"Tags": [
"java",
"sorting",
"comparative-review",
"quick-sort"
],
"Title": "Median of 3 partitioning taking more time than quicksort in java"
} | 216336 |
<p>I wrote a program that animates the Recamán sequence. It is in uses HTML canvas and JavaScript. I was hoping for some feedback on how it could 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>"use strict";
function getMousePos(evt, can) {
var rect = can.getBoundingClientRect();
return {
x: evt.clientX - rect.x,
y: evt.clientY - rect.y,
}
}
function clearAllIntervals() {
var id = window.setTimeout(() => {}, 0);
while (id--) {
window.clearInterval(id);
}
}
class Arc {
constructor(x, y, r, ccw) {
this.x = x;
this.y = y;
this.r = r;
this.ccw = ccw;
}
draw() {
ctx.beginPath();
ctx.arc(this.x - offset.x, this.y - offset.y, this.r, 0, Math.PI, this.ccw);
ctx.stroke();
}
}
document.getElementById("stop").onclick = clearAllIntervals;
document.getElementById("zi").onclick = () => {
scale += 0.25;
ctx.scale(scale, scale);
}
document.getElementById("zo").onclick = () => {
scale -= 0.25;
ctx.scale(scale, scale);
}
document.getElementById("cls").onclick = () => {
arcs.splice(0, arcs.length);
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
document.getElementById("hm").onclick = () => {
offset = { x: 0, y: 0 };
}
document.getElementById("anim").onclick = () => {
var speed = parseInt(document.getElementById("spd").value);
var size = parseInt(document.getElementById("size").value);
if (speed && size) {
draw(speed, size);
}
};
addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
addEventListener("mousedown", (e) => {
pos = getMousePos(e, canvas);
});
addEventListener("mouseup", () => {
pos = undefined;
});
addEventListener("mousemove", (e) => {
if (pos !== undefined) {
var mouse = getMousePos(e, canvas);
offset.x += pos.x - mouse.x;
offset.y += pos.y - mouse.y;
pos = mouse;
}
});
const canvas = document.getElementById("disp");
const ctx = canvas.getContext("2d");
var arcs = [];
var offset = { x: 0, y: 0 };
var pos = undefined;
var scale = 1;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function draw(spd, siz) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
clearAllIntervals();
var xPos = 0;
var used = [];
arcs = [];
var i = siz;
var drawNext = () => {
if (i > 2500) {
return null;
}
let next = xPos - i;
if (used.includes(next) || next < 1) {
next = xPos + i;
}
let rad = (next - xPos) / 2;
arcs.push(new Arc(xPos + rad, canvas.height / 2, Math.abs(rad), i / siz % 2 || 0));
used.push(next);
xPos = next;
i += siz;
ctx.clearRect(0, 0, canvas.width, canvas.height);
arcs.forEach((arc) => {
arc.draw();
});
setTimeout(drawNext, 1000 / spd);
};
drawNext();
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
height: 100%;
margin: 0;
overflow: hidden;
display: grid;
}
#disp {
height: 100vh;
width: 100vw;
margin: auto;
}
#menu {
position: absolute;
z-index: 1;
left: 10px;
top: 10px;
}
#menu input {
width: 50px;
}
button {
margin-bottom: 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Recáman Sequence</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="menu">
<span>Size: <input id="size" type="number" value="10"></span><br><br>
<span>Speed: <input id="spd" type="number" value="10"></span><br><br>
<span><button id="anim">Animate</button></span>
<span><button id="stop">Stop</button></span>
<span><button id="cls">Clear</button></span><br>
<span><button id="hm">Home</button></span>
<span><button id="zi" disabled="true">&#x1f50d;+</button></span>
<span><button id="zo" disabled="true">&#x1f50d;-</button></span>
</div>
<canvas id="disp"></canvas>
<script src="js/init.js"></script>
<script src="js/draw.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>This works best in full-screen.</p>
| [] | [
{
"body": "<p>Surround your code in a self invoking anonymous function</p>\n\n<p><code>(function(){ /** code here */ })();</code></p>\n\n<p>So it does not conflict with any other variables that may have been declared in the same scope.</p>\n\n<hr>\n\n<p>Declare all global variables at the top of your file and within an object wrapper. It'll be easier to handle them later and know where they are located.</p>\n\n<pre><code>const data = {\n arcs: [],\n offset: { x: 0, y: 0 },\n pos: undefined,\n scale: 1\n};\n</code></pre>\n\n<hr>\n\n<p>HTML Elements that are called more than once should be stored in their own variable in the global scope of your project.</p>\n\n<p>Change this</p>\n\n<pre><code>var speed = parseInt(document.getElementById(\"spd\").value);\nvar size = parseInt(document.getElementById(\"size\").value);\n</code></pre>\n\n<p>To</p>\n\n<pre><code>/** set with all other global variables */\nconst speedEle = document.getElementById(\"spd\");\nconst sizeEle = document.getElementById(\"size\");\n\n/** in your method */\nvar speed = parseInt(speedEle.value);\nvar size = parseInt(sizeEle.value);\n</code></pre>\n\n<hr>\n\n<p>Store your setTimeout's ids in a global <em>store</em> with <a href=\"https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Set\" rel=\"nofollow noreferrer\">Set</a>.</p>\n\n<pre><code>const ids = new Set();\n\nfunction clearAllIntervals() {\n ids.values().map(clearInterval);\n ids.clear();\n}\n</code></pre>\n\n<p>and add your ids like so:</p>\n\n<p><code>ids.add(setTimeout(drawNext, 1000 / spd));</code></p>\n\n<hr>\n\n<p>Don't use <code>var</code> use <code>let</code> or <code>const</code>.</p>\n\n<hr>\n\n<p>Don't use <strong>magic numbers</strong> i.e:</p>\n\n<pre><code>if (i > 2500) {\n return null;\n}\n</code></pre>\n\n<p>Define the 2500 as a global constant, preferable in the <code>data</code> object mentioned before OR (even better) a <code>config</code> object for other such variables (makes it easier if you wish to change those numbers later on)</p>\n\n<hr>\n\n<p>Don't use <strong>undefined</strong> as a value of reference. It's cleaner to use <code>null</code> instead.</p>\n\n<p><code>let pos = null;</code></p>\n\n<hr>\n\n<p>Simplify redundant code</p>\n\n<pre><code>function canvasSizeHandler(){\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n}\n\naddEventListener(\"resize\", canvasSizeHandler);\n/** on initial start */\ncanvasSizeHandler();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:18:38.550",
"Id": "216342",
"ParentId": "216337",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216342",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:36:02.290",
"Id": "216337",
"Score": "3",
"Tags": [
"javascript",
"animation",
"canvas"
],
"Title": "Recamán Sequence Animation"
} | 216337 |
<p>I am currently developing a Django Rest Framework API with TDD. I have 15 tests and counting for two views, which doesn't seem right to me. It takes me a lot of time to write the tests and a lot of the testing logic seems redundant to me, especially because I have to check permissions for each test request. Furthermore I am unsure how to test permissions. If every view has about 3 permissions, it takes an enormous amount of tests to cover it. My questions are:</p>
<ul>
<li>Should my tests be so much?</li>
<li>Am I testing in an efficient way?</li>
</ul>
<p>Please comment on my way of testing and give me any advice regarding how I can improve it.</p>
<p>Here are my Views:</p>
<pre><code>class UserListView(APIView):
permission_classes = [IsAuthenticated, IsAdminUser]
def get(self, request, format=None):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data) #if you only return the data, it is automatically HTTP_200_OK
def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserDetailView(APIView):
permission_classes = [IsAuthenticated, IsAdminUser]
def get_object(self, pk):
try:
return User.objects.get(pk=pk)
except User.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user)
return Response(serializer.data)
def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>And here is my tests:</p>
<pre><code>class TestUserBase(APITestCase):
def setUp(self):
self.client = APIClient()
self.regular_user = User.objects.create_user(email="testuser1@example.com", password="1234")
self.super_user = User.objects.create_superuser(email="supertestuser1@example.com", password="1234")
def _super_auth(self):
self.client.force_authenticate(user=self.super_user)
def _regular_auth(self):
self.client.force_authenticate(user=self.regular_user)
class TestUserListView(TestUserBase):
url = reverse('user-list')
valid_user = {
"email": "testuser@valid.com",
"password": "validvalid",
"first_name": "test",
"last_name": "user"
}
invalid_user = {
"email": "",
"password": "validvalid",
"first_name": "test",
"last_name": "user"
}
def test_unauthorized_users_view(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_authorized_but_forbidden_users_view(self):
self._regular_auth()
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_authorized_and_permitted_users_view(self):
self._super_auth()
response = self.client.get(self.url)
expected_data = UserSerializer(User.objects.all(), many=True).data
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, expected_data)
self.assertEqual(User.objects.count(), 2)
def test_unauthorized_user_create(self):
response = self.client.post(self.url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_authorized_but_forbidden_user_create(self):
self._regular_auth()
response = self.client.post(self.url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_authorized_and_permitted_invalid_user_create(self):
self._super_auth()
response = self.client.post(self.url, self.invalid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_authorized_and_permitted_valid_user_create(self):
self._super_auth()
response = self.client.post(self.url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, self.valid_user)
self.assertEqual(User.objects.count(), 3)
class TestUserDetailView(TestUserBase):
valid_url = reverse('user-detail', kwargs={"pk": 1})
invalid_url = reverse('user-detail', kwargs={"pk": 5})
valid_user = {
"email": "testuser1@example.com",
"first_name": "bob",
"last_name": "von peer"
}
invalid_user = {
"email": "johnny@nevergonnaupdate.com"
}
def test_unauthorized_user_view(self):
response = self.client.get(self.valid_url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_authorized_but_forbidden_user_view(self):
self._regular_auth()
response = self.client.get(self.valid_url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_authorized_and_permitted_valid_user_view(self):
self._super_auth()
response = self.client.get(self.valid_url)
expected_data = UserSerializer(User.objects.get(pk=1)).data
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, expected_data)
def test_authorized_and_permitted_invalid_user_view(self):
self._super_auth()
response = self.client.get(self.invalid_url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_unauthorized_user_update(self):
response = self.client.post(self.valid_url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_authorized_but_forbidden_user_update(self):
self._regular_auth()
response = self.client.post(self.valid_url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_authorized_and_permitted_valid_user_update(self):
self._super_auth()
response = self.client.put(self.valid_url, self.valid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, self.valid_user)
def test_authorized_and_permitted_invalid_user_update(self):
self._super_auth()
response = self.client.put(self.valid_url, self.invalid_user, format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:55:04.670",
"Id": "418577",
"Score": "0",
"body": "you could reduce the code with data driven tests"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:55:27.613",
"Id": "418602",
"Score": "0",
"body": "You no need to rewrite all tests again, just put all your repetible code inside a class and then each test class can inherits from this new class. I think that is totally nessesary test all about permissions on each view and it doesn't redundat"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:59:25.800",
"Id": "418603",
"Score": "0",
"body": "I will you share a [repository](https://github.com/german970814/siiom) on Github, you can see how I implement TDD, and I have another repos with similar implementation, but they are in other languages"
}
] | [
{
"body": "<p>As a side note, including your \"includes\" in the code you want reviewed makes it much easier to do so, this way we don't have to check if, for example <code>APIClient</code> and <code>User</code> are parts of the django library, because it's not really mandatory to understand Django to review unit testing.</p>\n\n<p>Now, for the review : </p>\n\n<p><code>test_authorized_and_permitted_users_view</code> :</p>\n\n<p>You test that <code>User.objects</code> contains two items, but the code you are testing has nothing to do with this. By writing this, you are testing your unit test kind of like this :</p>\n\n<pre><code>def some_method(parameter):\n return paramter+1\n\ndef some_test():\n parameter = 1\n result = some_method(parameter)\n\n self.assertEqual(parameter, 1)\n ....\n</code></pre>\n\n<p>You already test that <code>expected_data = response.data</code> and that's plenty enough. It's a \"risk\" to test more than your test should test because if something ever changes that isn't related to the tested code and the test fails, well you might search for awhile what's the problem and bad tests are worst than no test (citation needed).</p>\n\n<p><code>test_authorized_and_permitted_invalid_user_create</code></p>\n\n<p>This test isn't \"unit\", it tests two things. It tests that an authorized user can access the page and it tests that the creation fails with an invalid user. It should be two tests, because if your test ever fails you don't want to wonder if it's because of a change in the authentication module or in the user creation module (That's pretty much the point of a unit test)</p>\n\n<p>For your other tests, there are also places where both these comments apply. Apart from these points, I think you've pretty much nailed the principle of unit testing. What isn't shown in your code though, is if you use dependency injection. This is a pretty valuable tool when it comes to unit testing, because you don't want to have complex mechanisms running when your unit tests run. There are two <strong>important</strong> (I really felt the need to bold that word :p) reasons for this : </p>\n\n<ol>\n<li>If your tests are slow, chances are devs won't run them. And if you force them to run before pushing or stuff like that, they'll a) loose time while the tests are running b) won't push as often as they should.</li>\n<li><p>It makes another thing that could make your test fail for the wrong reason. If, for example, you have </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def some_simple_unit_test():\n real_database.connect()\n\n # do things and assert\n</code></pre></li>\n</ol>\n\n<p>If the database connection fails for whatever reason, your test will fail, but was it really what you wanted? Does your test <strong>really</strong> need to test access to a database or could it access some simple in-memory data storage for a simple unit test? Wouldn't you expect whichever database provider who wrote the package to have tested it first, so you don't need to? </p>\n\n<p>The whole point of this last point is to tell you that it's important to keep tests simple and I don't think it's been done enough in your case (But maybe there're some tests configuration I'm missing)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T23:32:07.667",
"Id": "225494",
"ParentId": "216339",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:48:23.820",
"Id": "216339",
"Score": "7",
"Tags": [
"python",
"unit-testing",
"django",
"rest",
"authorization"
],
"Title": "TDD tests for every view and its permissions in a REST API"
} | 216339 |
<p>I have one following question and write a function for it. can anyone give me some suggestion how my code can be better and better way to handle to build up return list with even frequency?</p>
<blockquote>
<p>One message system contains two device type message that each message is formatted with device type identifier with
device id and message count. Write a function to parse the message based on device type and message count and return
a list with each device id in even message frequency<br>
rule: input string: message<br>
device identifier<br>
1:iOS device ID identifier: start with 'I' following with 3 character, total length is 4 character<br>
2:Android device ID identifier: start with 'A' following with 2 character, total length is 3 character<br>
3:message count is following by device id until next device ID<br>
ex:
input: Asq2: {'Asq': 2} Asq with 2 message count<br>
output: ['Asq', 'Asq']</p>
<p>input: Akb2IAld3: ID: {'Akb': 2, 'IAld2': 3} Akb with 2 message count, IAld with 3 message count<br>
output: ['Akb', 'IAld', 'Akb', 'IAld', 'IAld']</p>
<p>input: Aqp1Iasd2Aqp4IAbd1: {'Aqp': 5, 'Iasd': 2, 'IAbd': 1}<br>
output: ['Aqp', 'Iasd', 'IAbd', 'Aqp', 'Iasd', 'Aqp', 'Aqp', 'Aqp']</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>from typing import List
def parse_message(string) -> List:
i, j, ids_map, n, ids = 0, 0, dict(), len(string), ''
while i < n:
if string[i] in ('I', 'A') or i == n - 1:
if ids:
if i == n - 1:
ids_map[ids] = ids_map.get(ids, 0) + int(string[j:])
else:
ids_map[ids] = ids_map.get(ids, 0) + int(string[j:i])
j = i + 4 if string[i] == 'I' else i + 3
ids = string[i:j]
i = j - 1
i += 1
res = []
while any(i > 0 for i in ids_map.values()):
for k, v in ids_map.items():
if v > 0:
res.append(k)
ids_map[k] -= 1
return res
</code></pre>
| [] | [
{
"body": "<p>Your code is really hard to understand. When I read the description I noticed three steps:</p>\n\n<ol>\n<li>Extract ID and message count.</li>\n<li>Total duplicate message counts.</li>\n<li>Return a round robin of these IDs.</li>\n</ol>\n\n<p>You've got 1&2 mangled together, and 3 nicely by itself.</p>\n\n<p>Since you're using Python, it's easier to read iterator based approaches to these things. Firstly you can replace your step 3 with a recipe from the <code>itertools</code> standard library. All you need to do is call <code>itertools.repeat</code> beforehand.</p>\n\n<p>It's not immediately clear what your code is doing when you've mangled indexed iteration with business logic, with step 2 as well. And so I suggest re-writing it. You know the data will come in the form <code>{type}{message}{amount}</code>, where the type and amount has a length of 1, and message is either 2 or 3. And so to extract the messages and amounts you can just use <code>next</code>/<code>islice</code> on an iterator. Using a <code>try</code> <code>while</code> loop. After this totaling the message counts is simple.</p>\n\n<p>Also if you're going to use <code>typing</code> you should use mypy too, and put type information on both the arguments and return types.</p>\n\n<p>from typing import List, Iterator, Tuple, Sequence, TypeVar\n import itertools</p>\n\n<pre><code>MESSAGE_LENGTH = {\n 'I': 3,\n 'A': 2\n}\n\nTValue = TypeVar('TValue')\n\n\ndef roundrobin(*iterables: Tuple[Sequence[TValue], ...]) -> Iterator[TValue]:\n \"roundrobin('ABC', 'D', 'EF') --> A D E B F C\"\n # Recipe credited to George Sakkis\n num_active = len(iterables)\n nexts = itertools.cycle(iter(it).__next__ for it in iterables)\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = itertools.cycle(itertools.islice(nexts, num_active))\n\n\ndef extract_messages(input: Iterator[str]) -> Iterator[Tuple[str, int]]:\n input = iter(input)\n message_type = next(input)\n while True:\n length = MESSAGE_LENGTH[message_type]\n message = ''.join([message_type] + list(itertools.islice(input, length)))\n message_type = next(input)\n number = []\n try:\n while message_type not in MESSAGE_LENGTH:\n number += [message_type]\n message_type = next(input)\n except StopIteration:\n break\n finally:\n yield message, int(''.join(number))\n\n\ndef parse_message(string: str) -> List[str]:\n message_counts = {}\n for message, amount in extract_messages(string):\n message_counts.setdefault(message, 0)\n message_counts[message] += amount\n\n return list(roundrobin(*(\n itertools.repeat(key, amount)\n for key, amount in message_counts.items()\n )))\n\n\nif __name__ == '__main__':\n print(parse_message('Akb2IAld3'))\n print(parse_message('Aqp1Iasd2Aqp4IAbd1'))\n print(parse_message('Aqp1Iasd2Aqp4IAbd10'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:32:13.173",
"Id": "418598",
"Score": "0",
"body": "thanks for feedback. however need to clarify that length of message count does not have to be 1, we may have input like `Akb2000IAld300`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:34:15.447",
"Id": "418599",
"Score": "0",
"body": "@A.Lee I don't see that in the examples or text you gave in your original post. It's also easy to change my code to account for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:35:14.883",
"Id": "418600",
"Score": "0",
"body": "understand, again, great feedback and lots of great point. thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:43:09.640",
"Id": "418601",
"Score": "0",
"body": "@A.Lee Please see the updated code to handle that. In the future I'd recommend that you link to challenge descriptions so these errors don't happen again. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:37:08.500",
"Id": "216346",
"ParentId": "216340",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:49:20.937",
"Id": "216340",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "find substring with count and return even frequency substring list"
} | 216340 |
<p>I have created a simple CRUD method using Web API project which consumed by 2 platform: Console App and MVC Web Application. The EntityModel project is mainly the entity and the DAL layer. Is my architecture/structure okay in regards to implementing Web Api? Should I have this DTO thingy or do without? There is only one entity which is the Employee class.</p>
<pre><code>using EntityModel;
using EntityModel.DAL;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
namespace WebApi.Controllers
{
public class EmployeeController : ApiController
{
private AppDbContext db = new AppDbContext();
// GET api/Employee
public IQueryable<Employee> GetEmployees()
{
return db.Employees;
}
// GET api/Employee/5
[ResponseType(typeof(Employee))]
public IHttpActionResult GetEmployee(int id)
{
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}
// PUT api/Employee/5
public IHttpActionResult PutEmployee(int id, Employee employee)
{
if (id != employee.EmployeeID)
{
return BadRequest();
}
db.Entry(employee).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST api/Employee
[ResponseType(typeof(Employee))]
public IHttpActionResult PostEmployee(Employee employee)
{
db.Employees.Add(employee);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
}
// DELETE api/Employee/5
[ResponseType(typeof(Employee))]
public IHttpActionResult DeleteEmployee(int id)
{
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return NotFound();
}
db.Employees.Remove(employee);
db.SaveChanges();
return Ok(employee);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool EmployeeExists(int id)
{
return db.Employees.Count(e => e.EmployeeID == id) > 0;
}
}
</code></pre>
<p>}</p>
<p>Full solution source code is available in my git - <a href="https://github.com/ngaisteve1/WebAPIDemo" rel="nofollow noreferrer">https://github.com/ngaisteve1/WebAPIDemo</a></p>
<p><a href="https://i.stack.imgur.com/0jVLr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0jVLr.jpg" alt="enter image description here"></a></p>
<p>I just check on Microsoft article on Domain-Driven Design. I think I have combined Domain layer and Infrastructure layer, right?</p>
<p><a href="https://i.stack.imgur.com/jXuTM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jXuTM.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:10:47.453",
"Id": "418578",
"Score": "1",
"body": "I'm not going to do a full review; suffice to say that merely seeing `private AppDbContext db = new AppDbContext();` already breaks a cardinal rule. Please read the \"lifetime\" section @ https://docs.microsoft.com/en-us/ef/ef6/fundamentals/working-with-dbcontext . Also, keep your controllers lean: https://jonhilton.net/2016/06/06/simplify-your-controllers-with-the-command-pattern-and-mediatr/ . See also https://stackoverflow.com/a/8828946/648075 . See also https://gunnarpeipman.com/aspnet/why-to-avoid-fat-controllers/ . Etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:14:45.960",
"Id": "418580",
"Score": "1",
"body": "We review only code that is posted in the question so if you have any concerns about your DAL then you should post its code too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T02:01:35.090",
"Id": "418639",
"Score": "0",
"body": "I have just edited to add the screen shot of my solution structure"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T02:02:21.033",
"Id": "418640",
"Score": "0",
"body": "@BCdotWEB thanks. Will look into those items."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:03:06.643",
"Id": "216341",
"Score": "2",
"Tags": [
"c#",
"asp.net-web-api"
],
"Title": "Web API CRUD Demo with Console App and MVC Web Application"
} | 216341 |
<p>I have the following very simple class:</p>
<pre class="lang-cpp prettyprint-override"><code>class accusation
{
private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
};
</code></pre>
<p>I have overloaded my extraction from istream operator as follows:</p>
<pre class="lang-cpp prettyprint-override"><code>std::istream& operator>>(std::istream& is, accusation& readable)
{
std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))
{
std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);
}
if (accusation.size() == 3)
{
is.clear();
bool valid{ false };
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)
{
valid = true;
break;
}
if (valid)
{
valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)
{
valid = true;
break;
}
if (valid)
{
valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)
{
valid = true;
break;
}
if (valid)
{
readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
return is;
}
</code></pre>
<p>I am reading input as <code>green, dagger, kitchen</code> and storing it in my accusation. The first element has to be in <code>clue::characters</code> (an array of possible game characters), second element in <code>clue::weapons</code>, and third element in <code>clue::places</code>.</p>
<p>Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is <strong>a lot</strong> of space for improvements. Any push into the right direction is highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:43:53.377",
"Id": "418583",
"Score": "1",
"body": "Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)"
}
] | [
{
"body": "<p>95 percent of programming is looking for redundancies and eliminating them.</p>\n\n<p>For example, why do you bother with reading strings into <code>accusations[]</code> first, and then <em>later</em> copying them into <code>readable.murderer</code> et cetera? Why not just read them directly into <code>readable.murderer</code>? This would have the bonus of eliminating those \"magic number\" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.</p>\n\n<pre><code>std::getline(is, readable.murderer, ',');\nstd::getline(is, readable.weapon, ',');\nstd::getline(is, readable.place, ','); // shouldn't this last one be '\\n' not ','?\n</code></pre>\n\n<p>You should test your code and see if it does what you wanted.</p>\n\n<pre><code>std::istringstream iss(\n \"Mr Green, lead pipe, conservatory\\n\"\n \"Mrs Peacock, noose, kitchen\"\n);\naccusation acc;\niss >> acc;\n</code></pre>\n\n<p>This reads 5 items into <code>accusation</code>. Is this what you wanted to happen?</p>\n\n<hr>\n\n<p>Reduce repetition. You have the following snippet repeated three times:</p>\n\n<pre><code> for (const auto& THING : THINGS)\n if (accusation[INDEX] == THING)\n {\n valid = true;\n break;\n }\n</code></pre>\n\n<p>So, first of all, we wrap the loop body in curly braces to protect against <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"noreferrer\">goto fail</a>; and then we factor it out into a function.</p>\n\n<pre><code>template<class T>\nbool vector_contains(const std::vector<T>& vec, const T& value) {\n for (auto&& elt : vec) {\n if (elt == value) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>And then our main function's code can become simply</p>\n\n<pre><code>bool valid = vector_contains(clue::characters, readable.murderer)\n && vector_contains(clue::weapons, readable.weapon)\n && vector_contains(clue::places, readable.place);\nif (!valid) {\n is.setstate(std::ios_base::failbit);\n}\n</code></pre>\n\n<hr>\n\n<p>The body of <code>vector_contains</code> could also be implemented simply by using an STL algorithm, e.g.</p>\n\n<pre><code>template<class T>\nbool vector_contains(const std::vector<T>& vec, const T& value) {\n return std::count(vec.begin(), vec.end(), value);\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>template<class T>\nbool vector_contains(const std::vector<T>& vec, const T& value) {\n return std::find(vec.begin(), vec.end(), value) != vec.end();\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>template<class T>\nbool vector_contains(const std::vector<T>& vec, const T& value) {\n return std::any_of(vec.begin(), vec.end(), [&](const auto& elt) {\n return elt == value;\n });\n}\n</code></pre>\n\n<p>I named the function <code>vector_contains</code>, rather than simply <code>contains</code>, because in my estimation there is a very real possibility that C++2a might add <code>std::contains</code> to the library <a href=\"https://quuxplusone.github.io/blog/2018/06/17/std-size/\" rel=\"noreferrer\">and thus break any code using ADL calls to <code>contains</code>.</a></p>\n\n<hr>\n\n<p>Minor nits:</p>\n\n<ul>\n<li><p>I strongly recommend making all your constructors <code>explicit</code>, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)</p></li>\n<li><p>I strongly recommend making <code>operator>></code> and <code>operator<<</code> into <em>inline</em> friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your <code>operator>></code> to be only five or six lines long! :)</p></li>\n</ul>\n\n<hr>\n\n<p>You're also doing something weird with <code>stringstream</code> to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,</p>\n\n<pre><code>std::string strip(const std::string& s)\n{\n int i = 0;\n while (isspace(s[i])) ++i;\n int j = s.size();\n while (j >= 1 && isspace(s[j-1])) --j;\n return s.substr(i, j-i);\n}\n</code></pre>\n\n<p><a href=\"https://wandbox.org/permlink/uVSolN0Nepk48Mgm\" rel=\"noreferrer\">https://wandbox.org/permlink/uVSolN0Nepk48Mgm</a></p>\n\n<pre><code>class accusation\n{\nprivate:\n std::string murderer;\n std::string weapon;\n std::string place;\npublic:\n accusation() = default;\n explicit accusation(std::string, std::string, std::string);\n friend std::ostream& operator<<(std::ostream&, const accusation&);\n friend std::istream& operator>>(std::istream& is, accusation& a) {\n std::getline(is, a.murderer, ',');\n std::getline(is, a.weapon, ',');\n std::getline(is, a.place);\n if (!vector_contains(clue::characters, a.murderer) ||\n !vector_contains(clue::weapons, a.weapon) ||\n !vector_contains(clue::places, a.place)) {\n is.setstate(std::ios_base::failbit);\n }\n return is;\n }\n};\n</code></pre>\n\n<p>Deciding whether your <code>std::transform</code> lowercasing should be removed, kept, or folded into the helper function <code>vector_contains</code> (renaming that function to indicate its new purpose, and using a non-mutating facility such as <code>strcasecmp</code>) is left as an exercise for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:01:08.160",
"Id": "418588",
"Score": "0",
"body": "Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:25:05.190",
"Id": "418589",
"Score": "1",
"body": "Given that you made `mr green` acceptable as a synonym for `Mr Green`, maybe you should consider whether `mrgreen` should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to `strcasecmp`, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter `Mr Green` using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at https://en.wikipedia.org/wiki/Approximate_string_matching for ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T23:23:01.397",
"Id": "418859",
"Score": "0",
"body": "Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid `accusation` objects with broken invariants. Writing into a temp object then moving into `a`, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:39:36.393",
"Id": "216350",
"ParentId": "216343",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "216350",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:20:16.083",
"Id": "216343",
"Score": "7",
"Tags": [
"c++",
"beginner",
"parsing",
"stream",
"overloading"
],
"Title": "Overloading istream>> to read comma-separated input"
} | 216343 |
<p>I want to reduce some repeated code in my Java 1.8/Spring Boot application, and to that end I tried to make a reuseable asynchronous utility module. <strong>In essence its an async List.forEach</strong> that takes a List and a consumer for each item of the list. Output is optional.</p>
<hr>
<p><strong>AsyncUtilImpl</strong></p>
<pre class="lang-java prettyprint-override"><code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
public class AsyncUtilImpl implements AsyncUtil {
private TaskExecutor executor;
@Autowired
@Qualifier("threadPoolTaskExecutor")
public void setTaskExecutor(TaskExecutor exe){
this.executor = exe;
}
public void configureExecutor(int threadCount){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadCount);
executor.setMaxPoolSize(threadCount);
executor.setThreadNamePrefix("async_thread_");
executor.initialize();
this.executor = executor;
}
public <E> List<Throwable> consumeListAsync(List<E> list, Consumer<E> handler){
return consumeListAsync(list, handler, this.executor);
}
public <E> List<Throwable> consumeListAsync(List<E> list, Consumer<E> consumer, TaskExecutor executor){
List<Throwable> errors = new ArrayList<>();
try{
if(executor == null || executor.equals(null)){throw new NullPointerException("Executor null, ensure that your Executor is non-null or else that the local executor is configured");}
List<CompletableFuture<Void>> asyncTaskList = list
.stream()
.map(e -> AsyncCall
.accept(consumer, e, executor)
.handle((info, error) -> {
if(error != null){
errors.add(error);
return null;
}
return CompletableFuture.completedFuture(info);
})
.thenCompose(Function.identity())
).collect(Collectors.toList());
CompletableFuture<Void> process =
CompletableFuture.allOf(asyncTaskList.toArray(new CompletableFuture[asyncTaskList.size()]))
.thenRun(() -> asyncTaskList.stream().map(future -> future.join()));
process.get();
}catch(Exception e){
errors.add(e);
}
return errors;
}
@Async
private static class AsyncCall{
public static <E> CompletableFuture<Void> accept(Consumer<E> consumer, E e, Executor executor){
return CompletableFuture.runAsync(()-> consumer.accept(e), executor);
}
}
}
</code></pre>
<p><strong>An Incomplete explanation of Design/Choices</strong></p>
<p>Firstly, void returns:
I focused on a void-execution model because of the nature of my app's calls (mostly db CRUD, heavy C and U) These calls have no need of a return type, and this is reflected in my design. <strong>However</strong>, returning data is simple when combined with an Accumulator:</p>
<pre class="lang-java prettyprint-override"><code>List<SomeType> taskItems = ...
List<SomeOtherType> resultAccumulator = ...
List<Throwable> errors = AsyncUtil.consumeListAsync(
taskItems,
(SomeType item)-> resultAccumulator.add(someReturningProcess(item))
);
if(errors.isEmpty()){doSomethingWithResults(resultAccumulator);}
</code></pre>
<p>Second, errors:
The Async call hides exceptions thrown inside the thread of execution. I .handle these exceptions and create a List of these thread-level exceptions. I return this list of errors, and the user can choose how to respond to these errors. List.isEmpty() indicates completion without errors</p>
<hr>
<p>In the client code, I check for errors like so:</p>
<pre class="lang-java prettyprint-override"><code>...
List<Throwables> errors = AsyncUtil.consumeListAsync(...);
for(Throwable th : errors){
if(th instanceof ExecutionException
|| th instanceof InterruptedException){
throw new RuntimeException(th);
}else{
th.printStackTrace();
}
}
</code></pre>
<p><strong>Is this error handling acceptable given the context? Is this good design for a reusable utility? Is it as extensible/configurable as should be expected from a modern utility?</strong></p>
<p>Any feedback (even feedback that isn't targeting the above questions, and ESPECIALLY feedback as to the format of how I asked this question) is much appreciated</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:44:10.693",
"Id": "216351",
"Score": "2",
"Tags": [
"java",
"multithreading",
"asynchronous",
"spring"
],
"Title": "Let Them Eat Lists, Eventually (Asynchronous Generic List Consumption with Spring and CompletableFuture)"
} | 216351 |
<p>I was told to code a board game app using React for a job interview.<br/>
They told me they chose other candidates to move forward with, so I was wondering on what I could improve.</p>
<p>The full code can be viewed <a href="https://github.com/Kashio/react-board-game" rel="nofollow noreferrer">here</a>.<br/>
Here are the more interesting components:</p>
<p><code>TicTacToeGame</code></p>
<pre><code>import React, {useCallback} from 'react'; // useCallback imported by mistake here..
import './tic-tac-toe.scss';
import update from 'immutability-helper';
import Board from '@/board/board';
import ScoreList from '@/score-list/score-list';
import {isGameOver, isDraw} from '../../utils/tic-tac-toe';
import x from '#/images/x.svg';
import o from '#/images/o.svg';
import restart from '#/images/restart.svg';
const X = 0;
const O = 1;
const EMPTY = 2;
const xImg = <img className="xo" src={x}/>;
const oImg = <img className="xo" src={o}/>;
const IMAGE_MAP = {
[X]: xImg,
[O]: oImg
};
const INITIAL_STATE = {
turn: 0,
players: [{
score: 0
}, {
score: 0
}],
board: [
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]
]
};
class TicTacToe extends React.Component {
constructor(props) {
super(props);
this.state = INITIAL_STATE;
}
renderBox = (row, column) => {
const {board} = this.state;
const value = board[row][column];
if (value === EMPTY) {
return null;
}
return IMAGE_MAP[value];
};
boxClickHandler = (row, column) => {
const {turn, players, board} = this.state;
const value = board[row][column];
if (value === EMPTY) {
const newBoard = update(board, {[row]: {$splice: [[column, 1, turn % 2]]}});
if (isGameOver(newBoard, row, column)) {
// React will batch both setStates since it's in onClick event handler
const newPlayers = update(players, {
[turn % 2]: {
score: {
$apply: function (s) {
return s + 1;
}
}
}
});
this.setState({
turn: INITIAL_STATE.turn,
players: newPlayers,
board: INITIAL_STATE.board
});
} else if (isDraw(board, turn)) {
this.setState({
turn: INITIAL_STATE.turn,
players,
board: INITIAL_STATE.board
});
}
else {
this.setState({
turn: turn + 1,
board: newBoard
});
}
}
};
resetGame = () => {
this.setState({
...INITIAL_STATE
});
};
render() {
const {players, board} = this.state;
return <div className="tic-tac-toe">
<div className="tic-tac-toe-row">
<div className="tic-tac-toe-wrapper">
<h1 className="title">
Tic - Tac - Toe
</h1>
</div>
</div>
<div className="tic-tac-toe-row">
<div className="tic-tac-toe-wrapper">
<Board
board={board}
width={400}
height={400}
isGameOver={isGameOver}
boxTemplate={this.renderBox}
onBoxClick={this.boxClickHandler}/>
</div>
</div>
<div className="tic-tac-toe-row">
<div className="tic-tac-toe-wrapper">
<div className="scores-and-reset">
<ScoreList
width={340}
height={100}
players={players}/>
<button className="reset-button" onClick={this.resetGame}>
Reset
<img src={restart}/>
</button>
</div>
</div>
</div>
</div>;
}
}
export default TicTacToe;
</code></pre>
<p><code>Board</code></p>
<pre><code>import React, {useCallback} from 'react';
import './board.scss';
import Box from '@/box/box';
import classNames from 'classnames';
const Board = ({board, width, height, boxTemplate, onBoxClick}) => {
return <div className="board" style={{width, height}}>
{board.map((row, i) => <div key={i} className="row" style={{height: height / board.length}}>
{row.map((column, j) => {
const boxClass = classNames({
top: i !== 0,
right: j !== row.length - 1,
bottom: i !== board.length - 1,
left: j !== 0
});
const memoizedBoxClickCallback = useCallback(
(e) => {
onBoxClick(i, j);
},
[i, j],
);
return <Box key={i + j} className={boxClass} width={width / row.length} height={height / board.length} onClick={memoizedBoxClickCallback}>
{boxTemplate(i, j)}
</Box>;
})}
</div>
)}
</div>;
};
export default Board;
</code></pre>
<p><code>Box</code></p>
<pre><code>import React from 'react';
import './box.scss';
class Box extends React.PureComponent {
render() {
const {children, className, width, height, onClick} = this.props;
return <div className={`box ${className} pointer`} style={{width, height}} onClick={onClick}>
{children}
</div>;
}
}
export default Box;
</code></pre>
<p>Design choices:</p>
<ul>
<li><p>I tried to make the base components reusable for other implementation of board games so I pass <code>onClick</code> handler for the <code>Box</code> component and <code>boxTemplate</code> function as a children to the <code>Box</code> component to render whatever the game wants (e.g TicTacToeGame will render XO respectively, SnakesNLaddersGames will render snakes and ladders respectively and so on..), also the <code>Board</code> component sets class <code>top</code> <code>right</code> <code>left</code> <code>bottom</code> respectively (depends on where the box is relative to the edge of the board) without styles for each <code>Box</code> so the game component it-self could decide on the styling of these components based on the location of the <code>Box</code>.</p></li>
<li><p>I didn't use any state management library as this is a pretty small project. I know adding such library could benefit me in the future for when the application expands, but right now I don't see a reason for the state logic update (which is inside the function <code>boxClickHandler</code> in <code>TicTacToeGame</code>) to be inside a reducer function (even if using <code>useReducer</code> hook) because this logic is not a reusable logic for other board games that might get implemented using the base <code>Board</code> and <code>Box</code> components.</p></li>
</ul>
<p>The only thing I didn't took into account is that the functional component <code>Board</code> might get rendered for nothing if a game component state <em>which doesn't require board update</em> will change, but since I implemented only <code>TicTacTacGame</code> and all its state requires re-render of the <code>Board</code> component I didn't took this into account. If I were to solve this I would just use <code>PureComponenet</code> or <code>React.memo</code> on the component.</p>
| [] | [
{
"body": "<p>Overall, it looks pretty good to me, pretty much all my comments are opinionated to a lesser or (often) greater extent. I'd summarize my main feedback as \"<a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>\" and \"think readability, not reusability\".</p>\n\n<hr>\n\n<h3>Less Reusability</h3>\n\n<p>Unless it was stipulated in the interview, I think the concern of trying to make this reusable was unnecessary and somewhat unhelpful. IMO, premature reusability is a common source of unnecessary complication (like premature optimization). </p>\n\n<p>Certainly, there are some obvious cases for reusability (like UI widgets), but trying to make core \"business concerns\" like a game implementation reusable is, in my experience, often more trouble than it's worth. In general, YAGNI. And when you guess about how something may be reused in the future you often build the <a href=\"https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction\" rel=\"nofollow noreferrer\">wrong abstraction</a>.</p>\n\n<p>Specifically, I think the Board and Box are complicated by trying to be more flexible than they really need to be.</p>\n\n<h3>More CSS</h3>\n\n<p>The CSS code wasn't included, but you should probably leverage CSS more. </p>\n\n<ul>\n<li><p>Setting explicit widths and heights in the view is inflexible and could probably be handled more gracefully in CSS - depending on browser support requirements, <a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"nofollow noreferrer\">CSS Grid</a> might be a good fit, but more 'traditional' approaches would work too. (Even if you went with fixed width/height, it'd still be better to have that in CSS than your HTML)</p></li>\n<li><p>Similar with <code>left</code>, <code>right</code>, <code>top</code>, <code>bottom</code>: which I believe are better handled with <code>:first-child</code> and <code>:last-child</code> selectors. </p></li>\n</ul>\n\n<h3>State Management</h3>\n\n<p>I agree with your decision to not use a state management library, as I do think that would be overkill. I do, however, find the large amount of logic in <code>boxClickHandler</code> unsatisfying - it's not wrong, but I don't think it's very good readability to have the entire tic-tac-toe logic in a click handler: some separation of the view and the logic would be good.</p>\n\n<p>I do think <code>useReducer</code> would be a good fit: personally I'd probably define the reducer function in its own file - it's good for readability from a separation of concerns perspective, and if you were going to write unit tests it'd be much better for that. It's trivial to write good unit tests for a reducer function - much harder when that logic is in a click handler.</p>\n\n<p>(Though even just defining a <code>makeMove</code> function on the <code>TicTacToe</code> component and calling it from the click handler would have been something of an improvement, IMO)</p>\n\n<h3>Nits</h3>\n\n<ul>\n<li>Maybe split things into more components: the TicTacToe component has fairly large render function: personally, I like my top-level components to look more like:</li>\n</ul>\n\n<pre><code>render() {\n return (\n <>\n <Title />\n <Game /*...*/ /> \n <Scores /*...*/ />\n </>\n )\n}\n</code></pre>\n\n<p>(Even if those components are just defined elsewhere in the same file, I like when a component's render function makes the overall structure obvious)</p>\n\n<ul>\n<li><code>useCallback</code> is technically violating the rules of hooks: it's not at the top of the function as hooks are supposed to be: they're not supposed to be in 'loops' like <code>.map</code>. In practice, the current version works: since there's always the same number of boxes, the call order is consistent, but I'd advise against breaking the hook rules, anyways. </li>\n</ul>\n\n<p>I'd probably share a single click handler among the boxes and either have the boxes pass in their <code>(i, j)</code> coordinate when they call the click handler, or the coordinates could be attached to the element via data-attributes and read by the click handler. </p>\n\n<p>Alternatively, you can save complexity by not using <code>useCallback</code> or <code>PureComponent</code> - both Dan Abramov and sophiebits (core React developers) have said that you <a href=\"https://stackoverflow.com/a/49685684\">shouldn't use <code>PureComputed</code> everywhere unless you've measured performance first</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:11:26.410",
"Id": "418624",
"Score": "0",
"body": "Thanks, I appreciate the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:02:48.177",
"Id": "216370",
"ParentId": "216352",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T16:19:53.927",
"Id": "216352",
"Score": "2",
"Tags": [
"interview-questions",
"tic-tac-toe",
"react.js",
"jsx",
"sass"
],
"Title": "React board game app"
} | 216352 |
<p>I have a simple app, which is something like a <strong>launcher for my macro enabled excel workbook</strong>. I made it for easier distribution, to be able to check if excel installed and also to make it look and behave like a standalone application.</p>
<p>I am <strong>using Office Interop</strong> which, according to MS, has many performance issues. But still, have you got any idea what I could improve to perform faster?</p>
<pre><code>Imports System.Threading
Imports Microsoft.Win32
Imports Microsoft.Office.Interop.Excel
Module Module1
Public Sub Main()
On Error GoTo ErrorHandler
Dim singleInstance As Boolean = False
Dim mutex As New Mutex(True, My.Application.Info.AssemblyName,
singleInstance)
Dim excelKey As RegistryKey = Registry.ClassesRoot.OpenSubKey("Excel.Application")
Dim excelInstalled As Boolean = If(excelKey Is Nothing, False, True)
If excelInstalled = True And singleInstance = True Then
SplashForm.Show()
Dim MyAppPath As String = My.Application.Info.DirectoryPath
Dim ExcelFilePath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Správce rozpisů 2019\" & "Rozpis1.xlsb")
If Not IO.File.Exists(ExcelFilePath) Then
Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis1.xlsb")
If IO.File.Exists(ExcelfileBackupPath) Then
My.Computer.FileSystem.CopyFile(ExcelfileBackupPath, ExcelFilePath, True)
Call Open(ExcelFilePath)
Else
SplashForm.Close()
ErrorForm.ShowDialog()
End
End If
Else
Call Open(ExcelFilePath)
End If
SplashForm.Close()
ElseIf excelInstalled = False Then
SplashForm.Close()
CompatibilityErrorForm.ShowDialog()
ElseIf singleInstance = False Then
MsgBox("Správce rozpisů je již spuštěn.", vbInformation, "Aplikace je již spuštěna")
End If
Exit Sub
ErrorHandler:
MsgBox("Při spouštění Správce rozpisů došlo k chybě.", vbCritical, "Došlo k chybě")
Resume Next
End Sub
Sub Open(openThis As String)
Dim xls As Application = New Application With {
.WindowState = XlWindowState.xlMaximized
}
Dim workbook As Workbook = xls.Workbooks.Open(openThis)
xls.Visible = True
End Sub
End Module
</code></pre>
| [] | [
{
"body": "<p>Interop is surely enough for this purpose. To <em>manipulate</em> workbooks, fill in 10.000th of cells then I usually use SpreadsheetLight (<a href=\"http://spreadsheetlight.com/\" rel=\"nofollow noreferrer\">http://spreadsheetlight.com/</a>), a free, MIT licensed .NET library that works on the XML level of the Excel files and is incredibly fast compared to the Application.Excel object.</p>\n\n<p>From the point of code review, I think you could dive a bit more into VB​<em>.NET</em>, your code still has the feeling of being VB6 or VBA. Why don't you switch to try/catch error handling for example? I assure you, you are going to like it. And as a rule of thumb, never compile any path/file names into your application, put them into app.config (especially if this is a standalone application) or into start parameters (especially if this application is called from within an enterprise database application).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-26T11:15:42.207",
"Id": "221054",
"ParentId": "216353",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221054",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:17:32.397",
"Id": "216353",
"Score": "1",
"Tags": [
"beginner",
"vb.net"
],
"Title": "Optimization - open excel file from VB.NET using interop"
} | 216353 |
<p>Calculating many remainders for each prime and composite consumes more time.</p>
<p>I use a factoring function to find factors of single values.</p>
<p>When I use a factoring function to find lists of primes, I use a wheel.</p>
<p>A wheel exploits composite values punctuating an otherwise prime sequence.</p>
<p>The primary advantage of a wheel is reducing significantly, the candidate list and so processing.</p>
<p>My wheel eliminates 2, 3, 5 and 7 multiples from the a list. For the longest time, I used only elimination of 2s, 3s and 5s because the wheel list is only 8 values and simple to construct but there are just to many 7s.</p>
<p>Take the list of primes 11,13,17,19,23,29,31,39 and add 30 to each of the previous 8 values for subsequent values.</p>
<p>Take the first 55 from the list and remove the 7 multiples. The deltas will be this wheel.</p>
<p>What should be faster is subtraction of one list from another where the calc is compare and once only for each.</p>
<pre><code>wl = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
-- the so-called wheel: the recurring pattern in a composite punctuated list
n7sl = scanl (+) 11 $ cycle wl -- infinite
-- short list of composits with no 2's, 3's 5's or 7's; 77%+ reduced
n7s = take 150 $ n7sl
-- diagonalize and limit the factor's composite list
lls i y = drop i.take y $ n7sl
-- substract the 1st list from the 2nd, infinite list
rms [] _ = [] -- stop when first list is exhausted
rms n@(x:xs) p@(y:ys)
| x==y = rms xs ys
| x>y = y:rms n ys
| y>x = rms xs p
-- generate the composite list
comps [] _ _ _ _ =[]
comps (n:ns) [] y i b = comps ns (lls (i+1) y) y (i+1) b
comps k@(n:ns) (r:rs) y i b
| m>b =comps ns (lls (i+1) y) y (i+1) b
| m<=b =m:comps k rs y i b
where m = n*r
-- the result of `comps` is not just a diagonalization but 2, top & irregular bottom
-- `comps` is maybe necessary to stop when the limit of a list is reached
-- otherwise, I was using a list comprehension which is way less complicated
-- `comps` has to many parameters so this to reduce it to 1
-- it will be subtracted the fixed length wheel numbers and the lazy wheel
comp1 n =sort $ comps n7s (lls 0 n) n 0 (11*(last.take n $ n7sl))
-- put everything together to generate primes
</code></pre>
<p>last $ rms (comp1 5000) n7sl</p>
<p>240641</p>
<p>(0.12 secs, 65,219,592 bytes)</p>
<p>last $ rms (comp1 10000) n7sl</p>
<p>481249</p>
<p>(0.24 secs, 143,743,944 bytes)</p>
<p>last $ rms (comp1 15000) n7sl</p>
<p>721891</p>
<p>(0.37 secs, 220,099,904 bytes)</p>
<p>Question is this better that factoring? Is there a better way to generate multiples without multiplying in <code>comps</code> or list comprehensions?</p>
<p>Any prime list I generate excludes 2,3,5 & 7 because they are misbehaved, irregular and to well known.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:33:17.850",
"Id": "418614",
"Score": "0",
"body": "Well, I had residuals. `rms` was written to remove 7s from 2s,3s,5s list. Remove sevens: `rms` Then, in `comps` I had had trouble with the multiple. It was in a where statement b/c it occurs 3 times. Then, after fixing another problem forgot to put it back."
}
] | [
{
"body": "<p>You should use more <code>Data.List</code> functions - explicit recursion is hard to read.</p>\n\n<pre><code>comp1 y = sort [ m\n | (i,n) <- zip [0..149] n7sl\n , m <- takeWhile ((<= 11 * last (take y n7sl))) $ map (n*) $ drop i $ take n n7sl\n ]\n</code></pre>\n\n<p>Edit: Not sure whether my version fails to be equal to your original one, but here's a further refactoring of the one in your comment to get rid of some number manipulation. The <code>takeWhile</code> reflects the short-circuiting behavior of the original, explicitly recursive implementation, which uses that <code>bs</code> is ascending.</p>\n\n<pre><code>t = sort [ m | bs@(a:_) <- tails n7s,\n m <- takeWhile (<= 11*last n7s) $ map (a*) bs]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:02:07.310",
"Id": "418698",
"Score": "0",
"body": "Well, thank you. Your comprehension removes a fixed amount from each factor sublist. Mine removes a varied amount according to value. Yours does not provide near enough of any. There should `n` multiples of 11 for `comp1 n`. Finally, it *must* work as a select list to subtract from the wheel to produce primes. Yours does not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:46:14.957",
"Id": "418705",
"Score": "0",
"body": "A list comprehension to produce the correct composits\n`n7s = take 50 n7sl`; \n`t = sort [ m | (a,i) <- zip n7s [0..], b <- drop i n7s, m <- [a*b], m <= (11*(last n7s))]`; \n`rms t n7sl`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T16:38:05.680",
"Id": "418823",
"Score": "0",
"body": "Well, I'm so impressed. I am also sorry. When I checked your results with mine I found a mismatch but it was because I had forgot to sort mine so I assumed yours was wrong. My bad. It is right. It is impressive and so clean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T01:51:54.990",
"Id": "418939",
"Score": "0",
"body": "With all the other advantages of this, it is also the fastest, if you move off the limit calculation with something like >`nt lim = sort [ m | bs@(a:_) <- tails n7s, m <- takeWhile (<= lim) $ map (a*) bs]` with `ntr = nt (11*last n7s)`. It should speed up the primes program nicely, Thanks again!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:03:03.110",
"Id": "216420",
"ParentId": "216354",
"Score": "4"
}
},
{
"body": "<p>Breaking up <code>comps</code> results in simpler, more efficient, easier to control functions.</p>\n\n<p>Two lists (x,y) for a Cartesian product are usual. The products are half duplicates. If each column starts with a perfect square, the duplicates are eliminated.</p>\n\n<p>Then each column is generated. Each column starts with a perfect square but then must also be specifically trimmed in length. Each multiple is compared to the limititing value.</p>\n\n<p>So, about 25% or less of the Cartesian product are used, that is, calculated.</p>\n\n<p><code>calcc</code> limits the value of each factor multiple it calculates just like <code>comps</code> but unlike <code>comps</code> it doesn't use an initial-factor list.\nEach initial-factor squared is first on the multiple list. Each initial-factor is the <code>head</code> of each factor lists input.</p>\n\n<p>I tried making <code>comps</code> use one list only instead of two. The function was short, more complicated but not faster. Two remaining problems with it were the calculation for the limit value which only needs to be calculated one time at the beginning and a problem with all such functions a glob of parameters or superflous <code>where</code> calculations. The functions need the parameters but should not be recalculated time-after-time.</p>\n\n<p><code>runr</code> passes the initial-factor to apply to itself and all other factors. The list sent to <code>calcc</code> starts with a perfect square factor value. The diagonal eliminates duplicates.</p>\n\n<p><code>rrunr</code> sarts <code>runr</code> with a length <code>n</code> factor list and the limit based on that list length.<br>\nThe 11 multiples extend to <code>n</code>. Successive columns shorten to none at about <code>n/10</code></p>\n\n<p>Checking every perfect square against the limit does not save time.</p>\n\n<p>I also tried <code>mergeAll</code> from Data.List.Ordered but it seemed to error around 3/4 the way down a prime list. I still have to investigate. <code>sort</code> is what I still use but the functions now let me create a single list or a list of lists for <code>mergeAll</code>. </p>\n\n<pre><code>calcc _ _ []= []\ncalcc f lim (x:xs)\n | m<= lim= m:calcc f lim xs\n | True= []\n where m= f*x\n\nrunr _ []= []\nrunr lim xss@(x:xs) = (calcc x lim xss)++runr lim xs\n\nrrunr n = runr lim ds\n where ds= take n n7sl\n lim= 11*last ds \n</code></pre>\n\n<p><code>last.rms (sort $ rrunr 5000) $ n7sl</code></p>\n\n<p>240641</p>\n\n<p>(0.07 secs, 50,617,744 bytes)</p>\n\n<p><code>last.rms (sort $ rrunr 10000) $ n7sl</code></p>\n\n<p>481249</p>\n\n<p>(0.18 secs, 115,282,560 bytes)</p>\n\n<p><code>last.rms (sort $ rrunr 15000) $ n7sl</code></p>\n\n<p>721891</p>\n\n<p>(0.25 secs, 179,096,928 bytes)</p>\n\n<p><strong>5/13/2019</strong></p>\n\n<p>I tried <code>unionAll</code> instead of <code>mergeAll</code> because each sub-list is already in order. It did result in a minor speed up. <code>runr</code> produces individual sub-lists for <code>unionAll</code>. </p>\n\n<pre><code>runr _ []= []\nrunr lim xss@(x:xs) = [calcc x lim xss]++runr lim xs\n</code></pre>\n\n<p><code>last $ rms (unionAll $ rrunr 10000) n7sl</code></p>\n\n<p>481249</p>\n\n<p>(0.12 secs, 89,250,264 bytes)</p>\n\n<p><code>last $ rms (unionAll $ rrunr 15000) n7sl</code></p>\n\n<p>721891</p>\n\n<p>(0.20 secs, 140,110,392 bytes)</p>\n\n<p><code>last $ rms (unionAll $ rrunr 20000) n7sl</code></p>\n\n<p>962509</p>\n\n<p>(0.27 secs, 192,858,656 bytes)</p>\n\n<p>I have an infinite version of this which is much simpler coding but it is a little slower.</p>\n\n<pre><code>mupcl _ [] = []\nmupcl (x:xs) (y:ys) = [(x*) <$> y]++ mupcl xs ys\n\nuat = unionAll.mupcl n7sl $ (\\i-> (take i n7sl)) <$> [1..]\n</code></pre>\n\n<p><code>take 50000 $ rms uat n7sl</code></p>\n\n<p>611993</p>\n\n<p>(0.45 secs, 269,026,264 bytes)</p>\n\n<p>I updated this because finding the nth prime is important and this can. It's still slower than the fixed just before this but has some uses not available to the fixed.\nI toyed with making the sublists sequences but then found that I could generate the sublist end value and multiply it by all previous values and itself. Sequence would access the end value in about O(1) which is awesome but the end values are in one-to-one correspondence with each sublist.</p>\n\n<p>The diagonal of these is just each sublist is one longer than the previous.This is the top diagonal necessary for an infinite list.</p>\n\n<p>The previous functions use a bottom diagonal and a limit value. If they used the top diagonal would they end as this function? IDK </p>\n\n<p><strong>5/27/2019</strong></p>\n\n<p>The composite list was being traversed twice and it was driving me nuts.\nI could not come up with a single function that would multiply two identical infinite lists diagonally. </p>\n\n<p>I had developed one function to multiply 2s, 3s & 5s together to form the Hamming list. Saturday morning I looked at that function and followed the pattern for this function. It amazed me it worked. <code>unionAll</code> does the limiting.</p>\n\n<pre><code>umap = unionAll $ map (\\n -> (n*) <$> n7sl) n7sl\n</code></pre>\n\n<p>But, I am such an impatient idiot the function is going through two lists, exactly what I didn't want. I have an aversion to <code>tails</code>, more like a phobia because of experience with <code>tails</code> crashing my PC in an infinite function. What I discovered the past two or three months is that <code>mergeAll</code> and <code>unionAll</code> do magic with infinite lists. They automatically limit end points. Talk about no coding. I spent so much time coding end points in this and in the Hamming numbers (which are way fast, too) that I really feel like an idiot. @Will Ness knows way more than I, too. Haskell is <code>pure</code> (no pun) magic with laziness.</p>\n\n<pre><code>c2 = unionAll $ map (\\xs@(x:_)-> (x*) <$> xs) $ tails n7sl\n</code></pre>\n\n<p><code>(minus n7sl c2) !! 1000000</code></p>\n\n<p>15485941</p>\n\n<p>(1.55 secs, 3,545,902,888 bytes)</p>\n\n<p>And now, it's way faster than the non-infinite above.</p>\n\n<p>This does 75803 primes to 962509 in 0.08 and the non-infinite does 75803 to 962509 in 0.27 and uses a little more memory.</p>\n\n<p>This does</p>\n\n<p><code>(minus n7sl c2) !! 75803</code></p>\n\n<p>962509</p>\n\n<p>(0.08 secs, 162,030,280 bytes)</p>\n\n<p><strong>5.30.2019</strong></p>\n\n<p>OMG. It worked! I told @Will Ness it might, but that it would not with the non-infinite. What it is is the size of the wheel. I started calling it a wheel when I saw the deltas to create it. Mine is not a wheel because I have to generate the deltas from a column in Excel. I take 300 of <code>n7sl</code> into a column in Excel them I remove all the 11 multiples. I take the deltas of the remainder then find where it repeats.</p>\n\n<p>My no 11s list is </p>\n\n<pre><code>n11s=[4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,14,4,6,2,10,2,6,6,4,2,4,6,2,10,2,4,2,12,10,2,4,2,4,6,2,6,4,6,6,6,2,6,4,2,6,4,6,8,4,2,4,6,8,6,10,2,4,6,2,6,6,4,2,4,6,2,6,4,2,6,10,2,10,2,4,2,4,6,8,4,2,4,12,2,6,4,2,6,4,6,12,2,4,2,4,8,6,4,6,2,4,6,2,6,10,2,4,6,2,6,4,2,4,2,10,2,10,2,4,6,6,2,6,6,4,6,6,2,6,4,2,6,4,6,8,4,2,6,4,8,6,4,6,2,4,6,8,6,4,2,10,2,6,4,2,4,2,10,2,10,2,4,2,4,8,6,4,2,4,6,6,2,6,4,8,4,6,8,4,2,4,2,4,8,6,4,6,6,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10,2,6,4,6,2,6,4,2,4,6,6,8,4,2,6,10,8,4,2,4,2,4,8,10,6,2,4,8,6,6,4,2,4,6,2,6,4,6,2,10,2,10,2,4,2,4,6,2,6,4,2,4,6,6,2,6,6,6,4,6,8,4,2,4,2,4,8,6,4,8,4,6,2,6,6,4,2,4,6,8,4,2,4,2,10,2,10,2,4,2,4,6,2,10,2,4,6,8,6,4,2,6,4,6,8,4,6,2,4,8,6,4,6,2,4,6,2,6,6,4,6,6,2,6,6,4,2,10,2,10,2,4,2,4,6,2,6,4,2,10,6,2,6,4,2,6,4,6,8,4,2,4,2,12,6,4,6,2,4,6,2,12,4,2,4,8,6,4,2,4,2,10,2,10,6,2,4,6,2,6,4,2,4,6,6,2,6,4,2,10,6,8,6,4,2,4,8,6,4,6,2,4,6,2,6,6,6,4,6,2,6,4,2,4,2,10,12,2,4,2,10,2,6,4,2,4,6,6,2,10,2,6,4,14,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,12,2,12]\nn11sl = scanl (+) 13 $ cycle n11s\n</code></pre>\n\n<p>The improvement is not stark and going any further with this would not be beneficial. <code>c2</code> modified to use <code>n11sl</code></p>\n\n<pre><code>c2 = unionAll $ map (\\xs@(x:_) -> (x*) <$> xs) $ tails n11sl\n</code></pre>\n\n<p>Executing it would be</p>\n\n<p><code>(11:(minus n11sl c2)) !! 1000000</code></p>\n\n<p>15485941</p>\n\n<p>(1.30 secs, 2,968,456,072 bytes)</p>\n\n<p><code>(11:(minus n11sl c2)) !! 500000</code></p>\n\n<p>7368841</p>\n\n<p>(0.55 secs, 1,305,594,104 bytes)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:38:12.900",
"Id": "219366",
"ParentId": "216354",
"Score": "3"
}
},
{
"body": "<p>After simplifications, your <em>infinite</em> code (from your <em>answer</em>) turns out to be equivalent to</p>\n\n<pre><code>import Data.List (tails)\nimport Data.List.Ordered (minus, unionAll)\n\nprimes = ([2,3,5,7] ++) . minus n7sl . unionAll $\n [ map (x*) xs | xs@(x:_) <- tails n7sl ]\n</code></pre>\n\n<p>The main difference is that whereas your code builds the matrix</p>\n\n<pre><code>> mapM_ print $ take 20 $ zip n7sl [take i n7sl | i <- [1..]]\n(11,[11])\n(13,[11,13])\n(17,[11,13,17])\n(19,[11,13,17,19])\n(23,[11,13,17,19,23])\n(29,[11,13,17,19,23,29])\n(31,[11,13,17,19,23,29,31])\n(37,[11,13,17,19,23,29,31,37])\n(41,[11,13,17,19,23,29,31,37,41])\n(43,[11,13,17,19,23,29,31,37,41,43])\n(47,[11,13,17,19,23,29,31,37,41,43,47])\n(53,[11,13,17,19,23,29,31,37,41,43,47,53])\n(59,[11,13,17,19,23,29,31,37,41,43,47,53,59])\n(61,[11,13,17,19,23,29,31,37,41,43,47,53,59,61])\n(67,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67])\n(71,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71])\n(73,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73])\n(79,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79])\n(83,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83])\n(89,[11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89])\n</code></pre>\n\n<p>by rows (in each row, the list is multiplied by the first number in the tuple), and processes it by rows -- putting them through the <code>unionAll</code> process -- the rewrite in this answer is <em>as if</em> working on the <em>same</em> matrix <em>by columns</em> (after the multiplication by the first number in the tuple, again).</p>\n\n<p>Because <code>tails</code> is much less computationally demanding compared with your repeated use of <code>take</code>, and because we use <code>minus</code> from <code>Data.List.Ordered</code> package instead of your <code>rms</code> (with the flipped order of arguments), this runs much <em>much</em> faster now. Testing in GHCi:</p>\n\n<pre><code>> primes !! 1000000\n15485867\nit :: Integral a => a\n(2.12 secs, 3734834160 bytes)\n\n> primes !! 500000\n7368791\nit :: Integral a => a\n(0.98 secs, 1765893576 bytes)\n\n> logBase 2 (2.12 / 0.98)\n1.113210610447991\n</code></pre>\n\n<p>Yes, that's a <em>million</em> primes that it now reaches, in just over 2 seconds, at about <i>n<sup>1.1</sup></i> <a href=\"https://en.wikipedia.org/wiki/Analysis_of_algorithms#Empirical_orders_of_growth\" rel=\"nofollow noreferrer\">empirical orders of growth</a> (in n primes produced), which is quite good (the coefficient, not the time; arithmoi's code reaches the one millionth prime in 0.1 seconds on the same computer).</p>\n\n<p>This is not a sieve of Eratosthenes though. It builds the multiples not from primes, but from the 2-3-5-7-wheel enumeration. </p>\n\n<hr>\n\n<p>For <em>proper</em> testing always compile with the <code>-O2</code> switch and run the resulting standalone executable at the shell, with <code>+RTS -s</code> run-time options (to get the time and space statistics).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T00:39:41.427",
"Id": "427561",
"Score": "0",
"body": "You so often amaze me and you are always right.\n'n7sl' is remove 1st 4 prime multiples wheel.\nI had since changed the infinite function composites to (w/no take)\n`umap = unionAll $ map (\\n -> (n*) <$> n7sl) n7sl` ;\n`take 50000 $ rms umap n7sl`\nBut the non-infinite above still outperforms it and yours (IDK) and makes me mad\nBoth mine above eschew trial division."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T06:08:19.630",
"Id": "427575",
"Score": "0",
"body": "which non-infinite above? please give a test expression to run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T17:30:18.377",
"Id": "427858",
"Score": "0",
"body": "The infinite is now way faster. My misconception was remarkable, in a bad way. I thought I had to do `inits` for an infinite application. It put my factor at the end of each list so I had to use two lists and was penalized it time. `tails` is congruent with Haskell pattern matching and the factor is now at the head of each list by using `tails`. @Will Ness is the best. `inits` or `tails` diagonalizes the Cartesian product, upper or lower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T17:37:20.717",
"Id": "427863",
"Score": "0",
"body": "did you notice that using `n7sl` there are no non-prime numbers until 121? Your diagonal of my function is all primes. In Haskell `Data.Numbers.Primes` the `wheelSieve` take a parameter of the number of initial primes used to create the wheel and the larger wheel speeds it up. In my non-infinite list the larger wheel slowed it down. Maybe it won't in the infinite function."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:48:59.593",
"Id": "221161",
"ParentId": "216354",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T17:25:12.210",
"Id": "216354",
"Score": "2",
"Tags": [
"haskell",
"primes"
],
"Title": "Determining primality by removing select composits"
} | 216354 |
<p>I just wrote this template to detect if a given element is found inside a container:</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename Iterator> bool is_contained(Iterator begin, Iterator end, decltype(*begin) object)
{
for (; begin != end; ++begin)
{
if (*begin == object)
{
return true;
}
}
return false;
}
</code></pre>
<p>Which then would be called for examples as:</p>
<pre class="lang-cpp prettyprint-override"><code>bool test = is_contained<decltype(container.begin())>(container.begin(), container.end(), anything);
</code></pre>
<p>This works fine, but I believe it is not so readable. I am also new to using <code>decltype</code> which makes me wonder if this would crash, and somehow I wont be calling the template correctly. Any feedback is highly appreciated.</p>
| [] | [
{
"body": "<p>Note that for functions the compiler will detect the template types based on the parameters.<br>\nSo you can simply write:</p>\n\n<pre><code>bool test = is_contained(container.begin(), container.end(), anything);\n</code></pre>\n\n<p>I don't particularly like the use of <code>decltype</code> in your function. I would simply make it another template parameter.</p>\n\n<pre><code>template <typename Iterator, typename Value>\nbool is_contained(Iterator begin, Iterator end, Value const& object);\n</code></pre>\n\n<p>Because of the compiler deducing the names you can use any type. Also this is more flexable as it allows you to use any type that is comparable to the type inside the container (rather than only allowing values that are the same type (or trivial convertible)).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:15:41.567",
"Id": "216362",
"ParentId": "216361",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>Do you want to test whether an element is in a container, or an iterator-range?</p>\n\n<ul>\n<li>The first allows for optimisation (taking advantage of the container's peculiarities). See \"<em><a href=\"https://codereview.stackexchange.com/questions/59997/contains-algorithm-for-stdvector\">contains() algorithm for std::vector</a></em>\" for an example.</li>\n<li>The second is more general in the absence of any range-library, like the one expected for the C++20 standard, and available for earlier versions.</li>\n</ul></li>\n<li><p>Constraining the needle to the type <code>decltype(*begin)</code> is very problematic:</p>\n\n<ul>\n<li>It forces pass-by-value, which while it <em>should</em> be possible, at least with moveing, might be inefficient.</li>\n<li>You cannot take advantage of transparent comparators (a C++14 feature), forcing the creation of a useless temporary. On the flip-side, if transparent comparators are not used, only a single temporary is constructed.</li>\n<li>If the type is a proxy like with the dreaded <code>std::vector <bool></code>, hilarity ensues.</li>\n</ul></li>\n<li><p>Consider taking advantage of the standard library, specifically <code>std::find ()</code>.</p></li>\n<li><p>C++ will deduce the function's template-arguments perfectly fine, no need for error-prone verbosity.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:09:59.203",
"Id": "418749",
"Score": "0",
"body": "On point 2, it's even worse: you can't pass a value that's *convertible* to `decltype(*begin)`, because templates need exact matches."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:04:25.587",
"Id": "216365",
"ParentId": "216361",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:04:33.713",
"Id": "216361",
"Score": "4",
"Tags": [
"c++",
"beginner",
"template"
],
"Title": "Detecting if an element is found inside a container"
} | 216361 |
<p>I implemented a standard quicksort and I have a project where I need to improve it. I am trying to make quicksort faster by implementing median of 3 partitioning. I copied codes from trusted educational sites and the code is working, everything is being sorted. The issue is that, the median of 3 partitioning is taking 20 milliseconds to 40 milliseconds more than the standard quicksort. I am sorting 10240000 integers, positive and negative.<br>
Can anybody help me solve this out?</p>
<p>main class</p>
<pre><code>package sorttest;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class SortTest {
public static void main(String[] args) throws FileNotFoundException, IOException {
Clock c = new Clock();
int lo = 0;
int hi = 10239999;
sort s = new sort();
Option2 o = new Option2();
int[] NumArray = populate();
/*c.start();
s.quick(NumArray, lo, hi);
double time = c.stop();
System.out.println("Improved quicksort takes " +time);*/
int[] NumArrays = populate();
c.start();
s.quickiSort(NumArrays, lo, hi);
double times = c.stop();
System.out.println("Quicksort takes " + times);
c.start();
o.quickSort(NumArray, lo, hi);
double time = c.stop();
System.out.println("Improved quicksort takes " + time);
/*for (int i =0; i<NumArray.length; i++){
System.out.println(NumArray[i]);
}*/
}
public static int[] populate() throws FileNotFoundException, IOException {
String[] splitArr = split();
int[] arr = new int[10240000];
for (int i = 0; i < splitArr.length; i++) {
int num = Integer.parseInt(splitArr[i]);
arr[i] = num;
}
return arr;
}
public static String[] split() throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\username\\Documents\\year2\\Engeneering Software Development\\cw3\\ints10240000.dat")));
String line;
String[] aList = new String[10240000];
while ((line = reader.readLine()) != null) {
aList = line.split("\\s+");
//String aList = (line.split("\\s+"))); //using whitespace as delimeter to split
}
return aList;
}
}
</code></pre>
<p>Standard quicksort</p>
<pre><code>public void quickiSort(int arr[], int begin, int end) {
if (begin < end) {
int partitionIndex = partitionL(arr, begin, end);
quickiSort(arr, begin, partitionIndex - 1);
quickiSort(arr, partitionIndex + 1, end);
}
}
private int partitionL(int arr[], int begin, int end) {
int pivot = arr[end];
int i = (begin - 1);
for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) {
i++;
int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}
int swapTemp = arr[i + 1];
arr[i + 1] = arr[end];
arr[end] = swapTemp;
return i + 1;
}
</code></pre>
<p>Median of 3 quicksort</p>
<pre><code>package sorttest;
public class Option2 {
public void quickSort(int[] theArray, int lo, int hi) {
recQuickSort(theArray, lo, hi);
}
public void recQuickSort(int[] theArray, int left, int right) {
int size = right - left + 1;
if (size <= 3) {
manualSort(theArray, left, right);
} else {
long median = medianOf3(theArray, left, right);
int partition = partitionIt(theArray, left, right, median);
recQuickSort(theArray, left, partition - 1);
recQuickSort(theArray, partition + 1, right);
}
}
public long medianOf3(int[] theArray, int left, int right) {
int center = (left + right) / 2;
if (theArray[left] > theArray[center]) {
swap(left, center, theArray);
}
if (theArray[left] > theArray[right]) {
swap(left, right, theArray);
}
if (theArray[center] > theArray[right]) {
swap(center, right, theArray);
}
swap(center, right - 1, theArray);
return theArray[right - 1];
}
public void swap(int dex1, int dex2, int[] theArray) {
int temp = theArray[dex1];
theArray[dex1] = theArray[dex2];
theArray[dex2] = temp;
}
public int partitionIt(int[] theArray, int left, int right, long pivot) {
int leftPtr = left;
int rightPtr = right - 1;
while (true) {
while (theArray[++leftPtr] < pivot)
;
while (theArray[--rightPtr] > pivot)
;
if (leftPtr >= rightPtr) {
break;
} else {
swap(leftPtr, rightPtr, theArray);
}
}
swap(leftPtr, right - 1, theArray);
return leftPtr;
}
public void manualSort(int[] theArray, int left, int right) {
int size = right - left + 1;
if (size <= 1) {
return;
}
if (size == 2) {
if (theArray[left] > theArray[right]) {
swap(left, right, theArray);
}
return;
} else {
if (theArray[left] > theArray[right - 1]) {
swap(left, right - 1, theArray);
}
if (theArray[left] > theArray[right]) {
swap(left, right, theArray);
}
if (theArray[right - 1] > theArray[right]) {
swap(right - 1, right, theArray);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T22:01:27.007",
"Id": "418630",
"Score": "2",
"body": "Your benchmark is flawed. The `o.quickSort` is given an _already sorted_ array. For a fair comparison you need to repopulate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T04:03:20.190",
"Id": "418643",
"Score": "0",
"body": "I called int[] NumArray = populate(); before o.quickSort, and it took 35 milliseconds more than quicksort. Is there any other methods to make quicksort faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:44:00.413",
"Id": "418680",
"Score": "1",
"body": "Your benchmark is flawed. You need to compare same inputs for both algorithms (now you are sorting the array with quickiSort and passing the sorted array to quickSort). You also need to calculate a median from multiple passes over the same input on same algorithm to minimize effect of \"random\" OS/JVM events. Also, is the difference even significant? How long does each algorithm take in total?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:27:34.993",
"Id": "419093",
"Score": "1",
"body": "To extend on the suggestion of @TorbenPutkonen, before you worry about the time difference values, you need to first determine if those values are _significantly_ different. To do this, you need two steps: Data generation and analysis.\n\nGenerating Data:\nI would recommend independent tests and recording their run times until you have >30 records (a minimum size requirements for a standard distribution to be significant)\n\nOnce you have your two data sets, you can perform analysis:\n[link](https://m.wikihow.com/Assess-Statistical-Significance) has a step by step to performing a simple test."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T21:19:31.513",
"Id": "216374",
"Score": "1",
"Tags": [
"java",
"sorting",
"comparative-review",
"quick-sort"
],
"Title": "Median of three partitioning taking more time than standard quicksort in java"
} | 216374 |
<p>I'm writing several local servers which have almost the same code in <code>main.cpp</code>. Appreciate your comments, improvement suggestions and especially notes on potential memory leaks since the services are supposed to run 24/7 and process large requests. Thanks!</p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <unordered_map>
#include "UdsServer.hpp"
#include "RequestManager.hpp"
#include "MSutils.hpp" //MS::log()
void pullRequests();
const std::string pathToSocket = "/var/run/SomeServer.sock";
const std::string SERVICE_NAME = "SomeServer";
RequestManager service; //Does the actual processing of the request
std::unordered_map<int, std::string> requestQueue;
std::mutex requestQueue_mutex;
std::condition_variable processorsThreadSwitch;
bool gotNewRequests = false;
int main()
{
UdsServer app; //Server listening on a Unix Domain Socket
try
{
app.createServer(pathToSocket);
}
catch (const std::string & err)
{
MS::log(SERVICE_NAME, "Failed to start the service. Error: " + err, MS::MessageType::FatalException);
return -1;
}
unsigned n_concThreads = std::thread::hardware_concurrency();
if (!n_concThreads) //if the query failed...
{
std::ifstream cpuinfo("/proc/cpuinfo");
n_concThreads = std::count(std::istream_iterator<std::string>(cpuinfo),
std::istream_iterator<std::string>(),
std::string("processor"));
if (!n_concThreads)
n_concThreads = 6; // ~number of CPU cores. TODO: make the number of worker processes/threads configurable using a config file
}
for (int i = 0; i < n_concThreads; ++i)
{
std::thread t (pullRequests);
t.detach();
}
while ((int clientConnection = app.newConnectionEstablished()) > -1) //Uses accept() internally
{
std::string command = app.getMsg (clientConnection); //Uses read() internally
if (command.empty())
app.closeConnection(clientConnection);
else if (command == "SHUTDOWN")
{
app.closeConnection(clientConnection);
return 0;
}
else
{
{ //Anonymous scope just to get rid of the lock before notifying a thread
std::lock_guard<std::mutex> writeLock(requestQueue_mutex);
requestQueue[clientConnection] = std::move(command);
gotNewRequests = true;
}
processorsThreadSwitch.notify_one(); //nothing happens here if all threads are busy
}
}
}
void pullRequests()
{
UnixDomainSocket uds;
std::unique_lock<std::mutex> writeLock(requestQueue_mutex);
while (true) //Let the thread run "forever"
{
while (!gotNewRequests)
processorsThreadSwitch.wait(writeLock);
std::unordered_map<int, std::string> queueCopy (std::move(requestQueue));
requestQueue.clear();
gotNewRequests = false;
writeLock.unlock(); //Don't let the other threads wait when this threads doesn't need to access the shared data any more
if (queueCopy.empty())
continue;
else if (queueCopy.size() == 1)
{
std::string response = service.pullRequests(queueCopy.cbegin()->second);
if (response.length())
{
auto sendResult = uds.sendMsg(queueCopy.cbegin()->first, response);
if (!sendResult.isValid())
MS::log(SERVICE_NAME, "Could not send the response for request: " + queueCopy.begin()->second, MS::MessageType::Error);
}
if (!uds.closeConnection(queueCopy.begin()->first))
MS::log(SERVICE_NAME, "Could not close the connection.", MS::MessageType::Error);
}
else //Multiplex
{
std::unordered_map<std::string, std::vector<int>> multiplexedRequests;
for (auto & request : queueCopy)
multiplexedRequests[std::move(request.second)].push_back(request.first);
for (const auto & request : multiplexedRequests)
{
std::string response = service.pullRequests(request.first);
if (response.length())
for (auto socket : request.second)
{
auto sendResult = uds.sendMsg(socket, response);
if (!sendResult.isValid())
MS::log(SERVICE_NAME, "Could not send the response for request: " + request.first, MS::MessageType::Error);
if (!uds.closeConnection(socket))
MS::log(SERVICE_NAME, "Could not close the connection.", MS::MessageType::Error);
}
}
}
writeLock.lock();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T00:18:30.873",
"Id": "418635",
"Score": "1",
"body": "Have you run it with valgrind to check for memory leaks or race conditions (just wondering)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T07:08:21.647",
"Id": "418649",
"Score": "0",
"body": "If you running a professional site don't write your own. There are many good multi threaded servers out there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T09:02:00.470",
"Id": "418658",
"Score": "0",
"body": "It is not a web server. It's a microservice communicating with other local microservices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T19:31:52.890",
"Id": "418726",
"Score": "0",
"body": "@ScepticalJule: That does not affect my comment (or my review) in any way. Apache may be a bit heavy weight then but there are still plenty of already existing server based platforms you can use. `Node.js` jumps to mind as done `engnx`. Also why would you not use a standard (HTTP) over HTTPS well documented well understood protocol that already has tools for debugging and maintenance."
}
] | [
{
"body": "<h2>Overview</h2>\n<p>You over-allocate the number of child threads. Remember you should save one thread (the main thread for listening for new messages).</p>\n<pre><code>// Remember master thread takes a CPU while listening for connections.\nunsigned n_concThreads = std::thread::hardware_concurrency() - 1;\n</code></pre>\n<p>Using multiple threads to handle incoming connection is not the way to go. The problem here is that the parallelization is limited by the number of threads (which is usually in the single digits low double digits if you are lucky).</p>\n<p>A single thread can handle thousands of connections simultaneously because most of the time is spent waiting for data on the port. Thus your thread will be idle for most of the time it is handling a request waiting for input. If handled correctly, this idle time could be used to handle other requests.</p>\n<p>A good example is the <code>Node.js</code> server. It is single-threaded and will easily handle thousands of incoming connections.</p>\n<p>If you want to do this properly you need to use a library like <code>LibEvent</code> (or you can do it manually with <code>select()</code>, <code>pselect()</code> or <code>ppoll()</code>). This allows you to handle multiple sockets with the same thread.</p>\n<p>But to be blunt. Doing this is not trivial and not for the beginner. I would opt for a server that already does this part of the work for you. <code>Apache</code> for heavyweight, or <code>nginx</code> for lightweight, or if you want to use another language <code>Node.js</code>. All these servers allow you to write your own request handling code but do the complex stuff for you.</p>\n<h2>Code Review</h2>\n<p>Bad form to have global variables.</p>\n<pre><code>std::unordered_map<int, std::string> requestQueue;\nstd::mutex requestQueue_mutex;\nstd::condition_variable processorsThreadSwitch;\nbool gotNewRequests = false;\n</code></pre>\n<p>Would be much nicer to wrap this in a class and pass a reference to each string. That would make the application much more expandable in the long run.</p>\n<hr />\n<p>OK. This is speculation. But I find it strange that something would throw a <code>std::string</code>! It would be more normal to throw something derived from <code>std::runtime_error</code>.</p>\n<pre><code> try\n {\n app.createServer(pathToSocket);\n }\n catch (const std::string & err)\n {\n MS::log(SERVICE_NAME, "Failed to start the service. Error: " + err, MS::MessageType::FatalException);\n\n return -1;\n }\n</code></pre>\n<p>Also I would not return -1. I would rethrow the exception. This gives the calling function more information about the issue.</p>\n<hr />\n<p>OK. A bit of a hack. But clever way of finding the number of processors.</p>\n<pre><code> unsigned n_concThreads = std::thread::hardware_concurrency();\n\n if (!n_concThreads) //if the query failed...\n {\n std::ifstream cpuinfo("/proc/cpuinfo");\n\n n_concThreads = std::count(std::istream_iterator<std::string>(cpuinfo),\n std::istream_iterator<std::string>(),\n std::string("processor"));\n\n if (!n_concThreads)\n n_concThreads = 6; // ~number of CPU cores. TODO: make the number of worker processes/threads configurable using a config file\n }\n</code></pre>\n<p>But it is OS-specific. So I would wrap it in a function that is OS specific. That way on Linux you can do your clever check. On Windows it defaults to 6 (and the next person can simply replace the Windows version with a Windows specific hack without having to understand your Linux hack).</p>\n<hr />\n<p>Not a fan of detaching the thread.</p>\n<pre><code> for (int i = 0; i < n_concThreads; ++i)\n {\n std::thread t (pullRequests);\n t.detach();\n }\n</code></pre>\n<p>You lose all control of the thread. You also lose any warnings when you have a bug in your code and you accidentally shut down while one of the threads is still executing. Using <code>detach()</code> should be a last resource when all neat ways of doing something have been tried and failed.</p>\n<hr />\n<p>The locking in <code>pullRequests()</code> seems highly roundabout. Move all the locking into a separate function. That way your scope lock behaves like it should.</p>\n<p>I would have written it like this:</p>\n<pre><code>std::unordered_map<int, std::string> getNextTask()\n{\n std::unique_lock<std::mutex> writeLock(requestQueue_mutex);\n\n // note this can be written more succinctly.\n // But I am to lazy to look up condition variables at the moment.\n // The following three lines should be a one liner\n // with wait taking a lambda\n while (!gotNewRequests) {\n processorsThreadSwitch.wait(writeLock);\n }\n\n std::unordered_map<int, std::string> result = std::move(requestQueue);\n return result;\n}\n\nvoid pullRequests()\n{\n while(/*test*/)\n {\n // STUFF\n std::unordered_map<int, std::string> queueCopy = getNextTask();\n // STUFF\n }\n}\n</code></pre>\n<hr />\n<p>Seems like some repeated code:</p>\n<pre><code> if (!sendResult.isValid())\n MS::log(SERVICE_NAME, "Could not send the response for request: " + queueCopy.begin()->second, MS::MessageType::Error);\n }\n\n if (!uds.closeConnection(queueCopy.begin()->first))\n MS::log(SERVICE_NAME, "Could not close the connection.", MS::MessageType::Error);\n</code></pre>\n<p>If you find repeated code then put it in a function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T07:44:39.000",
"Id": "216397",
"ParentId": "216379",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T22:25:36.297",
"Id": "216379",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"linux",
"server"
],
"Title": "Multithreaded local server"
} | 216379 |
<p>I created my brainfuck interpreter and I would like to know what can be done better and is the code clear and readable. I will be very thankful for opinions and suggestions.
Here is the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define ALLOCATION_ERROR 1
#define FILE_ERROR 2
#define OTHER_ERROR 3
#define TAPE_SIZE 30000
FILE* get_file_handle(const char* filename){
FILE* input_file=fopen(filename,"rb");
if(input_file==NULL){
fprintf(stderr,"Error: failed to open file %s\n",filename);
exit(FILE_ERROR);
}
return input_file;
}
unsigned char* read_code(FILE* input_file){
fseek(input_file,0,SEEK_END);
size_t code_size=(size_t)ftell(input_file);
fseek(input_file,0,SEEK_SET);
unsigned char* code=malloc(code_size+1);
if(code==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",code_size+1);
exit(ALLOCATION_ERROR);
}
if(fread(code,1,code_size,input_file)!=code_size){
perror("Error: failed to read from file\n");
exit(FILE_ERROR);
}
code[code_size]=0;
return code;
}
unsigned char* create_tape(){
unsigned char* tape=calloc(TAPE_SIZE,1);
if(tape==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",(size_t)TAPE_SIZE*1);
exit(ALLOCATION_ERROR);
}
return tape;
}
void find_matching_bracket(unsigned char** tape_ptr,unsigned char** code_ptr){
int is_right_bracket=']'==**code_ptr;
if(is_right_bracket?**tape_ptr:!**tape_ptr){
int loop=1;
while(loop){
is_right_bracket?--*code_ptr:++*code_ptr;
if(**code_ptr=='[')
is_right_bracket?--loop:++loop;
if(**code_ptr==']')
is_right_bracket?++loop:--loop;
}
}
}
void run(const char* filename){
FILE* input_file=get_file_handle(filename);
unsigned char *tape=create_tape(),*tape_ptr=tape;
unsigned char *code=read_code(input_file),*code_ptr=code;
fclose(input_file);
for(;*code_ptr;++code_ptr){
switch(*code_ptr){
case '>':
++tape_ptr;
break;
case '<':
--tape_ptr;
break;
case '+':
++*tape_ptr;
break;
case '-':
--*tape_ptr;
break;
case ',':
*tape_ptr=(unsigned char)getchar();
break;
case '.':
putchar(*tape_ptr);
fflush(stdout);
break;
case '[':
case ']':
find_matching_bracket(&tape_ptr,&code_ptr);
break;
}
}
free(tape);
free(code);
}
int main(int argc,char** argv){
if(argc!=2){
puts("Usage: bfic <source>");
exit(OTHER_ERROR);
}
run(argv[1]);
}
</code></pre>
<p>Code after review from @luserdroog and @AustinHastings:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define ALLOCATION_ERROR 1
#define FILE_ERROR 2
#define OTHER_ERROR 3
#define TAPE_SIZE ((size_t)300000)
static inline FILE*
get_file_handle(const char* filename){
FILE* input_file=fopen(filename,"rb");
if(input_file==NULL){
fprintf(stderr,"Error: failed to open file %s\n",filename);
exit(FILE_ERROR);
}
return input_file;
}
static inline unsigned char*
read_code(FILE* input_file){
fseek(input_file,0,SEEK_END);
size_t code_size=(size_t)ftell(input_file);
fseek(input_file,0,SEEK_SET);
unsigned char* code=malloc(code_size+1);
if(code==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",code_size+1);
exit(ALLOCATION_ERROR);
}
if(fread(code,1,code_size,input_file)!=code_size){
perror("Error: failed to read from file\n");
exit(FILE_ERROR);
}
code[code_size]=0;
return code;
}
static inline unsigned char*
create_tape(){
unsigned char* tape=calloc(TAPE_SIZE,1);
if(tape==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",TAPE_SIZE*1);
exit(ALLOCATION_ERROR);
}
return tape;
}
static inline void
find_matching_bracket(unsigned char** tape_ptr,unsigned char** code_ptr){
int is_right_bracket=']'==**code_ptr;
if(is_right_bracket?**tape_ptr:!**tape_ptr){
int depth=1;
while(depth>0){
is_right_bracket?--*code_ptr:++*code_ptr;
if(**code_ptr=='[')
is_right_bracket?--depth:++depth;
if(**code_ptr==']')
is_right_bracket?++depth:--depth;
}
}
}
static inline void
run(const char* filename){
FILE* input_file=get_file_handle(filename);
unsigned char* tape=create_tape();
unsigned char* tape_ptr=tape;
unsigned char* code=read_code(input_file);
unsigned char* code_ptr=code;
fclose(input_file);
for(;*code_ptr;++code_ptr){
switch(*code_ptr){
case '>':
++tape_ptr;
break;
case '<':
--tape_ptr;
break;
case '+':
++*tape_ptr;
break;
case '-':
--*tape_ptr;
break;
case ',':
*tape_ptr=(unsigned char)getchar();
break;
case '.':
putchar(*tape_ptr);
fflush(stdout);
break;
case '[':
case ']':
find_matching_bracket(&tape_ptr,&code_ptr);
break;
}
}
free(tape);
free(code);
}
static inline void
parse_args(int argc){
if(argc!=2){
puts("Usage: bfic <source>");
exit(OTHER_ERROR);
}
}
int
main(int argc,char** argv){
parse_args(argc);
run(argv[1]);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T00:21:05.677",
"Id": "418636",
"Score": "0",
"body": "You have chosen to write this using just one function. Is there a reason or requirement for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T06:39:21.470",
"Id": "418648",
"Score": "0",
"body": "I think that I don't need 8 or 10 separate functions for interpreting language with 8 instructions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T05:30:40.450",
"Id": "419298",
"Score": "0",
"body": "Functions are good for you. It can often make the code smaller and simpler. Eg. [bf interpreter written using functions](https://codereview.stackexchange.com/questions/25934/5912/brainfuck-interpreter-in-c)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T19:26:17.927",
"Id": "419380",
"Score": "0",
"body": "@luserdroog is the code more readable now when I used functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T22:31:26.187",
"Id": "419389",
"Score": "0",
"body": "Yes, I think it is. +1 from me. I'll try to dig in and have more comments for you. I think it really helps to be able to see the whole function on one screen. The code for the function can the be read more easily because there's less state to carry around in the mind. The `run` function is still quite big, but there's only one, and it is the important one after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:30:12.370",
"Id": "419407",
"Score": "0",
"body": "Thanks @luserdroog. I created separate functions for creating tape, so the **run** function is smaller and code is more readable now. When I will have time I will sort out the evaluation of brackets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:03:52.297",
"Id": "419476",
"Score": "0",
"body": "@luserdroog I edited the code and now I can see each function clearly and fully on the screen, but program is 2x slower. It runs in 12 instead of 6 seconds. Should it be like that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T21:44:24.150",
"Id": "419507",
"Score": "0",
"body": "@DeBos99 Don't worry. We can fix that. I'm writing an answer."
}
] | [
{
"body": "<p>First let me say \"Good work!\" on revising the code to use functions. This is important in C (and most other languages, too) because it makes smaller units of code which are easier to read and reason about. </p>\n\n<p>As you have discovered, making more function calls has the potential to make the program slower if the compiler is not doing significant optimizations. Modern optimizing compilers can automatically inline functions when the optimizations are turned on, but you can also suggest to the compiler that it can inline the functions. </p>\n\n<p>If you change the function prototype from, eg. </p>\n\n<pre><code>void find_matching_bracket(unsigned char** tape_ptr,unsigned char** code_ptr){\n</code></pre>\n\n<p>to</p>\n\n<pre><code>static inline\nvoid find_matching_bracket(unsigned char** tape_ptr,unsigned char** code_ptr){\n</code></pre>\n\n<p>that should help with the speed. Especially this function which is in the \"inner loop\" should have a significant benefit from being inlined.</p>\n\n<p><code>static</code> isn't strictly necessary here, but it often goes well with <code>inline</code>. </p>\n\n<p>Another option is to turn up the compiler optimization level. With gcc or clang, you can add <code>-O2</code> or <code>-O3</code> and it should do the inlining for you.</p>\n\n<p>Btw, your <code>find_matching_bracket</code> function looks better than the one I wrote for my interpreter. It's shorter and simpler.</p>\n\n<p>(out of time. more to add later)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:33:25.810",
"Id": "419516",
"Score": "0",
"body": "Thanks @luserdroog. I added `-03` flag and `static inline` before each functions except `main` and program is 2.5x faster (~5s). Can you tell me why I got `undefined reference error` without using `static` with `inline`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T22:02:20.417",
"Id": "216889",
"ParentId": "216381",
"Score": "2"
}
},
{
"body": "<h2>CodeReview problems</h2>\n\n<p>You've made two \"codereview\" errors (as opposed to \"coding\" errors): </p>\n\n<h3>Use tags</h3>\n\n<p>You didn't specify enough about your environment. What version of C are you writing for? (I'm guessing \"not K&R\" since you're using ANSI-style function declarations. But is that C89, C99, C11, or C18?) Is your code limited to *nix or Windows, or must it run on both? Do you care about compiler versions? Are you allowed to use compiler extensions?</p>\n\n<h3>No moving targets!</h3>\n\n<p>You edited your code after posting it. Someone is going to yell at you for that - it's considered poor form. Since nobody had replied when you edited, it's not the end of the world, though.</p>\n\n<h2>Coding style</h2>\n\n<p>I have some issues with your coding style. You didn't specify what style you were trying to write, and I suspect you started with <a href=\"https://www.ioccc.org/\" rel=\"nofollow noreferrer\">\"IOCCC\"</a> as your base, although I don't know why. So:</p>\n\n<h3>Find a style</h3>\n\n<p>There are three kinds of \"C Coding Style\" guides out there:</p>\n\n<p>The first kind are actually C++ guides. Ignore these. </p>\n\n<p>The second kind are \"we want to have a guide, but we don't want to risk a flamewar, so we're afraid to make any firm guidelines\". Ignore these, too. </p>\n\n<p>The third kind will provide some good advice, and some amount of nutrient-laden fertilizer. That's the kind you want! Find one of those you like and <strong>stick with it.</strong> </p>\n\n<p>I don't care if your tabs are 2 spaces, 11 spaces or what, as long as they stay the same. I don't care if your braces are up or down, or even (God forbid) down and indented. The good advice and consistency will overwhelm your failure to use a multiple of a perfect prime number as your tab size.</p>\n\n<p>Once you find your ideal coding standard, tattoo it on your body somewhere. I have found that whatever style people adopt first they will be able to rationalize retaining for the rest of their lives. And you can be really dogmatic about it - it's fine! I still write (C) code using the coding standard from my first \"corporate\" job by default. (Of course, it was a pretty well-thought-out standard, even if pre-ANSI...)</p>\n\n<p>Having a formal document to refer to makes it really easy to be dogmatic. Go ahead, it's the internet!</p>\n\n<p><img src=\"https://i.stack.imgur.com/EscFY.jpg\" width=\"175\" height=\"225\" alt=\"According to this, you're a heretic!\" /></p>\n\n<h3>Whitespace is free. Use lots of it.</h3>\n\n<p>I'm not aware of any coding style guide that argues for the elimination of whitespace. If you are following one, please post a link to it so that we can burn it out for the heresy that it is! This code shows a lack of horizontal and vertical spacing:</p>\n\n<pre><code> code[code_size]=0;\n return code;\n }\n unsigned char* create_tape(){\n</code></pre>\n\n<p>It should be:</p>\n\n<pre><code> code[code_size] = 0;\n return code;\n }\n\n unsigned char *\n create_tape()\n {\n</code></pre>\n\n<p>(Although you might want to \"cuddle\" that opening brace... if you're a heretic.)</p>\n\n<h3>Pick better names</h3>\n\n<p>This is a bit of an art form, but what does <code>get_file_handle</code> return? Surprisingly, it returns a <code>FILE</code> pointer. This is surprising because <code>handle</code> is one of those <em>magic words</em> in computing that \"everybody knows\" what it means. And it doesn't mean that. According to <a href=\"http://www.catb.org/jargon/html/H/handle.html\" rel=\"nofollow noreferrer\">Jargon</a> a <strong>handle</strong> is:</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>A magic cookie, often in the form of a numeric index into some array somewhere, through which you can manipulate an object like a file or window. The form file handle is especially common. </li>\n </ol>\n</blockquote>\n\n<p>Also, what does \"get\" mean? (Seriously.) There are quite a few meanings for <code>get</code> in computing. Java(Beans) screwed it up for most people by slathering it in front of their accessors. But it used to mean \"fetch or create.\" Now days, you're better off avoiding it, especially considering what your function does: return a valid file handle or die.</p>\n\n<p>I'd suggest either explicitly stating that in your function name (<code>open_or_die</code>), or simply echoing the \"successful\" behavior by calling it something like <code>fopen_rb</code> or <code>open_file_rb</code>.</p>\n\n<pre><code>FILE *\nopen_or_die(filename)\n const char *filename;\n{\n FILE *input = fopen(filename, \"rb\");\n\n if (input)\n return input;\n\n fprintf(stderr, \"Error: failed to open file %s\\n\", filename);\n exit(FILE_ERROR);\n}\n</code></pre>\n\n<p>Finally, what does <code>loop</code> mean? Maybe <code>nested</code> or <code>levels</code> or <code>depth</code> would be better. Or even <code>num_open</code> or <code>open_brackets</code>.</p>\n\n<h3>Create the right functions</h3>\n\n<p>There are three reasons to create a function from some non-function code.</p>\n\n<ol>\n<li><p>Create a function for things you do more than one time. In my opinion, N=2 is the right time to create a function. Sometimes you'll find yourself doing N>2, but IMO 2 is the right number. (For example, some trivial pair of calls to configure buttons in a GUI might seem \"simple enough\" to not make a function. Make the function!)</p>\n\n<p>In your code, you have three different places where you <code>exit</code> if a pointer is NULL. That would fall under the rule of N > 1, and so you might write something like:</p>\n\n<pre><code>void die(const char * fmt, ...);\n\n// ...\n\ninput = fopen(filename, \"rb\") \n || die(\"Could not open input file '%s' for reading\", filename);\n</code></pre>\n\n<p>(Note: I don't suggest doing that, because of #2 here.)</p></li>\n<li><p>Create a function to \"abstract away\" code to a separate layer. In your <code>main</code>, you have:</p>\n\n<pre><code>int main(int argc,char** argv){\n if(argc!=2){\n puts(\"Usage: bfic <source>\");\n exit(OTHER_ERROR);\n }\n run(argv[1]);\n}\n</code></pre>\n\n<p>The first paragraph (the <code>if</code> statement) is at a much lower level of detail than the <code>run</code> call. I would be inclined to write something like:</p>\n\n<pre><code>parse_args(argc, argv);\nrun_code(argv[1]);\n</code></pre>\n\n<p>despite the \"trivial\" nature of the <code>parse_args</code>, because that puts them both at the same level of abstraction. Alternatively, you might pull out some of the code from <code>run</code> to put more meat into <code>main</code> like:</p>\n\n<pre><code>const char *code_file = parse_args(argc, argv);\nconst code_t *code = load_code(code_file);\nint result = run_code(code);\nreturn result;\n</code></pre></li>\n</ol>\n\n<p>You do this with your <code>read_code</code> and <code>create_tape</code> functions, and this is generally the right way to go if you have to choose between #1 (above) and #2 (this option).</p>\n\n<ol start=\"3\">\n<li><p>Create a function to isolate a potentially valuable operation for reuse.</p>\n\n<p>This is the gold standard for functions, and so you won't see it very often. But when you <em>do</em> see it, grab on! In your case, you've got a couple of them right here:</p>\n\n<pre><code>fseek(input_file,0,SEEK_END);\nsize_t code_size=(size_t)ftell(input_file);\nfseek(input_file,0,SEEK_SET);\n</code></pre>\n\n<p>This code computes the size of a file given a file pointer. That's something you might wish to reuse later, and it has nothing to do with your main code - there are no special types or anything getting in the way. This would be something you could put in your toolbox. (You'll probably find half a dozen different ways to do this task. Collect 'em all!)</p>\n\n<p>Also, consider that your <code>read_code</code> function represents an operation so common that Perl <a href=\"https://perldoc.perl.org/perlglossary.html#slurp\" rel=\"nofollow noreferrer\">gives it a name:</a></p>\n\n<blockquote>\n <p><strong>slurp</strong></p>\n \n <p>To read an entire file into a string in one operation.</p>\n</blockquote>\n\n<p>That's another function that would be worth \"isolating\" so you could keep it in your toolbox. (By \"isolating\" I mean separating it from your code, so that the name is more general, the types used are all standard types, etc.)</p></li>\n</ol>\n\n<h2>Code organization</h2>\n\n<p>The one weak spot I think I see with your code organization is writing your code with a common level of abstraction inside functions. I've already mentioned <code>main</code>. This also shows up in <code>run</code> in two ways. First, because the interpreter code is finer grained than the <code>make_tape</code> and <code>read_code</code> functions, and second because <code>read_code</code> should just go ahead and incorporate the file open and close operations. Change this:</p>\n\n<pre><code>FILE* input_file=get_file_handle(filename);\nunsigned char *tape=create_tape(),*tape_ptr=tape;\nunsigned char *code=read_code(input_file),*code_ptr=code;\nfclose(input_file);\n</code></pre>\n\n<p>... to this:</p>\n\n<pre><code>unsigned char *tape = create_tape();\nunsigned char *tape_ptr = tape;\nunsigned char *code = read_code(filename);\nunsigned char *code_ptr = code;\n</code></pre>\n\n<p>... by moving the open/close operations down into <code>read_code</code>. And adding newlines.</p>\n\n<h2>Final notes</h2>\n\n<p>You spend some characters casting the value of TAPE_SIZE. Why not either include the typecast in the macro (<code>#define TAPE_SIZE ((size_t)300000)</code>) or declare a static variable for the value which you could configure from the command line (<code>-t SIZE</code>):</p>\n\n<pre><code>size_t Tape_size = TAPE_SIZE;\n</code></pre>\n\n<p>You also mentioned in the comments on your request a performance hit after converting to functions. If you look at your original version, you handled '[' and ']' separately. Why not do that in your functions? And while you're at it, just return the result.</p>\n\n<pre><code>const unsigned char *\nfind_matching_bracket(tape_ptr, code_ptr)\n const unsigned char *tape_ptr;\n const unsigned char *code_ptr;\n{\n if (*code_ptr == ']') {\n // search this-a-way\n }\n else {\n // search that-a-way\n }\n\n return code_ptr;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:42:53.427",
"Id": "419518",
"Score": "0",
"body": "Thanks for the review @AustinHastings. I'm writing in C89 for linux (if code works on windows it is good, but it is not necessary). I edited code in my post because I was making improvements around 4 times and I did not want to have 5 big blocks of code in post. Someone could get confused. I use tab for indentation. I'm using tab size 4, but it depends on your editor settings. Can you tell me why type of function should be above it's name? In my case `handle` means like `file descriptor` I think. If I'm wrong correct me. `get` means that you are getting this `handle` from function (return)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:51:59.260",
"Id": "419520",
"Score": "0",
"body": "`loop` means the depth in nested loops. I think that `nested` would we wrong too. It suggest bool (1 or 0), but it is only my opinion. I will change to `depth`. I made little improvements in my code and I added edit to the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T17:03:32.030",
"Id": "419591",
"Score": "0",
"body": "The reason for putting the type above the name is so that `grep \"^name\" *.c` trivially finds the function definition. Note that `file descriptor` is an `int` not a `FILE*`. (That's a file pointer.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T18:54:34.280",
"Id": "419600",
"Score": "0",
"body": "I made next improvements to the code. I'm wondering what can be short and clear name for the function `get_file_handle`. Something like `get_file_pointer`? I don't know what is wrong with `get` in your opinion. I think that function named `open_file` suggests `void` that opens file without returning anything, when my function returns the pointer to the file to you are `get`ting this pointer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T02:37:13.747",
"Id": "216901",
"ParentId": "216381",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T22:36:01.963",
"Id": "216381",
"Score": "8",
"Tags": [
"c",
"interpreter",
"brainfuck"
],
"Title": "Brainfuck interpreter in C 3"
} | 216381 |
<p>I made code for signing in users and storing data about them. Everything is fully encrypted and secure also, it is meant to be imported into other code. I'm looking for ways to improve it and to fix any bugs people might find.</p>
<pre><code>import pickle
import base64
class user():
def __init__(self, username, password, user_data):
self.username = username
self.password = password
self.user_data = user_data
def get_user():
try:
user_saves = open("users", 'rb')
users = dict(pickle.load(user_saves))
user_saves.close
name, password, users = sign_in(users)
except:
name, password, users = new_user(True)
name = base64.b64decode(name.decode('utf-8'))
password = base64.b64decode(password.decode('utf-8'))
return name, password, users
def new_user(is_first = False, users=None):
print('Creating account... ')
if users != None:
loop = True
while loop:
name = input('What is your username: ')
name = base64.b64encode(name.encode('utf-8'))
if name in users:
print('Already taken.')
else:
loop = False
password = input('What is your password: ')
password = base64.b64encode(password.encode('utf-8'))
else:
name = input('What is your username: ')
name = base64.b64encode(name.encode('utf-8'))
password = input('What is your password: ')
password = base64.b64encode(password.encode('utf-8'))
if is_first == True:
user = {name:password}
user_saves = open("users", 'wb')
pickle.dump(user, user_saves)
add_user_data('', password, True)
return name, password, user
else:
add_user_data('', password)
users.update({name:password})
user_saves = open("users", 'wb')
pickle.dump(users, user_saves)
return name, password, users
user_saves.close
def sign_in(users):
nsi = True #not signed in
while nsi == True:
username = input('What is your username: ')
username = base64.b64encode(username.encode('utf-8'))
if username in users:
password = input('What is your password: ')
password = base64.b64encode(password.encode('utf-8'))
if password == users.get(username):
print('working')
nsi = False
return username, password
else:
print('Wrong password.')
else:
yn = y_or_n('y or n, are you a new user: ')
if yn == True:
nsi = False
name, password = new_user(users=users)
return name, password
def y_or_n(promt):
ni = True #no input
while ni:
yn = input(promt).lower()
if yn == 'y':
return True
elif yn == 'n':
return False
else:
print('y or n')
def add_user_data(data, password, is_first=False):
password = base64.b64encode(password.encode('utf-8'))
data = base64.b64encode(data.encode('utf-8'))
if is_first == True:
user_data = {password:data}
users_data = open("users_data", 'wb')
pickle.dump(user_data, users_data)
else:
user_data.update({password:data})
users_data = open("users_data", 'wb')
pickle.dump(user_data, users_data)
users_data.close
def get_user_data(password):
password = base64.b64encode(password.encode('utf-8'))
user_data = pickle.load('user_data')
user_data = base64.b64decode(user_data.decode('utf-8'))
return user_data
def delete_user(name, data, ):
data.pop('name', None)
name, password, users = get_user()
data = get_user_data(password)
print(data)
user_stats = user(name, password, data)
</code></pre>
| [] | [
{
"body": "<h2>Security</h2>\n\n<blockquote>\n <p>Everything is fully encrypted and secure</p>\n</blockquote>\n\n<p>Oh, really? I hope that you aren't confusing encoding with encryption. I don't see any encryption taking place.</p>\n\n<p>This is a huge topic, so you have some reading to do - but the bar for 'secure password store' is significantly above where this program currently resides.</p>\n\n<h2>Class syntax</h2>\n\n<p>This:</p>\n\n<pre><code>class user():\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>class User:\n</code></pre>\n\n<p>Also, you're currently using it as a struct with no methods. That should change - you should move some of your code to be methods on that class.</p>\n\n<h2>Break</h2>\n\n<p>This:</p>\n\n<pre><code>loop = True\nwhile loop:\n</code></pre>\n\n<p>should be reworked. You can use a <code>while True</code>, and replace the <code>loop = False</code> with a <code>break</code> at the end of that <code>if</code> block.</p>\n\n<h2>File handles</h2>\n\n<p>Rather than explicitly closing your files, you should usually use them in a <code>with</code> block. Also, this:</p>\n\n<pre><code>user_saves.close\n</code></pre>\n\n<p>doesn't do what you think it does; in fact it does nothing. For the function call to occur, you need to add <code>()</code>.</p>\n\n<h2>Redundant <code>else</code></h2>\n\n<p>This:</p>\n\n<pre><code> return name, password, user\nelse:\n</code></pre>\n\n<p>doesn't need an <code>else</code>, because you've returned in the previous block.</p>\n\n<h2>Write a <code>main</code> method</h2>\n\n<p>...to pull this code out of global scope:</p>\n\n<pre><code>name, password, users = get_user()\ndata = get_user_data(password)\nprint(data)\nuser_stats = user(name, password, data)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T03:21:12.337",
"Id": "216384",
"ParentId": "216383",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216384",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T02:06:18.823",
"Id": "216383",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"authentication"
],
"Title": "User creation and sign-in script"
} | 216383 |
<p>An extension to array functions I am building for my snake game. This one allows you to remove / insert particular elements.</p>
<p><a href="https://github.com/Evanml2030/Excel-ArrayFunctions" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-ArrayFunctions</a></p>
<p><strong>API CALLS</strong></p>
<pre><code>Private Declare PtrSafe Function VarPtrArray Lib "VBE7" Alias "VarPtr" _
(ByRef Var() As Any) As LongPtr
Private Declare PtrSafe Sub CopyMemoryI Lib "kernel32.dll" Alias "RtlMoveMemory" _
(ByVal dst As LongPtr, ByVal src As LongPtr, ByVal Length As Long)
Private Declare PtrSafe Sub CopyMemoryII Lib "kernel32.dll" Alias "RtlMoveMemory" _
(ByRef dst As SAFEARRAY, ByVal src As LongPtr, ByVal Length As Long)
</code></pre>
<p><strong>DATA STRUCTS</strong></p>
<pre><code>Private Type SAFEARRAY_BOUND
cElements As Long
lLbound As Long
End Type
Private Type SAFEARRAY
cDims As Integer
fFeatures As Integer
cbElements As Long
cLocks As Long
pvData As LongPtr
rgsabound(0) As SAFEARRAY_BOUND
End Type
Public Type TestStruct
Column As Long
Row As Long
End Type
Private Const TESTSTRUCT_BYTELENGTH = 8
</code></pre>
<p><strong>FUNCTIONS</strong></p>
<pre><code>Public Function ArrayInsertElement(ByRef ArrayOriginal() As TestStruct, ByRef ElementToAdd As TestStruct, ByRef Position As Long) As TestStruct()
Dim NewLength As Long
Dim CopiedBytesFirstSection As Long
Dim CopiedBytesSecondSection As Long
NewLength = UBound(ArrayOriginal) + 1
ReDim ArrayInsertElement(NewLength)
CopiedBytesFirstSection = Position * TESTSTRUCT_BYTELENGTH
CopiedBytesSecondSection = (NewLength - Position) * TESTSTRUCT_BYTELENGTH
CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytesFirstSection
CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, Position, TESTSTRUCT_BYTELENGTH), VarPtr(ElementToAdd), TESTSTRUCT_BYTELENGTH
CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, Position + 1, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, Position, TESTSTRUCT_BYTELENGTH), CopiedBytesSecondSection
End Function
Public Function ArrayRemoveElement(ByRef ArrayOriginal() As TestStruct, ByRef Position As Long) As TestStruct()
Dim NewLength As Long
Dim CopiedBytesFirstSection As Long
Dim CopiedBytesSecondSection As Long
NewLength = UBound(ArrayOriginal) - 1
ReDim ArrayRemoveElement(NewLength)
CopiedBytesFirstSection = Position * TESTSTRUCT_BYTELENGTH
CopiedBytesSecondSection = (UBound(ArrayOriginal) - Position) * TESTSTRUCT_BYTELENGTH
CopyMemoryI ArrayElementGetPointer(ArrayRemoveElement, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytesFirstSection
CopyMemoryI ArrayElementGetPointer(ArrayRemoveElement, Position, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, Position + 1, TESTSTRUCT_BYTELENGTH), CopiedBytesSecondSection
End Function
Public Function ArrayElementGetPointer(ByRef Arr() As TestStruct, ByVal ElementIndex As Long, ByVal ElementByteLength As Long) As LongPtr
Dim ptrToArrayVar As LongPtr
Dim ptrToSafeArray As LongPtr
Dim ptrToArrayData As LongPtr
Dim ptrCursor As LongPtr
Dim uSAFEARRAY As SAFEARRAY
ptrToArrayVar = VarPtrArray(Arr)
CopyMemoryI VarPtr(ptrToSafeArray), ptrToArrayVar, 8
CopyMemoryII uSAFEARRAY, ptrToSafeArray, LenB(uSAFEARRAY)
ptrToArrayData = uSAFEARRAY.pvData
ptrCursor = ptrToArrayData + (ElementIndex * ElementByteLength)
ArrayElementGetPointer = ptrCursor
End Function
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T04:06:53.223",
"Id": "216385",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel",
"winapi"
],
"Title": "VBA Array Functions: insert element, remove element"
} | 216385 |
<p>Source: <em>HackerRank & ProjectEuler.net</em> </p>
<p><strong>Problem: Largest Product in a Grid</strong><br>
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.</p>
<pre><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
</code></pre>
<p>The product of these numbers is 26 × 63 × 78 × 14 = 1788696.</p>
<p>What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?</p>
<p><strong>Input</strong><br>
Input consists of 20 lines each containing 20 integers.</p>
<p><strong>Output</strong><br>
Print the required answer.</p>
<p><strong>Limits</strong><br>
0 ≤ each integer in the grid ≤ 100</p>
<p><strong>Sample</strong><br>
Input</p>
<pre><code>89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
</code></pre>
<p>Output</p>
<pre><code>73812150
</code></pre>
<p><strong>My solution (C++14)</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
// 2D grid represented by 1D vector for cache optimization
auto getGrid(int rows, int columns) {
auto values = rows * columns;
std::vector<int> grid(values);
std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());
return grid;
}
class LargestProductInAGrid {
public:
LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
columns_(columns),
nAdjacents_(nAdjacents) {}
auto largestProductInAGrid() {
long long largestProduct = 0;
for (auto row = 0; row < rows_; row++) {
largestProduct = std::max(largestProduct, largestProductInARow(row));
}
for (auto column = 0; column < columns_; column++) {
largestProduct = std::max(largestProduct, largestProductInAColumn(column));
largestProduct = std::max(largestProduct, largestProductInARightDiagonal(column));
largestProduct = std::max(largestProduct, largestProductInALeftDiagonal(column));
}
return largestProduct;
}
private:
long long largestProductInARow(int row) {
int low = row * columns_, end = low + columns_;
long long currentProduct = 0, highestProduct = 0;
while (low + nAdjacents_ - 1 < end) {
if (currentProduct == 0) {
currentProduct = std::accumulate(grid_.begin() + low, grid_.begin() + low + nAdjacents_, 1LL,
std::multiplies<>());
} else {
currentProduct /= grid_[low - 1];
currentProduct *= grid_[low + nAdjacents_ - 1];
}
if (currentProduct == 0) {
auto zero = std::find(grid_.begin() + low, grid_.begin() + low + nAdjacents_, 0);
low += zero - (grid_.begin() + low) + 1;
} else {
low++;
}
highestProduct = std::max(highestProduct, currentProduct);
}
return highestProduct;
}
int oneDIndex(int row, int column) {
return row * columns_ + column;
}
long long largestProductInAColumn(int column) {
int row = 0;
long long currentProduct = 0, highestProduct = 0;
while (row + nAdjacents_ - 1 < rows_) {
if (currentProduct == 0) {
currentProduct = 1;
for (int i = row; i < row + nAdjacents_; i++) {
currentProduct *= grid_[oneDIndex(i, column)];
}
} else {
currentProduct /= grid_[oneDIndex(row - 1, column)];
currentProduct *= grid_[oneDIndex(row + nAdjacents_ - 1, column)];
}
if (currentProduct == 0) {
while (grid_[oneDIndex(row, column)] != 0) {
row++;
}
}
row++;
highestProduct = std::max(highestProduct, currentProduct);
}
return highestProduct;
}
long long largestProductInARightDiagonal(int startingColumn) {
int row = 0, column = startingColumn;
long long currentProduct = 0, highestProduct = 0;
while (row + nAdjacents_ - 1 < rows_ && column + nAdjacents_ - 1 < columns_) {
if (currentProduct == 0) {
currentProduct = 1;
for (int i = row; i < row + nAdjacents_; i++) {
currentProduct *= grid_[oneDIndex(i, column + i)];
}
} else {
currentProduct /= grid_[oneDIndex(row - 1, column - 1)];
currentProduct *= grid_[oneDIndex(row + nAdjacents_ - 1, column + nAdjacents_ - 1)];
}
if (currentProduct == 0) {
while (grid_[oneDIndex(row, column)] != 0) {
row++, column++;
}
}
row++, column++;
highestProduct = std::max(highestProduct, currentProduct);
}
return highestProduct;
}
long long largestProductInALeftDiagonal(int startingColumn) {
int row = 0, column = startingColumn;
long long currentProduct = 0, highestProduct = 0;
while (row + nAdjacents_ - 1 < rows_ && column - nAdjacents_ + 1 >= 0) {
if (currentProduct == 0) {
currentProduct = 1;
for (int i = row; i < row + nAdjacents_; i++) {
currentProduct *= grid_[oneDIndex(i, column - i)];
}
} else {
currentProduct /= grid_[oneDIndex(row - 1, column + 1)];
currentProduct *= grid_[oneDIndex(row + nAdjacents_ - 1, column - nAdjacents_ + 1)];
}
if (currentProduct == 0) {
while (grid_[oneDIndex(row, column)] != 0) {
row++, column--;
}
}
row++, column--;
highestProduct = std::max(highestProduct, currentProduct);
}
return highestProduct;
}
std::vector<int> grid_;
int rows_;
int columns_;
int nAdjacents_;
};
int main() {
const int rows = 20, columns = 20, nAdjacents = 4;
auto grid = getGrid(rows, columns);
LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
std::cout << solution.largestProductInAGrid() << std::endl;
}
</code></pre>
<p><strong>Analysis</strong><br>
Time complexity: <span class="math-container">\$O(r * c)\$</span><br>
Space complexity: <span class="math-container">\$O(1)\$</span>, not counting initial data</p>
<p><strong>Comments</strong><br>
In the past, I solved this problem when I was learning to program using the brute force method. This time, I wanted to optimize it for performance while maintaining a reasonable standard of readability.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:38:29.353",
"Id": "418692",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>You are using <code>long long</code> for your products. The maximum possible product of 4 numbers between 0 & 100 is <span class=\"math-container\">\\$100^4\\$</span>, which fits in 27 bits. Using a <code>long</code> would be sufficient, as well as probably faster.</p>\n\n<hr>\n\n<p>When traversing rows, columns, right diagonals and left diagonals, your <code>oneDIndex()</code> increases by 1, 20, 21, and 19, respectively. The structure of your product_line maximum search is roughly the same in all 4 cases. You could combine these functions into one general purpose utility function to handle all of the 4 cases, with appropriate parametrization of the starting points, stopping points and strides.</p>\n\n<p>(Since this is a programming challenge, I will leave the realization of the above algorithm to the reader.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:44:52.073",
"Id": "418681",
"Score": "0",
"body": "Probably could template the largestProduct's type. My thinking was that 5+ elements would overflow with a long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:57:19.220",
"Id": "418697",
"Score": "0",
"body": "I implemented your suggestions here: https://codereview.stackexchange.com/questions/216426/follow-up-project-euler-11-largest-product-in-a-grid-cache-optimized-slid"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T05:24:55.853",
"Id": "216389",
"ParentId": "216386",
"Score": "1"
}
},
{
"body": "<p>There's a lot more duplication here than I'd expect. The processing of rows, columns, forward diagonals and reverse diagonals are all very similar to each other, particularly once the coordinates are linearised to an index into <code>grid</code>:</p>\n\n<ul>\n<li>rows have a step of 1 from one element to the next</li>\n<li>columns have a step of <code>columns</code> (or, in general, the \"stride\" of the array)</li>\n<li>diagonals have a step of <code>columns ± 1</code> depending on their direction.</li>\n</ul>\n\n<p>The other difference is the start and end margins to prevent advancing beyond the 2D bounds of the array; these are easily adjusted according to the direction.</p>\n\n<hr>\n\n<p>We ought to be more robust when reading inputs in <code>getGrid()</code>. We could test <code>std::cin</code> after reading from it, or simply set it before reading to throw exceptions on failures.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:57:09.167",
"Id": "418696",
"Score": "0",
"body": "I implemented your suggestions here: https://codereview.stackexchange.com/questions/216426/follow-up-project-euler-11-largest-product-in-a-grid-cache-optimized-slid"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:03:29.883",
"Id": "216405",
"ParentId": "216386",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T04:25:00.660",
"Id": "216386",
"Score": "2",
"Tags": [
"c++",
"performance",
"object-oriented",
"programming-challenge",
"c++14"
],
"Title": "Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)"
} | 216386 |
<p>The following function is accepting PUT connection to a server API, checks authorization to write and then performs write to a database.</p>
<p>The <code>eslint</code> linting tool complains saying "avoid nesting promises" and "Each then() should return a value or throw". I'm new to promises and I am not sure how to improve my code.</p>
<pre><code>app.put('/api/v0/note/:id', (req, res) => {
const id = req.params.id;
const uid = req.user ? req.user.uid : null;
return user_can_edit_note(uid, id).then(yes => {
if (yes) {
return db.collection('notes').doc(id).update({
title: req.body.title,
text: req.body.text,
author_uid: req.user ? req.user.uid : null,
updated_on: admin.firestore.Timestamp.now()
}).then(() => {
return res.json({
ok: "ok"
});
});
} else {
return res.status(403).json({
error: "Permission Denied",
note_id: id
});
}
}).catch((err) => {
console.error(err);
return res.status(500).json({error: String(err)});
});
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:19:48.213",
"Id": "418670",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<pre><code>// Nothing fancy, we just wrapped the result in an array\nconst promise1 = someAsyncOperation()\nconst promise2 = promise1.then(result => [result])\npromise2.then(result => console.log(result)) // [result]\n\n// More concisely\nsomeAsyncOperation()\n .then(result => [result])\n .then(resultInArary => console.log(resultInArray)) // [result]\n</code></pre>\n\n<p>Whatever you return in <code>then</code> becomes the resolved value of the promise it returns. In this case, when <code>promise1</code> resolved, we added a <code>then</code> that wrapped the result in an array. The returned value becomes the resolved value of <code>promise2</code>.</p>\n\n<p>Now here's where everyone fails when talking about promises. They miss explaining this one behavior which is vital to the concept of \"promise chaining\":</p>\n\n<pre><code>const promise1 = asyncOperation1()\nconst promise2 = promise1.then(result1 => asyncOperation2())\npromise2.then(result2 => {\n // This will not be invoked until asyncOperation2()'s promise resolves.\n // Also, result2 is NOT asyncOperation2()'s promise, but its resolved value.\n\n console.log(result2) // [result]\n})\n\n// More concisely\nsomeAsyncOperation()\n .then(result1 => asyncOperation2())\n .then(result2 => {\n // This will not be invoked until asyncOperation2()'s promise resolves.\n // Also, result2 is NOT asyncOperation2()'s promise, but its resolved value.\n\n console.log(result2) // [result]\n })\n</code></pre>\n\n<p>When you return <em>a promise</em> in a <code>then</code>, two things happen that's different from returning a \"normal value\".</p>\n\n<ol>\n<li>It uses the resolved value of <code>asyncOperation2()</code> as the resolved value of <code>promise2</code>, not the promise returned by the function call.</li>\n<li><code>promise2</code> will not resolve and its callbacks will not be invoked until the promise returned by <code>asyncOperation2()</code> resolves. </li>\n</ol>\n\n<p>By now, you should now see how promise \"chaining\" is achieved. It's because of this one trick, returning promises in <code>then</code>, that allows subsequent <code>then</code>s to \"wait\" for (more precisely, not fire callbacks until) the previous promise. You could have code that looks like:</p>\n\n<pre><code>asyncOp1()\n .then(r1 => asyncOp2())\n .then(r2 => asyncOp3())\n .then(r3 => asyncOp4())\n .then(r4 => asyncOp5())\n .then(r5 => console.log('done'))\n .catch(e => console.log('one of the above failed'))\n</code></pre>\n\n<p>So in your code's case, it would look like this:</p>\n\n<pre><code>class ForbiddenError extends Error {\n constructor(message){\n super(message)\n // Add additional properties\n }\n}\n\napp.put('/api/v0/note/:id', (req, res) => {\n const id = req.params.id\n const uid = req.user ? req.user.uid : null\n\n user_can_edit_note(uid, id)\n .then(yes => {\n\n // The catch() down below will, uhm... catch this throw.\n if(!yes) throw new ForbiddenError()\n\n // Return the promise of this operation. The next then() handles it.\n return db.collection('notes').doc(id).update({\n title: req.body.title,\n text: req.body.text,\n author_uid: req.user ? req.user.uid : null,\n updated_on: admin.firestore.Timestamp.now()\n })\n })\n .then(() => {\n // Update completed, respond with ok.\n\n return res.json({\n ok: \"ok\"\n });\n })\n .catch((err) => {\n // Any throws not recovered in the sequence will invoke this catch.\n // Use this to evaluate your error. You can extend Error to have it carry\n // custom properties and messages.\n\n if(err instanceof ForbiddenError){\n return res.status(403).json({\n error: \"Permission Denied\",\n note_id: id\n })\n } else {\n return res.status(500).json({\n error: \"Server error\"\n })\n }\n })\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:55:52.643",
"Id": "216427",
"ParentId": "216388",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216427",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T05:23:07.003",
"Id": "216388",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"database",
"promise"
],
"Title": "Handling a PUT API call to write to a database using promises"
} | 216388 |
<p>I have three getters in my store:</p>
<pre><code>getActiveTournaments(state) {
return state.tournaments.data
? state.tournaments.data
.filter(tournament => tournament.state_value === 'in_progress')
// sort tournaments by date of creation
.sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
: [];
},
getFutureTournaments(state) {
return state.tournaments.data
? state.tournaments.data
.filter(tournament => tournament.state_value === 'promo')
// sort tournaments by date of creation
.sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
: [];
},
getPastTournaments(state) {
return state.tournaments.data
? state.tournaments.data
.filter(tournament => tournament.state_value === 'finished')
// sort tournaments by date of creation
.sort((tournamentA, tournamentB) => tournamentA.created_at - tournamentB.created_at)
: [];
},
</code></pre>
<p>In my component I have a slider which accept an array of three items, each first one from an arrays returned by every getters.
So I created a computed property in my component in order to get these items and then pass them to the slider:</p>
<pre><code><template>
...
<hovering-image-slider v-if="getLatestTournaments.length > 0"
:slideData="getLatestTournaments" />
...
</template>
<script>
...
getLatestTournaments() {
return this.getFutureTournaments[0]
&& this.getActiveTournaments[0]
&& this.getPastTournaments[0]
? [
this.getFutureTournaments[0],
this.getActiveTournaments[0],
this.getPastTournaments[0]]
: [];
},
</script>
</code></pre>
<p>It works fine but it seems like an ugly solution. Slider component will get an error of undefined data if I will not check the presence of <code>[0]</code> element in the computed property. I thought that by doing some checking at the level of my getters, it will not require checking in the component but apparently it does. Can you please advice how I can improve this existing code? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:16:50.317",
"Id": "418662",
"Score": "1",
"body": "If you would add `console.log(state.tournaments.data)` in your getters, what do they say?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:21:36.287",
"Id": "418664",
"Score": "0",
"body": "It will return all tournaments I have. I send one request to get them all and then filter this state in getters in order to get tournament of one type."
}
] | [
{
"body": "<h2>DRY the code</h2>\n\n<p>The 3 store getters are identical apart from the filter value. So first thing is to remove the repeated code. Create a function (either in the store, or within its scope, that you pass the <code>state</code> and the filter string.</p>\n\n<p>You get something like</p>\n\n<pre><code>filterTournaments(state, filter) {\n return state.tournaments.data\n ? state.tournaments.data\n .filter(tournament => tournament.state_value === filter)\n .sort((A, B) => A.created_at - B.created_at)\n : [];\n}, \ngetActiveTournaments(state) { return this.filterTournaments(state, \"in_progress\") },\ngetFutureTournaments(state) { return this.filterTournaments(state, \"promo\") },\ngetPastTournaments(state) { return this.filterTournaments(state, \"finished\") },\n</code></pre>\n\n<h2>Direct to the array</h2>\n\n<p>The current solution on the HTML side is ugly, if you do have data to display, you have to get the data again, filtering and sorting each a second time.</p>\n\n<p>Get the three items and put them directly in an array and test if all truthy, if so return the array, else an empty array.</p>\n\n<pre><code>getLatestTournaments() {\n const tournaments = [\n this.getActiveTournaments[0], \n this.getFutureTournaments[0], \n this.getPastTournaments[0]\n ];\n return tournaments[0] && tournaments[1] && tournaments[2] ? tournaments : [];\n}\n</code></pre>\n\n<h2>Do it in the store</h2>\n\n<h3>Fast and efficient</h3>\n\n<p>If you want it done at the store and you can add some smarts to the filter function, that way you can avoid a lot of needless processing and memory use. Using filter and sort to find the min item with a matching <code>state_value</code> is not efficient.</p>\n\n<pre><code>getFilteredTournaments(state) { \n const data = state.tournaments.data;\n if (!data) { return [] }\n const filters = [\"in_progress\", \"promo\", \"finished\"];\n const tournaments = [];\n for (const filter of filters) {\n let min = Infinity, minTournament;\n for (const tournament of data) {\n const {state_value, created_at} = tournament;\n if (state_value === filter && created_at < min) {\n min = created_at;\n minTournament = tournament;\n }\n }\n if (minTournament) { tournaments.push(minTournament) }\n else { return [] }\n }\n return tournaments;\n}, \n</code></pre>\n\n<p>Then you need only the one call</p>\n\n<pre><code>:slideData=\"getFilteredTournaments\"\n</code></pre>\n\n<p>I am not that familiar with VUE so may need the wrapper</p>\n\n<pre><code>:slideData=\"getLatestTournaments\"\n\n<script>\n getLatestTournaments() { return this.getFilteredTournaments }\n</script>\n</code></pre>\n\n<p>But that type of code does not suit everyone.</p>\n\n<h2>Keep it simple</h2>\n\n<p>Using the existing methodologies you can do the 3 filters in one function in the store as follows</p>\n\n<pre><code>getAllTournaments(state) { \n const data = state.tournaments.data;\n if (data) {\n const filter = filter => data\n .filter(tournament => tournament.state_value === filter)\n .sort((A, B) => A.created_at - B.created_at)[0];\n const result = [\n filter(\"in_progress\"),\n filter(\"promo\"),\n filter(\"finished\"),\n ];\n return result.some(item => !item) ? [] : result;\n }\n return [];\n},\n</code></pre>\n\n<p>and call with</p>\n\n<pre><code>getLatestTournaments() { return this.getAllTournaments }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:40:43.913",
"Id": "418704",
"Score": "0",
"body": "Thank you very much for this wonderful explanation and solution! It works! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:40:58.240",
"Id": "216423",
"ParentId": "216401",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216423",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T09:58:58.517",
"Id": "216401",
"Score": "1",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Remove excessive recurrent code from store and computed"
} | 216401 |
<p>I am working on the problem <code>removeDuplicatesFromSortedList</code></p>
<blockquote>
<p>Given a sorted array <em>nums</em>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" rel="nofollow noreferrer"><strong>in-place</strong></a> such that each element appear only <em>once</em> and return the new length.</p>
<p>Do not allocate extra space for another array, you must do this by <strong>modifying the input array in-place</strong> with O(1) extra memory.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
</code></pre>
</blockquote>
<p>My solution and TestCase</p>
<pre><code>class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""
"""
#Base Case
if len(nums) < 2: return len(nums)
#iteraton Case
i = 0 #slow-run pointer
for j in range(1, len(nums)):
if nums[j] == nums[i]:
continue
if nums[j] != nums[i]: #capture the result
i += 1
nums[i] = nums[j] #in place overriden
return i + 1
class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_raw1(self):
nums = [1, 1, 2]
check = self.solution.removeDuplicates(nums)
answer = 2
self.assertEqual(check, answer)
def test_raw2(self):
nums = [0,0,1,1,1,2,2,3,3,4]
check = self.solution.removeDuplicates(nums)
answer = 5
self.assertEqual(check, answer)
unittest.main()
</code></pre>
<p>This runs but I get a report:</p>
<blockquote>
<p>Runtime: 72 ms, faster than 49.32% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 14.8 MB, less than 5.43% of Python3 online submissions for Remove Duplicates from Sorted Array.</p>
</blockquote>
<p>Less than 5.43%, I employ the in-place strategies but get such a low rank, how could improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:44:35.587",
"Id": "418674",
"Score": "0",
"body": "This would be cheating, but did you try if the online judge actually checks if the array is manipulated in-place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:01:41.923",
"Id": "486319",
"Score": "0",
"body": "You don't test whether the changes are in-place"
}
] | [
{
"body": "<p>One way that might speed up your solution slightly is to only place the value if necessary. Also note that only one of the two <code>if</code> conditions can be true, so just use <code>else</code>. Or even better, since there was a <code>continue</code> in the other case, just don't indent it.</p>\n\n<pre><code>i = 0 #slow-run pointer\nfor j in range(1, len(nums)):\n if nums[j] == nums[i]: \n continue \n # capture the result\n i += 1\n if i != j:\n nums[i] = nums[j] #in place overriden \n</code></pre>\n\n<p>You can also save half of the index lookups by iterating over the values. Of course it will need slightly more memory this way.</p>\n\n<pre><code>def removeDuplicates(nums):\n if len(nums) < 2:\n return len(nums)\n i = 0 #slow-run pointer\n for j, value in enumerate(nums):\n if value == nums[i]:\n continue\n # capture the result\n i += 1\n if i != j:\n nums[i] = value # in place overriden \n return i + 1\n</code></pre>\n\n<p>This can probably be further sped-up by saving <code>nums[i]</code> in a variable as well.</p>\n\n<hr>\n\n<p>What is interesting is to see timing comparisons to using the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipe</a> <code>unique_justseen</code> (which I would recommend you use in production if you want to get duplicate free values in vanilla Python):</p>\n\n<pre><code>from itertools import groupby\nfrom operator import itemgetter\n\ndef unique_justseen(iterable, key=None):\n \"List unique elements, preserving order. Remember only the element just seen.\"\n # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B\n # unique_justseen('ABBCcAD', str.lower) --> A B C A D\n return map(next, map(itemgetter(1), groupby(iterable, key)))\n\ndef remove_duplicates(nums):\n for i, value in enumerate(unique_justseen(nums)):\n nums[i] = value\n return i + 1\n</code></pre>\n\n<p>For <code>nums = list(np.random.randint(100, size=10000))</code> they take almost the same time:</p>\n\n<ul>\n<li><code>removeDuplicates</code> took 0.0023s</li>\n<li><code>remove_duplicates</code> took 0.0026s</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:29:36.337",
"Id": "418701",
"Score": "0",
"body": "@Aethenosity I read it as both improvements would be welcome (and since they accepted the answer, apparently it was not so far off the mark either). Note that answers are free to comment on any and all aspects of the code here, anyways, regardless of what the OP wants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:30:31.140",
"Id": "418702",
"Score": "0",
"body": "@Aethenosity Feel free to post another answer if you see a way to reduce the memory used, though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T05:10:07.357",
"Id": "472654",
"Score": "0",
"body": "Your removeDuplicates solution does not work when referring back to resulting list value.\ninput: [1, 1, 2, 3, 3, 3, 3, 5]\noutput: [1, 2, 3, 5, 3, 3, 3, 5]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T05:14:21.700",
"Id": "472655",
"Score": "0",
"body": "@EdwardWilliams That's fine according to the specifications as long as it also returns `4` as the new length. Might have time later to check if this is the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:02:25.537",
"Id": "472706",
"Score": "1",
"body": "Yeah that is the case, I went and checked :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:54:00.497",
"Id": "216408",
"ParentId": "216403",
"Score": "8"
}
},
{
"body": "<p>A very minor concern: we have this condition:</p>\n\n<blockquote>\n<pre><code> if len(nums) < 2: return len(nums)\n</code></pre>\n</blockquote>\n\n<p>but none of the included tests exercise it. If we want our testing to be complete, we should have cases with empty and 1-element lists as input.</p>\n\n<p>TBH, I'd reduce that to a simpler condition, and remove the need for one of the tests:</p>\n\n<pre><code>if not nums:\n return 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T16:42:44.960",
"Id": "216431",
"ParentId": "216403",
"Score": "2"
}
},
{
"body": "<p>I have posted this solution and I got 76 ms, faster than 98% on my first submission.\nBut consider this, to check the timer of LeetCode I tried more submissions (with the same exact code) and obtain very different results: 124, 156, 164, 120, 88 ms.\nWhile the memory stays always consistent the runtime may vary quite a bit!</p>\n<pre><code> i = 0\n for j in range(1, len(nums)):\n if (nums[i] != nums[j]):\n i += 1\n nums[i] = nums[j]\n i +=1\n return i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T07:26:04.847",
"Id": "486305",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. On Code Review, every answer should contain at least a part review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T04:09:51.217",
"Id": "486770",
"Score": "0",
"body": "It was my first StackOverflow comment so I'm really new to this, what do you mean by a part review? Maybe saying the algorithm works in place and saves memory? It is a really simple algorithm that's why I felt there was no need for comments and such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T11:34:52.657",
"Id": "486796",
"Score": "0",
"body": "That not the entire answer has to be about the code/approach presented (the review), but every answer must at least do this in part. It's fine if you provide alternative implementations, as long as they're part of a review. Alternative implementations on itself are not a review and not helpful on a site called Code *Review*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T04:28:25.280",
"Id": "248303",
"ParentId": "216403",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216408",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:44:22.050",
"Id": "216403",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"memory-optimization"
],
"Title": "In place solution to remove duplicates from a sorted list"
} | 216403 |
<p>This is a follow-up to my ex-posted Blackjack game that uses a MySQL database to store the accounts and user's money. I tried splitting <code>display_info()</code> a bit, I also added a check for validating the Email address and the passwords are now hashed.</p>
<pre><code>from random import shuffle
import os
import cymysql
from getpass import getpass
import sys
import re
from bcrypt import hashpw, gensalt
def shuffled_shoe():
shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
shuffle(shoe)
return shoe
def deal_card(shoe, person, number):
for _ in range(number):
person.append(shoe.pop())
def deal_hand(shoe, player, dealer):
for _ in range(2):
deal_card(shoe, player, 1)
deal_card(shoe, dealer, 1)
def score(person):
non_aces = [c for c in person if c != 'A']
aces = [c for c in person if c == 'A']
total = 0
for card in non_aces:
if card in 'JQK':
total += 10
else:
total += int(card)
for card in aces:
if total <= 10:
total += 11
else:
total += 1
return total
def set_money(money, money_bet, win, push):
if win:
money += money_bet * 2
elif push:
money += money_bet
return money
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
def display_info(still_playing, player, dealer, money, money_bet, player_stands):
win = False
push = False
clear_console()
print(f"Money: ${money}")
print(f"Money bet: ${money_bet}")
print("Your cards: [{}] ({})".format(']['.join(player), score(player)))
if player_stands:
print("Dealer cards: [{}] ({})".format(']['.join(dealer), score(dealer)))
else:
print("Dealer cards: [{}][?]".format(dealer[0]))
first_hand = len(dealer) == 2
if score(player) == 21:
print("Blackjack! You won")
still_playing = False
win = True
elif first_hand and score(dealer) == 21:
print("Dealer got a blackjack. You lost!")
still_playing = False
elif score(player) > 21:
print("Busted! You lost!")
still_playing = False
if player_stands:
if score(dealer) > 21:
print("Dealer busted! You won")
win = True
elif score(player) > score(dealer):
print("You beat the dealer! You won!")
win = True
elif score(player) < score(dealer):
print("Dealer has beaten you. You lost!")
else:
print("Push. Nobody wins or losses.")
push = True
still_playing = False
money = set_money(money, money_bet, win, push)
return still_playing, money
def hit_or_stand():
while True:
print("What do you choose?")
print("[1] - Hit")
print("[2] - Stand")
ans = input('> ')
if ans in '12':
return ans
def bet(money):
clear_console()
print(f"Money: ${money}")
print("How much money do you want to bet?")
while True:
money_bet = int(input('> '))
if money_bet <= money and not money_bet <= 0:
money -= money_bet
return money, money_bet
else:
print("Please enter a valid bet.")
def player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands):
while not player_stands:
if hit_or_stand() == '2':
player_stands = True
player_plays = False
elif not player_stands:
deal_card(shoe, player, 1)
display_info(True, player, dealer, money, money_bet, player_stands)
if score(player) >= 21:
player_plays = False
break
return player_plays, player_stands
def dealer_play(shoe, dealer, dealer_minimum_score):
while score(dealer) <= dealer_minimum_score:
deal_card(shoe, dealer, 1)
return False
def check_money(money):
if money == 0:
print("\nUnfortunately you don't have any money.")
sys.exit()
def update_db_money(cur, money, email):
cur.execute("UPDATE `users` SET `money`=%s WHERE `email`=%s", (money, email))
cur.close()
def play_again(cur, money, email):
check_money(money)
while True:
print("\nDo you want to play again? [Y]es/[N]o")
ans = input("> ").lower()
if ans == 'y':
return True
elif ans == 'n':
update_db_money(cur, money, email)
return False
def get_user_info():
while True:
email = input("Email address (max. 255 chars.): ")
password = getpass("Password (max. 255 chars.): ").encode('utf-8')
hashed_pw = hashpw(password, gensalt())
if len(email) < 255 and len(password) < 255:
if re.match(r'[^@]+@[^@]+\.[^@]+', email):
return email, password, hashed_pw
else:
print("Please enter a valid email address.")
def register(cur, email, hashed_pw):
cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, hashed_pw))
def login(cur, email, password, hashed_pw):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
correct_credentials = cur.fetchone()
correct_hash = correct_credentials[2].encode('utf-8')
if hashpw(password, correct_hash) == correct_hash:
print("You've succesfully logged-in!")
else:
print("You failed logging-in!")
sys.exit()
def check_account(cur, email):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
return bool(cur.fetchone())
def start():
print("\nDo you want to start playing? [Y]es/[N]o")
ans = input('> ').lower()
if ans == 'y':
return True
elif ans == 'n':
return False
def db_conn():
conn = cymysql.connect(
host='127.0.0.1',
user='root',
passwd='',
db='blackjack'
)
with conn:
cur = conn.cursor()
email, password, hashed_pw = get_user_info()
checked = check_account(cur, email)
if checked:
login(cur, email, password, hashed_pw)
else:
register(cur, email, hashed_pw)
print("You've succesfully registered and recieved $1000 as a gift!")
cur.execute("SELECT `money` FROM `users` WHERE `email`=%s", (email,))
money_tuple = cur.fetchone()
money = money_tuple[0]
check_money(money)
return cur, money, email
def main():
cur, money, email = db_conn()
keeps_playing = start()
while keeps_playing:
shoe = shuffled_shoe()
player = []
dealer = []
still_playing = True
player_plays = True
player_stands = False
money, money_bet = bet(money)
deal_hand(shoe, player, dealer)
still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
while still_playing:
while player_plays:
player_plays, player_stands = player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands)
still_playing = dealer_play(shoe, dealer, 17)
still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
keeps_playing = play_again(cur, money, email)
if __name__ == '__main__':
main()
</code></pre>
<p>Blackjack.sql:</p>
<pre class="lang-sql prettyprint-override"><code>SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
`money` int(11) NOT NULL DEFAULT '1000',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
</code></pre>
| [] | [
{
"body": "<h2>Don't materialize generators unless you have to</h2>\n\n<p>These:</p>\n\n<pre><code>non_aces = [c for c in person if c != 'A']\naces = [c for c in person if c == 'A']\n</code></pre>\n\n<p>take up memory, however inconsequential. Since you only iterate through them once, change the <code>[]</code> brackets to <code>()</code> parens to leave it as a generator.</p>\n\n<h2>Choose a quote standard</h2>\n\n<p>You have both single and double:</p>\n\n<pre><code> print(\"[2] - Stand\")\n ans = input('> ')\n</code></pre>\n\n<p>Choose one and stick with it.</p>\n\n<h2>Redundant else</h2>\n\n<pre><code> return money, money_bet\n else:\n</code></pre>\n\n<p>doesn't require an <code>else</code>, because you've already returned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:07:34.533",
"Id": "216436",
"ParentId": "216409",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:15:53.240",
"Id": "216409",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sql",
"mysql",
"playing-cards"
],
"Title": "Blackjack game with database - follow-up"
} | 216409 |
<p>I have a web application where users can uploads image documents.</p>
<p>Now, <strong>after</strong> a new document is uploaded into the system, it should:</p>
<p>1) Be optimized. (OCR)</p>
<p>2) Perform various rules on the OCR output.</p>
<p>For this, I rely on <code>Events</code> in Laravel. </p>
<p>I have registered below events for my model <code>Document.php</code>:</p>
<pre><code>protected $dispatchesEvents = [
'created' => DocumentCreated::class, //Once document has been uploaded.
'updated' => DocumentUpdated::class, //Once OCR has been performed.
];
</code></pre>
<p>Now, for each event, I have also defined listeners.</p>
<p>This is my <code>EventServiceProvider.php</code>:</p>
<pre><code>DocumentCreated::class => [
PerformOCROnDocument::class,
],
DocumentUpdated::class => [
ParseDocument::class,
],
</code></pre>
<p>So when a new document is created, it will:</p>
<p>1) Perform OCR on the document. This class <code>PerformOCROnDocument</code> will do various tasks.
Most importantly, <code>PerformOCROnDocument</code> will ultimately call: </p>
<pre><code>$document->save();
</code></pre>
<p>Since I have defined <code>updated</code> on my <code>Document</code> model, once the <code>save()</code> method is called, it will trigger the next event: <code>DocumentUpdated</code>. </p>
<p>2) Now, <code>ParseDocument</code> will run, and do some various tasks as well.</p>
<p><strong>Important:</strong></p>
<p>The <code>ParseDocument</code> <strong>cannot</strong> run <em>before</em> <code>PerformOCROnDocument</code> has finished.</p>
<p>Now my question is: <strong>is this the correct way of doing this and handling events?</strong> Ultimately, my events will implement <code>ShouldQueue</code> so everything will be added to a queue and handled async.</p>
<h1>Alternative solution</h1>
<p>Now, what I could also do was to trigger an event <em>inside</em> <code>PerformOCROnDocument</code>, like this:</p>
<pre><code>$document->save();
event(new OCRFinished($document));
</code></pre>
<p>And then in <code>EventSerivceProvider.php</code>, do like this:</p>
<pre><code>OCRFinished::class => [
ParseDocument::class,
],
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:31:56.817",
"Id": "216412",
"Score": "1",
"Tags": [
"php",
"laravel"
],
"Title": "Handling Multiple Asynchronous Events"
} | 216412 |
<p>I want to reduce the big time it needed for my mandelbrot set generator to work. I'm working this for already a week.
I tried to reduce the canvas size from 400 by 400 to 200 by 200 and the speed increased a bit. Tried using multithread.js but still slow...</p>
<p>Here's the JavaScript code:</p>
<pre><code>//Create the canvas, then collect the height and width
var a, b, c, canvas, rect;
//zoomon click
var zoomOnClick = true;
//if running
var running = false;
//to prevent error during loading, make sure that
//the canvas is loaded first before calling any methods
canvas = document.getElementById("paper");
c = canvas.getContext("2d");
a = canvas.width;
b = canvas.height;
//when canvas is clicked, call drawOnClick function
canvas.onclick = function(e){
setTimeout(function(){
drawOnClick(e);
}, 10)
}
//changes the mandelbrot set based on mouse clicks
function drawOnClick(e){
rect = canvas.getBoundingClientRect()
if(zoomOnClick){
var mx = panX + (e.clientX - rect.left) / zooms;
var my = panY + (e.clientY - rect.top) / zooms;
zooms *= zf;
panX = mx - ((e.clientX - rect.left) / zooms);
panY = my - ((e.clientY - rect.top) / zooms);
}else{
var mx = panX + (e.clientX - rect.left) / zooms;
var my = panY + (e.clientY - rect.top) / zooms;
zooms /= zf;
panX = mx - ((e.clientX - rect.left) / zooms);
panY = my - ((e.clientY - rect.top) / zooms);
}
pan = (panX + 2 / zooms) - (panX - 1 / zooms);
document.getElementById("xa").value = panX;
document.getElementById("ya").value = panY;
document.getElementById("za").value = zooms;
pallete.setNumberRange(0,maxI);
if(0 < zooms && zooms < 50){
pallete.setNumberRange(0, 50);
maxI = 50;
}else if(50 < zooms && zooms < 100){
pallete.setNumberRange(0,100);
maxI = 100;
}else if(100 < zooms && zooms < 1000){
pallete.setNumberRange(0,255);
maxI = 255;
}else if(1000 < zooms && zooms < 10000){
pallete.setNumberRange(0,500);
maxI = 500;
}else if(10000 < zooms && zooms < 100000){
pallete.setNumberRange(0, 750);
maxI = 750;
}else if(100000 < zooms && zooms < 1000000){
pallete.setNumberRange(0, 1000);
maxI = 1000;
}else if(1000000 < zooms && zooms < 10000000){
pallete.setNumberRange(0, 2500);
maxI = 2500;
}
show();
requestAnimationFrame(abortRun);
requestAnimationFrame(startRun);
}
//when + was clicked above the canvas
function plus(){
zoomOnClick = true;
}
//same here
function minus(){
zoomOnClick = false;
}
//aborts startRun
function abortRun(){
if(running){running = false}
}
//starts calling mandelbrot
function startRun(){
//(function(){
setTimeout(function(){running = true}, 10);
setTimeout(function(){mandelbrot(zooms, panX, panY, 8)}, 10);
setTimeout(function(){mandelbrot(zooms, panX, panY, 5)}, 20);
setTimeout(function(){mandelbrot(zooms, panX, panY, 1)}, 30);
//})()
}
//in the instance, create all thngs
try{
//pan is the length of scroll
//zooms is the current number of zoom
//panX is the upper left Corner
//panY is the bottom left Corner
//zf is the increase factor in the zoom
//maxI is the total number of iteration
//per complex number
//create pallete to color mandelbrot by
//using rainbowvis.js
var pan, zooms, panX, panY, zf = 1.5, maxI = 50, ticks;
var pallete = new Rainbow();
pallete.setSpectrum("#000764","#206bcb","#edffff","#ffaa00","#000200");
pallete.setNumberRange(0,maxI);
//function that draws the mandelbrot set
// based on current zoom, panX, panY and scale
function mandelbrot(zm, panX, panY, scale){
//cncel run in some case
if(!running){
return;
}
if(scale === 1){
running = false;
}
scale = scale || 1;
//reset ticks
ticks = 0;
//px - Canvas x
//py - canvas y
//x - real x
//y - imaginary y
var px, py, x, y;
//loop from y's, then loop all x's
for(px = 0; px < a; px+=scale){
for(py = 0; py < b; py+=scale){
//zoom factors
x0 = panX + px/zm;
y0 = panY + py/zm;
var x = 0;
var y = 0;
var i = 0;
var xtemp;
while (x*x + y*y <= 4 && i < maxI) {
ticks++
xtemp = x*x - y*y + x0
y = 2*x*y + y0
x = xtemp
i = i + 1
}
//coloring
var shade = pallete.colourAt(i);
c.fillStyle = "#"+shade;
c.fillRect(px,py,scale, scale);
}
}
console.log("Total ticks: " + ticks + ", based on scale " + scale);
}
//reset
function work(){
document.getElementById("xa").value = -2.5;
document.getElementById("ya").value = -2;
document.getElementById("za").value = a/4;
pan = 0.01;
zooms = a / 4;
panX = -2.5;
panY = -2.0;
zf = 1.5;
maxI = 50;
pallete.setSpectrum("#000764","#206bcb","#edffff","#ffaa00","#000200");
pallete.setNumberRange(0,maxI);
show();
abortRun();
startRun();
}
//left to right scroll adjustment
function xScroll(n){
var temp = n ? parseFloat(document.getElementById("xa").value) + pan : parseFloat(document.getElementById("xa").value) - pan;
document.getElementById("xa").value = temp;
panX = temp;
show();
abortRun();
startRun();
}
//top to bottom scroll adjustment
function yScroll(n){
var temp = n ? parseFloat(document.getElementById("ya").value) + pan : parseFloat(document.getElementById("ya").value) - pan;
document.getElementById("ya").value = temp;
panY = temp;
show();
abortRun();
startRun();
}
//zoom in function
function zoomIn(){
zooms = zooms + zf;
pan = (panX + 2 / zooms) - (panX - 1 / zooms);
document.getElementById("za").value = zooms;
if(0 < zooms && zooms < 100){
pallete.setNumberRange(0,100);
maxI = 100;
}else if(100 < zooms && zooms < 1000){
pallete.setNumberRange(0,255);
maxI = 255;
}else if(1000 < zooms && zooms < 10000){
pallete.setNumberRange(0,500);
maxI = 500;
}
show();
abortRun();
startRun();
}
//zoom out function
function zoomOut(){
zooms = zooms - zf;
pan = (panX + 2 / zooms) - (panX - 1 / zooms)
document.getElementById("za").value = zooms;
if(zooms < 100){
pallete.setNumberRange(0,50);
maxI = 50;
}else if(zooms > 100 && zooms < 1000){
pallete.setNumberRange(0,100);
maxI = 100;
}else if(zooms > 1000 && zooms < 10000){
pallete.setNumberRange(0,255);
maxI = 255;
}
show();
abortRun();
startRun();
}
//adjust zoomfactor
function zoomFactor(){
var temp = document.getElementById("zf").value;
zf = parseInt(temp);
show();
}
//adjust maxI
function changeMaxI(){
var temp = document.getElementById("mi").value;
maxI = parseInt(temp);
pallete.setNumberRange(0,maxI);
show();
abortRun();
startRun();
}
//adjust pallete
function changePallete(){
var temp = (document.getElementById("plt").value).split(" ");
if(temp.length < 3){
alert(" Please enter more colors ");
return
}
pallete.setSpectrumByArray(temp);
show();
abortRun();
startRun();
}
//show details
function show(){
var temp = "Scroll: " + pan + "<br /> Current zoom: " + zooms + "<br /> topLeftX: " + panX + "<br /> topRightY: " + panY + "<br /> zoom factor: " + zf + "<br /> max iterations of loop: " + maxI;
document.getElementById("dtls").innerHTML = temp;
}
/*favorable zoom
-0.373346235978374
-0.6582261932152258
7000
-0.3618206208864465
-0.6453957620586814
155300315925100
*/
//about function
function about(){
alert("A mandelbrot set generator in javascript created by pvzzombs")
console.log("A mandelbrot set generator in javascript created by pvzzombs");
}
}catch(e){
throw "Error: " + e ;
}
</code></pre>
<p>Here's a <a href="https://htmlpreview.github.io/?https://github.com/pvzzombs/mandelbrots-in-javascript/blob/master/test.html" rel="nofollow noreferrer">preview link</a>.</p>
<p><b> EDIT: </b></p>
<p>The javascript libraries I used are <a href="https://github.com/anomal/RainbowVis-JS/" rel="nofollow noreferrer">rainbow-vis.js</a>,</p>
<p>and <a href="https://github.com/keithwhor/multithread.js" rel="nofollow noreferrer">multithread.js</a> </p>
<p><strong>Edit 5/6/19</strong></p>
<p>The link above is now working :-).
I <strong>updated the code and I need more reviews from here</strong>. My mandelbrot set viewer is <em>slow on operating system like android</em>, it takes <strong>few seconds</strong> before it completes. But in <em>operating system like windows</em>, my mandelbrot set viewer just takes fraction of seconds.</p>
<p>Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:36:59.853",
"Id": "418691",
"Score": "0",
"body": "Do I see correctly that you do not use `var r` anywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T16:06:07.677",
"Id": "418706",
"Score": "1",
"body": "The linked page does not do anything. And what libraries are you using? there are many external references in the code snippet you provided, guessing what they are or how they works is not going to make for a good review."
}
] | [
{
"body": "<h2>What is Slow?</h2>\n<p>It is hard to know what people mean by slow. Your expectation may be comparable to a good C multi threaded Mandelbrot viewer zooming at 60fps, and slow means your code is more like 30-20fps.</p>\n<p>So all I can do is give you some pointers in regard to performance.</p>\n<p>Use ctx.getImageData to create an array to hold the pixels as 32Bit ints. Use a Uint32Array to hold the pallet colors so you can move them to the image pixels in one step.</p>\n<p>In performance code don't create and then dump arrays. <code>var arr = []</code> has a lot of overhead. so does <code>a.push(1)</code> even dumping an array has overhead <code>arr = undefined</code></p>\n<p>Don't do what is not needed inside performance code. At the very core of the render you had a completely redundant calculation that amounted to about 1/3 of the calculations done in the inner loop. that one line would have been 20% of the CPU cost (if you had all else optimal)</p>\n<h2>A slight improvement</h2>\n<p>Below is a quick example of the above points. I don't know if its the type of improvement you are looking for, (there are faster algorithms but they are complex) For a single thread JS per pixel Mandelbrot its about as fast as it can be done using the standard method.</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 blindmansPallet = {\n color: (r, g, b, a = 255) => ({r, g, b, a}),\n createLookup(range, size) {\n var idx = 0;\n blindmansPallet.range = range;\n blindmansPallet.int32 = new Uint32Array(size);\n const int8 = new Uint8ClampedArray(blindmansPallet.int32.buffer);\n const rangeStep = size / (range.length -1);\n for(let i = 0; i < size; i ++) {\n const low = i / rangeStep | 0;\n const high = low + 1;\n const unitDistBetweenRange = (i - (low * rangeStep)) / rangeStep;\n const u = unitDistBetweenRange;\n const lRGBA = range[low];\n const hRGBA = range[high];\n int8[idx++] = ((hRGBA.r ** 2 - lRGBA.r ** 2) * u + lRGBA.r ** 2) ** 0.5;\n int8[idx++] = ((hRGBA.g ** 2 - lRGBA.g ** 2) * u + lRGBA.g ** 2) ** 0.5;\n int8[idx++] = ((hRGBA.b ** 2 - lRGBA.b ** 2) * u + lRGBA.b ** 2) ** 0.5;\n int8[idx++] = ((hRGBA.a ** 2 - lRGBA.a ** 2) * u + lRGBA.a ** 2) ** 0.5;\n }\n return blindmansPallet.int32;\n }\n};\n\n;(() => {\n var panX = -3.5, panY = -1.5, zoom = 50, maxI = 100;\n const pallet = blindmansPallet.createLookup([\n blindmansPallet.color(0x00, 0x07, 0x64), \n blindmansPallet.color(0x20, 0x6b, 0xcb), \n blindmansPallet.color(0xed, 0xff, 0xff), \n blindmansPallet.color(0xff, 0xaa, 0x00), \n blindmansPallet.color(0x00, 0x02, 0x00)\n ], maxI\n );\n\n const ctx = canvas.getContext(\"2d\");\n const W = canvas.width, H = canvas.height;\n const imgData = ctx.getImageData(0,0,W,H);\n const pixels = new Uint32Array(imgData.data.buffer);\n canvas.addEventListener(\"click\",(e) => {\n var mx = panX + e.clientX / zoom;\n var my = panY + e.clientY / zoom;\n zoom *= 1.20;\n panX = mx - (e.clientX / zoom);\n panY = my - (e.clientY / zoom);\n draw(zoom, panX, panY);\n });\n\n draw(zoom, panX, panY);\n function draw(zoom, panX, panY, w = W, h = H, maxI = 100) {\n var px,py,x,y,xOld,yOld,xNew,yNew,i;\n for (px = 0; px < w; px++) {\n for (py = 0; py < h; py++) {\n xOld = x = panX + px / zoom;\n yOld = y = panY + py / zoom;\n for (i = 0; i < maxI; i++) {\n xNew = (xOld * xOld) - (yOld * yOld) - x;\n yNew = (2 * xOld * yOld) - y;\n if (xNew * xNew + yNew * yNew > 4) { break }\n xOld = xNew;\n yOld = yNew;\n }\n pixels[px + py * W] = pallet[i];\n }\n }\n ctx.putImageData(imgData,0,0);\n }\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: verdana;\n user-select: none; \n -moz-user-select: none; \n}\ncanvas {\n cursor: crosshair;\n border: 1px solid black;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\" width=\"400\" hieght=\"250\" style=\"cursor:crosshair\"></canvas>\n<div>Click to image to zoom. 400px by 250px single thread</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>More performance</h2>\n<p>For better you can use web-workers and share the typed arrays.</p>\n<p>You can use previous rendering to estimate where to add detail as you zoom in (a type of quad tree renderer).</p>\n<p>You can have instant refresh. That is, rather than wait for a frame to finish, as soon as a pan/zoom request is made, you drop the current processing and start on the new frame (this gives the illusion of better performance)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:16:17.077",
"Id": "216439",
"ParentId": "216415",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:44:43.127",
"Id": "216415",
"Score": "2",
"Tags": [
"javascript",
"performance",
"game",
"canvas",
"fractals"
],
"Title": "Mandelbrot Set generator"
} | 216415 |
<p>I have an assignment to solve this problem.</p>
<p><strong>Problem Description</strong></p>
<blockquote>
<p>Bob the Cat is building a new system, dubbed the Cats Transmission
System (CTS). This horribly inefficient system utilises cats to help
transfer information. In this system, there are <strong>N</strong> cats lined up in
a line from cat <strong>0</strong> to cat <strong>N-1</strong>. If a message needs to be
transferred from, say, cat 2 to cat 7, cat 2 will pass on the message
to cat 3, to cat 4... and so on, until it reaches cat 7. Sounds
simple, right? </p>
<p>However, there is a problem. As everyone knows, cats LOVE sleeping.
Some of these cats tend to fall asleep on the job. Say, if cat 3 falls
asleep, the message from cat 2 to cat 7 will not be able to be
transmitted. As such, given a list of "SLEEP" and "WAKE" events, as
well as "TRANSMIT" requests in between, Bob wants you to check if each
of these "TRANSMIT" requests will pass. All cats start out awake. </p>
<p>There will be a total of <strong>Q</strong> events. The format of the events will
be as follows: </p>
<p>Input The first line of input will contain two integers, <strong>N</strong> and
<strong>Q</strong>. The next <strong>Q</strong> lines of input will each contain one event as stated above. </p>
<p>Output There should be one line of output for every "TRANSMIT"
operation, either stating a "YES" or a "NO". </p>
<p>Limits</p>
<p>• 0<<strong>N</strong>≤2^31-1</p>
<p>• 0<<strong>Q</strong>≤300,000.</p>
<p>• All values of x and y are guaranteed to be between <strong>0</strong> and
<strong>N-1</strong>. </p>
<p><strong>Commands</strong></p>
<p>WAKE [x] </p>
<p>Cat [x] wakes up</p>
<p>SLEEP [x] </p>
<p>Cat [x] falls sleep</p>
<p>TRANSMIT [x][y] </p>
<p>Attempt to transmit information from cat [x] to cat [y] ([x] ≤ [y]).
If it is successful (all cats from [x] to [y] inclusive are awake),
then output “YES”. Otherwise, output “NO”.</p>
<p><strong>Sample input</strong></p>
<pre><code>8 8
TRANSMIT 2 7
SLEEP 6
TRANSMIT 1 7
TRANSMIT 1 5
SLEEP 4
TRANSMIT 1 3
WAKE 4
TRANSMIT 1 5
</code></pre>
<p><strong>Sample output</strong></p>
<pre><code>YES
NO
YES
YES
YES
</code></pre>
<p>Explanation There is a total of 8 cats, labelled from 0 to 7, and 8
events that follows.</p>
<p>Initially, all the 8 cats are awake. Hence, the transmission request
from cats 2 to 7 will succeed. Then, cat 6 falls asleep.
Subsequently, the transmission request from cats 1 to 7 will fail as
cat 5 cannot transfer the information to cat 6, which is sleeping.</p>
<p>However, the transmission request from cats 1 to 5 will still succeed
as every cat in the range is still awake.</p>
<p>Then, cat 4 falls asleep. The next transmission request from cats 1 to
3 still succeeds as every cat in the range is still awake.</p>
<p>Cat 4 now wakes up. The transmission request from cats 1 to 5 will
succeed as every cat in the range is now awake.</p>
</blockquote>
<p>I have attempted this problem using a TreeSet(I chose it because it's something like a double ended priority queue, hence my solution would run in <code>O(log n)</code>, however for some reason I can still get <code>TimeLimitExceeded</code> on the platform I'm testing on. Is there anything slow about the TreeSet that I'm unaware of, and what is the better solution here?</p>
<p><strong>Attempt</strong></p>
<pre><code>import java.util.*;
public class Transmission {
private void run() {
Scanner sc = new Scanner(System.in);
int endIdx = sc.nextInt()-1;
int cmdCount = sc.nextInt();
TreeSet<Integer> dEndQueue = new TreeSet<>();
for (int i=0;i< cmdCount;i++) {
String cmd = sc.next();
if (cmd.equals("TRANSMIT")) {
int start = sc.nextInt();
int end = sc.nextInt();
if (dEndQueue.isEmpty()) {
System.out.println("YES");
continue;
}
Integer firstHole = dEndQueue.ceiling(start);
if (firstHole==null || firstHole>end) {
System.out.println("YES");
} else {
System.out.println("NO");
}
} else if (cmd.equals("SLEEP")) {
int entry = sc.nextInt();
dEndQueue.add(entry);
} else if (cmd.equals("WAKE")) {
int entry = sc.nextInt();
dEndQueue.remove(entry);
}
}
}
public static void main(String[] args) {
Transmission newTransmission = new Transmission();
newTransmission.run();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:17:11.013",
"Id": "418834",
"Score": "0",
"body": "Seems like this should work. I have a feeling that perhaps the time limit was exceeded due to slow I/O, since your input could have up to 300,000 lines. You can try [taking the advice from this webpage to speed up Java I/O](https://algocoding.wordpress.com/2015/04/23/fast-io-methods-for-competitive-programming/) and see if it helps."
}
] | [
{
"body": "<p>I recommend you to use a Boolean array (states[n]) and set the value of the correspondent element to either true or false and iterate that array every time the TRANSMIT command is called:</p>\n\n<pre><code>private static String keyWord;\nprivate static int source;\nprivate static int destination;\nprivate static boolean[] states;\n\n\npublic static void main(String[] args){\n Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n int q = sc.nextInt();\n sc.nextLine();\n String [] commands = new String[q];\n states = new boolean[n];\n for(int i=0; i<n; i++) {\n states[i] =true;\n }\n String output = \"\";\n for(int i=0; i<q; i++) {\n commands[i] = sc.nextLine();\n output+=readCommand(commands[i]).length()!=0?readCommand(commands[i])+\"\\n\":\"\";\n }\n System.out.println(output);\n}\n\nprivate static String readCommand(String command) {\n String[] words = command.split(\" \");\n keyWord = words[0];\n source = Integer.parseInt(words[1]);\n if(keyWord.equals(\"SLEEP\")) {\n states[source] = false;\n return\"\";\n }\n if(keyWord.equals(\"WAKE\")) {\n states[source] = true;\n return \"\";\n }\n if(keyWord.equals(\"TRANSMIT\")) {\n destination = Integer.parseInt(words[2]);\n return isTransmitted(source, destination);\n }\n return\"\";\n}\n\nprivate static String isTransmitted(int from, int to) {\n for(int i = from; i<=to; i++) {\n if(!states[i]) {\n return \"NO\";\n }\n }\n return \"YES\";\n}\n</code></pre>\n\n<p>I hope this would help you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T12:28:12.060",
"Id": "418787",
"Score": "0",
"body": "Hi Mahdi, it is often more helpful to the OP if you can explain the parts in the original question that you liked or didn't like and what could be changed rather than just provide new code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T13:23:17.920",
"Id": "418794",
"Score": "0",
"body": "Hi Harald, thank you for the comment, I am partially new to the Stack community.\nthis is a problem solving issue, Prashin proposed a solution, which seems to cause a TimeLimitExceeded error on the platform he's working on using TreeSet as a main Data collection to solving this issue.\nI suggested another mechanism to solve the issue."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:49:57.337",
"Id": "216470",
"ParentId": "216416",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:45:45.450",
"Id": "216416",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Transmission Of Messages"
} | 216416 |
<p>Here is a rundown of the situation</p>
<ul>
<li>This is a .Net Core (2.1) application with a console and web front ends.
<em>For simplicity this question focuses only on the console end although
the web end has the same issues.</em> </li>
<li><a href="https://serilog.net/" rel="nofollow noreferrer">Serilog</a> is the logger of choice. We use 2 sinks (i.e. output sources): <a href="https://github.com/serilog/serilog-sinks-console" rel="nofollow noreferrer">Console</a> and <a href="https://github.com/serilog/serilog-sinks-mongodb" rel="nofollow noreferrer">MongoDB</a></li>
<li>Security is a concern - the MongoDB connection string contains the password so it needs to be fetched from a secure source. <em>Here we are using an custom created library to retrieve any sensitive information.</em></li>
<li>My understanding is that Serilog configurations are not mutable (for example, add/configure another sink) after initialization, but can be modified after the fact to some extent with "<a href="https://github.com/serilog/serilog/wiki/Enrichment" rel="nofollow noreferrer">enrichers</a>". This is an aspect I am unfamiliar with.</li>
<li>This solution is using <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1" rel="nofollow noreferrer">standard .NET dependency injection</a></li>
</ul>
<p><strong>What's a better way of setting up Serilog, where a sink has a dependency, in a solution using dependency injection?</strong> Examples, patterns, templates are welcome. Most examples I've come across of Serilog with .NET Core DI don't address this situation.</p>
<pre><code>public class Program
{
static int Main(string[] args)
{
var secrets = new ThirdPartySecretProvider("MyApp.Console");
var secretWrapper = new ThirdPartySecretProviderWrapper(secrets);
var loggingConnectionString = GetLoggingConnectionString(secretsWrapper);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Error)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.MongoDB(loggingConnectionString, "applicationLogs")
.CreateLogger();
SelfLog.Enable(System.Console.Error);
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection, secretServerWrapper);
var serviceProvider = serviceCollection.BuildServiceProvider();
try
{
var logger = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<Application>();
var config = serviceProvider.GetRequiredService<IConfiguration>();
Application app = new Application(logger, config);
app.Run(args);
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureServices(IServiceCollection services, ISecretsWrapper secrets)
{
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.Build();
var mongoUsernameRead = config["MongoDB:ReadUsername"];
var mongoClientRead = new DataAccess.Mongo.MongoClient(mongoUsernameRead, secrets.MongoReadPassword);
services.AddSingleton<DataAccess.Mongo.IMongoClient>(mongoClientRead);
var hadoopRepository = new HadoopRepository(secretServer.HadoopApiKey);
services.AddSingleton<IHadoopRepository>(hadoopRepository);
services
.AddLogging(configure => configure.AddSerilog(dispose: true))
.AddSingleton(config)
.AddSingleton<ISecretsWrapper>(secrets)
.AddSingleton<IFileHelper, FileHelper>()
.AddSingleton<IRepositoryMongo, RepositoryMongo>()
.AddSingleton<IServiceMongo, ServiceMongo>()
.AddSingleton<IBaseHttpClient, BaseHttpClient>()
// ... additional dependencies omitted
}
private static string GetLoggingConnectionString(ISecretsWrapper secrets)
{
var mongoUsernameReadWrite = "app_myAppReadWrite";
var mongoClientLog = new DataAccess.Mongo.MongoClient(mongoUsernameReadWrite, secrets.MongoReadWritePassword);
return mongoClientLog.MongoConnectionString;
}
}
</code></pre>
<p>Related examples:</p>
<ul>
<li>Writeup by nblumhardt, <s>a major Serilog contributor</s> creator of Serilog
<a href="https://nblumhardt.com/2017/08/use-serilog/" rel="nofollow noreferrer">https://nblumhardt.com/2017/08/use-serilog/</a> </li>
<li>Clean example with some a sink other than console <a href="https://jacksowter.net/serilog-config/" rel="nofollow noreferrer">https://jacksowter.net/serilog-config/</a></li>
<li><a href="https://stackoverflow.com/questions/25477415/how-can-i-reconfigure-serilog-without-restarting-the-application">Stack Overflow example</a> of creating multiple loggers at startup </li>
<li><a href="https://msdn.microsoft.com/en-us/magazine/mt707534.aspx" rel="nofollow noreferrer">Vanilla DI with .NET Core from MSDN</a> </li>
</ul>
<p>One potential change is to create a simple logger (using Serilogger or other) initially to capture failures before the application proper gets started, then create the desired logger to use for the rest of the application. <strong>What are the considerations of this approach?</strong></p>
| [] | [
{
"body": "<p>This issue is being discussed on the <a href=\"https://github.com/serilog/serilog-aspnetcore/issues/141\" rel=\"nofollow noreferrer\">Serilog integration for ASP.NET Core</a> repository. Nicholas Blumhardt has proposed a <a href=\"https://gist.github.com/nblumhardt/34c0c273c383da9745f4e974f12b9cac\" rel=\"nofollow noreferrer\">draft</a> for a <em>late init sink</em> that would be used like this:</p>\n\n<pre><code>var signalRSink = new LateInitSink();\n\nLog.Logger = new LoggerConfiguration()\n .WriteTo.Sink(signalRSink)\n .CreateLogger();\n\nLog.Information(\"Sadly, nobody will get this\");\n\n// ... resolve that hub ...\nsignalRSink.Init(wt => wt.Console());\n\nLog.Information(\"Ah so nice to be loggin' again\");\n</code></pre>\n\n<p>The final version is not yet implemented. Quoting Nicholas Blumhardt from the aforementioned issue:</p>\n\n<blockquote>\n <p>Yes, it's still being considered - just a matter of someone finding the time to dig in deeply/write some code. Cheers!</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T12:35:32.887",
"Id": "232440",
"ParentId": "216417",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "232440",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T12:53:35.857",
"Id": "216417",
"Score": "2",
"Tags": [
"c#",
"logging",
"dependency-injection",
".net-core"
],
"Title": "Include Serilog sink requiring dependency before dependency injection in .NET Core"
} | 216417 |
<p>I have a function that sorts and groups items inside an array and then adds a corresponding jsx element to the page.</p>
<p>I've already refactored it from 100 lines of code to 44, but I'm sure that its still unreadable pile of spaghetti code. I've tried filtering individuals and groups separately but that just bloats my code to some unbelievable extent so im looking for ways to reduce bloat and improve readability.</p>
<pre><code>// array - array im sorting
// ageStart - minimal age of person
// ageEnd - minimum age of person
// activity & time - specific to the jsx elements inside(dont really play a role here)
//
function group(array, ageStart, ageEnd, activity, time = '') {
// filtering by political views and age.
const polViewsLib = array.filter(item => item.polViews === 'Liberal'
&& item.age >= ageStart
&& item.age <= ageEnd)
//grouping items inside an array using reduce(groups people whose age difference is less than 5)
.reduce((acc, curr, ind, arr) => {
if (
!ind
|| curr.age - arr[ind - 1].age > 5
)acc.push([]);
acc[acc.length - 1].push(curr);
return acc;
}, []);
const polViewsConservative = array.filter(item => item.polViews === 'Conservative'
&& item.age >= ageStart
&& item.age <= ageEnd).reduce((acc, curr, ind, arr) => {
if (
!ind
|| curr.age - arr[ind - 1].age > 5
)acc.push([]);
acc[acc.length - 1].push(curr);
return acc;
}, []);
// returning data sorted by age and mapping them to corresponding jsx elements
return [polViewsLib, polViewsConservative].sort((a,b) => {
a[0].age - b[0].age;
}).map((item, index) => {
const res = item.length > 1 ? (
<PersonContainer
key={item[index].id}
data={item}
visibility={activity}
timePeriod={time}
/>
)
: (
<Person
key={item.id}
data={item[0]}
visibility={activity}
timePeriod={item}
/>
);
return res;
});
}
</code></pre>
<p>Typical item inside array that I process:</p>
<pre><code> {
id:151324,
name: 'John',
age: 45,
polViews: 'Liberal',
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:21:32.420",
"Id": "216421",
"Score": "2",
"Tags": [
"react.js",
"jsx"
],
"Title": "Grouping and displaying people by political demographics"
} | 216421 |
<p><strong>Original code review:</strong> <a href="https://codereview.stackexchange.com/questions/216386/project-euler-11-largest-product-in-a-grid-cache-optimized-sliding-window">Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)</a></p>
<hr>
<p>Source: <em>HackerRank & ProjectEuler.net</em> </p>
<p><strong>Problem: Largest Product in a Grid</strong><br>
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.</p>
<pre><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
</code></pre>
<p>The product of these numbers is 26 × 63 × 78 × 14 = 1788696.</p>
<p>What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?</p>
<p><strong>Input</strong><br>
Input consists of 20 lines each containing 20 integers.</p>
<p><strong>Output</strong><br>
Print the required answer.</p>
<p><strong>Limits</strong><br>
0 ≤ each integer in the grid ≤ 100</p>
<p><strong>Sample</strong><br>
Input</p>
<pre><code>89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
</code></pre>
<p>Output</p>
<pre><code>73812150
</code></pre>
<p><strong>My updated solution (C++14)</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
// 2D grid represented by 1D vector for cache optimization
auto getGrid(int rows, int columns) {
auto values = rows * columns;
std::vector<int> grid(values);
std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());
if (std::cin.fail()) {
throw std::runtime_error(
"The input is invalid! Check the rows and columns in your input and that all numbers in the grid are integers between 0 and 100.");
}
return grid;
}
class LargestProductInAGrid {
public:
LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
columns_(columns),
nAdjacents_(nAdjacents) {}
template<typename T>
auto largestProductInAGrid() {
T largestProduct = 0;
for (auto row = 0; row < rows_; row++) {
largestProduct = std::max(largestProduct,
largestProductInASeries<T>(SeriesType::HORIZONTAL, row * columns_));
}
for (auto column = 0; column < columns_; column++) {
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::VERTICAL, column));
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_RIGHT, column));
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_LEFT, column));
}
return largestProduct;
}
private:
enum SeriesType {
HORIZONTAL, VERTICAL, DIAGONAL_RIGHT, DIAGONAL_LEFT
};
template<typename T>
T largestProductInASeries(SeriesType type, int startingIndex) {
int low = startingIndex, current = low;
T currentProduct = initializeProductInASeries<T>(type, current);
if (current < 0) return 0;
T highestProduct = currentProduct;
while (current >= 0) {
if (currentProduct == 0) {
while (grid_[low] != 0) low = nextIndex(type, low);
low = nextIndex(type, low);
current = low;
currentProduct = initializeProductInASeries<T>(type, current);
} else {
currentProduct /= grid_[low];
currentProduct *= grid_[current];
low = nextIndex(type, low);
current = nextIndex(type, current);
}
highestProduct = std::max(highestProduct, currentProduct);
}
return highestProduct;
}
template<typename T>
T initializeProductInASeries(SeriesType type, int &index) {
T product = 1;
for (int i = 0; i < nAdjacents_ && product > 0; i++) {
product *= grid_[index];
index = nextIndex(type, index);
if (index < 0) return 0;
}
return product;
}
int nextIndex(SeriesType type, int currentIndex) {
auto canAdvanceRight = bool((currentIndex + 1) % columns_);
if (type == SeriesType::HORIZONTAL && canAdvanceRight) {
return currentIndex + 1;
}
auto canAdvanceDown = currentIndex / columns_ + 1 < rows_;
if (type == SeriesType::VERTICAL && canAdvanceDown) {
return currentIndex + columns_;
}
if (type == SeriesType::DIAGONAL_RIGHT && canAdvanceRight && canAdvanceDown) {
return currentIndex + columns_ + 1;
}
auto canAdvanceLeft = bool(currentIndex % columns_);
if (type == SeriesType::DIAGONAL_LEFT && canAdvanceLeft && canAdvanceDown) {
return currentIndex + columns_ - 1;
}
return -1;
}
std::vector<int> grid_;
int rows_;
int columns_;
int nAdjacents_;
};
int main() {
const int rows = 20, columns = 20, nAdjacents = 4;
auto grid = getGrid(rows, columns);
LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
std::cout << solution.largestProductInAGrid<int>() << std::endl;
}
</code></pre>
<p><strong>Analysis</strong><br>
Time complexity: <span class="math-container">\$O(r * c)\$</span><br>
Space complexity: <span class="math-container">\$O(1)\$</span>, not counting initial data</p>
<p><strong>Comments</strong><br>
Changes:</p>
<ol>
<li>Combined the logic of rows, columns, and diagonals into a single method. </li>
<li>Templated the methods so that it can handle adjacent numbers <4 efficiently with <code>int</code> and between 5 and 9 numbers with <code>unsigned long long</code>.</li>
<li>getGrid now throws an exception when the input is invalid.</li>
</ol>
| [] | [
{
"body": "<p>I'd separate the concerns of storage (<code>Grid</code>) and the search (<code>longestProduct</code>), like this:</p>\n<pre><code>class Grid\n{\n std::vector<int> grid;\n int rows;\n int columns;\n\npublic:\n Grid(int rows, int columns)\n : grid(rows * columns),\n rows(rows), columns(columns)\n {\n }\n\n void read(std::istream& in);\n long largestProduct(unsigned nAdjacents) const;\n}\n</code></pre>\n<p>See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.</p>\n<p>To calculate a <em>n</em>-product, we just need to know the starting point, stride, and length:</p>\n<pre><code>private:\n long product(int x, int y, int step, unsigned n) const\n {\n long product = 1;\n for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {\n product *= *p;\n }\n return product;\n }\n</code></pre>\n<p>We can create a "high water mark" type to save typing all those <code>std::max()</code> invocations:</p>\n<pre><code>// a simple value that can only be ovewritten by greater values\ntemplate<typename T>\nstruct MaxValue\n{\n T value;\n\n MaxValue(T value = T{})\n : value(value)\n {}\n\n operator T() const\n {\n return value;\n }\n\n MaxValue& operator=(T other)\n {\n if (value < other)\n value = other;\n return *this;\n }\n};\n</code></pre>\n<p>Then our <code>largestProduct</code> search becomes much simpler (C++17, for my convenience):</p>\n<pre><code>long largestProduct(unsigned nAdjacents) const\n{\n static const std::initializer_list<std::pair<int,int>> directions\n = {{0,1}, {1,1}, {1,0}, {1,-1}};\n\n MaxValue<long> largestProduct = 0;\n for (auto const [dy, dx]: directions) {\n // determine range to search\n auto const row_0 = 0u;\n auto const row_n = dy > 0 ? rows - nAdjacents : rows;\n auto const col_0 = dx < 0 ? nAdjacents : 0;\n auto const col_n = dx > 0 ? columns - nAdjacents : columns;\n auto const step = dy * columns + dx;\n // do the search\n for (auto r = row_0; r < row_n; ++r) {\n for (auto c = col_0; c < col_n; ++c) {\n largestProduct = product(r, c, step, nAdjacents);\n }\n }\n }\n return largestProduct;\n}\n</code></pre>\n<hr />\n<h1>Full code</h1>\n<pre><code>#include <algorithm>\n#include <initializer_list>\n#include <iterator>\n#include <istream>\n#include <vector>\n\n// a simple value that can only be ovewritten by greater values\ntemplate<typename T>\nstruct MaxValue\n{\n T value;\n\n MaxValue(T value = T{})\n : value(value)\n {}\n\n operator T() const\n {\n return value;\n }\n\n MaxValue& operator=(T other)\n {\n if (value < other)\n value = other;\n return *this;\n }\n};\n\n\nclass Grid\n{\n std::vector<int> grid;\n int rows;\n int columns;\n\npublic:\n Grid(int rows, int columns)\n : grid(rows * columns),\n rows(rows), columns(columns)\n {\n }\n\n void read(std::istream& in)\n {\n // temporarily set in to throw on error\n auto saved_exceptions = in.exceptions();\n in.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n\n auto values = rows * columns;\n std::copy_n(std::istream_iterator<int>(in), values, grid.begin());\n\n // restore exception state\n in.exceptions(saved_exceptions);\n }\n\n long largestProduct(unsigned nAdjacents) const\n {\n static const std::initializer_list<std::pair<int,int>> directions\n = {{0,1}, {1,1}, {1,0}, {1,-1}};\n\n MaxValue<long> largestProduct = 0;\n for (auto const [dy, dx]: directions) {\n // determine range to search\n auto const row_0 = 0u;\n auto const row_n = dy > 0 ? rows - nAdjacents : rows;\n auto const col_0 = dx < 0 ? nAdjacents : 0;\n auto const col_n = dx > 0 ? columns - nAdjacents : columns;\n auto const step = dy * columns + dx;\n // do the search\n for (auto r = row_0; r < row_n; ++r) {\n for (auto c = col_0; c < col_n; ++c) {\n largestProduct = product(r, c, step, nAdjacents);\n }\n }\n }\n return largestProduct;\n }\n\nprivate:\n long product(int x, int y, int step, unsigned n) const\n {\n long product = 1;\n for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {\n product *= *p;\n }\n return product;\n }\n};\n\n\n\n#include <iostream>\n#include <sstream>\n\nint main()\n{\n std::istringstream in(R"(\n89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48\n)");\n Grid grid{20, 20};\n grid.read(in);\n\n std::cout << grid.largestProduct(4) << std::endl;\n}\n</code></pre>\n<hr />\n<p>From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:14:05.327",
"Id": "418782",
"Score": "0",
"body": "I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:19:15.293",
"Id": "418783",
"Score": "1",
"body": "I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:22:12.973",
"Id": "418784",
"Score": "0",
"body": "The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T12:16:13.910",
"Id": "418785",
"Score": "1",
"body": "\"*a Grid struct that can be constructed by the different classes...*\" - Indeed, I agree with that. I was just being lazy when I made `read()` a member."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T16:26:18.437",
"Id": "216429",
"ParentId": "216426",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:55:11.083",
"Id": "216426",
"Score": "3",
"Tags": [
"c++",
"performance",
"object-oriented",
"programming-challenge",
"c++14"
],
"Title": "(Follow-up) Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)"
} | 216426 |
<p>I have this function (wb is a public workbook variable):</p>
<pre><code>Function GetTiersAccount(TiersName As String, Clients As Boolean) As Long
If Clients = True Then
On Error GoTo ERRRRR
GetTiersAccount = WorksheetFunction.VLookup(TiersName, wb.Sheets(1).Range("A1:B13"), 2, False)
Exit Function
Else
On Error GoTo ERRRRR
GetTiersAccount = WorksheetFunction.VLookup(TiersName, wb.Sheets(1).Range("D1:E94"), 2, False)
Exit Function
End If
ERRRRR:
GetTiersAccount = 471
End Function
</code></pre>
<p>I feel like the way I have managed to deal with <code>worksheetfunction.vlookup</code> error unelegant. However I want Gettieraccount to return 471 on vlookup error.</p>
<p>There must be a better way to do that.
Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:50:59.633",
"Id": "418714",
"Score": "0",
"body": "How about https://stackoverflow.com/a/18064104"
}
] | [
{
"body": "<p>Your handling is not necessarily unelegant, but there are a couple of things to point out.</p>\n\n<p>The main thing is that you're repeating code that really only needs to be there once. For example, you only need to write the <code>VLookup</code> statement once. Just set up a variable to define your range. </p>\n\n<p>Your error handling can work, but you need to more clearly define what is a \"normal exit\" from your routine and what is an error exit. It's typical in this case to structure your error handling with the form shown below because there may be processing required during a normal exit only that you still might have to perform during an error exit.</p>\n\n<pre><code>Option Explicit\n\nFunction GetTiersAccount(TiersName As String, Clients As Boolean) As Long\n Dim lookupRange As Range\n If Clients = True Then\n Set lookupRange = wb.Sheets(1).Range(\"A1:B13\")\n Else\n Set lookupRange = wb.Sheets(1).Range(\"D1:E94\")\n End If\n\n On Error GoTo ERRRRR\n GetTiersAccount = WorksheetFunction.VLookup(TiersName, lookupRange, 2, False)\n\nNormalExit:\n Exit Function\n\nERRRRR:\n GetTiersAccount = 471\n Resume NormalExit\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:47:34.257",
"Id": "419068",
"Score": "0",
"body": "Think you can reduce to If Clients Then ... without the = True"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:19:40.127",
"Id": "419075",
"Score": "1",
"body": "I agree, though in that case I would change the variable name to something other than `Clients`. Since I didn't know what the purpose of the variable was, I left it in the OP's form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:38:00.197",
"Id": "419243",
"Score": "0",
"body": "Client = customer if that matters.\n\nIf there is no impact on performance between `if boolean vs if boolean = true` I'd rather keep it = true; so that I remeber the variable is a bool.\n\nThanks for input & answer i'll keep that in mind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:58:39.037",
"Id": "419244",
"Score": "0",
"body": "The kind of variable name I'm talking about would be something like `theClientListIsValid` or `clientsExist`. That way, the code is self-commenting, self-descriptive, and self-documenting because you read `If theClientListIsValid Then ...`. In this form the `= True` is superfluous."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:14:30.177",
"Id": "419445",
"Score": "0",
"body": "I see, I'll try to do it that way in my future projects."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:08:57.367",
"Id": "216487",
"ParentId": "216428",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T15:51:02.487",
"Id": "216428",
"Score": "1",
"Tags": [
"vba"
],
"Title": "Worksheetfunction.Vlookup value on error"
} | 216428 |
<p>I would value your opinion on the following piece of code. I am rather new to both Python and Monte Carlo analysis, so I was wondering whether the routine makes sense to more experienced and knowledgeable users.</p>
<pre><code>import numpy as np
import scipy.optimize
from scipy.optimize import curve_fit
from scipy.stats import kde
def MC_analysis_a():
x = (0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.064, 0.128)
y_signal_a = (1.0, 0.83, 0.71, 0.62, 0.55, 0.49, 0.45, 0.42)
x = np.array(x, dtype = float)
y_signal_a = np.array(y_signal_a, dtype = float)
e_signal_a = (0.06, 0.05, 0.04, 0.05, 0.04, 0.02, 0.04, 0.03)
def func(x, a, b):
return a * np.exp(-b * x)
initial_guess = [1.0, 1.0]
fitting_parameters, covariance_matrix = curve_fit(func, x, y_signal_a, initial_guess)
print(round(fitting_parameters[1], 2))
# ---> PRODUCING PARAMETERS ESTIMATES
total_iterations = 5000
MC_pars = np.array([])
for iTrial in range(total_iterations):
xTrial = x
yTrial = y_signal_a + np.random.normal(loc = y_signal_a, scale = e_signal_a, size = np.size(y_signal_a))
try:
iteration_identifiers, covariance_matrix = curve_fit(func, xTrial, yTrial, initial_guess)
except:
dumdum = 1
continue
# ---> STACKING RESULTS
if np.size(MC_pars) < 1:
MC_pars = np.copy(iteration_identifiers)
else:
MC_pars = np.vstack((MC_pars, iteration_identifiers))
# ---> SLICING THE ARRAY
print(np.shape(MC_pars))
print(np.median(MC_pars[:,1]))
print(np.std(MC_pars[:,1]))
</code></pre>
<p>The output I get is apparently satisfactory and plausible.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:27:36.803",
"Id": "418711",
"Score": "1",
"body": "Welcome to Code Review! In order to get the best possible outcome from the review please change your code so that is is runnable and complete ([How to create a MWE?](https://stackoverflow.com/help/mcve), minimal is not so important here). This allows users to verify that it is actually [on-topic](https://codereview.stackexchange.com/help/on-topic) as well as to get a better feeling on what you actually want to accomplish."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:29:00.343",
"Id": "418712",
"Score": "0",
"body": "Does the code need to be generalised in any particular way? Are you wanting to apply it to different datasets, or to fit a different family of curves? Do you want to store the output for further analysis?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:22:52.180",
"Id": "418722",
"Score": "0",
"body": "As @Alex says. Don't omit any of your imports, especially for external references like numpy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:59:32.047",
"Id": "418725",
"Score": "0",
"body": "Hello! Thanks everybody for the feedback, I'll edit the post incorporating actual data to fit. @RussHyde I don't really aim at generalisation as of now, I don't think I'll use it for anything else than exponential decay actually..."
}
] | [
{
"body": "<p>Before starting with feedback on the actual code, I would like to share some thoughts about the style.</p>\n\n<h2>Chose a style, be consistent</h2>\n\n<p>Python comes with an official style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> which summarizes a whole lot of style advice and best practices generally to be used while coding Python. If you decide to stick with PEP8 or not is up to you, but if you chose a style, e.g. for variable names, <em>stick to it</em>. Your code has a mix of <code>camelCase</code> (e.g. <code>iTrial</code>), <code>snake_case</code> (e.g. <code>initial_guess</code>, actually most of the code is like this and also the PEP8 recommendation) and <code>snake_swallowed_CASE_case</code> (e.g. <code>MC_analysis_a</code>).</p>\n\n<p>Another recommendation of PEP8 is to omit whitespace around <code>=</code> when used as keyword arguments to functions/methods. Incorporating the first one the line</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>yTrial = y_signal_a + np.random.normal(loc = y_signal_a, scale = e_signal_a, size = np.size(y_signal_a))\n</code></pre>\n\n<p>would become</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>y_trial = y_signal_a + np.random.normal(loc=y_signal_a, scale=e_signal_a, size=np.size(y_signal_a))\n</code></pre>\n\n<p>The same goes for <code>np.array(...)</code> and friends earlier in the code.</p>\n\n<p>As a final note, do your future self a favor and document what you're doing in that function in a short little description right at the beginning. You might think you will remember your thoughts when looking at it in three months, but trust me, you won't. It is as simpe as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def mc_analysis_a():\n \"\"\"Running Monte Carlo analysis on some 1D sample data\n\n This function uses scipy.optimize.curve_fit to estimate the parameters of\n a simple x -> y timeseries.\n \"\"\"\n</code></pre>\n\n<p>This type of documentation has the nice feature that it will be picked up by Python's built-in <code>help(...)</code> function.</p>\n\n<h2>The code itself</h2>\n\n<p>At the moment, there are some unused imports in your code (namely <code>import scipy.optimize</code> and <code>from scipy.stats import kde</code>, but that might be a symptom from bringing the code here on Code Review.</p>\n\n<p>The next thing that caught my attention was that you do not use the estimated covariance matrix returned by <code>curve_fit</code>. If you really have no use for it, replace <code>covariance_matrix</code> by <code>_</code> (underscore). This a convention used to tell yourself and others that you don't care about that (part of the) return value.</p>\n\n<p>Next up comes <code>total_iterations = 5000</code> as hardcoded value. If you ever try to increase or decrease that value you would have to edit your function before rerunning the experiment. A more convenient approach from my point of view would be to use it as input parameter with an default value of <code>5000</code>. The same applys to <code>initial_guess</code> and friends. (<strong>Sidenote:</strong> if you were to use <code>initial_guess</code>' current value as default value and ever modified it in the function, funny things can happen. See <a href=\"https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\" rel=\"noreferrer\">this link</a> for more information on this topic, since this would get to involved for this review.)</p>\n\n<p>Now to the core loop of the function. While generating the noisy y values, <code>np.size(y_signal_a)</code> should be equal to <code>y_signal_a.size</code>. In your case, one could also use <code>y_signal.shape</code> in that spot which would then guarantee that the noise also fits the shape of the array if it was multidimensional.</p>\n\n<p>Using <code>try: ... catch: ...</code> without specifying an exception type is considered a bad practice since it will catch all kinds of exceptions including keyboard interupts (Ctrl+C). So if you ever decide to stop the test because 5000 iterations where to much, well, you would have to kill the Python process itself. The <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html\" rel=\"noreferrer\">documentation</a> of <code>curve_fit</code> lists all the exceptions that might be raised while using this function. These are <code>ValueError</code> for bad input data or input options and <code>Runtime Error</code> in case the least-squares minimization failed. So these would likely be your candidates to catch, with the following construct:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n ...\ncatch (ValueError, RuntimeError):\n continue # or handle the exception however you want\n</code></pre>\n\n<p>This would still stop the execution if something unexpected has happened and, as you can see, works for <a href=\"https://docs.python.org/3/tutorial/errors.html#handling-exceptions\" rel=\"noreferrer\">multiple exceptions</a> as well.</p>\n\n<p>On the same loop you're using the NumPy array <code>MC_pars</code> to collect the results of those iterations step by step. As you might have noticed NumPy arrays are not really comfortable to use in an expanding way since their main purpose is to allow fast vectorized operations on \"fixed\" size numerical data (though their use is not limited to that). At this point using a simple Python list might be a better option. This would allow you to <code>.append(...)</code> the results of every run very conveniently. And, as you seem to know, it's quite easy to convert Python iterables (lists, tuples) into NumPy arrays.</p>\n\n<p>For reference you can find the modified version of the total script below.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nfrom scipy.optimize import curve_fit\n\ndef mc_analysis_a(total_iterations=5000):\n \"\"\"Running Monte Carlo analysis on some 1D sample data\n\n This function uses scipy.optimize.curve_fit to estimate the parameters of\n a simple x -> y timeseries.\n \"\"\"\n x = (0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.064, 0.128)\n y_signal_a = (1.0, 0.83, 0.71, 0.62, 0.55, 0.49, 0.45, 0.42)\n x = np.array(x, dtype = float)\n y_signal_a = np.array(y_signal_a, dtype = float)\n e_signal_a = (0.06, 0.05, 0.04, 0.05, 0.04, 0.02, 0.04, 0.03)\n\n def func(x, a, b):\n return a * np.exp(-b * x)\n\n initial_guess = [1.0, 1.0]\n fitting_parameters, _ = curve_fit(func, x, y_signal_a, initial_guess)\n print(round(fitting_parameters[1], 2))\n\n # ---> PRODUCING PARAMETERS ESTIMATES\n mc_pars = []\n for _ in range(total_iterations): # i was replaced by _ here, because it was not used\n x_trial = x\n y_trial = y_signal_a + np.random.normal(loc=y_signal_a, scale=e_signal_a, size=y_signal_a.shape)\n try:\n iteration_identifiers, _ = curve_fit(func, x_trial, y_trial, initial_guess)\n except (ValueError, RuntimeError):\n continue\n\n mc_pars.append(iteration_identifiers)\n\n # ---> SLICING THE ARRAY\n mc_pars = np.array(mc_pars)\n print(mc_pars.shape)\n print(mc_pars[:, 1].std())\n\nif __name__ == \"__main__\":\n mc_analysis_a(5000):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:10:21.220",
"Id": "418736",
"Score": "0",
"body": "Thanks @Alex for the very complete review, I was indeed unaware of the PEP8 convention. To be honest, I am pretty consistent and always use snake_case type of names, but since this code was partially adapted from a source, then some features just stayed like that. With respect to the \"useless\" imports, this MC simulation is part of a much larger code, approx. 1000 lines, which I thought would have been inappropriate posting. Most importantly: the estimated covariance matrix from curve_fit is needed because I am actually interested in seeing how much MC does improve the fit. Thanks a lot again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:27:30.270",
"Id": "418740",
"Score": "0",
"body": "Good to hear that, I hope you'll still get some value ouf of the review. (I tend to feel uneasy when thinking about 1000+ line scripts, especially if the parts are not clearly separated. But that's a topic for another time.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:57:58.870",
"Id": "216447",
"ParentId": "216433",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216447",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:10:06.793",
"Id": "216433",
"Score": "6",
"Tags": [
"python",
"numpy",
"statistics",
"numerical-methods",
"scipy"
],
"Title": "Monte Carlo errors estimation routine"
} | 216433 |
<p>I have a working solution on a training exercise that I wish to improve as I feel there is a better way to utilize the form and get to the fieldsets etc using page model. </p>
<p>HTML:</p>
<pre><code><!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>QAE Challenge</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function(e,n,t){function r(t){if(!n[t]){var o=n[t]={exports:{}};e[t][0].call(o.exports,function(n){var o=e[t][1][n];return r(o||n)},o,o.exports)}return n[t].exports}if("function"==typeof __nr_require)return __nr_require;for(var o=0;o<t.length;o++)r(t[o]);return r}({1:[function(e,n,t){function r(){}function o(e,n,t){return function(){return i(e,[c.now()].concat(u(arguments)),n?null:this,t),n?void 0:this}}var i=e("handle"),a=e(3),u=e(4),f=e("ee").get("tracer"),c=e("loader"),s=NREUM;"undefined"==typeof window.newrelic&&(newrelic=s);var p=["setPageViewName","setCustomAttribute","setErrorHandler","finished","addToTrace","inlineHit","addRelease"],d="api-",l=d+"ixn-";a(p,function(e,n){s[n]=o(d+n,!0,"api")}),s.addPageAction=o(d+"addPageAction",!0),s.setCurrentRouteName=o(d+"routeName",!0),n.exports=newrelic,s.interaction=function(){return(new r).get()};var m=r.prototype={createTracer:function(e,n){var t={},r=this,o="function"==typeof n;return i(l+"tracer",[c.now(),e,t],r),function(){if(f.emit((o?"":"no-")+"fn-start",[c.now(),r,o],t),o)try{return n.apply(this,arguments)}catch(e){throw f.emit("fn-err",[arguments,this,e],t),e}finally{f.emit("fn-end",[c.now()],t)}}}};a("actionText,setName,setAttribute,save,ignore,onEnd,getContext,end,get".split(","),function(e,n){m[n]=o(l+n)}),newrelic.noticeError=function(e,n){"string"==typeof e&&(e=new Error(e)),i("err",[e,c.now(),!1,n])}},{}],2:[function(e,n,t){function r(e,n){if(!o)return!1;if(e!==o)return!1;if(!n)return!0;if(!i)return!1;for(var t=i.split("."),r=n.split("."),a=0;a<r.length;a++)if(r[a]!==t[a])return!1;return!0}var o=null,i=null,a=/Version\/(\S+)\s+Safari/;if(navigator.userAgent){var u=navigator.userAgent,f=u.match(a);f&&u.indexOf("Chrome")===-1&&u.indexOf("Chromium")===-1&&(o="Safari",i=f[1])}n.exports={agent:o,version:i,match:r}},{}],3:[function(e,n,t){function r(e,n){var t=[],r="",i=0;for(r in e)o.call(e,r)&&(t[i]=n(r,e[r]),i+=1);return t}var o=Object.prototype.hasOwnProperty;n.exports=r},{}],4:[function(e,n,t){function r(e,n,t){n||(n=0),"undefined"==typeof t&&(t=e?e.length:0);for(var r=-1,o=t-n||0,i=Array(o<0?0:o);++r<o;)i[r]=e[n+r];return i}n.exports=r},{}],5:[function(e,n,t){n.exports={exists:"undefined"!=typeof window.performance&&window.performance.timing&&"undefined"!=typeof window.performance.timing.navigationStart}},{}],ee:[function(e,n,t){function r(){}function o(e){function n(e){return e&&e instanceof r?e:e?f(e,u,i):i()}function t(t,r,o,i){if(!d.aborted||i){e&&e(t,r,o);for(var a=n(o),u=v(t),f=u.length,c=0;c<f;c++)u[c].apply(a,r);var p=s[y[t]];return p&&p.push([b,t,r,a]),a}}function l(e,n){h[e]=v(e).concat(n)}function m(e,n){var t=h[e];if(t)for(var r=0;r<t.length;r++)t[r]===n&&t.splice(r,1)}function v(e){return h[e]||[]}function g(e){return p[e]=p[e]||o(t)}function w(e,n){c(e,function(e,t){n=n||"feature",y[t]=n,n in s||(s[n]=[])})}var h={},y={},b={on:l,addEventListener:l,removeEventListener:m,emit:t,get:g,listeners:v,context:n,buffer:w,abort:a,aborted:!1};return b}function i(){return new r}function a(){(s.api||s.feature)&&(d.aborted=!0,s=d.backlog={})}var u="nr@context",f=e("gos"),c=e(3),s={},p={},d=n.exports=o();d.backlog=s},{}],gos:[function(e,n,t){function r(e,n,t){if(o.call(e,n))return e[n];var r=t();if(Object.defineProperty&&Object.keys)try{return Object.defineProperty(e,n,{value:r,writable:!0,enumerable:!1}),r}catch(i){}return e[n]=r,r}var o=Object.prototype.hasOwnProperty;n.exports=r},{}],handle:[function(e,n,t){function r(e,n,t,r){o.buffer([e],r),o.emit(e,n,t)}var o=e("ee").get("handle");n.exports=r,r.ee=o},{}],id:[function(e,n,t){function r(e){var n=typeof e;return!e||"object"!==n&&"function"!==n?-1:e===window?0:a(e,i,function(){return o++})}var o=1,i="nr@id",a=e("gos");n.exports=r},{}],loader:[function(e,n,t){function r(){if(!E++){var e=x.info=NREUM.info,n=l.getElementsByTagName("script")[0];if(setTimeout(s.abort,3e4),!(e&&e.licenseKey&&e.applicationID&&n))return s.abort();c(y,function(n,t){e[n]||(e[n]=t)}),f("mark",["onload",a()+x.offset],null,"api");var t=l.createElement("script");t.src="https://"+e.agent,n.parentNode.insertBefore(t,n)}}function o(){"complete"===l.readyState&&i()}function i(){f("mark",["domContent",a()+x.offset],null,"api")}function a(){return O.exists&&performance.now?Math.round(performance.now()):(u=Math.max((new Date).getTime(),u))-x.offset}var u=(new Date).getTime(),f=e("handle"),c=e(3),s=e("ee"),p=e(2),d=window,l=d.document,m="addEventListener",v="attachEvent",g=d.XMLHttpRequest,w=g&&g.prototype;NREUM.o={ST:setTimeout,SI:d.setImmediate,CT:clearTimeout,XHR:g,REQ:d.Request,EV:d.Event,PR:d.Promise,MO:d.MutationObserver};var h=""+location,y={beacon:"bam.nr-data.net",errorBeacon:"bam.nr-data.net",agent:"js-agent.newrelic.com/nr-1118.min.js"},b=g&&w&&w[m]&&!/CriOS/.test(navigator.userAgent),x=n.exports={offset:u,now:a,origin:h,features:{},xhrWrappable:b,userAgent:p};e(1),l[m]?(l[m]("DOMContentLoaded",i,!1),d[m]("load",r,!1)):(l[v]("onreadystatechange",o),d[v]("onload",r)),f("mark",["firstbyte",u],null,"api");var E=0,O=e(5)},{}]},{},["loader"]);</script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(){
const FORM_TIME_START = Math.floor((new Date).getTime()/1000);
let formElement = document.getElementById("tfa_0");
if (null === formElement) {
formElement = document.getElementById("0");
}
let appendJsTimerElement = function(){
let formTimeDiff = Math.floor((new Date).getTime()/1000) - FORM_TIME_START;
let cumulatedTimeElement = document.getElementById("tfa_dbCumulatedTime");
if (null !== cumulatedTimeElement) {
let cumulatedTime = parseInt(cumulatedTimeElement.value);
if (null !== cumulatedTime && cumulatedTime > 0) {
formTimeDiff += cumulatedTime;
}
}
let jsTimeInput = document.createElement("input");
jsTimeInput.setAttribute("type", "hidden");
jsTimeInput.setAttribute("value", formTimeDiff.toString());
jsTimeInput.setAttribute("name", "tfa_dbElapsedJsTime");
jsTimeInput.setAttribute("id", "tfa_dbElapsedJsTime");
jsTimeInput.setAttribute("autocomplete", "off");
if (null !== formElement) {
formElement.appendChild(jsTimeInput);
}
};
if (null !== formElement) {
if(formElement.addEventListener){
formElement.addEventListener('submit', appendJsTimerElement, false);
} else if(formElement.attachEvent){
formElement.attachEvent('onsubmit', appendJsTimerElement);
}
}
});
</script>
<link href="https://www.tfaforms.com/dist/form-builder/5.0.0/wforms-layout.css?v=530-13" rel="stylesheet" type="text/css" />
<link href="https://www.tfaforms.com/uploads/themes/theme-52691.css" rel="stylesheet" type="text/css" />
<link href="https://www.tfaforms.com/dist/form-builder/5.0.0/wforms-jsonly.css?v=530-13" rel="alternate stylesheet" title="This stylesheet activated by javascript" type="text/css" />
<script type="text/javascript" src="https://www.tfaforms.com/wForms/3.11/js/wforms.js?v=530-13"></script>
<script type="text/javascript">
if(wFORMS.behaviors.prefill) wFORMS.behaviors.prefill.skip = true;
</script>
<script type="text/javascript" src="https://www.tfaforms.com/wForms/3.11/js/localization-en_US.js?v=530-13"></script>
</head>
<body class="default wFormWebPage">
<div id="tfaContent">
<div class="wFormContainer" >
<div class="wFormHeader"></div>
<style type="text/css"></style><div class=""><div class="wForm" id="4710335-WRPR" dir="ltr">
<div class="codesection" id="code-4710335"></div>
<h3 class="wFormTitle" id="4710335-T">QAE Challenge</h3>
<form method="post" action="https://www.tfaforms.com/responses/processor" class="hintsBelow labelsAbove" id="4710335" role="form" enctype="multipart/form-data">
<div class="oneField field-container-D " id="tfa_1-D">
<label id="tfa_1-L" class="label preField reqMark" for="tfa_1">Your email</label><br><div class="inputWrapper"><input type="text" id="tfa_1" name="tfa_1" value="" aria-required="true" title="Your email" data-dataset-allow-free-responses="" class="validate-email required"></div>
</div>
<div class="oneField field-container-D " id="tfa_4-D" role="group" aria-labelledby="tfa_4-L">
<label id="tfa_4-L" class="label preField ">Favorite Food</label><br><div class="inputWrapper"><span id="tfa_4" class="choices vertical "><span class="oneChoice"><input type="checkbox" value="tfa_5" class="" id="tfa_5" name="tfa_5" data-conditionals="#tfa_8" aria-labelledby="tfa_4-L tfa_5-L"><label class="label postField" id="tfa_5-L" for="tfa_5"><span class="input-checkbox-faux"></span>Cheese</label></span><span class="oneChoice"><input type="checkbox" value="tfa_6" class="" id="tfa_6" name="tfa_6" data-conditionals="#tfa_14" aria-labelledby="tfa_4-L tfa_6-L"><label class="label postField" id="tfa_6-L" for="tfa_6"><span class="input-checkbox-faux"></span>Bread</label></span><span class="oneChoice"><input type="checkbox" value="tfa_7" class="" id="tfa_7" name="tfa_7" data-conditionals="#tfa_19" aria-labelledby="tfa_4-L tfa_7-L"><label class="label postField" id="tfa_7-L" for="tfa_7"><span class="input-checkbox-faux"></span>Veggies</label></span></span></div>
</div>
<fieldset id="tfa_8" class="section" data-condition="`#tfa_5`">
<legend id="tfa_8-L">Cheese</legend>
<div class="oneField field-container-D " id="tfa_9-D" role="radiogroup" aria-labelledby="tfa_9-L">
<label id="tfa_9-L" class="label preField ">Pick a cheese</label><br><div class="inputWrapper"><span id="tfa_9" class="choices vertical "><span class="oneChoice"><input type="radio" value="tfa_10" class="" id="tfa_10" name="tfa_9" aria-labelledby="tfa_9-L tfa_10-L"><label class="label postField" id="tfa_10-L" for="tfa_10"><span class="input-radio-faux"></span>Chedder</label></span><span class="oneChoice"><input type="radio" value="tfa_11" class="" id="tfa_11" name="tfa_9" aria-labelledby="tfa_9-L tfa_11-L"><label class="label postField" id="tfa_11-L" for="tfa_11"><span class="input-radio-faux"></span>Swiss</label></span><span class="oneChoice"><input type="radio" value="tfa_12" class="" id="tfa_12" name="tfa_9" aria-labelledby="tfa_9-L tfa_12-L"><label class="label postField" id="tfa_12-L" for="tfa_12"><span class="input-radio-faux"></span>Brie</label></span></span></div>
</div>
<div class="oneField field-container-D " id="tfa_13-D">
<label id="tfa_13-L" class="label preField " for="tfa_13">Attach Picture</label><br><div class="inputWrapper"><input type="file" id="tfa_13" name="tfa_13" size="" title="Attach Picture" class=""></div>
</div>
</fieldset>
<fieldset id="tfa_14" class="section" data-condition="`#tfa_6`">
<legend id="tfa_14-L">Bread</legend>
<div class="oneField field-container-D " id="tfa_15-D" role="group" aria-labelledby="tfa_15-L">
<label id="tfa_15-L" class="label preField ">Bread Types</label><br><div class="inputWrapper"><span id="tfa_15" class="choices vertical "><span class="oneChoice"><input type="checkbox" value="tfa_16" class="" id="tfa_16" name="tfa_16" aria-labelledby="tfa_15-L tfa_16-L"><label class="label postField" id="tfa_16-L" for="tfa_16"><span class="input-checkbox-faux"></span>Rye</label></span><span class="oneChoice"><input type="checkbox" value="tfa_17" class="" id="tfa_17" name="tfa_17" aria-labelledby="tfa_15-L tfa_17-L"><label class="label postField" id="tfa_17-L" for="tfa_17"><span class="input-checkbox-faux"></span>Almond Flour</label></span><span class="oneChoice"><input type="checkbox" value="tfa_18" class="" id="tfa_18" name="tfa_18" aria-labelledby="tfa_15-L tfa_18-L"><label class="label postField" id="tfa_18-L" for="tfa_18"><span class="input-checkbox-faux"></span>Something else</label></span></span></div>
</div>
</fieldset>
<fieldset id="tfa_19" class="section" data-condition="`#tfa_7`">
<legend id="tfa_19-L">Veggies</legend>
<div class="oneField field-container-D " id="tfa_20-D">
<label id="tfa_20-L" class="label preField " for="tfa_20">Select all the ones you like</label><br><div class="inputWrapper"><select id="tfa_20" multiple name="tfa_20[]" title="Select all the ones you like" class=""><option value="">Please select...</option>
<option value="tfa_21" id="tfa_21" class="">Peppers</option>
<option value="tfa_22" id="tfa_22" class="">Celery</option>
<option value="tfa_23" id="tfa_23" class="">Apples</option></select></div>
</div>
</fieldset>
<div class="actions" id="4710335-A"><input type="submit" data-label="Submit" class="primaryAction" id="submit_button" value="Submit"></div>
<div style="clear:both"></div>
<input type="hidden" value="709-8a7ad32603893fd5f51e64de3741d534" name="tfa_dbCounters" id="tfa_dbCounters" autocomplete="off"><input type="hidden" value="4710335" name="tfa_dbFormId" id="tfa_dbFormId"><input type="hidden" value="" name="tfa_dbResponseId" id="tfa_dbResponseId"><input type="hidden" value="51914f055edc03755e1f773c4771ede9" name="tfa_dbControl" id="tfa_dbControl"><input type="hidden" value="1553796870" name="tfa_dbTimeStarted" id="tfa_dbTimeStarted" autocomplete="off"><input type="hidden" value="3" name="tfa_dbVersionId" id="tfa_dbVersionId"><input type="hidden" value="" name="tfa_switchedoff" id="tfa_switchedoff">
</form>
</div></div><div class="wFormFooter"><p class="supportInfo"><a target="new" class="contactInfoLink" href="https://www.tfaforms.com/forms/help/4710335">Contact Information</a><br></p></div>
<p class="supportInfo" >
</p>
</div> </div>
<script src='https://www.tfaforms.com/js/iframe_resize_helper_internal.js'></script>
<script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"bam.nr-data.net","licenseKey":"c33294f5df","applicationID":"90069622","transactionName":"YQNTMBRRXxZTAkJZVlhJchEVRF4IHUs=","queueTime":0,"applicationTime":129,"atts":"TURQRlxLTBg=","errorBeacon":"bam.nr-data.net","agent":""}</script></body>
</html>
</code></pre>
<p>Here is the code :</p>
<pre><code><?php
namespace Pages;
use SensioLabs\Behat\PageObjectExtension\PageObject\Page;
use Behat\Mink\Exception\ElementNotFoundException;
use WebDriver\Exception\NoAlertOpenError;
class ChallengePage extends Page
{
protected $path = '/4710335';
protected $elements = array(
'Form' => array('xpath' => '//*[@id="4710335"]'),
'Section_Cheese' => array('xpath' => '//fieldset[@id="tfa_8"]')
);
public function fillEmailField($email):ChallengePage
{
$form = $this->getElement('Form');
$form->fillField('tfa_1', $email);
return $this;
}
public function submitForm()
{
$form = $this->getElement('Form');
try{
$form->submit();
$this->getDriver()->getWebDriverSession()->accept_alert();
}catch(NoAlertOpenError $e){
}
}
public function checkFavoriteFood($favFood):ChallengePage
{
$form = $this->getElement('Form');
if ($favFood=='Cheese')
$form->checkField('tfa_5');
return $this;
}
public function unCheckFavoriteFood($favFood):ChallengePage
{
$form = $this->getElement('Form');
if ($favFood=='Cheese')
$form->uncheckField('tfa_5');
return $this;
}
public function isSectionVisible($sectionName):Bool
{
$section = $this->find('xpath', $this->elements['Section_'.$sectionName]['xpath']);
return $section->isVisible();
}
public function attachAFileForUpload():ChallengePage
{
$form = $this->getElement('Form');
$form->attachFileToField('tfa_13', public_path().'/rabbit.jpg' );
return $this;
}
private function wait($seconds) {
sleep($seconds);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T02:07:23.040",
"Id": "418865",
"Score": "0",
"body": "I don't see any advantage in checking `null !== cumulatedTime &&` on a `parseInt()` value."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:09:12.427",
"Id": "216437",
"Score": "1",
"Tags": [
"php",
"css",
"selenium"
],
"Title": "Behat Page Object Model"
} | 216437 |
<p>(I was suggested to post here from <a href="https://stackoverflow.com/q/55398124/6660678">stack overflow</a> so hey guys!)</p>
<p>I have been given a problem where fractions between 1/2 - 1/1000 have to be added to create the longest sequence of all unique unit fractions.</p>
<p>The rules on constructing these fractions:</p>
<p>Let create a set: D , D is only to hold unique unit fractions , sub-fractions can add up to the same fraction for example:</p>
<pre><code> 1/10
/ \
1/110 + 1/11 1/35 + 1/14
</code></pre>
<p>All sub-fractions can be held within the set as long as they themselves are not the same fractions once we are adding them together it is ok for them to total up to the same root.</p>
<p>The goal:</p>
<p>The fractions have to be added in a way to sum up to exactly 1. Any sub-fractions are not allowed to be over 1000 it is explicitly between 2 and 1000 hence the fractions which make up 1/1000 would not be applicable ( 1/1004 + 1/251000 ).</p>
<p>What currently I found to be the most effective:</p>
<p>Find the two lowest multiples which make-up the current fraction that I am looking at so for e.g 1/6 = A = 3 , B = 2. And now we complete the following equation: C = (A+B)*A , D = (A+B)*B. Now C & D are the sub-fractions which add up to my initial fraction</p>
<pre><code> 1/6
/ \
1/15 1/10
</code></pre>
<p>In code:</p>
<pre><code>public static int[] provideFactorsSmallest(int n) {
int k[] = new int[2];
for(int i = 2; i <= n - 1; i++) {
if(n % i == 0) {
k[0] = i;
break;
}
}
for(int i = k[0] + 1; i <= n - 1 && k[0] != 0; i++) {
//System.out.println("I HAVE BEEN ENTERED");
if(k[0] * i == n) {
k[1] = i;
int firstTerm = k[0];
int secondTerm = k[1];
k[0] = (firstTerm + secondTerm) * firstTerm;
k[1] = (firstTerm + secondTerm) * secondTerm;
return k;
}
}
return null;
}
</code></pre>
<p>My question:</p>
<p>What would be the most effective way to pair and group the numbers to achieve possible longest fraction sequence?</p>
| [] | [
{
"body": "<ol>\n<li>In first <code>for</code> loop we can stop when <code>i*i>=n</code>. As we need two different divisors, smallest must be less than <code>Math.sqrt(n)</code></li>\n<li>Second <code>for</code> loop looks like simple integer division.</li>\n</ol>\n\n<p>Whole code is equivalent to this:</p>\n\n<pre><code> private static int[] provideFactorsSmallest_v(int n) {\n for (int firstTerm = 2; firstTerm*firstTerm < n; firstTerm++) {\n if (n % firstTerm == 0) {\n int secondTerm = n / firstTerm;\n return new int[]{\n (firstTerm + secondTerm) * firstTerm,\n (firstTerm + secondTerm) * secondTerm\n };\n }\n }\n return null;\n }\n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:55:29.043",
"Id": "418734",
"Score": "0",
"body": "wow that return new int[] that got me spiced up!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:43:19.463",
"Id": "216446",
"ParentId": "216440",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216446",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:17:51.683",
"Id": "216440",
"Score": "2",
"Tags": [
"java",
"algorithm"
],
"Title": "Pairing unit fractions"
} | 216440 |
<p>I have created a LinkedList in Ruby and was wondering if anyone had any input on efficiencies that I could add or deficiencies I could remove.</p>
<pre><code>module LinkedList
class List
attr_accessor :node
def initialize
self.node = nil
end
def add(node)
if self.node.nil?
self.node = node
else
current_node = self.node
while ! current_node.getPointer.nil? do
current_node = current_node.getPointer
end
current_node.setPointer node
end
end
def get(node)
current_node = self.node
data_match = nil
while !current_node.getPointer.nil? and ! data_match.nil? do
data_match = current_node.getData if node.getData == current_node.getData
current_node = current_node.getPointer
end
return current_node
end
def remove(node)
previous_node = nil
current_node = self.node
next_node = current_node.getPointer
while ! current_node.nil? do
if current_node.getData == node.getData and current_node.getData == self.node.getData
self.node = next_node
return true
end
if current_node.getData == node.getData
previous_node.setPointer next_node
return true
end
previous_node = current_node
current_node = next_node
next_node = current_node.getPointer
end
return false
end
def print
current_node = self.node
while ! current_node.nil? do
pointerData = current_node.getPointer.nil? ? nil : current_node.getPointer.getData
puts "data=#{current_node.getData}, pointer=#{pointerData}"
current_node = current_node.getPointer
end
puts
end
end
class Node
attr_accessor :data
attr_accessor :pointer
def initialize(data = nil, pointer = nil)
self.data = data
self.pointer = pointer
end
def getData
return self.data
end
def getPointer
return self.pointer
end
def setData(data)
self.data = date
end
def setPointer(node)
self.pointer = node
end
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:21:57.530",
"Id": "418753",
"Score": "0",
"body": "Isn't `get` going to return the node _after_ the one with the match?"
}
] | [
{
"body": "<p>Some things that immediately hit me were not about the implementation of the algorithm but the look of the code, it's not idiomatic Ruby, it looks like Java.</p>\n\n<ol>\n<li>Most Rubyists use 2 spaces instead of 4.</li>\n<li>Why all the getters and setters? Setters are quite often a code smell, make sure you really need them (you may do but if you can draw a line under an object's period of mutability - hopefully by the end of initialization - you'll do yourself a favour).</li>\n<li>Camel case is the Java-y bit, so no <code>setPointer</code> and friends. <code>pointerData</code> would be <code>pointer_data</code> in idiomatic Ruby.</li>\n<li>You only need <code>def pointer</code> for the getter and <code>def pointer= val</code> for the setter, or to use the <code>attr_</code>… helpers.</li>\n<li>… and you've used the <code>attr_</code> helpers, so why is there even a <code>setPointer</code> at all? Just use <code>previous_node.pointer = next_node</code> (to give one example) and cut out the middle man. Same goes for all the others, why write a getter/setter to wrap another getter/setter?</li>\n<li><code>self.node = nil</code> in the intializer is unnecessary and if you were going to do it you'd probably use <code>@node = nil</code>.</li>\n<li><code>self.node = node</code>, again, why not access the instance variable directly if you know there's no extra processing going on? <code>@node = node</code> is more idiomatic.</li>\n<li>No need to write <code>return</code> unless you want an early return, everything's an expression so the last expression in a method will become its return value.</li>\n<li><code>pointer_data = current_node.pointer.nil? ? nil : current_node.pointer.data</code> - why use a ternary where an <code>&&</code> or <code>||</code> will do? <code>pointer_data = current_node.pointer && current_node.pointer.data</code> is terser.</li>\n<li>To be even more up to date and terse you could use the new safe-navigation operator, <code>&.</code>, e.g. <code>pointer_data = current_node.pointer&.data</code></li>\n<li>You're returning <code>true</code> and <code>false</code> from methods that are changing state. Return either <code>self</code> or the particular state changed (take a look at what happens when you do <code>[] << 1</code> or <code>[1,2,3].delete 2</code> in a REPL). Methods that return <code>true</code> or <code>false</code> are usually suffixed with <code>?</code> and side effects will probably surprise the consumer.</li>\n</ol>\n\n<p>Once you've cleaned up all of that then the algorithm will be clearer. Some more thoughts on the code that are stylistic but not about Ruby per se.</p>\n\n<p>Firstly, I'd allow the head node to be set in the <code>initialize</code> method - why make a 1 line operation into 2? Secondly, I'd be clearer in my naming, <code>node</code> is a bit abstract, if you're really talking about the position of a node - the head, then call it <code>head</code>:</p>\n\n<pre><code>def initialize head=nil # <- this makes it optional\n @head = head # <- this takes care of setting to nil anyway\n</code></pre>\n\n<p><code>while ! current_node.pointer.nil?</code> is the same as <code>while current_node.pointer</code> but the latter is much easier to understand. No one likes a double negative.</p>\n\n<p><code>def initialize(data = nil, pointer = nil)</code> Optional arguments are nice <em>until</em> you start using them in multiple positions, something like <code>def initialize(data = nil, pointer: nil)</code> is better, or <code>def initialize(data: nil, pointer: nil)</code>, it depends on what you think is most likely to be used / easier on the consumer of the library - think about the interface all the time.</p>\n\n<p>This brings me to my last point - where are the examples for running it? Where are the tests? I've pasted my own version using the advice I've given but does it work? I don't know. Any refactoring can (will!) break things which is why you need examples/tests to fall back on and check your work. It's also where you I'd advise you should start in future. If you don't know how you want the code to be called then you won't do a good job writing it.</p>\n\n<p>I hope that helps.</p>\n\n<pre><code>module LinkedList\n\n class List\n attr_accessor :node\n\n\n def initialize head=nil\n @head = head\n end\n\n\n def add(node)\n if @head.nil?\n @head = node\n else\n current_node = @head\n while current_node.pointer do\n current_node = current_node.pointer\n end\n current_node.pointer = node\n end\n self\n end\n\n\n def get(node)\n current_node = @head\n data_match = nil\n while current_node.pointer and data_match do\n data_match = current_node.data if node.data == current_node.data\n current_node = current_node.pointer\n end\n current_node\n end\n\n\n def remove(node)\n previous_node = nil\n current_node = @head\n next_node = current_node.pointer\n while current_node do\n if current_node.data == node.data and current_node.data == @head.data\n @head = next_node\n return node\n end\n if current_node.data == node.data\n # This looks like it will fail as previous_node is nil afaics\n previous_node.pointer = next_node\n return node\n end\n previous_node = current_node\n current_node = next_node\n next_node = current_node.pointer\n end\n nil\n end\n\n\n def print\n current_node = @head\n while current_node do\n pointer_data = current_node.pointer&.data\n puts \"data=#{current_node.data}, pointer=#{pointer_data}\"\n current_node = current_node.pointer\n end \n puts # puts *what*?\n end\n\n end\n\n class Node\n attr_accessor :data\n attr_accessor :pointer\n\n def initialize(data: nil, pointer: nil)\n @data = data\n @pointer = pointer\n end\n end\n\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:37:36.557",
"Id": "216594",
"ParentId": "216441",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216594",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:24:51.927",
"Id": "216441",
"Score": "4",
"Tags": [
"ruby",
"linked-list"
],
"Title": "LinkedList Implementation"
} | 216441 |
<p>I'm just looking for someone to review this and see if it all works, here you go.
I must mention that once you start this code adventure, all answers to questions must be in single quotes (i.e. <code>'</code>) and lowercase.</p>
<pre><code>import time
items = ['backpack','deagle','stick','mushrooms']
stupid = 0
backpack = 0
deagle = 0
stick = 0
def game():
def house():
print ("You walk inside slowly, nearly crying because you are such a baby")
print ("You look around the building, there is a selection of objects on the ground, a stick, a backpack, and a deagle with 100 rounds next to it. oh and lest we not forget, some mushrooms, picking them up will make you eat them immediately.")
print ("What do you want to do now?")
items1()
def evendeeperhouse():
print ("yeet")
def deeperhouse():
global stupid
global deagle
global stick
print ("You see a Hole In The Wall near the back of the house, do you wish to go inside?[y/n]")
print ("Should you go through the Hole In The Wall, or hang out with the unknown figure creeping up behind you?")
ch5 = str(input("Do you enter? [(enter)y/(pass)n]"))
if ch5 in ['y']:
print ("*LOUD SPRINTING NOISES* You run through the hole as fast as possible. you can hear the other being clanging a metal bar as he attempts to follow you. What do you do.")
if stupid > 4:
print ("Your level of Stupid is",stupid,"so you manage to hit your head on your way through the human sized hole, congrats, you are now even more stupid. Sadly, you did escape deeper into the house. Stupid +4")
stupid += 4
evendeeperhouse()
else:
print ("you now have a small selection of choices")
ch6 = str(input("Wanna use an item? or nah? [stick",stick,",deagle",deagle,"/(keep running)n]"))
if ch6 in ['deagle']:
print ("You turn around and fire 72 rounds into the being, as you investigate the rags remaining, you realize that you recognize the face, then realize that this guy isnt holding a metal bar, and hes wearing a uniform, oh man, you killed a cop, nice going, now they will just leave you here to die, but perhaps his vehicle is still here, you move on.")
time.sleep(3)
if ch6 in ['stick']:
print ("you turn around and stab at the being, shooing them off barely as you head into the deeper house")
print ("The tunnel collapses behind you, hopefully you wont see that creature again.")
else:
print ("You decide to turn away from the hole and end up making conversation with this creature, you both wind up finding a game of chess, playing, talking about eachother and whatnot, and you learn that they just wanted someone to play a game with, wow, fascinating, its a shame you beat a phsychotic murderer at chess, you shouldve let him win.")
time.sleep(.5)
print ("Achievement Get!")
time.sleep(.5)
print ("Metal Bar Lodged Through Spine")
time.sleep(.5)
print ("Shouldve let him win... *sigh*")
time.sleep(2)
game()
def foresttrail():
print("You leave the house with nothing but a backpack, congrats, you will likely die out here. you can see two more buildings ahead, they are in far worse shape, there is a flashlight on the ground as well, what do you do?")
def items1():
global items
global deagle
global backpack
global stick
global stupid
for x in range(4):
ch4 = str(input("Type what you would like to pick up if anything, or say no to move on like a brave little boy. [Deagle/Stick/Backpack/Mushrooms/N]"))
if "backpack" in ch4:
backpack +=1
print ("alright, you got a thug bag now, what would you like to steal?")
print ch4
print backpack
if "deagle" in ch4:
deagle+=1
if stupid > 0:
print ('alright, you got a Loaded Illegal Firearm now, youve got a stupid level of', stupid, 'you sure you know how to use this?')
else:
print ("Alright you got a gun, congrats bud, dont get yourself killed.")
print ch4
print deagle
if "stick" in ch4:
stick +=1
print ("alright, you got a stick now, in your case, this is better than the gun.")
print ch4
print stick
if "mushrooms" in ch4:
stupid +=3
print ("alright, you ate the shrooms, now you are 3 times more stupid, congrats... Stupid +3")
print ch4
print stupid
if ch4 not in items:
stupid +=1
print ("that's not a valid choice. Stupid +1")
if 'n'in ch4:
stupid + 3
print ("Somehow you manage to drop anything you just picked up and decide to leave.")
stick == 0
deagle == 0
backpack == 0
print ("Narrator-No? NO?!?! you just REFUSE?! *Thunder Cracks as a large storm has appeared outside* *The voice is Grim* You've made a mistake, Move Along.")
print ("Probably gonna die tbh")
foresttrail()
deeperhouse()
# game function
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("Welcome to the Text Based Adventure!")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
deagle == 0
backpack == 0
stick == 0
stupid == 0
time.sleep(1.5)
print ("You are walking down a forest trail among a dense stand of trees. Ahead you see a clearing. As you enter the clearing, you see the trail continue off to the south. In the clearing is a little hut about 6 feet tall.")
ch1 = str(input("Do you head down the trail(y)? I think you should go to the trail [y/y]: "))
if ch1 in ['y', 'Y']:
print("Sorry bud, the trail is FILLED with wolves, you are dead.")
game()
# Trail NOT Followed
else:
print("You decide to go look at the house first. How dare you defy me tiny being, you will pay later on.")
print ("Should you knock on the door, or pass by?")
ch2 = str(input("Do you knock? [(knock)y/(pass)n]"))
if ch2 in ['y', 'Y']:
print ("BangBangBang.” You knock on the door, but even if someone was home, your weak arms didnt make enough noise for them to hear you. The door isn’t locked. Should you open it and commit a crime?")
else:
print ("You walk away from the house slowly because you are too scared, lucky for you, a car happens to pull up, oh no! they cant stop because of the mud, they slam into you and you die on impact, twas a shame.")
time.sleep(1)
game()
ch3 = str(input("Do you enter? [y/n]"))
if ch3 in ['y', 'Y']:
house()
elif ch3 in ['n','N']:
print ("You walk away from the house slowly because you are too scared, lucky for you, a car happens to pull up, oh no! they cant stop because of the mud, they slam into you and you die on impact, twas a shame it had to end this way, well, for you, im laughing.")
game()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:40:06.163",
"Id": "418745",
"Score": "3",
"body": "Is this supposed to be used with Python 2 or Python 3? If it's really Python 3 as the tag suggests, the code is not working correctly, since there are a few spots where you're missing the `(...)` behind `print`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:37:43.510",
"Id": "418774",
"Score": "0",
"body": "Leaving items aside, a text adventure is basically a directed graph: Each room is a node and you can move from one room to another depending on the edges. You could try to separate the game logic (moving between rooms) from the game data (room content, possible answers, connections between rooms). This way, you could add new rooms or change the texts just by modifying some data files without touching the python code. Once you have done this, you could try to implement how the items and the other global variables of your example are handled in a data-driven way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:01:21.963",
"Id": "418781",
"Score": "0",
"body": "If your goal is to make a quality text adventure, rather than to learn python, you might want to look into one of the languages specifically designed for them like Inform, TADS, or Hugo. They or their standard libraries handle a lot of common difficult pieces like parsing typed commands, modeling objects and verbs, etc."
}
] | [
{
"body": "<p>Welcome to CodeReview. Your program is a fun start to programming, and Python is a great way to learn. For the following topics, I'm going to trust your ability to google, but if you can't find the appropriate documentation leave a comment and I'll add some links.</p>\n\n<h2>Avoid globals</h2>\n\n<p>Sometimes globals can be useful, but more often they hinder a developer's ability to maintain and debug code. It's a better idea to group related variables together into a class. This applies to the following variables:</p>\n\n<pre><code>items = ['backpack','deagle','stick','mushrooms']\nstupid = 0\nbackpack = 0\ndeagle = 0\nstick = 0\n</code></pre>\n\n<h2>Avoid stringly-typed objects</h2>\n\n<p>These things:</p>\n\n<pre><code>items = ['backpack','deagle','stick','mushrooms']\n</code></pre>\n\n<p>are strings. But in this case, it's not very good practice to handle them as strings until they need to be presented to the user. In other words, in this statement:</p>\n\n<pre><code>if \"mushrooms\" in ch4:\n</code></pre>\n\n<p>What if you misspelled 'mushrooms'? You wouldn't know until halfway through a program run; in other words, string-typing hinders <em>static analysis</em>, among other problems. One solution to this is to have an enum: a kind of object that can take only one of a set of mutually exclusive values. In other words, an item can be only a backpack, or a deagle, or a stick, or a mushroom. Python IDEs are better able to perform static analysis on this, and programmers make fewer errors when following this strategy.</p>\n\n<h2>Indenting</h2>\n\n<p>For legibility, you should ensure that each additional level of indentation only introduces 3-4 characters - pick one and stick with it. This:</p>\n\n<pre><code> def items1():\n global items\n</code></pre>\n\n<p>is too far in for the comfort of most developers.</p>\n\n<h2>These aren't assignments</h2>\n\n<pre><code> deagle == 0\n backpack == 0\n stick == 0\n stupid == 0\n</code></pre>\n\n<p>They're comparisons. Assignments need only one <code>=</code>.</p>\n\n<h2>Input comparison</h2>\n\n<p>This:</p>\n\n<pre><code>if ch3 in ['y', 'Y']:\n</code></pre>\n\n<p>is more easily done by first converting the character to lowercase, and then comparing it to a single character; in other words:</p>\n\n<pre><code>if ch3.lower() == 'y':\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:59:27.740",
"Id": "418758",
"Score": "1",
"body": "@Alex thanks; language cross talk."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:41:01.577",
"Id": "216451",
"ParentId": "216442",
"Score": "7"
}
},
{
"body": "<p>There are a few points I would like to add ontop of the <a href=\"https://codereview.stackexchange.com/a/216451/92478\">feedback already given</a> by Reinderien.</p>\n\n<h2>Remove nested functions</h2>\n\n<p>There is no good reason to define <code>house()</code>, <code>deeperhouse()</code>, etc. inside of <code>game()</code>. If your plan was to hide them from the user in this ways, you have probably chosen the wrong language. If you intend to indicate that these are not to be used directly, prefix their name with a leading underscore <code>_house()</code>. This is a <a href=\"https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow noreferrer\">common convention</a> to notify others that these functions are not intended to be used by them and are subject to change/removal/... without further notice.</p>\n\n<p>Also think about how you use these functions. Basically, your game's \"flow\" is encoded in them by calling deeper and deeper into other functions without ever returning.</p>\n\n<h2>Break lines to improve readability</h2>\n\n<p>Your text message come in super-long lines of text. Most text editors support automatic line breaking or soft wrap to cram those lines to the available screen width, but some don't (like the code preview here) or are deliberately configured not to do so. So be nice and break your lines if they get to long.<br/>\nPython's official style guide <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">recommends 79/80 characters</a> as maximum line length, although most modern IDEs and their style tools let you get away with about 100 (without manual tweaking) before getting upset.<br/>\nPython allows you to do this within the parenthesis of a function call without further line continuation markers.</p>\n\n<p>Applying this to <code>house()</code>, your code could look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def house():\n print(\"You walk inside slowly, nearly crying because you are such a baby\")\n print(\"You look around the building, there is a selection of objects on the ground, \"\n \"a stick, a backpack, and a deagle with 100 rounds next to it. oh and lest we not \"\n \"forget, some mushrooms, picking them up will make you eat them immediately.\")\n print(\"What do you want to do now?\")\n items1()\n</code></pre>\n\n<p>For more information on this refer to the previous link.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:46:34.887",
"Id": "418755",
"Score": "0",
"body": "I'm rather startled that you're just telling OP to unindent the nested functions, when they are *clearly* using function calls as a substitute for `goto`. Nothing ever returns!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:02:15.003",
"Id": "418759",
"Score": "0",
"body": "@Kevin: Yep, that's absolutely true and I'm fully aware of this. I added a note on that topic, but without further explanation towards a solution. Feel free to give the OP feedback yourself, and I will be happy to upvote your answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:48:44.337",
"Id": "418762",
"Score": "0",
"body": "I'd also offer that either a single print with a docstring, or a single print with implicit string concatenation - `print(\"foo\" \"bar\")` - are more appropriate than multiple prints."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:21:51.493",
"Id": "216452",
"ParentId": "216442",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:53:26.363",
"Id": "216442",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"game",
"adventure-game"
],
"Title": "Text adventure game code"
} | 216442 |
<p>I'm a first year computer engineering student and would appreciate feedback on some code.</p>
<p>I've created a linked-list with an iterator to be able to range for loops like: <code>for (int i : list) {}</code> where list is <code>Linked_List<int> list;</code>.</p>
<p>Flaws I already know of but choose to ignore because of how the teacher in class implements stuff:</p>
<ul>
<li><em>Use of raw pointers</em></li>
</ul>
<p><br>
<strong>Linked_List.h</strong></p>
<pre><code>namespace Util
{
template<typename T>
class Linked_List
{
public:
struct Iterator;
private:
struct Node;
public:
Linked_List();
~Linked_List() noexcept(false);
Linked_List(const Linked_List&) = delete;
Linked_List(Linked_List&&) = delete;
Linked_List& operator=(const Linked_List&) = delete;
Linked_List& operator=(Linked_List&&) = delete;
// Modifiers
void push_back(T);
void push_front(T);
void pop_back();
void pop_front();
// Capacity
bool empty() const;
unsigned int size() const;
// Element access
T back() const;
T front() const;
Iterator begin() const;
Iterator end() const;
// TODO:
//Iterator insert(const Iterator, T);
//Iterator erase(const Iterator);
private:
Node* _head;
Node* _tail;
unsigned int _size;
};
};
</code></pre>
<p><strong>Linked_List.cpp</strong></p>
<pre><code>#include "pch.h"
#include "Linked_List.h"
namespace Util
{
template<typename T>
struct Linked_List<T>::Node
{
Node() : prev(nullptr), next(nullptr) {}
Node(T t) : value(t), prev(nullptr), next(nullptr) {}
Node* prev;
Node* next;
T value;
};
template<typename T>
struct Linked_List<T>::Iterator
{
Iterator() : _current(nullptr)
{
//
}
T& operator*() const
{
return _current->value;
}
Iterator& operator++()
{
_current = _current->next;
return *this;
}
bool operator!=(const Iterator& rhs)
{
return _current != rhs._current;
}
private:
friend class Linked_List<T>;
Iterator(Node* n) : _current(n) {}
Node* _current;
};
template<typename T>
Linked_List<T>::Linked_List() : _size(0)
{
_head = new Node();
_tail = new Node();
_head->next = _tail;
_tail->prev = _head;
}
template<typename T>
Linked_List<T>::~Linked_List() noexcept(false)
{
while (!empty())
{
pop_back();
}
delete head;
delete tail;
}
template<typename T>
void Linked_List<T>::push_back(T t)
{
Node* n = new Node(t);
n->prev = _tail->prev;
n->next = _tail;
_tail->prev->next = n;
_tail->prev = n;
++_size;
}
template<typename T>
void Linked_List<T>::push_front(T t)
{
Node* n = new Node(t);
n->next = _head->next;
n->prev = _head;
_head->next->prev = n;
_head->next = n;
++_size;
}
template<typename T>
void Linked_List<T>::pop_back()
{
if (empty()) throw Error("pop_back(): on empty list");
Node* n = _tail->prev;
_tail->prev->prev->next = _tail;
_tail->prev = _tail->prev->prev;
--_size;
delete n;
}
template<typename T>
void Linked_List<T>::pop_front()
{
if (empty()) throw Error("pop_front(): on empty list");
Node* n = _head->next;
_head->next->next->prev = _head;
_head->next = _head->next->next;
--_size;
delete n;
}
template<typename T>
bool Linked_List<T>::empty() const
{
//return (_head->next == _tail) && (_tail->prev == _head);
return size() == 0;
}
template<typename T>
T Linked_List<T>::back() const
{
if (empty()) throw Error("back(): on empty list");
return _tail->prev->value;
}
template<typename T>
T Linked_List<T>::front() const
{
if (empty()) throw Error("front(): on empty list");
return _head->next->value;
}
template<typename T>
unsigned int Linked_List<T>::size() const
{
return _size;
}
template<typename T>
typename Linked_List<T>::Iterator Linked_List<T>::begin() const
{
return Iterator(_head->next);
}
template<typename T>
typename Linked_List<T>::Iterator Linked_List<T>::end() const
{
return Iterator(_tail);
}
};
</code></pre>
<p><br>
I haven't yet figured out how to implement:</p>
<ul>
<li><code>Iterator insert(const Iterator, T);</code></li>
<li><code>Iterator erase(const Iterator);</code></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:51:19.057",
"Id": "418752",
"Score": "1",
"body": "I'm guessing that you haven't started your `const_iterator` yet? It can be helpful to do them together."
}
] | [
{
"body": "<h2>Comment</h2>\n\n<blockquote>\n <p>Flaws I already know of but choose to ignore because of how the teacher in class implements stuff:`</p>\n \n <ul>\n <li>Use of raw pointers</li>\n </ul>\n</blockquote>\n\n<p>Not sure that is a flaw. Creating a container I would expect to see RAW pointers.</p>\n\n<h2>Overview</h2>\n\n<p>There is definitely a bug in your constructor where you build two <code>Sentinels</code> it should only be one. Otherwise your iterators for an empty list will iterate once.</p>\n\n<p>Additionally your <code>Node</code> always contains a value (even for the <code>Sentinel</code>). This means your type <code>T</code> (the value type) must be default constructible (not all types are so you class is limited to objects of this type).</p>\n\n<p>There are some requirements for Iterators that you don't implement. The iterator type is supposed to have a couple of internal types. The standard algorithms use these internal types (or they use <code>std::iterator_traits<Your Interator>::UsefulTypeInfo</code>) which default to point at your type object. Since your <code>Iterator</code> does not implement these types it may not be standard compliant and fail in some algorithms.</p>\n\n<p>Talking of missing type information your container is also missing some type information.</p>\n\n<p>Also you provide the pre-increment on your iterator but your don't provide the post-increment function. So you are missing at least one function. There is at least one more function you are missing (but I assume this is becausew your teacher has not got that far so I will leave it up to him).</p>\n\n<p>There are lots of parts to this class that look like the teacher will get you to fill in at a later date. So there is still a lot of work to do to complete this task.</p>\n\n<h2>Code Review</h2>\n\n<p>That's a bit wierd.</p>\n\n<pre><code> ~Linked_List() noexcept(false);\n</code></pre>\n\n<p>This makes the class act like a C++03 class. Exceptions are allowed to propagate out of the destructor. Not usual but it's OK. I assume this will be modified in future class.</p>\n\n<hr>\n\n<p>I assume these are deleted to make the first version easy to write.</p>\n\n<pre><code> Linked_List(const Linked_List&) = delete;\n Linked_List(Linked_List&&) = delete;\n Linked_List& operator=(const Linked_List&) = delete;\n Linked_List& operator=(Linked_List&&) = delete;\n</code></pre>\n\n<p>Probably come back in a later class and implement these.</p>\n\n<hr>\n\n<p>This is a bit strange passing by value.</p>\n\n<pre><code> void push_back(T);\n void push_front(T);\n</code></pre>\n\n<p>I would expect you to pass by reference to avoid a copy.</p>\n\n<hr>\n\n<p>Personally I hate the unsigned int as a size value. But it's very common and what was adopted by the standard container (they regretted that).</p>\n\n<pre><code> unsigned int size() const;\n</code></pre>\n\n<p>So I would keep it. But if you look up the history of why the standard committee choose <code>unsigned</code> then regretted it its an interesting story.</p>\n\n<p>But saying that. I would use <code>std::size_t</code> as that conveys intentions more.</p>\n\n<hr>\n\n<p>Return by value? Just like the insert by value you are potentially creating an unneeded copy. </p>\n\n<pre><code> T back() const;\n T front() const;\n</code></pre>\n\n<p>I am now assuming this is because you have not been tought about references and thus the teacher will expand on this in later classes and show you how to provide both normal reference and const reference versions of these methods.</p>\n\n<hr>\n\n<p>Sure this is fine as a starting point.</p>\n\n<pre><code> Iterator begin() const;\n Iterator end() const;\n</code></pre>\n\n<p>But you will see that the standard containers have a lot more of these. Also since these methods are const should they not be returning a const version of the iterator. Maybe that is for a later class.</p>\n\n<hr>\n\n<p>OK. A very basic <code>Node</code>.</p>\n\n<pre><code> template<typename T>\n struct Linked_List<T>::Node\n {\n Node() : prev(nullptr), next(nullptr) {}\n Node(T t) : value(t), prev(nullptr), next(nullptr) {}\n Node* prev;\n Node* next;\n T value;\n };\n</code></pre>\n\n<p>But the lack of interesting constructors means you will have to do some manual work setting up the chain when this could have been done in the constructor here. I'll point it out when we get to creating a node.</p>\n\n<hr>\n\n<p>OK so a very basic Iterator.</p>\n\n<pre><code> template<typename T>\n struct Linked_List<T>::Iterator\n {\n // Nothing interesting here.\n };\n</code></pre>\n\n<hr>\n\n<p>You create a <code>Sentinel</code> for both both the beginning and end. That seems a bit strange. I would expect to only see one <code>Sentinel</code> value at the end.</p>\n\n<pre><code> template<typename T>\n Linked_List<T>::Linked_List() : _size(0)\n {\n _head = new Node();\n _tail = new Node();\n _head->next = _tail;\n _tail->prev = _head;\n }\n</code></pre>\n\n<p>I would have expected this:</p>\n\n<pre><code> template<typename T>\n Linked_List<T>::Linked_List()\n : _head(new Node)\n , _tail(_head)\n , _size(0)\n {}\n</code></pre>\n\n<p>This way if the list is empty both head and tail point at the same node. Thus if you generate iterators for head and tail they will both generate the <code>end</code> iterator (which will compare equal).</p>\n\n<p>Additionally there is a bug in your version.</p>\n\n<pre><code> _head = new Node(); // Assume this works\n _tail = new Node(); // Assume this fails and throws.\n // Because your constructor has not finished\n // when the exception is thrown this object\n // will not be fully constructed and therefore\n // will not have its destructor called. This \n // means you will leak the value pointed at by\n // _head\n</code></pre>\n\n<hr>\n\n<p>Your destructor should work. But this is rather heavy handed. You are inside the class and thus are expected to understand the implementation details. You could write this much more simply and efficiently (as pop_back() has to make sure the chain stays valid after each call). </p>\n\n<pre><code> template<typename T>\n Linked_List<T>::~Linked_List() noexcept(false)\n {\n while (!empty())\n {\n pop_back();\n }\n delete head;\n delete tail;\n }\n</code></pre>\n\n<p>I would simply write like this:</p>\n\n<pre><code> Linked_List<T>::~Linked_List()\n {\n Node* current = _head;\n while(current != nullptr) {\n Node* old = current;\n current = current->next;\n delete old;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>You know I mentioned above in the <code>Node</code> description that the constructor could be made more useful. This is where it would work nicely.</p>\n\n<pre><code> Node(T value, Node* nextNode)\n : prev(nextNode->prev)\n , next(nextNode)\n , value(value)\n {\n if (prev) {\n prev->next = this;\n }\n next->prev = this; // There is always a next.\n }\n template<typename T>\n void Linked_List<T>::push_back(T t)\n {\n Node* n = new Node(t, tail); // insert before tail.\n tail = n->next;\n }\n\n template<typename T>\n void Linked_List<T>::push_front(T t)\n {\n Node* n = new Node(t, head); // insert before head\n head = n;\n }\n</code></pre>\n\n<p>Personally I think that is much easier to read.</p>\n\n<hr>\n\n<p>Personally I would not check if it is empty. It is the responsibility of the caller to check before calling <code>X_pop()</code>. If you provide the check and it is not needed you are forcing the user to use sub-optimal code. See example below:</p>\n\n<pre><code> template<typename T>\n void Linked_List<T>::pop_back()\n {\n if (empty()) throw Error(\"pop_back(): on empty list\");\n Node* n = _tail->prev;\n _tail->prev->prev->next = _tail;\n _tail->prev = _tail->prev->prev;\n --_size;\n delete n;\n }\n\n template<typename T>\n void Linked_List<T>::pop_front()\n {\n if (empty()) throw Error(\"pop_front(): on empty list\");\n Node* n = _head->next;\n _head->next->next->prev = _head;\n _head->next = _head->next->next;\n --_size;\n delete n;\n }\n</code></pre>\n\n<p>Here is a very common use case:</p>\n\n<pre><code> while(list.empty()) {\n list.pop_back(); // This is guaranteed to only be called if\n // if the list is not empty. So the check\n // inside `pop_back()` is redudant and therefore\n // a waste of cycles.\n }\n</code></pre>\n\n<p>One of the big philosophies of C++ is to never charge people for something they don't need. Now there is also an argument to having the check. <strong>BUT</strong> this can be provided by having an explicit checked <code>pop_back()</code> version: <code>checked_pop_back()</code>.</p>\n\n<pre><code> list.checked_pop_back(); // Do I need to make a check before this call?\n</code></pre>\n\n<hr>\n\n<p>Simply go for checking the size(). If your object is in a consistent state then you can simply check the variable without having to pay the expense of the functions call.</p>\n\n<pre><code> template<typename T>\n bool Linked_List<T>::empty() const\n {\n //return (_head->next == _tail) && (_tail->prev == _head);\n return size() == 0;\n }\n</code></pre>\n\n<p>I would just write:</p>\n\n<pre><code> bool Linked_List<T>::empty() const {return _size == 0;}\n</code></pre>\n\n<hr>\n\n<p>Again with the un-needed checks.</p>\n\n<pre><code> template<typename T>\n T Linked_List<T>::back() const\n {\n if (empty()) throw Error(\"back(): on empty list\");\n return _tail->prev->value;\n }\n\n template<typename T>\n T Linked_List<T>::front() const\n {\n if (empty()) throw Error(\"front(): on empty list\");\n return _head->next->value;\n }\n</code></pre>\n\n<hr>\n\n<p>These look fine:</p>\n\n<pre><code> template<typename T>\n typename Linked_List<T>::Iterator Linked_List<T>::begin() const\n {\n // Though with the fix I suggested above this changes.\n return Iterator(_head->next);\n\n // If you only have the tail `Sentinel` this becomes\n return Iterator(_head);\n }\n\n template<typename T>\n typename Linked_List<T>::Iterator Linked_List<T>::end() const\n {\n return Iterator(_tail);\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I haven't yet figured out how to implement:</p>\n \n <p>Iterator insert(const Iterator, T);\n Iterator erase(const Iterator);</p>\n</blockquote>\n\n<p>If you have to <code>insert</code> before the iterator? Then you can simply implement like I did above:</p>\n\n<pre><code>Iterator insert(const Iterator iterator, T value) {\n Node* n = new Node(value, iterator->_current);\n return Iterator(n);\n}\n</code></pre>\n\n<p>Lets assume erase returns the iterator to the next element.</p>\n\n<pre><code>Iterator erase(const Iterator iterator)\n Node* current = iterator->_current;\n if (current == _tail) // can't delete the tail\n return iterator;\n }\n\n // otherwise unlink from previous item.\n if (current->prev == nullptr) {\n head = current->next;\n }\n else {\n current->prev->net = current->next;\n }\n // Next unlink from the next item.\n current->next->prev=current->prev;\n\n // Get the next item so we can return it.\n Node* result = current->next;\n\n // Delete the old value.\n delete current;\n\n // return the new result.\n return Iterator(result);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T12:33:14.923",
"Id": "418789",
"Score": "0",
"body": "`push_back(T)` by value *would* make sense if it contained `new Node(std::move(t))` and if `Node(T)` constructor initialised using `: value(std::move(t))`. When a function needs to take a copy, it can help to pass by value (can save unnecessary copying of rvalues)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T01:03:46.370",
"Id": "216456",
"ParentId": "216444",
"Score": "6"
}
},
{
"body": "<p>Your <code>Linked_List</code> and your <code>Iterator</code> both should have a serial number to allow for fast failure of iterating over a list that is modified by something other than that iterator. </p>\n\n<p>The Problem:</p>\n\n<p>When you implement <code>Iterator::remove</code>, it has to hold on to a pointer just before (or just after or both) the node that was just removed. If that node is then removed by some means (direct call to <code>Linked_List::pop_*()</code> or removal by another iteration), the saved pointer will end up pointing to deallocated memory.</p>\n\n<p>Solution:</p>\n\n<p>Each change to the <code>Linked_List</code> should change the serial number (<code>+= 1</code> works). Each time an <code>Iterator</code> is created, it should take a snapshot of the serial number. Before performing any operation with the <code>Iterator</code>, it should compare its copy of the serial number to the actual <code>Linked_List</code> serial number and raise an exception if they are different. When an <code>Iterator</code> is used to modify the <code>Linked_List</code>, the serial number will change and that <code>Iterator</code> should capture this new value. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T12:28:20.847",
"Id": "418788",
"Score": "0",
"body": "Interesting idea, but contrary to STL philosophy (programmers are expected to know they have invalidated iterators, and simply not use them). Explicitly checks for invalidation could be a useful debugging feature, but you might not want the overhead of space and time in your production builds."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T06:11:50.723",
"Id": "216459",
"ParentId": "216444",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216456",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T20:13:08.990",
"Id": "216444",
"Score": "5",
"Tags": [
"c++",
"beginner",
"linked-list",
"homework",
"iterator"
],
"Title": "C++ linked list iterator implementation"
} | 216444 |
<p>I've already made all the changes suggested here. Here is the link for round 2: <a href="https://codereview.stackexchange.com/questions/216503/linked-list-implementation-along-with-unit-test-round-2">Linked list implementation along with unit test [Round 2]</a></p>
<p>I want to see how other people think of my code, so here it goes. This is my first time writing a unit test. I'm wondering if there needs to be more tests for the LinkedList class and also if I'm writing them correctly.</p>
<p>I've made the Node class public so I can use it for a binary tree implementation later.</p>
<pre><code>namespace DataStructuresAndAlgorithms.DataStructures
{
public class Node<T>
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node<T> Previous { get; set; }
public Node() { }
public Node(T t)
{
Data = t;
}
}
}
</code></pre>
<p>Implementation</p>
<pre><code>using System;
using System.Collections.Generic;
namespace DataStructuresAndAlgorithms.DataStructures
{
public class LinkedList<T>
{
public Node<T> Head { get; private set; }
public Node<T> Tail { get; private set; }
public LinkedList(Node<T> node)
{
Head = node;
Tail = node;
}
public void AddToFirst(Node<T> toAdd)
{
toAdd.Next = Head;
Head = toAdd;
}
public void AddToLast(Node<T> toAdd)
{
Tail.Next = toAdd;
Tail = toAdd;
}
public void RemoveFirst()
{
Head = Head.Next;
}
public void RemoveLast()
{
var pointer = Head;
while (pointer.Next != Tail)
{
pointer = pointer.Next;
}
// pointer is now before Tail
Tail = pointer;
Tail.Next = null;
}
public IEnumerator<Node<T>> GetEnumerator()
{
var pointer = Head;
while (pointer != null)
{
yield return pointer;
pointer = pointer.Next;
}
}
}
}
</code></pre>
<p>Unit Test</p>
<pre><code>using System;
using Xunit;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.DataStructures.Tests
{
public class LinkedListTest
{
[Fact]
public void AddToFirst_Node_Should_Become_Head()
{
// Arrange
var myLinkedList = new LinkedList<int>(new Node<int>(45));
// Act
var nodeToAdd = new Node<int>(67);
myLinkedList.AddToFirst(nodeToAdd);
// Assert
var theNode = GetNodeFromList<int>(myLinkedList, nodeToAdd);
Assert.Equal(nodeToAdd, theNode);
Assert.Equal(45, theNode.Next.Data);
}
[Fact]
public void AddToLast_Node_Should_Become_Tail()
{
// Arrange
var myLinkedList = new LinkedList<int>(new Node<int>(35));
// Act
var nodeToAdd = new Node<int>(14);
myLinkedList.AddToLast(nodeToAdd);
// Assert
var theNode = GetNodeFromList<int>(myLinkedList, nodeToAdd);
Assert.Equal(nodeToAdd, theNode);
}
[Fact]
public void RemoveFirst_Next_Node_Should_Be_Head()
{
// Arrange
var myLinkedList = new LinkedList<int>(new Node<int>(777));
var node1 = new Node<int>(1);
myLinkedList.AddToLast(node1);
var node2 = new Node<int>(2);
myLinkedList.AddToLast(node2);
var node3 = new Node<int>(3);
myLinkedList.AddToLast(node3);
// Act
myLinkedList.RemoveFirst();
// Assert
var theNode = GetNodeFromList<int>(myLinkedList, node1);
Assert.Equal(node1, myLinkedList.Head);
}
[Fact]
public void RemoveLast_Next_Node_Should_Be_Tail()
{
// Arrange
var myLinkedList = new LinkedList<int>(new Node<int>(777));
var node1 = new Node<int>(1);
myLinkedList.AddToLast(node1);
var node2 = new Node<int>(2);
myLinkedList.AddToLast(node2);
var node3 = new Node<int>(3);
myLinkedList.AddToLast(node3);
// Act
myLinkedList.RemoveLast();
// Assert
var theNode = GetNodeFromList<int>(myLinkedList, node2);
Assert.Equal(node2, myLinkedList.Tail);
}
public static Node<T> GetNodeFromList<T>(LinkedList<T> someLinkedList, Node<T> someNode) where T : struct
{
using (var itr = someLinkedList.GetEnumerator())
{
while (itr.Current != someNode)
{
itr.MoveNext();
}
return itr.Current;
}
}
}
}
</code></pre>
<p>Presentation</p>
<pre><code>using System;
using System.Collections;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.Presentation.Console
{
class Program
{
static void Main(string[] args)
{
RunNode();
System.Console.WriteLine();
RunLinkedList();
}
static void RunNode()
{
System.Console.WriteLine("Running the Node class");
System.Console.WriteLine("----------------------");
var myNode = new Node<int>(32);
System.Console.WriteLine(myNode.Data);
}
static void RunLinkedList()
{
System.Console.WriteLine("Running the LinkedList class");
System.Console.WriteLine("----------------------------");
var myLinkedList = new LinkedList<int>(new Node<int>(99));
myLinkedList.AddToFirst(new Node<int>(56));
myLinkedList.AddToFirst(new Node<int>(23));
myLinkedList.AddToFirst(new Node<int>(33));
myLinkedList.AddToLast(new Node<int>(8888));
myLinkedList.RemoveLast();
myLinkedList.RemoveFirst();
System.Console.WriteLine("HEAD = " + myLinkedList.Head.Data);
System.Console.WriteLine("TAIL = " + myLinkedList.Tail.Data);
using (var linkedListEnumerator = myLinkedList.GetEnumerator())
{
while (linkedListEnumerator.MoveNext())
{
System.Console.WriteLine(linkedListEnumerator.Current.Data);
}
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I've made the Node class public so I can use it for a binary tree implementation later</p>\n</blockquote>\n\n<p>I don't think you can use this <code>Node</code> type as a node in a binary tree, because nodes in binary trees typically has references to other nodes like <code>Parent</code>, <code>Left</code> and <code>Right</code>. So IMO keep this <code>Node</code> class as a dedicated node type for this linked list:</p>\n\n<pre><code> public class LinkedList<T>\n {\n class Node\n {\n public T Data { get; }\n public Node Next { get; set; }\n public Node Previous { get; set; }\n\n public Node(T data)\n {\n Data = data;\n }\n }\n</code></pre>\n\n<p>In this way you can skip the type parameter on the <code>Node</code> class. As shown above I've also made the <code>Node</code> class immutable for the <code>Data</code> property and hence no default constructor. It's easier to maintain, if you know that there is a one-to-one relationship between a data object and a <code>Node</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public Node<T> Head { get; private set; }\npublic Node<T> Tail { get; private set; }\n</code></pre>\n</blockquote>\n\n<p>It's fine to have a public <code>Head</code> and <code>Tail</code> property, but they should be of type <code>T</code> and not <code>Node</code>. The client should be agnostic about the inner implementation of your list and only \"communicate\" objects of type <code>T</code> with it:</p>\n\n<pre><code>public T Head => _headNode.Data; // TODO check for null\npublic T Tail => _tailNode.Data; // TODO check for null\n</code></pre>\n\n<p>This will require that you have private nodes for head and tail as illustrated above.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public LinkedList(Node<T> node)\n{\n Head = node;\n Tail = node;\n}\n</code></pre>\n</blockquote>\n\n<p>Having a one and only constructor that takes a node (or item) is not a good idea, because you often want to instantiate an empty list and provide it as argument to a method or something like that. So your list should have a default constructor with no arguments:</p>\n\n<pre><code>public LinkedList()\n{\n}\n</code></pre>\n\n<p>You could also consider to have a constructor with a vector of items:</p>\n\n<pre><code>public LinkedList(IEnumerable<T> items)\n{\n foreach (var item in items)\n {\n AddTail(item);\n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public void AddToFirst(Node toAdd) {...}\n public void AddToLast(Node toAdd) {...}\n</code></pre>\n</blockquote>\n\n<p>You would typically call these methods <code>AddHead</code> and <code>AddTail</code>:</p>\n\n<pre><code>public void AddHead(T item) {...}\npublic void AddTail(T item) {...}\n</code></pre>\n\n<p>as you would call <code>RemoveFirst()</code> <code>RemoveHead()</code>...</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void AddToFirst(Node<T> toAdd)\n{\n toAdd.Next = Head;\n Head = toAdd;\n}\n\npublic void AddToLast(Node<T> toAdd)\n{\n Tail.Next = toAdd; //OBS: This will fail if Tail is null!\n Tail = toAdd;\n}\n</code></pre>\n</blockquote>\n\n<p>Your <code>Node<T></code> class has a <code>Previous</code> property, why don't you use that (doubly linked list)?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void RemoveFirst()\n{\n Head = Head.Next;\n}\n</code></pre>\n</blockquote>\n\n<p>This will fail, if <code>Head</code> is <code>null</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void RemoveLast()\n{\n var pointer = Head;\n while (pointer.Next != Tail)\n {\n pointer = pointer.Next;\n }\n // pointer is now before Tail\n Tail = pointer;\n Tail.Next = null;\n}\n</code></pre>\n</blockquote>\n\n<p>Why iterate through the entire list, when you have a reference to the last node in <code>Tail</code>?:</p>\n\n<pre><code>public void RemoveLast()\n{\n if (Tail != null)\n {\n Tail = Tail.Previous;\n Tail.Next = null;\n }\n}\n</code></pre>\n\n<p>You could consider to return the <code>Data</code> value from the removed nodes.</p>\n\n<pre><code>public T RemoveLast() {...}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public IEnumerator<Node<T>> GetEnumerator()\n{\n var pointer = Head;\n while (pointer != null)\n {\n yield return pointer;\n pointer = pointer.Next;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>It's fine to provide an enumerator. But it would be better to implement the <code>IEnumerable<T></code> interface instead - where T is the <code>T</code> from your list - not <code>Node<T></code>. </p>\n\n<p>If you do that, instead of this</p>\n\n<blockquote>\n<pre><code> using (var linkedListEnumerator = myLinkedList.GetEnumerator())\n {\n while (linkedListEnumerator.MoveNext())\n {\n Console.WriteLine(linkedListEnumerator.Current.Data);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>you would be able to do </p>\n\n<pre><code> foreach (var item in myLinkedList)\n {\n Console.WriteLine(item);\n }\n</code></pre>\n\n<p>And besides that, by implementing <code>IEnumerable<T></code>, you'll be able to use LINQ extensions on the list. (see also VisualMelons comment).</p>\n\n<hr>\n\n<p>Consider to implement this:</p>\n\n<pre><code>public bool Remove(T item)\n{\n // TODO: implement this\n return <wasRemoved>;\n}\n</code></pre>\n\n<hr>\n\n<p>You could try to implement the above and make a new post with an updated version with unit tests and we could then review that... :-)</p>\n\n<p>Your use case should look as something like:</p>\n\n<pre><code>void RunLinkedList()\n{\n Console.WriteLine(\"Running the LinkedList class\");\n Console.WriteLine(\"----------------------------\");\n var myLinkedList = new LinkedList<int>();\n myLinkedList.AddHead(99);\n myLinkedList.AddHead(56);\n myLinkedList.AddHead(23);\n myLinkedList.AddHead(33);\n myLinkedList.AddTail(8888);\n myLinkedList.RemoveTail();\n myLinkedList.RemoveHead();\n Console.WriteLine(\"HEAD = \" + myLinkedList.Head);\n Console.WriteLine(\"TAIL = \" + myLinkedList.Tail);\n\n foreach (var item in myLinkedList)\n {\n Console.WriteLine(item);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:47:03.663",
"Id": "418811",
"Score": "1",
"body": "With your suggestion, `public T RemoveLast() {...}`, doesn't it violate \nCommand-Query Separation? RemoveLast() modifies state. Is It okay to break the rule sometimes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:56:29.067",
"Id": "418814",
"Score": "1",
"body": "+1; sadly (IMO) you can already use `foreach` on the OP's class, but properly implementing `IEnumerable<T>` will facilitate much more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T15:08:04.370",
"Id": "418816",
"Score": "0",
"body": "@VisualMelon: You're right. I know you can, but what I intended to show was that the Enumerator enumerates the `T`'s and not the `Node<T>`s. By implementing IEnumerable<T> you'll be able to use the standard Linq extensions etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T15:12:44.487",
"Id": "418818",
"Score": "0",
"body": "@feature_creep: IMO CQS is about not changing the object (the list) when querying it. Here I do the opposite: changing the object and provide the \"change\" to the client - it's not a query. It's a little different."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:47:26.450",
"Id": "216469",
"ParentId": "216453",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "216469",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:44:52.597",
"Id": "216453",
"Score": "8",
"Tags": [
"c#",
"beginner",
"linked-list",
"unit-testing"
],
"Title": "Linked list implementation along with unit test"
} | 216453 |
<p>I need to optimize this javascript method because it is a bit slow, I don't want to use the flat() command, as for some reason my angular6 app does not understand the vanilla flat() command, or display some annoying warning messages.</p>
<p>So check the below:</p>
<blockquote>
<ol>
<li>my original object</li>
<li>my result object desired</li>
<li>my slow solution (works, but is slow)</li>
</ol>
</blockquote>
<p><strong>1. my original object:</strong></p>
<pre><code> const data = [
{
"id": 1,
"name": "Application",
"groups": [
{
"groupName": "",
"configurations": [
{
"id": 17,
"icon": "access_time",
"title": "Daily Order Cut-Off Time",
"description": "Daily Order Cut-Off Time",
"code": "daily-order-cut-off-time",
"value": "09:35",
"valueType": "Time",
"configurationTypeId": 11,
"definition": {
"step": "none"
},
"isDefault": false
}
]
}
]
},
{
"id": 3,
"name": "Processing",
"groups": [
{
"groupName": "",
"configurations": [
{
"id": 1078,
"icon": "flash_on",
"title": "Auto Process",
"description": "Will process all orders that are in the same batch",
"code": "processing-auto-process",
"value": "0",
"valueType": "Boolean",
"configurationTypeId": 6,
"definition": null,
"isDefault": false
},
{
"id": 1074,
"icon": "subdirectory_arrow_right",
"title": "Allow Under Picking",
"description": "Allow under pick when processing order?",
"code": "processing-allow-under-picks",
"value": "0",
"valueType": "Boolean",
"configurationTypeId": 6,
"definition": null,
"isDefault": false
}
]
}
]
}
];
</code></pre>
<p><strong>2. object desired:</strong></p>
<pre><code> [
{
"id": 17,
"code": "daily-order-cut-off-time",
"value": "09:35"
},
{
"id": 1078,
"code": "processing-auto-process",
"value": "0"
},
{
"id": 1074,
"code": "processing-allow-under-picks",
"value": "0"
}
]
</code></pre>
<p><strong>My slow solution:</strong></p>
<pre><code>const result = data.map(module => module.groups.map(configurations => configurations.configurations.map(config => ({ id: config.id, code: config.code, value: config.value })))).reduce((l,n) => l.concat(n), []).reduce((l2,n2) => l2.concat(n2),[]));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:33:47.290",
"Id": "418754",
"Score": "2",
"body": "Is the ES6 spread operator available to you? `result = [].concat(...[].concat(...data.map( d => d.groups.map( g => g.configurations.map( c => ({id:c.id, code:c.code, value:c.value}))))))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:50:57.133",
"Id": "418756",
"Score": "0",
"body": "yes it is available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T23:55:15.293",
"Id": "418757",
"Score": "0",
"body": "AMAZING! YOUR CODE IS BEAUTIFUL!, please answer my question I will mark as the correct answer!"
}
] | [
{
"body": "<p>As commented, the ES6 spread operator flattens like you want. The syntax is a little weird for multiple invocations:</p>\n\n<pre><code>result = [].concat(...[].concat(...data.map( d => d.groups.map( g => g.configurations.map( c => ({id:c.id, code:c.code, value:c.value})))))) \n</code></pre>\n\n<p>The <code>arr.flat()</code> method does the same thing more simply. It takes an optional <em>depth</em> argument to indicate how many levels to descend when flattening. In your case, depth is 2. </p>\n\n<p><code>.flat</code> is a recent feature that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Browser_compatibility\" rel=\"nofollow noreferrer\">may not exist</a> on your platform. Most notably, Node 10 and MS Edge do not have it, while both of those do have the spread operator:</p>\n\n<pre><code>data.map( d => d.groups.map( g => g.configurations.map( c => ({id:c.id, code:c.code, value:c.value})))).flat(2)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T03:01:55.283",
"Id": "418765",
"Score": "0",
"body": "also, the use of the command .flat() would help somehow in this solution? thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T13:20:44.460",
"Id": "418793",
"Score": "0",
"body": "yes, if you have it. See my edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:13:11.203",
"Id": "216455",
"ParentId": "216454",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216455",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:48:21.963",
"Id": "216454",
"Score": "0",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Extracting grouped objects into a flattened list"
} | 216454 |
<p>I'm posting here to ask for some help improving myself using python since I'm fairly new to it and come from C#.</p>
<p>The main functionality of this bot is parsing the Wargaming API for player related information.</p>
<p>Project structure:</p>
<pre><code>project
| main.py
└───ENV
│
└───data
| classes.py
| dbcontext.py
| getStats.py
| secret.py
| log.py
| updateDb.py
| updateDbData.json
</code></pre>
<p>My Main:</p>
<pre><code>####### General imports #######
import asyncio
import logging
####### Discord imports #######
import discord
from discord.ext import commands
####### Data imports #######
import data.translations as trans
from data import dbcontext
from data import getStats as GetStats
from data import log, secret
from data.classes import Config, ErrorType, Player, ReturnVal, Ship, Stats
####### Bot Basic Configuration #######
bot = commands.Bot(command_prefix="!")
bot.remove_command('help')
####### err.log handler #######
logger = logging.getLogger('discord')
logger.setLevel(logging.ERROR)
handler = logging.FileHandler(filename='err.log', encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter(
'%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
####### Global Vars #######
configs = []
regions = ["eu", "ru", "na", "asia"]
langs = ["de", "en", "pl", "tr"] # remember adding to imports too
translations = [trans.de, trans.en, trans.pl, trans.tr]
####### Bot Events #######
@bot.event
async def on_ready():
log.writeLog("init", "Ready")
print("Bot Started")
configs = []
for x in bot.guilds:
configs.append(dbcontext.getConfig(x.id))
print("Connected to: " + x.name)
log.writeLog("Connected", x.name)
@bot.event
async def on_guild_join(guild):
log.writeLog("Connected", guild.name)
configs = []
for x in bot.guilds:
configs.append(dbcontext.getConfig(x.id))
@bot.command()
@commands.has_any_role('Stats-Bot')
async def statsRegion(ctx, *args):
if args[0] not in regions:
await ctx.send("Supported regions are: " + " ".join(regions[0:]))
else:
cfg = dbcontext.getConfig(ctx.guild.id)
if args[0] == "na":
cfg.region = "com"
else:
cfg.region = args[0]
retval = dbcontext.updateConfig(cfg)
if retval == ReturnVal.SUCCESS:
await ctx.send("Region changed to: " + args[0])
else:
await ctx.send("Failed to change region.")
@bot.command()
@commands.has_any_role('Stats-Bot')
async def statsLang(ctx, *args):
if args[0] not in langs:
await ctx.send("Supported languages are: " + " ".join(langs[0:]))
else:
cfg = dbcontext.getConfig(ctx.guild.id)
cfg.language = args[0]
retval = dbcontext.updateConfig(cfg)
if retval == ReturnVal.SUCCESS:
await ctx.send("Language changed to: " + args[0])
else:
await ctx.send("Failed to change Language.")
@bot.command()
@commands.has_any_role('Stats-Bot')
async def statsAddAsn(ctx, *args):
import re
name = ""
asn = ""
if len(args) == 2:
name = re.sub("[\"]", '', args[0])
asn = re.sub("[\"]", '', args[1])
result = dbcontext.addAsn(name, asn)
if result == ReturnVal.SUCCESS:
await ctx.send("Alternate shipname {an} for {on} was added".format(an=asn, on=name))
elif result == ReturnVal.DOUBLE:
await ctx.send("Alternate shipname already set")
else:
await ctx.send("An error has occured, please contact Owner")
else:
await ctx.send("Usage: !statsAddAsn \"Original Shipname\" \"Alternate Shipname\". the \" are Important and mandatory. ")
@bot.command()
async def stats(ctx, *args):
if ctx.message.guild is not None:
config = dbcontext.getConfig(ctx.guild.id)
# if (len(args) == 0) or (len(args) == 1 and args[0].lower() == "help"):
if len(args) == 0 or args[0].lower() == "help":
await writeHelp(ctx, config)
elif len(args) == 1 and args[0] != "help":
playerObject = GetStats.getPlayer(config, args[0])
if playerObject == ErrorType.UNKNOWN_PLAYER:
await writeError(ctx, config, playerObject)
else:
playerStats = GetStats.getStats(config, playerObject)
if playerStats == ErrorType.HIDDEN_STATS:
await writeError(ctx, config, playerStats)
elif playerStats == ErrorType.UNKNOWN_STATS:
await writeError(ctx, config, playerStats)
elif playerStats == ErrorType.SERVER_ERROR:
await writeError(ctx, config, playerStats)
elif playerStats == ErrorType.INTERNAL_ERROR:
await writeError(ctx, config, playerStats)
else:
await writeAnswer(ctx, config, playerObject, playerStats)
elif len(args) >= 2:
playerObject = GetStats.getPlayer(config, args[0])
if playerObject == ErrorType.UNKNOWN_PLAYER:
await writeError(ctx, config, playerObject)
else:
ship = dbcontext.getShip(" ".join(args[1:]))
if ship == ErrorType.UNKNOWN_SHIP:
await writeError(ctx, config, ship)
elif ship == ErrorType.INTERNAL_ERROR:
await writeError(ctx, config, ship)
else:
shipStats = GetStats.getStats(config, playerObject, ship)
if shipStats == ErrorType.HIDDEN_STATS:
await writeError(ctx, config, shipStats)
elif shipStats == ErrorType.UNKNOWN_STATS:
await writeError(ctx, config, shipStats)
else:
await writeAnswer(ctx, config, playerObject, ship, shipStats)
else:
await ctx.send("**I'm not allowed to answer in Private messages.**")
@bot.command()
async def statsr(ctx, *args):
import re
if ctx.message.guild is None:
await ctx.send("**I'm not allowed to answer in Private messages.**")
else:
config = dbcontext.getConfig(ctx.guild.id)
# regex to check for valid season
regex = re.compile("^(![1-9][1]|![1-9])|(!s[1-4])$", re.IGNORECASE)
if (len(args) == 0) or (len(args) == 1 and args[0].lower() == "help"):
await writeHelp(ctx, config)
elif regex.match(args[0]):
await writeError(ctx, config, ErrorType.UNKNOWN_SEASON)
elif len(args) == 2 and args[0] != "help":
season = convertSeason(args[0])
playerObject = GetStats.getPlayer(config, args[1])
if playerObject == None or playerObject.id == 0:
await writeError(ctx, config, ErrorType.UNKNOWN_PLAYER)
else:
playerStats = GetStats.getRankedStats(
config, playerObject, season)
if playerStats.hidden:
await writeError(ctx, config, ErrorType.HIDDEN_STATS)
elif playerStats.damage == 0:
await writeError(ctx, config, ErrorType.UNKNOWN_STATS)
else:
await writeAnswer(ctx, config, playerObject, playerStats)
elif len(args) > 2:
season = convertSeason(args[0])
playerObject = GetStats.getPlayer(config, args[1])
if playerObject == None or playerObject.id == 0:
await writeError(ctx, config, ErrorType.UNKNOWN_PLAYER)
else:
ship = dbcontext.getShip(" ".join(args[2:]))
if ship.id == 0:
await writeError(ctx, config, ErrorType.UNKNOWN_SHIP)
else:
shipStats = GetStats.getRankedStats(
config, playerObject, season, ship)
if shipStats.hidden:
await writeError(ctx, config, ErrorType.HIDDEN_STATS)
elif shipStats.damage == 0:
await writeError(ctx, config, ErrorType.UNKNOWN_STATS)
else:
await writeAnswer(ctx, config, playerObject, ship, shipStats)
else:
await writeHelp(ctx, config)
####### Helper Functions #######
async def writeAnswer(ctx, config, *args):
player = None
ship = None
stats = None
embed = None
translation = next(
_cls for _cls in translations if _cls.__name__ == config.language)
for arg in args:
if isinstance(arg, Player):
player = arg
elif isinstance(arg, Ship):
ship = arg
elif isinstance(arg, Stats):
stats = arg
if player != None and stats != None and ship != None:
color = getColor(stats.avgWins)
embed = discord.Embed(title=translation.title.format(username=player.name), url=GetStats.getPlayerLink(
config, player), description=translation.description.format(shipname=ship.name), color=color)
embed.set_author(name="WoWs-Stats-Bot",
url="https://github.com/De-Wohli")
embed.set_thumbnail(url=ship.url)
embed.add_field(name=translation.battles,
value=stats.battles, inline=True)
embed.add_field(name=translation.avgDamage,
value=stats.avgDamage, inline=True)
embed.add_field(name=translation.winrate,
value="{:.2f}%".format(stats.avgWins), inline=True)
embed.set_footer(text=translation.footer)
elif player != None and stats != None and ship == None:
color = getColor(stats.avgWins)
embed = discord.Embed(title=translation.title.format(username=player.name), url=GetStats.getPlayerLink(
config, player), description=translation.general, color=color)
embed.set_author(name="WoWs-Stats-Bot",
url="https://github.com/De-Wohli")
embed.add_field(name=translation.battles,
value=stats.battles, inline=True)
embed.add_field(name=translation.avgDamage,
value=stats.avgDamage, inline=True)
embed.add_field(name=translation.winrate,
value="{:.2f}%".format(stats.avgWins), inline=True)
embed.set_footer(text=translation.footer)
if embed != None:
await ctx.send(embed=embed)
async def writeHelp(ctx, config):
color = discord.Color.teal()
translation = next(
_cls for _cls in translations if _cls.__name__ == config.language)
embed = discord.Embed(title=translation.helpHeader,
description=translation.helpDescription, color=color)
embed.set_author(name="WoWs-Stats-Bot")
embed.add_field(name="!stats [player]",
value=translation.helpPlayer, inline=False)
embed.add_field(name="!stats [player] [shipname]",
value=translation.helpShip, inline=False)
embed.add_field(name="!statsr [season] [player]",
value=translation.helpRanked, inline=False)
embed.add_field(name="!statsr [season] [player] [shipname]",
value=translation.helpSRanked, inline=False)
embed.set_footer(text="This bot was made by Fuyu_Kitsune")
await ctx.send(embed=embed)
async def writeError(ctx, config, errorType):
color = discord.Color.dark_teal()
translation = next(
_cls for _cls in translations if _cls.__name__ == config.language)
errorText = translation.error[errorType.value]
embed = discord.Embed(title="Error", description=errorText, color=color)
embed.set_author(name="WoWs-Stats-Bot")
embed.set_footer(text=translation.footer)
await ctx.send(embed=embed)
def getColor(value):
if value <= 40:
return discord.Colour.red()
elif value > 40 and value <= 45:
return discord.Colour.orange()
elif value > 45 and value <= 50:
return discord.Colour.gold()
elif value > 50 and value <= 53:
return discord.Colour.green()
elif value > 53 and value <= 56:
return discord.Color.dark_green()
elif value > 56 and value <= 60:
return discord.Color.teal()
elif value > 60 and value <= 66:
return discord.Color.purple()
elif value > 66:
return discord.Colour.dark_purple()
def convertSeason(value):
season = value
if season == "s1":
season = "101"
elif season == "s2":
season = "102"
elif season == "s3":
season = "103"
elif season == "s4":
season = "104"
return season
####### Run Bot #######
bot.run(secret.Secret.token)
</code></pre>
<p>This being the main method, here is where the parsing of the command takes place. The usual command is <code>!stats [playername] [shipname]</code> My primary concerns here are the <code>async def stats(ctx, *args):</code> and <code>async def statsr(ctx, *args):</code> functions.</p>
<p>data/classes.py:</p>
<pre><code>f####### Imports #######
from enum import Enum
class Ship:
def __init__(self, id=0, name="", url=""):
self.id = id
self.name = name
self.url = url
def __eq__(self, other):
return self.name == other
class Player:
def __init__(self, id=0, name="", code="404"):
self.id = id
self.name = name
class Stats:
def __init__(self, battles=0, frags=0, damage_dealt=0, wins=0, hidden=False, code=404):
self.hidden = hidden
self.battles = battles
self.frags = float(frags)
self.damage = float(damage_dealt)
self.wins = wins
@property
def avgFrags(self):
if self.battles == 0:
return 0
return round(self.frags / self.battles, 2)
@property
def avgDamage(self):
if self.battles == 0:
return 0
return round(self.damage / self.battles, 2)
@property
def avgWins(self):
if self.battles == 0:
return 0
return round(float(self.wins / self.battles), 4)*100
class Config:
def __init__(self, serverId=0, region="eu", language="en"):
self.serverId = serverId
self.region = region
self.language = language
class ReturnVal(Enum):
SUCCESS = 0
FAILED = 1
DOUBLE = 2
class ErrorType(Enum):
"""
UNKNOWN_PLAYER = 0
UNKNOWN_SHIP = 1
UNKNOWN_STATS = 2
HIDDEN_STATS = 3
UNKNOWN_SEASON = 4
SERVER_ERROR = 5
INTERNAL_ERROR = 6
"""
def __str__(self):
return str(self.value)
UNKNOWN_PLAYER = 0
UNKNOWN_SHIP = 1
UNKNOWN_STATS = 2
HIDDEN_STATS = 3
UNKNOWN_SEASON = 4
SERVER_ERROR = 5
INTERNAL_ERROR = 6
</code></pre>
<p>these are my model classes, since I'm coming from C# I'm not too sure if this would be an acceptable way of dealing with it in python.</p>
<p>data/dbcontext.py:</p>
<pre><code>####### Imports #######
import mysql.connector
####### Data imports #######
import data.log as log
from data.classes import Config, ReturnVal, Ship, ErrorType
from data.secret import Secret
def connect():
''' Returns the MySQL connection '''
mydb = mysql.connector.connect(
host=Secret.dbAddr, user=Secret.dbUser, passwd=Secret.dbPwd, database=Secret.dbName)
return mydb
def getShip(name):
'''
Returns ship() the Ship ID, Name and URL from the Database, including Alternate Ship Names,
Returns ReturnVal enum on error
'''
try:
con = connect()
cursor = con.cursor()
sql = 'SELECT id,Name,url FROM Ships WHERE name LIKE %s'
val = (name,)
cursor.execute(sql, val)
rows = cursor.fetchone()
if rows is None:
sql = 'SELECT id,Name,url FROM Ships WHERE id = (SELECT id FROM Asn WHERE name LIKE %s)'
val = (name,)
cursor.execute(sql, val)
rows = cursor.fetchone()
if rows is None:
return ErrorType.UNKNOWN_SHIP
else:
return Ship(id=rows[0], name=rows[1], url=rows[2])
else:
return Ship(id=rows[0], name=rows[1], url=rows[2])
except Exception as e:
log.writeLog("getShip({name})".format(name=name), str(e))
con.rollback()
return ErrorType.InternalError
finally:
con.commit()
con.close()
def addAsn(name, asn):
'''
Adds an Alternate shipname to the Database.
Returns ReturnVal enum
'''
try:
con = connect()
cursor = con.cursor()
sql = 'SELECT id,Name,url FROM Ships WHERE name LIKE %s'
val = (name,)
cursor.execute(sql, val)
rows = cursor.fetchone()
if rows is None:
return ReturnVal.FAILED
else:
sql = 'INSERT INTO Asn (name,id,url) VALUES(%s,%s,%s)'
val = (asn, rows[0], rows[2])
cursor.execute(sql, val)
return ReturnVal.SUCCESS
except mysql.connector.IntegrityError as e:
return ReturnVal.DOUBLE
except Exception as e:
log.writeLog("getShip({name},{asn})".format(
name=name, asn=asn), str(e))
con.rollback()
return ReturnVal.FAILED
finally:
con.commit()
con.close()
def getConfig(id):
'''
Gets the Server configuration from the Database.
Returns Config()
'''
try:
con = connect()
cursor = con.cursor()
sql = 'SELECT region,language FROM Config WHERE ServerId = %s'
val = (id,)
cursor.execute(sql, val)
rows = cursor.fetchone()
if rows is None:
config = Config(serverId=id)
sql = 'INSERT INTO Config(ServerID,region,language) VALUES(%s,%s,%s)'
val = (config.serverId, config.region, config.language)
cursor.execute(sql, val)
return config
else:
return Config(serverId=id, region=rows[0], language=rows[1])
except Exception as e:
log.writeLog("getConfig({id})".format(id=id), str(e))
con.rollback()
finally:
con.commit()
con.close()
def addConfig(id):
'''
Adds an configuration of a new Server to the Database.
Returns ReturnVal enum
'''
try:
con = connect()
cursor = con.cursor()
sql = 'INSERT INTO Config (ServerId, region, language) VALUES(%s,%s,%s)'
val = (id, "eu", "en")
cursor.execute(sql, val)
return ReturnVal.SUCCESS
except Exception as e:
log.writeLog("addConfig({id})".format(id=id), str(e))
con.rollback()
return ReturnVal.FAILED
finally:
con.commit()
con.close()
def updateConfig(config):
'''
Updates an existing configuration of a Server in the Database.
Returns ReturnVal enum
'''
try:
con = connect()
cursor = con.cursor()
sql = 'UPDATE Config SET region = %s, language = %s WHERE ServerID = %s'
val = (config.region, config.language, config.serverId)
cursor.execute(sql, val)
return ReturnVal.SUCCESS
except Exception as e:
log.writeLog("updateConfig({config})".format(
config=str(config)), str(e))
con.rollback()
return ReturnVal.FAILED
finally:
con.commit()
con.close()
</code></pre>
<p>In this file I'm handling all database access. The database stores mainly Ship names & IDs. Is this way of handling the database connection secure or is this vulnerable?</p>
<p>data/getStats.py:</p>
<pre><code>####### Imports #######
import requests
import json
####### Data imports #######
from data.classes import Ship, Player, Stats, ErrorType
from data.secret import Secret
from data.api import api
from data import log
def getPlayer(config, playerName):
'''
Gets player Object from the Wargaming API
Returns player() on success
Returns ErrorType enum on failure
'''
try:
url = api.psearch.format(
reg=config.region, wgapi=Secret.api, playerName=playerName)
response = requests.get(url)
response = response.json()
if response["status"] == "ok":
if response["meta"]["count"] == 0:
return ErrorType.UNKNOWN_PLAYER
else:
nick = response["data"][0]["nickname"]
pid = response["data"][0]["account_id"]
newPlayer = Player(name=nick, id=pid)
return newPlayer
else:
return ErrorType.SERVER_ERROR
except Exception as e:
log.writeLog("getPlayer(config,{playerName}".format(
playerName=playerName), str(e))
return ErrorType.INTERNAL_ERROR
def getPlayerLink(config, player):
'''
Creates the Playerlink for the Wargaming Webprofile of the player.
returns str()
'''
link = str.format(
"{}{}-{}", str(api.plink).format(reg=config.region), player.id, player.name)
return link
def getStats(config, player, ship=None):
'''
Gets the players (optional ship) stats form the WargamingAPI
Returns stats() on success
Returns ErrorType enum on failure
'''
try:
if ship is not None:
url = api.sstats.format(
reg=config.region, wgapi=Secret.api, accountID=player.id, shipID=ship.id)
else:
url = api.pstats.format(
reg=config.region, wgapi=Secret.api, accountID=player.id)
response = requests.get(url)
response = response.json()
if(response["status"] == "ok"):
if bool(response["meta"]["hidden"]):
return ErrorType.HIDDEN_STATS
elif bool(response["data"]) and not response["data"][str(player.id)] == None:
if 'statistics' in response["data"][str(player.id)]:
statistics = response["data"][str(player.id)]['statistics']
else:
statistics = response["data"][str(player.id)][0]
battles = statistics['pvp']['battles']
wins = statistics['pvp']['wins']
frags = statistics['pvp']['frags']
damage_dealt = statistics['pvp']['damage_dealt']
return Stats(battles, frags, damage_dealt, wins, False)
else:
return ErrorType.UNKNOWN_STATS
else:
return ErrorType.SERVER_ERROR
except Exception as e:
log.writeLog("getStats(config,{player},{ship})".format(
player=player, ship=ship), str(e))
return ErrorType.INTERNAL_ERROR
def getRankedStats(config, player, season, ship=None):
'''
Gets the players ranked stats for specified player, (optional) ship and season from the Wargaming API
Returns stats() on success.
Returns ErrorType enum on failure
'''
try:
if ship is not None:
url = api.rsstats.format(
reg=config.region, wgapi=Secret.api, accountID=player.id, shipID=ship.id)
else:
url = api.rpstats.format(
reg=config.region, wgapi=Secret.api, accountID=player.id)
response = requests.get(url)
response = response.json()
if(response["status"] == "ok"):
if bool(response["meta"]["hidden"]):
return ErrorType.HIDDEN_STATS
elif bool(response["data"]) and not response["data"][str(player.id)] == None:
if ship is not None:
seasons = response["data"][str(player.id)][0]["seasons"]
if season in seasons:
currentSeason = response["data"][str(
player.id)][0]["seasons"][season]
else:
return ErrorType.UNKNOWN_STATS
else:
seasons = response["data"][str(player.id)]["seasons"]
if season in seasons:
currentSeason = response["data"][str(
player.id)]["seasons"][season]
else:
return ErrorType.UNKNOWN_STATS
stats = Stats()
rankeds = []
rankeds.append(currentSeason["rank_solo"])
rankeds.append(currentSeason["rank_div2"])
rankeds.append(currentSeason["rank_div3"])
for ranked in rankeds:
if ranked is not None:
stats.wins += ranked["wins"]
stats.damage += ranked["damage_dealt"]
stats.battles += ranked["battles"]
stats.frags += ranked["frags"]
else:
return ErrorType.UNKNOWN_PLAYER
return stats
else:
return ErrorType.SERVER_ERROR
pass
except Exception as e:
log.writeLog("getRankedStats(config,{player},{season},{ship})".format(
player=player, season=season, ship=ship), str(e))
return ErrorType.INTERNAL_ERROR
</code></pre>
<p>this is the communication class for querying the API endpoints. The endpoints are stored in a different file <code>data/api.py</code> containing a class with the variables stored. i.e.</p>
<pre><code>class api:
psearch = "https://api.worldofwarships.{reg}/wows/account/list/?application_id={wgapi}&search={playerName}"
pstats = "https://api.worldofwarships.{reg}/wows/account/info/?application_id={wgapi}&account_id={accountID}&fields=statistics.pvp.battles%2Cstatistics.pvp.damage_dealt%2C+statistics.pvp.frags%2Cstatistics.pvp.wins"
sstats = "https://api.worldofwarships.{reg}/wows/ships/stats/?application_id={wgapi}&account_id={accountID}&ship_id={shipID}&fields=pvp.battles%2C+pvp.damage_dealt%2C+pvp.frags%2C+pvp.wins"
plink = "https://worldofwarships.{reg}/community/accounts/"
rpstats = "https://api.worldofwarships.{reg}/wows/seasons/accountinfo/?application_id={wgapi}&account_id={accountID}"
rsstats = "https://api.worldofwarships.{reg}/wows/seasons/shipstats/?application_id={wgapi}&account_id={accountID}&ship_id={shipID}"
</code></pre>
<p>The code as shown here is currently working and being hosted on a linux server without too many troubles yet but I'm curious to know about the, probably many things, i could improve.
If needed I can provide the answers I'm getting from the API if that would be of any concern to the code I've posted.</p>
<p>In general I'm seeking assistance to improve my python programming aswell as improve performance / stability of my code. Any information aswell as critique is welcome. </p>
<p>Thank you.</p>
<p>EDIT: Updated classes to include already done improvements.</p>
<p><code>data/secret.py</code>:</p>
<pre><code>class Secret:
api = ""
token = ""
dbUser = ""
dbPwd = ""
dbName = ""
dbAddr = ""
</code></pre>
<p><code>data/translations.py</code>:</p>
<pre><code>class translation():
title = ""
description = ""
general = ""
battles = ""
avgDamage = ""
winrate = ""
footer = ""
helpHeader = ""
helpDescription = ""
helpPlayer = ""
helpShip = ""
helpRanked = ""
helpSRanked = ""
#### UNKNOWN_PLAYER,UNKNOWN_SHIP,UNKNOWN_STATS,HIDDEN_STATS,UNKNOWN_SEASON,SERVER_ERROR,INTERNAL_ERROR
error = []
class en(translation):
title = "Statistics from {username}"
description = "For {shipname}"
general = "General stats"
battles = "Battles"
avgDamage = "Avg. Damage"
winrate = "Winrate"
footer = ""
helpHeader = "Bot Usage"
helpDescription = "How to use me correctly"
helpPlayer = "Get the overall player stats"
helpShip = "Get ship stats from the player"
helpRanked = "Get season or sprint(e.g. 11 or s4) stats for a player"
helpSRanked = "Get season or sprint(e.g. 11 or s4) stats for a ship from the player"
#### UNKNOWN_PLAYER,UNKNOWN_SHIP,UNKNOWN_STATS,HIDDEN_STATS,UNKNOWN_SEASON,SERVER_ERROR,INTERNAL_ERROR
error = ["Unknown Player", "Unknown Ship", "No stats recorded",
"This player refuses to share his statistics", "Unknown Season", "Server Error", "Internal Error"]
class de(translation):
title = "Statistiken von {username}"
description = "Für {shipname}"
general = "Allgemeine Statistik"
battles = "Gefechte"
avgDamage = "Durchschn. Schaden"
winrate = "Winrate"
footer = ""
helpHeader = "Bot Benutzung"
helpDescription = "So funktioniere ich"
helpPlayer = "Für die allgemeinen Spieler Statistiken"
helpShip = "Für die Statistkien des Spielers für das Schiff"
helpRanked = "Für season oder sprint(z.B. 11 oder s4) statistiken eines Spielers"
helpSRanked = "Für season oder sprint(z.B. 11 oder s4) statistiken des schiffs für den Spieler"
#### UNKNOWN_PLAYER,UNKNOWN_SHIP,UNKNOWN_STATS,HIDDEN_STATS,UNKNOWN_SEASON,SERVER_ERROR,INTERNAL_ERROR
error = ["Unbekannter spieler", "Unbekanntes Schiff", "Keine Statistiken vorhanden",
"Dieser spieler möchte seine Statistiken nicht teilen", "Diese season ist nicht bekannt", "Server Error", "Internal Error"]
class pl(translation):
title = "Statystyki gracza {username}"
description = "dla okrętu {shipname}"
general = "Ogólne statystyki"
battles = "Bitew"
avgDamage = "Średnie obrażenia"
winrate = "Winrate"
footer = ""
helpHeader = "Bot Usage"
helpDescription = "Jak używać bota poprawnie"
helpPlayer = "Sprawdź ogólne statystyki gracza"
helpShip = "Sprawdź statystyki konkretnego okrętu danego gracza"
helpRanked = "Sprawdź statystyki sezonu bitew rankingowych lub sprintu dla gracza"
helpSRanked = "Srawdź statystyki konkretnego okrętu wybranego gracza dla sezonu rankingowego/sprintu"
#### UNKNOWN_PLAYER,UNKNOWN_SHIP,UNKNOWN_STATS,HIDDEN_STATS,UNKNOWN_SEASON,SERVER_ERROR,INTERNAL_ERROR
error = ["Nieznany gracz", "nieznany okręt", "brak danych",
"Gracz odmówił ujawniania swoich statystyk", "Nieznany sezon", "Server Error", "Internal Error"]
class tr(translation):
title = "{username} oyuncusunun istatistikleri"
description = "{shipname} için"
general = "Genel istatistikler"
battles = "Maçlar"
avgDamage = "Ortalama Hasar"
winrate = "Galibiyet Oranı"
footer = ""
helpHeader = "Bot Kullanımı"
helpDescription = "Kullanım Kılavuzu"
helpPlayer = "Oyuncunun bütün istatistiklerini al"
helpShip = "Oyuncudan gemi istatistikleri al"
helpRanked = "Bir oyuncunun belirli bir Sıralamalı Savaş veya Sprint(Örnek: 11 veya s4) sezonu istatistiklerini al"
helpSRanked = " Bir oyuncunun herhangi bir gemide Sıralamalı Savaş veya Sprint(Örnek: 11 veya s4) sezon istatistiklerini al "
#### UNKNOWN_PLAYER,UNKNOWN_SHIP,UNKNOWN_STATS,HIDDEN_STATS,UNKNOWN_SEASON,SERVER_ERROR,INTERNAL_ERROR
error = ["Tanımlanamayan Oyuncu", "Tanımlanamayan Gemi", "Kayıtlı istatistik bulunamadı",
"Bu oyuncu bilgilerini paylaşıma kapatmış", "Tanımlanamayan Sezon", "Server Error", "Internal Error"]
</code></pre>
<p><code>data/log.py</code></p>
<pre><code>####### Imports #######
import os
from datetime import datetime
mainFolder = os.path.join(os.path.dirname(__file__), "../")
logFile = os.path.join(mainFolder, "bot.log")
def writeLog(method, message):
'''
Writes error messages to the `bot.log` file
returns void
'''
file = open(logFile, "a")
file.write("{} | {} | {} \n".format(
str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), method, message))
</code></pre>
<p>with this edit all needed files should be given for the bot to be able to run.</p>
<p><a href="https://developers.wargaming.net/reference" rel="nofollow noreferrer">link for Wargaming API key</a></p>
<p>I've used the following script to create the database;</p>
<pre class="lang-sql prettyprint-override"><code>USE WOWS;
CREATE TABLE IF NOT EXISTS Ships(
Name NVARCHAR(255) UNIQUE,
Id BIGINT,
Url TEXT
);
CREATE TABLE IF NOT EXISTS Config(
ServerId BIGINT UNIQUE,
region NVARCHAR(255),
language NVARCHAR(255)
);
CREATE TABLE IF NOT EXISTS Asn(
Name NVARCHAR(255) UNIQUE,
Id BIGINT,
Url TEXT
);
</code></pre>
<p>Function to populate the database <code>data/updateDB.py</code></p>
<pre><code># -*- encoding: utf-8 -*-
import codecs
import json
import os
import mysql.connector
import sys
import time
import requests
from classes import Ship
from secret import Secret
# Vars
path = os.path.dirname(__file__)
apikey = Secret.api
# Functions
def GetShipsByType(n, s, lang):
response = requests.get(
"https://api.worldofwarships.eu/wows/encyclopedia/ships/?application_id={id}&type={type}&fields=ship_id%2Cname%2Cimages&language={lang}&nation={nation}".format(type=s, nation=n, id=apikey, lang=lang))
if(response.status_code == 200):
jArray = json.loads(response.content)
for x in jArray["data"].items():
if x[1]['name'] not in ships:
ships.append(
Ship(name=x[1]['name'], id=x[1]['ship_id'], url=x[1]['images']['small']))
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("\n")
sys.stdout.flush()
def db_connect():
mydb = mysql.connector.connect(
host=Secret.dbAddr, user=Secret.dbUser, passwd=Secret.dbUser, database=Secret.dbName)
return mydb
def AddShip(newShip):
try:
con = db_connect()
cursor = con.cursor()
try:
sql = 'INSERT INTO Ships(id,name,url) VALUES (%s,%s,%s);'
val = (newShip.id, newShip.name, newShip.url)
cursor.execute(sql, val)
con.commit()
except Exception as e:
print("Skipped " + newShip.name)
pass
con.close()
except Exception as e:
print(e)
def cooldown(seconds):
sys.stdout.write("cooldown")
for x in range(seconds):
time.sleep(1)
sys.stdout.write(".")
sys.stdout.write("\n")
sys.stdout.flush()
# Main
tmp = {}
toolFolder = os.path.join(os.path.dirname(__file__))
dataFile = os.path.join(toolFolder, "UpdateDbData.json")
try:
with codecs.open(dataFile, encoding="utf-8", mode="r") as f:
tmp = json.load(f, encoding="utf-8")
except:
print("error")
sys.exit(1)
langs = tmp["langs"]
nation = tmp["nations"]
shipTpe = tmp["types"]
ships = []
for l in langs:
print("Getting Ships in Language: "+l)
for n in nation:
for s in shipTpe:
print("Getting {} from {} ".format(s, n))
GetShipsByType(n, s, l)
cooldown(2)
cooldown(3)
for s in ships:
print(u"Adding {} to Database".format(s.name))
AddShip(s)
</code></pre>
<p>Configuration for updateDB <code>data/updateDbData.json</code>:</p>
<pre><code>{
"nations": [
"ussr",
"japan",
"germany",
"france",
"usa",
"pan_asia",
"pan_america",
"italy",
"uk",
"commonwealth",
"poland"
],
"langs": [
"en"
],
"types": [
"AirCarrier",
"Battleship",
"Cruiser",
"Destroyer"
]
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:06:55.337",
"Id": "419741",
"Score": "0",
"body": "I cannot get your code to run - you're missing files `data/log.py`, `data/secret.py`, `data/translations.py` and api file statements `api.plink`, `api.pstats`, `api.sstats`, `api.rsstats` as well as a database structure. Or do you just want advice on what you've posted thus far?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:25:53.810",
"Id": "419743",
"Score": "0",
"body": "Update: I Updated and included all files needed to run this project. Sorry didn't thought about that running the project might be interesting aswell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:39:10.457",
"Id": "419744",
"Score": "0",
"body": "@C.Harley Okay I should've included everything now, wanted to reduce the length of the question but it makes sense to be able to run the project. The Project has been updated by after I posted it here hence I changed everything posted in the question. I'm looking for general `do not do`s aswell as hints for improvements. Just a general Idea how `okayish` the projects state is and what would need improvement and what would need dire improvement."
}
] | [
{
"body": "<p>Thanks for the updates. First things first, when writing in a new language, it's best to learn what the standard for code formatting is, and Python has PEP8 and snake_case. I recommend learning them and conforming to that standard.</p>\n\n<p><strong>log.py</strong> - there's a standard logging package that comes with Python which can be used instead of rolling your own - and in main.py I see you import and instantiate it, but you use your own logger. Recommend spending a few mins reading the logging help pages.</p>\n\n<p>At the top of each file you write <code>## imports ... ##</code> (or a derivative of) - you don't need to make a comment for what your code already states. Only use comments to explain why, not how - that's for the code to explain.</p>\n\n<p>As for the imports, the method you use should be the newer Python3 style - <code>from package import class</code> (or method). You can take advantage of relative imports as well, which are imports from the files point of view. For instance, in <code>dbcontext.py</code> you have <code>from data.classes import Config, ...</code> in my IDE, I change this into <code>from .classes import Config, ...</code>. Have a look at the help pages about relative imports, and understand where you're executing your code from, everything should import from that dir tree.</p>\n\n<p><strong>main.py</strong> most of the code there looks discord specific but as mentioned, update the logging to use Python's logging package. You're missing an entry point <code>if __name__ == \"__main__\":</code> - always use this as it helps to point out where your code execution begins, and if you use packages that utilise reflection on your code, it will start running it instead of creating the objects for reflection.</p>\n\n<p><strong>api.py</strong> You create a class for what is a data structure. Here's a good tutorial on when to use classes - <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=o9pEzgHorH0</a> \"Stop Writing Classes\", quite an amusing watch and can improve your coding skills. Most likely the API only needs a dictionary for these definitions, and you can create that inside <code>main.py</code> (or going all the way, extract them out into an .ini and use ConfigParser - for proper separation and conform to the Open/Close Principle).</p>\n\n<p><strong>secret.py</strong> same as api.py<br>\n<strong>translations.py</strong> I'm not sure about this static inheritance overwriting the variables, I'm sure there's a cleaner way to do this, but <em>shrug</em> okay. Simple is fine too.</p>\n\n<p><strong>classes.py</strong> If you're using an <code>if</code> which will return either of two states, use a ternary. Also, 0 is nothing/false in Python - you can use a simple <code>if</code> check. To give an example of both suggestions:</p>\n\n<pre><code>@property\ndef avgFrags(self):\n if self.battles == 0:\n return 0\n return round(self.frags / self.battles, 2)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>@property\ndef average_frags(self):\n return round(self.frags / self.battles, 2) if self.battles else 0\n</code></pre>\n\n<p>You can see that I renamed 'AvgFrags' to 'average_frags' - remember to name your variables/classes/method fully to make the intention clear. I'm not suggesting you go verbose - something like 'calculate_the_average_frags' would be excessive (<em>I'm sure you know I what I mean</em>). </p>\n\n<p><strong>dbcontext.py</strong> The first function is connecting to the database, which is an expensive procedure in terms of time, especially when you're doing it hundreds of times. You should move the instantiation of the db object into your <code>__main__</code> and pass that when necessary into functions. Your connection string is verbose too - use unpacking to make this simple. For example:</p>\n\n<pre><code>def connect():\n ''' Returns the MySQL connection '''\n mydb = mysql.connector.connect(\n host=Secret.dbAddr, user=Secret.dbUser, passwd=Secret.dbPwd, database=Secret.dbName)\n return mydb\n</code></pre>\n\n<p>(you also don't need a comment, it's obvious what it's doing) becomes (when your kwargs are named the same):</p>\n\n<pre><code>def connect():\n return mysql.connector.connect(**Secret)\n</code></pre>\n\n<p>Further down, you're using fetchone() which is expensive too - the database will hold all the results in memory and maintain a thread with your script whilst you step through each answer. When you're writing to a database, if the dbadmin hasn't configured row locking properly (perhaps the db doesn't support it) - your loop can block other scripts from updating the table, a real traffic jam begins to pile up.<br>\nRecommend to use <code>fetchall()</code> and process the rows into a list of dictionaries. See here for some code: <a href=\"https://codereview.stackexchange.com/questions/216769/identifying-tcp-and-udp-streams-using-a-database-populated-from-a-sniffer-tool/\">Identifying TCP and UDP streams using a database populated from a sniffer tool</a><br>\nFinally - all the functions in dbcontext really do look the same (DRY: Don't Repeat Yourself). It might be worth writing a basic select() and update() function which accepts (sql, values) and executes those so you remove the duplicated code from every function in this package file. </p>\n\n<p><strong>getstats.py</strong> I notice in the functions that the start is the same again (DRY) - it gets the URL for a type of stats, with the authentication data and some specific IDs - this is more DRY which we can replace.<br>\nWe could create a helper which would handle the connection, authentication and query process, returning the result. It would be something like query_api(**kwargs) - where your function would unpack the named keyword arguments to determine what values are appropriate - like you have here:</p>\n\n<pre><code>if ship is not None:\n url = api.sstats.format(\n reg=config.region, wgapi=Secret.api, accountID=player.id, shipID=ship.id)\nelse:\n url = api.pstats.format(\n reg=config.region, wgapi=Secret.api, accountID=player.id)\n</code></pre>\n\n<p>It would handle error responses and logging, and return the HTML response code (200,404, etc) to the caller along with any data which is necessary (such as your statistics function). Something like:</p>\n\n<pre><code>return status_code, meta_data\n</code></pre>\n\n<p><strong>updatedb.py</strong> Your <code>GetShipsByType</code> function has a magic string in it (the URL). This violates the Open/Close Principle (from the SOLID Principles), which states code should be open for extension but closed for modification - if your URL changes, you'd need to go back into the code to edit the URL before you can make it work again.<br>\nIf you accidentally made an error, or unintentionally removed a line of code - do you have a backup or a git commit you can roll back? It's best to keep URLs and other magic numbers/strings outside the code, preferably in an .ini file.</p>\n\n<p>To pick on the function a little more - you have some code which writes a dot to the screen when a new ship is being loaded. The Single Responsibility Principle states a function should do one, and only one thing.<br>\nIf there's a problem writing that dot to the console (perhaps you're running a detached graphical session where there is no frame buffer/GDI - I've had that experience before) and it crashes the entire script?<br>\nI'm being a little dramatic with my point, but I'm sure you get what I mean. Hunting down bugs is much easier when a single function with 4 or 5 lines of code fails - then you only have to fix a single line (and not a chunk of code around the bug) and run your local tests again before committing/pushing into UAT.</p>\n\n<p>You have a comment <code># Main</code> - which implies you're running updateDB.py - remember to include the entry point if you are executing this package.</p>\n\n<pre><code>except:\n print(\"error\")\n sys.exit(1)\n</code></pre>\n\n<p>When using Try/Catch - always catch the exception (run your code to see what exception it raises, and put that into the catch), that way other exceptions do not fail silently. Never let your code fail silently, even if it means adding another 10 lines to handle it. Either handle it or raise/throw it higher.<br>\nUsing sys.exit(error_code) is only needed if your software which is executing this script is checking the return level/errorlevel status. If you don't need it, log the error and raise a <code>RuntimeError(\"Could not load data file correctly\")</code> instead of exiting silently, forcing the operator to scratch their head and mabye run <code>echo $?</code> or <code>echo %ERRORLEVEL%</code> to find out the status code, then look into your code for what that status code means? </p>\n\n<p>That's about all I can come up with this short review - I hope this was helpful?<br>\nGood Luck and keep up the coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T19:12:02.997",
"Id": "419776",
"Score": "0",
"body": "Thank you very much for the suggestions. The only reason I exported the `secret.py` is that I actually have provided an `secret_template.py`, this is done to avoid commiting the api keys etc to git. What would be a common solution to avoid posting passwords and API keys to git, I'm planing to publish this project on git once I feel like it's \"ready\" so people can host it themselfs. Have a .ini file where they're written along with the API etc.?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:40:54.717",
"Id": "419803",
"Score": "0",
"body": "In my experience we usually have something like `secret_template.py` and a comment stating \"copy this to `secret.py` to make it work\" - with a .gitignore entry so `secret.py` is not committed/pushed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:38:06.197",
"Id": "419836",
"Score": "0",
"body": "Okay so exactly the way I'm handling it at the moment."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:59:34.503",
"Id": "217026",
"ParentId": "216457",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217026",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T01:36:59.413",
"Id": "216457",
"Score": "8",
"Tags": [
"python"
],
"Title": "Discord Bot querying an External API"
} | 216457 |
<p>I wrote the following code for Radix Sort algorithm for number sorting. Any review is highly appreciated. </p>
<blockquote>
<p>You can also view and run/test the code here <a href="http://cpp.sh/7t4uk" rel="nofollow noreferrer">Radix Sort</a></p>
</blockquote>
<pre><code>#include<iostream>
using namespace std;
int getNumberAtPosition(int num,int position){
return (num/position)%10;
}
void radixSort(int array[],int length){
int sizeOfEachBucket = length;
int numberOfBuckets = 10;
int buckets[10][sizeOfEachBucket];
int large = 0;
int maxPasses = 0;
//finding largest number from array
for(int i=0; i<length; i++){
if(array[i]>large){
large = array[i];
}
}
//finding the number of passes
while(large != 0){
maxPasses++;
large = large/10;
}
cout<<"Max passes ="<<maxPasses<<endl;
int position = 1;
int bucketIndex = 0;
int newListIndex = 0;
int arrayLengths[10];
for(int i=0; i<maxPasses; i++){
//cout<<"i ="<<i<<endl;
for(int k=0; k<=9; k++){
//cout<<"k ="<<k<<endl;
bucketIndex = 0;
for(int j=0; j<length; j++){
if(k==getNumberAtPosition(array[j],position)){
buckets[k][bucketIndex] = array[j];
bucketIndex++;
}
}
arrayLengths[k] = bucketIndex;
}
position = position*10;
int newArrayIndex = 0;
for(int k=0; k<=9; k++){
//cout<<"k ="<<k<<endl;
bucketIndex = 0;
for(int x=0; x<arrayLengths[k];x++){
array[newArrayIndex] = buckets[k][x];
newArrayIndex++;
}
}
}
for(int i=0; i<length; i++){
cout<<array[i]<<"\t";
}
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>First things first, don't use <code>using namespace std</code> in header files, where your radix sort implementation should be. Besides, convenience isn't a valid excuse when the only thing you import from <code>std</code> is <code>cout</code>: just type <code>std::cout</code> and you're done.</p></li>\n<li><p>One liner functions are often useless and noisy: you need to refer to the implementation to know exactly what they do, so they don't make the code more readable, and you have to come up with a name, which is not always easy. In the case of <code>getNumberAtPosition</code>, for instance, it's impossible to tell from the name if the position is meant for the most or least significant digit, and both are equally likely in a radix sort algorithm.</p></li>\n<li><p>everything that isn't meant to change should be <code>const</code>. The only place where it isn't idiomatic is in function signature, where you often don't tag built-in type arguments passed by value as const. </p></li>\n<li><p>Also, don't alias variables: <code>length</code> is only used to define <code>sizeOfEachBucket</code>, that's two names to track down instead of one.</p></li>\n<li><p>Use the standard library: there may not be many things inside compared to other languages, but what's inside is very well implemented. It will also make your code more concise and expressive. For instance, the largest element in a <code>[first, last)</code> sequence is the result of <code>std::max_element(first, last)</code> (<code>std::max_element</code> resides in <code><algorithm></code>). Using standard containers is also a statement: a constant size array will be a <code>std::array</code>, whereas a variable-size one will be a <code>std::vector</code>.</p></li>\n<li><p>Avoid <em>naked loops</em>: by that I mean loops like <code>for (int i = 0; i < z; ++i)</code>. The nested ones are particularly difficult to read, with all those meaningless one-letter variable names. Use either <em>range based for loops</em> when you iterate over the whole container (e.g: <code>for (auto item : vector)</code>) or named algorithm when your loop has a standardly implemented purpose (<code>std::for_each</code>, <code>std::copy</code>, etc.).</p></li>\n<li><p>When implementing your own algorithms, try to use an stl-like interface: iterators are preferable because they abstract the concrete container-type. Your algorithm won't work on an <code>std::list</code> although it very well could be (radix sort doesn't rely on random access like quick sort does).</p></li>\n</ul>\n\n<p>Here's an example of better-looking (though not thoroughly tested) code:</p>\n\n<pre><code>#include <algorithm>\n#include <vector>\n#include <array>\n#include <cmath>\n\ntemplate <typename Iterator>\nvoid radix_sort(Iterator first, Iterator last) {\n const int max_divisor = std::pow(10, std::log10(*std::max_element(first, last)));\n for (int divisor = 1; divisor < max_divisor; divisor *= 10) {\n std::array<std::vector<int>, 10> buckets;\n std::for_each(first, last, [&buckets, divisor](auto i) {\n buckets[(i / divisor) % 10].push_back(i);\n });\n auto out = first;\n for (const auto& bucket : buckets) {\n out = std::copy(bucket.begin(), bucket.end(), out);\n }\n }\n} \n</code></pre>\n\n<p><strong>EDIT</strong>: since the algorithm exposed in the question relies on decimal digits, I also formulated a base-10 based algorithm. But thinking back about this, I feel like my answer isn't complete if I don't precise that a base-two approach is more optimal (and more generally used as far as I know). Why is that?</p>\n\n<ul>\n<li><p>because binary arithmetic is easier for a computer (not a very strong reason since decimal arithmetic is often optimized into binary arithmetic by the compiler);</p></li>\n<li><p>because -and that's a much stronger reason- you can the rely on a very well-known algorithm to distribute your number between buckets, an algorithm that moreover does it in place, thus without any memory allocation; </p></li>\n<li><p>by the way, that algorithm is <code>std::stable_partition</code></p></li>\n</ul>\n\n<p>And here is a sample:</p>\n\n<pre><code>template <typename Iterator>\nvoid binary_radix_sort(Iterator first, Iterator last) {\n using integer_type = std::decay_t<decltype(*first)>;\n bool finished = false;\n for (integer_type mask = 1; !finished; mask <<= 1) {\n finished = true;\n std::stable_partition(first, last, [mask, &finished](auto i) {\n if (mask < i) finished = false;\n return !(mask & i);\n });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:34:08.847",
"Id": "418830",
"Score": "0",
"body": "Thanks for such a valuable advice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T18:12:46.437",
"Id": "418832",
"Score": "4",
"body": "I have to strongly disagree with #2. One line functions often provide important abstractions that are invaluable and significantly reduce cognitive load"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:27:59.443",
"Id": "216464",
"ParentId": "216460",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216464",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T06:11:57.860",
"Id": "216460",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"sorting"
],
"Title": "Implementation of Radix Sort algorithm for sorting integers in c++"
} | 216460 |
<p>The game is hosted <a href="https://merkur0.github.io/Local-Multiplayer-Flappy-Bird/" rel="nofollow noreferrer">here</a>.</p>
<p><a href="https://github.com/merkur0/Local-Multiplayer-Flappy-Bird" rel="nofollow noreferrer">GitHub repo</a></p>
<p>This is my first Phaser 3 game/project and I'm still pretty new to Javascript so I'm sure there are many things I could be doing better. The number 1 thing that I would like to improve about my code is the performance. Then code effectiveness and readability, but performance is the top priority.</p>
<p><strong>Your feedback is valuable even if you have no experience with PhaserJS whatsoever</strong>, because a lot of things that I could probably be doing better only have to do with pure Javascript.</p>
<p>My JS code:</p>
<pre><code>const width = window.innerWidth;
const height = window.innerHeight;
let hiScore = localStorage['hiScore'] || 0;
const config = {
width: width,
height: height,
backgroundColor: 0x50C875,
scene: {
preload,
create,
update,
},
physics: {
default: 'arcade',
arcade: {
gravity: { y: 50 },
},
}
}
const gameState = {
gameOver: false,
score: 0,
scoreText: false,
player1AnimationStage: 0,
player2AnimationStage: 0,
player1SpriteSheet: ['upflap', 'midflap', 'downflap',],
player2SpriteSheet: ['player2_upflap', 'player2_midflap', 'player2_downflap',],
player1Y: (height / 2 * 0.5),
player2Y: (height / 2 * 0.5),
secondPlayerSpawned: false,
player1Dead: false,
player2Dead: false,
}
const game = new Phaser.Game(config, 'root');
game.clearBeforeRender = false;
function preload() {
this.load.image('background', 'assets/images/background.png');
this.load.image('ground', 'assets/images/ground.png');
this.load.image('pipe', 'assets/images/pipe.png');
this.load.image('upflap', 'assets/images/upflap.png');
this.load.image('midflap', 'assets/images/midflap.png');
this.load.image('downflap', 'assets/images/downflap.png');
this.load.image('player2_upflap', 'assets/images/player2_upflap.png');
this.load.image('player2_midflap', 'assets/images/player2_midflap.png');
this.load.image('player2_downflap', 'assets/images/player2_downflap.png');
this.load.audio('hit', 'assets/audio/hit.mp3');
this.load.audio('point', 'assets/audio/point.mp3');
this.load.audio('wing', 'assets/audio/wing.mp3');
this.load.audio('die', 'assets/audio/die.mp3');
}
function create() {
gameState.hitSound = this.sound.add('hit');
gameState.pointSound = this.sound.add('point');
gameState.wingSound = this.sound.add('wing');
gameState.dieSound = this.sound.add('die');
// Hide Score Table
document.getElementById('hiScoreTable').style.display = 'none';
const colliderTile = this.physics.add.staticGroup();
gameState.colliderTile = colliderTile.create(50, 0, 'pipe').setScale(0.1, 80).refreshBody();
gameState.colliderTile2 = colliderTile.create(1, 0, 'pipe').setScale(0, 80).refreshBody();
gameState.bgTile = this.add.tileSprite(0, height, width, height, 'background').setScale(2);
gameState.ground = this.physics.add.staticGroup();
gameState.ground.create(0, height, 'ground').setScale((8.6, 1)).refreshBody();
gameState.groundTile = this.add.tileSprite(0, height, width, null, 'ground').setScale(8.6, 1);
gameState.gameOver = false;
gameState.player1 = this.physics.add.sprite(100, gameState.player1Y, 'midflap').setScale(2);
gameState.player1.body.acceleration.y = 1500;
gameState.pipes = this.physics.add.group();
gameState.scoreText = this.add.text((width / 2) - 100, 100, `Score: ${gameState.score}`, { fontSize: '40px', fontWeight: 'bold', });
gameState.secondPlayerSpawned = false;
// Layers
gameState.groundTile.setDepth(1);
gameState.pipes.setDepth(2);
gameState.scoreText.setDepth(3);
gameState.playSoundMethod = (sound) => {
this.sound.play(sound);
}
const addRowOfPipes = () => {
const hole = Math.floor(Math.random() * 7) + 3;
for (let i = 0; i < 17; i++) {
if (i !== hole && i !== hole + 1 && i !== hole + 2) {
let pipe = gameState.pipes.create(width - 60, i * 50 + 25, 'pipe');
pipe.body.setVelocityX(-200);
pipe.outOfBoundsKill = true;
pipe.body.allowGravity = false;
pipe.body.immovable = true;
this.physics.add.collider(pipe, gameState.colliderTile2, (item) => {
if (i === 16) {
gameState.pointSound.play();
gameState.score++;
if (gameState.scoreText)
gameState.scoreText.destroy();
gameState.scoreText = this.add.text((width / 2) - 100, 100, `Score: ${gameState.score}`, { fontSize: '40px', fontWeight: 'bold', });
}
item.destroy();
})
if (i === 16) {
pipe.onWorldBounds = true;
}
}
}
}
gameState.fallDown = () => {
if (gameState.player1Dead) {
gameState.player1.y += 5;
if (gameState.player1.y > height)
gameState.player1fallDownCaller.destroy();
}
if (gameState.player2Dead) {
gameState.player2.y += 5;
if (gameState.player2.y > height)
gameState.player2fallDownCaller.destroy();
}
}
addRowOfPipes();
gameState.gameOverMethod = () => {
this.physics.pause();
gameState.scoreText.destroy();
if (gameState.score > hiScore)
localStorage['hiScore'] = gameState.score;
hiScore = localStorage.getItem('hiScore');
document.getElementById('hiScoreTable').style.display = 'initial';
document.getElementById('score').innerHTML = gameState.score;
document.getElementById('hiScore').innerHTML = hiScore;
birdAnimation.destroy();
gameState.gameOver = true;
this.add.text();
pipeGen.destroy();
gameState.player1.setVelocityY(150);
gameState.player1.setVelocityX(0);
if (gameState.secondPlayerSpawned) {
gameState.player2.setVelocityY(150);
gameState.player2.setVelocityX(0);
}
if (gameState.score > 10) {
if (gameState.score > 20) {
if (gameState.score > 30) {
displayMedal('gold');
}
displayMedal('silver');
}
displayMedal('bronze');
}
function displayMedal(medal) {
let medalColor;
document.getElementById('medalContainer').style.display = 'initial';
switch (medal) {
case 'bronze':
medalColor = '#cd7f32';
break;
case 'silver':
medalColor = '#c0c0c0';
break;
case 'gold':
medalColor = '#ccac00';
break;
}
document.getElementById('medal').style.backgroundColor = medalColor;
}
gameState.score = 0;
}
gameState.fallDownCaller = (player) => {
if (player === 'player1') {
gameState.player1fallDownCaller = this.time.addEvent({
delay: 10,
callback: gameState.fallDown,
loop: true,
})
} else {
gameState.player2fallDownCaller = this.time.addEvent({
delay: 10,
callback: gameState.fallDown,
loop: true,
})
}
}
gameState.collisionMethod = (player) => {
if (player === 'player1') {
gameState.player1Dead = true;
if ((gameState.player1Dead && gameState.player2Dead) || !gameState.secondPlayerSpawned) {
gameState.gameOverMethod();
}
gameState.fallDownCaller(player);
} else {
gameState.player2Dead = true;
if (gameState.player1Dead && gameState.player2Dead) {
gameState.gameOverMethod();
}
gameState.fallDownCaller(player);
}
}
// Colliders
gameState.player1.setCollideWorldBounds(true);
this.physics.add.collider(gameState.player1, gameState.ground, () => {
gameState.dieSound.play();
gameState.collisionMethod('player1')
});
this.physics.add.collider(gameState.player1, gameState.pipes, () => {
gameState.hitSound.play();
gameState.collisionMethod('player1');
});
// Initialize input keys
gameState.cursors = this.input.keyboard.createCursorKeys();
const pipeGen = this.time.addEvent({
callback: addRowOfPipes,
delay: 1500,
callbackScope: this,
loop: true,
})
// Animation
const animateBird = () => {
gameState.player1AnimationStage++;
if (gameState.player1AnimationStage > 2)
gameState.player1AnimationStage = 0;
if (gameState.secondPlayerSpawned) {
gameState.player2AnimationStage++;
if (gameState.player2AnimationStage > 2)
gameState.player2AnimationStage = 0;
}
gameState.player1.setTexture(gameState.player1SpriteSheet[gameState.player1AnimationStage]);
if (gameState.secondPlayerSpawned)
gameState.player2.setTexture(gameState.player2SpriteSheet[gameState.player2AnimationStage]);
}
const birdAnimation = this.time.addEvent({
callback: animateBird,
delay: 100,
callbackScope: this,
loop: true,
})
}
function update() {
if (!gameState.gameOver) {
gameState.bgTile.tilePositionX += 0.1;
gameState.groundTile.tilePositionX += 1;
}
// Press spacebar to fly up
if (gameState.cursors.space.isDown) {
if (gameState.gameOver) {
this.scene.restart();
} else {
gameState.wingSound.play();
gameState.player1.setVelocityY(-350);
}
}
const spawnSecondPlayer = () => {
gameState.secondPlayerSpawned = true;
gameState.player2 = this.physics.add.sprite(100, gameState.player2Y, 'player2_midflap').setScale(2);
gameState.player2.body.acceleration.y = 1500;
gameState.player2.setCollideWorldBounds(true);
this.physics.add.collider(gameState.player2, gameState.ground, () => {
gameState.dieSound.play();
gameState.collisionMethod('player2')
});
this.physics.add.collider(gameState.player2, gameState.pipes, () => {
gameState.hitSound.play();
gameState.collisionMethod('player2');
});
}
if (!gameState.secondPlayerSpawned) {
if (gameState.cursors.shift.isDown) {
spawnSecondPlayer();
}
} else {
if (gameState.cursors.shift.isDown) {
if (gameState.gameOver) {
this.scene.restart();
} else {
gameState.player2.setVelocityY(-350);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>What if you want to add the functionality for up to 3 players?</p>\n\n<p>You'd have to create a 'player3AnimationStage, player3SpriteSheet etc. It's also inside the 'gameState', which arguably makes sense, but still could be separated into it's own class.</p>\n\n<p>For example:</p>\n\n<pre><code>class Player\n{\n constructor(spriteSheet, animationStage)\n {\n this.SpriteSheet = spriteSheet;\n this.AnimationStage = animationStage;\n }\n}\n\nconst gameState = {\n player1: new Player(...);\n player2: new Player(...);\n</code></pre>\n\n<p>Or better yet, have an array of Players. Try to code your game so that it does not matter how many players there are. (E.g iterate through the list of players).</p>\n\n<p>Your colours could be made into an ENUM, or a class with score, colorName, colorCode.</p>\n\n<p>I'd suggest declaring some variables at the top, to make maintenance easier.\nSuch as key div elements (hiScoreTable). (Or even just the ids of the elements).\nImages.</p>\n\n<p>Try to avoid 'maigc numbers' by using named variables. For example, what is '17' here?:</p>\n\n<pre><code>for (let i = 0; i < 17; i++) \n</code></pre>\n\n<p>Avoiding 'magicNumbers' also decreases code duplication and makes maintenance easier. For example, to increase player speed currently we'd have to change it in at least 2 places. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:17:58.107",
"Id": "216488",
"ParentId": "216462",
"Score": "7"
}
},
{
"body": "<p>This code makes great use of the keywords <code>let</code> and <code>const</code> where appropriate. Some of the functions are a little on the long side, so those could potentially be split up into smaller functions. The repeated calls to functions like <code>this.load.image</code> could be done in a loop over arrays if pre-defined arrays were setup.</p>\n\n<hr>\n\n<p>Did you consider using element references, which was mentioned in <a href=\"https://codereview.stackexchange.com/a/212334/120114\">blindman’s answer to your previous question <em>Tip Calculator in pure JS</em></a>?</p>\n\n<hr>\n\n<p>In the method <code>gameState.collisionMethod()</code> there is a line in both cases that could be pulled outside of the conditional blocks: <code>gameState.fallDownCaller(player);</code></p>\n\n<hr>\n\n<p>In the method <code>gameState.fallDownCaller()</code> the object passed to <code>this.time.adddEvent()</code> is the same and could be declared in one spot above (or else in a separate function). </p>\n\n<hr>\n\n<p>Instead of using a <code>switch</code> statement in <code>displayMedal()</code>, a mapping of color names to hex values could be used. </p>\n\n<p>For example:</p>\n\n<pre><code>const colorToHexMap = {\n bronze: '#cd7f32',\n silver: '#c0c0c0',\n gold: '#ccac00',\n};\n</code></pre>\n\n<p>Then use it with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"nofollow noreferrer\">in</a> operator:</p>\n\n<pre><code>if (color in colorToHexMap) {\n medalColor = colorToHexMap[color];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T21:01:13.110",
"Id": "219674",
"ParentId": "216462",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216488",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:18:58.503",
"Id": "216462",
"Score": "5",
"Tags": [
"javascript",
"game",
"ecmascript-6",
"phaser.io"
],
"Title": "Flappy Bird game supporting local multiplayer of up to 2 players"
} | 216462 |
<p>I'm implementing the singly linked list data structure and functions to work with it. In particular I'm concerned about prepending and removing nodes. Currently I defined linked list as follows:</p>
<pre><code>typedef struct string_list_node{
int id;
const char *value;
struct string_list_node *next;
} string_list_node_t;
string_list_node_t **string_list_alloc(int id, const char *value){
string_list_node_t *string_list_ptr = malloc(sizeof(*string_list_ptr));
string_list_node_t **list = malloc(sizeof(*list));
string_list_ptr -> id = id;
string_list_ptr -> value = value;
string_list_ptr -> next = NULL;
*list = string_list_ptr;
return list;
}
</code></pre>
<p>The thing I'm concerned about is the following implementation of <code>prepend</code> and <code>delete_first_by_id</code> functions:</p>
<pre><code>void prepend(int id, const char *value, string_list_node_t ** list_ptr){
string_list_node_t *node_ptr = *list_ptr;
string_list_node_t *prepended_node = malloc(sizeof(*prepended_node));
prepended_node -> id = id;
prepended_node -> value = value;
prepended_node -> next = node_ptr;
*list_ptr = prepended_node;
}
//returns 0 if not found, 1 if found and list changed
int delete_first_by_id(string_list_node_t **source,
int id,
string_list_node_t ** deleted_value_out){
string_list_node_t *prev = NULL;
string_list_node_t *current = *source;
while(current && current -> id != id){
prev = current;
current = current -> next;
}
if(current){
if(!prev){
*source = current -> next;
*deleted_value_out = current;
} else {
*deleted_value_out = current;
prev -> next = current -> next;
}
return 1;
} else {
return 0;
}
}
</code></pre>
<p>Is this code looks ok in terms of sort of common C style? Is the behavior of the code undefined? I created a live example of usage here:</p>
<p><a href="https://coliru.stacked-crooked.com/a/48afe000bc380b4e" rel="nofollow noreferrer"><strong><em>LIVE DEMO</em></strong></a></p>
| [] | [
{
"body": "<h1>Style</h1>\n\n<ul>\n<li>POSIX reserves type names ending with <code>_t</code>. This means that in the future, standard c may create standardized types with the same name as <code>string_list_node_t</code>, and your code would not compile. See <a href=\"https://stackoverflow.com/a/12727104\">https://stackoverflow.com/a/12727104</a> for more details. A common alternative is to use upper camel-case for typedefs, e.g. <code>StringListNode</code>.</li>\n<li>There is a strong case against typedefing structures. The major benefit of this is to save keystrokes, but it removes important information available to programmers. To see some opinions on this, <a href=\"https://stackoverflow.com/q/252780/4458609\">here is another stack overflow question</a>.</li>\n<li>I have never seen code that has spaces between <code>-></code> when accessing struct members. Just use <code>prepended_node->id</code> instead. You wouldn't write <code>prepended_node . id</code>, would you?</li>\n</ul>\n\n<h1>Code Review</h1>\n\n<h2>Use the bool type</h2>\n\n<p>A boolean type, <code>bool</code>, was introduced in C99. Unless you have really good reasons not to, you should use this for true/false values instead of an integer. This type is found in the <code><stdbool.h></code> header.</p>\n\n<h2>Multi-use functions</h2>\n\n<p>Finding nodes in a linked list is a relatively common procedure. If your list supports lookup, it is better to have a separate function that can handle all of your lookup cases:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static void _find_node_by_id(int id, str_node *head, \n str_node **prev, str_node **node) {\n *prev = NULL;\n *node = head;\n while(node && (*node)->id != id) {\n *prev = *node;\n *node = (*node)->next;\n }\n}\n</code></pre>\n\n<p>This way, you can use the search implementation in multiple places:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>bool delete_first_by_id(string_list_node_t **source,\n int id,\n string_list_node_t ** deleted_value_out){\n string_list_node_t *prev = NULL;\n string_list_node_t *current = *source;\n\n _find_node_by_id(id, *source, &prev, &current);\n\n if(current){\n if(!prev){\n *source = current -> next;\n *deleted_value_out = current;\n } else {\n *deleted_value_out = current;\n prev -> next = current -> next;\n }\n return true;\n } else {\n return false;\n }\n}\n\nbool find_node_by_id(str_node *head, int id, str_node **return_ptr) {\n string_list_node_t *prev = NULL;\n *ret_ptr = head;\n\n _find_node_by_id(id, *source, &prev, return_ptr);\n\n if(*return_ptr) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>Note that I didn't test any of this code.</p>\n\n<h2>Try to avoid pointers to pointers</h2>\n\n<p>More specifically, don't use them when it's not necessary. There isn't a great reason for <code>string_list_alloc</code> to return <code>string_list_node_t **</code>. It makes much more sense to just return a pointer to the node. This does two things for you:</p>\n\n<ol>\n<li>Non-destructive operations don't need a pointer to a pointer, so it avoids either \nyou or the function from needing to deference them.</li>\n<li>It makes destructive operations more explicit, as you need to take the address of \nthe pointer to use the function. </li>\n</ol>\n\n<h1>Edit addressing question in comments:</h1>\n\n<blockquote>\n <p>In case I want to preserve it across different function calls I should not allocate it on the stack shouldn't I?</p>\n</blockquote>\n\n<p>There seems to be some confusion on how malloced memory and pointers work, especially in the context of function return values.</p>\n\n<p>First, remember that a variable holds a value. In this case, the variable contains a memory location, whose value could be any integer greater than or equal to 0. We really don't care about the variable itself, we care about its value.</p>\n\n<p>Second, lets talk about return values. When you return a value from a function, it is copied so that the code calling the function has access to it. Here's a little program that illustrates this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nstruct test_struct {\n int a;\n int b;\n};\n\nstruct test_struct return_struct() {\n struct test_struct test = { .a = 1, .b = 2 };\n printf(\"The pointer in the function is: %p\\n\", &test);\n return test;\n}\n\nint main(void) {\n struct test_struct main_struct;\n main_struct = return_struct();\n printf(\"The pointer in main is: %p\\n\", &main_struct);\n return 0;\n}\n</code></pre>\n\n<p>On my system, this program prints out</p>\n\n<pre><code>The pointer in the function is: 0x7fffef30f048\nThe pointer in main is: 0x7fffef30f070\n</code></pre>\n\n<p>Notice that the addresses are different. Since the value being returned is copied, we don't need to worry about manually manipulating memory, as the compiler takes care of that for us. It works the same way when returning a pointer from function: the value we care about is copied, so that we can access it when the variable that originally held it no longer exists.</p>\n\n<p>Lets look at this in a different context.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// what your alloc function is doing:\nint *malloc_add(int a, int b) {\n int *result = malloc(sizeof(result));\n *result = a + b;\n return result;\n}\n// what it should be doing:\nint add(int a, int b) {\n int result;\n result = a + b;\n return result;\n}\n</code></pre>\n\n<p>While we get the value we want in both cases, in the first we need to perform two extra steps: we need to dereference the pointer to get the value, and we need to free the memory allocated on the heap. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T06:12:24.407",
"Id": "418870",
"Score": "0",
"body": "Thanks for the review. But I have one more question about `string_list_node_t **`. In case I want to preserve it across different function calls I should not allocate it on the stack shouldn't I?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:52:43.360",
"Id": "216501",
"ParentId": "216465",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216501",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T09:33:47.880",
"Id": "216465",
"Score": "2",
"Tags": [
"c",
"linked-list"
],
"Title": "Removing node from a linked list"
} | 216465 |
<p>I have read the book "C++ concurrency in action" and understood the thread_pool implementation. I have changed a few things according to my project requirements. </p>
<p>I have used <code>std::variant</code> to support heterogeneous <code>work-queue</code> to store different task arriving on a <code>epoll-event</code> loop. Currently In my project I have only two different types of task arrive on the epoll loop. Those are <code>TaskECB</code> and <code>TaskRPCB</code>. I have created classes for both of them and overloaded the <code>operator()</code></p>
<pre><code>#define THREAD_POOL_SIZE 100
std::map<std::string,std::string> tidToTname;
template<typename T>
class threadSafeQueue {
private:
mutable std::mutex mut;
std::queue<std::shared_ptr<T>> taskQueue; /* task as pushed here and
task are processed in FIFO
style */
std::condition_variable dataCond; /* used to protect the queue */
public:
threadSafeQueue(){}
void waitAndPop(T& value); /* wait untill task is not available in
the queue */
std::shared_ptr<T> waitAndPop();/* same but returns a shared pointer */
bool tryPop(T& value); /* does not block */
std::shared_ptr<T> tryPop(); /* does not block and returns a pointer*/
void Push(T newData);
bool Empty() const; /* check if queue is empty or not */
void notifyAllThreads(); /* notify all the waiting threads
used in Thpool decallocation */
};
template<typename T>
void threadSafeQueue<T>::notifyAllThreads() {
dataCond.notify_all();
}
template<typename T>
void threadSafeQueue<T>::waitAndPop(T& value) {
std::unique_lock<std::mutex> lk(mut);
dataCond.wait(lk,[this](){return !taskQueue.empty();});
value = std::move(*taskQueue.front());
taskQueue.pop();
}
template<typename T>
std::shared_ptr<T> threadSafeQueue<T>::waitAndPop() {
std::unique_lock<std::mutex> lk(mut);
dataCond.wait(lk,[this](){return !taskQueue.empty();});
std::shared_ptr<T> res = taskQueue.front();
taskQueue.pop();
return res;
}
template<typename T>
bool threadSafeQueue<T>::tryPop(T& value) {
std::lock_guard<std::mutex> lk(mut);
if(taskQueue.empty())
return false;
value = std::move(*taskQueue.front());
taskQueue.pop();
return true;
}
template<typename T>
std::shared_ptr<T> threadSafeQueue<T>::tryPop() {
std::lock_guard<std::mutex> lk(mut);
if(taskQueue.empty())
return std::shared_ptr<T>(); /* return nullptr */
std::shared_ptr<T> res = taskQueue.front();
taskQueue.pop();
return res;
}
template<typename T>
void threadSafeQueue<T>::Push(T newData) { /* TODO: size check before pushing */
std::shared_ptr<T> data(std::make_shared<T>(std::move(newData)));
/* construct the object before lock*/
std::lock_guard<std::mutex> lk(mut);
taskQueue.push(data);
dataCond.notify_one();
}
template<typename T>
bool threadSafeQueue<T>::Empty() const {
std::lock_guard<std::mutex> lk(mut);
return taskQueue.empty();
}
class TaskRPCB { /* Task RecvAndProcessCallbacks */
private:
int len;
uint fdId;
int streamId;
void* msgBlob;
std::function<void(void*,int,uint,int)> func;
public:
TaskRPCB(std::function<void(void*,int,uint,int)>&f , void* msgBlob,int len,
uint fdId, int streamId) {
this->func = f;
this->msgBlob = msgBlob;
this->len = len;
this->fdId = fdId;
this->streamId = streamId;
}
void operator()() {
higLog("%s","TaskRPCB function is executing...");
func(msgBlob,len,fdId,streamId);
}
};
class TaskECB { /* Task eventCallBack */
private:
std::function<void(void)> func;
public:
TaskECB(std::function<void(void)>&f) : func(f) {}
void operator()() {
higLog("%s","TaskECB function is executing...");
func();
}
};
typedef variant<TaskECB,TaskRPCB> taskTypes;
class Thpool {
std::atomic_bool done;
threadSafeQueue<taskTypes> workQ;
std::vector<std::thread> threads;
void workerThread() {
auto tid = std::this_thread::get_id();
std::stringstream ss;
ss << tid;
std::string s = ss.str();
while(!done) {
auto task = workQ.waitAndPop();
if(task != nullptr and !done) {
printf("%s is executing now : ",tidToTname[s].c_str());
if((*task).index() == 0) { // TODO: change 0 and 1 to enums
auto func = get<TaskECB>(*task);
func();
}else if((*task).index() == 1) {
auto func = get<TaskRPCB>(*task);
func();
}
}
}
}
public:
Thpool(): done(false) {
// unsigned const maxThreadCount = std::thread::hardware_concurrency();
unsigned const maxThreadCount = THREAD_POOL_SIZE;
printf("ThreadPool Size = %d",maxThreadCount);
/* save thread names for logging purpose */
std::vector<std::string> tnames;
for(unsigned int i = 0;i<maxThreadCount;i++) {
tnames.push_back("Thread_" + std::to_string(i+1));
}
try { /* exception might arise due to thread creation */
for(unsigned int i = 0;i<maxThreadCount;i++) {
threads.push_back(std::thread(&Thpool::workerThread,this));
/*map this ith threadID to a name Thread_i*/
auto tid = threads[i].get_id();
std::stringstream ss;
ss << tid;
tidToTname[ss.str()] = tnames[i];
}
}catch(...) {
done = true;
throw;
}
}
~Thpool() {
// done = true;
}
template<typename taskType>
void submit(taskType task) {
workQ.Push(task);
}
void deAllocatePool() {
done = true;
workQ.notifyAllThreads();
// unsigned const maxThreadCount = std::thread::hardware_concurrency();
unsigned const maxThreadCount = THREAD_POOL_SIZE;
for(unsigned int i = 0;i<maxThreadCount;) {
if(threads[i].joinable()) {
threads[i].join();
i++; /* go for the next thread in the pool */
}else {
workQ.notifyAllThreads();
}
}
}
};
/*============== Thread Pool code ends ============== */
</code></pre>
<p>How I use this <code>thread_pool</code> ?</p>
<pre><code>Thpool pool;
</code></pre>
<p>Following code will be inserted in required functions. I am showing for the <code>TaskRPCB</code> type task only. </p>
<pre><code>std::function<void(void*,int,uint,int)> func = NFVInstance->CallBackTable[channel];
/* create a task object : members of it :
- the callback function
- msgBlob
- len of the msgBlob
- some other ID
- stream ID on which this message was received
*/
TaskRPCB task(func,msg,rc,fdd.id,streamId);
/* submit this task to the pool.
one of the waiting threads will pick this task
*/
pool.submit(task);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T12:43:51.947",
"Id": "418791",
"Score": "0",
"body": "sorry for mixing tags. I would like to have suggestions regarding thread pool implementation overall and the use of` std:: variant` ? is it ok ? or does it have some performance penalty?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:04:51.437",
"Id": "418796",
"Score": "1",
"body": "I've edited tags to C++17 (since `std::variant` requires that). I hope you get good reviews!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:40:37.493",
"Id": "419118",
"Score": "1",
"body": "`THREAD_POOL_SIZE 100` I hope you are running on some large hardware. The point os a thread pool is that you create a thread for each available processor (or very close to that) then each processor gets new work from the pool without having to switch threads (as that is a relatively expensive operation)."
}
] | [
{
"body": "<p>Naming nits:</p>\n\n<ul>\n<li><p>Why <code>threadSafeQueue</code> instead of <code>ThreadSafeQueue</code>? You CamelCaps all your other class names. Why not this one?</p></li>\n<li><p><code>class TaskECB { /* Task eventCallBack */</code> is a very verbose way of writing <code>class TaskEventCallback {</code>. If you have to spell it out in a comment anyway, just spell it out <em>in the code</em>. Your readers will thank you.</p></li>\n<li><p><code>bool threadSafeQueue<T>::Empty() const</code>: Since you're diverging from the traditional STL naming convention anyway (<code>Empty</code> is not <code>empty</code>), I recommend prefixing boolean accessors with <code>Is</code>, as in, <code>myQueue.IsEmpty()</code>. This way you don't confuse it with the verb \"to empty,\" as in, \"this function <em>empties</em> the queue.\" Orthogonally, you might mark this function <code>[[nodiscard]]</code> just to emphasize that it has no side effects.</p></li>\n<li><p><code>deAllocatePool()</code> would more traditionally be spelled <code>deallocatePool()</code>. \"Deallocate\" is a single word in English.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>template<typename T>\nvoid threadSafeQueue<T>::Push(T newData) { /* TODO: size check before pushing */\n std::shared_ptr<T> data(std::make_shared<T>(std::move(newData)));\n /* construct the object before lock*/\n std::lock_guard<std::mutex> lk(mut);\n taskQueue.push(data);\n dataCond.notify_one();\n}\n</code></pre>\n\n<p>Personally, I would simplify this to</p>\n\n<pre><code>template<class T>\nvoid threadSafeQueue<T>::Push(T newData) { /* TODO: size check */\n auto data = std::make_shared<T>(std::move(newData));\n std::lock_guard<std::mutex> lk(mut);\n taskQueue.push(std::move(data));\n dataCond.notify_one();\n}\n</code></pre>\n\n<p>Notice the use of <code>=</code> for initialization — it helps distinguish <code>bool foo(int)</code> from <code>bool foo(true)</code>, and helps readability in general. I also put a <code>std::move</code> on the push, so that we're not unnecessarily copying the <code>shared_ptr</code> and incurring an extra atomic increment and decrement of the refcount. (No big deal.) Notice that we are <em>still</em> incurring an extra call to <code>T</code>'s move-constructor; we might want to take <code>T</code> by reference here, in which case we might want two versions — one that takes <code>const T&</code> and one that takes <code>T&&</code>.</p>\n\n<p>In fact, we might want to cut out the middleman entirely:</p>\n\n<pre><code>template<class T>\ntemplate<class... Args>\nvoid threadSafeQueue<T>::Emplace(Args&&... args) { /* TODO: size check */\n auto data = std::make_shared<T>(std::forward<Args>(args)...);\n std::lock_guard<std::mutex> lk(mut);\n taskQueue.push(std::move(data));\n dataCond.notify_one();\n}\n</code></pre>\n\n<hr>\n\n<pre><code>typedef variant<TaskECB,TaskRPCB> taskTypes;\n</code></pre>\n\n<p>You're missing a <code>std::</code> there. Also, isn't it weird to have a <em>single</em> type named <code>taskTypes</code> (plural)? When I see the name \"task<strong>Types</strong>\", I expect to see <em>multiple</em> types — like a parameter pack or something. Here I think this type alias wants to be just a <code>taskType</code> or <code>taskVariant</code>, singular.</p>\n\n<hr>\n\n<pre><code> auto tid = std::this_thread::get_id();\n std::stringstream ss;\n ss << tid;\n std::string s = ss.str();\n</code></pre>\n\n<p>Yuck. In an ideal world, <code>std::to_string(std::this_thread::get_id())</code> would Do The Right Thing; but we don't live in an ideal world.</p>\n\n<p>However, why are you using <code>std::string</code> as your map key, anyway? Why not just define</p>\n\n<pre><code>std::map<std::thread::id, std::string> tidToTname;\n</code></pre>\n\n<p>and skip the expensive stringification?</p>\n\n<p>Then, instead of</p>\n\n<pre><code>printf(\"%s is executing now : \",tidToTname[s].c_str());\n</code></pre>\n\n<p>you would write simply</p>\n\n<pre><code>printf(\"%s is executing now : \",tidToTname.at(tid).c_str());\n</code></pre>\n\n<p>(notice that we no longer risk <em>modifying</em> <code>tidToTname</code> accidentally!), and instead of</p>\n\n<pre><code>tidToTname[ss.str()] = tnames[i];\n</code></pre>\n\n<p>you'd write simply</p>\n\n<pre><code>tidToTname.insert_or_assign(tid, tnames[i]);\n</code></pre>\n\n<p>(Still beware: using <code>emplace</code> instead of <code>insert_or_assign</code> will still compile, but it will do the wrong thing if the key is already present! The STL's <code>map</code> is a very tricky beast. You have to be careful with it.)</p>\n\n<hr>\n\n<pre><code>if((*task).index() == 0) { // TODO: change 0 and 1 to enums\n auto func = get<TaskECB>(*task);\n func();\n}else if((*task).index() == 1) {\n auto func = get<TaskRPCB>(*task);\n func(); \n}\n</code></pre>\n\n<p>First of all, <code>(*task).index()</code> is traditionally spelled <code>task->index()</code>, and I strongly recommend that you do so. Nested parentheses make things hard to read. That's why the <code>-></code> operator was added to C back in the '70s! (Probably late '60s, actually. Maybe earlier.)</p>\n\n<p>Second, this is not a typical way to interact with <code>std::variant</code>. The library really intends you to interact with it like this:</p>\n\n<pre><code>std::visit([](auto& callback) {\n callback();\n}, *task);\n</code></pre>\n\n<p>If you want to preserve your inefficient copying, just change <code>auto&</code> to <code>auto</code>.</p>\n\n<p>Really, IMO, it should be <code>const auto&</code>; but in order to make that work, you'll have to make your <code>callback</code> types const-callable. Right now their <code>operator()</code>s are non-const member functions:</p>\n\n<pre><code>void operator()() /* NO CONST HERE -- INTENTIONAL? */ {\n higLog(\"%s\",\"TaskECB function is executing...\");\n func();\n}\n</code></pre>\n\n<p>If you're allergic to <code>visit</code> — which you shouldn't be! — but if you are, then a <em>slightly</em> more idiomatic way to write your chain of <code>if</code>s would be</p>\n\n<pre><code>if (auto *func = std::get_if<TaskECB>(task.get())) {\n (*func)();\n} else if (auto *func = std::get_if<TaskRPCB>(task.get())) {\n (*func)();\n}\n</code></pre>\n\n<p>Having to use <code>task.get()</code> to get a raw pointer, instead of just <code>task</code> or <code>*task</code>, definitely isn't ideal API design on the STL's part. But again, the ideal solution is to just use <code>std::visit</code>! You should use <code>std::visit</code>.</p>\n\n<hr>\n\n<p>I didn't check the multithreading parts. Odds are, there are bugs. Multithreaded code always has at least one bug. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-12T03:16:23.490",
"Id": "528267",
"Score": "1",
"body": "You mentioned `->` was created in the 70s, maybe the 60s. At least in C, it wouldn't have been added before `struct`, and thanks to some UNIX preservation work, we can put that in the 1972 - 1973 timeframe.\n\nhttps://www.bell-labs.com/usr/dmr/www/primevalC.html\n\nThe last1120c version has no `struct` support. prestruct-c does (including `->`); it's the last version before the compiler began to make use of `struct` itself."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:53:46.357",
"Id": "216682",
"ParentId": "216467",
"Score": "4"
}
},
{
"body": "<p>Some additions to the review from @Quuxpluson. </p>\n\n<p>With regard to threadsafety, i'd be concerned that you are not calling <code>deAllocatePool</code> in the destructor. It's undefined behavior to call a destructor on <code>std::mutex</code> when the mutex is locked. It is also <em>a bad thing</em> to call the destructor on <code>std::thread</code> when it is considered <code>joinable</code>. Both of these may happen if you destruct your threadpool without clearing out the work queue. </p>\n\n<p>Looking further at your <code>deAllocatePool</code>, I think that you could get into cases where you can't end a thread. You are setting <code>done</code> but if the queue is empty, the thread could be waiting in <code>waitAndPop()</code>. While the <code>notifyAllThreads</code> will cause it to wake the lambda expression that you are using in your <code>wait</code> statement</p>\n\n<pre><code>dataCond.wait(lk,[this](){return !taskQueue.empty();});\n</code></pre>\n\n<p>would immediately go back into a wait state after awoken. If you manage to call <code>join()</code> on this kind of thread your <code>deallocatePool</code> would hang. I think is that checking for an abort condition inside the wait would mitigate that. If this hasn't happened yet there could be a variety of issues, i could be wrong, your use pattern has prevented this, or just pure coincidence ... </p>\n\n<p>Both of your task types could be reduced to a functor with the type <code>std::function<void(void)></code>. You could use either lambdas or <code>std::bind</code> to enclose the state information, this would reduce the complexity inside your threadpool. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T21:00:30.820",
"Id": "216686",
"ParentId": "216467",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T10:30:13.433",
"Id": "216467",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "C++ thread_pool with heterogeneous work-queue"
} | 216467 |
<p>The task:</p>
<blockquote>
<p>Given an array of integers in which two elements appear exactly once
and all other elements appear exactly twice, find the two elements
that appear only once.</p>
<p>For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and
8. The order does not matter.</p>
<p>Follow-up: Can you do this in linear time and constant space?</p>
</blockquote>
<pre><code>const lst = [2, 4, 6, 8, 10, 2, 6, 10];
</code></pre>
<p>My functional solution</p>
<pre><code>const findUnique = lst => lst
.sort((a,b) => a - b)
.filter((x, i) => lst[i-1] !== x && lst[i+1] !== x);
console.log(findUnique(lst));
</code></pre>
<p>My imperative solution:</p>
<pre><code>function findUnique2(lst) {
const res = [];
const map = new Map();
lst.forEach(x => map.set(x, map.get(x) === undefined));
map.forEach((val, key) => {
if(val) { res.push(key); }
});
return res;
}
console.log(findUnique2(lst));
</code></pre>
<p>I think the imperative solution is in linear time but not constant space. How would you do it with constant space?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T10:10:36.310",
"Id": "418876",
"Score": "1",
"body": "`order does not matter` *order of inputs* or *order of results*? The example shows exactly *one* deviation from monotonicity. (My guess: both.)"
}
] | [
{
"body": "<p>Sorting is not needed. A Set may be a better data structure for the task.</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 find2Unique2 = a => Array.from( a.reduce( \n (once, x) => (once.delete(x) || once.add(x), once),\n new Set() \n))\n\nconsole.log( find2Unique2( [2, 0, 6, 8, 10, 2, 6, 10] ) );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I\"m not sure how to solve this in constant space. If you xor all of the terms together </p>\n\n<pre><code>arr.reduce( (xor,x) => xor ^ x, 0 )\n</code></pre>\n\n<p>Then <code>result = a ^ b</code>, where <code>a</code> and <code>b</code> are your two unique terms. If you can figure out <code>a</code>, then <code>b = result ^ a</code>. Or you can find some other reduction, you'll have two equations and two unknowns, and an algebraic solution might be possible. </p>\n\n<p>For example, xor of the negated array combines with positive xor to uniquely identify a and b if they are two bits wide: </p>\n\n<pre><code> xor = arr.reduce( (xor,x) => xor ^ x, 0 )\n neg = arr.reduce( (xor,x) => xor ^ -x, 0 )\n\n a b xor neg & 0xF (high bits omitted for clarity)\n 0 1 => 1 1111 \n 0 10 => 10 1110 \n 0 11 => 11 1101 \n 1 10 => 11 1 \n 1 11 => 10 10 \n10 11 => 1 11 \n</code></pre>\n\n<p>But it doesn't work for larger values. You could do multiple passes, with each pass xor-ing a right-shifted version of elements that could possibly match (if the last two bytes are <code>11</code> and <code>10</code>, you can skip numbers that don't end in those bits). </p>\n\n<p>I didn't implement this because it's pretty complicated and it doesn't seem like the right answer. But maybe it gives you an idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T06:22:57.210",
"Id": "418871",
"Score": "2",
"body": "`to solve this in constant space [xor all] terms together` right on track! Think about what the value (*X*) obtained means: every bit *not* set is the same in both unique values (*a* and *b*). A bit *set* is different in *a* and *b*: *Every* bit set in *X* **tells** *a* from *b*."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:57:16.177",
"Id": "216502",
"ParentId": "216468",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>How would you do it with constant space?</p>\n</blockquote>\n\n<ul>\n<li>Reduce the input list with <code>^</code>, let's call this result <code>xor</code></li>\n<li><code>xor</code> is <code>a ^ b</code>, where <code>a</code> and <code>b</code> are the numbers that appear only once</li>\n<li>Any set bit appears in either <code>a</code> or <code>b</code> but not both</li>\n<li>Set <code>bit</code> to a single bit that is in <code>xor</code>. For example if <code>xor</code> is <code>6</code>, then <code>bit</code> could be <code>2</code>, or it could be <code>4</code>, whichever, doesn't matter</li>\n<li>Filter the input list with <code>& bit</code>. Realize that the matched values will include either <code>a</code> or <code>b</code> but not both, thanks to our observation earlier. The filtered list will also include 0 or more duplicate pairs that may have matched.</li>\n<li>Reduce the filtered list with <code>^</code>, let's call this result <code>a</code>. The value of <code>b</code> is <code>xor ^ a</code>.</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>function findUnique(lst) {\n const xor = lst.reduce((x, e) => x ^ e);\n var bit = 1;\n while ((bit & xor) === 0) {\n bit <<= 1;\n }\n const a = lst.filter(x => x & bit).reduce((x, e) => x ^ e);\n return [a, xor ^ a];\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:53:06.983",
"Id": "216547",
"ParentId": "216468",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216547",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T11:02:51.493",
"Id": "216468",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Find the elements that appear only once"
} | 216468 |
<p>Given a string taken from the following set:</p>
<pre><code>strings = [
"The sky is blue and I like it",
"The tree is green and I love it",
"A lemon is yellow"
]
</code></pre>
<p>I would like to constuct a function which replaces subject, color and optional verb from this string with others values. </p>
<p>All strings match a certain regex pattern as follow:</p>
<pre><code>regex = r"(?:The|A) (?P<subject>\w+) is (?P<color>\w+)(?: and I (?P<verb>\w+) it)?"
</code></pre>
<p>The expected output of such function would look like this:</p>
<pre><code>repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"
</code></pre>
<p>Here is the solution I come with (I can't use <code>.replace()</code> because there is edge cases if the string contains the subject twice for example):</p>
<pre><code>def repl(sentence, subject, color, verb):
m = re.match(regex, sentence)
s = sentence
new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
if m.group("verb") is None:
new_string += s[m.end("color"):]
else:
new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
return new_string
</code></pre>
<p>Do you think there is a more straightforward way to implement this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:06:46.677",
"Id": "418797",
"Score": "0",
"body": "Do you have to use a regex? If not, `split(\" \")` the string into words, replace words 1, 3, and possibly 6, then `\" \".join(...)` it back into a sentence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:18:35.483",
"Id": "418798",
"Score": "0",
"body": "What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:35:50.917",
"Id": "418802",
"Score": "0",
"body": "@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:40:14.313",
"Id": "418806",
"Score": "0",
"body": "@Reinderien For example, `repl(\"The meloon is orange\", \"orange\", \"great\", \"like\")` or simply `repl(\"A letter is A\", \"letter\", \"B\", \"fail\")`"
}
] | [
{
"body": "<pre><code>import re\n\nregex = re.compile(\n r'(The|A) '\n r'\\w+'\n r'( is )'\n r'\\w+'\n r'(?:'\n r'( and I )'\n r'\\w+'\n r'( it)'\n r')?'\n)\n\n\ndef repl(sentence, subject, colour, verb=None):\n m = regex.match(sentence)\n new = m.expand(rf'\\1 {subject}\\2{colour}')\n if m[3]:\n new += m.expand(rf'\\3{verb}\\4')\n return new\n\n\ndef test():\n assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') == \\\n 'The bathroom is smelly and I distrust it'\n assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') == \\\n 'The pinata is angry and I fear it'\n assert repl('A lemon is yellow', 'population', 'dumbfounded') == \\\n 'A population is dumbfounded'\n</code></pre>\n\n<p>Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T15:12:08.593",
"Id": "418817",
"Score": "2",
"body": "I did not know `expand()`, this seems very useful. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:34:32.370",
"Id": "216478",
"ParentId": "216474",
"Score": "12"
}
},
{
"body": "<p>You might want to experiment with <a href=\"https://www.nltk.org/\" rel=\"nofollow noreferrer\">NLTK</a>, a <code>leading platform for building Python programs to work with human language data</code>:</p>\n\n<p>You could import it, tags the words (NOUN, ADJ, ...) and replace words in the original sentence according to their tags:</p>\n\n<pre><code>import nltk\nfrom collections import defaultdict\nfrom nltk.tag import pos_tag, map_tag\n\ndef simple_tags(words):\n #see https://stackoverflow.com/a/5793083/6419007\n return [(word, map_tag('en-ptb', 'universal', tag)) for (word, tag) in nltk.pos_tag(words)]\n\ndef repl(sentence, *new_words):\n new_words_by_tag = defaultdict(list)\n\n for new_word, tag in simple_tags(new_words):\n new_words_by_tag[tag].append(new_word)\n\n new_sentence = []\n\n for word, tag in simple_tags(nltk.word_tokenize(sentence)):\n possible_replacements = new_words_by_tag.get(tag)\n if possible_replacements:\n new_sentence.append(possible_replacements.pop(0))\n else:\n new_sentence.append(word)\n\n return ' '.join(new_sentence)\n\nrepl(\"The sea is blue\", \"moon\", \"white\", \"hate\")\n# 'The moon is white'\nrepl(\"The sea is blue\", \"yellow\", \"elephant\")\n# 'The elephant is yellow'\n</code></pre>\n\n<p>This version is brittle though, because some verbs appear to be nouns or vice-versa.</p>\n\n<p>I guess someone with more NLTK experience could find a more robust way to replace the words.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:46:16.367",
"Id": "216499",
"ParentId": "216474",
"Score": "4"
}
},
{
"body": "<p>Here is a solution using the original format string, instead of the inverted format string suggested by Reindeerien.</p>\n\n<hr>\n\n<p>Your difficulty come in manually building up the original string parts from the spans of the original string. If you maintained a list of the starting points (which is the start of the string and the end of every group), and a list of the ending points (which is the start of every group, and the end of the string), you could use these to retrieve the parts of the original string you want to keep:</p>\n\n<pre><code>start = [0] + [m.end(i+1) for i in range(m.lastindex)]\nend = [m.start(i+1) for i in range(m.lastindex)] + [None]\n</code></pre>\n\n<p>We can glue these parts together with a placeholder which we will substitute the desired value in:</p>\n\n<pre><code>fmt = \"{}\".join(sentence[s:e] for s, e in zip(start, end))\n</code></pre>\n\n<p>Using <code>\"{}\"</code> as the joiner will create a string like <code>The {} is {} and I {} it</code>, which makes a perfect <code>.format()</code> string to substitute in the desired replacements:</p>\n\n<pre><code>def repl(sentence, subject, color, verb=None):\n m = re.match(regex, sentence)\n start = [0] + [m.end(i+1) for i in range(m.lastindex)]\n end = [m.start(i+1) for i in range(m.lastindex)] + [None]\n fmt = \"{}\".join(sentence[s:e] for s, e in zip(start, end))\n return fmt.format(subject, color, verb)\n</code></pre>\n\n<p>If you dont mind being a little cryptic, we can even make this into a shorter 3-line function:</p>\n\n<pre><code>def repl(sentence, subject, color, verb=None):\n m = re.match(regex, sentence)\n idx = [0] + [pos for i in range(m.lastindex) for pos in m.span(i+1)] + [None]\n return \"{}\".join(sentence[s:e] for s, e in zip(*[iter(idx)]*2)).format(subject, color, verb)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:07:03.740",
"Id": "216507",
"ParentId": "216474",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216478",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T13:18:56.773",
"Id": "216474",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"strings",
"regex"
],
"Title": "Elegant way to replace substring in a regex with optional groups in Python?"
} | 216474 |
<p>I have two variables that could be the same. In such a case I am assigning one of them to be <code>undefined</code>. Is this code the best way I can write it?</p>
<pre><code> let folderOwner = $("#change-folder-owner").val();
let folderUser = $("#user_name_alias").data('value');
folderOwner = (folderOwner === folderUser) ? undefined : folderOwner;
</code></pre>
<p>Can someone please help me with a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T17:22:46.950",
"Id": "418828",
"Score": "2",
"body": "Why should the value be undefined if they are equal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:35:43.617",
"Id": "418840",
"Score": "0",
"body": "Using `if` can be clearer and easier to understand than the ternary operator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:01:39.990",
"Id": "419027",
"Score": "0",
"body": "@dustytrash I need to use that undefined elsewhere"
}
] | [
{
"body": "<p>It would be clearer to use <code>if</code>:</p>\n\n<pre><code>if (folderOwner === folderUser) folderOwner = undefined\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T15:18:22.517",
"Id": "216481",
"ParentId": "216479",
"Score": "4"
}
},
{
"body": "<p>You can avoid re-assigning <code>folderOwner</code>'s value. Use two separate variables for the raw values, then evaluate for <code>folderOwner</code>'s value.</p>\n\n<pre><code>const ownerValue = ...\n\nconst userValue = ...\n\nconst folderOwner = (ownerValue === userValue) ? undefined : ownerValue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T16:19:16.783",
"Id": "216483",
"ParentId": "216479",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T14:59:19.453",
"Id": "216479",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Optimizing JS code"
} | 216479 |
<p>The question itself should be fairly self-explanatory. My method takes in <code>value</code>, <code>max_digits</code>, and <code>decimal_places</code>, and returns a formatted decimal number string. The code:</p>
<pre><code>from decimal import Decimal, ROUND_DOWN
def format_to_decimal_string(value, max_digits, decimal_places):
"""Formats a decimal number to the given number of decimal places.
Notes:
- If the decimal number is equal to zero, the absolute of the decimal
number is formatted and returned to remove the minus sign. See the
first doctest for an example.
- If the number of digits in the rounded up decimal number exceeds the
`max_digits`, the method tries to return the rounded down version. See
the second doctest for an example.
Doctests:
>>> format_to_decimal_string('-0.000', 4, 2)
'0.00'
>>> format_to_decimal_string('99.999999', 4, 2)
'99.99'
>>> format_to_decimal_string('99.999999', 5, 2)
'100.00'
>>> format_to_decimal_string('420.2108', 5, 0)
'420'
>>> format_to_decimal_string('foo', 4, 2)
Traceback (most recent call last):
...
TypeError: The value 'foo' is not a valid decimal number.
>>> format_to_decimal_string('120.411', 4, 2)
Traceback (most recent call last):
...
ValueError: After formatting, the number of digits in the value
'120.41' is 5, which exceeds the maximum number of digits of 4.
"""
try:
decimal_number = Decimal(str(value))
except:
raise TypeError(
'The value \'{}\' is not a valid decimal number.'.format(value)
)
if decimal_number == 0:
return str(abs(decimal_number).quantize(
Decimal(10) ** -decimal_places)
)
rounded_up = decimal_number.quantize(Decimal(10) ** -decimal_places)
if not len(rounded_up.as_tuple().digits) > max_digits:
return str(rounded_up)
rounded_down = decimal_number.quantize(
Decimal(10) ** -decimal_places,
rounding=ROUND_DOWN
)
rounded_down_digits_length = len(rounded_down.as_tuple().digits)
if not rounded_down_digits_length > max_digits:
return str(rounded_down)
else:
raise ValueError(
'After formatting, the number of digits in the value \'{}\' is ' \
'{}, which exceeds the maximum number of digits of {}.'.format(
rounded_down, rounded_down_digits_length, max_digits
)
)
</code></pre>
<p>Please assume that <code>max_digits</code>, and <code>decimal_places</code> will always be positive integers, and <code>max_digits</code> is greater than <code>decimal_places</code>, because these are coming from my database, so no validation is required for these arguments.</p>
<p>The comments should also be self explanatory. We only want to round up if the rounding up does not exceed the given maximum number of digits. Would really appreciate a review of this method.</p>
| [] | [
{
"body": "<p>Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.</p>\n\n<p>There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new <a href=\"https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python\" rel=\"nofollow noreferrer\">f-string synthax</a> instead of <code>format</code>. So your error messages would become something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>raise TypeError(\n f\"The value '{value}' is not a valid decimal number.\"\n)\n</code></pre>\n\n<p>which I think looks even nicer. I also replaced the outer <code>'</code> with <code>\"</code> so one does not have to escape the inner <code>'</code> with backslashes.</p>\n\n<p>The last error message could use the same tricks and could also utilize <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">implicit line continuation in function parenthesis</a> instead of manual line continuation triggered by <code>\\</code>. This would ultimately lead to the following snippet:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>raise ValueError(\n f\"After formatting, the number of digits in the value '{rounded_down}' \"\n f\"is {rounded_down_digits_length}, which exceeds the maximum number of \"\n f\"digits of {max_digits}.\"\n)\n</code></pre>\n\n<p>I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:28:16.097",
"Id": "216498",
"ParentId": "216484",
"Score": "4"
}
},
{
"body": "<p>Some other minor issues:</p>\n\n<h2>Invert your logic</h2>\n\n<pre><code>if not len(rounded_up.as_tuple().digits) > max_digits:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if len(rounded_up.as_tuple().digits) <= max_digits:\n</code></pre>\n\n<h2>Lose the redundant <code>else</code></h2>\n\n<p>This:</p>\n\n<pre><code>if not rounded_down_digits_length > max_digits:\n return str(rounded_down)\nelse:\n raise ...\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>if rounded_down_digits_length <= max_digits:\n return str(rounded_down)\nraise ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:27:26.380",
"Id": "418973",
"Score": "0",
"body": "Can you tell my why the inversion of logic is necessary? Is this mentioned somewhere in some best practices doc or something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T15:34:54.783",
"Id": "418977",
"Score": "0",
"body": "It's not necessary, but it is more legible. In the modified syntax, you don't need to write a `not`. I can't really find a reference for this, but I stand by it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:57:13.080",
"Id": "216544",
"ParentId": "216484",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T16:21:07.500",
"Id": "216484",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"formatting",
"fixed-point"
],
"Title": "Method for formatting a decimal number in Python using the given maximum number of digits and decimal places"
} | 216484 |
<p>Edit 1: changed a few portions of the code to hopefully make it runnable code and more understandable. If something is still incorrect please let me know.</p>
<p>Edit 2: just remembered I am doing this in python 2.7 because I am required to. If that causes any issues again please let me know.</p>
<p>I am trying to create 4 symbolic equations that correspond to the 4 elements of a normalized quaternion. The equation is for quaternion multiplication </p>
<p><span class="math-container">\$\dot q = 0.5*q*[0, \omega]^T\$</span></p>
<p><span class="math-container">\$\omega = [\omega_x, \omega_y, \omega_z]\$</span></p>
<p><span class="math-container">\$q = [q_r, q_i, q_j, q_k]\$</span>
and then I normalize the output. My solution is:</p>
<pre><code>import sympy as sy
def quat_equ(q_l, q_w, renorm=1):
# quaternion multiplication using equation: q_dot = 0.5 * q * [0, omega)^T
# multiplication broken up into individual quaternion states
q_r_d = 0.5 * (q_l[0] * q_w[0] - q_l[1] * q_w[1] + q_l[2] * q_w[2] +
q_l[3] * q_w[3])
q_i_d = 0.5 * (q_l[0] * q_w[1] + q_l[1] * q_w[0] + q_l[2] * q_w[3] -
q_l[3] * q_w[2])
q_j_d = 0.5 * (q_l[0] * q_w[2] + q_l[2] * q_w[0] + q_l[3] * q_w[1] -
q_l[1] * q_w[3])
q_k_d = 0.5 * (q_l[0] * q_w[3] + q_l[3] * q_w[0] + q_l[1] * q_w[2] -
q_l[2] * q_w[1])
# Re-normalizing the quaternion multiple times (heuristic I was taught/required to use)
# The for loop is causing the slowdown of the code due to re-normalizing
for i in range(renorm):
q_r_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
q_i_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
q_j_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
q_k_d *= 1 / sy.sqrt(q_r_d ** 2 + q_i_d ** 2 + q_j_d ** 2 + q_k_d ** 2)
return [q_r_d, q_i_d, q_j_d, q_k_d]
# setting up symbolics
q_r, q_i, q_j, q_k, w_ib_l, w_ib_m, w_ib_n = sy.symbols("q_r q_i q_j q_k w_ib_l w_ib_m w_ib_n")
q1 = [q_r, q_i, q_j, q_k]
q2 = [0, w_ib_l, w_ib_m, w_ib_n]
# separation of symbolic equations for each state in q_dot (this is a requirement for the code)
quat0 = quat_equ(q1, q2, 3)[0]
quat1 = quat_equ(q1, q2, 3)[1]
quat2 = quat_equ(q1, q2, 3)[2]
quat3 = quat_equ(q1, q2, 3)[3]
# testing of the symbolic equations using substitution
qq = [1., 0., 0., 0., 1., 1., 1.]
var = [q_r, q_i, q_j, q_k, w_ib_l, w_ib_m, w_ib_n]
q0 = sy.Subs(quat0, var, qq).doit()
q1 = sy.Subs(quat1, var, qq).doit()
q2 = sy.Subs(quat2, var, qq).doit()
q3 = sy.Subs(quat3, var, qq).doit()
</code></pre>
<p>When I try to re-normalize the quaternion more than 2 times this method becomes very slow. The symbolic equation also becomes massive because the re-normalization adds on basically 4 extra symbolic equations, which slows down later processes a lot. I couldn't think of a better method to create a normalized quaternion that 1) initializes faster and 2) is a smaller symbolic equation. I don't use symbolics in python much so most of Sympy is new to me.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:33:43.280",
"Id": "418837",
"Score": "1",
"body": "Why is `for i in range(1)` written as a loop? It's indentation is wrong, which makes this broken code. (A good 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-03-29T19:34:26.353",
"Id": "418839",
"Score": "0",
"body": "Note that MathJax is available for writing equations in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T21:04:28.823",
"Id": "418851",
"Score": "0",
"body": "In addition to what 200_success alreay said about broken code, the symbol definition is also no valid Python code. Your code could also greatly benefit from some comments to give reviewers a few hints which parts you suspect or know to be slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T17:25:42.473",
"Id": "418893",
"Score": "1",
"body": "Once the code runs without crashing, you should also test it with some simple test cases which will find the obvious bugs it currently has. For preference you could also edit the test code into the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:50:28.797",
"Id": "418924",
"Score": "0",
"body": "@200_sucess, the for loop is for multiple renormalizations of the quaternion. I had it set to 1 when i copied the code. I want to set the loop to 10.\n\nI'll also make sure to follow suggestions and edit the code. I am new to adding code to stack exchange, so apologize for that."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T18:34:19.313",
"Id": "216491",
"Score": "2",
"Tags": [
"python",
"symbolic-math",
"sympy"
],
"Title": "quaternion renormalization"
} | 216491 |
<p>I have a VBA script that does the following and I am trying to see if I can have it perform faster than 44 seconds:</p>
<ol>
<li>start with ~138k rows of data on sheets("Data")</li>
<li>concatenate each cell in the row into a temp string variable
<ul>
<li>temp string will look some like this if my row are columns A:D, "I am cellAI am cell BI am cell CI am cell D"</li>
</ul></li>
<li>sort the column holding all temp strings, so I can see all duplicates</li>
<li>filter to first temp string value to get the count of each occurrence</li>
<li>copy count into a sheets("reporting") and hyperlink the count number</li>
<li>create a new sheet that is opened from the hyperlink
<ul>
<li>in the end, after all count of duplicate strings are accounted for, I am creating 345 sheets</li>
</ul></li>
<li>copy the filtered results into the newly created sheet</li>
<li>hide the sheet</li>
<li>repeat steps 4 through 8</li>
</ol>
<p>My question is, based on the amount of work being done, is 38 - 44 seconds reasonable or can it be in any way faster (less than 30 seconds)</p>
<p>Below is the code:</p>
<pre><code>Option Explicit
Sub runReportV2()
'----------------------------------------------------------------------------------------------------------
'-V1 code
' - allow user to create grouping of fields
' - create temp strings of each row
' - compare all temp strings with each other
' - get count of each duplicate string occurrence and paste count to 'Report Summary' sheet
'----------------------------------------------------------------------------------------------------------
'----------------------------------------------------------------------------------------------------------
'-V2 code
' - adding hyperlinks to aggregation count on Report Summary sheet
' - linking hyperlinks to a new sheet with filtered row data from data sheet
'----------------------------------------------------------------------------------------------------------
'These will help speed things up
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Dim x As Double ' used for the For Loop when creating temp strings
Dim y As Double ' used for the For Loop when creating temp strings
Dim tempStr1 As String ' cell value used to concatenate to str1 variable
Dim str1 As String ' temp string from each cell value for the given row
Dim aggStr As String ' temp string value used in the while loop
Dim dataAggCount As Double ' get the last row on the rDataSheet in the while loop
Dim count As Double: count = 1 ' used to get count of each temp string occurrence
Dim overallRowCount As Double: overallRowCount = 2 ' this tells me which row to start on my next aggregation
Dim aggCol As Long ' last column used on the rDataSheet. helps me know where to provide aggregation results (count variable)
Dim pctdone As Single ' gives the statusBarForm the percentage completion
Dim reportCount As Double ' used to provide next available row on reportSheet
Dim sheetarray As Variant ' used to hold the worksheet creation variable. this is done in the while loop
Dim rDataLastRow As Double ' get last row value when copying filtered data on rDataSheet
Dim hOverallRowCount As Double ' get the overall row count to know where to paste the data in the sheetarray variable worksheet
Dim hDataAggCount As Double ' get count of rows on temp string column
'Variables for worksheets
Dim rDataSheet As Worksheet: Set rDataSheet = Sheets(1) '!1 Sheet
Dim reportSheet As Worksheet: Set reportSheet = Sheets(2)
reportSheet.Name = "Report Summary"
'********** THESE COLLECTION VALUES ARE USER UPDATED ***********
'Create Collection to hold items that are going to be used in the grouping
Dim headerColl As New Collection
headerColl.Add "SIM_c_site_id"
headerColl.Add "iim_c_FcstName"
headerColl.Add "iim_c_description"
'*********************************************
'array to hold all of the column numbers used for each grouping column
Dim headerArray As Variant
ReDim headerArray(1 To headerColl.count)
'variables used to get colum letter
Dim rFind As Range
Dim colNum As Long
Dim z As Long
'get count of fields (columns) with data
Dim colCount As Long: colCount = rDataSheet.Cells(1, Columns.count).End(xlToLeft).Column
For z = 1 To headerColl.count
'find the needed header from header collection and get the column number
With rDataSheet.Range(Cells(1, 1), Cells(1, colCount))
Set rFind = .Find(What:=headerColl(z), LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
'gives me the column number
colNum = rFind.Column
'add column number to headerArray
If z <> headerColl.count + 1 Then
headerArray(z) = colNum
End If
End If
End With
Next z
Set rFind = Nothing
'insert header from data sheet to report sheet
reportSheet.Rows(2).Value = rDataSheet.Rows(1).Value
'------------------------------------------------------------------------------------------------
'------------------------------------------------------------------------------------------------
'
'***This section will need to be updated once the user wants to add more aggregations (columns)***
' 'Alias the aggregation columns and possible the other columns
'
'insert column for aggregating
reportSheet.Cells(2, colCount + 1).Value = "nCount"
'these variables are used for column numbers of the created columns above
aggCol = colCount + 1
'------------------------------------------------------------------------------------------------
'------------------------------------------------------------------------------------------------
'column letter conversion for the aggregation column
Dim aggReportColLetter As String: aggReportColLetter = Col_Letter(aggCol)
'column letter conversion for the aggregation column
Dim lastReportColLetter As String: lastReportColLetter = Col_Letter(aggCol - 1)
'set the progress label and show the form
statusBarForm.LabelProgress.Width = 0
statusBarForm.Show
'update user on progress of script: this is where the temp strings will be produced and sorted
With statusBarForm
.LabelCaption.Caption = "Preparing data aggregation..."
End With
DoEvents
'get count of rows on data sheet
Dim dataRowCount As Double: dataRowCount = rDataSheet.Cells(Rows.count, 1).End(xlUp).Row
'create tempStr column
rDataSheet.Cells(1, colCount + 1).Value = "tempStr"
str1 = vbNullString
'create temp strings
For y = 2 To dataRowCount
For x = 1 To UBound(headerArray)
tempStr1 = Cells(y, headerArray(x))
str1 = str1 & tempStr1
tempStr1 = vbNullString
Next x
rDataSheet.Cells(y, aggCol) = str1
str1 = vbNullString
Next y
'create filter for sorting temp string column
rDataSheet.Range("A1").AutoFilter
'sort temp string column
Columns("A:" & aggReportColLetter).Sort key1:=Range(aggReportColLetter & "1"), _
order1:=xlAscending, Header:=xlYes
'********** THIS IS WHERE THE MAGIC HAPPENS **********
'SUMMARY:
' - filter temp string
' - get the count of occurrences of temp string individual
' - paste count to 'Report Summary' sheet
' - create worksheet and paste aggregated row data results onto each sheet
' - do while the the row the temp string is on, is not greater than the overall row count
Do While overallRowCount < dataRowCount
'update progress bar percentage
pctdone = Round((overallRowCount / dataRowCount) * 100, 2)
With statusBarForm
.LabelCaption.Caption = "Report Summary is " & pctdone & "%" & " complete."
.LabelProgress.Width = pctdone * 2.7
End With
DoEvents
rDataSheet.Select
'row item to copy over to the 'Report Summary' sheet
aggStr = Cells(overallRowCount, aggCol).Value
'filter '!1' sheet to aggStr variable
Range("$A$1:$" & aggReportColLetter & "$" & aggCol).AutoFilter Field:=aggCol, Criteria1:=aggStr
'aggregation count (only counting visible rows)
count = Application.Subtotal(103, Columns(aggCol)) - 1
'last used row on the current aggregation
dataAggCount = rDataSheet.Cells(Rows.count, aggCol).End(xlUp).Row
'get count of rows on report sheet
reportCount = reportSheet.Cells(Rows.count, 1).End(xlUp).Row
With reportSheet
'add row from data sheet to report sheet
.Rows(reportCount + 1).Value = rDataSheet.Rows(overallRowCount).Value
'copy aggregated result to 'Report Summary' sheet
.Cells(reportCount + 1, aggCol).Value = count
End With
'next row to use for copying to 'Report Summary' sheet and aggregating
overallRowCount = dataAggCount + 1
aggStr = vbNullString
'create new worksheet that will open up when the hyperlinked number is clicked
Set sheetarray = Worksheets.Add(After:=Sheets(Sheets.count))
sheetarray.Name = "!" & CStr(sheetarray.Index - 1)
'' create hyperlink to sheets created
reportSheet.Select
ActiveSheet.Hyperlinks.Add Anchor:=Cells(reportCount + 1, aggCol), Address:="", SubAddress:= _
"'" & sheetarray.Name & "'!A1", TextToDisplay:=""
rDataLastRow = rDataSheet.Cells(Rows.count, 1).End(xlUp).Row
hDataAggCount = rDataSheet.Cells(Rows.count, aggCol - 1).End(xlUp).Row
hOverallRowCount = hDataAggCount - count + 1
'copy filtered data from rDataSheet and paste into the newly created sheet
sheetarray.Select
sheetarray.Range("A1:" & lastReportColLetter & 1).Value = rDataSheet.Range("A1:" & lastReportColLetter & 1).Value
sheetarray.Range("A2:" & lastReportColLetter & count + 1).Value = rDataSheet.Range("A" & hOverallRowCount & ":" & lastReportColLetter & rDataLastRow).Value
'format the sheet
sheetarray.Range(Cells(1, 1), Cells(1, aggCol - 1)).EntireColumn.AutoFit
'hide the sheet
sheetarray.Visible = xlSheetHidden
rDataSheet.AutoFilterMode = False
'set the sheet to nothing, so the same variable can dynamically be used again for the next aggregation row
Set sheetarray = Nothing
Loop
'********** Clean up the report and close out the routine **********
'delete the temp string column
With rDataSheet
.Columns(aggCol).Delete
End With
'auto fit columns on the Report Summary sheet
With reportSheet
.Range(Cells(1, 1), Cells(1, aggCol)).EntireColumn.AutoFit
End With
'close out of the status bar
Unload statusBarForm
MsgBox "Aggregation results are now availabe!", vbOKOnly, "Aggregation Completion"
'restore order to the Excel world
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayStatusBar = True
ActiveSheet.DisplayPageBreaks = True
End Sub
'function that converts a number into a column letter
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:21:17.850",
"Id": "418835",
"Score": "1",
"body": "Welcome to CR! I don't have time for a review right now, but I'd be curious what the performance is if you comment-out the progress indicator code? Consider updating progress once every x% of total, rather than at every single iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:16:13.893",
"Id": "418842",
"Score": "0",
"body": "@MathieuGuindon Thanks! I commented out the progress indicator code, and on the second run, commented out the statusBarForm as a whole and it surprisingly ran on average 2.5 second slower between both runs. For the change in progress update, are you thinking something like ```if overallRowCount / dataRowCount is equal to x% then update the progress indicator``` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:20:47.910",
"Id": "418843",
"Score": "0",
"body": "As it stands your code won't compile with `Option Explicit` at the top - can you please qualify all variables and edit your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:33:25.457",
"Id": "418845",
"Score": "1",
"body": "Surprising indeed... did you leave the `DoEvents` in? As for the update, consider `If overallRowCount Mod 100 = 0 Then UpdateProgress` -- regarding the progress indicator itself, you might be interested to read [this article](https://rubberduckvba.wordpress.com/2018/01/12/progress-indicator/) I wrote a while back (the original code is somewhere on this site!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:38:00.540",
"Id": "418846",
"Score": "0",
"body": "@dwirony Maybe I copy and pasted something incorrectly? It works fine for me. I recopied whole sub, so hopefully that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:44:41.990",
"Id": "418847",
"Score": "2",
"body": "Don't have time for a review at the moment. Most of your loops can be accomplished through an array, rather than switching between the Excel model and the VBA model - this will have a big impact on performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:57:01.007",
"Id": "418848",
"Score": "0",
"body": "@AJD When you have time, I would be interested to know how my loops could be accomplished through an array, rather than switching between the Excel model and the VBA model."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:59:10.700",
"Id": "418849",
"Score": "0",
"body": "@MathieuGuindon ```DoEvents ``` was not left in I'll have to integrate that snippet of code in the script and see if I have better results. Thanks for the tip on the article btw!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:37:26.213",
"Id": "418854",
"Score": "0",
"body": "@MathieuGuindon just a heads-up, I tried “If overallRowCount Mod 100 = 0 Then UpdateProgress“ but changed it to 1000, and that saved a few seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T08:40:10.200",
"Id": "419040",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>In this review, I am only looking at options for addressing the loops. With the number of rows you have described, finding efficiencies in the loops should have a big payoff. </p>\n\n<p>Don't collapse lines of code using \":\", it is not necessary, breaks indenting and makes it harder to find some lines. </p>\n\n<h2>Loop 1</h2>\n\n<pre><code>'get count of fields (columns) with data\nDim colCount As Long\ncolCount = rDataSheet.Cells(1, Columns.count).End(xlToLeft).Column\n\nFor z = 1 To headerColl.count\n 'find the needed header from header collection and get the column number\n With rDataSheet.Range(Cells(1, 1), Cells(1, colCount))\n Set rFind = .Find(What:=headerColl(z), LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)\n If Not rFind Is Nothing Then\n 'gives me the column number\n colNum = rFind.Column\n 'add column number to headerArray\n If z <> headerColl.count + 1 Then\n headerArray(z) = colNum\n End If\n End If\n End With\nNext z\n</code></pre>\n\n<p>You use the Excel model with <code>Range</code>, <code>.Find</code>, <code>.Column</code>. With your current example, this would only loop 3 times, so is not significant in terms of performance. However, this presents a good training opportunity. </p>\n\n<p>You work with a single range(<code>rDataSheet.Range(Cells(1, 1), Cells(1, colCount))</code>), but you set that range each time in the loop. If you were using Excel objects, you coud set the <code>With</code> statement outside of the loop and save some performance time there.</p>\n\n<p>But you are only working with the values, so this allows us to use Arrays.</p>\n\n<pre><code>Dim dataValues as Variant\nDim hCollValue as Variant ' Must be variant to work in a for each loop\ndataValues = rDataSheet.Range(Cells(1, 1), Cells(1, colCount)).Value\n'For each hCollValue in headerColl ' was For z = 1 To headerColl.count\nFor z = 1 To headerColl.count\n 'find the needed header from header collection and get the column number\n For i = LBound(dataValues) to UBound(dataValues)\n If UCase(CStr(dataValues(i,1))) = UCase(CStr(headerColl(z)) Then\n headerArray(z) = i\n Exit For\n End If\n Next i\nNext z\n</code></pre>\n\n<p>Iterating through the entire loop to find the one value (noting that I exit when the first one is found) can be cheaper than calling the equivalent Excel function. You can see now that I am not touching Excel at all during that loop. Because of the use of Variants, I have cast them to strings, and taken the UpperCase to conduct a case-insensitive search.</p>\n\n<p>The array returned by a <code>Range</code> of values is always two-dimensional. Because we are taking it from a single column, the array is only one wide, hence why I have used <code>dataValues(i,1)</code></p>\n\n<p>Point to note in your original loop:</p>\n\n<pre><code> 'If z <> headerColl.count + 1 Then ' This can never be false, because you are in a loop\n ' headerArray(z) = colNum\n 'End If\n</code></pre>\n\n<p>Another thing to consider is the use of a custom class that acts as a data structure. In that way, you could:</p>\n\n<pre><code>For Each MyCustomClass in headerColl\n ....\n If dV = MyCustomClass.HeaderTitle Then\n MyCustomClass.ColumnNumber = i\n End If\n ....\nNext MyCustomClass\n</code></pre>\n\n<p>Could be a real game changer if you tie lots of data or logic to these items. I suggest a <code>Class</code> and not a <code>Type</code> because you cannot iterate over a <code>Type</code> collection in VBA and there are some other wrinkles.</p>\n\n<h2>Loop 2</h2>\n\n<pre><code>'create temp strings\nFor y = 2 To dataRowCount\n For x = 1 To UBound(headerArray)\n tempStr1 = Cells(y, headerArray(x))\n str1 = str1 & tempStr1\n tempStr1 = vbNullString\n Next x\n rDataSheet.Cells(y, aggCol) = str1\n str1 = vbNullString\nNext y\n</code></pre>\n\n<p>This is where you are going to get the real performance hit. I am also finding it difficult to unpack the loop and what you are trying to achieve. If I am interpreting this right, you are creating a temporary string out of the values across the row (selected columns only), and putting this string into another column on the same row. Except in a different sheet.</p>\n\n<p>Note: Always use qualified ranges, as you can't really tell which is the active sheet once the code is running.</p>\n\n<pre><code>Dim sourceStrings as Variant ` this will be a multi-dimensional array\nDim targetArray(dataRowCount - 2 + 1, 1) as String\n\nDim unionRange as Range\nDim r as Long, r2 as Long\nWith [ThisSheet] ' whatever you have set this sheet too - qualify all ranges.\n For r = LBound(headerArray) to UBound(headerArray)\n If unionRange is Nothing Then\n set unionRange = .Range(.Cells(2, headerArray(r)),.Cells(dataRowCount, headerArray(r)) )\n Else\n set unionRange = Union(unionRange, .Range(.Cells(2, headerArray(r)),.Cells(dataRowCount, headerArray(r))))\n End If\n Next r\nEnd With \nsourceStrings = unionRange.Value\n\nFor r = LBound(sourceStrings,1) to UBound(sourceStrings,1) ' loop through the first dimension - but \"1\" is optional default and not really needed here.\n targetArray(r) = vbNullString '\"\"\n For r2 = LBound(sourceStrings,2) to UBound(sourceStrings,2) ' loop through the second dimension\n targetArray(r) = targetArray(r) & sourceStrings(r, r2)\n Next r2\nNext r \nWith rDataSheet\n .Range(.Cells(2,aggCol),.Cells(dataRowCount,aggCol)).Value = targetArray\nEnd With \n</code></pre>\n\n<p>The first <code>r</code> loop seems a bit complicated, but it is short (3 iterations in your example) and it now sets up the quicker array.\nDISCLAIMER: I have not tested this. Possible may require some tweaking if Excel does funky things with values from a multi-area range.</p>\n\n<p>Instead of switching in and out of Excel (headers * rowcount + rowcount) times, you would only do it (headers + insert values) times - which in this case is about 4 times. </p>\n\n<h2>Loop 3</h2>\n\n<p>Sometimes, there is not much that can be done. I have had a quick look, but I don't think using Arrays here is going to help much because of the diverse amount of data and Excel object items (not just <code>.Value</code>) that are used. Avoid using <code>.Select</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:19:12.390",
"Id": "419274",
"Score": "0",
"body": "To answer your question on Loop 2: what I am doing is grabbing all cell values for the first row, concatenating them into a temp string, pasting them into the same row, but in a new column (taking the last column index +1 to know where to input the \"temp string\" column) and then repeating for each row. This is all done on the same sheet.With this amount of rows, it is currently taking ~3.5 seconds to complete. I am using a column to store the temp strings, so I can then sort them to get my duplicates in chunks. This helps not having to take the each temp string and check that against every row"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:23:16.113",
"Id": "419275",
"Score": "0",
"body": "To answer your question on Loop 3: I was initially trying to avoid using ```.Select```, but I ran into errors. Mainly when trying to create the hyperlink ```ActiveSheet.Hyperlinks.Add Anchor:=Cells(reportCount + 1, aggCol), Address:=\"\", SubAddress:= \"'\" & sheetarray.Name & \"'!A1\", TextToDisplay:=\"\"``` and in this line of code when using the \"sheetarray\" sheet ```sheetarray.Range(Cells(1, 1), Cells(1, aggCol - 1)).EntireColumn.AutoFit``` When I used the ```sheetname.Select``` first, the errors disappeared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:26:06.837",
"Id": "419276",
"Score": "0",
"body": "To respond to your Loop 1: The code I was using took milliseconds to complete, so I wasn't too concerned with this section of the code. I did, though, use the block of code you provided, as it looks a lot cleaner than what I was using."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T05:55:46.823",
"Id": "216517",
"ParentId": "216494",
"Score": "6"
}
},
{
"body": "<p>With this review, I hope to offer an alternative approach to your stated problem by using a SQL query.</p>\n\n<p>Instead of copying your data into subdivided sheets, I think a better fit to your stated problem would be simply query or filter the data you want to find, when you need it. Leave your raw data as is, and just pull it up on demand when needed. I chose to use <code>ADODB</code> with a SQL statement, but you could achieve something very similar with <code>AutoFilter</code> or <code>Advanced Filter</code> too.</p>\n\n<p><strong><em>How is this better? (IMO)</em></strong></p>\n\n<ul>\n<li>By copying your unique groups into new sheets, you are effectively doubling your raw data size. With this approach, your raw data remains untouched, you just summarize it.</li>\n<li>You don't need to create 300+ sheets, you'd only ever need 2 sheets (given the stated problem). A summary sheet and a raw data sheet. A lot easier to debug is something goes awry.</li>\n<li>No column concatenation is needed with this approach. Instead of making a composite key (of sorts) with 4 columns of joined data, simply filter (or query) the columns with the values you need for each column. BTW, concatenating all columns again, doubles the size of your data...again.</li>\n</ul>\n\n<p>I've mocked up a spreadsheet with 150,000 rows of data in Worksheet called <code>Raw Data</code>. This sheet has 4 columns of randomly generated single characters to mock up what you described. </p>\n\n<p><a href=\"https://i.stack.imgur.com/gJFSn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gJFSn.png\" alt=\"Raw Data\"></a></p>\n\n<p>You'll also need a sheet named <code>Summary</code>, this is where the data is output to. </p>\n\n<p>The way this work is it will find all matching rows that match the parameters you supply for Column 1 through 4. Each Column value needs to match what you provided to get returned. </p>\n\n<p>The code below has querying approach built out. I didn't create a form/UI to pass in values, however that should be fairly easy to do now, just update the <code>SearchParameters</code> type, you can do this in the <code>CreateView</code> sub. The performance is pretty good, queries are taking less than 2 seconds to finish on my machine.</p>\n\n<p>Let me know if there are any questions, happy to help.</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>Option Explicit\nPrivate Const adCmdText As Long = 1\nPrivate Const adVarWChar As Long = 202\nPrivate Const adParamInput As Long = 1\n\nPublic Type SearchParameters\n Column1Value As String\n Column2Value As String\n Column3Value As String\n Column4Value As String\nEnd Type\n\nPrivate Function GetExcelConnection() As Object\n Set GetExcelConnection = CreateObject(\"ADODB.Connection\")\n GetExcelConnection.ConnectionString = \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & _\n ThisWorkbook.FullName & \";Extended Properties='Excel 12.0;HDR=YES';\"\n GetExcelConnection.Open\nEnd Function\n\nPrivate Sub DisplayFilteredRawData(SQLParameters As SearchParameters)\n Const SQL As String = \"SELECT [Column 1],[Column 2],[Column 3],[Column 4] \" & _\n \"FROM [Raw Data$] \" & _\n \"WHERE [Column 1] = ? and [Column 2] = ? and [Column 3] = ? and [Column 4] = ?\"\n Static dbConnection As Object\n Static OutputSheet As Excel.Worksheet\n Static OutputRange As Excel.Range\n Static RecordCount As Excel.Range\n Dim FilteredRS As Object\n Const MaxCellLength As Long = 32767\n Const NumberOfHeaderRows As Long = 4\n\n If OutputSheet Is Nothing Then Set OutputSheet = ThisWorkbook.Sheets(\"Summary\")\n If OutputRange Is Nothing Then Set OutputRange = OutputSheet.Range(\"A5:F100000\") 'Where data is output\n If RecordCount Is Nothing Then Set RecordCount = OutputSheet.Range(\"F4\") 'Where the record count goes\n If dbConnection Is Nothing Then Set dbConnection = GetExcelConnection\n\n With CreateObject(\"ADODB.Command\")\n .ActiveConnection = dbConnection\n .CommandType = adCmdText\n .CommandText = SQL\n .Parameters.Append .CreateParameter(\"@Value1\", adVarWChar, adParamInput, MaxCellLength, SQLParameters.Column1Value)\n .Parameters.Append .CreateParameter(\"@Value2\", adVarWChar, adParamInput, MaxCellLength, SQLParameters.Column2Value)\n .Parameters.Append .CreateParameter(\"@Value3\", adVarWChar, adParamInput, MaxCellLength, SQLParameters.Column3Value)\n .Parameters.Append .CreateParameter(\"@Value4\", adVarWChar, adParamInput, MaxCellLength, SQLParameters.Column4Value)\n Set FilteredRS = .Execute\n End With\n\n OutputRange.Clear\n If Not FilteredRS Is Nothing Then\n OutputSheet.Range(OutputRange.Cells(1, 1).Address).CopyFromRecordset FilteredRS\n End If\n RecordCount.Value2 = OutputSheet.Range(\"A1048576\").End(xlUp).Row - NumberOfHeaderRows\nEnd Sub\n\nPublic Sub CreateView()\n Dim myTimer As Double: myTimer = Timer\n Dim mySearchParameters As SearchParameters\n\n With mySearchParameters\n .Column1Value = \"l\"\n .Column2Value = \"o\"\n .Column3Value = \"l\"\n .Column4Value = \"z\"\n End With\n\n DisplayFilteredRawData mySearchParameters\n Debug.Print Timer - myTimer\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:00:21.130",
"Id": "419100",
"Score": "0",
"body": "@AJD. I updated the answer slightly. I mention in my post there isn't a UI built out, but how to update the parameters for the query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:34:28.713",
"Id": "419277",
"Score": "0",
"body": "Pt.1 -This a thoughtful approach, but I don't think that this fits with what I am needing to do. The amount of rows on the sheet and the kind of data that will be provided on the \"DataSheet\" will vary each time the user pulls this data from a website and exports it to this Excel sheet, which houses the VBA script. With that being said, my goal when the user exports and opens the Excel doc is to get a summary sheet of all duplicate values based off of the grouping (set by the admin in the VBA code - Collection data), their count and a hyperlink to all the data when clicking the count hyperlink."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:37:03.713",
"Id": "419278",
"Score": "0",
"body": "Pt. 2 - The hyperlink would then open up their respective sheet with all of the data that pertains to the grouping used. I may have 15 columns in the raw data, but only want to group by 4 columns. The hyperlink count, let's say is 10, would give me the 10 rows of data that pertain to my grouping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T22:50:58.627",
"Id": "419281",
"Score": "0",
"body": "Gotcha, if you want to return everything (e.g. all columns). You can change this part `SELECT [Column 1],[Column 2],[Column 3],[Column 4]` to `SELECT *`. This approach should work regardless of how many rows are returned."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T16:38:33.807",
"Id": "216588",
"ParentId": "216494",
"Score": "4"
}
},
{
"body": "<p>I like the project but ...</p>\n\n<h2>Separation of Concerns</h2>\n\n<p>It is best to keep your procedure under 40 lines. Generally speaking, it is best to identify each task that is to be performed, divide the tasks up and have subprocedures that process one or two of them at a time. The main method would be responsible for passing data between the methods as parameters. It is much easier to debug and modify a small block of code then it is to run complex subroutine before you can test a code block.</p>\n\n<h2>Qualify References</h2>\n\n<p>You should avoid selecting and activating objects whenever possible. Using fully qualified ranges will make the code more efficient and less fragile. </p>\n\n<p>This line fails if <code>rDataSheet</code> is not the ActiveSheet because of the cells within the range not being qualified to <code>rDataSheet</code>. They are referencing the cells on the ActiveSheet.</p>\n\n<blockquote>\n<pre><code>With rDataSheet.Range(Cells(1, 1), Cells(1, colCount))\n</code></pre>\n</blockquote>\n\n<p>Here is how to properly reference ranges:</p>\n\n<blockquote>\n<pre><code>With rDataSheet\n .Range(.Cells(1, 1), .Cells(1, colCount))\n</code></pre>\n</blockquote>\n\n<h2>Generating Unique Keys</h2>\n\n<p>It is important to use a delimiter when creating a key. </p>\n\n<p>Generating keys for the table below without using a delimiter only yields two unique keys, even though, all rows are unique.</p>\n\n<p>+----------+----------+\n| Column A | Column B |\n+----------+----------+\n| 12 | 34 |\n+----------+----------+\n| 123 | 4 |\n+----------+----------+\n| 1234 | |\n+----------+----------+\n| ABC | DF |\n+----------+----------+</p>\n\n<h2>User Experience (UX)</h2>\n\n<ul>\n<li>Hyperlinking to a hidden sheet. I'm guessing you'll fix this using the <code>Worksheet_FollowHyperlink</code> event</li>\n<li>330 hidden WorkSheets? You probably just delete them between runs but wouldn't it be easier to create a new Workbook for the report?</li>\n</ul>\n\n<h2>Naming Convention</h2>\n\n<ul>\n<li><code>headerColl</code>: This is obviously the Column Headers. Oh, my mistake, it is the columns used to generate unique keys. But doesn't \"concatenate each cell in the row into a temp string variable\" suggest that each cell in the row is part of the unique key? This explains why there is a worksheet for each key. Otherwise, all the rows per each key worksheet would be identical. Anyway, I would use <code>keyColumns</code>.</li>\n<li>rDataLastRow: DataLastRow</li>\n<li>rDataSheet: DataSheet, wsData</li>\n<li><p>tempStr1: There is value in being able to watch tempStr1 in the Locals Window or add a watch. But in my opinion, it is just clutter. Helper variables should be used to make the code more readable. This looks easier to read to me:</p>\n\n<pre><code>For x = 1 To UBound(headerArray)\n str1 = str1 & Cells(y, headerArray(x))\nNext x\n</code></pre></li>\n</ul>\n\n<h2>Can it be done faster?</h2>\n\n<p>Hell yeah.\nAltough, not 100% to specs, this code is over 8 times faster. </p>\n\n<pre><code>Option Explicit\nPrivate Const Delimiter As String = \"|\"\n\nSub Main()\n Dim t As Double: t = Timer\n Application.ScreenUpdating = False\n Dim groups As New Scripting.Dictionary, subDic As Scripting.Dictionary\n Set groups = getRowsGroupedByDuplicateKeyColumns(ThisWorkbook.Worksheets(1), 1, 2, 3, 4)\n\n Dim wbReport As Workbook\n Set wbReport = CreateReport(groups)\n\n Dim key As Variant\n For Each key In groups\n Set subDic = groups(key)\n AddDuplicatesWorksheet wbReport, subDic\n Next\n Debug.Print Round(Timer - t, 2)\nEnd Sub\n\nPrivate Function CreateReport(ByRef groups As Scripting.Dictionary) As Workbook\n Dim wb As Workbook\n Set wb = Workbooks.Add\n Dim subDic As Scripting.Dictionary\n Dim key As Variant, results As Variant\n\n For Each key In groups\n Set subDic = groups(key)\n '.......\n Next\n\n Set CreateReport = wb\nEnd Function\n\nPrivate Sub AddDuplicatesWorksheet(wbReport As Workbook, subDic As Scripting.Dictionary)\n Dim key As Variant, results() As Variant, rowData() As Variant\n\n Dim r As Long, c As Long\n For Each key In subDic\n rowData = subDic(key)\n If r = 0 Then ReDim results(1 To subDic.count, 1 To UBound(rowData) + 1)\n\n r = r + 1\n results(r, 1) = key\n For c = 1 To UBound(rowData)\n results(r, c + 1) = rowData(c)\n Next\n Next\n\n With wbReport.Worksheets.Add\n .Range(\"A1\").Resize(UBound(results), UBound(results, 2)).Value = results\n End With\n\nEnd Sub\n\nPrivate Function getRowsGroupedByDuplicateKeyColumns(ByRef ws As Worksheet, ParamArray KeyColumns() As Variant) As Scripting.Dictionary\n Dim dic As New Scripting.Dictionary\n Dim data() As Variant\n With ws\n data = .Range(.Range(\"A1\", .Range(\"A1\").End(xlToRight)), .Range(\"A1\", .Cells(.Rows.count, 1).End(xlUp))).Value\n End With\n\n Dim key As Variant, keyData() As Variant, rowData() As Variant\n Dim r As Long, c As Long, keyIndex As LongPtr\n ReDim keyData(0 To UBound(KeyColumns))\n ReDim rowData(1 To UBound(data, 2))\n\n For r = 2 To UBound(data)\n For c = 0 To UBound(KeyColumns)\n keyIndex = KeyColumns(c)\n keyData(c) = data(r, keyIndex)\n Next\n For c = 1 To UBound(data, 2)\n rowData(c) = data(r, c)\n Next\n key = Join(keyData, Delimiter)\n If Not dic.Exists(key) Then dic.Add key, New Scripting.Dictionary\n dic(key).Add r, rowData\n Next\n Set getRowsGroupedByDuplicateKeyColumns = dic\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:27:53.677",
"Id": "216647",
"ParentId": "216494",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T18:59:42.880",
"Id": "216494",
"Score": "8",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Speed up VBA with 138k rows and ~330 sheet creation"
} | 216494 |
<p>I have the following <code>log4j2.properties</code> file:</p>
<pre><code>status = info
name = my-app
# properties
property.name = my-app
property.basePath = log
property.filename = ${basePath}/${name}.log
# console layout
appender.console.type = Console
appender.console.name = console-logger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{ISO8601} %-5p [%t] %c{1}.%M:%L - %msg%n
# rolling layout
appender.rolling.type = RollingFile
appender.rolling.name = rolling-file-logger
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = ${basePath}/${name}-%d{yyyy-MM-dd-hh-mm}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{ISO8601} %-5p [%t] %c{1}.%M:%L - %msg%n
# rolling policies
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
# root logger
rootLogger.level = info
rootLogger.appenderRefs = rolling, stdout
rootLogger.appenderRef.console.ref = console-logger
rootLogger.appenderRef.rolling.ref = rolling-file-logger
</code></pre>
<p>The main criteria I am aiming for is:</p>
<ol>
<li>Log files to <code>log/my-app.log</code>.</li>
<li>Rollover log files each minute to <code>log/my-app-yyyy-MM-dd-hh-mm.log</code>.</li>
</ol>
<p>The properties file above works for my purposes, but I would like to remove redundancy wherever possible.</p>
<p>A couple questions:</p>
<ol>
<li>Is there a way to use the variable <code>name = my-app</code>? I created another variable <code>property.name</code>, but not entirely sure that's necessary.</li>
<li>Both <code>console-logger</code> and <code>rolling-file-logger</code> have the same <code>layout.type</code> and <code>layout.pattern</code>. Is there a simpler way to have both loggers use the same <code>layout.type</code> and <code>layout.pattern</code> without defining it twice?</li>
<li>Any other opportunities for simplifying.</li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:15:35.633",
"Id": "216495",
"Score": "1",
"Tags": [
"logging",
"properties"
],
"Title": "Refactor log4j2 properties file"
} | 216495 |
<p>I was creating a script to pull data from a SharePoint list and display its contents in graphical form on another page. My original script was very messy and I had <a href="https://codereview.stackexchange.com/q/216294/194653">asked advice</a> on how I should increase readability. Taking some inspiration from <a href="https://github.com/stevekwan/experiments/blob/master/javascript/module-pattern.html" rel="nofollow noreferrer">Steve Kwan's GitHub</a> I tried to refactor to the script below. It's about twice as long as the previous one but I believe much more readable.</p>
<p>I would like some advice on where/how I can improve this script. Primarily in terms of style, but any obvious efficiencies would be appreciated as well.</p>
<p>I do have to make the script compatible with Explorer, so new(er) functionality such as arrow expressions (<code>arr.map(a => a*2)</code>) or spread syntax (<code>[obj, ...arr2]</code> isn't usable. </p>
<pre><code>// Namespace for the current initiative
var printingStatistics = printingStatistics || {};
// Module for showing the current page statistics
printingStatistics.graphPages = function () {
var oData = null; // Data array sent to the Google Chart
var oElem = null;
// initializing method. Inputs are Data and a document.querySelector() input.
var init = function (data, location) {
if (!data)
printingStatistics.requireData('data')
if (!location)
printingStatistics.requireData('location')
// Create the parent element that the chart(s) will be inserted into the page.
oElem = document.createElement("div");
oElem.id = "container";
oElem = document.querySelector(location).appendChild(oElem);
dataManip(data);
}
// data aggregator for each object name.
var dataManip = function (data) {
oData = {};
// Itterate through the data and put it in a more useable format.
for (var i = 0; i < data.length; i++) {
// Should be either Current Quarter or Previous Quarter
var qStatus = data[i][1];
// Take the name and remove sub categorization (-zvl) and
// replace an observed discontinuity (Counsel) in names.
var qStatusGroup = data[i][0].replace(/\s*\-\s*ZVL/i, "").replace(/Council/g, "Counsel");
// Will be the n-th week within a Quarter. Used to combine entries from the same week.
var weekNumbers;
// variable shortener for temporary use.
var tmp = null;
// 2 long array holding [number of pages, week Number]
var pageWeekTuple = null;
if (["Current Quarter", "Previous Quarter"].indexOf(qStatus) === -1)
continue;
// Create backbone of datastructure from the initialized attributes
if (!oData[qStatus])
oData[qStatus] = {};
if (!oData[qStatus][qStatusGroup])
oData[qStatus][qStatusGroup] = [];
tmp = oData[qStatus][qStatusGroup];
if (qStatus === "Current Quarter") {
// Take the date value and find week number the date was in.
// week = (ISO week of the year) - ( (Quarter #) -1 ) * 13
var eDate = new Date(data[i][2]);
var week = eDate.getWeek() - (eDate.getWeekQuarter() - 1) * 13;
// Get a duplicate week, if it exists
pageWeekTuple = tmp[tmp.map(function (o) {
return o[0] === week
}).indexOf(true)]
// Was there a duplicate? If not, create a new array.
if (!pageWeekTuple) {
tmp.push([0, 0])
pageWeekTuple = tmp[tmp.length - 1];
}
// week = (ISO week of the year) - ( (Quarter #) -1 ) * 13
pageWeekTuple[0] = eDate.getWeek() - (eDate.getWeekQuarter() - 1) * 13;
}
else if (qStatus === "Previous Quarter") {
// Only interested in one array here. There shouldn't be any duplicates.
if (!tmp[tmp.length - 1])
tmp.push([0, 0])
pageWeekTuple = tmp[tmp.length - 1]
}
// Sum all the weeks page numbers together
pageWeekTuple[1] += data[i][3];
}
google.charts.setOnLoadCallback(defineCharts);
}
// Creates the columns and rows for the Google Chart
var defineCharts = function () {
var gDataTable = new google.visualization.DataTable();
var cols = [];
// Create the rows for each label in the Google Chart
for (var propert in oData["Current Quarter"]) {
// If the label isn't in both Previous Quarter or Current Quarter, skip it.
if (!oData["Previous Quarter"].hasOwnProperty(propert)) continue;
if (!oData["Current Quarter"].hasOwnProperty(propert)) continue;
// [Label, col1, col2, ...]
var row = [];
row.push(propert);
// For each item for the current label, compare its value to the previous quarter's total
// Push that ratio off as a percentage (0-100) and push a placeholder value in for the tooltip.
oData["Current Quarter"][propert].forEach(function (obj) {
var lastQuarter;
if (oData["Previous Quarter"][propert])
lastQuarter = oData["Previous Quarter"][propert][0][1]
var ratio = Math.round(obj[1] / lastQuarter * 2000) / 20
row.push(ratio);
row.push(0);
});
// Get the cumulative percentage and create the tooltip HTML string.
var total = parseInt(20 * row.slice(1).sum()) / 20
for (var i = 2; i < row.length; i += 2) {
row[i] = createHTMLObject(propert, total, row[i - 1], parseInt(i / 2)).outerHTML;
}
// Finish by pushing the row to a collection array.
cols.push(row);
}
// Filter each column by type === number and sort them in increasing order.
cols.sort(function (a, b) {
var f = function (v) {
return typeof v === 'number'
}
var first = a.filter(f).sum()
var second = b.filter(f).sum()
return first - second
});
// Find the largest length sub-array in the 2d array.
var highest = 0;
highest = Math.max.apply(
Math,
cols.map(function (o) {
return o.length
})
);
// Add the respective columns.
// Every even column >0 is a tooltip
// Every odd column is a week's ratio value
gDataTable.addColumn('string', 'SBU');
for (var i = 1; i < highest; i++) {
if (i % 2)
gDataTable.addColumn('number', "Week " + (i).toString());
else
gDataTable.addColumn({
'type': 'string',
'role': 'tooltip',
'id': 'Quarter (%):',
'p': {
'html': true
}
});
}
// add the rows to the table, now that the columns are sorted
// Draw the table with the specified title.
gDataTable.addRows(cols)
drawChart('Percentage of pages printed, relative to last quarter (by SBU)', gDataTable)
}
// Draws the Google Charts chart with pre-defined options
// Inputs are the title of the Chart (chartTitle)
// the data to be displayed.
var drawChart = function (chartTitle, dTable) {
var options = {
title: chartTitle,
legend: 'none',
height: 700,
isStacked: true,
'tooltip': {
'isHtml': true
},
colors: ['#137C14', '#257F15', '#378216', '#498517', '#5B8818', '#6D8B1A', '#7F8E1B', '#92911C', '#A4941D', '#B6971F', '#C89A20', '#DA9D21', '#ECA022', '#FFA324']
};
// Instantiate and draw the chart.
var elem = createContainer(chartTitle.replace(/[^a-zA-Z]/g, ""));
var chart = new google.visualization.ColumnChart(elem);
chart.draw(dTable, options);
}
// Creates containers as needed, with the id being a string who's
// non-alpha characters are stripped
var createContainer = function (id) {
var newElem = document.createElement("div");
newElem.id = id.replace(/[^a-zA-Z]+/);
oElem.appendChild(newElem);
return newElem;
}
// Creates the tooltips for each weeks data.
// Creates the element structured as follows:
// <returnElem><titleElem/><totalElem/><weekElem/></returnElem>
var createHTMLObject = function (Title, totalPercent, weekPercent, weekNum) {
var returnElem = document.createElement('div');
var titleElem = document.createElement('div');
titleElem.textContent = Title
titleElem.style.fontWeight = 'bolder'
var totalElem = document.createElement('div');
totalElem.textContent = 'Quarter (%): ' + totalPercent.toString() + '%'
var weekElem = document.createElement('div');
weekElem.textContent = 'Week ' + weekNum + ' (%): ' + weekPercent.toString() + '%'
returnElem.appendChild(titleElem)
returnElem.appendChild(totalElem)
returnElem.appendChild(weekElem)
return returnElem;
}
// Getter for the Data created.
var getData = function () {
return oData;
}
// Makes variables/methods public.
var oPublic = {
init: init,
getData: getData
}
return oPublic;
}();
// Module for collecting user-specified data.
printingStatistics.executeQueries = function () {
var oListTitle = null; // To prepare the ClientContext
var oViewTitle = null; // To prepare the ClientContext
var oView; // To prepare the ClientContext
var oProperties = null; // Push the specified properties into oDictStats
var oItems = null; // Used to initialize the enumerator after async request
var oClientContext = null; // used to hold ClientContext for later use
var oDictStats = null; // Output variable
// Define intenral variables
var init = function (listName, properties, viewName) {
if (!listName)
printingStatistics.requireData('listName')
oListTitle = listName;
if (viewName)
oViewTitle = viewName;
if (properties)
oProperties = properties
}
// Run the queries after initializing.
// Ensures sp.js is loaded and that sp.clientContext is available.
var execute = function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', queryInit);
}
// First query.
// If there's a list view defined (oViewTitle) then get the CAML query from the view
// Otherwise get all items from list. This can be long if many items in list.
var queryInit = function () {
var oList;
oClientContext = new SP.ClientContext.get_current();
oList = oClientContext.get_web().get_lists().getByTitle(oListTitle);
if (oViewTitle) {
oView = oList.get_views().getByTitle(oViewTitle);
oClientContext.load(oView);
oClientContext.executeQueryAsync(
queryGetListView,
queryFailed
);
}
else {
oItems = oList.getItems();
oClientContext.load(oItems);
oClientContext.executeQueryAsync(
queryGetListItems,
queryFailed
);
}
}
// On failed queries, notify the user.
var queryFailed = function (sender, args) {
alert('Request failed. ' + args.get_message() + '\n' +
args.get_stackTrace() + '\n' +
'Please contact an administrator');
}
// Get the CAML view from the list, then get all items from said view.
var queryGetListView = function (sender, args) {
oClientContext = new SP.ClientContext.get_current();
oList = oClientContext.get_web().get_lists().getByTitle(oListTitle);
var query = new SP.CamlQuery();
query.set_viewXml(oView.get_viewQuery());
oItems = oList.getItems(query);
oClientContext.load(oItems);
oClientContext.executeQueryAsync(
queryGetListItems,
queryFailed
);
}
// enumerates through the items and pulls the requeisted data from objects.
var queryGetListItems = function (sender, args) {
var listItemEnumerator = oItems.getEnumerator();
var oListItem;
oDictStats = [];
while (listItemEnumerator.moveNext()) {
// Get all defined fields
oListItem = listItemEnumerator.get_current().get_fieldValues();
var quarter = oListItem.PreviousOrCurrentQuarter;
var itemTitle = oListItem.Title.replace(/\s*\-\s*ZvL/i, "");
var itemStats = [];
// if properties were defined by requester, pull the data
// Otherwise pull the whole object.
if (oProperties) {
for (var i = 0; i < oProperties.length; i++) {
itemStats.push((oListItem[oProperties[i]]));
}
}
else {
itemStats.push(oListItem);
}
oDictStats.push(itemStats);
}
}
// Getter for the stats.
var getStats = function () {
return oDictStats;
}
// Makes variables and methods available to public.
var oPublic = {
init: init,
execute: execute,
getStats: getStats
}
return oPublic;
}();
// For throwing errors when there's missing data
printingStatistics.requireData = function (paramName) {
throw "Missing parameter: " + paramName.toString();;
}
// Module for adding additional functionalty to datastructures
printingStatistics.addPrototypes = function () {
/*
* * * * * * Additional Scripting tools * * * * * *
*
* This script is released to the public domain and may be used, modified and
* distributed without restrictions. Attribution not necessary but appreciated.
* Source: https://weeknumber.net/how-to/javascript
*
* Returns the ISO week of the date.
*/
Date.prototype.getWeek = function () {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 -
3 + (week1.getDay() + 6) % 7) / 7);
}
// Returns how many weeks are in a given year.
Date.prototype.getWeeksInYear = function () {
var date = new Date(this.getTime());
var isLeap = new Date(date.getYear() + 1900, 1, 29).getMonth() === 1;
//check for a Jan 1 that's a Thursday or a leap year that has a
//Wednesday jan 1. Otherwise it's 52
return date.getDay() === 4 || isLeap && date.getDay() === 3 ? 53 : 52
}
// Returns what quarter a specified date is in
Date.prototype.getWeekQuarter = function () {
var date = new Date(this.getTime());
weekNum = date.getWeek();
return weekNum == 53 ? 4 : Math.ceil(weekNum / 13);
}
// Creates a summation of the array
Array.prototype.sum = function () {
return this.reduce(function (a, b) {
return a + b
}, 0);
}
}();
var interval = null;
var done = function (obj) {
// Function called at interval that checks if the object exists and runs
// printingStatistics.graphPages.init() once it does.
if (obj) {
clearInterval(interval)
printingStatistics.graphPages.init(obj, ".ms-rte-layoutszone-inner")
}
}
printingStatistics.executeQueries.init(
"Printing Stats",
["Title",
"PreviousOrCurrentQuarter",
"RelevantDate",
"TotalPrintedPages"],
"Current Stats"
);
printingStatistics.executeQueries.execute()
interval = setInterval(function () {
done(printingStatistics.executeQueries.getStats())
}, 200)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:08:47.283",
"Id": "216497",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"data-visualization"
],
"Title": "Creating Google Charts on SharePoint"
} | 216497 |
<p>I’ve written a program for solving a problem using standard single-threaded code. However, it looks like it could be recast as a multi-threaded problem using divide & conquer. Since this is a first attempt at multi-thread programming (and debugging), I thought it might be advisable to separate the problem itself from the parallel management. The following is a multi-threaded divide & conquer skeleton, which hopefully the actual problem could fit into. I would appreciate a code check and any relevant advice about how to better code multi-threaded applications like this.</p>
<p>The skeleton uses the Lparallel library with queues for communicating among the threads. There is a main thread which initializes the queues & threads, submits the problem, and then blocks waiting for a solution. The problem is submitted to a pool of threads, whose number can range up to one less than the number of hardware processors available. Each idle thread blocks until a (sub)problem becomes available on the <em>problems</em> queue, which it may then then capture. If the problem size is above a minimal <em>problem-size-cutoff</em>, the thread splits off a subproblem (randomly to simulate the uncertainty in how much future processing the subproblem will require). The subproblem is pushed onto the <em>problems</em> queue so another idle thread can deal with it subsequently, and the thread then continues processing with what’s remaining of the problem after the split. When a thread finishes working on its problem, it reports that it is now idle via the <em>idles</em> queue. When any thread (namely, the last thread running) observes that all threads are idle, it reports problem complete via the <em>done</em> queue.</p>
<p>To run the following code, simply switch to the :test package and execute (main) after loading. The printout shows when any thread receives a problem (its size—eg, 34), and if it is split, what the random split is—eg, (13 21). If it is not split because it is too small, the printout just shows the simulated processing of what’s remaining.</p>
<p>Secondary questions: 1) The function <em>main</em> uses up a whole thread just waiting for problem completion. Is there a way to use this thread too? 2) Can the number of queues or queue accesses be reduced? 3) Would a so-called sequence diagram be the best way to verify correctness? Ie, is this worth learning, or is there a better way. (Ps: The program seems to run OK, but I’m not even sure how to simulate the duration of a thread.) Thanks for any time you can spare.</p>
<p>EDITS 3/30/19: 1) Replaced <code>with-temp-kernel (1)</code> with <code>(setf lparallel:*kernel* (lparallel:make-kernel *num-threads*))</code> and <code>(lparallel:end-kernel)</code> to follow library recommended way to start and stop lparallel kernel. 2) Added tracing queues for each thread to collect each thread’s problem solution progress for debugging. 3) Added epilog code to main to printout the trace of each thread after kernel shutdown, in order to avoid printing interference during shutdown.</p>
<pre><code>#-:lparallel (ql:quickload :lparallel)
(defpackage :test (:use :cl :lparallel :lparallel.queue))
(in-package :test)
(defparameter *num-threads* 2) ;available problem-solving threads (excludes main thread-0)
(defparameter *problem* 100) ;estimated size of the main problem
(defparameter *problem-size-cutoff* 5) ;don't split small problems
(defun thread (problems idles trace done)
"Definition for a problem-solving thread."
(loop do
(let ((problem (pop-queue problems))) ;blocks until a problem is available
(pop-queue idles) ;one (this) thread is no longer idle
(push-queue problem trace) ;track this thread's solution of its problem
(loop do
(when (and (> problem (* 2 *problem-size-cutoff*)) ;don't split if small problem
(>= (queue-count idles) 1)) ;ie, some threads are idle
(let ((n (+ (random (- problem (* 2 *problem-size-cutoff*)))
*problem-size-cutoff*))) ;split problem
(sleep .01) ;time to run splitting algorithm
(push-queue n problems) ;n is random size of subproblem split
(setf problem (- problem n)) ;remaining problem size after split
(push-queue (list n problem) trace))) ;track this thread's splitting
(decf problem) (sleep .1) ;work more on current problem
(push-queue problem trace) ;track this thread's incremental progress
(when (= problem 0) ;is this thread's task complete?
(push-queue t idles) ;this thread now idle
(if (= (queue-count idles) *num-threads*) ;all threads idle
(progn (push-queue t done) ;signal all done to main
(return-from thread))
(return))))))) ;return from inner loop to get new problem
(defun main ()
"The main consumer of parallel thread processing."
(setf lparallel:*kernel* (lparallel:make-kernel *num-threads*))
(let ((c (make-channel))
(problems (make-queue)) ;holds current problems to be solved
(idles (make-queue)) ;holds a t for each current idle thread
(traces nil) ;holds a trace of the progress of each thread for debugging
(done (make-queue))) ;signals t when all processing is done
(loop for i from 1 to *num-threads* ;get all threads up & running
do (let ((trace (make-queue))) ;track the progress of a thread using a queue
(push trace traces)
(submit-task c #'thread problems idles trace done)
(push-queue t idles))) ;each t in idles means a thread is currently idle
(push-queue *problem* problems) ;send the main problem to the thread pool
(pop-queue done) ;block until thread pool reports done
(let ((list-of-traces ;collect each thread's trace before shutting down kernel
(map 'list (lambda (trace)
(loop until (queue-empty-p trace)
collect (pop-queue trace)))
traces)))
(lparallel:end-kernel)
(loop for rtrace in (reverse list-of-traces) ;printout each thread's trace
do (print rtrace))))) ;final print to avoid interference with shutdown
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:48:44.680",
"Id": "216500",
"Score": "5",
"Tags": [
"multithreading",
"common-lisp",
"multiprocessing",
"divide-and-conquer"
],
"Title": "A Parallel Processing Template for Divide & Conquer Problems"
} | 216500 |
<p>Here is the link to the next round of code review: <a href="https://codereview.stackexchange.com/questions/216758/linked-list-implementation-along-with-unit-test-round-3">Linked list implementation along with unit test [Round 3]</a></p>
<p>Here's the link to the previous code review:
<a href="https://codereview.stackexchange.com/questions/216453/linked-list-implementation-along-with-unit-test">Linked list implementation along with unit test</a></p>
<p>Implementation</p>
<pre><code>/*************************************************************************************************************
*
* Special Thanks to Henrik Hansen for the awesome code review!
* Url: https://codereview.stackexchange.com/questions/216453/linked-list-implementation-along-with-unit-test
*
*************************************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
namespace DataStructuresAndAlgorithms.DataStructures
{
public class LinkedList<T> : IEnumerable<T>
{
class Node
{
public T Data { get; }
public Node Next { get; set; }
public Node Previous { get; set; }
public Node(T data)
{
Data = data;
}
}
private Node _head, _tail;
public T Head => _head == null ? throw new ArgumentNullException("Head is null") : _head.Data;
public T Tail => _tail == null ? throw new ArgumentNullException("Tail is null") : _tail.Data;
public LinkedList() { }
public LinkedList(IEnumerable<T> items)
{
foreach (var item in items)
{
AddTail(item);
}
}
public void AddHead(T item)
{
if (item == null)
throw new ArgumentNullException("AddHead: An item you are trying to add is not initialized!");
if (_head == null && _tail == null)
{
_head = new Node(item);
_tail = _head;
}
else
{
_head.Previous = new Node(item);
var temp = _head;
_head = _head.Previous;
_head.Next = temp;
}
}
public void AddTail(T item)
{
if (item == null)
throw new ArgumentNullException("AddTail: An item you are trying to add is not initialized!");
if (_tail == null && _head == null)
{
_tail = new Node(item);
_head = _tail;
}
else
{
_tail.Next = new Node(item);
var temp = _tail;
_tail = _tail.Next;
_tail.Previous = temp;
}
}
public void RemoveHead()
{
if (_head == null) return;
else
{
_head = _head.Next;
if (_head == null) return;
_head.Previous = null;
}
}
public void RemoveTail()
{
if (_tail == null) return;
else
{
_tail = _tail.Previous;
if (_tail == null) return;
_tail.Next = null;
}
}
public bool Remove(T item)
{
var pointer = _head;
while (pointer.Data.Equals(item) == false)
{
if (pointer.Next == null)
return false;
pointer = pointer.Next;
}
if (pointer.Previous == null)
{
// It is the Head
pointer.Next.Previous = null;
return true;
}
if (pointer.Next == null)
{
// It is the Tail
pointer.Previous.Next = null;
return true;
}
pointer.Previous.Next = null;
pointer.Next.Previous = null;
return true;
}
public IEnumerator<T> GetEnumerator()
{
var pointer = _head;
while (pointer != null)
{
yield return pointer.Data;
pointer = pointer.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
</code></pre>
<p>Unit Test</p>
<pre><code>using System;
using Xunit;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.DataStructures.Tests
{
public class LinkedListTest
{
[Fact]
public void AddHead_Node_Should_Become_Head()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.AddHead(45);
// Assert
Assert.Equal(45, myLinkedList.Head);
}
[Fact]
public void AddTail_Node_Should_Become_Tail()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.AddTail(7777);
// Assert
Assert.Equal(7777, myLinkedList.Tail);
}
[Fact]
public void RemoveHead_Next_Node_Should_Be_Head()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.RemoveHead();
// Assert
Assert.Equal(2, myLinkedList.Head);
}
[Fact]
public void RemoveTail_Next_Node_Should_Be_Tail()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.RemoveTail();
// Assert
Assert.Equal(4, myLinkedList.Tail);
}
}
}
</code></pre>
<p>Presentation</p>
<pre><code>using System;
using System.Collections;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.Presentation.Console
{
class Program
{
static void Main(string[] args)
{
RunLinkedList();
}
static void RunLinkedList()
{
System.Console.WriteLine("Running the LinkedList class");
System.Console.WriteLine("----------------------------");
var myLinkedList = new LinkedList<int>();
myLinkedList.AddHead(54);
myLinkedList.AddHead(44);
myLinkedList.AddHead(96);
myLinkedList.AddTail(300);
myLinkedList.AddTail(900);
myLinkedList.AddTail(77);
myLinkedList.Remove(900);
System.Console.WriteLine("HEAD = " + myLinkedList.Head);
System.Console.WriteLine("TAIL = " + myLinkedList.Tail);
foreach (var item in myLinkedList)
{
System.Console.WriteLine(item);
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T21:43:15.677",
"Id": "418852",
"Score": "0",
"body": "I have found an error where it prints the wrong tail. I will be fixing this. This means I must be missing some tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:33:30.333",
"Id": "418853",
"Score": "0",
"body": "I find it difficult to add valuable tests like `public void Head_Should_Only_Have_Previous_Equal_NULL()` and `public void Tail_Should_Only_Have_Next_Equal_NULL()` when my `_head` and `_tail` member variables are set to private."
}
] | [
{
"body": "<ul>\n<li><p><code>Remove...</code> family methods fail with an exception if from the list is of size 1. <code>pointer.Previous == null</code> does not mean that <code>pointer.Next</code> is not.</p></li>\n<li><p>It is quite important to convey a success/failure of the removal to the caller. <code>Remove</code> should return at least a boolean.</p></li>\n<li><p>I am not sure why do you disallow a <code>Node</code> having <code>null</code> data. In any case, if you want to enforce it, do it in a <code>Node</code> constructor, rather than in insertion methods.</p></li>\n<li><p><code>AddHead</code> should be streamlined. After all, the <code>new Node</code> is created in both branches, and becomes <code>head</code> no matter what. Lift the common functionality out:</p>\n\n<pre><code>public void AddHead(T item)\n{\n var node = new Node(item);\n node.Next = _head;\n\n if (_head == null && _tail == null)\n {\n _tail = node;\n }\n else\n {\n _head.Previous = node;\n }\n _head = node;\n}\n</code></pre>\n\n<p>Ditto for <code>AddTail</code>.</p></li>\n<li><p>A <code>while (pointer.Data.Equals(item) == false)</code> loop deserves to become a <code>Find</code> method.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:54:44.087",
"Id": "216511",
"ParentId": "216503",
"Score": "4"
}
},
{
"body": "<p>Much better.</p>\n\n<p>I have the following to add to vnp's answer:</p>\n\n<blockquote>\n<pre><code>public T Head => _head == null ? throw new ArgumentNullException(\"Head is null\") : _head.Data;\npublic T Tail => _tail == null ? throw new ArgumentNullException(\"Tail is null\") : _tail.Data;\n</code></pre>\n</blockquote>\n\n<p>Instead of <code>ArgumentNullException</code> it's better to use <code>NullReferenceException</code> because there is no argument.</p>\n\n<hr>\n\n<p>Instead of iterating this way:</p>\n\n<blockquote>\n<pre><code> while (pointer.Data.Equals(item) == false)\n {\n if (pointer.Next == null)\n return false;\n pointer = pointer.Next;\n }\n</code></pre>\n</blockquote>\n\n<p>I find it more intuitive to do:</p>\n\n<pre><code> Node node = _head;\n while (node != null)\n {\n if (item.Equals(node.Data))\n {\n break;\n }\n\n node = node.Next;\n }\n\n if (node == null) return false;\n</code></pre>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code> if (pointer.Previous == null)\n {\n // It is the Head\n pointer.Next.Previous = null;\n return true;\n }\n</code></pre>\n</blockquote>\n\n<p>consider reuse <code>RemoveHead()</code>:</p>\n\n<pre><code> if (node == _head)\n {\n RemoveHead();\n return true;\n }\n</code></pre>\n\n<p>That will be more DRY. And you can do the same for the tail.</p>\n\n<hr>\n\n<p>You could consider to implement:</p>\n\n<pre><code>public bool IsEmpty { get; }\npublic int Count { get; }\n</code></pre>\n\n<hr>\n\n<p>You tests seems OK to me. You're missing one for <code>Remove(T value)</code>. </p>\n\n<p>About \"Head_Should_Only_Have_Previous_Equal_NULL\": unit tests are about testing the public interface of an object, so checking for <code>_head.Previous == null</code> should be tested indirectly through testing the public interface. In fact you'd have to test for it every time you make a change to the list. An indirect test could be trying to remove the head or tail from an empty list. If that doesn't fail, it may indicate that something is wrong with the handling of <code>Node.Previous</code>. In your case, you'll then have to throw or return false from <code>RemoveHead()</code> to find out...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T09:21:57.747",
"Id": "216520",
"ParentId": "216503",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T21:09:35.520",
"Id": "216503",
"Score": "4",
"Tags": [
"c#",
"beginner",
"linked-list",
"unit-testing"
],
"Title": "Linked list implementation along with unit test - Round 2"
} | 216503 |
<p>I do not know how to do this without four nested <code>for</code> loops. </p>
<p>I'd like to apply a function to every possible combination of subsets for <code>hour</code> and <code>day</code>, return that value, and then pivot the data frame into a square matrix. However, these <code>for</code> loops seem excessive so I'm looking for a more efficient way to do this. The data I have is fairly large so any gain in speed would be beneficial.</p>
<p>I took a stab at compression lists but that seems excessive too. </p>
<p>The following code runs fine with smaller groups (<code>days=1:2</code> and hours=<code>1:2</code>) but with large groups, say years of data, performance is lost.</p>
<p>Note: I'm requesting help given any custom function, not just a cross-product solution as suggested here, <a href="https://stackoverflow.com/questions/53699012/performant-cartesian-product-cross-join-with-pandas">Performant cartesian product (CROSS JOIN) with pandas</a></p>
<p><strong>Sample data</strong></p>
<pre><code>import pandas as pd
import numpy as np
dat = pd.DataFrame({'day': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'hour': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'distance': {0: 1.2898851269657656, 1: 0.0, 2: 0.8371526423804061, 3: 0.8703856587273138, 4: 0.6257425922449789, 5: 0.0, 6: 0.0, 7: 0.0, 8: 1.2895328696587023, 9: 0.0, 10: 0.6875527848294374, 11: 0.0, 12: 0.0, 13: 0.9009031833559706, 14: 0.0, 15: 1.1040652963428623, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.0}})0}})
</code></pre>
<p><strong>Code</strong></p>
<pre><code>def custom_fn(x, y):
x = pd.Series(x)
y = pd.Series(y)
x = x**2
y = np.sqrt(y)
return x.sum() - y.sum()
# Empty data.frame to append to
dmat = pd.DataFrame()
# For i, j = hour; k, l = day
for i in range(1, 3):
for j in range(1, 3):
for k in range(1, 3):
for l in range(1, 3):
x = dat[(dat['hour'] == i) & (dat['day'] == k)].distance
y = dat[(dat['hour'] == j) & (dat['day'] == l)].distance
# Calculate difference
jds = custom_fn(x, y)
# Build data frame and append
outdat = pd.DataFrame({'day_hour_a': f"{k}_{i}", 'day_hour_b': f"{l}_{j}", 'jds': [round(jds, 4)]})
dmat = dmat.append(outdat, ignore_index=True)
# Pivot data to get matrix
distMatrix = dmat.pivot(index='day_hour_a', columns='day_hour_b', values='jds')
</code></pre>
<p><strong>Output</strong></p>
<pre><code>> print(distMatrix)
day_hour_b 1_1 1_2 2_1 2_2
day_hour_a
1_1 -0.2609 2.3782 1.7354 2.4630
1_2 -2.1118 0.5273 -0.1155 0.6121
2_1 -2.4903 0.1488 -0.4940 0.2336
2_2 -2.5557 0.0834 -0.5594 0.1682
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:44:26.687",
"Id": "418856",
"Score": "0",
"body": "@Alex Thanks. I corrected it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T23:53:46.830",
"Id": "418860",
"Score": "0",
"body": "Inside your 4-loops, are you expecting `x` and `y` to contain a single value each time through? That is, does `[day,hour]` represent a unique key for the distance column?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T00:01:30.387",
"Id": "418861",
"Score": "0",
"body": "Also, your answer may be in this SO question: https://stackoverflow.com/questions/53699012/performant-cartesian-product-cross-join-with-pandas"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T01:24:57.710",
"Id": "418863",
"Score": "0",
"body": "@AustinHasting `x` and `y` will be subset `pd.Series` provided to a custom function. Note that I don't need cross products because I will be using a custom function on each `day` and `hour`. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T22:16:48.147",
"Id": "419388",
"Score": "0",
"body": "I couldn't run this on account of a few extra characters at the end of the `dat = ` line."
}
] | [
{
"body": "<p>I'm afraid that I'm not familiar with pandas, so there are definitely some things that I'm missing. However, I've done a bit of poking this code with a profiler, and I have a two suggestions that I expect would be helpful. </p>\n\n<p>In my timings, over half of the runtime (3.5s out of 6.5s for 100 repetitions) in your example was spent on these two lines:</p>\n\n<pre><code>x = dat[(dat['hour'] == i) & (dat['day'] == k)].distance\ny = dat[(dat['hour'] == j) & (dat['day'] == l)].distance\n</code></pre>\n\n<p>If I understand the code correctly, <code>(dat['hour'] == i)</code> is passing over the whole dataset searching for indexes with the specified hour. Especially given that this is in the middle of a very hot loop, that seems like prime work to avoid doing! Consider changing the data structure to allow for quicker look ups: perhaps have a dictionary that maps your chosen hour to a list or set of indexes. </p>\n\n<hr>\n\n<p>Second, let's take a look at this <code>custom_fn</code></p>\n\n<pre><code>def custom_fn(x, y):\n x = pd.Series(x)\n y = pd.Series(y)\n x = x**2\n y = np.sqrt(y)\n return x.sum() - y.sum()\n</code></pre>\n\n<p>Now, I would normally not pay much attention to this function, because according to the profiler it just used up 8% of the total runtime. However, I did notice that it is almost completely seperable. The last line uses data derived from both <code>x</code> and <code>y</code> but until that you just use <code>x</code> for <code>x</code> things and <code>y</code> for <code>y</code> things. That suggests that there is considerable opportunity to cache the relevant <code>x.sum()</code> and <code>y.sum()</code> components, with the relevant calculations done outside of so deeply nested a loop.</p>\n\n<hr>\n\n<p>For reference, the following code is my initial go at using some of this caching approach. There is still plenty of opportunity to improve, including changing data structure as mentioned, but it is already significantly faster. It has come down from 6.5 seconds to 3.5 seconds in total, of which 2 seconds is packing the dmat table. </p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\ndat = pd.DataFrame({'day': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'hour': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2}, 'distance': {0: 1.2898851269657656, 1: 0.0, 2: 0.8371526423804061, 3: 0.8703856587273138, 4: 0.6257425922449789, 5: 0.0, 6: 0.0, 7: 0.0, 8: 1.2895328696587023, 9: 0.0, 10: 0.6875527848294374, 11: 0.0, 12: 0.0, 13: 0.9009031833559706, 14: 0.0, 15: 1.1040652963428623, 16: 0.0, 17: 0.0, 18: 0.0, 19: 0.0}})\n\ndef x_sum(x):\n x = pd.Series(x)\n x = x**2\n return x.sum()\n\ndef y_sum(y):\n y = pd.Series(y)\n y = np.sqrt(y)\n return y.sum()\n\ndef custom_fn(x_s, y_s):\n return x_s - y_s\n\ndef get_hour(i):\n return (dat['hour'] == i)\n\ndef get_day(k): \n return (dat['day'] == k)\n\ndef get_day_hour(hour, day):\n x = dat[hour & day].distance\n return x\n\n# Empty data.frame to append to\ndmat = pd.DataFrame()\n\nday_indices = {k : get_day(k) for k in range(1, 3)}\nhour_indices = {i : get_hour(i) for i in range(1, 3)}\n\nx_sum_indices = { (i, j): x_sum(get_day_hour(hour_indices[i], day_indices[j])) for i in range(1, 3) for j in range(1, 3)}\ny_sum_indices = { (i, j): y_sum(get_day_hour(hour_indices[i], day_indices[j])) for i in range(1, 3) for j in range(1, 3)}\n\n# For i, j = hour; k, l = day\nfor i in range(1, 3):\n for j in range(1, 3):\n for k in range(1, 3):\n for l in range(1, 3):\n x_s = x_sum_indices[(i, k)]\n y_s = y_sum_indices[(j, l)]\n\n # Calculate difference\n jds = custom_fn(x_s, y_s)\n\n # Build data frame and append\n outdat = pd.DataFrame({'day_hour_a': f\"{k}_{i}\", 'day_hour_b': f\"{l}_{j}\", 'jds': [round(jds, 4)]})\n dmat = dmat.append(outdat, ignore_index=True)\nreturn dmat\n\n# Pivot data to get matrix\ndistMatrix = dmat.pivot(index='day_hour_a', columns='day_hour_b', values='jds')\n\nprint(distMatrix)\n</code></pre>\n\n<p>If you had a different <code>custom_fn</code> function that was not so easily separable, you could still benefit from caching the inputs to the function. E.g. </p>\n\n<pre><code>x_indices = { (i, j): get_day_hour(hour_indices[i], day_indices[j]) for i in range(1, 3) for j in range(1, 3)}\ny_indices = x_indices\n\n...\n jds = custom_fn(x_indices[(i, k)], y_indices[(j, l)])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T23:33:52.283",
"Id": "216822",
"ParentId": "216508",
"Score": "2"
}
},
{
"body": "<p>With a little rework I was able to increase speed 4x.</p>\n\n<p><strong>Initial Code:</strong></p>\n\n<pre><code>start = time.time()\n# Empty data.frame to append to\ndmat = pd.DataFrame()\n\n# For i, j = hour; k, l = day\nfor i in range(1, 3):\n for j in range(1, 3):\n for k in range(1, 3):\n for l in range(1, 3):\n x = dat[(dat['hour'] == i) & (dat['day'] == k)].distance\n y = dat[(dat['hour'] == j) & (dat['day'] == l)].distance\n # Calculate difference\n jds = custom_fn(x, y)\n # Build data frame and append\n outdat = pd.DataFrame({'day_hour_a': f\"{k}_{i}\", 'day_hour_b': f\"{l}_{j}\", 'jds': [round(jds, 4)]})\n dmat = dmat.append(outdat, ignore_index=True)\n\n# Pivot data to get matrix\ndistMatrix = dmat.pivot(index='day_hour_a', columns='day_hour_b', values='jds')\n\nend = time.time()\n\nprint(end - start)\n</code></pre>\n\n<p><strong>Time 1</strong>:</p>\n\n<pre><code>> 0.07694768905639648\n</code></pre>\n\n<p><strong>Reworked code:</strong></p>\n\n<pre><code>start = time.time()\n\nx = []\ng = dat.groupby(['day', 'hour'])['distance']\nfor k1, g1 in g:\n for k2, g2 in g:\n x += [(k1, k2, custom_fn(g1, g2))]\n\nx = pd.DataFrame(x).pivot(index=0, columns=1, values=2)\n\nprint(x)\n\nend = time.time()\n\nprint(end - start)\n</code></pre>\n\n<p><strong>Time 2</strong></p>\n\n<pre><code>> 0.022540807723999023\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:33:13.947",
"Id": "216874",
"ParentId": "216508",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:21:53.600",
"Id": "216508",
"Score": "7",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Apply function to every subset combination and return square matrix"
} | 216508 |
<p>The task:</p>
<blockquote>
<p>Given a real number n, find the square root of n. For example, given n
= 9, return 3.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const findRoot = n => n >= 0 ? n ** .5 : void 0;
console.log(findRoot(9));
</code></pre>
<p>Is this some kind of trick question? What's there to solve? Did I miss something?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T00:27:39.713",
"Id": "418862",
"Score": "3",
"body": "-1 is a real number. You might also be meant to solve it without using `sqrt` or floating-point exponentiation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T01:11:54.363",
"Id": "419158",
"Score": "0",
"body": "It’s a binary search question."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:36:41.180",
"Id": "216509",
"Score": "1",
"Tags": [
"javascript",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find the square root of n"
} | 216509 |
<p>When I used to use a PC I was familiar with py2exe, the mac equivalent I saw most people talking about was py2app — which compiles python to .app files, not .exec files. I was familiar with compiling C files to execs on mac, and I had heard of cython (but I had never used it before), so I figured I could write something to go from python to cython to an exec. I initially did not write this for anyone else to use — but now I'm thinking about packaging it as a pip module.</p>
<p>This is my first time building a command line tool for executing shell commands and messing with files and directories.</p>
<pre class="lang-py prettyprint-override"><code>"""(PYCX) PYthon to Cython to eXec, a unix command line util
Usage:
pycx FILES... [-o DIR --show --delete --run]
pycx --help
Options:
FILES one or more python files to compile
-o --output=DIR output directory
-s --show show output from exec compiling
-d --delete delete the c file after compiling exec
-r --run run the exec after compiling
-h --help show this screen.
"""
import os, re
from docopt import docopt
args = docopt(__doc__)
# the two pathnames below tell gcc where python is so that cython can be compiled to an exec
INCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'
LIBRARY = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'
HIDEDATA = '&>/dev/null' # this is used to hide output while compiling C files
for pyFILE in args['FILES']:
if pyFILE.endswith('.py'): # file must be a python file
path, name = os.path.split(pyFILE) # split full path to seperate path & filename
cFILE = re.sub('\.py$', '.c', pyFILE) # name of the file with .c extension & path
FILE = re.sub('\.py$', '', name) # name of the file with no extension or path
PATH = path + '/' if path is not '' else '.' # if in current directory, path = '.'
OUTPUT = args['--output'] + '/' if args['--output'] else '' # blank if no arg given
SHOW = HIDEDATA if not args['--show'] else '' # will hide gcc output if SHOW is false
# this command will be used to delete the C file
DELETE = f'find {PATH} -name "{FILE}.c" -type f|xargs rm -f' if args['--delete'] else ''
RUN = f'./{OUTPUT}{FILE}' if args['--run'] else '' # command to run the exec
commands = [ # cython to make C file, gcc to compile to exec, and some options
f"cython --embed -o {cFILE} {pyFILE}", # convert python to cython C file
# compile cython C file to exec file
f"gcc -v -Os -I {INCLUDES} -L {LIBRARY} {cFILE} -o {OUTPUT}{FILE} " + \
# source python & other options -- hide or show, delete C file, run exec
f"-lpython3.7 -lpthread -lm -lutil -ldl {SHOW}", f"{DELETE}", f"{RUN}"
]
for command in commands:
os.system(command) # execute commands above, excluding blank commands
else:
print(__doc__) # show the help menu if user doesn't put a python file
</code></pre>
<p>Besides modifying <code>INCLUDES</code> and <code>LIBRARY</code> to work with varying path locations, are there any other major problems preventing this from working as a python module? Does this even seem like a tool some people might use?</p>
| [] | [
{
"body": "<p>I recommend that you <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">read PEP 8</a>.</p>\n\n<ul>\n<li>It's advised against doing <code>import os, re</code>. Instead have one line dedicated to each import.</li>\n<li>You should have an empty line between importing third party libraries and standard library ones.</li>\n<li>In Python it's standard to use <code>snake_case</code>.</li>\n<li>You should only have one space either side of the equals sign when performing assignment.</li>\n<li>Rather than doing <code>path is not ''</code> you should use the <code>!=</code> operator.</li>\n<li><code>'\\.py$'</code> is <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals\" rel=\"noreferrer\">deprecated in Python 3.6, and will become a syntax error in a future version of Python</a>. Instead use <code>r'\\.py$'</code>.</li>\n<li>Don't mix <code>'</code> and <code>\"</code> string delimiters. Unless it's to do <code>\"'\"</code>.</li>\n<li>You don't need to use a <code>\\</code> for line breaking as your within brackets.</li>\n<li>You should have the <code>+</code> in front of the next line, rather than the end of the previous line.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Your variable names are crap. <code>path</code>, <code>name</code> <code>FILE</code>, <code>cFILE</code>, <code>PATH</code>. The reason you need your comments is because of this.</li>\n<li>If you fix your variable names your comments are useless.</li>\n<li>Don't make a list to then call <code>os.system</code> just call it straight away.</li>\n<li>Use <code>pathlib</code>, it singlehandedly makes your code ridiculously simple.</li>\n<li>Put your code in an <code>if __name__ == '__main__'</code> guard. You don't want to destroy things by accident.</li>\n</ul>\n\n<p><sub>untested:</sub></p>\n\n<pre><code>\"\"\"(PYCX) PYthon to Cython to eXec, a unix command line util\nUsage:\n pycx FILES... [-o DIR --show --delete --run]\n pycx --help\n\nOptions:\n FILES one or more python files to compile\n -o --output=DIR output directory\n -s --show show output from exec compiling\n -d --delete delete the c file after compiling exec\n -r --run run the exec after compiling\n -h --help show this screen.\n\"\"\"\nimport os\nfrom pathlib import Path\n\nfrom docopt import docopt\n\n\nINCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'\nLIBRARY = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'\nHIDEDATA = '&>/dev/null'\n\n\ndef main(args):\n for path in args['FILES']:\n path = Path(path)\n if path.suffix != '.py':\n print(__doc__)\n continue\n\n output = Path(args['--output'] or '') / path.stem\n c_file = path.parent / path.stem + '.c'\n\n os.system(f'cython --embed -o {c_file} {path}')\n os.system(\n f'gcc -v -Os -I {INCLUDES} -L {LIBRARY} {c_file} '\n f'-o {output} -lpython3.7 -lpthread -lm -lutil -ldl '\n + HIDEDATA if not args['--show'] else ''\n )\n\n if args['--delete']:\n os.system(\n f'find {path.parent} -name \"{path.stem}.c\" -type f'\n f'|xargs rm -f'\n )\n\n if args['--run']:\n os.system(f'{output}')\n\n\nif __name__ == '__main__':\n main(docopt(__doc__))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:46:52.113",
"Id": "418913",
"Score": "0",
"body": "`you should use the != operator`\n\nEh, not really. I posted a small answer on that in particular. Otherwise this seems sane."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:21:45.030",
"Id": "418935",
"Score": "0",
"body": "Would `c_file = path.parent / (path.stem + '.c')` do something different then what you have? It seems like this works better.\nThanks for your valuable tips!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T12:12:23.030",
"Id": "418962",
"Score": "0",
"body": "@Reinderien I'd like to point out that that is only talking about the `is` operator in that line, not the turnery logic too. Hence why it's in the pep8 section of my answer and changed to use pathlib and an or in my code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T02:57:13.850",
"Id": "216515",
"ParentId": "216510",
"Score": "5"
}
},
{
"body": "<p>This code is obviated by @Peilonrayz, which has posted a good solution. However, in the future, if you need to do something like</p>\n\n<pre><code>PATH = path + '/' if path is not '' else '.'\n</code></pre>\n\n<p>you're better off to do</p>\n\n<pre><code>PATH = (path or '.') + '/'\n</code></pre>\n\n<p>Otherwise, the other suggestion is complete.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:17:22.040",
"Id": "418933",
"Score": "1",
"body": "Yes! After editing my code based on his suggestions I was beginning to realize I can do this variable assignments, I'm glad I know this now. Thanks for the tip!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:45:52.033",
"Id": "216543",
"ParentId": "216510",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T22:43:16.410",
"Id": "216510",
"Score": "4",
"Tags": [
"python",
"compiler",
"cython"
],
"Title": "Python command line tool for compiling py files to exec files on Mac"
} | 216510 |
<p>I've written a java application that can handle operations on big integers implemented with array list of digits. </p>
<p>I have a difficulty with the way I implemented the divide method, because when the difference between the two numbers is high, the operation can take a huge amount of time. </p>
<p>I'd like to hear your thoughts about this implementation and ways it can be improved. Here is the class and its test class:</p>
<p><strong>BigInt.java</strong> </p>
<pre><code>import java.util.ArrayList;
public class BigInt implements Comparable<BigInt> {
private static final char MINUS_CHAR = '-';
private static final char PLUS_CHAR = '+';
// Saves the digits of the number - last element represents the smallest unit of the number
private ArrayList<Integer> numberDigits = new ArrayList<>();
// Indication if the number is negative
private boolean negative;
// String representation as given by the user
private String stringNumber;
BigInt(String number){
if (number.equals("")){
stringNumber = "0";
numberDigits.add(0);
}
else {
// Dealing with the positive/negative signs
char firstChar = number.charAt(0);
if (firstChar == MINUS_CHAR || firstChar == PLUS_CHAR) {
if (firstChar == MINUS_CHAR)
negative = true;
number = number.substring(1);
}
// Regex to remove zeros at the beginning of the number
number = number.replaceFirst("^0+(?!$)", "");
stringNumber = number;
// Saving the digits
for (int index = 0; index < number.length(); index++) {
int curDigNumericVal = Character.getNumericValue(number.charAt(index));
// Current char is not a valid digit
if (curDigNumericVal == -1)
throw new IllegalArgumentException();
numberDigits.add(curDigNumericVal);
}
}
}
private boolean isNegative() {
return negative;
}
private void flipNegativity() {
if (stringNumber == "0")
return;
negative = !negative;
if (stringNumber.charAt(0) == MINUS_CHAR){
stringNumber = stringNumber.substring(1);
} else {
stringNumber = MINUS_CHAR + stringNumber;
}
}
// Adding another bigInt number to the current bigInt number
BigInt plus(BigInt otherNumber) {
// current is negative, other is positive - subtract current from the other
if (negative && !otherNumber.isNegative()) {
return otherNumber.minus(new BigInt(stringNumber));
}
// other is negative - subtract its value
if (otherNumber.isNegative()) {
return minus(new BigInt(otherNumber.toString()));
}
// Setting the longer number of the two numbers
ArrayList<Integer> longerNumber, shorterNumber;
if (numberDigits.size() >= otherNumber.numberDigits.size()) {
longerNumber = numberDigits;
shorterNumber = otherNumber.numberDigits;
}
else {
longerNumber = otherNumber.numberDigits;
shorterNumber = numberDigits;
}
int lengthsDifferences = longerNumber.size() - shorterNumber.size();
StringBuilder resultString = new StringBuilder();
// Initializing a carry for every addition
int carry = 0;
// Iterating from smallest unit digit to the biggest
for (int index = shorterNumber.size() - 1; index >= 0; index--) {
int shorterNumberDigit = shorterNumber.get(index);
int longerNumberDigit = longerNumber.get(index + lengthsDifferences);
int newDigit = shorterNumberDigit + longerNumberDigit + carry;
// Calculating the carry and the new digit
carry = newDigit / 10;
newDigit = newDigit % 10;
resultString.append(newDigit);
}
// Adding digits of longer number
for (int index = lengthsDifferences - 1; index >= 0; index--) {
int currDig = longerNumber.get(index);
// Check if need to add carry
if (currDig + carry == 10) {
resultString.append(0);
carry = 1;
} else {
resultString.append(currDig + carry);
carry = 0;
}
}
// Check if there is carry on last digit
if (carry > 0)
resultString.append(carry);
return new BigInt(resultString.reverse().toString());
}
BigInt minus(BigInt otherNumber){
// If the other number is negative, add its value
if (otherNumber.isNegative()) {
return plus(new BigInt(otherNumber.stringNumber));
}
// subtract a bigger number than the current
if (this.compareTo(otherNumber) < 0) {
BigInt result = otherNumber.minus(this);
result.flipNegativity();
return result;
}
// Other number is positive and not greater than current:
int lengthsDifferences = numberDigits.size() - otherNumber.numberDigits.size();
StringBuilder resultString = new StringBuilder();
int carry = 0;
for (int index = otherNumber.numberDigits.size() - 1; index >=0 ; index--) {
int biggerNumDig = numberDigits.get(index + lengthsDifferences) - carry;
int smallerNumDig = otherNumber.numberDigits.get(index);
carry = 0;
if (biggerNumDig < smallerNumDig){
carry = 1;
biggerNumDig += 10;
}
resultString.append(biggerNumDig - smallerNumDig);
}
for (int index = lengthsDifferences - 1; index >=0 ; index--) {
int currDig = numberDigits.get(index);
// Check if carry is needed
if (carry > currDig){
resultString.append(currDig + 10 - carry);
carry = 1;
} else {
resultString.append(currDig - carry);
carry = 0;
}
}
return new BigInt(resultString.reverse().toString());
}
// Multiply bigInt
BigInt multiply(BigInt otherNumber){
BigInt finalResult = new BigInt("0");
BigInt currentUnit = new BigInt("1");
for (int otherNumIndex = otherNumber.numberDigits.size() - 1; otherNumIndex >=0; otherNumIndex--){
int currentOtherNumDigit = otherNumber.numberDigits.get(otherNumIndex);
// Holds the result of multiplication of the number by the current digit of the other number
BigInt currentResult = new BigInt("0");
BigInt currentDigitUnit = new BigInt(currentUnit.toString());
for (int index = numberDigits.size() - 1; index >=0; index--) {
int currentDigit = numberDigits.get(index);
int digitsMultiplication = currentDigit * currentOtherNumDigit;
currentResult = currentDigitUnit.MultiplyUnit(digitsMultiplication);
currentDigitUnit.multiplyByTen();
}
currentUnit.multiplyByTen();
finalResult = finalResult.plus(currentResult);
}
// Check if need to flip negativity
if (otherNumber.isNegative() && !isNegative() || isNegative() && !otherNumber.isNegative())
finalResult.flipNegativity();
return finalResult;
}
BigInt divide(BigInt otherNumber) {
if (isBigIntZero(otherNumber))
throw new ArithmeticException();
// Handling the case where the current number is positive and the other is negative
if (otherNumber.isNegative() && !isNegative()) {
BigInt result = divide(new BigInt(otherNumber.stringNumber));
result.flipNegativity();
return result;
// Handling the case where the current number is negative and the other is positive
} else if (!otherNumber.isNegative() && isNegative()) {
BigInt result = new BigInt(stringNumber).divide(otherNumber);
result.flipNegativity();
return result;
}
int compareResult = this.compareTo(otherNumber);
if (compareResult == 0)
return new BigInt("1");
else if (compareResult < 0)
return new BigInt("0");
BigInt result = new BigInt("0");
BigInt tempNumber = new BigInt("0");
while (tempNumber.compareTo(this) < 0) {
tempNumber = tempNumber.plus(otherNumber);
result = result.plus(new BigInt("1"));
}
return result;
}
private boolean isBigIntZero(BigInt number) {
return number.stringNumber.replace("0", "").equals("");
}
// Multiply a unit of BigInt with an integer. Example: 1000000000000000000 * 54
private BigInt MultiplyUnit(int majorUnits){
// Setting the string representation
String majorUnitsString = String.valueOf(majorUnits);
String newNumber = majorUnitsString + stringNumber.substring(1);
return new BigInt(newNumber);
}
private void multiplyByTen() {
this.numberDigits.add(0);
stringNumber += '0';
}
@Override
public int compareTo(BigInt other) {
// Current is negative, other is positive
if (isNegative() && !other.isNegative())
return -1;
// Current is positive, other is negative
else if (!isNegative() && other.isNegative()){
return 1;
}
// Both are negative
else if (isNegative()){
// Current is negative and has more digits - therefore it is smaller
if (numberDigits.size() > other.numberDigits.size())
return -1;
// Current is negative and has less digits - Therefore it is bigger
else if (numberDigits.size() < other.numberDigits.size())
return 1;
// Both have same number of digits - need to iterate them
else
for (int index = 0; index < numberDigits.size(); index++) {
// Current has bigger negative digit - therefore it is smaller
if (numberDigits.get(index) > other.numberDigits.get(index))
return -1;
// Current has smaller negative digit - therefore it is smaller
else if (numberDigits.get(index) < other.numberDigits.get(index))
return 1;
}
// If we have reached here, the numbers are completely identical
return 0;
}
// If we have reached here, both numbers are positive
// Current is positive and has more digits - Therefore it is bigger
if (numberDigits.size() > other.numberDigits.size()) {
return 1;
}
// Current is positive and has less digits - Therefore it is smaller
else if (numberDigits.size() < other.numberDigits.size())
return -1;
// Both have same number of digits - need to iterate them
else
for (int index = 0; index < numberDigits.size(); index++) {
// Current has bigger positive digit - therefore it is bigger
if (numberDigits.get(index) > other.numberDigits.get(index))
return 1;
// Current has smaller positive digit - therefore it is smaller
else if (numberDigits.get(index) < other.numberDigits.get(index))
return -1;
}
// If we have reached here, the numbers are completely identical
return 0;
}
@Override
public boolean equals(Object o) {
// self check
if (this == o)
return true;
// null check
if (o == null)
return false;
// type check and cast
if (getClass() != o.getClass())
return false;
BigInt other = (BigInt) o;
// field comparison
return other.toString().equals(stringNumber);
}
@Override
public String toString() {
return stringNumber;
}
}
</code></pre>
<p><strong>Main</strong></p>
<pre><code>import com.sun.javaws.exceptions.InvalidArgumentException;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
BigInt firstNumber;
BigInt secondNumber;
System.out.println("Enter first number: ");
firstNumber = inputBigIntNumber();
System.out.println("Enter second number: ");
secondNumber = inputBigIntNumber();
System.out.println("The result of plus is: " + firstNumber.plus(secondNumber));
System.out.println("The result of minus is: " + firstNumber.minus(secondNumber));
System.out.println("The result of multiply is: " + firstNumber.multiply(secondNumber));
try {
System.out.println("The result of divide is: " + firstNumber.divide(secondNumber));
} catch (ArithmeticException ex){
System.out.println("Can not divide by zero");
}
}
// Taking a valid integer input from the user (greater than 0)
private static BigInt inputBigIntNumber(){
String str = scanner.nextLine();
while (true) {
try {
return new BigInt(str);
}
catch (IllegalArgumentException ex) {
System.out.println("Invalid number, please try again: ");
}
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>Main</h2>\n\n<blockquote>\n<pre><code>import com.sun.javaws.exceptions.InvalidArgumentException;\n</code></pre>\n</blockquote>\n\n<p>Are you using Eclipse? This looks like an IDE being unhelpful. The <code>InvalidArgumentException</code> you want is in <code>java.lang</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static void main(String[] args) {\n BigInt firstNumber;\n BigInt secondNumber;\n\n System.out.println(\"Enter first number: \");\n firstNumber = inputBigIntNumber();\n\n System.out.println(\"Enter second number: \");\n secondNumber = inputBigIntNumber();\n\n System.out.println(\"The result of plus is: \" + firstNumber.plus(secondNumber));\n System.out.println(\"The result of minus is: \" + firstNumber.minus(secondNumber));\n System.out.println(\"The result of multiply is: \" + firstNumber.multiply(secondNumber));\n\n try {\n System.out.println(\"The result of divide is: \" + firstNumber.divide(secondNumber));\n } catch (ArithmeticException ex){\n System.out.println(\"Can not divide by zero\");\n }\n\n }\n</code></pre>\n</blockquote>\n\n<p>This isn't a great way of doing tests. Much better to have unit tests.</p>\n\n<p>I tested it with input <code>17</code> <code>42</code> and the value given for the multiplication is <code>420</code>, which is clearly wrong.</p>\n\n<hr>\n\n<h2>BigInt</h2>\n\n<blockquote>\n<pre><code> // Saves the digits of the number - last element represents the smallest unit of the number\n private ArrayList<Integer> numberDigits = new ArrayList<>();\n</code></pre>\n</blockquote>\n\n<p>Thumbs up for documenting the endianness clearly. In my experience the opposite endianness is easier to work with.</p>\n\n<p>I think <code>BigInt</code> is immutable, so I'm not sure what advantage there is to using <code>ArrayList<Integer></code> over <code>int[]</code>, and the boxing/unboxing is an obvious disadvantage.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Indication if the number is negative\n private boolean negative;\n</code></pre>\n</blockquote>\n\n<p>I would call it <code>isNegative</code> as a hint that it's a Boolean and to read well in <code>if</code> statements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // String representation as given by the user\n private String stringNumber;\n</code></pre>\n</blockquote>\n\n<p>I'm curious as to why the class keeps two copies of the digits. Is that a time/memory tradeoff due to <code>toString()</code> being a bottleneck?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private boolean isNegative() {\n return negative;\n }\n</code></pre>\n</blockquote>\n\n<p>Why is this <code>private</code>? It might be useful if it were <code>public</code>, but for private use you have access to the field.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void flipNegativity() {\n if (stringNumber == \"0\")\n return;\n\n negative = !negative;\n</code></pre>\n</blockquote>\n\n<p>Ah, it's not immutable. Some explicit documentation of this at the top of the class would be nice.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Adding another bigInt number to the current bigInt number\n BigInt plus(BigInt otherNumber) {\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> BigInt minus(BigInt otherNumber){\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> // Multiply bigInt\n BigInt multiply(BigInt otherNumber){\n</code></pre>\n</blockquote>\n\n<p>Again, not public?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> BigInt finalResult = new BigInt(\"0\");\n BigInt currentUnit = new BigInt(\"1\");\n\n for (int otherNumIndex = otherNumber.numberDigits.size() - 1; otherNumIndex >=0; otherNumIndex--){\n int currentOtherNumDigit = otherNumber.numberDigits.get(otherNumIndex);\n\n // Holds the result of multiplication of the number by the current digit of the other number\n\n BigInt currentResult = new BigInt(\"0\");\n BigInt currentDigitUnit = new BigInt(currentUnit.toString());\n\n for (int index = numberDigits.size() - 1; index >=0; index--) {\n int currentDigit = numberDigits.get(index);\n int digitsMultiplication = currentDigit * currentOtherNumDigit;\n\n currentResult = currentDigitUnit.MultiplyUnit(digitsMultiplication);\n currentDigitUnit.multiplyByTen();\n }\n\n currentUnit.multiplyByTen();\n finalResult = finalResult.plus(currentResult);\n }\n</code></pre>\n</blockquote>\n\n<p>Maybe you could factor out the addition into a method which takes two input <code>BigInt</code>s or representations thereof and a power of 10 offset for the second. Then you could share the code with <code>add</code> and reuse it here, saving all the <code>multiplyByTen()</code> etc.</p>\n\n<p>Sketch code:</p>\n\n<pre><code>int[] accumulator = new int[worst case length of the output];\nfor (int powerOfTen = 0; powerOfTen < numberDigits.size(); powerOfTen++) {\n addImpl(accumulator, powerOfTen, numberDigits.get(powerOfTen), otherNumber.numberDigits);\n}\n</code></pre>\n\n<p>The core of <code>add(BigInt)</code> would be</p>\n\n<pre><code>accumulator = new int[worst case length of the output]\naddImpl(accumulator, 0, 1, numberDigits);\naddImpl(accumulator, 0, 1, otherNumber.numberDigits);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> BigInt divide(BigInt otherNumber) {\n</code></pre>\n</blockquote>\n\n<p>This could use a comment about rounding. It looks like it rounds to zero: is that correct?</p>\n\n<blockquote>\n<pre><code> // Handling the case where the current number is positive and the other is negative\n if (otherNumber.isNegative() && !isNegative()) {\n BigInt result = divide(new BigInt(otherNumber.stringNumber));\n result.flipNegativity();\n return result;\n\n // Handling the case where the current number is negative and the other is positive\n } else if (!otherNumber.isNegative() && isNegative()) {\n BigInt result = new BigInt(stringNumber).divide(otherNumber);\n result.flipNegativity();\n return result;\n }\n\n int compareResult = this.compareTo(otherNumber);\n if (compareResult == 0)\n return new BigInt(\"1\");\n else if (compareResult < 0)\n return new BigInt(\"0\");\n</code></pre>\n</blockquote>\n\n<p>That doesn't look right. If both numbers are negative and <code>this.compareTo(otherNumber) < 0</code> then the result should be at least <code>1</code>.</p>\n\n<blockquote>\n<pre><code> BigInt result = new BigInt(\"0\");\n BigInt tempNumber = new BigInt(\"0\");\n\n while (tempNumber.compareTo(this) < 0) {\n tempNumber = tempNumber.plus(otherNumber);\n result = result.plus(new BigInt(\"1\"));\n }\n</code></pre>\n</blockquote>\n\n<p>The keywords you need to search for are <em>long division</em>. That's the algorithm they teach you in school which everyone forgets by the time they leave school.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> @Override\n public int compareTo(BigInt other) {\n\n // Current is negative, other is positive\n if (isNegative() && !other.isNegative())\n return -1;\n\n // Current is positive, other is negative\n else if (!isNegative() && other.isNegative()){\n return 1;\n }\n</code></pre>\n</blockquote>\n\n<p>Might be good to add an equality test before anything else: at the very least <code>if (this == other) return 0</code>. Other than that, so far, so good; but then it goes off the rails. It might be a lot simpler to look at the sign of <code>this.minus(other)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> @Override\n public boolean equals(Object o) {\n // self check\n if (this == o)\n return true;\n\n // null check\n if (o == null)\n return false;\n\n // type check and cast\n if (getClass() != o.getClass())\n return false;\n\n BigInt other = (BigInt) o;\n // field comparison\n\n return other.toString().equals(stringNumber);\n }\n</code></pre>\n</blockquote>\n\n<p>If you override <code>equals</code> you should also override <code>getHashCode()</code> to ensure that the class works correctly with <code>HashSet</code>, <code>HashMap</code>, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T17:09:25.080",
"Id": "418891",
"Score": "0",
"body": "thanks for the useful comments. Could you further explain this statement: `Maybe you could factor out the addition into a method which takes two input BigInts or representations thereof and a power of 10 offset for the second. Then you could share the code with add and reuse it here, saving all the multiplyByTen() etc`. And moreover, regarding your suggestion using the `minus` method in the compareTo - I would really like to do that but the `minus` method uses the `CompareTo` and the `plus` uses the `minus` so it can't be used as well. Do you have another suggestion to solve that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T17:23:10.373",
"Id": "418892",
"Score": "1",
"body": "I've added some outline code which I hope will make that clearer. Fair point on the circular reference between `minus` and `compareTo`. My own big integer class just does addition and multiplication because it's for combinatoric problems where the bottleneck in Java's built-in `BigInteger` is `toString()`, but I think that maybe the solution would be to do the addition using tens complement: that way it's just an addition and a bit of bookkeeping at the end if the result turns out to be negative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:34:22.137",
"Id": "418912",
"Score": "2",
"body": "Instead of `InvalidArgumentException` (which comes from .NET), Java code typically uses `IllegalArgumentException`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T16:13:45.017",
"Id": "216531",
"ParentId": "216513",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216531",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T00:08:30.193",
"Id": "216513",
"Score": "3",
"Tags": [
"java",
"beginner",
"integer"
],
"Title": "Java BigInteger implementation"
} | 216513 |
<p>My model called <code>Customer</code> contains a method called <code>generate_fields</code> which creates records based on its return values.</p>
<pre><code>def generate_fields
words.map do |word|
numbers.map do |number|
content = find_content(word, number)
next if content.nil?
{
kind: word,
value: content
}
end.compact
end.flatten
end
#[
# { kind: "S", value: "BRL" },
# { kind: "M", value: "AUS" },
# { kind: "L", value: "PER" },
#]
</code></pre>
<p>The methods <code>words</code> and <code>numbers</code> are private and return an array of strings. Their implementation is not relevant to this discussion. <code>generate_fields</code> returns an array of hashes which is used to create multiple customers at the database.</p>
<pre><code>Customer.create(generate_fields)
</code></pre>
<p>The problem is <code>compact</code> and <code>flatten</code> create a new array for every time they are called as pointed out by @David Aldridge. How can this function be rewritten to avoid excessive array creation? Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T04:55:06.703",
"Id": "418869",
"Score": "1",
"body": "Welcome to Code Review. As you have currently framed the question, you seem to be asking about a specific practice, with two hypothetical code snippets included merely as an example. To make this question on-topic, please state what task the code accomplishes, and retitle the question accordingly, so that we are reviewing real concrete code from a project. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:48:59.297",
"Id": "418923",
"Score": "0",
"body": "@200_success thanks for pointing me out in the right direction. I've changed the question and I believe now it's closer to this community guidelines."
}
] | [
{
"body": "<p>I'm not a fan of the latter because the <code>compact</code> and <code>flatten</code> methods create new arrays.</p>\n\n<p>Here's another variation with two additional style options: use of <code>product</code> to combine the two arrays, and <code>each_with_object</code>:</p>\n\n<pre><code>def generate_fields_3\n words = [\"foo\", \"bar\", \"bla\"]\n numbers = [1, 2, 3]\n\n words.product(numbers).each_with_object([]) do |(word, number), fields|\n content = find_content(word, number)\n next if content.nil?\n\n fields << {\n kind: word,\n value: content\n }\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T10:13:24.453",
"Id": "418958",
"Score": "0",
"body": "I should point out that if efficiency is the aim then the `product` method should be avoided really. For two arrays size N and M it creates another (N*M)+1 arrays."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T13:37:59.707",
"Id": "216527",
"ParentId": "216516",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216527",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T04:33:24.410",
"Id": "216516",
"Score": "0",
"Tags": [
"performance",
"ruby",
"ruby-on-rails"
],
"Title": "Searching for combinations of words and numbers"
} | 216516 |
<p>I implemented a <a href="https://en.wikipedia.org/wiki/Stable_marriage_problem" rel="nofollow noreferrer">stable marriage problem</a> in Haskell few month ago. It's not optimized at all and I'd like to know how to make it better from performance and readability perspective. </p>
<pre><code>data Sex = Male | Female deriving (Eq, Show)
data Virtue = Intelligence | Appearence | Kindness deriving (Eq, Show, Enum)
data Parameter = Parameter{
virtue :: Virtue,
value :: Int
} deriving (Eq, Show)
data Person = Person{
name :: String,
sex :: Sex,
preferences :: [Virtue],
parameters :: [Parameter],
partner :: Maybe Person
} deriving (Eq, Show)
</code></pre>
<p>Results list of women sorted by preferences of one man by <code>defaultRateFunction :: Person -> Person -> Int</code>. In my implementation it depends on judges <code>preferences</code> and rated person <code>parameters</code>. I won't put it there for brevity. You can find full program in a link to Gist at the bottom of post. Imagine that function to be anything you want.</p>
<pre><code>personalRating :: Person -> [Person] -> [Person]
personalRating x ys = sortBy (comparing (\y -> defaultRateFunction x y)) ys
</code></pre>
<p>Man makes an engagement proposal for the woman and if she don't have partner — she replies positively (<code>True</code>) and if she does, if new partner's rating > than the old one's — "returns" <code>True</code> and if it does not — <code>False</code></p>
<pre><code>proposal :: Person -> Person -> Bool
proposal male female
| isNothing (partner female) = True
| defaultRateFunction female male > defaultRateFunction female (fromJust $ partner female) = True
| otherwise = False
</code></pre>
<p>Man makes a proposal for each woman in females untill he'll find the one who'll reply positively. Assumed that there are at least one of this type in the array</p>
<pre><code>findTheBride :: Person -> [Person] -> Person
findTheBride male females
| proposal male (head females) == True = head females
| otherwise = findTheBride male (tail females)
</code></pre>
<p>The ugliest part is marrige algorhitm itself. As I call it recursively I have to clean person from array of corresponded sexes every time it finds partner and also check if woman has an ex-partner, and deal with thier "breakup" also.</p>
<pre><code>marrige :: [Person] -> [Person] -> [Person]
marrige males females
| sm == [] = females
| isNothing ex = marrige
(fsmWithNewPartner:(delete fsm males))
(fsmPartnerWithFsm:(delete fsmPartner females))
| otherwise = marrige
(fsmWithNewPartner:((fromJust ex) {partner = Nothing}):(delete fsm $ delete (fromJust ex) males))
(fsmPartnerWithFsm:(delete fsmPartner females))
where
sm = filter (\x -> partner x == Nothing) males -- Single males
fsm = head sm -- Fist single male
fsmPartner = findTheBride fsm (personalRating fsm females) -- Fist single male's partner
ex = partner fsmPartner -- Partner's ex (Maybe)
fsmWithNewPartner = fsm {partner = Just fsmPartner}
fsmPartnerWithFsm = fsmPartner {partner = Just fsm}
</code></pre>
<p>Full version of program (where random Person data are generated) avialible on <a href="https://gist.github.com/altjsus/8ca2f0b8cd771a5e7a7ae3bdefb83a23" rel="nofollow noreferrer">Gist</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:12:08.330",
"Id": "418969",
"Score": "0",
"body": "I'm sorry for mistake: marrige = marriage. I'm not native in English."
}
] | [
{
"body": "<pre><code>import Safe (findJust)\nimport Data.Foldable (null, all)\n\npersonalRating = sortBy . comparing . defaultRateFunction\n\nproposal m f = all (on (>) (defaultRateFunction f) m) $ partner f\n\nremarry p x = (x {partner = p} :) . delete x\n\nmarrige :: [Person] -> [Person] -> [Person]\nmarrige ms fs = case find (null . partner) ms of\n Nothing -> fs\n Just m -> marrige\n (remarry (Just f} m $ maybe id (remarry Nothing) (partner f) ms)\n (remarry (Just m) f fs)\n where f = findJust (proposal m) $ personalRating m fs\n</code></pre>\n\n<p>You never actually use <code>ms</code> that have a partner. Why keep track of them? I'll assume that all start out without partners, otherwise filter once at the start. In particular, I'll assume the invariant that partnership is symmetric.</p>\n\n<pre><code>marrige :: [Person] -> [Person] -> [Person]\nmarrige [] fs = fs\nmarriage (m:ms) fs = marrige \n (maybe id (\\ex -> (ex {partner = Nothing} :)) (partner f) ms)\n (f {partner = Just m} : delete f fs)\n where f = findJust (proposal m) $ personalRating m fs\n</code></pre>\n\n<p>For performance, you could use <code>Data.Map</code> instead of <code>[]</code>'s <code>delete</code>.</p>\n\n<p>Edit: Here's one where the explicit recursion is less global. Unsetting <code>ex</code>'s partner may be superfluous.</p>\n\n<pre><code>import Control.Monad.State\n\nmarrige = execState . traverse_ go where go m = do\n f <- gets $ findJust (proposal m) . personalRating m\n modify $ (f {partner = Just m} :) . delete f\n for_ (partner f) $ \\ex -> go $ ex {partner = Nothing}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:13:14.410",
"Id": "418971",
"Score": "0",
"body": "Thank you. Do I have to mark your answer. I'd like to know if `marriage` could be more syntax-sweet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T02:03:55.227",
"Id": "419287",
"Score": "0",
"body": "If you're not satisfied, we needn't be done! Specify what metric you'd like to improve. For example, with another data structure and using the `lens` library, the penultimate line could be `at f ?= m`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:26:56.600",
"Id": "216562",
"ParentId": "216522",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216562",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T11:39:22.623",
"Id": "216522",
"Score": "4",
"Tags": [
"haskell"
],
"Title": "Stable marriage in Haskell"
} | 216522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.