body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>An attempt at a clean implementation of this important data structure in C.</p>
<p>It's hard to make such structures generic in C without losing performance, so this specialises on <code>char*</code> keys and <code>int</code> values, but uses some type aliases, such that only a few places need changing to change the key or value types.</p>
<p>The hash table dynamically grows by 2x when 80% of the slots are used to keep efficiency high.</p>
<p>As a demo, we parse the <a href="https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt" rel="nofollow noreferrer">complete works of Shakespeare</a>, call <code>ht_inc()</code> for each word. Then build a flat "view" of the hashtable, sort and report the 10 most common words. On my machine the entire task takes just 50ms.</p>
<p>Feedback on quality of coding style please.</p>
<pre><code>#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* ht_key_t;
typedef int ht_value_t;
// key => value plus pointer to next item for hash collisions
typedef struct HashTableItem HashTableItem;
struct HashTableItem {
ht_key_t key;
ht_value_t value;
HashTableItem* next;
};
// Array of pointers to HashTableItems, plus counters
typedef struct HashTable {
HashTableItem** slots;
size_t size; // how many slots are there
size_t scount; // how many slots are used
size_t itemcount; // how many items are there
} HashTable;
// Creates a new HashTableItem
HashTableItem* ht_create_item(ht_key_t key, ht_value_t value) {
HashTableItem* item = malloc(sizeof *item);
if (!item) {
perror("malloc item");
exit(EXIT_FAILURE);
}
item->key = strdup(key); // take a copy
item->value = value;
item->next = NULL;
return item;
}
// Creates a new HashTable
HashTable* ht_create(size_t size) {
HashTable* table = malloc(sizeof *table);
if (!table) {
perror("malloc table");
exit(EXIT_FAILURE);
}
table->size = size;
table->scount = 0;
table->itemcount = 0;
table->slots = calloc(table->size, sizeof *table->slots); // NOLINT
if (!table->slots) {
perror("calloc items");
exit(EXIT_FAILURE);
}
return table;
}
// Frees an item depending on their types, if the key or value members
// need freeing that needs to happen here too
void ht_free_item(HashTableItem* item) {
free(item->key);
free(item);
}
// Frees the whole hashtable
void ht_free(HashTable* table) {
// free the HashTableItems in the linked lists
for (size_t i = 0; i < table->size; i++) {
HashTableItem* item = table->slots[i];
while (item) {
HashTableItem* next = item->next;
ht_free_item(item);
item = next;
}
}
// free the array of pointers to HashTableItems
free(table->slots);
free(table);
}
// hash function. crucial to efficient operation
// returns value in range [0, size)
// an appropriate hash function for short strings is FNV-1a
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash
size_t ht_hash(size_t size, const char* str) {
uint64_t hash = 0xcbf29ce484222325; // FNV_offset_basis
while (*str) hash = (hash ^ (uint8_t)*str++) * 0x100000001b3; // FNV_prime
return hash % size; // fit to table
}
void ht_grow(HashTable* table) {
table->scount++;
if (table->scount * 100 / table->size >= 80) {
size_t nsize = table->size * 2;
HashTableItem** nslots = calloc(nsize, sizeof *table->slots); // NOLINT
if (!nslots) {
perror("calloc nitems");
exit(EXIT_FAILURE);
}
size_t ncount = 0;
for (size_t i = 0; i < table->size; i++) {
HashTableItem* item = table->slots[i];
while (item) {
HashTableItem* next = item->next; // save next
HashTableItem** nslot = &nslots[ht_hash(nsize, item->key)];
if (!*nslot) ++ncount;
item->next = *nslot; // push into new list
*nslot = item;
item = next;
}
}
free(table->slots);
table->scount = ncount;
table->size = nsize;
table->slots = nslots;
}
}
// Inserts an item (or updates if exists)
void ht_insert(HashTable* table, ht_key_t key, ht_value_t value) {
HashTableItem** slot = &table->slots[ht_hash(table->size, key)];
HashTableItem* item = *slot;
bool direct_slot = true;
while (item) {
if (strcmp(item->key, key) == 0) {
// exists, update value, free old value if needed
item->value = value;
return;
}
slot = &item->next;
item = *slot;
direct_slot = false;
}
*slot = ht_create_item(key, value); // new entry
++table->itemcount;
if (direct_slot) ht_grow(table); // HashTable accounting
}
// increments the value for a key or inserts with value = 1
// specialised for ht_value_t=int and faster than search then update.
void ht_inc(HashTable* table, ht_key_t key) {
HashTableItem** slot = &table->slots[ht_hash(table->size, key)];
HashTableItem* item = *slot;
bool direct_slot = true;
while (item) {
if (strcmp(item->key, key) == 0) {
++item->value;
return;
}
slot = &item->next;
item = *slot;
direct_slot = false;
}
*slot = ht_create_item(key, 1); // not found, init with one
++table->itemcount;
if (direct_slot) ht_grow(table); // HashTable accounting
}
// Deletes an item from the table
void ht_delete(HashTable* table, ht_key_t key) {
HashTableItem** slot = &table->slots[ht_hash(table->size, key)];
HashTableItem* item = *slot;
bool direct_slot = true;
while (item) {
if (strcmp(item->key, key) == 0) {
*slot = item->next; // remove item from linked list
ht_free_item(item);
--table->itemcount;
if (direct_slot) --table->scount; // HashTable accounting
return;
}
slot = &item->next;
item = *slot;
direct_slot = false;
}
}
// Searches the key in the hashtable
// and returns NULL ptr if it doesn't exist
HashTableItem* ht_search(HashTable* table, ht_key_t key) {
HashTableItem* item = table->slots[ht_hash(table->size, key)];
while (item) {
if (strcmp(item->key, key) == 0) return item;
item = item->next;
}
return NULL;
}
// debug printing. customise printf format strings by key & value types
void ht_print(HashTable* table) {
printf("\n---- Hash Table ---\n");
for (size_t i = 0; i < table->size; i++) {
printf("@%zu: ", i);
HashTableItem* item = table->slots[i];
while (item) {
printf("%s => %d | ", item->key, item->value);
item = item->next;
}
printf("\n");
}
printf("-------------------\n");
}
// debug printing. customise printf format strings by key & value types
void ht_print_search(HashTable* table, ht_key_t key) {
HashTableItem* val;
if ((val = ht_search(table, key)) == NULL) {
printf("Key:%s does not exist\n", key);
return;
}
printf("Key:%s => %d\n", key, val->value);
}
static inline bool ht_is_alpha(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
static inline char ht_tolower(char c) { return (c < 'a') ? c + 'a' - 'A' : c; }
int cmp_ht_items(const void* a, const void* b) {
int a_val = (*(HashTableItem**)a)->value;
int b_val = (*(HashTableItem**)b)->value;
if (a_val == b_val) return 0;
return a_val < b_val ? 1 : -1;
}
int main() {
// some tests
HashTable* ht = ht_create(4);
ht_insert(ht, "1", 10);
ht_insert(ht, "2", 20);
ht_insert(ht, "Hel3", 30);
ht_insert(ht, "Cau4", 40);
ht_print(ht);
ht_insert(ht, "Cau6", 60); // grow!
ht_print(ht);
ht_inc(ht, "11"); // increment
ht_inc(ht, "21"); // increment
ht_inc(ht, "31"); // increment
ht_inc(ht, "41"); // increment
ht_inc(ht, "51"); // increment
ht_inc(ht, "61"); // increment
ht_inc(ht, "71"); // increment
ht_inc(ht, "81"); // increment and grow again
ht_print(ht);
ht_print_search(ht, "1");
ht_print_search(ht, "2");
ht_print_search(ht, "3");
ht_print_search(ht, "Hel3");
ht_print_search(ht, "Cau4");
ht_insert(ht, "Cau6", 61); // update
ht_inc(ht, "1"); // increment
ht_inc(ht, "Hel3"); // increment
ht_inc(ht, "new"); // increment
ht_print(ht);
ht_delete(ht, "Hel3");
ht_delete(ht, "Cau6");
ht_delete(ht, "1");
ht_print(ht);
ht_free(ht);
// end of tests
// shakespeare demo
FILE* fp = fopen("shakespeare.txt", "re");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
ht = ht_create(32 * 1024);
#define BUFSIZE 1024
#define WORDSIZE 50
char buf[BUFSIZE];
char word[WORDSIZE];
char* word_ptr = word;
while (!ferror(fp) && !feof(fp)) {
size_t bytes_read = fread(buf, 1, BUFSIZE, fp);
char* buf_ptr = buf;
while ((buf_ptr < buf + bytes_read)) {
char c = *buf_ptr;
if (ht_is_alpha(c)) {
*(word_ptr++) = ht_tolower(c);
if (word_ptr - word == WORDSIZE - 1) { // -1 for NULL terminator
fputs("word too long. terminating\n", stderr);
exit(EXIT_FAILURE);
}
} else if (word_ptr == word) {
// ignore repeated terminators
} else {
*(word_ptr++) = '\0';
ht_inc(ht, word); // record
word_ptr = word; // restart new word
}
++buf_ptr; // next char from buf
}
}
fclose(fp);
// build a flat view of the hashtable items
HashTableItem** itemview = malloc(ht->itemcount * sizeof *itemview); // NOLINT
if (!itemview) {
perror("malloc itemview");
exit(EXIT_FAILURE);
}
HashTableItem** curritem = itemview;
for (size_t i = 0; i < ht->size; i++) {
HashTableItem* item = ht->slots[i];
while (item) {
*curritem++ = item;
item = item->next;
}
}
// now sort that view and print the top 10
qsort(itemview, ht->itemcount, sizeof *itemview, cmp_ht_items); // NOLINT
for (size_t i = 0; i < 10; i++)
printf("%s => %d\n", itemview[i]->key, itemview[i]->value);
free(itemview);
// ht_print(ht);
ht_free(ht);
}
</code></pre>
|
[] |
[
{
"body": "<h1>Make more use of <code>calloc()</code></h1>\n<p>I would use <code>calloc()</code> almost everywhere. It guarantees the memory is zeroed, so you won't have surprises if you forgot to initialize a member variable. I wouldn't worry about performance much; the compiler should be able to optimize the zeroing away if it sees you are setting a member variable to something else. So, use it in <code>ht_create_item()</code> and <code>ht_create()</code> where you currently use <code>malloc()</code>.</p>\n<h1>Consider avoiding a layer of indirection</h1>\n<p>Your hash table has an array <code>slots</code> that contains pointers to items, however items themselves are quite small, they are just two pointers and an <code>int</code>. Since you aim at a load factor of 0.4 to 0.8, it will use less memory to remove the indirection:</p>\n<pre><code>typedef struct HashTable {\n HashTableItem* slots;\n ...\n} HashTable;\n</code></pre>\n<p>This should also give a small performance gain.</p>\n<h1>Avoid code duplication</h1>\n<p><code>ht_inc()</code> and <code>ht_delete()</code> look very similar. It might be possible to put the common parts into a separate function. I think you can do this by creating a function that finds the pointer to where the item should be/go, and return a pointer to that pointer. Basically, a <code>ht_search()</code> that returns the slot instead of the item itself.</p>\n<pre><code>static HashTableItem** ht_search_slot(HashTable* table, ht_key_t key, bool *direct) {\n HashTableItem** slot = &table->slots[ht_hash(table->size, key)];\n *direct = true;\n while (*slot) {\n if (strcmp((*slot)->key, key) == 0) break;\n *direct = false;\n slot = &(*slot)->next;\n }\n return slot;\n}\n\nvoid ht_inc(HashTable* table, ht_key_t key) {\n bool direct_slot;\n HashTableItem** slot = ht_search_slot(table, key, &direct_slot);\n HashTableItem* item = *slot;\n if (item) {\n ++item->value;\n return;\n }\n *slot = ht_create_item(key, 1); // not found, init with one\n ++table->itemcount;\n if (direct_slot) ht_grow(table); // HashTable accounting\n}\n\nvoid ht_delete(HashTable* table, ht_key_t key) {\n bool direct_slot;\n HashTableItem** slot = ht_search_slot(table, key, &direct_slot);\n HashTableItem* item = *slot;\n if (item) {\n *slot = item->next; // remove item from linked list\n ht_free_item(item);\n --table->itemcount;\n if (direct_slot) --table->scount; // HashTable accounting\n }\n}\n\nHashTableItem* ht_search(HashTable* table, ht_key_t key) {\n bool direct_slot;\n return *ht_search_slot(table, key, &direct_slot);\n}\n</code></pre>\n<p>Of course, this approach will conflict with the above advice of avoiding indirection, although perhaps something similar is still possible.</p>\n<h1>Always call <code>ht_grow()</code> when inserting elements</h1>\n<p>You are only calling <code>ht_grow()</code> when an empty direct slot is used. However, if an item is inserted in an already used slot, you don't call it. That means that if you are unlucky, everything hashes to the same slot, and you will never grow and rebalance. I would play it safe and just unconditionally call <code>ht_grow()</code> when inserting an element. Of course, <code>ht_grow()</code> should use <code>itemcount</code> instead of <code>scount</code> to check whether it needs to grow the hash table.</p>\n<h1>Avoid division and modulo operations</h1>\n<p>Divisions (and thus also modulo operations) are quite expensive. I would avoid them by ensuring the hash table size is always a power of two. And if you ensure that the size is at least 16 elements, then you can replace the check in <code>ht_grow()</code> by:</p>\n<pre><code>if (table->itemcount >= 13 * (table->size >> 4)) {\n ...\n}\n</code></pre>\n<p>This will trigger a resize when the hash table is 81.25% full. You can even get rid of the multiplication by storing the binary logarithm of the size, but unless you plan to run this code on microcontrollers I would not bother with that. And in the hash function you can replace the modulo this way:</p>\n<pre><code>return hash & (size - 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T23:13:55.317",
"Id": "502823",
"Score": "0",
"body": "Good stuff, thanks. I considered most of these. I kept the indirection to not tie myself to this key=>value structure, but it's certainly debatable. I considered calloc, meh.. The code duplication is very interesting and I was still wrestling with this. Each function is only 10 lines, but they are \"somewhat complex\" pointer juggling. So not not just duplication but also clarity might improve if I factor out \"finding the slot incl linked list part\". I thought about load factor by itemcount vs slotcount, more common? And I really like the power of 2 idea and remove modulo/divide. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T00:54:09.653",
"Id": "502828",
"Score": "0",
"body": "Are you sure this is right? `table->itemcount >= 13 * (table->size >> 2)` I can't seem to make that work in my head. For me that would only trigger at >300% load factor? Or am I missing something?\n\nshouldn't it be `table->itemcount * 10 >= (table->size << 3)` for an 80% cutoff? And no restriction for size >=16 (which breaks my tests). In fact if I do the swap to itemcount, then the threshhold should be more lke 160% but that's easy to adjust."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T01:13:10.833",
"Id": "502830",
"Score": "0",
"body": "Interestingly, removing the `%` modulo in `ht_hash` gave a 20% gain immediately, whereas changing that `if` in `ht_grow` did nothing at all (similar number of calls). I guess on a big Intel CPU division is fast (but modulo is not), so unless I am going for an 8-bit pic18 the division is probably more readable? (the 8-bit pic can't handle uint64 anyway, nor malloc etc etc...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T07:24:32.863",
"Id": "502847",
"Score": "0",
"body": "It should've been `>> 4`, which is equal to `/ 16`. In fact you can just write the latter, the compiler is able to optimize that because it can see it's a constant. Your option to do `... * 10 >= ... << 3` should also work, but it might have issues with very large values of `table->size`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:17:13.443",
"Id": "502864",
"Score": "0",
"body": "I tried the `ht_search_slot` refactor for all of `ht_insert` `ht_delete` `ht_inc` and `ht_search`. I took it out again, because: I had already changed to grow by `itemcount` so `is_direct_slot` got removed, so 3 of those methods were even shorter. Of course `item` is redundant in those 4 methods, you can just substitute `*slot` everywhere. BUT that makes it VERY hard to read, at least for my head, which is the reason I had `item` in the first place. And if you have `item` then the refactor makes it \"no shorter\", and a lot less clear IMO. Perhaps once case were small repetition is clearer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:11:56.840",
"Id": "502879",
"Score": "0",
"body": "Even though it might not make sense anymore from a line count perspective, it might still make the code more self-documenting if you have a function `ht_search_slot()` and have other functions calling that. Maybe you can post your updated version as a new review question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:08:15.487",
"Id": "502922",
"Score": "0",
"body": "The current version is here: https://github.com/oschonrock/cproj/blob/main/src/hashtable.c\n\nI think I have found a way of making it generic which I actually like. I had not seen this before. The idea is from here: \n\nhttps://gitlab.com/martinkunev/conquest_of_levidon/-/tree/2019/src/generic\n\nI think of it as \"C++ templates for C\".... ie you \"stamp out\" as many version of the \"generic code\" as you need at top of your file, then use them like they were concrete. ie, no macros in the actual main code. \n\nI am trying to copy that idea right now, might repost if it works out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:32:04.553",
"Id": "502924",
"Score": "0",
"body": "Personally I think that if you need templates in C, you should just use C++ instead of doing these kinds of contortions. That said, the method you linked to is one of the cleaner ones I've seen :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:38:56.277",
"Id": "502925",
"Score": "0",
"body": "I sort of agree, but, eg the Linux Kernel is written in C, because overall they decided C was the better tool. They needed hashmaps and other data structures too. It's a normal thing to need in a bigger project. Implementing such structures is actually quite slow and fiddly, if you want to do a good job. So because they needed them more than once, they wrote some macros ..those are part of the kernel. They were not about to \"switch to C++\". Exactly the same story for the BSD Kernel. They wrote this: https://linux.die.net/man/3/queue It's awful to use in IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T20:30:00.683",
"Id": "502999",
"Score": "1",
"body": "Thought you might like this commit: https://github.com/oschonrock/cproj/commit/536c6cf276e407e488d9f3051232ddeb1d6ecb6b"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:35:41.227",
"Id": "254925",
"ParentId": "254854",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254925",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:19:51.420",
"Id": "254854",
"Score": "3",
"Tags": [
"c",
"hash-map"
],
"Title": "Hashtable with separate chaining and dynamic resizing"
}
|
254854
|
<p>The module has three functions:</p>
<ol>
<li>get_property_from_dict, retrieves a dictionary property's from a given path.</li>
<li>token_collect_from_dict, builds a list of tokens and their location from a given dictionary.</li>
<li>token_replace_in_dict, replaces a tokens in a dictionary with supplied values.</li>
</ol>
<p>I want to use these functions in a larger project. I want to use these functions as an opportunity to get feedback on what I'm mucking up. I'm relatively new to Python. All feedback welcome e.g., style, correctness, etc.</p>
<p>This module is also available in the following gist:</p>
<p><a href="https://gist.github.com/adamfortuno/6df68c8624839dcd61f2eb262bb14303" rel="nofollow noreferrer">https://gist.github.com/adamfortuno/6df68c8624839dcd61f2eb262bb14303</a></p>
<pre><code>#! /usr/bin/env python3
import json
import re
from unittest import TestCase
import unittest.mock as mock
def get_property_from_dict(message: dict, path: list):
"""Get Property from Dictionary
This function retrieves the value of a property at a
specified location.
Args:
message (dict):
The message the function traverses.
path (list):
An ordered list of nested properties or elements. This is
the structure that identifies a property in a supplied
message.
path = ['romania', 'bar', 0, 'this']
message = {
"romania": {
"region": "transylvania"
"bar": [
{ "this": "Cheia", "that": True},
{ "this": "Brasov", "that": True}
{ "this": "Paris", "that": Frue}
]
}
}
}
Returns:
This function returns a the value of the property at the
specified location. The return value's data type can be any
type.
"""
for key in path:
message = message[key]
return message
def token_collect_from_dict(message: dict, message_path: list = None) -> dict:
"""Collect Tokens from Dictionary
This function parses a dictionary marking token locations.
The function returns a list of tokens and their locations
in a given message.
Args:
message (dict):
The message the function searches for tokens.
message_path (dict):
(Optional) An ordered list of nested properties or
elements. The path to the message's location in a
larger dictionary.
message = {
"romania": {
"region": "transylvania",
"dateCreated": "<TOKEN.ANY>"
"bar": [
{ "this": "Cheia", "that": True},
{ "this": "Brasov", "that": True}
{ "this": "<TOKEN.ff3c2f>", "that": Frue}
]
}
}
}
token_collect_from_dict(message['romania'], ['romania'])
Returns:
The function returns a list of tokens and their locations
in a given message.
[
{'<TOKEN.a3bcf2>': ['romania', 'bar', 2, 'this']},
{'<TOKEN.ANY>': ['romania', 'dateCreated']}
]
"""
tokens = []
message_path = [] if message_path is None else message_path
for key in message.keys():
path = message_path.copy()
path.append(key)
# Replace a token if found
if type(message[key]) == str:
res = re.findall('<TOKEN\..*>', message[key])
if res:
tokens.append({res[0]: path})
# If the key is a dictionary, check it for tokens
elif type(message[key]) == dict:
res = token_collect_from_dict(message[key], path)
if res:
tokens += res
# If the key is a list, check it for objects or tokens
elif type(message[key]) == list:
for element_position in range(len(message[key])):
object_path = path.copy()
if type(message[key][element_position]) == dict:
object_path.append(element_position)
res = token_collect_from_dict(
message[key][element_position], object_path)
if res:
tokens += res
return tokens
def token_replace_in_dict(message: dict, tokens: dict) -> dict:
"""Replace Tokens
This function replaces tokens in a given dictionary.
Args:
message (dict):
The message the function searches for tokens.
tokens (dict):
The tokens the function searches for. The token dict
includes tokens and values.
Returns:
The original dictinary with tokens replaced with
token values. For example, the following message:
{
'kid': 'Sabrina',
'incidents': [
{'description': 'jump on desk', 'dateOccurred': '<TOKEN.ANY>'},
{'description': 'paint on wall', 'dateOccurred': '<TOKEN.a3bcf2>'}
]
}
The following token bank:
{ "<TOKEN.ANY>": mock.ANY, "<TOKEN.a3bcf2>": '1234' }
Results in the following output:
{
'kid': 'Sabrina',
'incidents': [
{'description': 'jump on desk', 'dateOccurred': <ANY>},
{'description': 'paint on wall', 'dateOccurred': '1234'}
]
}
"""
for key in message.keys():
# Replace a token if found
if type(message[key]) == str and message[key] in tokens.keys():
message[key] = tokens[message[key]]
# If the key is a dictionary, check it for tokens
elif type(message[key]) == dict:
message[key] = \
token_replace_in_dict(message[key], tokens)
# If the key is a list, check it for objects or tokens
elif type(message[key]) == list:
for element_position in range(len(message[key])):
if type(message[key][element_position]) == dict:
message[key][element_position] = \
token_replace_in_dict(message[key][element_position], tokens)
return message
if __name__ == "__main__":
test_dictionary_1 = {
"name": "Ralphy",
"record": [
{"crime": "jump on desk", "occurrences": 2},
{"crime": "<TOKEN.a3bcf2>", "occurrences": 1},
],
"age": {
"years": "<TOKEN.ANY>",
"thinger": {
"thang1": "<TOKEN.a3bcf2>",
"thang2": "sabrina",
"thang3": [
{"foo": "<TOKEN.a3bcf2>", "bar": True}
],
}
}
}
test_dictionary_2 = {
"kid": "Sabrina",
"incidents": [
{"description": "jump on desk", "dateOccurred": "<TOKEN.ANY>"},
{"description": "paint on wall", "dateOccurred": "<TOKEN.a3bcf2>"},
]
}
token_bank = {
"<TOKEN.ANY>": mock.ANY,
"<TOKEN.a3bcf2>": '1234',
}
print(test_dictionary_2)
print(token_replace_in_dict(test_dictionary_2, token_bank))
#print(get_property_from_dict(test_dictionary_1, ('record', 0, 'crime')))
#print(token_collect_from_dict(test_dictionary_1))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:14:30.787",
"Id": "502747",
"Score": "0",
"body": "A list can never be a key"
}
] |
[
{
"body": "<p>The type hints here:</p>\n<pre><code>def get_property_from_dict(message: dict, path: list):\n</code></pre>\n<p>are a little tricky. The function could technically accept a dict with keys and values of any type, so you can't probably do much better than <code>dict</code>. For <code>path</code>, <code>list</code> is too specific - you can accept any <code>Iterable</code>. The return value, rather than being unspecified, should probably be indicated as <code>Any</code>.</p>\n<p>That function is an excellent candidate for <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">docstring tests</a> and only requires a little reformatting on your part to get there.</p>\n<p>This example:</p>\n<pre class=\"lang-json prettyprint-override\"><code> message = {\n "romania": {\n "region": "transylvania",\n "dateCreated": "<TOKEN.ANY>"\n "bar": [\n { "this": "Cheia", "that": True},\n { "this": "Brasov", "that": True}\n { "this": "<TOKEN.ff3c2f>", "that": Frue}\n ]\n }\n }\n }\n</code></pre>\n<p>is malformed in at least two ways - "Frue", and imbalanced braces. I'm having difficulty understanding what <code>token_collect_from_dict</code> even does, given that I don't think the input and output examples properly correspond to each other. Docstring tests will help with this.</p>\n<p>This:</p>\n<pre><code>for key in message.keys():\n</code></pre>\n<p>does not need <code>.keys()</code> since key iteration is the default.</p>\n<p>Do not determine types like this:</p>\n<pre><code>type(message[key]) == dict\n</code></pre>\n<p>Instead, call <code>isinstance</code>.</p>\n<p><code>message[key][element_position]</code> should be given a temporary variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T21:43:33.710",
"Id": "254864",
"ParentId": "254856",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:24:23.117",
"Id": "254856",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Functions that Find Tokens, Replace Tokens, and Retrieve Property Values from Dictionaries"
}
|
254856
|
<h1>Namespace list to directory structure</h1>
<h2>Motivation</h2>
<p>I have a list of namespaces I extracted from types, and I which to create a directory structure, that represents these namespaces. So that I can place a file at the namespace path of each type.
The simplest method would be to replace the <code>.</code> separator with a <code>\\</code>, and call it a day. But I want to be fancy, so I set myself the goal to minimize the number of directories created.</p>
<h2>Method</h2>
<p>This I do by not creating a directory, when no type with the namespace exists, instead keep the <code>.</code> where it is.</p>
<pre><code>split all namespaces into their segments
for each unique namespace in namespaces
for each segment in namespace, index i
list all namespaces where segments are equal as shared
if shared has lost namespaces compared to previous shared
for each namespace[i] previous shared
replace '.' with '\\'
replace '.' with '\\' in namespace[i]
set previous shared to shared
add namespace to namespaces
</code></pre>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
string[] namespaces = new[] { // Set namespaces from types
"Root.Sub11.Sub11.Sub3",
"Root.Sub11.Sub11",
"Root.Sub11.Sub21",
"Root.Sub11.Sub21.Sub12",
"Root.Sub11.Sub21.Sub13.Sub14",
"Root.Sub11.Sub21.Sub13.Sub14",
"Root.Sub11.Sub21.Sub13.Sub14",
"Root.Sub11.Sub21.Sub13.Sub14.Sub47",
};
/* Should result in this list of directories:
* Root.Sub11/Sub11/Sub3
* Root.Sub11/Sub11
* Root.Sub11/Sub21
* Root.Sub11/Sub21/Sub12
* Root.Sub11/Sub21/Sub13.Sub14
* Root.Sub11/Sub21/Sub13.Sub14/Sub47
*/
NamespacesToDirectoryStructure(namespaces.Select(n => n.Split(".")));
var sb = new StringBuilder();
foreach(var dir in typeNamespaceToPathMap.Values)
{
sb.AppendLine(new string(dir));
}
Console.WriteLine(sb.ToString());
}
private static readonly IDictionary<string[], char[]> typeNamespaceToPathMap = new Dictionary<string[], char[]>();
private static void NamespacesToDirectoryStructure(IEnumerable<string[]> namespaces)
{
IList<string[]> processedTypeNamespaces = new List<string[]>();
foreach (string[] segments in namespaces
.Distinct(new StringSequenceEqualityComparer())
.OrderBy(n => n.Length))
{
int segment = 0;
char[] path = string.Join('.', segments).ToCharArray();
IList<int> sharedNamespacePortionIndices;
IList<string[]> sharedNamespacePortions = processedTypeNamespaces;
do
{
// All namespaces, that share the segment and all previous with this.
sharedNamespacePortionIndices = IndexOfAll(sharedNamespacePortions, segments, segment).ToList();
if (segment != 0)
{
// All namespaces, that share all previous segments with this.
IList<int> indices = sharedNamespacePortionIndices;
IEnumerable<string[]> removedNamespaces = TakeWhere(sharedNamespacePortions, (i, x) => !indices.Contains(i));
if (removedNamespaces.Any())
{
// Convert the [.] to [\] to indicate a path branching for all that share previous segments
int charIndex = segments.Take(segment).Select(s => s.Length).Aggregate(0, (x, y) => x + y + 1) - 1;
path[charIndex] = '\\';
foreach (char[] value in typeNamespaceToPathMap
.Where(kvp => kvp.Value.Length > charIndex && (ReferenceEquals(kvp.Key, segments) || sharedNamespacePortions.Contains(kvp.Key)))
.Select(kvp => kvp.Value))
{
value[charIndex] = '\\';
}
}
}
sharedNamespacePortions = TakeWhere(sharedNamespacePortions, (i, x) => sharedNamespacePortionIndices.Contains(i)).ToList();
segment++;
} while (segment < segments.Length && sharedNamespacePortions.Count > 0);
processedTypeNamespaces.Add(segments);
typeNamespaceToPathMap.Add(segments, path);
}
}
// Enumerates all items of the collection where the segment is equal to the segment at the same position - specified by segment - in test.
private static IEnumerable<int> IndexOfAll(IList<string[]> collection, string[] test, int segment)
{
for (int index = 0; index < collection.Count; index++)
{
if (collection[index].Length > segment && String.Equals(test[segment], collection[index][segment], StringComparison.Ordinal))
{
yield return index;
}
}
}
private static IEnumerable<string[]> TakeWhere(IList<string[]> collection, Func<int, string[], bool> predicate)
{
for (int i = 0; i < collection.Count; i++)
{
if (predicate(i, collection[i]))
{
yield return collection[i];
}
}
}
private class StringSequenceEqualityComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
if (x is null || x.Length != y?.Length)
return false;
for(int i = 0; i < x.Length; i++)
{
if (!x[i].Equals(y[i], StringComparison.Ordinal))
return false;
}
return true;
}
public int GetHashCode(string[] obj) => obj.GetHashCode(true);
}
}
///<summary>Source: https://github.com/ProphetLamb-Organistion/Groundbeef/blob/master/src/Collections/Collections/CollectionHashing.cs</summary>
public static class CollectionHashing
{
public static int GetHashCode(this IList list, bool fromValues)
{
if (list is null)
throw new ArgumentNullException(nameof(list));
if (!fromValues)
return list.GetHashCode();
int length = list.Count;
if (length == 0)
throw new ArgumentException(nameof(list), "List cannot be empty");
int c = 0;
for (int i = 0; i < length; i++)
{
object value = list[i] ?? throw new NullReferenceException("Value cannot be null");
c = CombineHashCodes(c, value.GetHashCode());
}
return c;
}
internal static int CombineHashCodes(int h1, int h2)
{
return ((h1 << 5) + h1) ^ h2;
}
}
</code></pre>
<p>Code on <a href="https://dotnetfiddle.net/Eh1znD" rel="nofollow noreferrer">dotnetfiddle</a></p>
<h2>Problem</h2>
<p>While the code above works perfectly fine, the algorithm is redicolusily expensive and has way to much memory overhead for my liking. But I am at the end of my wits in regards to optimizing this code, while intuitively the desired behaviour <strong>should</strong> be achievable with much less computational effort. So I feel like I am missing something important here.</p>
<h2>Question</h2>
<p>So I need all the opinions I can get</p>
<ul>
<li>A: on how to optimize my existing code, or</li>
<li>B: on a fundamentally different approach to the problem, that yields a simplier solution.</li>
</ul>
<p>Thanks in advance, and happy coding!</p>
<p>Edit: Fix <code>Distinct</code>-clause: implement <code>IEqualityComparer<>.GetHashCode</code>, and loose trust in <code>IEnumerable<>.SequenceEquals</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T08:13:51.243",
"Id": "502704",
"Score": "1",
"body": "2 questions: why does \"Root.Sub11.Sub21.Sub13.Sub14.Sub47\" not go to \"Root.Sub11/Sub21/Sub13.Sub14.Sub47\", is there a limit of one \".\" per folder name? Would a solution that only returns unique directories be acceptable? e.g. you currently have 3 \"Root.Sub11/Sub21/Sub13.Sub14\" returned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:57:51.630",
"Id": "502729",
"Score": "0",
"body": "@RobH Good point. And indeed the code should do exactly as you suggest in the `Distinct`-clause. But I had to implement a custom `GetHashCode`-function, because `Distinct`first checks `GetHashCode`. See updated [dotnetfiddle](https://dotnetfiddle.net/Eh1znDl) file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T14:54:40.960",
"Id": "502745",
"Score": "1",
"body": "I don't see why you have \"Root.Sub11\" and \"Sub13.Sub14\" as directory names, other than because some random rule says so. Why indulge such inconsistent behavior? What if your list changes in the future and breaks the current directory structure?"
}
] |
[
{
"body": "<p>I think you can simplify the problem by splitting it into two parts. Part one, build a tree structure to hold your data. Part two, take the tree and spit out your paths. I knocked up a very quick example below.</p>\n<pre><code>// A simple, specialised node class for your tree\nclass Node\n{\n public bool Ends { get; private set; }\n public string Value { get; private set; }\n \n public List<Node> Children { get; private set; } = new List<Node>();\n\n private Node GetOrAddChild(string value)\n {\n var child = Children.FirstOrDefault(c => c.Value == value);\n if (child == null)\n {\n child = new Node { Value = value };\n Children.Add(child);\n }\n return child;\n }\n\n public void AddPath(string path) => AddPath(this, path);\n\n public static void AddPath(Node n, string path)\n {\n if (string.IsNullOrEmpty(path))\n return;\n \n var idx = path.IndexOf(".");\n if (idx == -1)\n {\n var child = n.GetOrAddChild(path);\n child.Ends = true;\n }\n else\n {\n var part = path.Substring(0, idx);\n var child = n.GetOrAddChild(part);\n AddPath(child, path.Substring(idx + 1));\n }\n }\n}\n</code></pre>\n<p>Using this, you then create your tree with your data:</p>\n<pre><code>void Main()\n{\n // build the tree\n Node root = new Node();\n string[] namespaces = new[] {\n "Root.Sub11.Sub11.Sub3",\n "Root.Sub11.Sub11",\n "Root.Sub11.Sub21",\n "Root.Sub11.Sub21.Sub12",\n "Root.Sub11.Sub21.Sub13.Sub14",\n "Root.Sub11.Sub21.Sub13.Sub14",\n "Root.Sub11.Sub21.Sub13.Sub14",\n "Root.Sub11.Sub21.Sub13.Sub14.Sub47",\n };\n foreach (var ns in namespaces)\n {\n root.AddPath(ns);\n }\n\n // Use the tree:\n GetDirectories(root).ToList();\n}\n</code></pre>\n<p>Now that you have a tree of unique paths, one simply walks the tree:</p>\n<pre><code>IEnumerable<string> GetDirectories(Node n)\n{\n if (n.Ends)\n {\n yield return n.Value;\n }\n var separator = n.Children.Count == 1 && !n.Ends ? "." : "/";\n foreach (var c in n.Children)\n foreach (var path in GetDirectories(c))\n {\n yield return n.Value == null\n ? path\n : $"{n.Value}{separator}{path}";\n }\n}\n</code></pre>\n<p>I haven't checked the performance of this code but I believe it is easier to follow what's happening. Because of that, you can also further specialize the tree structure e.g. store the children in an <code>IDictionary<string, Node></code> instead of using lists to speed things up by changing the <code>FirstOrDefault</code> to <code>TryGetValue</code>.</p>\n<p>I find this two step approach a useful pattern when an algorithm is getting overly complex. It's usually a sign that I haven't got a suitable data structure to work with and introducing one can simplify the implementation a lot. A nice side-effect is that you can easily add other formatters to spit out XML, HTML, mkdir commands, or whatever you need without having to change the core algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:29:21.550",
"Id": "502897",
"Score": "1",
"body": "Based on your answer I created a [tree class](https://dotnetfiddle.net/vZhWyL). Thanks a lot! I still would like to convert the GetDirectories into an iterative algorithm, but thats of little matter."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T14:15:16.990",
"Id": "254896",
"ParentId": "254859",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254896",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:54:47.500",
"Id": "254859",
"Score": "3",
"Tags": [
"c#",
"performance",
"algorithm"
],
"Title": "Namespace list to directory structure"
}
|
254859
|
<p>My name is Ruben and I am seeking tips on how to improve/optimize these functions. I picked up Python last year and I am at a point at which I can code scripts to do what is needed, but as you will see I am for sure a beginner especially when it comes to parsing files.</p>
<p>This section of the Python script has the purpose of going into a long log file that is given by the ab initio computational chemistry program MOLCAS (included a cropped log file) and copies the Dipole values under the RASSI module section to 3 separate files:</p>
<pre><code>XDIPOLE (MLTPL 1 COMPONENT 1 in log file),
YDIPOLE (MLTPL 1 COMPONENT 2 in log file),
ZDIPOLE (MLTPL 1 COMPONENT 3 in log file).
</code></pre>
<p>After doing so the next section of code also included here creates a color map that shows the dipole values in a more eye-friendly manner. The code as it stands does work however I have been able to optimize all the scripts except for these two tasks which I know are not the best approaches.</p>
<p>I am interested only in the values under <code>"PROPERTY: MLTPL 1"</code> I will include a copy of what the output files look like which are pretty straight forward especially when looking at a very small number of states.</p>
<pre><code>
import pandas as pd
from matplotlib import pyplot as plt
import sys
import seaborn as sns
from subprocess import Popen, PIPE
def GetDipoleValuesAsArray(filename,string,delimiter):
with open(filename, 'r') as fin:
value=[]
for line in fin:
if string in line:
option_value = (line.partition(delimiter)[2]).strip()
value.append(option_value)
return value
def ExecuteNoWrite(command):
#>Executes to command line but does not print
p = Popen(command, stdout=PIPE, shell=True)
p_status = p.wait()
if p_status > 0:
print("Errors found:: ", p_status)
sys.exit()
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
# >Gets Dipoles found inside of <Project>.log "RASSI" Section.
#
def CopyXYZDipoles(filein, fileout, linestart, linestop, numberofstates):
linestop2="PROPERTY: MLTPL 2"
with open(filein, 'r') as fin:
with open(fileout + "temp", 'w') as fout:
copy = False
for line in fin:
if linestart in line:
copy = True
next(fin)
next(fin)
next(fin)
elif "STATE" in line:
next(fin)
elif linestop in line:
copy = False
elif linestop2 in line:
copy = False
elif copy:
fout.write(line)
range_states = range(0, numberofstates, 1)
with open(fileout, 'w') as fout:
fout.write("\n")
for states in range_states:
states += 1
string = " " + str(states) + " "
value = GetDipoleValuesAsArray(fileout+"temp", string, " ")
fout.write(' '.join([str(f) for f in value]) + "\n")
ExecuteNoWrite("rm " + fileout + "temp")
# >Calls "CopyXYZDipoles"
def GetDipolesFromLogFile(Project_Name,numberofstates):
componentlist = list("123")
for component in componentlist:
component1 = str(int(float(component) + 1))
if component == "1":
dipolename = "X_DIPOLE"
elif component == "2":
dipolename = "Y_DIPOLE"
elif component == "3":
dipolename = "Z_DIPOLE"
CopyXYZDipoles(Project_Name + ".log", dipolename,
"PROPERTY: MLTPL 1 COMPONENT: " + component,
"PROPERTY: MLTPL 1 COMPONENT: " + component1, numberofstates)
print("Extracted " + dipolename)
# >Makes a color matrix of the Dipoles between each states
#
def Make_MU_HeatMap(directory):
rows = file_len(directory + "/X_DIPOLE")
cols = rows
direction_list = list("XYZ")
for direction in direction_list:
with open(directory + "/" + direction + '_DIPOLE', 'r') as fin:
data = []
next(fin)
for i in range(1, rows):
data.append(list(map(float, fin.readline().split()[:cols])))
df=pd.DataFrame(data)
# mask = np.zeros_like(data)
# mask[np.triu_indices_from(mask)] = True # cuts out upper triangular side of the matrix
f, ax = plt.subplots(figsize=(11, 9))
cmap = sns.color_palette("coolwarm", as_cmap=True)
sns.heatmap(
df, # The data to plot
# mask=mask, # Mask some cells
cmap=cmap, # What colors to plot the heatmap as
annot=True, # Should the values be plotted in the cells?
vmax=1, # The maximum value of the legend. All higher vals will be same color
vmin=-1, # The minimum value of the legend. All lower vals will be same color
center=0, # The center value of the legend. With divergent cmap, where white is
square=True, # Force cells to be square
linewidths=.5, # Width of lines that divide cells
cbar_kws={"shrink": .5} # Extra kwargs for the legend; in this case, shrink by 50%
)
f.savefig(directory + "/" + direction + '_DIPOLE_heatmap')
#!..Parameters
Project_Name = "CO2"
Number_of_States= 5
#!..Calls
GetDipolesFromLogFile(Project_Name, Number_of_States)
Make_MU_HeatMap(".")
</code></pre>
<p>These are the output files where the values are saved:</p>
<pre><code>XDIPOLE
-----------------------
7.712938629E-14 -9.102311508E-13 -3.732978631E-01 -2.438713418E-15 -4.761724182E-14
-9.102311508E-13 9.679238374E-12 1.728909151E+00 9.858812476E-15 5.265071924E-15
-3.732978631E-01 1.728909151E+00 -9.364600903E-12 -1.572229977E-14 -1.101781051E-14
-2.438713418E-15 9.858812476E-15 -1.572229977E-14 5.212719145E-12 1.710295527E+00
-4.761724182E-14 5.265071924E-15 -1.101781051E-14 1.710295527E+00 -5.040856621E-12
-----------------------
YDIPOLE
-----------------------
4.074216029E-14 6.729178137E-15 4.369864581E-15 -7.306955227E-01 1.089101587E-12
6.729178137E-15 -1.952287317E-15 1.801795560E-15 -3.231487341E-01 -4.975377619E-13
4.369864581E-15 1.801795560E-15 3.519326344E-17 3.572170536E-13 -3.559337038E-01
-7.306955227E-01 -3.231487341E-01 3.572170536E-13 -3.847568714E-14 -1.913983826E-15
1.089101587E-12 -4.975377619E-13 -3.559337038E-01 -1.913983826E-15 4.386068916E-17
-----------------------
ZDIPOLE
-----------------------
-1.137579010E-16 -5.756682914E-18 -3.879122328E-19 -2.660126688E-06 -6.017214054E-17
-5.756682914E-18 -1.113544139E-16 1.103580246E-17 -1.173776231E-06 1.101877183E-18
-3.879122328E-19 1.103580246E-17 -6.831956398E-17 1.297128434E-18 -1.293133976E-06
-2.660126688E-06 -1.173776231E-06 1.297128434E-18 -1.120046885E-16 1.098611840E-17
-6.017214054E-17 1.101877183E-18 -1.293133976E-06 1.098611840E-17 -6.842153071E-17
-----------------------
</code></pre>
<p>These are the colored matrixes
<a href="https://i.stack.imgur.com/AHTe9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AHTe9.png" alt="XDIPOLE COLOR MATRIX" /></a>
<a href="https://i.stack.imgur.com/L8ocC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L8ocC.png" alt="YDIPOLE COLOR MATRIX" /></a>
<a href="https://i.stack.imgur.com/EI4Q5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EI4Q5.png" alt="ZDIPOLE COLOR MATRIX" /></a></p>
<p>This is a shortened log file: ( for unedited log file I added it to <a href="https://drive.google.com/file/d/1qP5nsAZ64SyEktTYXm4eMAqlNamuBoQq/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1qP5nsAZ64SyEktTYXm4eMAqlNamuBoQq/view?usp=sharing</a> )</p>
<pre><code>()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
&RASSI
only a single process is used
available to each process: 10 GB of memory, 1 thread?
pid: 24875
()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
********************************************************************************
* *
* General data section *
* *
********************************************************************************
############################
#............... ##########
# ... Other parts of the long log file here. Skipping to Dipole section ...
#............... ##########
############################
****************************************************************************************************
* *
* Spin-free properties section *
* *
****************************************************************************************************
++ Matrix elements
=========================================
MATRIX ELEMENTS OF 1-ELECTRON OPERATORS
FOR THE SPIN-FREE EIGENSTATES:
=========================================
(including nuclear contrib.)
SELECTED PROPERTIES:
MLTPL 0 1 MLTPL 1 1 MLTPL 1 2 MLTPL 1 3 MLTPL 2 1
MLTPL 2 2 MLTPL 2 3 MLTPL 2 4 MLTPL 2 5 MLTPL 2 6
VELOCITY 1 VELOCITY 2 VELOCITY 3 ANGMOM 1 ANGMOM 2
ANGMOM 3 MLTPV 2 1 MLTPV 2 2 MLTPV 2 3 MLTPV 2 4
MLTPV 2 5 MLTPV 2 6
PROPERTY: MLTPL 0 COMPONENT: 1 #This is not wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 1.200000000E+01 -2.194426650E-16 4.318101516E-18 1.330225916E-15
2 -2.194426650E-16 1.200000000E+01 -8.386861199E-14 5.042296192E-17
3 4.318101516E-18 -8.386861199E-14 1.200000000E+01 -8.220056120E-17
4 1.330225916E-15 5.042296192E-17 -8.220056120E-17 1.200000000E+01
5 2.926475414E-26 1.490676187E-27 6.588695814E-27 -1.246229307E-15
STATE 5
1 2.926475414E-26
2 1.490676187E-27
3 6.588695814E-27
4 -1.246229307E-15
5 1.200000000E+01
PROPERTY: MLTPL 1 COMPONENT: 1 #This is wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 7.712938629E-14 -9.102311508E-13 -3.732978631E-01 -2.438713418E-15
2 -9.102311508E-13 9.679238374E-12 1.728909151E+00 9.858812476E-15
3 -3.732978631E-01 1.728909151E+00 -9.364600903E-12 -1.572229977E-14
4 -2.438713418E-15 9.858812476E-15 -1.572229977E-14 5.212719145E-12
5 -4.761724182E-14 5.265071924E-15 -1.101781051E-14 1.710295527E+00
STATE 5
1 -4.761724182E-14
2 5.265071924E-15
3 -1.101781051E-14
4 1.710295527E+00
5 -5.040856621E-12
PROPERTY: MLTPL 1 COMPONENT: 2 #This is wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 4.074216029E-14 6.729178137E-15 4.369864581E-15 -7.306955227E-01
2 6.729178137E-15 -1.952287317E-15 1.801795560E-15 -3.231487341E-01
3 4.369864581E-15 1.801795560E-15 3.519326344E-17 3.572170536E-13
4 -7.306955227E-01 -3.231487341E-01 3.572170536E-13 -3.847568714E-14
5 1.089101587E-12 -4.975377619E-13 -3.559337038E-01 -1.913983826E-15
STATE 5
1 1.089101587E-12
2 -4.975377619E-13
3 -3.559337038E-01
4 -1.913983826E-15
5 4.386068916E-17
PROPERTY: MLTPL 1 COMPONENT: 3 #This is wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 -1.137579010E-16 -5.756682914E-18 -3.879122328E-19 -2.660126688E-06
2 -5.756682914E-18 -1.113544139E-16 1.103580246E-17 -1.173776231E-06
3 -3.879122328E-19 1.103580246E-17 -6.831956398E-17 1.297128434E-18
4 -2.660126688E-06 -1.173776231E-06 1.297128434E-18 -1.120046885E-16
5 -6.017214054E-17 1.101877183E-18 -1.293133976E-06 1.098611840E-17
STATE 5
1 -6.017214054E-17
2 1.101877183E-18
3 -1.293133976E-06
4 1.098611840E-17
5 -6.842153071E-17
PROPERTY: MLTPL 2 COMPONENT: 1 #This is not wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 4.823310421E+01 -1.805369316E+00 4.783430444E-12 7.632822170E-14
2 -1.805369316E+00 4.482222024E+01 -9.951086369E-13 -4.665853905E-14
3 4.783430444E-12 -9.951086369E-13 4.458050931E+01 -7.566061281E-15
4 7.632822170E-14 -4.665853905E-14 -7.566061281E-15 4.585650178E+01
5 -9.358570459E-17 1.592285998E-16 1.279473824E-17 -1.616419414E-13
STATE 5
1 -9.358570459E-17
2 1.592285998E-16
3 1.279473824E-17
4 -1.616419414E-13
5 4.577125639E+01
PROPERTY: MLTPL 2 COMPONENT: 2 #This is not wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 -2.192419537E-16 -2.411741231E-16 -2.314343136E-17 -2.063236807E-12
2 -2.411741231E-16 -1.096619443E-16 -1.500648083E-17 1.065273015E-13
3 -2.314343136E-17 -1.500648083E-17 6.945394753E-17 -2.689810760E-25
4 -2.063236807E-12 1.065273015E-13 -2.689810760E-25 -1.257444004E-15
5 -1.431227599E+00 6.493368077E-02 -1.623715429E-13 -3.989299446E-14
STATE 5
1 -1.431227599E+00
2 6.493368077E-02
3 -1.623715429E-13
4 -3.989299446E-14
5 -1.454288070E-15
PROPERTY: MLTPL 2 COMPONENT: 3 #This is not wanted
ORIGIN: 0.000000000E+00 0.000000000E+00 0.000000000E+00
STATE 1 2 3 4
1 -7.138286176E-17 -3.053047924E-18 -5.733640991E-17 -1.369977170E-16
2 -3.053047924E-18 -7.650874504E-17 5.043306125E-17 -7.885876738E-17
3 -5.733640991E-17 5.043306125E-17 -4.059241581E-17 8.831450537E-29
4 -1.369977170E-16 -7.885876738E-17 8.831450537E-29 -7.209622042E-17
5 -5.208466495E-06 2.363040658E-07 -8.562577275E-17 4.752354755E-17
STATE 5
1 -5.208466495E-06
2 2.363040658E-07
3 -8.562577275E-17
4 4.752354755E-17
5 -3.593758270E-17
PROPERTY: MLTPL 2 COMPONENT: 4 #This is not wanted
############################
#............... ##########
# ... Keeps going after this and so on however I am only currently wantin go the make files for the MLTPL 1 COMONENTS: {1,2,3} ...
#............... ##########
############################
</code></pre>
<p>Thank you so much even for reading this question and any help or suggestion will help me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:37:14.193",
"Id": "502819",
"Score": "1",
"body": "How big are the log files? Read in the whole file and search for key strings like \"PROPERTY: MLTPL 1 COMPONENT:\" rather than process the file one line at a time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T21:29:39.360",
"Id": "503220",
"Score": "0",
"body": "Hi @Reinderien thank you for replying and I apologize for the delayed response, I added the missing functions I was calling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T21:31:56.300",
"Id": "503221",
"Score": "0",
"body": "@RootTwo the log files vary a lot but they can be a few thousand lines depending on the printing level selected. So you suggest reading the entire file first then looking for the specific string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:34:59.297",
"Id": "503230",
"Score": "2",
"body": "@RubenFernandez a reviewer should be able to copy the data and code from the question, run it, and get the desired output. You want the reviewer to spend time on improving your code, not wasting time figuring out missing imports or undefined functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T16:04:51.720",
"Id": "503495",
"Score": "1",
"body": "@RootTwo Hi I just fixed the previous issues, and you are right, I do apologize for wasting your time. The script now will produce the desired results using the complete log file I attached (added it as a google drive link). I would also add the rest of the code but I just corrected the above script to be self-contained the rest would not be related to the output as they handle other files. I took out any references to the output directory location so it should be run in the same directory in which the log file is found. Please let me know of any updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T16:05:35.860",
"Id": "503496",
"Score": "0",
"body": "@Reinderien Hi I realized that I could only notify one user at a time"
}
] |
[
{
"body": "<p>Thank you for completing your question! I'm glad you did, because this was interesting to me.</p>\n<p>Here is a list of things that I've suggested you change in your application:</p>\n<ul>\n<li>Put your constant parameters at the top of the file in all-caps</li>\n<li>Use snake_case for your variable and method names</li>\n<li>Use type hints, as I've shown below for your method signatures</li>\n<li>Change your <code>get_dipoles</code> method to look for a prefix, instead of looking for a substring; and use a simple <code>split()</code> instead of worrying about an explicitly specified whitespace delimiter</li>\n<li>Do not not not include an "execute no write" and do not call "rm", for so many reasons. Just call <code>remove</code>.</li>\n<li>Do not include a <code>file_len</code>. This is not the best way to count lines, but also just don't count lines. Leave that to Pandas when it reads the data frame.</li>\n<li>Do not use a temp file. Your data are extremely small - they should stay in memory. My quick fix is to use <code>StringIO</code> so that it still looks and smells like a file even though it's in memory; but you should probably just represent this as an in-memory list of strings. Even if you did have to use a temp file, use <code>tempfile</code> module instead of rolling your own.</li>\n<li>Don't include a blank line at the beginning of your matrix files.</li>\n<li>In your <code>join</code>, do not use an inner list and drop your redundant <code>str</code> cast.</li>\n<li>Simplify your <code>componentlist</code> iteration. Just enumerate over an <code>XYZ</code> string of names. Do not have an <code>if</code> based on your iteration index.</li>\n<li>Install and use a linter such as that built into PyCharm.</li>\n<li>Use <code>pathlib</code> for path management and concatenation.</li>\n<li>Do not save a space-delimited matrix. Use a standard <code>csv</code> instead, and load this in one call to <code>pd.read_csv</code>.</li>\n<li>Add a main guard at the bottom.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from io import StringIO\nfrom pathlib import Path\nfrom typing import Iterable\n\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\n# Parameters\nPROJECT_NAME = 'CO2'\nN_STATES = 5\n\n\ndef get_dipole_values(temp_file: StringIO, prefix: str) -> Iterable[str]:\n for line in temp_file:\n if line.startswith(prefix):\n yield from line[len(prefix):].split()\n\n\ndef copy_xyz_dipoles(\n filename_in: str,\n filename_out: str,\n line_start: str,\n line_stop: str,\n n_states: int,\n):\n """\n Gets Dipoles found inside of <Project>.log "RASSI" Section.\n """\n\n linestop2 = 'PROPERTY: MLTPL 2'\n\n with StringIO() as ftemp:\n with open(filename_in) as fin:\n copy = False\n\n for line in fin:\n if line_start in line:\n copy = True\n next(fin)\n next(fin)\n next(fin)\n elif 'STATE' in line:\n next(fin)\n elif line_stop in line:\n copy = False\n elif linestop2 in line:\n copy = False\n elif copy:\n ftemp.write(line)\n\n with open(filename_out, 'w') as fout:\n for state in range(1, n_states + 1):\n prefix = f' {state} '\n ftemp.seek(0)\n values = get_dipole_values(ftemp, prefix)\n fout.write(','.join(values) + '\\n')\n\n\ndef read_dipoles(project_name: str, n_states: int):\n """\n Calls "copy_xyz_dipoles"\n """\n\n for component, dim in enumerate('XYZ', 1):\n dipole_name = f'{dim}_DIPOLE.csv'\n copy_xyz_dipoles(project_name + '.log', dipole_name,\n f'PROPERTY: MLTPL 1 COMPONENT: {component}',\n f'PROPERTY: MLTPL 1 COMPONENT: {component + 1}',\n n_states)\n print('Extracted', dipole_name)\n\n\ndef make_mu_heatmap(directory: Path):\n """Makes a color matrix of the Dipoles between each states"""\n\n for direction in 'XYZ':\n df = pd.read_csv(directory / (direction + '_DIPOLE.csv'), header=None)\n f, ax = plt.subplots(figsize=(11, 9))\n cmap = sns.color_palette('coolwarm', as_cmap=True)\n\n sns.heatmap(\n df, # The data to plot\n cmap=cmap, # What colors to plot the heatmap as\n annot=True, # Should the values be plotted in the cells?\n vmax=1, # The maximum value of the legend. All higher vals will be same color\n vmin=-1, # The minimum value of the legend. All lower vals will be same color\n center=0, # The center value of the legend. With divergent cmap, where white is\n square=True, # Force cells to be square\n linewidths=.5, # Width of lines that divide cells\n cbar_kws={'shrink': .5} # Extra kwargs for the legend; in this case, shrink by 50%\n )\n\n f.savefig(directory / (direction + '_DIPOLE_heatmap'))\n\n\nif __name__ == '__main__':\n read_dipoles(PROJECT_NAME, N_STATES)\n make_mu_heatmap(Path('.'))\n</code></pre>\n<p>Here is a slightly longer version that:</p>\n<ul>\n<li>classifies the project and each component</li>\n<li>detects the number of states, rather than having that hard-coded</li>\n<li>is more careful in parsing the matrix definitions in the log file, using <code>read_csv</code> in whitespace-delimited mode</li>\n<li>Keeps the (very, very small) dataframes in memory rather than forcing a disk round-trip for plotting</li>\n<li>Plots X, Y and Z in one triple-subplot figure for better spatial interpretation</li>\n</ul>\n<pre><code>from io import StringIO\nfrom pathlib import Path\n\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom typing import Iterable\n\nfrom matplotlib.axes import Axes\nfrom matplotlib.colors import Colormap\nfrom matplotlib.figure import Figure\n\n\nclass Component:\n NAMES = 'XYZ'\n COLORMAP: Colormap = sns.color_palette('coolwarm', as_cmap=True)\n\n def __init__(self, section: str):\n *_, component, body = section.split(maxsplit=3)\n self.index = int(component)\n self.name = self.NAMES[self.index - 1]\n self.df = self._parse(body)\n\n @classmethod\n def _parse(cls, body: str) -> pd.DataFrame:\n colsets = [\n cls._str_to_df(colset)\n for colset in cls._colset_strings(body)\n ]\n without_state = (\n df.drop('STATE', 1)\n for df in colsets\n )\n\n return pd.concat(\n (colsets[0].STATE, *without_state),\n axis=1,\n )\n\n @staticmethod\n def _colset_strings(body: str) -> Iterable[str]:\n first_col = 'STATE'\n start = body.find(first_col)\n while start != -1:\n end = body.find(first_col, start + len(first_col))\n yield body[start:end]\n start = end\n\n @staticmethod\n def _str_to_df(body: str) -> pd.DataFrame:\n with StringIO(body) as f:\n return pd.read_csv(f, sep=r'\\s+')\n\n def __str__(self):\n return self.name\n\n @property\n def without_state(self) -> pd.DataFrame:\n return self.df.drop('STATE', axis=1)\n\n def write_csv(self, path: Path, bare: bool = True):\n if bare:\n self.without_state.to_csv(path, index=False, header=False)\n else:\n self.df.to_csv(path, index=False)\n\n def mu_heatmap(self, ax: Axes) -> Axes:\n ax.set_title(self.name)\n\n return sns.heatmap(\n self.without_state, # The data to plot\n ax=ax, # Axes to draw on\n cmap=self.COLORMAP, # What colors to plot the heatmap as\n annot=True, # Should the values be plotted in the cells?\n # The maximum value of the legend. All higher vals will be same color\n vmax=1,\n # The minimum value of the legend. All lower vals will be same color\n vmin=-1,\n # The center value of the legend. With divergent cmap, where white is\n center=0,\n square=True, # Force cells to be square\n linewidths=.5, # Width of lines that divide cells\n # Extra kwargs for the legend; in this case, shrink by 50%\n cbar_kws={'shrink': .5},\n )\n\n\nclass DipolesProject:\n def __init__(self, log_path: str):\n self.components = tuple(self._parse(log_path))\n\n @staticmethod\n def _parse(log_path: str):\n with open(log_path) as f:\n body = f.read()\n\n start_i = body.find('PROPERTY: MLTPL 1 ')\n end_i = body.find('PROPERTY: MLTPL 2 ', start_i)\n body = body[start_i: end_i]\n sections = body.split('PROPERTY: MLTPL')[1:]\n\n for section in sections:\n yield Component(section)\n\n def write_csvs(\n self,\n directory: str = '.',\n suffix: str = '_DIPOLE.csv',\n bare: bool = True,\n ):\n directory = Path(directory)\n for component in self.components:\n component.write_csv(directory / (component.name + suffix), bare)\n\n def get_mu_heatmaps(self) -> Figure:\n fig, ((z, x), (y, unused)) = plt.subplots(\n 2, 2, sharex='col', sharey='row',\n figsize=(10, 10),\n )\n unused.remove()\n\n for ax, component in zip((x, y, z), self.components):\n component.mu_heatmap(ax)\n\n return fig\n\n\ndef main():\n project = DipolesProject('CO2.log')\n project.write_csvs()\n fig = project.get_mu_heatmaps()\n fig.savefig('dipole-heatmap.png')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>The result of the plot is:</p>\n<p><a href=\"https://i.stack.imgur.com/L6yzS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L6yzS.png\" alt=\"triple subplot\" /></a></p>\n<p>By far the slowest part of the program is now saving the figure itself; everything before <code>savefig</code> executes "instantly".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-04T23:24:02.263",
"Id": "534698",
"Score": "1",
"body": "Hey, I just wanted to say thank you for your helpful comments at the beginning of your answer. To this day I am still using them. I did not complete all the changes to this specific project but have taken them with me going forward. Best, Ruben"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-04T23:41:18.710",
"Id": "534699",
"Score": "0",
"body": "@RubenFernandez Great to hear! Keep posting if you have anything else to review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T21:14:02.310",
"Id": "255234",
"ParentId": "254862",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255234",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T20:56:22.783",
"Id": "254862",
"Score": "7",
"Tags": [
"python"
],
"Title": "Read MOLCAS chemistry files to create color maps"
}
|
254862
|
<p>The goal of this module is to take in a string (user input, someone copy and pasting a large list of proxies) and parse it into an array of objects.</p>
<p>I appreciate <strong>any and all</strong> feedback, <s>but I'm specifically interested in improving the <code>stringToProxy</code> function.</s></p>
<p><s>Namely I'm unsure about mutating the string parameter, seems like there could be a better solution. And the way I'm declaring the proxy at the beginning of the function feels wrong to me (using <code>As</code>) but I couldn't think of any better solution. I also feel as though I may be overusing <code>string.split()</code>.</s></p>
<p>Thanks for your time!</p>
<p><strong>Edit:</strong>
Incorporated the <code>url</code> module as <a href="https://codereview.stackexchange.com/users/35905/nazar">Nazar</a> recommended. I'm happy with this solution but still taking feedback.</p>
<pre><code>const { URL } = require("url");
interface Proxy {
host: string;
port: number;
protocol: string;
auth?: {
username: string;
password: string;
};
}
function parse(string: string): Proxy[] {
const rawArray = stringToArray(string);
const fixedArray = rawArray.map((string) => fixProxyString(string));
const proxyArray = fixedArray.map((string) => stringToProxy(string));
return proxyArray;
}
function stringToArray(string: string): string[] {
return string.trim().replace(/[ ,\n]+/g, ",").split(",");
}
function fixProxyString(string: string): string {
return string.includes("://") ? string : `http://${string}`; //if user doesnt specify a protocol, default to http
}
function stringToProxy(string: string): Proxy {
const url = new URL(string);
return {
host: url.hostname,
port: url.port ? parseInt(url.port) : 80, //if proxy is 80 url will ignore it so i need to explicitly add it
protocol: url.protocol.slice(0, -1), //removing the colon
auth: url.username ? { username: url.username, password: url.password } : undefined
};
}
export = parse;
</code></pre>
<p>Before edit:</p>
<pre class="lang-js prettyprint-override"><code>interface Proxy {
host: string;
port: number;
auth?: {
username: string;
password: string;
};
protocol?: string;
}
function parse(string: string): Proxy[] {
const rawArray = stringToArray(string);
const proxyArray = rawArray.map((string) => stringToProxy(string));
return proxyArray;
}
function stringToArray(string: string): string[] {
return string.trim().replace(/[ ,\n]+/g, ",").split(",");
}
function stringToProxy(string: string) {
const proxy = {} as Proxy;
if (string.includes("://")) {
const [protocol, remainder] = string.split("://");
proxy.protocol = protocol;
string = remainder;
}
if (string.includes("@")) {
const [auth, remainder] = string.split("@");
const [username, password] = auth.split(":");
proxy.auth = { username, password };
string = remainder;
}
const [host, port] = string.split(":");
proxy.port = parseInt(port);
proxy.host = host;
return proxy;
}
export = parse;
</code></pre>
<p>Usage:</p>
<pre><code>const parse = require("parse-proxy");
parse(`1.1.1.1:80, 2.2.2.2:80, 3.3.3.3:80`)
//result
[
{ host: '1.1.1.1', port: 80 },
{ host: '2.2.2.2', port: 80 },
{ host: '3.3.3.3', port: 80 }
]
parse(`https://user:pass@104.236.55.48:8080\nhttps://user:pass@213.105.29.14:3128`)
//result
[
{
protocol: 'https',
auth: { username: 'user', password: 'pass' },
host: '104.236.55.48',
port: 8080
},
{
protocol: 'https',
auth: { username: 'user', password: 'pass' },
host: '213.105.29.14',
port: 3128
}
]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T21:55:32.960",
"Id": "502676",
"Score": "0",
"body": "I would suggest using a built-in WHATWG API. You can get almost the same output by calling `require('url').parse` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T23:49:20.037",
"Id": "502682",
"Score": "0",
"body": "Ah yes, that does the trick, thanks for the help!"
}
] |
[
{
"body": "<p>A couple of small comments:</p>\n<p>Don't call your parameter the same thing as its type <code>string: string</code>. This makes the code needlessly difficult to read - don't make the reader waste time wondering whether this <code>string</code> a type or the variable. Use <code>input</code>, <code>source</code> or something else that makes sense.</p>\n<p>Don't shadow outer variables/arguments in arrow functions, again this harms readability <code>rawArray.map((string) => fixProxyString(string));</code>. Note that the parenthesis are optional for one parameter too. Consider instead:</p>\n<pre><code>function parse(input: string): Proxy[] {\n const rawArray = stringToArray(input);\n const fixedArray = rawArray.map(raw => fixProxyString(raw));\n const proxyArray = fixedArray.map(fixed => stringToProxy(fixed));\n return proxyArray;\n}\n</code></pre>\n<p>I think (although not tested) that you can further simplify:</p>\n<pre><code>function parse(input: string): Proxy[] {\n return stringToArray(input)\n .map(fixProxyString)\n .map(stringToProxy);\n}\n</code></pre>\n<p>You don't need to replace and then split here <code>return string.trim().replace(/[ ,\\n]+/g, ",").split(",");</code>. You can just <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\"><code>split</code></a> by the regex directly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T11:49:39.353",
"Id": "255559",
"ParentId": "254863",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T21:19:35.347",
"Id": "254863",
"Score": "2",
"Tags": [
"javascript",
"parsing",
"node.js",
"typescript",
"proxy"
],
"Title": "Parse proxy strings to array of objects"
}
|
254863
|
<p>I wrote this function to generate random permutation of input vector, while making sure every element has switched place (for a Secret Santa like purpose).</p>
<pre><code>std::map<std::string, std::string> getPermutation(const std::vector<std::string>& participants)
{
auto permuted = participants;
std::random_device rd;
std::mt19937 g(rd());
bool correctlyPermuted = false;
while(!correctlyPermuted)
{
std::shuffle(permuted.begin(), permuted.end(), g);
auto res = std::mismatch(participants.begin(), participants.end(), permuted.begin(), std::not_equal_to{});
if(res.first == participants.end())
{
correctlyPermuted = true;
}
}
std::map<std::string, std::string> result;
for(int i = 0; i < participants.size(); ++i)
{
result[participants[i]] = permuted[i];
}
return result;
}
</code></pre>
<p>You can run code <a href="https://repl.it/@Yksisarvinen13/BozuMowiModluModlu#main.cpp" rel="nofollow noreferrer">here</a>. Note that's still work in progress, I'm mostly concerned about the function above.</p>
<p><code>participants</code> is guaranteed to contain no duplicate elements.</p>
<p>I'm not really concerned with speed - it's supposed to be executed by humans, they are unlikely to notice any performance improvement. Of course, you are welcome to point any obvious performance issues.<br />
However, I'm concerned with the readability of the function, particularly with the use of <code>std::mismatch</code> to find actually matching elements. It feels <em>too clever</em>, but maybe it's just good use of functional programming and I'm overthinking? It also seems too long for a good function (22 lines), but I can't think of how it could be splitted/shortened logically.</p>
|
[] |
[
{
"body": "<p>I would suggest breaking the actual permutation algorithm out into its own function, since it’s useful on its own. That would pretty much solve the readability problem.</p>\n<p>And then I would suggest doing the permutation with <em>indices</em>, rather than copying the whole input vector. (Indices would also work for other range types, especially if you limit the input range type to random-access, which is not unreasonable for a sorting algorithm.) Once you’re dealing with indices, detecting positions that are unchanged is trivial, and quick:</p>\n<pre><code>template <std::sized_range Rng, typename Gen>\nrequires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\nauto get_fully_permuted_indices(Rng const& rng, Gen&& gen)\n{\n auto idxs = std::vector<std::size_t>(std::ranges::size(rng));\n std::iota(idxs.begin(), idxs.end(), std::size_t(0));\n\n auto permuted = false;\n do\n {\n std::ranges::shuffle(idxs, gen);\n\n permuted = true; // hope for the best!\n for (auto i = std::size_t(0); i < res.size(); ++i)\n {\n // if the value at i is the same as i, then this is not properly permuted\n if (i == idxs[i])\n {\n permuted = false;\n break;\n }\n }\n } while (not permuted);\n\n return idxs;\n}\n</code></pre>\n<p>Once you have that, your main function is trivial:</p>\n<pre><code>std::map<std::string, std::string> getPermutation(const std::vector<std::string>& participants)\n{\n auto const idxs = get_fully_permuted_indices(participants, std::mt19937{std::random_device(){}});\n\n auto res = std::map<std::string, std::string>{};\n for (auto i = std::size_t(0); i < std::ranges::size(participants); ++i)\n res.emplace(participants[i], participants[idxs[i]]);\n\n return res;\n}\n</code></pre>\n<p>I would also suggest moving the creation of the RNG out of the function, and passing the RNG in as an argument:</p>\n<pre><code>template <typename Gen>\nrequires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\nauto getPermutation(const std::vector<std::string>& participants, Gen&& gen)\n{\n auto const idxs = get_fully_permuted_indices(participants, std::forward<Gen>(gen));\n\n auto res = std::map<std::string, std::string>{};\n for (auto i = std::size_t(0); i < std::ranges::size(participants); ++i)\n res.emplace(participants[i], participants[idxs[i]]);\n\n return res;\n}\n</code></pre>\n<p>This goes with the doctrine of “one function, one job”, and allows both reusing the RNG, and testing the function with a known RNG.</p>\n<p>If you want to go even further, an “is-fully-permuted-indices” algorithm, to remove that <code>for</code> loop in <code>get_fully_permuted_indices()</code>, also seems useful:</p>\n<pre><code>template <std::input_range Rng>\nrequires std::equality_comparable_with<std::ranges::range_value_t<Rng>, std::size_t>\nconstexpr auto is_fully_permuted_indices(Rng const& rng)\n{\n auto idx = std::size_t(0);\n for (auto&& item : rng)\n {\n if (item == idx++)\n return false;\n }\n\n return true;\n}\n\ntemplate <std::sized_range Rng, typename Gen>\nrequires std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\nauto get_fully_permuted_indices(Rng const& rng, Gen&& gen)\n{\n auto idxs = std::vector<std::size_t>(std::ranges::size(rng));\n std::iota(idxs.begin(), idxs.end(), std::size_t(0));\n\n do\n {\n std::ranges::shuffle(idxs, gen);\n } while (not is_fully_permuted_indices(idxs));\n\n return idxs;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T01:01:05.450",
"Id": "254871",
"ParentId": "254866",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T22:24:56.580",
"Id": "254866",
"Score": "2",
"Tags": [
"c++",
"random",
"combinatorics"
],
"Title": "Generating random permutation with forced change of order (Secret Santa)"
}
|
254866
|
<p>I wrote a function that returns a directed graph as an adjacency matrix. The function requires two arguments: the amount of nodes and the amount of edges. At first, nodes are placed and instantly connected to the graph. When all nodes are added, random edges are created until all edges are placed.</p>
<p>Code:</p>
<pre><code>public int[,] GenerateMatrix(int Nodes, int Edges)
{
if (Edges < Nodes - 1) throw new Exception("Too few edges");
if (Edges > Nodes * (Nodes - 1)) throw new Exception("Too many edges");
int[,] adjacencyMatrix = new int[Nodes, Nodes];
// Gives every cell a value of zero
for (int y = 0; y < Nodes; y++)
{
for (int x = 0; x < Nodes; x++)
{
adjacencyMatrix[x, y] = 0;
}
}
int placedEdges = 0;
for (int i = 1; i < Nodes; i++)
{
// produce edge between rnd(0, amountofnodes) to new node
int fromVertex = random.Next(0, i);
int weight = random.Next(1, 10);
adjacencyMatrix[i, fromVertex] = weight;
placedEdges++;
}
while (placedEdges < Edges)
{
int fromVertex = random.Next(0, Nodes);
int weight = random.Next(1, 10);
int targetVertex = random.Next(0, Nodes);
while (targetVertex == fromVertex || adjacencyMatrix[targetVertex, fromVertex] != 0) //|| adjacencyMatrix[fromVertex, targetVertex] != 0)// tredje condition tar bort parallella kanter
{
fromVertex = random.Next(0, Nodes);
targetVertex = random.Next(0, Nodes);
}
adjacencyMatrix[targetVertex, fromVertex] = weight;
placedEdges++;
}
return adjacencyMatrix;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:59:02.580",
"Id": "502734",
"Score": "2",
"body": "Welcome to CodeReview@SE. I think the difference in code indentation between the method head and the braces around its body unusual: please state, in comment or question body, whether it is intentional or not. If it is against your intentions, please heed [What should I [not\\] do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:59:24.497",
"Id": "502735",
"Score": "0",
"body": "When picking a fromVertex that already has Nodes-1 outgoing edges, the while-loop won't terminate."
}
] |
[
{
"body": "<p>Here are my suggestions:</p>\n<ul>\n<li><p><code>Nodes</code>, <code>Edges</code>: most of the time the function's parameters don't start with big letter. <code>nodes</code> and <code>edges</code> are more preferable.</p>\n<ul>\n<li>Also consider to restraint the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types\" rel=\"nofollow noreferrer\">possible range of these variables</a>. <code>uint</code> or even smaller like <code>ushort</code> might be a better fit for your use case.</li>\n</ul>\n</li>\n<li><p><code>throw new Exception</code>: It is good that you do preliminary checks. Usually the preferred Exception type is <code>ArgumentException</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.argumentexception\" rel=\"nofollow noreferrer\">1</a>) to indicate that you have a problem with the calling parameters.</p>\n</li>\n<li><p><code>adjacencyMatrix</code>: You don't need to zero all of the entries inside this matrix because by default their value will be zero. (<code>int</code> is a value type with a default value <code>0</code>).</p>\n<ul>\n<li>If you wish to clean the array, because you have received that for example via a parameter then you can use the built-in <code>Array.Clear</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.clear?#System_Array_Clear_System_Array_System_Int32_System_Int32_\" rel=\"nofollow noreferrer\">1</a>):<br />\n<code>Array.Clear(adjacencyMatrix, 0, adjacencyMatrix.Length);</code></li>\n</ul>\n</li>\n<li><p><s><code>random.Next(0, i)</code>: Alternative: <code>random.Next() % i</code> </s></p>\n</li>\n<li><p><s><code>random.Next(1, 10)</code>: Alternative: <code>new Random().Next() * (10 - 1) + 1</code> (<a href=\"https://stackoverflow.com/a/50347359/13268855\">1</a>) </s></p>\n</li>\n<li><p><code>placedEdges++</code>: instead of increasing it every time you could initialize it with the proper value: <code>int placedEdges = Nodes -1;</code></p>\n</li>\n<li><p><code>fromVertex</code> and <code>targetVertex</code>:</p>\n<ul>\n<li><code>fromVertex</code> + <code>toVertex</code></li>\n<li>OR <code>sourceVertex</code> and <code>targetVertex</code> would</li>\n</ul>\n<p>give more convenient naming.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:25:27.137",
"Id": "502724",
"Score": "0",
"body": "Why do you recommend the alternative randomization? Is it faster? According to me random.Next(start, to) is more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:31:31.307",
"Id": "502726",
"Score": "0",
"body": "`random.Next(start, to)` has a good chance to be uniform - slim for `random.Next() % i`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:35:15.563",
"Id": "502727",
"Score": "0",
"body": "If you look at the source code of [Next()](https://github.com/microsoft/referencesource/blob/master/mscorlib/system/random.cs#L131) and [Next(int minValue, int maxValue)](https://github.com/microsoft/referencesource/blob/master/mscorlib/system/random.cs#L160) then you can see that the latter might call the `InternalSample` [twice](https://github.com/microsoft/referencesource/blob/master/mscorlib/system/random.cs#L135) in some cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:37:49.817",
"Id": "502728",
"Score": "1",
"body": "In this particular case it won't call it, so I can agree with you guys that calling random.Next with min and max values might be more convenient here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T09:50:03.387",
"Id": "254880",
"ParentId": "254868",
"Score": "3"
}
},
{
"body": "<p>You describe what the code is to accomplish:<br />\ndo so <em>in the code</em>, using what tool support works for you. MS is on an <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/codedoc\" rel=\"nofollow noreferrer\">XML spree</a>, <a href=\"https://www.doxygen.nl/manual/docblocks.html\" rel=\"nofollow noreferrer\">doxygen</a> currently has a .nl domain.</p>\n<p>Omit <em>giving every cell a value of zero</em>:</p>\n<blockquote>\n<p><strong>The default values of numeric array elements are set to zero</strong>,<br />\nand reference elements are set to null.</p>\n</blockquote>\n<p>You use <em>node</em> as well as <em>vertex</em> - <a href=\"https://codereview.stackexchange.com/a/254880/93149\">Peter Csala</a> already assessed mixing <em>from</em> and <em>target</em>.</p>\n<p>For a uniformly pseudo-random non-negative number up to some <em>maxValue</em> call <code>int Random.Next(int maxValue)</code>.<br />\nEach and every edge from the first loop "points down", introducing a non-uniformity.</p>\n<p>When picking a <code>fromVertex</code> that already has <em>Nodes-1</em> outgoing edges, the <code>while</code>-loop won't terminate.<br />\nExpect <em>many</em> trips though this loop when there are more than about Nodes^3/2 edges, anyway.<br />\n(<em>tredje villkoret undviker <strong>anti</strong>parallella kanter</em>)<br />\n(Not using anti-parallel edges would need to be taken into account in the initial (uncommented!) range check.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:51:14.403",
"Id": "254887",
"ParentId": "254868",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254880",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T23:59:12.240",
"Id": "254868",
"Score": "0",
"Tags": [
"c#",
"graph"
],
"Title": "Generating a random directed graph"
}
|
254868
|
<p>This evening I have seen the text of the <a href="https://codereview.stackexchange.com/questions/38500/rainfall-challenge">Rainfall Challenge</a> posted seven years ago by <a href="https://codereview.stackexchange.com/users/9972/hunter-mcmillen">Hunter McMillen</a>. I did not look at his solution (besides, I have no clue about perl), but I was intrigued by the problem, so I set out to solve it. In this case, it seems to me that OOP is a bit of an overkill, so I did it in a procedural way. With Fortran. I imagine that in a high-level language it should be possible to write a very concise solution. Yet, the Fortran code length is in the same ballpark as Perl's in this case.</p>
<p>The program generates a random landscape (more like cosmic microwave background than countryside hills, but still ...) and save a 3D plot with elevation, an unique integer index per basin, and an error code specifying whether the conditions of the problem are met. For the most part, the program seems to work quite fast and well, but:</p>
<ol>
<li><p>I wonder whether the cycle that colors the map can be made (still) faster with some clever tweak;</p>
</li>
<li><p>Occasionally, there are isolated points in the map where the conditions are not met (two equivalent cells have different colors). We are talking about a handful points when the map has 160,000 cells. I imagine this glitches may occur in proximity of saddles or local extrema, where the elevation, represented just in single precision, can happen to be identical in two contiguous cells, thus breaking the assumptions of the problem. However, I have not pinned down the issue yet.</p>
</li>
</ol>
<p>Here are some sample plots in a field of 400 x 400 cells:</p>
<p><a href="https://i.stack.imgur.com/pHuFB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHuFB.jpg" alt="Landscape defining the pluvial basins" /></a></p>
<p><a href="https://i.stack.imgur.com/lVQGg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lVQGg.png" alt="Color-coded basin areas" /></a></p>
<p><a href="https://i.stack.imgur.com/vL4J6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vL4J6.png" alt="Flagged cells (assigned 'wrong' color - see text.)" /></a></p>
<p>I look forward to your hints and feedback. Below is the code and instructions on how to run it and plot the results. For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
<pre class="lang-fortran prettyprint-override"><code>program Basins
implicit none
integer, parameter :: XSIZE = 400
integer, parameter :: YSIZE = 400
real :: land (0:XSIZE+1,0:YSIZE+1) = 0.
integer :: color(0:XSIZE+1,0:YSIZE+1) = 0
integer :: error(0:XSIZE+1,0:YSIZE+1) = 0
call CreateLand( land, XSIZE, YSIZE )
call FindBasins( land, color, XSIZE, YSIZE )
call CheckColor( land, color, error, XSIZE, YSIZE )
call SaveData ( land, color, error, XSIZE, YSIZE )
contains
subroutine CreateLand( land, XSIZE, YSIZE )
real , intent(out):: land( 0:XSIZE+1, 0:YSIZE+1 )
integer, intent(in) :: XSIZE, YSIZE
real , parameter :: PI = 4. * atan(1.)
complex, parameter :: ZI = (0.,1.)
integer, parameter :: NFOURX = 4
integer, parameter :: NFOURY = 4
integer :: ikx, iky, ix, iy
real :: ck_abs, ck_arg, kx, ky
complex :: ck, vx(0:XSIZE+1,1), vy(1,0:YSIZE+1)
vx = (0.,0.)
vy = (0.,0.)
do iky = -NFOURY, NFOURY
ky = 2 * PI / real(YSIZE) * real(iky)
do iy = 1, YSIZE
vy(1,iy) = exp( ZI * ky * real(iy) )
enddo
do ikx = -NFOURX, NFOURX
kx = 2 * PI / real(XSIZE) * real(ikx)
do ix = 1, XSIZE
vx(ix,1) = exp( ZI * kx * real(ix) )
enddo
call random_number(ck_abs)
call random_number(ck_arg)
ck = ck_abs * exp( ZI * ck_arg * 2. * PI ) / sqrt(real(ikx*ikx+iky*iky+1.))
land = land + real( ck * matmul(vx,vy) )
enddo
enddo
do ix = 1, XSIZE
land( ix, 0 ) = land( ix, 1 ) + 1.
land( ix, YSIZE+1 ) = land( ix, YSIZE ) + 1.
enddo
do iy = 1, YSIZE
land( 0 , iy ) = land( 1 , iy ) + 1.
land( XSIZE+1, iy ) = land( XSIZE, iy ) + 1.
enddo
end subroutine CreateLand
subroutine FindBasins( land, color, XSIZE, YSIZE )
real , intent(in) :: land (0:XSIZE+1,0:YSIZE+1)
integer, intent(out):: color(0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: XSIZE, YSIZE
integer :: ix, iy, ix0, iy0, idx, idy
integer :: iColor, newColor, ncolors = 0
logical :: CHANGED
integer, allocatable :: colorVec(:)
!.. Cycles until all equivalent cells have the same color
do
CHANGED = .FALSE.
do iy = 1, YSIZE
do ix = 1, XSIZE
call FindLowestNeighbor( land(ix,iy), &
land(ix+1,iy), land(ix-1,iy) , &
land(ix,iy+1), land(ix,iy-1) , &
idx, idy )
ix0 = ix + idx
iy0 = iy + idy
call ReassignCellPairColor( &
land (ix0,iy0), land (ix,iy), &
color(ix0,iy0), color(ix,iy), nColors, CHANGED )
enddo
enddo
if(.not.CHANGED)exit
enddo
call ReMapColor( color, ncolors, XSIZE, YSIZE )
end subroutine FindBasins
subroutine FindLowestNeighbor( val, px, mx, py, my, idx, idy )
real , intent(in) :: val, px, mx, py, my
integer, intent(out):: idx, idy
real :: lowest
lowest = val
idx = 0
idy = 0
if( px < lowest )then
idx = 1
lowest = px
endif
if( mx < lowest )then
idx = -1
lowest = mx
endif
if( py < lowest )then
idy = 1
lowest = py
endif
if( my < lowest )then
idy = -1
lowest = my
endif
end subroutine FindLowestNeighbor
subroutine ReassignCellPairColor( v0, v1, c0, c1, nc, CHANGED )
real , intent(in) :: v0, v1
integer, intent(inout) :: c0, c1, nc
logical, intent(inout) :: CHANGED
if( v0 < v1 )then
if( c1 == 0 )then
if( c0 == 0 )then
nc = nc + 1
c0 = nc
c1 = nc
else
c1 = c0
endif
CHANGED = .TRUE.
else
if( c0 == 0 )then
c0 = c1
CHANGED = .TRUE.
else
if( c0 /= c1 )then
c1 = min( c0, c1 )
c0 = c1
CHANGED = .TRUE.
endif
endif
endif
else
if( c1 == 0 )then
nc = nc + 1
c1 = nc
CHANGED = .TRUE.
endif
endif
end subroutine ReassignCellPairColor
subroutine ReMapColor( color, ncolors, XSIZE, YSIZE )
integer, intent(inout) :: color( 0:XSIZE+1, 0:YSIZE+1 )
integer, intent(in) :: ncolors, XSIZE, YSIZE
integer :: colorVec(nColors), newColor, iColor, ix, iy
colorVec=0
do ix = 1, XSIZE
do iy = 1, YSIZE
colorVec(color(ix,iy))=1
enddo
enddo
newColor=0
do iColor = 1, nColors
newColor = newColor + colorVec(iColor)
colorVec(iColor) = newColor
end do
do ix = 1, XSIZE
do iy = 1, YSIZE
color(ix,iy) = colorVec(color(ix,iy))
enddo
enddo
end subroutine ReMapColor
subroutine CheckColor( land, color, error, XSIZE, YSIZE )
real , intent(in) :: land (0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: color(0:XSIZE+1,0:YSIZE+1)
integer, intent(out):: error(0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: XSIZE, YSIZE
integer :: ix, iy, ix0, iy0, idx, idy
real :: lowest
error = 0
do ix = 1, XSIZE
do iy = 1, YSIZE
call FindLowestNeighbor( land(ix,iy), &
land(ix+1,iy), land(ix-1,iy) , &
land(ix,iy+1), land(ix,iy-1) , &
idx, idy )
ix0 = ix + idx
iy0 = iy + idy
if( abs(idx) + abs(idy) > 0 .and. color(ix0,iy0) /= color(ix,iy) ) error(ix,iy) = 1
enddo
enddo
end subroutine CheckColor
subroutine SaveData( land, color, error, XSIZE, YSIZE )
real , intent(in) :: land (0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: color(0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: error(0:XSIZE+1,0:YSIZE+1)
integer, intent(in) :: XSIZE, YSIZE
integer :: uid, ix, iy
open(newunit = uid, &
file ="basin.txt")
do ix = 1, XSIZE
do iy = 1, YSIZE
write(uid,"(i0,x,i0,x,e14.6,x,i0,x,i0)") &
ix, iy, land(ix,iy), color(ix,iy), error(ix,iy)
enddo
write(uid,*)
enddo
close(uid)
end subroutine SaveData
end program
</code></pre>
<p>The code compiles with <code>gfortran -O3</code></p>
<p>To plot the result with gnuplot:</p>
<pre><code>set pm3d
set view map
set hidden3d
set size square
f='basin.txt'
splot f u 1:2:3 w l
splot f u 1:2:4 w l
splot f u 1:2:5 w l
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T04:11:51.950",
"Id": "254874",
"Score": "2",
"Tags": [
"programming-challenge",
"unit-testing",
"interview-questions",
"fortran"
],
"Title": "Rainfall challenge: procedural implementation"
}
|
254874
|
<p>Last week I challenged myself to create the smallest possible code for a Tic Tac Toe game with an AI as opponent. Smallest possible in regards to say least number of characters used. The requirements on the game are as follows:</p>
<ul>
<li>A "nice" playing experience (ability to get user input and print the board after every move)</li>
<li>Handling wrong input data without crashing.</li>
<li>Having an unbeatable AI as opponent.</li>
<li>The ability to play again or exit after game is over</li>
</ul>
<p>The result is this code:</p>
<pre><code>def p(b):
c = [' ' if i == 0 else 'X' if i == -1 else 'O' if i == 1 else i for i in b]
[print(f'\n{c[r*3:3+r*3]}') if r == 0 else print(c[r*3:3+r*3]) for r in range(3)]
def e(b, t):
for p in ([0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]):
if b[p[0]] == b[p[1]] == b[p[2]] == t: return 1
def n(b, d, t):
if e(b, t): return 0, (9+d)
if e(b, -t): return 0, -(9 + d)
if 0 not in b: return 0, 0
x = -20
for m in [i for i in range(9) if not b[i]]:
b[m] = t
s = -n(b, d - 1, -t)[1]
b[m] = 0
if s > x: x, y = s, m
return y, x
def r():
b, w = [0]*9, -1
p(b)
while 1:
if w == -1 and not (e(b, w) or e(b, -w)) and 0 in b:
while 1:
u = input('\nPlease enter your move (1-9): ')
if u.isnumeric():
u = int(u)-1
if 0 <= u < 9 and not b[u]:
b[u], w = -1, w*-1
p(b)
break
elif w == 1 and not (e(b, w) or e(b, -w)) and 0 in b:
m, s = n(b, 8, 1)
b[m], w = 1, w*-1
p(b)
else:
f = 'You won!' if e(b, -1) else 'AI won!' if e(b, 1) else 'Game drawn!'
if input(f'\n{f} Do you want to play again (y/n)? ') != 'y': break
r()
break
r()
</code></pre>
<p>And with a bit of commentary to easier understand what is going on:</p>
<pre><code># Printing the board on the "standard" format with X:s and O:s instead of -1, 0, 1.
def print_board(board):
new_board = [' ' if i == 0 else 'X' if i == -1 else 'O' if i == 1 else i for i in board]
[print(f'\n{new_board[row*3:3+row*3]}') if row == 0 else print(new_board[row*3:3+row*3]) for row in range(3)] # Print with new line to get nicer format
# Evaluates the board
def evaluate(boart, turn):
for pos in ([0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]): # Go through all possible winning lines
if board[pos[0]] == board[pos[1]] == board[pos[2]] == turn: return 1 # Return 1 if player turn has 3 in a row
# Recursive negamax function which goes through the entire game tree.
# Depth d is used in the returned scores to get shortest possible route to victory.
def negamax(board, depth, turn):
if evaluate(board, turn): return 0, (9+depth) # Return positive score if maximizing player
if evaluate(board, -turn): return 0, -(9 + depth) # Return negative score if minimizing player wins
if 0 not in board: return 0, 0 # Drawn game, return 0
best_score = -20 # Initiate with less than smallest possible score
for move in [i for i in range(9) if not board[i]]: # Go through all empty squares on board
board[move] = turn # Make move
score = -negamax(board, depth - 1, -turn)[1] # Recursive call to go through all child nodes
board[move] = 0 # Unmake the move
if score > best_score: best_score, best_move = score, move # If score is larger than previous best, update score
return best_move, best_score # Return the best move and its corresponding score
# Main game loop.
def run():
board, turn = [0]*9, -1 # Initiate board and turn to move (-1 is human to start, 1 AI to start)
print_board(board)
while 1: # Loop until game is over
if turn == -1 and not (evaluate(board, turn) or evaluate(board, -turn)) and 0 in board: # Human turn if game is not over and there are places left on board
while 1: # Loop until a valid input is given
user_input = input('\nPlease enter your move (1-9): ') # Get input
if user_input.isnumeric(): # Find if a number is entered
u = int(user_input)-1 # Get it on the right board format (square 1 corresponds to array[0])
if 0 <= u < 9 and not board[u]: # Check if number is in the correct range and on an empty square
board[u], turn = -1, turn*-1 # Make move and change turn
print_board(board)
break
elif turn == 1 and not (evaluate(board, turn) or evaluate(board, -turn)) and 0 in b: # Ai turn if game is not over and there are places left on board
move, score = negamax(board, 8, 1) # Run Negamax loop to get a best move and the score
board[move], turn = 1, turn*-1 # Make move and change turn
print_board(board)
else: # This means the game is over or board is full
text = 'You won!' if evaluate(board, -1) else 'AI won!' if evaluate(board, 1) else 'Game drawn!' # Check who won or if there is a draw
if input(f'\n{text} Do you want to play again (y/n)? ') != 'y': break # Ask to play again, break if answer is not 'y'
run() # Run game again if answer is 'y'
break
run() # Run the game loop
</code></pre>
<p>My question is if there are any other approaches that are simpler in terms of number of characters for a functioning game with the given requirements above? Of course the input/output text to console can be shorter, but I think that doesn't count :)</p>
<p>In terms of readability and PEP 8 style there are of course lots of things to improve, I wanted to keep the code to a reasonable minimum of lines.</p>
<p>I hope this type of question is allowed here, otherwise please remove it.</p>
<p>EDIT: Example game as proposed by user "superb rain" in the comments:</p>
<pre><code>[' ', ' ', ' ']\
[' ', ' ', ' ']\
[' ', ' ', ' ']
Please enter your move (1-9): 5
[' ', ' ', ' ']\
[' ', 'X', ' ']\
[' ', ' ', ' ']
['O', ' ', ' ']\
[' ', 'X', ' ']\
[' ', ' ', ' ']
Please enter your move (1-9): 4
['O', ' ', ' ']\
['X', 'X', ' ']\
[' ', ' ', ' ']
['O', ' ', ' ']\
['X', 'X', 'O']\
[' ', ' ', ' ']
Please enter your move (1-9): 2
['O', 'X', ' ']\
['X', 'X', 'O']\
[' ', ' ', ' ']
['O', 'X', ' ']\
['X', 'X', 'O']\
[' ', 'O', ' ']
Please enter your move (1-9): 3
['O', 'X', 'X']\
['X', 'X', 'O']\
[' ', 'O', ' ']
['O', 'X', 'X']\
['X', 'X', 'O']\
['O', 'O', ' ']
Please enter your move (1-9): 9
['O', 'X', 'X']\
['X', 'X', 'O']\
['O', 'O', 'X']
Game drawn! Do you want to play again (y/n)?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T10:28:12.883",
"Id": "502715",
"Score": "1",
"body": "We cannot really help you in reducing the number of characters needed. That would be code-golfing and is [something we have decided we can not really do here](https://codereview.meta.stackexchange.com/a/949/98493). However, there is our sister site [codegolf.se], which also has a nice [guide on some general tips on golfing Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T10:29:17.777",
"Id": "502716",
"Score": "2",
"body": "I find it hard to review code with one letter variables everywhere. You might want to consider using clear, concise names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:27:16.690",
"Id": "502725",
"Score": "0",
"body": "@theProgrammer, I totally understand, I did it to save on characters to get a measurement of \"minimal\". The commented version is now updated with better naming, sorry if I missed a place or made any typo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:38:33.823",
"Id": "502743",
"Score": "0",
"body": "Please don't update the question after it has been answered, everyone needs to see what the reviewer saw. Please read [What should I do when someone answers?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:30:42.240",
"Id": "502752",
"Score": "0",
"body": "@pacmaninbw, I put an EDIT in there so it should be clear to everyone I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:41:52.567",
"Id": "502757",
"Score": "0",
"body": "Yes, which is why I didn't roll back the edit. Just be advised in the future not to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:26:40.967",
"Id": "502800",
"Score": "0",
"body": "@pacmaninbw, cheers :)"
}
] |
[
{
"body": "<p>Your</p>\n<pre><code>def evaluate(boart, turn):\n for pos in ([0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]):\n if board[pos[0]] == board[pos[1]] == board[pos[2]] == turn: return 1\n</code></pre>\n<p>could be</p>\n<pre><code>def evaluate(boart, turn):\n for i, j, k in [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]:\n if board[i] == board[j] == board[k] == turn: return 1\n</code></pre>\n<p>That is, for indices, single letters <code>i</code>, <code>j</code> and <code>k</code> are common and totally fine. And the tuple doesn't need parentheses.</p>\n<p>You could also define each line with just two values instead of three. Like I did in mine that I wrote a while ago:</p>\n<pre><code>def show():\n for i in range(0, 9, 3):\n print(*board[i : i+3])\n\ndef possible_moves(board):\n return (i for i in range(9) if isinstance(board[i], int))\n\ndef move(board, p, i):\n return board[:i] + [p] + board[i+1:]\n\ndef won(board):\n for i, d in (0, 1), (3, 1), (6, 1), (0, 3), (1, 3), (2, 3), (0, 4), (2, 2):\n if board[i] == board[i + d] == board[i + 2*d]:\n return True\n\ndef value(board, p, q):\n if won(board):\n return -1\n return -min((value(move(board, p, i), q, p)\n for i in possible_moves(board)),\n default=0)\n\ndef best_move():\n return min(possible_moves(board),\n key=lambda i: value(move(board, 'O', i), 'X', 'O'))\n\nboard = list(range(1, 10))\ntry:\n while True:\n show()\n board = move(board, 'X', int(input('your move: ')) - 1)\n if won(board):\n raise Exception('You won!')\n if board.count('X') == 5:\n raise Exception('Draw!')\n board = move(board, 'O', best_move())\n if won(board):\n raise Exception('You lost!')\nexcept Exception as result:\n show()\n print(result)\n</code></pre>\n<p>Demo game:</p>\n<pre><code>1 2 3\n4 5 6\n7 8 9\nyour move: 5\nO 2 3\n4 X 6\n7 8 9\nyour move: 3\nO 2 X\n4 X 6\nO 8 9\nyour move: 4\nO 2 X\nX X O\nO 8 9\nyour move: 8\nO O X\nX X O\nO X 9\nyour move: 9\nO O X\nX X O\nO X X\nDraw!\n</code></pre>\n<p>Like I said I wrote mine a while ago, you just gave me an excuse to dump it here :-). So my program is not "reviewy" regarding yours and it doesn't handle invalid input and doesn't ask for another game (the user can just run the program again), but maybe you'll find something useful in it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:20:12.250",
"Id": "502740",
"Score": "0",
"body": "Thanks, that is nice! I like the simplifications but don't really get your AI move logic, I will have to take a closer look at it tonight :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:29:19.883",
"Id": "502742",
"Score": "0",
"body": "@eligolf Yeah, I guess some documentation would help. I think the lack thereof is one of the reasons I hadn't posted this yet (I had considered making it a question similar to yours). Main thing would be to note that the `value` function returns `-1` if the board is a lost state (because the game is already won, in the last move made), `1` if it's a winning state (you can force a win from there), or `0` if it's a draw state (neither player will win if both play perfectly)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:14:35.993",
"Id": "254890",
"ParentId": "254875",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T06:51:07.793",
"Id": "254875",
"Score": "1",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"game",
"tic-tac-toe"
],
"Title": "Simplest possible Tic Tac Toe AI in Python"
}
|
254875
|
<p>I'm taking CS50 Intro to CS. In this assignment, we're asked to make a program that can identify what type of credit card (AMEX, Visa, MasterCard) is given in the input (and whether it is valid.) Validity is checked using Luhn's Algorithm. Here's how the algorithm works:</p>
<ol>
<li>Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together. (We're not adding the <em>products</em> together, rather the digits of the products!)</li>
<li>Add the sum to the sum of the digits that weren’t multiplied by 2.</li>
<li>If the total’s last digit is 0, the number is valid!</li>
</ol>
<p>Then, the type of credit card is checked by checking the first few digits of the credit card. I.e American Express numbers start with 34 or 37, VISA starts with 4, etc etc. Here's my implementation:</p>
<pre><code>#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <stdlib.h>
bool check_is_card_valid(long card);
int checksum(long card);
bool array_consists(const unsigned int arr[], int val, int arrlen);
string get_card_type(long card);
int get_nth_digit(long card, int digit);
int get_card_length(long card);
const unsigned int accepted_card_length[] =
{
15, // AMEX uses 15 digit numbers
16, // MasterCard and VISA uses 16 digit numbers
13 // VISA uses 13 digit numbers
};
const size_t acc_card_len = sizeof(accepted_card_length) / sizeof(*accepted_card_length);
const unsigned int AMEX_first_digits[] = {34, 37};
const size_t amex_digits_len = sizeof(AMEX_first_digits) / sizeof(*AMEX_first_digits);
const unsigned int MASTERCARD_first_digits[] = {51, 52, 53, 54, 55};
const size_t mc_digits_len = sizeof(MASTERCARD_first_digits) / sizeof(*MASTERCARD_first_digits);
const unsigned int VISA_first_digit = 4;
int main(void)
{
long card_number = get_long("Card number: ");
if (check_is_card_valid(card_number) == true)
{
printf("%s\n", get_card_type(card_number));
}
else
{
printf("INVALID\n");
}
}
/*
Luhn's algorithm. Starting from the right, multiply every other digit by 2 and add up the digits
add this sum to the sum of the digits that were not multiplied by 2.
*/
int checksum(long card)
{
int checksum = 0;
for (int i = 0; i < get_card_length(card); i++)
{
if (i % 2 == 0)
{
checksum += get_nth_digit(card, i);
}
else if (i % 2 == 1)
{
int num = get_nth_digit(card, i) * 2;
if (num > 9)
{
num = get_nth_digit(num, 0) + get_nth_digit(num, 1);
}
checksum += num;
}
}
return checksum;
}
bool array_consists(const unsigned int arr[], int val, int arrlen)
{
for (int i = 0; i < arrlen; i++)
{
if (val == arr[i])
{
return true;
}
}
return false;
}
// Luhn's algorithm states that if the last digit of the checksum is 0, it is valid
bool check_is_card_valid(long card)
{
if (array_consists(accepted_card_length, get_card_length(card), acc_card_len) == true)
{
return checksum(card) % 10 == 0;
}
else
{
return false;
}
}
string get_card_type(long card)
{
int card_length = get_card_length(card);
int first_digit = get_nth_digit(card, card_length - 1);
int second_digit = get_nth_digit(card, card_length - 2);
int first_two_digits = (first_digit * 10) + second_digit;
if (first_digit == VISA_first_digit)
{
return "VISA";
}
else if (array_consists(AMEX_first_digits, first_two_digits, amex_digits_len) == true)
{
return "AMEX";
}
else if (array_consists(MASTERCARD_first_digits, first_two_digits, mc_digits_len) == true)
{
return "MASTERCARD";
}
else
{
return "INVALID";
}
}
// gets nth digit from the right, starting with 0, using modulo
int get_nth_digit(long card, int digit)
{
return fmod(floor(card / pow(10, digit)), 10);
}
int get_card_length(long card)
{
return floor(log10(card)) + 1;
}
</code></pre>
<p>I would like some feedback on my code and how I could improve it; things like style, readability, cleanness, efficiency, etc. Is my code easily understandable? What about the comments - is there not enough comments? I try not to comment on my code when the function of something seems obvious. How do I improve the style, and are there any code conventions I'm not following? Can I optimize this to make it a faster process? Or maybe there's a better way to do the same thing? Basically, how do I improve my code?</p>
|
[] |
[
{
"body": "<p>A simplification would be the following.</p>\n<pre><code>int checksum(long card)\n{\n int checksum = 0;\n for (int i = 0; i < get_card_length(card); i++)\n {\n int digit = get_nth_digit(card, i);\n if (i % 2 == 0)\n {\n checksum += digit;\n }\n else\n {\n int num = digit * 2;\n if (num > 9) // 10, 12, 14, 16, 18\n {\n //num = get_nth_digit(num, 0) + get_nth_digit(num, 1);\n //num = 1 + num - 10;\n num -= 9;\n }\n checksum += num;\n }\n }\n return checksum;\n}\n</code></pre>\n<ul>\n<li>More readable by introducing <code>digit</code>.</li>\n<li><code>else if</code> can become an <code>else</code>. As the values of % operands are non-negative,\nthe result cannot be -1.</li>\n<li><code>get_nth_digit</code> is a kludge, and in fact the final result seems to represent\nmuch more simple semantics.</li>\n</ul>\n<p>The API to check a credit card number uses an intermediate <code>checksum</code>. It "last digit", value % 10, should be 0 for a valid checksum. So the function <code>checksum</code> could be a local "private" function. It is not entirely evident what you put in a .h and what in a .c.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T09:44:08.383",
"Id": "254879",
"ParentId": "254876",
"Score": "0"
}
},
{
"body": "<p>Be very wary of using floating-point for exact integer math. If it isn't wrong (proving it right for all cases is often complicated and error-prone), it is at least inefficient.</p>\n<p>Next, if you must process all digits of a number in order, producing them in order is simple and efficient. Calling code to isolate random digits on demand is inefficient and the cumbersome.</p>\n<p>If you use a signed type for non-negative values, you have to verify the input is non-negative. Better fix the type.</p>\n<p>If you put the definition before the first call-site, you don't need forward-declarations.</p>\n<p>If a function or global is local to the current file, mark it <code>static</code> to enforce it. That simplifies / enables further optimizations due to inlining and avoids inadvertent symbol-clashes.</p>\n<pre><code>static int checksum(unsigned long n) {\n int r = 0;\n while (n) {\n r += n % 10;\n n /= 10;\n r += 2 * (n % 10);\n if (n % 10 > 4) r -= 9;\n n /= 10;\n }\n return r;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-17T13:53:24.797",
"Id": "263146",
"ParentId": "254876",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T08:48:03.193",
"Id": "254876",
"Score": "1",
"Tags": [
"performance",
"beginner",
"c",
"programming-challenge",
"checksum"
],
"Title": "Checking the type and validity of a credit card with Luhn's algorithm in C (CS50)"
}
|
254876
|
<p>I made a method that takes an array and converts it to a matrix, given that it is a valid conversion. However, there is some redundant code in the beginning and I thought maybe you could help me? I am new to programming so avoid complicated imports and such.</p>
<pre><code> private int[][] toMatrix(int[] arr) {
if(validConversion(arr)){
int index = 0;
//redundant
int row = (int) Math.sqrt(arr.length);
int col = (int) Math.sqrt(arr.length);
int[][] matrix = new int[row][col];
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
matrix[i][j] = arr[index];
index++;
}
}
return matrix;
}
return null;
}
boolean validConversion(int[] arr) {
return arr.length == 1 || arr.length % Math.sqrt(arr.length) == 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:18:51.463",
"Id": "502790",
"Score": "3",
"body": "The method name should really be called `toSquareMatrix()`"
}
] |
[
{
"body": "<p>We could evaluate the square root just once:</p>\n<pre><code> int width = (int)Math.sqrt(arr.length);\n if (width * width != arr.length) {\n // not square - invalid\n return null;\n }\n\n int height = width // not really needed, since we know matrix is square\n</code></pre>\n<p>It's not clear why you reject arrays of 0 or 1 elements, so I removed that test.</p>\n<p>We should consider throwing an exception (perhaps <code>InvalidArgumentException</code>?) rather than returning a null object when the test fails.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:07:15.390",
"Id": "254889",
"ParentId": "254882",
"Score": "3"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>private int[][] toMatrix(int[] arr) {\n</code></pre>\n<p>Don't shorten names just because you can.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if(validConversion(arr)){\n</code></pre>\n<p>This does not need to be an extra function, actually, especially if you drop the "1" special case. An array of one item can technically be converted to a matrix with one item...it's just not much of a matrix.</p>\n<pre class=\"lang-java prettyprint-override\"><code>int matrixSize = (int) Math.sqrt(array.length);\n\nif ((array.length % matrizSize) == 0) {\n</code></pre>\n<p>You can also reuse <code>matrixSize</code> now.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(int i = 0; i<row; i++){\n for(int j = 0; j<col; j++){\n</code></pre>\n<p>I'm a very persistent advocate for that you're only allowed to use single-letter variable names when dealing with dimensions. In this case, using <code>column</code> and <code>row</code> would make the code very nicely readable:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int row = 0; row < matrixSize; row++) {\n for (int column = 0; column < matrixSize; column++) {\n matrix[row][column] = array[index];\n index++;\n }\n}\n</code></pre>\n<p><code>index++</code> could be rolled into the assignment:</p>\n<pre class=\"lang-java prettyprint-override\"><code>matrix[row][column] = array[index++];\n</code></pre>\n<p>I'm torn whether that actually improves readability or not, though.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>boolean validConversion(int[] arr) {\n</code></pre>\n<p>Members and functions without an explicit visibility modifier are <code>package-private</code>. In my opinion, <code>package-private</code> should be avoided as it easily can lead to unhealthy couplings between classes in the same package.</p>\n<hr />\n<p>Consider whether you want to perform additional error checks and throw <code>IllegalArgumentException</code>s if they don't add up, for example when the given array is <code>null</code> and so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T07:57:10.513",
"Id": "503645",
"Score": "0",
"body": "An alternative rule (which I follow) for single-character names is that *the larger the scope, the more descriptive the name*. Loop index variables that span 2 or 3 lines ought to be very short, probably a single character. Whereas the function parameter has much greater scope and should be longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:01:30.910",
"Id": "503685",
"Score": "0",
"body": "@TobySpeight My point with that rule is, that every line should be readable on its own, without having to go hunting for definitions (too much). As an example, `performCalculation(i, j)` and `performCalculation(groupIndex, rowIndex)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T07:51:49.227",
"Id": "503735",
"Score": "0",
"body": "I wasn't disagreeing - just a different means to similar ends. I don't go so far as \"a single line on its own\", but a small group of lines (e.g. such as this `for` loop) should be intelligible. Readers can choose what's right for them. Great answer, by the way!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:28:27.707",
"Id": "254912",
"ParentId": "254882",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:45:12.300",
"Id": "254882",
"Score": "3",
"Tags": [
"java",
"array",
"matrix"
],
"Title": "Array To Matrix"
}
|
254882
|
<p>I am relatively new to C++ coming from languages such as Java and would like tips to make my code more C++ like and doing things in the C++ way.</p>
<p>The header file:</p>
<pre><code>#pragma once
#include <string>
#include <memory>
class Expression
{
public:
std::string symbol;
std::shared_ptr<Expression> left;
std::shared_ptr<Expression> right;
float eval();
static Expression parse(std::string s);
private:
Expression(std::string symbol, Expression *left, Expression *right);
static Expression parseRec(std::string s);
static float evalRec(const Expression &e);
};
</code></pre>
<p>cpp file:</p>
<pre><code>#include "Expression.hpp"
#include <unordered_map>
Expression::Expression(std::string symbol, Expression *left, Expression *right)
: symbol(symbol), left(left), right(right) {}
float Expression::eval()
{
return Expression::evalRec(*this);
}
float Expression::evalRec(const Expression &e)
{
switch (e.symbol[0])
{
case '+':
return evalRec(*e.left) + evalRec(*e.right);
case '-':
return evalRec(*e.left) - evalRec(*e.right);
case '*':
return evalRec(*e.left) * evalRec(*e.right);
case '/':
return evalRec(*e.left) / evalRec(*e.right);
default:
return std::stoi(e.symbol);
}
}
Expression Expression::parse(std::string s)
{
//Remove whitespace
std::string output;
for (auto &i : s)
{
if (i != ' ')
output += i;
}
return parseRec(output);
}
Expression Expression::parseRec(std::string s)
{
const std::unordered_map<char, int> precedence = {{'+', 1}, {'-', 1}, {'*', 10}, {'/', 10}};
int indexOfLowest = -1;
int i = 0;
for (auto &&j : s)
{
switch (j)
{
case '+':
case '-':
case '*':
case '/':
if (indexOfLowest == -1)
indexOfLowest = i;
else if (precedence.at(j) <= precedence.at(s[indexOfLowest]))
indexOfLowest = i;
break;
default:
break;
}
i++;
}
if (indexOfLowest == -1)
{
return Expression(s, NULL, NULL);
}
else
{
return Expression(std::string(1, s[indexOfLowest]),
new Expression(parseRec(s.substr(0, indexOfLowest))),
new Expression(parseRec(s.substr(indexOfLowest + 1, s.length() - indexOfLowest - 1))));
}
}
</code></pre>
<p>and a simple main:</p>
<pre><code>#include <iostream>
#include "Expression.hpp"
int main(int argc, char const *argv[])
{
//Parsed expression tree
Expression e = Expression::parse("5 + 10 * 2 + 6 / 3");
std::cout << e.eval() << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:02:13.760",
"Id": "502736",
"Score": "2",
"body": "Welcome to Code Review! Thanks for this great question - I hope you get some good reviews, and I hope to see more of your contributions here in future!"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef EXPRESSION_H\n#define EXPRESSION_H\n// file contents go here\n#endif // EXPRESSION_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"noreferrer\">SF.8</a></p>\n<h2>Consider using standard routines</h2>\n<p>C++ provides a great number of useful utilites such as <a href=\"https://en.cppreference.com/w/cpp/algorithm/remove\" rel=\"noreferrer\"><code>std::remove</code></a> that you could use instead of your own hand-written function to remove whitespace. They're almost always faster and less buggy and by using library software, you can develop your own code more quickly and accurately. So instead of this:</p>\n<pre><code>//Remove whitespace\nstd::string output;\nfor (auto &i : s)\n{\n if (i != ' ')\n output += i;\n}\nreturn parseRec(output);\n</code></pre>\n<p>One could use this:</p>\n<pre><code>s.erase(std::remove(s.begin(), s.end(), ' '), s.end());\nreturn parseRec(s);\n</code></pre>\n<p>Note that this uses <code>s</code> rather than <code>output</code> per the next suggestion.</p>\n<h2>Understand pass-by-value</h2>\n<p>One thing that is quite different about C++ as compared with Java is how parameter passing is done. In general, there is pass-by-value and pass-by-reference. The pass-by-value is what we get when we write things like this:</p>\n<pre><code>static Expression parse(std::string s);\n</code></pre>\n<p>The gives <code>parse</code> <em>its own copy</em> of <code>s</code>. If we use pass-by-reference, it would generally look something like this:</p>\n<pre><code>static Expression parse(const std::string& s);\n</code></pre>\n<p>Now we are giving <code>parse</code> a reference (indicated by <code>&</code>) rather than copying it. In this example, we use the very common idiom of passing a <code>const</code> reference. This indicates that the called function <code>parse</code> may examine but not alter the value. Unlike Java, there is no automatic garbage collector in C++, so it's up to you to manage memory. Generally, passing by reference is faster and uses less memory, but in cases where we would be making a copy anyway, passing by value makes sense.</p>\n<h2>Prefer <code>private</code> to <code>public</code> where practical</h2>\n<p>The <code>Expression</code> class has its only data members as public members. Rather than do it that way, it would be better to keep them private. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-private\" rel=\"noreferrer\">C.9</a> for details.</p>\n<h2>Eliminate redundant functions</h2>\n<p>When a non-static member function is called in a C++ class, <code>*this</code> is implicitly passed. So the result is that this function is entirely useless:</p>\n<pre><code>float Expression::eval()\n{\n return Expression::evalRec(*this);\n}\n</code></pre>\n<p>Instead, just rename <code>evalRec</code> as <code>eval</code> and write it as a member function:</p>\n<pre><code>float Expression::eval()\n{\n switch (symbol[0])\n {\n case '+':\n return left->eval() + right->eval();\n case '-':\n return left->eval() - right->eval();\n case '*':\n return left->eval() * right->eval();\n case '/':\n return left->eval() / right->eval();\n default:\n return std::stoi(symbol);\n }\n}\n</code></pre>\n<h2>Simplify your code by making full use of standard library structures</h2>\n<p>The <code>parseRec</code> routine uses a <code>std::ordered_map</code> and also a <code>switch</code> to find the operator with the lowest precedence. I suggest that when you see that you have repeated the operators in multiple places, this is a hint that perhaps you could use a different approach to avoid this duplication. In this case, my inclination would be to use <a href=\"https://en.cppreference.com/w/cpp/algorithm/min_element\" rel=\"noreferrer\"><code>std::min_element</code></a>. This requires beginning and ending iterators and a comparison operation. First, let's write a comparison operation:</p>\n<pre><code>enum class op_precedence { LOW, MED, NON_OP };\n\nstatic constexpr op_precedence precedence(char ch) {\n op_precedence val{op_precedence::NON_OP};\n switch (ch) {\n case '+':\n case '-':\n val = op_precedence::LOW;\n break;\n case '*':\n case '/':\n val = op_precedence::MED;\n break;\n default:\n break;\n }\n return val;\n}\n</code></pre>\n<p>Now we can use <code>std::min_element</code>:</p>\n<pre><code>std::string::iterator lowest{std::min_element(s.begin(), s.end(), \n [](const char &a, const char &b){\n return precedence(a) < precedence(b); \n })\n};\n</code></pre>\n<p>This uses a <em>lambda</em> to actually effect the comparison. So now the whole function looks like this:</p>\n<pre><code>Expression Expression::parseRec(std::string s) {\n std::string::iterator lowest{std::min_element(s.begin(), s.end(), \n [](const char &a, const char &b){\n return precedence(a) < precedence(b); \n })\n if (precedence(*lowest) == op_precedence::NON_OP) {\n return Expression(s, nullptr, nullptr);\n } else {\n return Expression(std::string(1, *lowest),\n new Expression(parseRec(s.substr(0, lowest-s.begin()))),\n new Expression(parseRec(s.substr(lowest-s.begin() + 1)))\n );\n }\n}\n</code></pre>\n<p>Note, too, that this uses the modern <code>nullptr</code> rather than the old C-style <code>NULL</code>.</p>\n<h2>Dive deeper into C++</h2>\n<p>I know you're just beginning with C++ (and it looks like a promising beginning!) but to whet your appetite for more, we can actually go a little further with the concept mentioned above. Specifically, we have a similar duplication in <code>eval</code>, so we could further consolidate information. Here's one way to do it:</p>\n<pre><code>enum class op_precedence { LOW, MED, NON_OP };\nstruct op {\n op_precedence precedence;\n float (*operation)(float, float);\n};\n\nstatic const std::unordered_map<char, op> operation = {\n { '+', { op_precedence::LOW, [](float a, float b){return a+b;}} },\n { '-', { op_precedence::LOW, [](float a, float b){return a-b;}} },\n { '*', { op_precedence::MED, [](float a, float b){return a*b;}} },\n { '/', { op_precedence::MED, [](float a, float b){return a/b;}} },\n};\n\nstatic op_precedence precedence(char ch) {\n auto myop{operation.find(ch)};\n return myop == operation.end() ? op_precedence::NON_OP : myop->second.precedence;\n}\n</code></pre>\n<p>Now the rest of the program gets shorter and more concise:</p>\n<pre><code>float Expression::eval()\n{\n auto myop{operation.find(symbol[0])};\n if (myop == operation.end()) {\n return std::stoi(symbol);\n }\n return myop->second.operation(left->eval(), right->eval());\n}\n\nExpression Expression::parse(std::string s)\n{\n s.erase(std::remove(s.begin(), s.end(), ' '), s.end());\n return parseRec(s);\n}\n\nExpression Expression::parseRec(std::string s)\n{\n std::string::iterator lowest{std::min_element(s.begin(), s.end(), [](const char &a, const char &b){\n return precedence(a) < precedence(b); })};\n if (precedence(*lowest) == op_precedence::NON_OP)\n {\n return Expression(s, nullptr, nullptr);\n }\n else\n {\n return Expression(std::string(1, *lowest),\n new Expression(parseRec(s.substr(0, lowest-s.begin()))),\n new Expression(parseRec(s.substr(lowest-s.begin() + 1)))\n );\n }\n}\n</code></pre>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>About <code>return 0;</code></h2>\n<p>All compliant compilers will generate the equivalent of <code>return 0</code> at the end of <code>main</code>, so I generally omit that. Others prefer to write it explicitly for stylistic reasons. Whichever you choose, it's useful to know.</p>\n<h2>Use the appropriate smart pointer type</h2>\n<p>The code, as written, abuses <code>std::shared_ptr</code> because no two objects should ever actually share the same <code>Expression</code>. For that reason, what you really should use instead is <code>std::unique_ptr</code>, but that makes things a bit more complex. In particular, we can no longer freely make copies (or they wouldn't be unique!) so we must use C++ <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"noreferrer\"><em>move semantics</em></a>. It's all perhaps a bit much for a beginner, but here's how one would rewrite the relevant portions of the class declaration.</p>\n<pre><code>std::unique_ptr<Expression> left;\nstd::unique_ptr<Expression> right;\nExpression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right);\n</code></pre>\n<p>Now the constructor looks like this:</p>\n<pre><code>Expression::Expression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right)\n : symbol(symbol), left(std::move(left)), right(std::move(right)) {}\n</code></pre>\n<p>And instead of using <code>new</code> (which is rather rare in modern C++), we use <code>std::make_unique</code> instead:</p>\n<pre><code>return Expression(std::string(1, *lowest),\n std::make_unique<Expression>(parseRec(s.substr(0, lowest-s.begin()))),\n std::make_unique<Expression>(parseRec(s.substr(lowest-s.begin() + 1)))\n );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T14:51:21.283",
"Id": "254898",
"ParentId": "254884",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "254898",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T11:51:59.163",
"Id": "254884",
"Score": "10",
"Tags": [
"c++"
],
"Title": "Simple equation parser and evaluator"
}
|
254884
|
<p>Initially I have a code in <code>JavaScript</code> which looks like -</p>
<pre><code>const createUsersInfo = obj => {
const studentDetails = [];
const teacherDetails = [];
obj.forEach(x => {
if (x.type) {
if ( x.type === 'teacher' && x.group !== 'admin' ) {
teacherDetails.push(x);
} else if ( x.type === 'student' && x.group !== 'admin' ) {
studentDetails.push(x);
}
}
});
return {
studentDetails,
teacherDetails
};
};
</code></pre>
<p>Then, I refactored it to -</p>
<pre><code>const createUsersInfo = obj => {
const studentDetails = [];
const teacherDetails = [];
obj.forEach(x => {
const type = x.type;
if ( type && x.group !== 'admin' ) {
if ( type === 'teacher' ) {
teacherDetails.push(x);
}
if ( type === 'student' ) {
studentDetails.push(x);
}
}
});
return {
studentDetails,
teacherDetails
};
};
</code></pre>
<p>Is this better as compared to my initial version or it can further improved ?
Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:45:49.107",
"Id": "502811",
"Score": "0",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If you have a new question, post a new question with a link back to this one instead."
}
] |
[
{
"body": "<p>A short review;</p>\n<ul>\n<li>You can avoid process typeless and admin users by using an upfront <code>.filter()</code></li>\n<li><code>obj</code> is a terrible name (it implies the parameter is just an <code>Object</code> instead of an <code>Array</code>, <code>list</code> would be better, something meaningful like <code>userDetails</code> the best</li>\n<li>If you want to go for slightly less efficient code, you could replace the whole loop with 2 filters</li>\n<li>Dont go for fat arrow syntax unless you are coding and inline function</li>\n</ul>\n<p>I would go for something like this;</p>\n<pre><code>function createUsersInfo(userDetails){\n const cleanUserDetails = userDetails.filter(user => (user.type && user.group != 'admin'));\n return {\n studentDetails: cleanUserDetails.filter(user => user.type === 'student'),\n teacherDetails: cleanUserDetails.filter(user => user.type === 'teacher')\n };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:45:42.820",
"Id": "502795",
"Score": "0",
"body": "Thanks for the inputs. Yes, I totally agree with you on the naming convention side but I believe replacing `forEach` and `if` statements with 3 `filter()` will might impact performance (at least theoritically)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:07:07.230",
"Id": "502797",
"Score": "0",
"body": "I tried an implementation using `reducer()` function, please have a look at it well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:59:14.067",
"Id": "254888",
"ParentId": "254886",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254888",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:39:27.763",
"Id": "254886",
"Score": "1",
"Tags": [
"javascript",
"performance"
],
"Title": "Parse user data in to student and teacher details"
}
|
254886
|
<p>My program applies stacking penalty rule in Daily Fantasy Football by choosing which players to be penalized by which amount of points.</p>
<p>The rule is about penalizing teams with two or more defensive players when the team conceded no goals.</p>
<p>Here is the description of the rule:</p>
<blockquote>
<p>For the 2019/20 football season, there is a new, important rule in place for daily fantasy tournaments: If you pick more than one defensive player (included keeper) from a club, the points awarded for clean sheet will decrease by 1 point for each additional defensive player from the same club. The stacking penalty has a maximum of minus 3 points.</p>
</blockquote>
<blockquote>
<p>1st defensive player: 0 points<br />
2nd defensive player: -1 points<br />
3rd defensive player: -2 points<br />
4th-6th defensive player: -3 points</p>
</blockquote>
<blockquote>
<p>It is actually quite easy; if you have three defensive players from the same club, one will have no stacking penalty (he gets 4 points for clean sheet), one will get minus 1 (so he gets 3 points for a clean sheet), and one will get minus 2 (he gets 2 points for a clean sheet).</p>
</blockquote>
<p><strong>How to choose players to be penalized:</strong></p>
<blockquote>
<p>We rank the players that are on your team. When ranking defensive players from the same club, the priority is:
Captain > Vice Captain > Price > Last name.
For price, the higher price will rank highest. For last name, early position in the alphabet will rank highest.
So, if you have a defensive player as captain he will never get a stacking penalty. If you don’t have a defensive player from this club as captain, but instead as vice captain, he will not get a stacking penalty. If there is no captain or vice captain in defense, the highest priced player will be 1st defensive player, and won’t get a stacking penalty.</p>
</blockquote>
<p>Please note, that I didn't handle the case of players having the same pursuit points and tie-breaker being last name since it doesn't come up in practice.</p>
<p>I would like to get feedback on my way of decomposing this problem and how to reduce highly repetitive functions that work with particular amount of defensive players to more general one.</p>
<p>Here is the code:</p>
<pre><code>"""
Applying stacking penalty rule to a team in Fantasy Football.
"""
from dataclasses import dataclass
from typing import List, Tuple
@dataclass
class Player:
"""
Represents a player in Fantasy Football with his id, name, club,
playing position, pursuit points and whether he is the captain
or vice-captain.
"""
p_id: int
name: str
club: str
position: str
pursuit: float
is_captain: bool = False
is_vice_captain: bool = False
PlayerId = int
PenalizedPlayer = Tuple[PlayerId, int]
PenalizedPlayers = List[PenalizedPlayer]
Team = List[Player]
players = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88),
Player(160699, "Mari", "ARS", "defender", -0.52),
Player(139989, "Tierney", "ARS", "defender", -0.72),
Player(24075, "Holding", "ARS", "defender", -0.60),
Player(23332, "Bellerin", "ARS", "defender", -0.76),
Player(197966, "Smith Rowe", "ARS", "midfielder", -1.24),
Player(137793, "Ceballos", "ARS", "midfielder", -1.08),
Player(106430, "Saka", "ARS", "midfielder", -1.72),
Player(23337, "Xhaka", "ARS", "midfielder", -0.84),
Player(77663, "Aubameyang", "ARS", "forward", -1.88),
Player(45079, "Lacazette", "ARS", "forward", -2.00),
]
team1 = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88, is_captain=True),
Player(139989, "Tierney", "ARS", "defender", -0.72),
Player(24075, "Holding", "ARS", "defender", -0.60),
Player(77663, "Aubameyang", "ARS", "forward", -1.88),
Player(45079, "Lacazette", "ARS", "forward", -2.00, is_vice_captain=True)
]
team2 = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88),
Player(139989, "Tierney", "ARS", "defender", -0.72),
Player(24075, "Holding", "ARS", "defender", -0.60, is_captain=True),
Player(77663, "Aubameyang", "ARS", "forward", -1.88),
Player(45079, "Lacazette", "ARS", "forward", -2.00, is_vice_captain=True)
]
team3 = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88),
Player(139989, "Tierney", "ARS", "defender", -0.72, is_vice_captain=True),
Player(24075, "Holding", "ARS", "defender", -0.60, is_captain=True),
Player(77663, "Aubameyang", "ARS", "forward", -1.88),
Player(45079, "Lacazette", "ARS", "forward", -2.00)
]
team4 = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88),
Player(139989, "Tierney", "ARS", "defender", -0.72, is_captain=True),
Player(24075, "Holding", "ARS", "defender", -0.60),
Player(160699, "Mari", "ARS", "defender", -0.52),
Player(106430, "Saka", "ARS", "midfielder", -1.72, is_vice_captain=True)
]
team5 = [
Player(88472, "Leno", "ARS", "goalkeeper", -0.88, is_captain=True),
Player(160699, "Mari", "ARS", "defender", -0.52, is_vice_captain=True),
Player(139989, "Tierney", "ARS", "defender", -0.72),
Player(24075, "Holding", "ARS", "defender", -0.60),
Player(23332, "Bellerin", "ARS", "defender", -0.76)
]
team6 = [
Player(139989, "Tierney", "ARS", "defender", -0.72),
Player(137793, "Ceballos", "ARS", "midfielder", -1.08),
Player(106430, "Saka", "ARS", "midfielder", -1.72),
Player(23337, "Xhaka", "ARS", "midfielder", -0.84),
Player(77663, "Aubameyang", "ARS", "forward", -1.88, is_captain=True),
Player(45079, "Lacazette", "ARS", "forward", -2.00, is_vice_captain=True)
]
team7 = [
Player(24075, "Holding", "ARS", "defender", -0.60),
Player(23332, "Bellerin", "ARS", "defender", -0.76),
Player(197966, "Smith Rowe", "ARS", "midfielder", -1.24, is_vice_captain=True),
Player(137793, "Ceballos", "ARS", "midfielder", -1.08, is_captain=True),
Player(106430, "Saka", "ARS", "midfielder", -1.72),
]
team8 = [
Player(24075, "Holding", "ARS", "defender", -0.60, is_vice_captain=True),
Player(23332, "Bellerin", "ARS", "defender", -0.76),
Player(197966, "Smith Rowe", "ARS", "midfielder", -1.24),
Player(137793, "Ceballos", "ARS", "midfielder", -1.08),
Player(106430, "Saka", "ARS", "midfielder", -1.72, is_captain=True),
]
def choose_players_to_penalize(team: Team) -> PenalizedPlayers:
"""
Returns list of tuples with players ids to be penalised and amount of
points to be taken away from each of them.
Raises ValueError if defensive players count is greater than 5.
"""
defensive_players = get_defensive_players(team)
if len(defensive_players) < 2:
return []
if len(defensive_players) == 2:
return penalize_two_players(defensive_players)
if len(defensive_players) == 3:
return penalize_three_players(defensive_players)
if len(defensive_players) == 4:
return penalize_four_players(defensive_players)
if len(defensive_players) == 5:
return penalize_five_players(defensive_players)
raise ValueError("There can't be more than 5 defensive players")
def penalize_two_players(players: Team) -> PenalizedPlayers:
"""
Chooses players ids to be penalised and amount of points to be taken away
from a team with two defensive players.
"""
sorted_players = sort_player_ids_for_penalty(players)
return [(sorted_players[1], -1)]
def penalize_three_players(players: Team) -> PenalizedPlayers:
"""
Chooses players ids to be penalised and amount of points to be taken away
from a team with three defensive players.
"""
sorted_players = sort_player_ids_for_penalty(players)
return [(sorted_players[-1], -2),
(sorted_players[-2], -1)]
def penalize_four_players(players: Team) -> PenalizedPlayers:
"""
Chooses players ids to be penalised and amount of points to be taken away
for a team with four defensive players.
"""
sorted_players = sort_player_ids_for_penalty(players)
return [(sorted_players[-1], -3),
(sorted_players[-2], -2),
(sorted_players[-3], -1)]
def penalize_five_players(players: Team) -> PenalizedPlayers:
"""
Chooses players ids to be penalised and amount of points to be taken away
for a team with five defensive players.
"""
sorted_players = sort_player_ids_for_penalty(players)
return [(sorted_players[-1], -3),
(sorted_players[-2], -3),
(sorted_players[-3], -2),
(sorted_players[-4], -1)]
def sort_player_ids_for_penalty(players: Team) -> List[PlayerId]:
"""
Returns list of players ids sorted in reverse order by the following criterias:
- is_captain
- is_vice_captain
- more expensive players by pursuit points
(more "expensive" means smaller value, for example, a player with
pursuit points -0.72 is more expensive than a player with pursuit
points +1.24, so that when sorting pursuits are taken multiplied by -1)
"""
return [p.p_id for p in sorted(players, key=lambda x:
(x.is_captain, x.is_vice_captain,
-x.pursuit), reverse=True)]
def get_defensive_players(players: Team) -> Team:
"""
Returns each player in the team whose position is either defender
or goalkeeper.
"""
return [p for p in players if p.position in ['goalkeeper', 'defender']]
def tests():
"""
Tests for choose_players_to_penalize()
"""
assert sorted(choose_players_to_penalize(team1)) == sorted([(24075, -2),
(139989, -1)])
assert sorted(choose_players_to_penalize(team2)) == sorted([(139989, -2),
(88472, -1)])
assert sorted(choose_players_to_penalize(team3)) == sorted([(88472, -2),
(139989, -1)])
assert sorted(choose_players_to_penalize(team4)) == sorted([(160699, -3),
(24075, -2),
(88472, -1)])
assert sorted(choose_players_to_penalize(team5)) == sorted([(24075, -3),
(139989, -3),
(23332, -2),
(160699, -1)])
assert choose_players_to_penalize(team6) == []
assert choose_players_to_penalize(team7) == [(24075, -1)]
assert choose_players_to_penalize(team8) == [(23332, -1)]
print("Tests pass.")
if __name__ == '__main__':
tests()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:21:26.463",
"Id": "503003",
"Score": "0",
"body": "What if a fantasy team has 2 defensive players from team A and 2 defensive players from team B?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:22:59.147",
"Id": "503005",
"Score": "0",
"body": "Each team is penalized separately: a player from team A will get -1 as well as player from team B."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:32:13.170",
"Id": "503008",
"Score": "0",
"body": "That's what I thought, but I don't think your code handles that case, nor are there tests for it. Aghast's answer should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:37:42.503",
"Id": "503010",
"Score": "0",
"body": "I posted this to handle the case with players from one team and then made a version handling players from arbitrary amount of teams. I'm afraid it is not appropriate to change the code."
}
] |
[
{
"body": "<p>You’re right that you can shorten the penalization functions into a single general function. You can do it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def choose_players_to_penalize(team: Team) -> PenalizedPlayers:\n """\n Returns list of tuples with players ids to be penalised and amount of\n points to be taken away from each of them.\n\n Raises ValueError if defensive players count is greater than 5.\n """\n defensive_players = get_defensive_players(team)\n return penalize_players(defensive_players)\n\ndef penalize_players(players: Team) -> PenalizedPlayers:\n """\n Chooses players ids to be penalised and amount of points to be taken away\n from a team with n defensive players.\n """\n sorted_players = sort_player_ids_for_penalty(players)\n list_len = len(sorted_players)\n if list_len > 5:\n raise ValueError("There can't be more than 5 defensive players")\n return [\n (sorted_players[-n], max(-3, -list_len + n))\n for n in range(1, list_len)\n ]\n</code></pre>\n<p>The choose_players_to_penalize function might not be needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T20:47:59.797",
"Id": "254923",
"ParentId": "254892",
"Score": "2"
}
},
{
"body": "<p>I will start by saying that I have no understanding of Daily Fantasy Football. Forgive me if I miss some important point.</p>\n<p>If I understand your rules quote correctly, individual players are subjected to the "stacking penalties". So this doesn't just reduce some arbitrary total score, but affects how each player is scored individually.</p>\n<p>Thus, you need to write a sorting function that matches the ordering they describe, so that you will identify the <em>same players</em> in the <em>same relative order</em> for the penalties.</p>\n<p>Also, the question of which defenders to penalize also requires attention to the club the defenders play for. If you have 4 defensive players, from clubs A, B, C, and D, then none of the players will be penalized. If you have 4 defensive players all from club ARS, then the first one gets no penalty, the second one gets 4-1=3 points, the third one gets 4-2=2 points, and the last one gets 4-3=1 point. Finally, if you have 4 defensive players, 2 from club A and 2 from club B, then the second player from each club will get 4-1=3 points.</p>\n<p>As I see it, you can solve this problem by sorting the players on the <code>club</code> as a first key. Then within the club, sort using the criteria described in the rule citation.</p>\n<p>Once you have the players in this order, use the <a href=\"https://docs.python.org/3/library/itertools.html?highlight=itertools%20groupby#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> function to bundle players with the same club together, and process the bundles.</p>\n<p>I think this function works as your key:</p>\n<pre><code>def defensive_player_key(p):\n """ Group players by club. Within the same club, \n order according to "stacking penalty" rule. \n """\n return (p.club, \n not p.is_captain, # NOTE: not() to reverse sort order\n not p.is_vice_captain, # NOTE: not() to reverse sort order\n -p.pursuit, # NOTE: negative to reverse sort order\n p.name)\n</code></pre>\n<p>Assuming that your "pursuit points" is the same as "price" in the rule citation. So you can write something like:</p>\n<pre><code>defenders = sorted([p for p in team where p.position in ("defender", "goalkeeper")], key=defensive_player_key)\n\nfor club, mates in itertools.groupby(defenders, key=lambda p: p.club):\n for player, order in enumerate(mates):\n penalty = min(order, 3) # 0, 1, 2, 3, 3, 3\n\n # TODO: do something with player, penalty\n</code></pre>\n<p>I understand this happens in a "clean sheet" scenario, but have no idea what that is. Presumably you would award <code>4 - penalty</code> points to each of the defenders, somehow?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T15:38:21.617",
"Id": "502966",
"Score": "0",
"body": "Apparently you get the rules right. Clean sheet means that a team conceded no goals. Assume that the function is called only in this scenario. Does your solution pass my tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:18:00.080",
"Id": "503002",
"Score": "1",
"body": "`False` sorts before `True`, so I think you need to change the sort to use `not p.is_captain` and `not p.is_vice_captain`. Otherwise, they will come out last when you `enumerate(mates)` ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T01:07:26.327",
"Id": "503025",
"Score": "0",
"body": "@RootTwo updated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T14:44:15.520",
"Id": "255000",
"ParentId": "254892",
"Score": "4"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/254923/200133\">my_first_c_program's answer</a> is good and directly addresses your question. I'm just adding minor points and details about the rest of your implementation. (like doing the daily crossword ☺)</p>\n<ul>\n<li>Rather than a lambda, make the ordering key a method of the Player class. I <em>don't</em> suggest making it the innate ordering of <code>Player</code> though.</li>\n<li>It's not clear why you skipped the last-name tie-breaker, except possibly for the fact that parsing names can be tricky in the real world.</li>\n<li>In general, dataclasses should be <code>frozen</code> (immutable) unless you need mutability; it's just a good habit that will help you catch mistakes. (I guess it's only fair to warn that if you change it later to make it mutable, you'll have problems with equality/hashes/sets.)</li>\n<li>It seems like the captain, vice-captain, and number of players are strict requirements for a <code>Team</code>. Probably good to make <code>Team</code> another data-class, with "who's the captain" stored there instead of in each <code>Player</code>.\n<ul>\n<li><s>Of course this will mean that <code>Player</code>s can't generate their own ordering anymore; that's ok it can be a <code>Team</code> method.</s></li>\n<li>Actually just leave the ordering as a stand-alone method, but enforce the "captains first" part structurally instead of as part of the ordering-key.</li>\n</ul>\n</li>\n<li>Depending on your python-version <code>Player.position</code> could be a <code>Literal[...]</code> (like an enum).</li>\n<li>Make the defensiveness test a <code>Player</code> method/property.</li>\n<li>Inline sanity checks can use <code>assert</code>, just be aware that <a href=\"https://docs.python.org/3/using/cmdline.html#cmdoption-o\" rel=\"nofollow noreferrer\">asserts can be bypassed</a>.</li>\n<li>Get your test data out of the top-level namespace. You may also want to restructure the tests somewhat:\n<ul>\n<li>You're not using the variable <code>players</code>, but in fact you could and it would save you some verbosity if it were a dict of some kind.</li>\n<li>Just use a loop over team-result pairs for the assertions.</li>\n<li>Catch-and-rethrow to give the context for a failed test.</li>\n</ul>\n</li>\n<li>The logic for the possible penalty values is pretty trivial, but it's also suspiciously arbitrary; for this reason I'd suggest making it its own function.</li>\n<li>It seems weird for the function to return player identifiers instead of just players. On the other hand, it's not perfectly clear to me what identifier means what; if <code>p_id</code> is really the ID, then <code>Player</code> equality should be based on just that. I don't have enough context to say exactly how that should work...</li>\n<li>On the other hand, <em>where</em> are these penalties going? Are they properties of the respective players? Of the team? Should we bake them into the type system? That could get tricky, but fun...</li>\n<li>There's always room for better names.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>"""\nApplying stacking penalty rule to a team in Fantasy Football.\n"""\nfrom dataclasses import asdict, dataclass\nfrom typing import Iterable, Literal, Mapping, Tuple\nfrom itertools import chain\n\nPlayerId = int\n# Literal is new in 3.8:\nPosition = Literal["goalkeeper", "defender", "midfielder", "forward"]\n\n@dataclass(frozen=True)\nclass Player:\n p_id: PlayerId\n name: str\n club: str\n position: Position\n pursuit: float\n\n def is_defensive(self):\n return self.position in ['goalkeeper', 'defender'] \n\n@dataclass(frozen=True)\nclass PenalizedPlayer(Player):\n penalty: int\n\ndef defence_stacking_penalty(index: int) -> int:\n return min(0, max(-3, -index))\n\ndef stacking_penalty_order(\n captain: Player, vice: Player, *others: Player\n) -> Iterable[Player]:\n yield captain\n yield vice\n def key(player):\n last_name = player.name.split(maxsplit=1)[-1]\n return (-player.pursuit, last_name)\n yield from sorted(others, key=key, reverse=True)\n\ndef assign_defence_stacking_penalties(\n captain: Player, vice: Player, *others: Player\n)-> Mapping[Player, PenalizedPlayer]:\n sorted_defence = [player\n for player\n in stacking_penalty_order(captain, vice, *others)\n if player.is_defensive()]\n assert len(sorted_defence) <= 5, "There can't be more than 5 defensive players."\n non_defence_pairs = ((0, player)\n for player\n in (captain, vice, *others)\n if not player.is_defensive())\n return {\n player: PenalizedPlayer(penalty=defence_stacking_penalty(i),\n **asdict(player))\n for (i, player) # This isn't great, in that i could be the index from enumerate or the literal 0 from non_defence_pairs.\n in chain(enumerate(sorted_defence), non_defence_pairs)\n }\n\n@dataclass(frozen=True)\nclass Team:\n captain: PenalizedPlayer\n vice_captain: PenalizedPlayer\n others: Tuple[PenalizedPlayer, ...]\n \n def __iter__(self):\n yield self.captain\n yield self.vice_captain\n yield from self.others\n\n def __post_init__(self): # enforce uniqueness and sufficiency\n unique = len(set(self))\n assert len(tuple(self)) == unique\n assert 5 <= unique\n\n @staticmethod\n def make(*others: Player, captain: Player, vice: Player) -> "Team":\n """Wrap the init for convienence. Force kwargs for explicitness."""\n penalized = assign_defence_stacking_penalties(captain, vice, *others)\n return Team(captain=penalized[captain],\n vice_captain=penalized[vice],\n others=tuple(penalized[player] for player in others))\n\ndef tests():\n players = {\n player.p_id: player # the below team declarations might read better if we used name as the key...\n for player in (\n Player(88472, "Leno", "ARS", "goalkeeper", -0.88),\n Player(160699, "Mari", "ARS", "defender", -0.52),\n Player(139989, "Tierney", "ARS", "defender", -0.72),\n Player(24075, "Holding", "ARS", "defender", -0.60),\n Player(23332, "Bellerin", "ARS", "defender", -0.76),\n Player(197966, "Smith Rowe", "ARS", "midfielder", -1.24),\n Player(137793, "Ceballos", "ARS", "midfielder", -1.08),\n Player(106430, "Saka", "ARS", "midfielder", -1.72),\n Player(23337, "Xhaka", "ARS", "midfielder", -0.84),\n Player(77663, "Aubameyang", "ARS", "forward", -1.88),\n Player(45079, "Lacazette", "ARS", "forward", -2.00),\n )\n }\n\n tests = [\n (Team.make(players[139989], players[24075], players[77663],\n captain=players[88472], vice=players[45079]),\n [(24075, -2), (139989, -1)]),\n (Team.make(players[88472], players[139989], players[77663],\n captain=players[24075], vice=players[45079]),\n [(139989, -2), (88472, -1)]),\n (Team.make(players[88472], players[77663], players[45079],\n captain=players[24075], vice=players[139989]),\n [(88472, -2), (139989, -1)]),\n (Team.make(players[88472], players[24075], players[160699],\n captain=players[139989], vice=players[106430]),\n [(160699, -3), (24075, -2), (88472, -1)]),\n (Team.make(players[139989], players[24075], players[23332],\n captain=players[88472], vice=players[160699]),\n [(24075, -3), (139989, -3), (23332, -2), (160699, -1)]),\n (Team.make(players[139989], players[137793], players[106430], players[23337],\n captain=players[77663], vice=players[45079]),\n []),\n (Team.make(players[24075], players[23332], players[106430], \n captain=players[137793], vice=players[197966]),\n [(24075, -1)]),\n (Team.make(players[23332], players[197966], players[137793], \n captain=players[106430], vice=players[24075]),\n [(23332, -1)]),\n ]\n\n for (team, known_result) in tests:\n try:\n result = sorted((player.p_id, player.penalty)\n for player in team\n if player.penalty)\n assert result == sorted(known_result)\n except:\n print(team)\n print(known_result)\n print(result) # concievable that some errors might cause this to presist from a prior loop iteration\n raise\n \n print("Tests pass.")\n \nif __name__ == '__main__':\n tests()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:46:51.280",
"Id": "255027",
"ParentId": "254892",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255027",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:21:38.150",
"Id": "254892",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Applying stacking penalty rule in Daily Fantasy Football"
}
|
254892
|
<p>Assume we are given <span class="math-container">\$ n \$</span> natural numbers, <span class="math-container">\$a_{1}, a_{2}, \dots, a_{n} \$</span> and we are supposed to calculate the following summation:</p>
<p><span class="math-container">\$ \sum_{i = 1}^{n}\sum_{j = 1}^{n} \left\lfloor \dfrac{a_{i}}{a_{j}} \right\rfloor\$</span>.</p>
<p>This is a question from a challenge and in only one test, I get time-limit exceeded error.</p>
<p>Can my code become faster?</p>
<p><a href="https://quera.ir/problemset/contest/62455/" rel="nofollow noreferrer">Here</a>'s the question and my code is as follows:</p>
<pre><code>from collections import Counter
numbers = sorted(Counter(int(i) for i in input().split()).items())
sigma = 0
for i in range(len(numbers)):
for j in range(i, len(numbers)):
sigma += (numbers[j][0] // numbers[i][0]) * numbers[j][1] * numbers[i][1]
print(sigma)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:55:56.490",
"Id": "502758",
"Score": "0",
"body": "What's with the sorted Counter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:09:07.580",
"Id": "502763",
"Score": "0",
"body": "@TedBrownlow I didn't understand your question...what do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:13:28.383",
"Id": "502764",
"Score": "0",
"body": "I don't understand what you're using Counter for here. `numbers=[int(number) for number in input.split()]` should be sufficient unless I'm missing something"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:18:16.730",
"Id": "502766",
"Score": "0",
"body": "@TedBrownlow I want to count how many same elements exist. For example if you have 4 1's and 10 2's, the summation will be \\$ 4 \\times 10 \\times 2 \\$ which is much faster than summing one by one all the floors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:34:07.593",
"Id": "502793",
"Score": "0",
"body": "Please include the link to the challenge. How large can n be?"
}
] |
[
{
"body": "<p>Indexing in Python is relatively slow. If you have several thousand numbers, you are looking up <code>number[i][0]</code>, and <code>number[i][1]</code> repeatedly in the <code>j</code> loop, despite those values being unchanged:</p>\n<p>You should find the following reworked code to be faster:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nnumbers = sorted(Counter(int(i) for i in input().split()).items())\n\nsigma = 0\nfor i in range(len(numbers)):\n a_i, a_i_count = numbers[i]\n for j in range(i, len(numbers)):\n sigma += (numbers[j][0] // a_i) * numbers[j][1] * a_i_count\n\nprint(sigma)\n</code></pre>\n<p>Not only is it faster, it is also clearer. It takes a lot of reasoning to determine <code>numbers[i][0]</code> is a count of the number of occurrences of <code>numbers[i][0]</code>, where as the reader will have an easier time understanding <code>a_i_count</code> as the number of occurrences of <code>a_i</code>, and can even see <code>a_i</code> in the question text.</p>\n<p>We can even remove the indexing of <code>numbers[i]</code>, to speed things up slightly more:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nnumbers = sorted(Counter(int(i) for i in input().split()).items())\n\nsigma = 0\nfor i, (a_i, a_i_count) in enumerate(numbers):\n for j in range(i, len(numbers)):\n sigma += (numbers[j][0] // a_i) * numbers[j][1] * a_i_count\n\nprint(sigma)\n</code></pre>\n<p>Can we do the same thing in the second loop? Conditionally yes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nnumbers = sorted(Counter(int(i) for i in input().split()).items())\n\nsigma = 0\nfor i, (a_i, a_i_count) in enumerate(numbers):\n for a_j, a_j_count in numbers[i:]:\n sigma += (a_j // a_i) * a_j_count * a_i_count\n\nprint(sigma)\n</code></pre>\n<p>It looks cleaner, but is it faster? The problem is <code>numbers[i:]</code>, which will copy the data as it realizes the values. This copy takes time, and increases the memory footprint. What you want is just an iterator over the slice, without generating copies of the data. For that, we need to use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nfrom itertools import islice\n\nnumbers = sorted(Counter(int(i) for i in input().split()).items())\n\nsigma = 0\nfor i, (a_i, a_i_count) in enumerate(numbers):\n for a_j, a_j_count in islice(numbers, i, None):\n sigma += (a_j // a_i) * a_j_count * a_i_count\n\nprint(sigma)\n</code></pre>\n<p>Lastly, we can ask Python to perform the summing for us:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nfrom itertools import islice\n\nnumbers = sorted(Counter(int(i) for i in input().split()).items())\n\nsigma = sum((a_j // a_i) * a_j_count * a_i_count\n for i, (a_i, a_i_count) in enumerate(numbers)\n for a_j, a_j_count in islice(numbers, i, None))\n\nprint(sigma)\n</code></pre>\n<p><strong>Note</strong>: <code>//</code> has the same precedence as <code>*</code>, so parenthesis are unnecessary in the <code>(a_j // a_i) * a_j_count * a_i_count</code> expression.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:27:25.840",
"Id": "502791",
"Score": "0",
"body": "Except `islice(numbers, i, None)` does *not* just iterate over the slice but over the entire list (it just doesn't pass on the first `i` elements to its consumer). See a [benchmark](https://preview.tinyurl.com/y6jwvwqz) where it's *slower*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:33:09.417",
"Id": "502792",
"Score": "0",
"body": "Even `islice(a, i)` is appears to be [slower](https://preview.tinyurl.com/y5qekpll) than `a[:i]`. The extra layer of iteration does cost extra time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:40:21.773",
"Id": "502794",
"Score": "1",
"body": "Benchmarks of your various solutions would be good. And maybe `itertools.combinations_with_replacement` would really be the proper tool here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:55:55.533",
"Id": "502796",
"Score": "0",
"body": "@KellyBundy Maybe you are right. The only time-limit-exceded test hasn't been handled yet. The link of challenge has been included in my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:29:47.240",
"Id": "502802",
"Score": "0",
"body": "@MohammadAliNematollahi Since n can be as large as 100,000, you might need something better than quadratic time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:37:55.343",
"Id": "502882",
"Score": "0",
"body": "As expected from my pure-iteration test, `islice` also makes the solution to the problem *slower*. See benchmarks in my new answer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:46:10.670",
"Id": "254916",
"ParentId": "254895",
"Score": "1"
}
},
{
"body": "<p>Your approach takes <span class=\"math-container\">\\$O(n^2)\\$</span> time. Since n can be as large as 100,000, you'll likely need something better. Some benchmarks (inputs are the numbers 1 to n shuffled, and the table shows times in seconds):</p>\n<pre><code> n | original AJNeufeld AJ_no_islice Kelly_Bundy \n-------+------------------------------------------------\n 1000 | 0.12 0.07 0.06 0.07 \n 10000 | 11.92 7.98 7.23 0.09 \n 20000 | 50.82 32.83 29.79 0.11 \n100000 | - - - 0.18 \n</code></pre>\n<p>I didn't run the first three solutions on n=100000, they're too slow. <code>AJ_no_islice</code> is the same as <code>AJNeufeld</code>, except with a regular slice instead of <code>islice</code> to demonstrate that <code>islice</code> is <em>not</em> faster but slower.</p>\n<p>My solution in a function that takes a list of numbers and returns the result (much better for testing, and for clarity):</p>\n<pre><code>def solve(numbers):\n incs = [0] * 100001\n for numerator, freq in Counter(numbers).items():\n for multiple in range(numerator, 100001, numerator):\n incs[multiple] += freq\n incs = list(accumulate(incs))\n return sum(incs[denominator] for denominator in numbers)\n</code></pre>\n<p>It's similar to the sieve of Eratosthenes, though I mark multiples of all numbers, not just of primes. Runtime is O(n log n).</p>\n<p>Consider some numerator, let's say 3. Then for every denominator 3 or higher, it contributes 1 to the total. For every denominator 6 or higher, it contributes 2 to the total. And so on. As a table:</p>\n<p><code>incs = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, ...]</code></p>\n<p>So if you then consider some <em>denominator</em>, let's say 7, you simply look up <code>incs[7]</code> to see that it contributes 2 to the total (with the numerator 3).</p>\n<p>Now instead consider some other numerator, let's say 4. Its table is:</p>\n<p><code>incs = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, ...]</code></p>\n<p>Together for numerators 3 and 4:</p>\n<p><code>incs = [0, 0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 5, 7, 7, 7, 8, 9, 9, ...]</code></p>\n<p>How to efficiently compute that table? First only mark the increment spots, e.g., for denominator 3:</p>\n<p><code>incs = [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, ...]</code></p>\n<p>And for denominators 3 and 4 together:</p>\n<p><code>incs = [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 1, 0, 1, 0]</code></p>\n<p>And then just accumulate the prefix sums.</p>\n<p>Full benchmark code (includes correctness checking):</p>\n<pre><code>from timeit import repeat\nfrom random import choices, shuffle\nfrom collections import Counter\nfrom itertools import islice\nfrom itertools import accumulate\n\ndef original(numbers):\n numbers = sorted(Counter(numbers).items())\n sigma = 0\n for i in range(len(numbers)):\n for j in range(i, len(numbers)):\n sigma += (numbers[j][0] // numbers[i][0]) * numbers[j][1] * numbers[i][1]\n return sigma\n\ndef AJNeufeld(numbers):\n numbers = sorted(Counter(numbers).items())\n sigma = sum((a_j // a_i) * a_j_count * a_i_count\n for i, (a_i, a_i_count) in enumerate(numbers)\n for a_j, a_j_count in islice(numbers, i, None))\n return sigma\n\ndef AJ_no_islice(numbers):\n numbers = sorted(Counter(numbers).items())\n sigma = sum((a_j // a_i) * a_j_count * a_i_count\n for i, (a_i, a_i_count) in enumerate(numbers)\n for a_j, a_j_count in numbers[i:])\n return sigma\n\ndef Kelly_Bundy(numbers):\n incs = [0] * 100001\n for numerator, freq in Counter(numbers).items():\n for multiple in range(numerator, 100001, numerator):\n incs[multiple] += freq\n incs = list(accumulate(incs))\n return sum(incs[denominator] for denominator in numbers)\n\nfuncs = original, AJNeufeld, AJ_no_islice, Kelly_Bundy\n\n# Correctness\nnumbers = choices(range(1, 100001), k=1000)\nexpect = funcs[0](numbers)\nfor func in funcs:\n result = func(numbers)\n print(result == expect, func.__name__,)\nprint()\n\n# Speed\nnames = [f' {func.__name__} ' for func in funcs]\nprint(' n |' + ''.join(names))\nprint('-------+' + '-' * sum(map(len, names)))\nfor n in 1000, 10000, 20000, 100000:\n print(f'{n:6} |', end='')\n numbers = list(range(1, n+1))\n shuffle(numbers)\n for func in funcs:\n if n <= 20000 or func is Kelly_Bundy:\n t = min(repeat(lambda: func(numbers), number=1, repeat=1))\n t = '%.2f' % t\n else:\n t = '-'\n print(f'{t:>{len(func.__name__)-1}} ', end='')\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:16:55.930",
"Id": "502885",
"Score": "0",
"body": "Now the output of your function is wrong..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:19:37.000",
"Id": "502886",
"Score": "0",
"body": "@MohammadAliNematollahi I doubt that. For what input? Note that it computes the same as yours in my correctness check, which I'd expect to catch mistakes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:22:52.587",
"Id": "502887",
"Score": "0",
"body": "Now it's correct... I think you made some edits... Thank you. It passed all the tests... I learned a lot here..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:24:43.060",
"Id": "502888",
"Score": "0",
"body": "@MohammadAliNematollahi Ok... yeah I did make some edits, but only renaming variables, not affecting the results. Oh well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:36:30.687",
"Id": "254949",
"ParentId": "254895",
"Score": "3"
}
},
{
"body": "<p>Not competing with @KellyBundy's linearithmic solution, but optimizing the quadratic approach:</p>\n<pre><code> n | original AJ_no_islice superb_rain superb_rain_2 \n-------+----------------------------------------------------\n 1000 | 0.13 0.07 0.05 0.04 \n 10000 | 13.65 8.02 4.66 6.15 \n 20000 | 60.31 35.07 19.16 25.86 \n</code></pre>\n<p>Code for the fastest one (<code>superb_rain</code>):</p>\n<pre><code>def solve(numbers):\n sigma = 0\n counted = []\n for a_j, a_j_count in sorted(Counter(numbers).items()):\n sigma += a_j_count * sum([(a_j // a_i) * a_i_count\n for a_i, a_i_count in counted],\n a_j_count)\n counted.append((a_j, a_j_count))\n return sigma\n</code></pre>\n<p>Things that make it faster:</p>\n<ul>\n<li>Inner iteration directly over the list <code>counted</code> instead of a slice or <code>islice</code>. An <code>append</code> is cheaper than those.</li>\n<li>List comprehension instead of generator.</li>\n<li>Taking the multiplication with <code>a_j_count</code> out of the sum.</li>\n<li>Combine <span class=\"math-container\">\\$a_j\\$</span> with itself not with <code>(a_j // a_j) * a_j_count</code> but by initializing <code>sum</code> with <code>a_j_count</code>).</li>\n</ul>\n<p>My <code>superb_rain_2</code> is the same, but instead of building another list, it shrinks the one from <code>sorted</code>. I thought it might be faster, but oddly it's significantly slower.</p>\n<p>Benchmark code (mostly @KellyBundy's):</p>\n<pre><code>from timeit import repeat\nfrom random import choices, shuffle\nfrom collections import Counter\nfrom itertools import islice\nfrom itertools import accumulate\n\ndef original(numbers):\n numbers = sorted(Counter(numbers).items())\n sigma = 0\n for i in range(len(numbers)):\n for j in range(i, len(numbers)):\n sigma += (numbers[j][0] // numbers[i][0]) * numbers[j][1] * numbers[i][1]\n return sigma\n\ndef AJ_no_islice(numbers):\n numbers = sorted(Counter(numbers).items())\n sigma = sum((a_j // a_i) * a_j_count * a_i_count\n for i, (a_i, a_i_count) in enumerate(numbers)\n for a_j, a_j_count in numbers[i:])\n return sigma\n\ndef superb_rain(numbers):\n sigma = 0\n counted = []\n for a_j, a_j_count in sorted(Counter(numbers).items()):\n sigma += a_j_count * sum([(a_j // a_i) * a_i_count\n for a_i, a_i_count in counted],\n a_j_count)\n counted.append((a_j, a_j_count))\n return sigma\n\ndef superb_rain_2(numbers):\n sigma = 0\n counted = sorted(Counter(numbers).items())\n while counted:\n a_j, a_j_count = counted.pop()\n sigma += a_j_count * sum([(a_j // a_i) * a_i_count\n for a_i, a_i_count in counted],\n a_j_count)\n return sigma\n\nfuncs = original, AJ_no_islice, superb_rain, superb_rain_2\n\n# Correctness\nnumbers = choices(range(1, 100001), k=1000)\nexpect = funcs[0](numbers)\nfor func in funcs:\n result = func(numbers)\n print(result == expect, func.__name__)\nprint()\n\n# Speed\nnames = [f' {func.__name__} ' for func in funcs]\nprint(' n |' + ''.join(names))\nprint('-------+' + '-' * sum(map(len, names)))\nfor n in 1000, 10000, 20000:\n print(f'{n:6} |', end='')\n numbers = list(range(1, n+1))\n shuffle(numbers)\n for func in funcs:\n if n <= 200000 or func is Kelly_Bundy:\n t = min(repeat(lambda: func(numbers), number=1, repeat=1))\n t = '%.2f' % t\n else:\n t = '-'\n print(f'{t:>{len(func.__name__)}} ', end='')\n print()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T17:14:11.830",
"Id": "254956",
"ParentId": "254895",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254949",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:53:59.947",
"Id": "254895",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Summation of large inputs"
}
|
254895
|
<p>I'm trying to do a simulation on the role of luck in human achievement.</p>
<p>Here is what I intend to do with my code:</p>
<ol>
<li>Create 20000 instances of people with randomly generated scores for skill, experience and hard-work(0 to 99), and a luck value(0 to 100).</li>
<li>Create a total score for each person, with 95% of the average of the skill, experience and hard-work, and 5% of their luck value.</li>
<li>Select the top 10 persons and record their luck value.</li>
<li>Iterate the procedure a specified amount of times and find the total average luck of all the people who came top ten in all of the iterations.</li>
</ol>
<p>Please review the code and tell me if my code is correctly written for the above purpose. I'm skeptical about the pseudo-randomness random library interfering with the results.</p>
<pre><code>import random
class candidate :
def __init__(self):
self.skill = random.uniform(0,99)
self.exp = random.uniform(0,99)
self.work = random.uniform(0,99)
self.luck = random.uniform(0,100)
self.total_score = ((self.skill+self.exp+self.work)/3)*.95+self.luck*0.05
candidate_list = []
candidate_selected_lucks = []
def select():
for i in range (0,20000):
candidate_list.append(candidate())
for m in range(0,10):
_max = 0.0
for j in range (0,len(candidate_list)):
if (candidate_list[j].total_score > _max):
_max = candidate_list[j].total_score
index = j
candidate_selected_lucks .append(candidate_list[index].luck)
print(m,"."," Score : ", candidate_list[index].total_score, " Luck : ", candidate_list[index].luck,"\n")
candidate_list.pop(index)
def find_avg(candidate_selected_lucks):
return sum(candidate_selected_lucks)/len(candidate_selected_lucks)
def simulate(N):
for k in range(0,N):
print ("Iteration ",str(k+1),". ")
select()
candidate_list.clear()
print ("average luck is", find_avg(candidate_selected_lucks),"\n")
count = int(input("Enter no of simulations\n"))
simulate(count)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:12:43.183",
"Id": "502884",
"Score": "2",
"body": "Some \"meta-advice\" here; if you say luck is 5% of a person's score, you're probably going to find that the luck score varies drastically and has an average near 50. It may be more interesting to repeat this experiment with *different* weights for luck, in which case you wouldn't want to hard-code the `...*0.95` and `...*0.05` values either. I'm not fluent in Python, but as a step one I'm sure you could allow `luckWeight` to be configured for each instance of `Candidate`."
}
] |
[
{
"body": "<ul>\n<li><code>candidate</code> class should be named <code>Candidate</code></li>\n<li><code>find_avg()</code> is already covered by the built-in <code>statistics.mean()</code></li>\n<li><code>candidates</code> can be created by a list comprehension</li>\n<li>global variables such as <code>candidate_list</code> and <code>candidate_selected_lucks</code> can be replaced with return values</li>\n</ul>\n<pre><code>import random\nfrom statistics import mean\n\nclass Candidate :\n def __init__(self):\n self.skill = random.uniform(0,99)\n self.exp = random.uniform(0,99)\n self.work = random.uniform(0,99)\n self.luck = random.uniform(0,100)\n self.total_score = ((self.skill+self.exp+self.work)/3)*.95+self.luck*0.05\n\ndef generate_winners():\n candidates = [Candidate() for _ in range(0,20000)]\n candidates_by_luck = sorted(candidates,\n key=lambda candidate: candidate.luck, reverse=True)\n winners = candidates_by_luck[:10]\n for idx, winner in enumerate(winners):\n print(f"{idx}. Score : {winner.total_score} Luck : {winner.luck}")\n print()\n return winners\n\ndef simulate(N):\n for k in range(0,N):\n print ("Iteration ",str(k+1),". ")\n winners = generate_winners()\n avg_luck = mean(winner.luck for winner in winners)\n print ("average luck is", avg_luck,"\\n")\n \ncount = int(input("Enter no of simulations\\n"))\nsimulate(count)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T02:38:31.787",
"Id": "502834",
"Score": "0",
"body": "Appreciate that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:10:33.293",
"Id": "254907",
"ParentId": "254899",
"Score": "5"
}
},
{
"body": "<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using <code>PascalCase</code> for classes, so your class should be called <code>Candidate</code>. It also recommends using spaces after a <code>,</code> when passing multiple arguments to a function.</p>\n<p>The creation of the candidates is as simple as this:</p>\n<pre><code>candidate_list = [Candidate() for _ in range(20000)]\n</code></pre>\n<p>Note that the starting index of <code>range</code> is <code>0</code> by default and that I used the customary variable name <code>_</code> for the unused loop variable.</p>\n<p>This also removes having to <code>clear</code> the candidates list, since it is being created anew every time you call the <code>select</code> function.</p>\n<p>To get the candidate with the largest score, just use:</p>\n<pre><code>best_candidate = max(candidate_list, key=lambda c: c.total_score)\n</code></pre>\n<p>This does not allow you to easily remove them from the list of candidates, though. For this you can use <code>enumerate</code>:</p>\n<pre><code>index, candidate = max(enumerate(candidate_list), key=lambda t: t[1].total_score)\n</code></pre>\n<hr />\n<p>However, since you are running a not quite small numerical simulation, you might want to look into using <a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\"><code>numpy</code></a>, which would greatly speed up the calculations. Instead of having a <code>Candidate</code> class, just create arrays. Generating random numbers in bulk is vastly faster than doing it one at a time as well:</p>\n<pre><code>import numpy as np\n\niterations = 100\ncandidates = 20000\ntop_ten_luck = []\n\nfor _ in range(iterations):\n scores = np.random.randint(0, 99, size=(candidates, 3))\n luck = np.random.randint(0, 100, size=candidates)\n total_score = 0.95 * scores.mean(axis=1) + 0.05 * luck\n top_ten = np.argpartition(-total_score, 10)[:10]\n top_ten_luck.extend(luck[top_ten])\n\nprint(np.mean(top_ten))\n</code></pre>\n<p>This runs in less than a second (132ms on my machine, to be exact). The <code>for</code> loop can also be vectorized, but at that point you might run into memory constraints.</p>\n<p>Note that I used <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html\" rel=\"nofollow noreferrer\"><code>numpy.argpartition</code></a> to get the indicies of the top ten candidates, in order to only partially sort the data as much as needed and not further. We need to use <code>-total_score</code> because it only gives you minimal values. This should be both faster than <code>pop</code>ing the maximum value ten times as well as completely sorting the list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T02:38:14.993",
"Id": "502833",
"Score": "0",
"body": "Thank you for you input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T03:00:20.090",
"Id": "502835",
"Score": "1",
"body": "May I ask what technique did you used to measure the time of execution? Did you use the time library? How accurate would it be?\nAn interesting thing I found is that the average luck score converges around 70 to 75%, I ran 100, 1000, 10000, and 100,000 iterations. I never expected this result. Could this have to do with the pseudo randomness of the python random library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T08:12:16.807",
"Id": "502848",
"Score": "1",
"body": "@ASWINVENU I used an interactive python terminal (`ipython`) and there the `%timeit` magic command. It reported the result as `132 ms ± 1.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T08:13:22.270",
"Id": "502849",
"Score": "1",
"body": "@ASWINVENU As to why that seems to be the limiting value, one would have to do some math. You might want to ask this question on one of our sister sites ([stats.se] might be the right place for this). But it will almost certainly not have anyhing to do with the random library. `numpy` uses a different one and I get similar results."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:11:19.067",
"Id": "254908",
"ParentId": "254899",
"Score": "7"
}
},
{
"body": "<p>No one else has mentioned: Taking the mean of three uniformly random variables from 0-99 is the same as just generating one uniformly random variable from 0-99 (excepting fractional remainders).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T03:23:55.273",
"Id": "254977",
"ParentId": "254899",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T14:59:42.067",
"Id": "254899",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"random"
],
"Title": "Applying random luck scores to instances of people"
}
|
254899
|
<p>absolute newbie here. I need help with simplifying my code. I want to create many more similar functions as shown below. Is there a simpler way where I can code without having to manually type in the same function every time I want to add a new function?</p>
<pre><code>function toggleItem1() {
var myItem1 = document.getElementById('item1Image');
var displaySetting = myItem1.style.display;
var item1Button = document.getElementById('item1Button');
if (displaySetting == 'block') {
myItem1.style.display = 'none';
item1Button.innerHTML = 'Show item';
} else {
myItem1.style.display = 'block';
item1Button.innerHTML = 'Hide item';
}
}
function toggleItem2() {
var myItem2 = document.getElementById('item2Image');
var displaySetting = myItem2.style.display;
var item2Button = document.getElementById('item2Button');
if (displaySetting == 'block') {
myItem2.style.display = 'none';
item2Button.innerHTML = 'Show item';
} else {
myItem2.style.display = 'block';
item2Button.innerHTML = 'Hide item';
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:22:09.137",
"Id": "502748",
"Score": "3",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:23:24.947",
"Id": "502750",
"Score": "0",
"body": "Mini-review: `Item1` and`Item2` are not very descriptive identifiers; they should be made more meaningful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:06:45.353",
"Id": "502762",
"Score": "0",
"body": "@TobySpeight The code is obvious enough to provide sufficient context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:45:57.493",
"Id": "502773",
"Score": "1",
"body": "@konjin, it includes nothing at all to indicate its purpose; it doesn't even include a document that contains `item1Image`, `item1Button`, `item2Image` and `item2Button`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:24:38.353",
"Id": "502867",
"Score": "0",
"body": "(Numbering *named things* is a *code smell*.)"
}
] |
[
{
"body": "<p>Similar but different functions can be merged by using parameters.</p>\n<pre><code>function toggleItem(itemId, buttonId) {\n\n var item = document.getElementById(itemId);\n var displaySetting = item.style.display;\n var button = document.getElementById(buttonId);\n\n if (displaySetting == 'block') {\n item.style.display = 'none';\n button.innerHTML = 'Show item';\n } else {\n\n item.style.display = 'block';\n button.innerHTML = 'Hide item';\n }\n }\n\n// usage\ntoggleItem('item1image', 'item1button')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T23:34:21.400",
"Id": "502824",
"Score": "0",
"body": "Thank you so much for the help, really appreciate it! :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:06:48.093",
"Id": "254902",
"ParentId": "254900",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254902",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:00:11.390",
"Id": "254900",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "How to Simplify Different but Similar Functions?"
}
|
254900
|
<p>I just recently learned how to write Methods in C#. Here is one experiment I made. It calculates addition, subtraction, division, multiplication, and the square root of a number. fill free to give me suggestions on how I can improve the code. I also do know I need to set up a system that prevents the user from typing wrong answers. I just don't have enough experience to do it yet (I tried).</p>
<pre><code>static void Main(string[] args)
{
string userAnswer;
Console.WriteLine("Calculater or Square Root Calculater?");
Console.WriteLine("-Please respond with Calculater or Square");
userAnswer = Console.ReadLine().ToUpper();
Console.Clear();
switch(userAnswer)
{
case "CALCULATER":
Calculater();
break;
case "SQUARE":
SquareRootCalculater();
break;
default:
Console.WriteLine("Invalid Input");
break;
}
Console.ReadKey();
}
static void SquareRootCalculater()
{
int squareNumber;
Console.WriteLine("Input Number:");
squareNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.WriteLine($"The Square Root of {squareNumber} is");
Console.WriteLine(Math.Sqrt(squareNumber));
}
static void Calculater()
{
int firstNumber;
string sign;
int secondNumber;
int answer = 0;
Console.WriteLine("Input Number:");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.WriteLine("Input Operation:");
sign = Console.ReadLine();
Console.Clear();
Console.WriteLine("Input Second Number:");
secondNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();
switch (sign)
{
case "+":
answer = firstNumber + secondNumber;
break;
case "-":
answer = firstNumber - secondNumber;
break;
case "*":
answer = firstNumber * secondNumber;
break;
case "/":
answer = firstNumber / secondNumber;
break;
default:
Console.WriteLine("Invalid Input");
break;
}
Console.WriteLine($"The answer of {firstNumber} {sign} {secondNumber} is");
Console.WriteLine(answer);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:34:33.250",
"Id": "502753",
"Score": "4",
"body": "Please improve the title of your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:38:07.220",
"Id": "502755",
"Score": "6",
"body": "I have already provided a [thorough answer](https://codereview.stackexchange.com/a/254374/224104) for your previous question. Now the same code appears here again. Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:38:45.567",
"Id": "502770",
"Score": "0",
"body": "Peter Csala. Thank you for your previous answer to the calculater improvement question I put out around a week ago. I have recently learned how to work with methods and was experimenting with it. I decided to reuse some code from the calculater improvement question while experimenting with methods. I put out this question because I was seeking advice on how well I implemented the methods. I also will try to improve the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T08:33:52.507",
"Id": "502858",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:29:01.597",
"Id": "502983",
"Score": "0",
"body": "@the if you look at Peter Csala's answer to your original question https://codereview.stackexchange.com/a/254374/47174 he's provided a good example for for a key principal for writing better Methods called *Separation of Concerns* (You should do some research on this topic). If you look at his code that contains `answer = PerformAddition(lhs, rhs);` you'll see he's modified your code to include 4 additional functions. This is a separating those 4 concerns into their own methods, with descriptive names, that makes the code easier to read and maintain."
}
] |
[
{
"body": "<p>You should aim to declare variables at initialization when possible. Pre-initialized variables are suspicious and make me wonder whether they are being optionally assigned or edited elsewhere.</p>\n<pre><code> // string userAnswer;\n\n Console.WriteLine("Calculater or Square Root Calculater?");\n Console.WriteLine("-Please respond with Calculater or Square");\n string userAnswer = Console.ReadLine().ToUpper();\n Console.Clear();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:23:19.643",
"Id": "502749",
"Score": "1",
"body": "Thanks for the advice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:20:34.660",
"Id": "254905",
"ParentId": "254901",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:03:26.027",
"Id": "254901",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Methods improvements"
}
|
254901
|
<p>The following code will add to each code block on <a href="https://codereview.stackexchange.com/">https://codereview.stackexchange.com/</a> or <a href="https://stackoverflow.com/">https://stackoverflow.com/</a> a 'Select Code' button that will select the code belonging to that block.</p>
<p>This was originally written in 2013, I adjusted it to the new CSS and exchanged <code>var</code> with <code>let</code>, otherwise I think it looks fine. However JS has changed a lot, so I am submitting it again.</p>
<p>The original code was reviewed <a href="https://codereview.stackexchange.com/q/38336/14625">here</a> 7 years ago.</p>
<p>In order to use this, visit <a href="http://codereviewcommunity.github.io/CodeReviewBookmarklet/" rel="nofollow noreferrer">http://codereviewcommunity.github.io/CodeReviewBookmarklet/</a></p>
<pre><code>javascript: $('pre.s-code-block').not('button + *').each(function createButton() {
/* Thank you http://stackoverflow.com/a/2838358/7602 */
function selectCode(el, win) {
win = win || window;
let doc = win.document,
sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
let buttonText = 'Select Code',
length = buttonText.length,
codeBlock = this,
$link = $('<button type=\'button\'>' + buttonText + '</button>').click(function buttonListener() {
console.log($(codeBlock).text().substring(length));
selectCode(codeBlock);
});
$(codeBlock).before($link);
});
/* Cross browser bookmarklet sorcery */
void(0);
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:29:42.500",
"Id": "254906",
"Score": "1",
"Tags": [
"javascript",
"bookmarklet"
],
"Title": "Bookmarklet for selecting code snippets on StackExchange in 2021"
}
|
254906
|
<p>I've just started learning myself Rust. I am practicing with the exercises from the book available on the official website.
Here is my attempt at the temperature converter exercise at the end of chapter 3.</p>
<p>Could you tell me if my approach is correct? Is there something I could have done more efficiently? Is there something I shouldn't do because it's not how Rust is supposed to work?</p>
<p>Thank you!</p>
<pre><code>use std::io;
fn main() {
println!("Enter a temperature.");
let mut temperature = String::new();
io::stdin()
.read_line(&mut temperature)
.expect("Failed to read temperature");
let (value, unit) = temperature.split_at(temperature.len() - 2);
let value: f32 = match value.trim().parse() {
Ok(num) => num,
Err(_) => panic!("{} is not a number", value),
};
let unit = unit.trim().to_lowercase();
print!("The input temperature is: {}", temperature);
if unit == "c" {
c_to_f(value);
} else if unit == "f" {
f_to_c(value);
} else {
println!("Unsupported unit");
}
}
fn c_to_f(c: f32) {
output(c * 1.8 + 32.0, "F".to_string());
}
fn f_to_c(f: f32) {
output((f - 32.0) / 1.8, "C".to_string());
}
fn output(t: f32, u: String) {
println!("The output temperature is: {}{}", t, u);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I hope some late help will still be helpful!\nI've erred on the side of providing a bit too much feedback, but this may give you a sense of some of the styles and conventions that Rust uses even if they are overkill for this simple program.</p>\n<ul>\n<li><p>Nicely organized code overall, very understandable and clear use of functions.</p>\n</li>\n<li><p>In function arguments, it's generally cleaner/more efficient/more idiomatic to accept <code>&str</code> instead of <code>String</code>. This is usually confusing for beginners, but <code>&str</code> is read-only string data and <code>String</code> is an owned, dynamically growable string, so basically if you only need read-only, you should use <code>&str</code>. As a rule of thumb, it's a good starting point to just make all function arguments <code>&str</code> and the return value <code>String</code>. Here's <code>output</code> fixed; noticed that this means you don't have to to <code>.to_string()</code> in your other functions:</p>\n<pre><code>fn c_to_f(c: f32) {\n output(c * 1.8 + 32.0, "F");\n}\n\nfn f_to_c(f: f32) {\n output((f - 32.0) / 1.8, "C");\n}\n\nfn output(t: f32, u: &str) {\n println!("The output temperature is: {}{}", t, u); \n}\n</code></pre>\n</li>\n<li><p>Although it doesn't make a huge difference for a small project like this, another good rule of thumb is to avoid functions with printing behavior; instead functions should return Strings, and only the top-level program (i.e. main function) prints. So let's change <code>fn output</code> again. All we need to do is use <code>format!</code> instead of <code>println!</code> (and print in <code>main</code>):</p>\n<pre><code>fn c_to_f(c: f32) -> String {\n output(c * 1.8 + 32.0, "F")\n}\n\nfn f_to_c(f: f32) -> String {\n output((f - 32.0) / 1.8, "C")\n}\n\nfn output(t: f32, u: &str) -> String {\n format!("The output temperature is: {}{}", t, u)\n}\n</code></pre>\n</li>\n<li><p>The <code>let value: f32</code> logic is a bit verbose, the usual function for this is <code>unwrap_or_else</code>:</p>\n<pre><code>let value: f32 = value.trim().parse().unwrap_or_else(|_| {\n panic!("{} is not a number", value)\n});\n</code></pre>\n</li>\n<li><p>In the line <code>let (value, unit) = temperature.split_at(temperature.len() - 2)</code>, this use of <code>split_at</code> is considered fragile and mostly discouraged. Remember that in Rust strings are not just sequences of bytes, but valid UTF-8 data where the characters may not correspond to bytes. So this code introduces a silent failure (i.e. one that is not explicitly exposed and dealt with by the application): I tried running your program on input <code>4 </code> and I got</p>\n<pre><code>thread 'main' panicked at 'byte index 5 is not a char boundary; it is inside ''\n</code></pre>\n<p>In fact, there is actually a second similar issue in the same line: when run with an empty input line in release mode, you have integer underflow:</p>\n<pre><code>thread 'main' panicked at 'byte index 18446744073709551615 is out of bounds of `\n`'\n</code></pre>\n<p>These edge cases do not introduce a bigger problem for your case, but in production code such failures could cause an unexpected crash, or worse, a security vulnerability. So the preference in Rust is always to be explicit about handling errors. You can browse the functions available in the documentation <code>https://doc.rust-lang.org/std/primitive.str.html</code> for some ideas of how to parse strings in general; here the easiest is probably to explicitly check for both errors:</p>\n<pre><code>let mid = temperature.len().checked_sub(2).expect("Input string was empty");\nif !temperature.is_char_boundary(mid) {\n panic!("Input should end in a single-byte char (the unit)");\n}\nlet (value, unit) = temperature.split_at(mid);\n</code></pre>\n</li>\n<li><p>If you only need mutability for a temporary amount of time (as with <code>temperature</code>), it's good practice to declare the variable immutable after that: <code>let temperature = temperature</code></p>\n</li>\n<li><p>The last part of <code>main</code> can be reduced a bit by using <code>match</code> instead of <code>if</code>: <code>match unit.as_str() {</code></p>\n</li>\n<li><p>Finally, for extensibility it would be great to abstract temperature into an appropriate type; Rust programmers like to leverage static types to make sure they keep for example Celsius and Fahrenheit values separate, without any actual overhead at runtime. Although I won't change your code for this, you would define types like so:</p>\n<pre><code>struct Fahrenheit(f64);\nstruct Celsius(f64);\n</code></pre>\n<p>You could alternatively have a Temperature type if you want a lot of functionality related to temperatures in general:</p>\n<pre><code>enum Temperature {\n Fahrenheit(f64),\n Celsius(f64),\n}\n</code></pre>\n<p>Then, you would define parsing functions (parse from <code>&str</code>), display functions (convert to <code>String</code>), and so on on those types, rather than including all of this in <code>main</code>.</p>\n</li>\n</ul>\n<hr />\n<p>Here's the final code incorporating all the suggestions except the last one:</p>\n<pre><code>use std::io;\n\nfn main() {\n println!("Enter a temperature.");\n\n let mut temperature = String::new();\n io::stdin()\n .read_line(&mut temperature)\n .expect("Failed to read temperature");\n let temperature = temperature;\n\n let mid = temperature.len().checked_sub(2).expect("Input string was empty");\n if !temperature.is_char_boundary(mid) {\n panic!("Input should end in a single-byte char (the unit)");\n }\n let (value, unit) = temperature.split_at(mid);\n\n let value: f32 = value.trim().parse().unwrap_or_else(|_| {\n panic!("{} is not a number", value)\n });\n let unit = unit.trim().to_lowercase();\n\n println!("The input temperature is: {}", temperature);\n\n match unit.as_str() {\n "c" => println!("{}", c_to_f(value)),\n "f" => println!("{}", f_to_c(value)),\n _ => panic!("Unsupported unit"),\n }\n}\n\nfn c_to_f(c: f32) -> String {\n output(c * 1.8 + 32.0, "F")\n}\n\nfn f_to_c(f: f32) -> String {\n output((f - 32.0) / 1.8, "C")\n}\n\nfn output(t: f32, u: &str) -> String {\n format!("The output temperature is: {}{}", t, u)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T18:57:15.520",
"Id": "504171",
"Score": "1",
"body": "Wow, that's an in depth review, it's greatly appreciated! Thank you so much. I need to digest that now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T17:02:11.577",
"Id": "255514",
"ParentId": "254909",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:13:30.947",
"Id": "254909",
"Score": "2",
"Tags": [
"beginner",
"rust"
],
"Title": "Temperature converter in Rust"
}
|
254909
|
<p>I wrote a function in C that reads an entire line from a stream into a dynamically allocated buffer. What would you suggest I should do to improve its performance? Also, are there any errors that could occur and are not handled?</p>
<p>This is the code:</p>
<pre><code>#define ERRALLOC(ptr) \
if (ptr == NULL) { \
printf("Unable to allocate memory for %s", #ptr); \
exit(1); \
}
#define PACK_SIZE 512
size_t readLine(FILE *istream, char **line_buffer, size_t *bufsize) {
size_t line_size = 0;
int eol_flag = 0;
char temp_buffer[PACK_SIZE];
while (fgets(temp_buffer, PACK_SIZE, istream) != NULL) {
size_t temp_len = strlen(temp_buffer);
line_size += temp_len;
if (line_size+1 > *bufsize) {
*bufsize = line_size+1;
*line_buffer = realloc(*line_buffer, *bufsize * sizeof(char));
ERRALLOC(*line_buffer)
}
if (temp_buffer[ temp_len - 1 ] == '\n') {
temp_buffer[ temp_len - 1 ] = '\0';
eol_flag = 1;
}
strcpy(*line_buffer + (line_size-temp_len), temp_buffer);
if (eol_flag) break;
}
return line_size;
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, it's a lot of effort (perhaps not in the right place) for one line. Textual data typically has lines that are very short, on the order of 80 bytes. If you're so deeply concerned about performance, you need to back out of this function and look at the I/O pattern of the calling program for more context. You'll very likely find that it's more efficient to have a buffer much larger than your current <code>PACK_SIZE</code>, perhaps 4MB. Read the file into it one such chunk at a time with <code>fread</code>, not <code>fgets</code>; then iterate through to find and split on newlines. Roughly,</p>\n<ol>\n<li>Allocate a large buffer</li>\n<li><code>fread</code> as much as possible</li>\n<li><code>memchr</code> your way to a newline</li>\n<li>Set that newline to <code>'\\0'</code></li>\n<li>Consume the line</li>\n<li>Repeat 3-5 until you're at the end of the buffer</li>\n<li>If there is a partial line segment at the end, then <code>memcpy</code> the segment to the beginning of the buffer and plan for the next <code>fread</code> to use a buffer write position that starts after the end of the segment</li>\n<li>Repeat until end of file</li>\n</ol>\n<p>The principle to heed here is that I/O (particularly disk I/O) is expensive, and frequent calls to the I/O layer are expensive even when cached at the operating system level. Doing as much in RAM as possible is strongly preferred.</p>\n<p>If you want a convenience interface, then consider accepting a <code>FILE*</code> and a callback function, making the buffer locally rather than accepting it, and invoking the callback for each line when found.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:25:54.467",
"Id": "502937",
"Score": "1",
"body": "This approach is problematic for user I/O with `stdin` as function return is usually expected after each `'\\n'`. OP's code is usable with both stream and file lines. The expense of file I/O is less with SS drives than hard disks negating some of this approaches benefit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:29:43.797",
"Id": "502939",
"Score": "0",
"body": "Still, direct use of `fgets()` has its corner case drawbacks too - so good to see alternatives."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:41:45.453",
"Id": "254921",
"ParentId": "254913",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>#define ERRALLOC(ptr) \\\nif (ptr == NULL) { \\\n printf("Unable to allocate memory for %s", #ptr); \\\n exit(1); \\\n}\n</code></pre>\n</blockquote>\n<p>That's a poor way to handle allocation failure, and makes your function pretty much unusable in any realistic program context. It's very rude to simply <code>exit()</code> from within a library function, and it's unhelpful to write to <code>stdout</code>, rather than <code>stderr</code> that's designed for such messages. And why are you not writing a complete line, with <code>\\n</code> at the end?</p>\n<blockquote>\n<pre><code> *line_buffer = realloc(*line_buffer, *bufsize * sizeof(char));\n</code></pre>\n</blockquote>\n<p>Don't do this; when allocation fails then the pointed-to memory is still allocated, but inaccessible. The standard pattern is</p>\n<pre><code>void *new_mem = realloc(buffer, newsize);\nif (!new_mem) {\n return buffer;\n /* or free(buffer); return new_mem; */\n}\nbuffer = new_mem;\n</code></pre>\n<p>Note also that <code>sizeof (char)</code> is 1 by definition, so multiplying by it has no effect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:47:04.117",
"Id": "254950",
"ParentId": "254913",
"Score": "2"
}
},
{
"body": "<p><strong>What does <code>line_size</code> represent?</strong></p>\n<p>String length (like <code>strlen()</code>), string size or what?</p>\n<p>With input <code>"abc\\n"</code>, <code>*line_buffer</code> is <code>"abc"</code> and <code>line_size</code> is 4.</p>\n<p>With input <code>"abc" End-of-file</code>, <code>*line_buffer</code> is <code>"abc"</code> and <code>line_size</code> is 3.</p>\n<p><strong>Input error - non handling</strong></p>\n<p>When <code>fgets()</code> returns <code>NULL</code> due to an input error, consider also returning 0 regardless of the number of characters read.</p>\n<p><strong>Reading a <em>null character</em></strong></p>\n<p>Code has undefined behavior (UB) when the first character read is a <em>null character</em>.</p>\n<p><code>temp_buffer[ temp_len - 1 ]</code> becomes <code>temp_buffer[SIZE_MAX]</code></p>\n<p>When a null character is read anywhere, <code>size_t temp_len = strlen(temp_buffer);</code> fails to correctly report the length of data read.</p>\n<p><strong>Minor simplification</strong></p>\n<p><code>strcpy(*line_buffer + (line_size-temp_len), temp_buffer);</code> could happen before <code>if (temp_buffer[ ...</code> and simplify the <code> break</code> condition.</p>\n<p>Yet, I would think the <code>line_size += temp_len;</code> should reduce by what happens in <code>if (temp_buffer[ ...</code>.</p>\n<p>I'd expect <code>memcpy()</code> a tad faster here than <code>strcpy()</code>, but <code>fgets()</code> is the tall pole in the tent here.</p>\n<p><strong>Optimization</strong></p>\n<p>As long as <code>*bufsize</code> is not tiny, I'd consider doing the first read directly into <code>*line_buffer</code>. Since code is re-using that buffer, at some point, it is likely big enough for most following reads.</p>\n<p><strong>Sizing by reference rather than type</strong></p>\n<p>Consider the easier to review and maintain:</p>\n<pre><code>//*line_buffer = realloc(*line_buffer, *bufsize * sizeof(char));\n*line_buffer = realloc(*line_buffer, *bufsize * sizeof **line_buffer);\n</code></pre>\n<p><strong>Missing example</strong></p>\n<p>Proper usage of <code>readLine()</code> lacks a guiding example. Perhaps:</p>\n<pre><code>char *line_buffer = NULL;\nsize_t bufsize = 0;\nsize_ sz;\nwhile ((sz = readLine(stdin, &line_buffer, &bufsize)) > 0) {\n printf("Sz:%zu <%s>\\n", sz, line_buffer);\n}\nfree(line_buffer);\n</code></pre>\n<p><strong>Naming consistency</strong></p>\n<p>3 styles in one line. Consider any 1 style.</p>\n<pre><code>readLine(FILE *istream, char **line_buffer, size_t *bufsize\nreadLine: camel case\nline_buffer: `_` separation\nbufsize: packed\n</code></pre>\n<p><strong>Research <code>restrict</code></strong></p>\n<p>This provide some self documentation and hints for compiler optimization.</p>\n<pre><code>///size_t readLine(FILE *istream, char **line_buffer, size_t *bufsize) {\nsize_t readLine(FILE * restrict istream, char ** restrict line_buffer, \n size_t * restrict bufsize) {\n</code></pre>\n<p><strong>Missing <code>#include <></code>s</strong></p>\n<p>At least <code>stdio.h, string.h, strlib.h</code></p>\n<p><strong>Good uses of <code>size_t</code></strong></p>\n<p><strong>Good formating</strong></p>\n<p><strong>Style</strong></p>\n<p><code>ERRALLOC(*line_buffer)</code> <em>looks</em> wrong without a trialing <code>;</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:18:32.250",
"Id": "254981",
"ParentId": "254913",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:31:15.743",
"Id": "254913",
"Score": "4",
"Tags": [
"performance",
"c"
],
"Title": "Improvements for a C getline implementation"
}
|
254913
|
<p>I'm trying to apply Uncle Bob's Clean Code practices onto this exercise I'm helping someone with.
(The exercise assignment is in a "docstring" comment above the <code>Main</code>.)</p>
<p>I'm unsure what the best naming convention would be for <code>ReturnAllCombinationsOfInputtedList</code>, although I suspect it doesn't involve the return word in it's name for starters.
Same for <code>CreateArray1to30()</code>. Any suggestions for name choices/proper conventions here?</p>
<p>Do you guys see anything else that I should've done differently in your opinion?</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleAppHelpingAlexWithExercices
{
class Program
{
//**************************************************************************
// How many different exam tickets with two different questions can be made,
// from a syllabus with 30 questions
//**************************************************************************
static void Main(string[] args)
{
int[] questionsList = CreateArray1to30();
List<string> combinations = ReturnAllCombinationsOfInputtedList(questionsList);
int amountOfUniqueCombinations = combinations.Distinct<string>().Count();
Console.WriteLine("Total unique combinations: {0}", amountOfUniqueCombinations);
}
static List<string> ReturnAllCombinationsOfInputtedList(int[] questionsList)
{
List<string> combinations = new List<string>();
int[] aTest = new int[2];
foreach (int firstQuestion in questionsList)
{
foreach (int secondQuestion in questionsList)
{
if (firstQuestion != secondQuestion)
{
aTest[0] = firstQuestion;
aTest[1] = secondQuestion;
//Makes AB and BA tests both AB, so we can de-duplicate later.
Array.Sort(aTest);
combinations.Add(String.Format("{0}&{1}", aTest[0], aTest[1]));
Console.WriteLine("{0} and {1}", aTest[0], aTest[1]);
}
}
}
return combinations;
}
static int[] CreateArray1to30()
{
return Enumerable.Range(1, 30).ToArray();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:15:59.720",
"Id": "502798",
"Score": "3",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T13:56:02.600",
"Id": "502963",
"Score": "0",
"body": "I'm not a c# programmer so won't go into any detail, but surely you don't need to make all permutations and de-duplicate them?\nIf you have 30 questions, you have a choice of 29 to combine with the first, but only 28 to combine with the second and so on..."
}
] |
[
{
"body": "<ul>\n<li><code>CreateArray1to30()</code> could be renamed to <code>CreateQuestions()</code></li>\n<li><code>ReturnAllCombinationsOfInputtedList()</code> could be renamed to <code>Combinations()</code> or <code>QuestionCombinations()</code></li>\n<li><code>ReturnAllCombinationsOfInputtedList()</code> does too much. The call to <code>.Distinct()</code> is unecessary, and can be replaced with correct indices in the first place. Furthermore, the <code>aTest</code> array is entirely useless and could be replaced by using <code>firstQuestion</code> and <code>secondQuestion</code> directly.</li>\n<li>Strings are a non ideal data structures for the exams, as you use a different format when printing them out</li>\n</ul>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n\nnamespace ConsoleAppHelpingAlexWithExercices\n{\n struct ExamTicket {\n public int Question1, Question2;\n public ExamTicket(int Question1, int Question2) {\n this.Question1 = Question1;\n this.Question2 = Question2;\n }\n }\n class Program\n {\n //**************************************************************************\n // How many different exam tickets with two different questions can be made, \n // from a syllabus with 30 questions\n //**************************************************************************\n static void Main(string[] args)\n {\n int[] questions = CreateQuestions();\n var combinations = new List<ExamTicket>(Combinations(questions));\n foreach (var combination in combinations) {\n Console.WriteLine($"{combination.Question1} and {combination.Question2}");\n }\n Console.WriteLine("Total unique combinations: {0}", combinations.Count);\n }\n\n static IEnumerable<ExamTicket> Combinations(int[] questions)\n {\n for (int i=0;i<questions.Length;++i) {\n for (int j=i+1;j<questions.Length;++j) {\n yield return new ExamTicket(questions[i],questions[j]);\n }\n }\n }\n\n static int[] CreateQuestions()\n {\n return Enumerable.Range(1, 30).ToArray();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:53:01.723",
"Id": "502984",
"Score": "1",
"body": "`static IEnumerable<ExamTicket> ToExam(this int[] questions)` :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:04:02.560",
"Id": "254918",
"ParentId": "254914",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:32:32.383",
"Id": "254914",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Applying 'Uncle Bob's Clean Code' on this small exercice"
}
|
254914
|
<p>I implemented Tic-Tac-Toe in Rust to learn the language.</p>
<p>I split the implementation into two files: <code>game.rs</code> contains the actual game logic, and <code>main.rs</code> contains the main function and the command-line UI.</p>
<p>I'm interested in any feedback. One particular question I have: I'm interested in trying to implement a GUI interface for the game – have I split the logic correctly between <code>main.rs</code> and <code>game.rs</code> so that <code>game.rs</code> could be reused in a GUI version?</p>
<p><strong>Cargo.toml</strong></p>
<pre><code>[package]
name = "tic-tac-toe"
version = "0.1.0"
authors = ["Stephen Wade <stephen@stephenwade.me>"]
edition = "2018"
[dependencies]
rustyline = "7.1.0"
</code></pre>
<p><strong>game.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use std::fmt;
use std::ops::{Deref, DerefMut};
#[derive(Clone, Copy, PartialEq)]
pub enum BoardValue {
Filled(Player),
Empty,
}
impl fmt::Display for BoardValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Filled(player) => write!(f, "{}", player),
Self::Empty => write!(f, " "),
}
}
}
impl Default for BoardValue {
fn default() -> Self {
Self::Empty
}
}
impl BoardValue {
fn player(self) -> Player {
if let Self::Filled(player) = self {
player
} else {
panic!("not filled")
}
}
}
#[derive(Clone, Copy, PartialEq)]
pub enum Player {
X,
O,
}
impl fmt::Display for Player {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::X => "X",
Self::O => "O",
}
)
}
}
impl Default for Player {
fn default() -> Self {
Player::X
}
}
type BoardType = [[BoardValue; 3]; 3];
#[derive(Default)]
pub struct Board(BoardType);
impl Deref for Board {
type Target = BoardType;
fn deref(&self) -> &BoardType {
&self.0
}
}
impl DerefMut for Board {
fn deref_mut(&mut self) -> &mut BoardType {
&mut self.0
}
}
impl fmt::Display for Board {
#[rustfmt::skip]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "┌───┬───┬───┐")?;
writeln!(f, "│ {} │ {} │ {} │", self[0][0], self[0][1], self[0][2])?;
writeln!(f, "├───┼───┼───┤")?;
writeln!(f, "│ {} │ {} │ {} │", self[1][0], self[1][1], self[1][2])?;
writeln!(f, "├───┼───┼───┤")?;
writeln!(f, "│ {} │ {} │ {} │", self[2][0], self[2][1], self[2][2])?;
write! (f, "└───┴───┴───┘")
}
}
impl Board {
fn get_winnable_slices(&self) -> Vec<[&BoardValue; 3]> {
vec![
// Horizontal
[&self[0][0], &self[0][1], &self[0][2]],
[&self[1][0], &self[1][1], &self[1][2]],
[&self[2][0], &self[2][1], &self[2][2]],
// Vertical
[&self[0][0], &self[1][0], &self[2][0]],
[&self[0][1], &self[1][1], &self[2][1]],
[&self[0][2], &self[1][2], &self[2][2]],
// Diagonal
[&self[0][0], &self[1][1], &self[2][2]],
[&self[0][2], &self[1][1], &self[2][0]],
]
}
fn get_all_cells(&self) -> Vec<&BoardValue> {
self.iter().flatten().collect::<Vec<&BoardValue>>()
}
}
pub struct Game {
pub board: Board,
pub current_player: Player,
}
pub enum GameStatus {
Continue,
PlayerWins(Player),
Draw,
}
pub enum PlayError {
InvalidMove,
}
impl Game {
pub fn new() -> Self {
Game {
board: Board::default(),
current_player: Player::default(),
}
}
pub fn play(&mut self, row: usize, column: usize) -> Result<GameStatus, PlayError> {
if matches!(self.board[row][column], BoardValue::Filled(_)) {
return Err(PlayError::InvalidMove);
}
self.board[row][column] = BoardValue::Filled(self.current_player);
let game_status = self.get_game_status();
if matches!(game_status, GameStatus::Continue) {
self.current_player = match self.current_player {
Player::X => Player::O,
Player::O => Player::X,
};
}
Ok(game_status)
}
fn get_game_status(&self) -> GameStatus {
for slice in self.board.get_winnable_slices() {
if matches!(*slice[0], BoardValue::Filled(_))
&& slice[0] == slice[1]
&& slice[1] == slice[2]
{
return GameStatus::PlayerWins(slice[0].player());
}
}
if self
.board
.get_all_cells()
.into_iter()
.all(|cell| matches!(*cell, BoardValue::Filled(_)))
{
return GameStatus::Draw;
}
GameStatus::Continue
}
}
</code></pre>
<p><strong>main.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>mod game;
use game::*;
use std::str;
use rustyline::Editor;
fn main() {
let mut game = Game::new();
println!("Welcome to tic tac toe!");
loop {
println!("{}", game.board);
println!("It's {}'s turn.", game.current_player);
let inputs = match get_row_and_column() {
Ok(inputs) => inputs,
Err(_) => return,
};
match game.play(inputs.0, inputs.1) {
Ok(GameStatus::Continue) => continue,
Ok(GameStatus::Draw) => {
println!("{}", game.board);
println!("It's a draw.");
return;
}
Ok(GameStatus::PlayerWins(player)) => {
println!("{}", game.board);
println!("{} wins!", player);
return;
}
Err(PlayError::InvalidMove) => {
println!("Invalid move. Please try again.");
}
};
}
}
fn get_row_and_column() -> Result<(usize, usize), ()> {
let strings = match read_row_and_column_strings() {
Ok(strings) => strings,
Err(_) => return Err(()),
};
let numbers = match parse_row_and_column_strings(strings) {
Ok(numbers) => numbers,
Err(_) => return Err(()),
};
Ok((numbers.0 - 1, numbers.1 - 1))
}
fn parse_row_and_column_strings(
input: (String, String),
) -> Result<(usize, usize), <usize as str::FromStr>::Err> {
let row: usize = input.0.parse()?;
let column: usize = input.1.parse()?;
Ok((row, column))
}
fn read_row_and_column_strings() -> Result<(String, String), rustyline::error::ReadlineError> {
let mut rl = Editor::<()>::new();
let valid_inputs: Vec<&str> = vec!["1", "2", "3"];
let mut row_line: String;
let mut column_line: String;
loop {
row_line = rl.readline("Enter a row (1, 2, 3): ")?;
if valid_inputs.iter().any(|&s| row_line == s) {
break;
};
}
loop {
column_line = rl.readline("Enter a column (1, 2, 3): ")?;
if valid_inputs.iter().any(|&s| column_line == s) {
break;
};
}
Ok((row_line, column_line))
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>General impression</h1>\n<p>The code is clear and concise —\nit is a great pleasure to read your code.\nThis review is thus less about problems\nthan it is about pointing out opportunities to simplify the code.</p>\n<p>The split between game logic and UI also seems fine —\nI wouldn't worry too much about it at this point.</p>\n<h1>Naming</h1>\n<p>Some personal thoughts on naming:</p>\n<ul>\n<li><p>simplify <code>BoardValue</code> to <code>Cell</code> or similar;</p>\n</li>\n<li><p>rename <code>X</code> and <code>O</code> to <code>Cross</code> and <code>Nought</code> for more legibility;</p>\n</li>\n<li><p>rename <code>BoardValue::player</code> to something along the lines of\n<code>BoardValue::unwrap_player</code> (following <code>Option::unwrap</code>),\nto clearly indicate its panicking behavior;</p>\n</li>\n<li><p>rename <code>play</code>, which is too generic, to <code>try_place</code>.</p>\n</li>\n</ul>\n<h1>User interface</h1>\n<p>I would index the board by</p>\n<pre><code>+---+---+---+\n| 1 | 2 | 3 |\n+---+---+---+\n| 4 | 5 | 6 |\n+---+---+---+\n| 7 | 8 | 9 |\n+---+---+---+\n</code></pre>\n<p>rather than use <code>(row, column)</code>, for simplicity.</p>\n<h1>Board computation</h1>\n<p><code>get_winnable_slices</code> and <code>get_all_cells</code> feel wasteful —\nan iterator or callback interface should be possible in theory.</p>\n<h1>Using crates</h1>\n<p>There are some crates you can use to reduce boilerplate:</p>\n<ul>\n<li><p>(highly recommended) <a href=\"https://docs.rs/anyhow\" rel=\"nofollow noreferrer\"><code>anyhow</code></a> for error handling;</p>\n</li>\n<li><p><a href=\"https://docs.rs/derive_more\" rel=\"nofollow noreferrer\"><code>derive_more</code></a> for deriving <code>Display</code>, <code>Deref</code>, and <code>DerefMut</code>;</p>\n</li>\n<li><p><a href=\"https://docs.rs/smart-default\" rel=\"nofollow noreferrer\"><code>smart_default</code></a> for deriving <code>Default</code>;</p>\n</li>\n<li><p>a <a href=\"https://lib.rs/search?q=table\" rel=\"nofollow noreferrer\">table rendering crate</a>.</p>\n</li>\n</ul>\n<h1>Helper functions</h1>\n<p>Ideas for helper functions:</p>\n<ul>\n<li><p><code>BoardValue::is_filled</code>, to reduce the number of <code>matches!</code>;</p>\n</li>\n<li><p><code>Player::toggle</code>, to toggle the player.</p>\n</li>\n</ul>\n<h1>Miscellaneous</h1>\n<p>For <code>BoardValue</code> and <code>Player</code>,\nI would derive <code>Eq</code> in addition to <code>PartialEq</code>.</p>\n<p>Is there a specific reason why <code>X</code> is the default player?\nI would leave <code>Default</code> out if the selection is arbitrary.</p>\n<p>For <code>Game::new</code>, you can <code>derive(Default)</code> and then call it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T12:04:17.773",
"Id": "255412",
"ParentId": "254920",
"Score": "2"
}
},
{
"body": "<p>Nicely organized code! In addition to what L.F. suggested:</p>\n<ul>\n<li><p>The <code>fn player(self)</code> looks like a questionably useful function; it basically wraps normal pattern matching of an <code>enum</code> type, and since it can panic it is likely to obfuscate rather than clarify wherever it is used. Indeed, closer inspection reveals you only use this function once, and you can replace this, for example with (I've renamed <code>BoardValue</code> to <code>Cell</code> following L.F.'s idea):</p>\n<pre><code>fn get_game_status(&self) -> GameStatus {\n for slice in self.board.get_winnable_slices() {\n if let Cell::Filled(player) = slice[0] {\n if slice[0] == slice[1] && slice[1] == slice[2] {\n return GameStatus::PlayerWins(*player);\n }\n }\n }\n</code></pre>\n</li>\n<li><p>Defining <code>Cell</code> before <code>Player</code> is difficult to follow. Better to put <code>pub enum Player</code> at the top and then define <code>Cell</code> afterwards.</p>\n</li>\n<li><p>The use of <code>impl Deref</code> and <code>impl DerefMut</code> for <code>Board</code> is clever! One thing to consider is that this makes type conversions implicit, so if you do something weird (like calling a function on the underlying <code>[[Cell; 3]; 3]</code> that you didn't know existed), the compiler won't give you a type error. I think it is probably worth it for convenience in this case. But an alternative would be to write getters and setters for grid cells, like <code>fn get_cell(&self, i: usize, j: usize) -> Cell</code> and <code>fn set_cell(&mut self, i: usize, j: usize)</code>. This could be more extensible later if you add more fields to the <code>Board</code> struct.</p>\n</li>\n<li><p>Your error type <code>pub enum PlayError</code> is great design; extensible for other error types. A problem, though, is that <code>pub fn play</code> seems to implicitly panic if given an out-of-range row and column. Since you are already returning Result, I think it would be better to include an out-of-bounds error: i.e.</p>\n<pre><code>pub fn play(&mut self, row: usize, column: usize) -> Result<GameStatus, PlayError> {\n if row > 2 || column > 2 {\n return Err(PlayError::OutOfBounds)\n }\n if matches!(self.board[row][column], Cell::Filled(_)) {\n return Err(PlayError::AlreadyFilled);\n }\n</code></pre>\n<p>This may also simplify and clarify the logic in <code>main</code> as you don't can handle the Result type instead of checking the bounds yourself.</p>\n</li>\n<li><p>In your <code>get_all_cells</code> function, instead of returning a vector you can return an iterator. That works like this:</p>\n<pre><code>fn iter_cells(&self) -> impl Iterator<Item = &Cell> {\n self.iter().flatten()\n}\n</code></pre>\n<p>This eliminates a needless iterator-to-vector-to-iterator conversion, since you are only using <code>get_all_cells</code> in order to iterate anyway. So in <code>get_game_status</code> you would just use <code>if self.board.iter_cells().all(...) { ... }</code></p>\n</li>\n<li><p>The board length <code>3</code> is a magic constant. Since it's only used in a few places I would prefer <code>const BOARD_ROWS: usize = 3</code> and <code>const BOARD_COLS: usize = 3</code>. This is also fun because you can then try out tic-tac-toe on other board dimensions like 2-by-5 or something, but you would have to re-implement <code>get_winnable_slices</code> in a more general way.</p>\n</li>\n<li><p>Minor but worth thinking about: I am overall not sure that having both <code>Game</code> and <code>Board</code> types is worth it. It is not clear that there is functionality specific to <code>Board</code> that isn't just the fact that it's a grid of cells. If you move <code>impl fmt::Display</code>, <code>get_winnable_slices</code>, and <code>iter_cells</code> to <code>Game</code>, then you can get rid of <code>Board</code> entirely and avoid the indirection of having to implement <code>Deref</code> and <code>DerefMut</code>. Or you could still keep these functions separate, but more in a functional style rather than object-oriented.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T17:24:05.043",
"Id": "255418",
"ParentId": "254920",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:26:07.213",
"Id": "254920",
"Score": "6",
"Tags": [
"beginner",
"rust"
],
"Title": "Command-line Tic-Tac-Toc in Rust"
}
|
254920
|
<p>Despite the many decent answers to <a href="https://stackoverflow.com/questions/14962018/detecting-and-fixing-circular-references-in-javascript">this question</a>, one was unable to find an iterative solution. Here's what I came up with:</p>
<p><strong>Code:</strong></p>
<pre><code>type CircularReferenceHandler = (parentKey: IndexKey, parentValue: Dictionary<IndexKey, any>, childKey: IndexKey, childValue: Dictionary<IndexKey, any>) => void;
type Dictionary<TKey extends IndexKey, TValue> = Record<TKey, TValue>;
type IndexKey = (number | string);
const processCircularReferences = <T extends object>(input: T, handler: CircularReferenceHandler, initialPathValue = "o"): T => {
const objectStack = [{ k: initialPathValue, v: input, },];
const objectTracker = new WeakSet<Dictionary<IndexKey, any>>();
objectTracker.add(input);
while (objectStack.length) {
const { k: parentKey, v: parentValue } = objectStack.shift()!;
for (const [childKey, childValue] of Object.entries(parentValue)) {
if ((childValue && ("object" === typeof childValue))) {
if (objectTracker.has(childValue)) {
handler(parentKey, parentValue, childKey, childValue);
}
else {
objectStack.push({ k: `${parentKey}.${childKey}`, v: childValue, });
objectTracker.add(childValue);
}
}
}
}
return input;
}
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code>let o: any = { x: 0, y: 1, };
o.me = {};
o.me.self = o;
o.self = o;
processCircularReferences(o, (pK, pV, cK, _cV) => {
console.log(`${pK}.${cK}`);
pV[cK] = undefined;
});
console.log(o);
/*
[log]: o.me.self
[log]: o.self
[log]: {
me: {
self: undefined
},
self: undefined,
x: 0,
y: 1
}
*/
</code></pre>
|
[] |
[
{
"body": "<h2>Correctness</h2>\n<p>Following testcase breaks your code:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const o={};\no.x = o.y = {};\n</code></pre>\n<p>This is due to <code>objectTracker</code> tracks all seen values not all parent values.</p>\n<h2>Interface Design</h2>\n<ul>\n<li><code>initialPathValue</code> looks strange to me. The parameter has no meaning to this function as far as I can tell.</li>\n<li>Dot separated path won't work if any <code>.</code>s in keys. For example: <code>{ "a.b": {}, "a": { "b": {} } }</code>. To avoid any confusion, I would suggest use <code>string[]</code> instead.</li>\n</ul>\n<h2>Implementation</h2>\n<ul>\n<li><code>objectStack</code> is named as Stack, but you are using it as a Queue. I believe there should be a mistake here. Maybe you want <code>pop()</code> instead of <code>shift()</code>.</li>\n<li><code>parentValue</code> is a <code>WeakSet</code>. But I cannot find a reason why any objects in it will be garbage collected during the functions life cycle. So maybe a simple <code>Set</code> would fint your requirement.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:55:48.097",
"Id": "255086",
"ParentId": "254922",
"Score": "3"
}
},
{
"body": "<ul>\n<li>dot-separated path's aren't the best as the keys aren't always alpha-numeric. I would suggest preserving the list of keys instead of trying to format them for the callback. If the callback want's to <code>.join('.')</code> the list, or do something else, it's up to the callback. An added bonus: You can get rid of the initialPathValue parameter since that just has to do with formatting the result, not the business logic.</li>\n<li>As @tsh mentions, Your algorithm is finding duplicate elements inside the data structure instead of finding circular references (some of the answers to the linked question suffer from the same issue). To fix this, make each entry in your stack keep its own list of its ancestors. To check for a circular dependency, you just need to check if the object you're looking at also appears in one of your ancestors.</li>\n<li>The callback seems a little weird to me as you're not doing any async logic in here. Why not just return the found results? If you're worried about performance and are wanting to handle the results as soon as you find them, use a generator instead - that way the user of this function can decide if they want all of the results at once (by turning your generator into a list), or to handle them when they're available (by iterating over the generator).</li>\n</ul>\n<p>Here's an example (in javascript) that applies the above suggestions:</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 topOfStack = array => array[array.length - 1];\n\nfunction* findCircularReferences(rootObj) {\n const stack = [{ path: [], objectsInPath: [rootObj] }];\n while (stack.length) {\n const { path, objectsInPath } = stack.pop();\n for (const [childKey, childObj] of Object.entries(topOfStack(objectsInPath))) {\n if (typeof childObj !== 'object' || childObj === null) continue;\n\n const nextStackEntry = {\n path: [...path, childKey],\n objectsInPath: [...objectsInPath, childObj],\n };\n\n if (objectsInPath.includes(childObj)) {\n yield nextStackEntry;\n } else {\n stack.push(nextStackEntry);\n }\n }\n }\n}\n\n// Should find two circular references\nconst obj1 = { obj3: null };\nconst obj2 = { obj1, 'obj1-again': obj1 };\nconst obj3 = { obj2 };\nobj1.obj3 = obj3;\nconsole.log([...findCircularReferences(obj1)].map(({ path }) => path));\n\n// Should not find any circular references\nconst dupEntry = { x: 2 };\nconsole.log([...findCircularReferences([dupEntry, dupEntry])].map(({ path }) => path));</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-26T05:45:52.143",
"Id": "255243",
"ParentId": "254922",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:57:28.443",
"Id": "254922",
"Score": "1",
"Tags": [
"javascript",
"typescript"
],
"Title": "Handling Circular References Without Recursion"
}
|
254922
|
<p>The below function takes in a dataframe consisting of an excel sheet with the <code>Price</code> column. It works correctly however it looks unnecessarily long for something quite simple. Basically calculating a Simple Moving Average based on <code>Price</code> : <code>SMA</code> = <code>Sum</code> of all prices in a period/period:</p>
<pre><code>def SimpleMA(Timing, n):
sum = 0
count = 0
for i in range(n, len(df.index)):
count += 1
sum += df['Price'][i]
if count == Timing:
df.loc[i, f'MA_{Timing}'] = sum/Timing
n += 1
if n != len(df.index) - Timing:
SimpleMA(Timing, n)
else:
plt.figure(figsize = (20,6))
plt.title("Price vs MA")
plt.plot(x, df[f'MA_{Timing}'], x, df['Price'])
plt.show()
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:51:01.730",
"Id": "502820",
"Score": "0",
"body": "Please retag your question. It helps distinguish which language you are using in the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:57:38.317",
"Id": "502821",
"Score": "0",
"body": "This is salvageable, but you need to fix your indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:58:23.027",
"Id": "502822",
"Score": "0",
"body": "You also need to show enough context - including the definition of `plt` and particularly `df`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T02:20:17.330",
"Id": "502832",
"Score": "4",
"body": "pandas.DataFrames implement `.rolling` methods. I would use that."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:39:17.473",
"Id": "254927",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Can you help me optimize this code that calculates a Simple Moving Average?"
}
|
254927
|
<p>I wanted to render some Vega plots in a rust+wasm web application I've been building with Yew. I'm a bit new to Rust, so I'm looking for feedback on runtime safety and stylistic issues.</p>
<p>I was specially skeptical of the <code>spawn_local</code> I copied from someone's GitHub and the amount of <code>unwrap</code>s thrown around.</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
use vega_lite_4::*;
use wasm_bindgen_futures::*;
use wasm_bindgen::prelude::*;
use yew::prelude::*;
#[wasm_bindgen]
extern {
fn vegaEmbed(
el: web_sys::Element,
spec: JsValue,
opts: JsValue,
) -> js_sys::Promise;
}
pub fn vega_embed(
node_ref: &NodeRef,
spec: &Vegalite,
opts: &Option<HashMap<String, String>>,
) -> Result<(), Box<dyn std::error::Error>> {
let el = node_ref.cast::<web_sys::Element>().unwrap();
let spec = JsValue::from_serde(spec)?;
let opts = match &opts {
Some(x) => JsValue::from_serde(x)?,
None => JsValue::from(js_sys::Object::new()),
};
let embed: JsFuture = vegaEmbed(el, spec, opts).into();
spawn_local(async move { embed.await.unwrap(); });
Ok(())
}
#[derive(Properties, Clone)]
pub struct Props {
pub spec: Vegalite,
pub opts: Option<HashMap<String, String>>,
}
pub struct VegaLiteChart {
node_ref: NodeRef,
spec: Vegalite,
opts: Option<HashMap<String, String>>,
}
impl Component for VegaLiteChart {
type Message = ();
type Properties = Props;
fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self {
VegaLiteChart {
node_ref: NodeRef::default(),
spec: props.spec,
opts: props.opts,
}
}
fn view(&self) -> Html {
html! { <div ref=self.node_ref.clone()></div> }
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
false
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn rendered(&mut self, _first_render: bool) {
vega_embed(&self.node_ref, &self.spec, &self.opts).unwrap();
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T22:52:49.123",
"Id": "254929",
"Score": "1",
"Tags": [
"rust",
"data-visualization",
"webassembly"
],
"Title": "Vega lite plot rendering with Yew (rust + wasm)"
}
|
254929
|
<p>I have 2 dictionaries that I have to compare, if an element of one dictionary exists in the other dictionary, then add the element to an array but only one time...</p>
<p>here the working code</p>
<pre><code>const getFavouriteShows = (graphql, favouriteShows) => {
const arraya = [];
//iterate trough favouriteShows
for (let item in favouriteShows) {
//iterate trough graphql
for (let itemGQL in graphql) {
//if same slug, add the item to new array JUST ONE TIME
if(favouriteShows[item].slug === graphql[itemGQL].show?.slug){
arraya.push(graphql[itemGQL])
break
}
}
}
return Object.assign(arraya)
}
</code></pre>
<p>So, how to express this in a more inline functional way? using map, filter.</p>
<p>Thanks!</p>
<p>Edit, examples for the data coming in and out <a href="https://gist.github.com/mako34/44301d3c96249de9a07aa2550ca1172a" rel="nofollow noreferrer">https://gist.github.com/mako34/44301d3c96249de9a07aa2550ca1172a</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T04:33:25.720",
"Id": "502838",
"Score": "0",
"body": "Can you provide some example inputs and outputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:51:33.047",
"Id": "502846",
"Score": "0",
"body": "thanks @TedBrownlow link with sample data added"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T08:27:36.027",
"Id": "502853",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h2>Review</h2>\n<ul>\n<li><p>Use semicolons. Why? If you don't know why you should use them, then you should use them. Not using them can result in very hard to track down bugs that will waste hours of your valuable time.</p>\n</li>\n<li><p>Use <code>const</code> wherever and whenever possible.</p>\n</li>\n<li><p>The return expression <code>Object.assign(arraya)</code> does nothing and is not required ( <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Object.assign\">Object.assign</a> returns the first argument unchanged if there is only one argument). <code>return arraya;</code> will do the same.</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statements reference for...of\">for of</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statements reference for...in\">for in</a>. When you use <code>for in</code> you need to ensure that the key belongs to the object which just makes the code more complex. If you dont check for own property <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Object.hasOwnProperty\">Object.hasOwnProperty</a> then you risk the code not working for reasons unrelated to your code.</p>\n<p>To get the keys of an object use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Object.keys\">Object.keys</a> eg you can then replace the for in with <code>for (let item of Object.keys(favouriteShows)) {</code></p>\n<p>As it is only the value <code>slug</code> you want from each item in the object <code>favouriteShows</code> you can further refine the for of loop to get that value for you. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Object.values\">Object.values</a> which will get the value you find with <code>favouriteShows[item]</code> and use destructure assignment to pull out <code>slug</code> thus (Note the <code>const</code>) you have <code>for (const {slug} of Object.values(favouriteShows)) {</code></p>\n</li>\n<li><p>Avoid naming variables after what they are, rather name them for what they represent (Unless they represent unknowns). Eg <code>arraya</code> would be better as <code>results</code></p>\n</li>\n<li><p>Don't use complicated or long names when there is no need. The arguments <code>(graphql, favouriteShows)</code> can be simplified to <code>(graph, shows)</code> without losing any meaning.</p>\n</li>\n</ul>\n<h2>Problems</h2>\n<p>There are a number of problems with this code.</p>\n<ol>\n<li><p>The statement that matches shows by slug <code>if(favouriteShows[item].slug === graphql[itemGQL].show?.slug){</code> will match any two shows that do not have <code>slug</code> defined IE <code>slug === undefined</code></p>\n<p>This is not a problem if all objects always have <code>slug</code> defined. However the use of <code>show?.</code> makes it clear that this is at least not true in part.</p>\n<p>You can check if slug is defined in the outer loop so you don't waste time searching for undefined in the inner loop.</p>\n</li>\n<li><p>In your question you state <em>"...then add the element to an array but only one time."</em> However if <code>favouriteShows</code> contains items that have the same value for <code>slug</code> and there is a match for that value in <code>graphql</code> your function will add the same entry for every occurrence in <code>favouriteShows</code></p>\n<p>To prevent this problem you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference Set\">Set</a> to hold the result rather than an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference Array\">Array</a>, It will ensure only one copy of each item is added.</p>\n</li>\n</ol>\n<h2>Improvement</h2>\n<p>The inner loop repeats, stepping over the same items for every item in <code>favouriteShows</code>. You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference Map\">Map</a> that indexes items via a generated hash value. This reduces the complexity of your inner loop from <span class=\"math-container\">\\$O(n)\\$</span> to <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n<p>Thus your code ends up as with added comments</p>\n<pre><code>// Keep the argument names simple\nconst favouriteShows = (graph, shows) => {\n\n // Use set to ensure only a single instance of each item will be in the result\n const result = new Set(); \n\n // Create a map of graph indexed by slug so the inner loop is not needed.\n const bySlug = new Map(Object.values(graph).map(val => [val.show?.slug, val]));\n\n // Extract value of slug from the item values in shows\n for (const {slug} of Object.values(shows)) {\n \n // Make sure slug is defined.\n // It is unclear if this value may be falsey so test against undefined\n if (slug !== undefined) {\n\n // Does the map bySlug have an entry that matches slug?\n if (bySlug.has(slug)) {\n\n // Yes then get that entry and add it to the result.\n result.add(bySlug.get(slug));\n }\n }\n }\n\n // To return an array convert the set to an array.\n return [...result.values()];\n}\n</code></pre>\n<p>It can also be compacted a little, and making an assumption that slug will be either undefined or some truthy string we get</p>\n<pre><code>const favouriteShows = (graph, shows) => {\n const result = new Set(); \n const bySlug = new Map(Object.values(graph).map(val => [val.show?.slug, val]));\n for (const {slug} of Object.values(shows)) {\n const show = bySlug.get(slug); \n slug && show && result.add(show);\n }\n return [...result.values()];\n}\n</code></pre>\n<p><strong>Note</strong> that <code>bySlug.get</code> will find the last entry in the object <code>graph</code> if <code>graph</code> contained duplicates (<code>slug</code> has the same value more than once). As your code uses the first instance you may want to change the second line in the function so that it reverses (via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.reverse\">Array.reverse</a>) the order that the map is created. If there are no duplicates then it does not matter.</p>\n<pre><code>const favouriteShows = (graph, shows) => {\n const result = new Set(); \n const bySlug = new Map(Object.values(graph)\n .map(val => [val.show?.slug, val])\n .reverse()\n );\n for (const {slug} of Object.values(shows)) {\n const show = bySlug.get(slug); \n slug && show && result.add(show);\n }\n return [...result.values()];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T05:01:18.847",
"Id": "255077",
"ParentId": "254930",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T00:43:10.853",
"Id": "254930",
"Score": "0",
"Tags": [
"javascript",
"functional-programming",
"iteration"
],
"Title": "JS create array by comparing 2 dictionaries"
}
|
254930
|
<p>Currently I have this code:</p>
<pre><code>private async Task<(List<SomeModel> data1, List<string> data2)>
ProcessFileAsync(IEnumerable<FileInfo> filesInDirectory)
{
var data1 = new List<SomeModel>();
var data2 = new List<string>();
var inDirectory = filesInDirectory as FileInfo[] ?? filesInDirectory.ToArray();
for (var lIndex = 0; lIndex < inDirectory.Count(); lIndex++)
{
var content = await File.ReadAllTextAsync(inDirectory.ElementAt(lIndex).FullName);
var name = Path.GetFileNameWithoutExtension(inDirectory.ElementAt(lIndex).Name);
var data1Task = GetData1Async(content, name);
var data2Task = GetData2Async(content);
await Task.WhenAll(data1Task, data2Task);
data1.AddRange(data1Task.Result);
data2.AddRange(data2Task.Result);
}
return (data1, data2);
}
</code></pre>
<p>The calling code:</p>
<pre><code>private async Task<(List<SomeModel> data1, List<string> data2)> BatchProcessFilesAsync()
{
var batchSize = 4;
var models
= await GetDataFromSomewhereAsync().ConfigureAwait(false);
var listOfRequests = new List<Task<(List<SomeModel> data1, List<string> data2)>>();
var fileModels = models.ToList();
for (var skip = 0; skip <= fileModels.Count(); skip += batchSize)
{
var files = fileModels.Skip(skip).Take(batchSize);
listOfRequests.Add(ProcessFileAsync(files));
}
// This will run all the calls in parallel to gain some performance
var allFinishedTasks = await
Task.WhenAll(listOfRequests).ConfigureAwait(false);
</code></pre>
<p>The problem I am facing is if I need to add data3 in future, i have to add code here again. Is there a way to make this code Solid.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:47:59.267",
"Id": "502870",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:48:47.013",
"Id": "502871",
"Score": "2",
"body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:50:12.710",
"Id": "502872",
"Score": "5",
"body": "Note that `GetDataFromSomewhereAsync` and `SomeModel` suggest this is obfuscated code, which is off-topic."
}
] |
[
{
"body": "<p>Let me show you how to review your code from SOLID principles point of view.</p>\n<p>Here I try to list some general questions and give some guidance to help you determine that your current solution does violate some of the principles or not.</p>\n<h3>Single - Responsibility principle</h3>\n<p>Q: What does <code>XYZ</code> method do?<br />\nIf your answer resembles to any of these:</p>\n<ul>\n<li><em>First it ... then it ...</em></li>\n<li><em>It does ... and it ...</em></li>\n<li><em>It calls ... method and ... method</em></li>\n<li>etc.</li>\n</ul>\n<p>it is a good sign that your code method does too much things.</p>\n<p>Just to make it clear this principle does NOT suggest to wrap each line into a separate function. On the contrary, it suggests to combine those that are closely related to each other to enhance cohesion. We should strive/aim for <strong>high cohesion</strong> and <strong>low coupling</strong>.</p>\n<h3>Open - Closed principle</h3>\n<p>Q: Is your <code>XYZ</code> method suitable for <em>T</em> or <em>W</em> type of changes?</p>\n<p>In this principle you try to guess what will future present you. Let's suppose that <code>XYZ</code> can handle <code>X</code>, <code>Y</code> and <code>Z</code>. If you need to support <code>T</code> and <code>W</code> then do you need to modify the current code or can you for example inherit from that and override only the necessary methods?</p>\n<h3>Liskov Substitution principle</h3>\n<p>Not applicable here.</p>\n<h3>Interface Segregation principle</h3>\n<p>Q: Do I (as a consumer of your API) have to know what does each method of <code>IXYZ</code> do?</p>\n<p>This principle suggests to try to think from the consumer perspective. If I want to call only <code>X</code> then do I need an interface which provides <code>X</code>, <code>Y</code> and <code>Z</code>? You can think of this principle as an extension of SRP to interfaces. If your interface contains members that are not highly coherent then you need to slip it.</p>\n<h3>Dependency Inversion principle</h3>\n<p>Q: Does your <code>XYZ</code> class / method depend on other concrete classes?</p>\n<p>This principle suggests to depend on abstractions rather than on concrete types. (Remember we are aiming for <strong>loose coupling</strong>). If you depend on abstraction and not the implementation then you can switch easily without the need to modify this class (this helps OCP as well).</p>\n<hr />\n<p>I hope this helped you a bit. I suggest to further read these excellent articles:</p>\n<ul>\n<li><a href=\"https://blog.jetbrains.com/upsource/2015/08/31/what-to-look-for-in-a-code-review-solid-principles-2/\" rel=\"nofollow noreferrer\">What to look for in a Code Review: SOLID Principles</a></li>\n<li><a href=\"https://www.red-gate.com/simple-talk/dotnet/net-framework/the-zen-of-code-reviews-review-as-if-you-own-the-code/\" rel=\"nofollow noreferrer\">The Zen of Code Reviews: Review As If You Own the Code</a></li>\n<li><a href=\"http://davecallan.com/what-to-look-for-when-reviewing-code-for-solid-principle-violations/\" rel=\"nofollow noreferrer\">What to look for when reviewing code for SOLID principle ‘violations’</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:00:44.407",
"Id": "254947",
"ParentId": "254941",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T09:58:29.413",
"Id": "254941",
"Score": "0",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "How to make this code follow Solid Principle C#"
}
|
254941
|
<p>I made the code underneath to sort my array and group people with the same score to show who all got 1st, 2nd and 3rd.</p>
<p>the "points" variable looks like this</p>
<pre><code>points: {
'204255221017214977': 3,
'208993609255485441': 5,
'382197942762602496': 4,
'664606841409634324': 5,
'779857709155090432': 4,
'381084508276916225': 5,
'794200859612545075': 4,
'155149108183695360': 4,
'438978127973318656': 3,
'304028235082104843': 2,
'174548757151481856': 1
}
</code></pre>
<p>I was wondering if there is a much easier way to sort and put together the string like I did underneath with much easier code. Cuz I'll be honest this code looks and feels aweful.</p>
<p>example endresult:</p>
<pre><code>:first_place: @Excanator had 5 points
:first_place: @zerow had 5 points
:first_place: @AnimeHotOwO had 5 points
:second_place: @christmas beans had 4 points
:second_place: @ExcavatorGames had 4 points
:second_place: @Dyno had 4 points
:second_place: @LogiBot Premium had 4 points
:third_place: @Restarter v3 had 3 points
:third_place: @YAGPDB.xyz had 3 points
@aNt had 2 points
@Kaori had 1 point
</code></pre>
<pre><code>const sorted = Object.keys(points).sort((a, b) => {
return points[b] - points[a]
})
var results = `\n`
var firstPlace = points[sorted[0]]
var secondPlace = null
var thirdPlace = null
var leftover = null
for(const key of sorted) {
var amount = points[key]
if(leftover){
results += `<@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else if(thirdPlace) {
if(thirdPlace === amount) {
results += `:third_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `<@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
leftover = amount
}
} else if(secondPlace) {
if(secondPlace === amount) {
results += `:second_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `:third_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
thirdPlace = amount
}
} else if(firstPlace) {
if(firstPlace === amount) {
results += `:first_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `:second_place: <@${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
secondPlace = amount
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Your code would benefit from separating data and display. Results can also be constructed by using the <code>.join()</code> method on an array, reducing the need for checking boundaries. I'm not sure that these modifications resulted in "easier" code, but the singular point of truth makes it harder for bugs to hide.</p>\n<pre><code>const points = {\n '204255221017214977': 3,\n '208993609255485441': 5,\n '382197942762602496': 4,\n '664606841409634324': 5,\n '779857709155090432': 4,\n '381084508276916225': 5,\n '794200859612545075': 4,\n '155149108183695360': 4,\n '438978127973318656': 3,\n '304028235082104843': 2,\n '174548757151481856': 1\n}\n\n// arrange items into a dictionary of lists\n// keyFunc determines bin for each item\nfunction bin(items, keyFunc) {\n const bins = new Map();\n for (const item of items) {\n const key = keyFunc(item);\n if (!bins.get(key)) bins.set(key,[]);\n bins.get(key).push(item);\n }\n return bins;\n}\n\n// create a list of lists of player tuples\n// each top level list represents a medal position\nfunction createPodium(points) {\n // bin players by score\n const bins = bin(Object.entries(points), ([player,score])=>score);\n const podium = [...bins.entries()];\n // sort medal positions by descending score\n podium.sort((a,b)=>b[0]-a[0]);\n // return only the players\n return podium.map(([score,players])=>players);\n}\n\nconst MEDAL_NAMES = ['first_place', 'second_place', 'third_place'];\nfunction medalName(index) {\n const medal = MEDAL_NAMES[index];\n if (medal) return `:${medal}: `;\n else return '';\n}\n\nconst playerString = (medal,[name,score]) =>\n medalName(medal)+\n `<${name}> had ${score} point${score>1?'s':''}`;\n\nconst podiumString = podium =>\n podium.flatMap((players,medal)=>\n players.flatMap(\n player=>playerString(medal,player)\n ).concat(['']) // add extra line between\n ).join('\\n');\n\nconst podium = createPodium(points);\nconsole.log(podiumString(podium));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T08:24:22.410",
"Id": "502946",
"Score": "0",
"body": "You're right it's not necessarily easier code but it sure does look and feel a lot better than what I came up with! It's a bit too advanced for me to think of doing it like this but that's great because it means I'll learn from it! thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T17:59:09.470",
"Id": "254957",
"ParentId": "254944",
"Score": "1"
}
},
{
"body": "<p>You can also use string templating. Something like this:</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 points = {\n '204255221017214977': 3,\n '208993609255485441': 5,\n '382197942762602496': 4,\n '664606841409634324': 5,\n '779857709155090432': 4,\n '381084508276916225': 5,\n '794200859612545075': 4,\n '155149108183695360': 4,\n '438978127973318656': 3,\n '304028235082104843': 2,\n '174548757151481856': 1\n};\n\nconst placeTemplates = {\n 5: (userId, points) => `:first_place: ${userId} had ${points} points`,\n 4: (userId, points) => `:secondt_place: ${userId} had ${points} points`,\n 3: (userId, points) => `:third_place_place: ${userId} had ${points} points`,\n 2: (userId, points) => `${userId} had ${points} points`, // DRY :-/\n 1: (userId, points) => `${userId} had ${points} points` // DRY :-/\n}\n\nconst aggregated = Object.entries(points).reduce((akku, userId_point) => {\n const [userId, point] = userId_point;\n if(!Array.isArray(akku[point])) {\n akku[point] = []\n }\n akku[point].push(placeTemplates[point](userId, point));\n return akku;\n}, {});\n\nconst result = Object.keys(aggregated).reverse().reduce((akku, point) => akku.concat(aggregated[point]), []).join(\"\\n\");\ndocument.getElementById('wrapper').innerText = result;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"wrapper\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T08:21:31.720",
"Id": "502945",
"Score": "0",
"body": "Wouldn't I have to make a placeTemplate for every score possible? I put the points for testing purpouses no higher than 5 but in theory they can go till inifity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T08:37:43.743",
"Id": "502947",
"Score": "0",
"body": "You can create placeTemplates with loop.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:01:41.317",
"Id": "502985",
"Score": "0",
"body": "fair fair. my brain was working at 5am hrs/thought my bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:39:31.617",
"Id": "254973",
"ParentId": "254944",
"Score": "0"
}
},
{
"body": "<h2>Functions</h2>\n<p>Always write code as functions. Even when its just an example, writing code as a function gives it a name, and make you think in terms of that name.</p>\n<p>Functions should be as simple as possible doing one thing only. (see rewrite)</p>\n<h2>Review</h2>\n<ul>\n<li>USE SEMICOLONS!!!</li>\n<li>Don't add code that is redundant or superfluous. Eg <code>var secondPlace = null</code> can be <code>var secondPlace</code>.</li>\n<li>Keep it DRY. (Don't Repeat Yourself). You have a lot of repeated code that does similar or the same. Using function will reduce a lot of repeated code.</li>\n<li>Use constants to define magic values. (see rewrite)</li>\n<li>Use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference\">Array</a> to hold lists of strings then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.join\">Array.join</a> to join them using the delimiter (see rewrite)</li>\n<li>Use appropriate names. Names define the abstractions you use, poor naming make code harder to understand especially when a single abstract concept gets many names, or the same name represent multiple abstractions.\n<ul>\n<li><code>points</code> As records should be <code>results</code></li>\n<li><code>key</code> could be <code>id</code>.</li>\n<li><code>amount</code> could be <code>score</code></li>\n</ul>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Rewrite is just an example as there are many ways to do this.</p>\n<p><strong>Functions</strong></p>\n<p>The rewrite breaks the task into 3 parts.</p>\n<ul>\n<li><code>groupByScore</code> groups by score. Using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference\">Map</a> indexed by score to hold arrays of ids with each score. Returns the groups as the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference\">Map</a></li>\n<li><code>sortByScore</code> Takes the grouped results and sorts by score returning an array</li>\n<li><code>resultsByPlace</code> Takes an array of grouped results and returning an array of strings each containing the place, id, and score.</li>\n</ul>\n<p><strong>Constants</strong></p>\n<p>There are two constants that remove magic values from the code and moves them to one place at the top of the code.</p>\n<p>One of the constants is defined as a function <code>score2Str</code> and created the string eg <code>" has 1 point"</code></p>\n<p><strong>Util functions</strong></p>\n<p>Common tasks can be written as utility functions. These function can be part of a library of functions you can use within other projects. There is one Util function <code>pluralize</code> that adds a "s" when a value is not <code>!=</code> 1. It is defined as a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates\" rel=\"nofollow noreferrer\">tagged template</a> and can be used as a tagged template</p>\n<pre><code>pluralize` point${score}`\n</code></pre>\n<p>Or called as a function</p>\n<pre><code>pluralize([` point`], score)\n</code></pre>\n<p><strong>As modules</strong></p>\n<p>Thus we get the code as</p>\n<p>File <code>strings/utils.jsm</code></p>\n<pre><code>const pluralize = (strs, value) => strs[0] + (value != 1 ? "s" : "") + (strs[1] ? strs[1]: "");\nexport {pluralize};\n</code></pre>\n<p>File <code>studentResults.jsm</code></p>\n<pre><code>import {pluralize} from "./strings/utils.jsm";\n\nconst PLACINGS = ":First Place: ,:Second Place: ,:Thrid Place: ".split(",");\nconst score2Str = score => " has " + score + pluralize` point${score}`;\n\nfunction groupByScore(students) {\n const scoreGroups = new Map();\n Object.entries(students).forEach(([id, score]) => {\n const group = scoreGroups.get(score);\n if (group) { group.push(id) }\n else { scoreGroups.set(score, [id]) }\n });\n return scoreGroups;\n} \nfunction sortByScore(scoreGroups) {\n return [...scoreGroups.entries()].sort((gA, gB) => gB[0] - gA[0]);\n} \nfunction resultsByPlace(sorted, cats = PLACINGS, scoreStr = score2Str) {\n var idx = 0;\n const results = [];\n for (const [score, group] of sorted) {\n const cat = idx < cats.length ? cats[idx ++] : (idx ++, "");\n results.push(...group.map(id => cat + id + scoreStr(score)));\n }\n return results;\n}\nexport {groupByScore, sortByScore, resultsByPlace};\n</code></pre>\n<h3>As running example.</h3>\n<p>As CodeReview snippets do not support modules below is a working example compatible with CodeReview snippets.</p>\n<p>Code</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const pluralize = (strs, value) => strs[0] + (value != 1 ? \"s\" : \"\") + (strs[1] ? strs[1]: \"\");\nconst tag = (tag, props = {}) => Object.assign(document.createElement(tag), props);\nconst append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par);\n\n// Rewrite\nconst studentScores = {'Adam': 3, 'Bill': 5,'Cindy': 4, 'Dafney': 5, 'Eric': 4, 'Fred': 5, 'Graham': 4, 'Hillary': 4, 'Ian': 3, 'Jill': 1, 'Kev': 0};\nconst PLACINGS = \":First Place: ,:Second Place: ,:Thrid Place: \".split(\",\");\nconst score2Str = score => \" has \" + score + pluralize` point${score}`;\n\nconst results = resultsByPlace(sortByScore(groupByScore(studentScores)));\nappend(document.body, ...results.map(result => tag(\"div\",{textContent: result})));\nfunction groupByScore(students) {\n const scoreGroups = new Map();\n Object.entries(students).forEach(([id, score]) => {\n const group = scoreGroups.get(score);\n if (group) { group.push(id) }\n else { scoreGroups.set(score, [id]) }\n });\n return scoreGroups;\n}\nfunction sortByScore(scoreGroups) {\n return [...scoreGroups.entries()].sort((gA, gB) => gB[0] - gA[0]);\n}\nfunction resultsByPlace(sorted, cats = PLACINGS) {\n var idx = 0;\n const results = [];\n for (const [score, group] of sorted) {\n const cat = idx < cats.length ? cats[idx ++] : (idx ++, \"\");\n results.push(...group.map(id => cat + id + score2Str(score)));\n }\n return results;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:56:49.493",
"Id": "502993",
"Score": "0",
"body": "Can I ask, why do you say I should ABSOLUTELY use semicolons? I've never really learnt the use of them and code seems to work without it too, is it performance related?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T20:15:56.083",
"Id": "502997",
"Score": "0",
"body": "@ExcanatorGames JavaScript requires semicolons. Not using them and they will be inserted automatically ASI (Automatic Semicolon Insertion). There are many ambiguous situations where the parser will not put the semicolon where one would expect. This can result in very hard to spot bugs (may not throw errors) Unless you know of by heart how ASI inserts semicolons you risk code that does not work as expected. Using them ensures this will never happen. For details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:09:34.737",
"Id": "503001",
"Score": "0",
"body": "I see! thank you very much for the explanation!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:26:59.793",
"Id": "255016",
"ParentId": "254944",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255016",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:34:01.330",
"Id": "254944",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "grouping people with the same score"
}
|
254944
|
<p>I've defined a data structure which represents a doe_model, providing two maps with a <code>configuration_id</code> as key and a <code>configuration_model</code> as value. The configuration_model is an unordered_map which has a <code>knob_name</code> as key and a <code>knob_value</code> as value. There are things I don't like very much about this but I can't get a grasp on how I should change them. For instance: using the <code>next</code> and <code>get_next()</code> trick I'm forced to add a copy constructor and an assignment operator in order to get rid of the undefined behavior I would get by shallow copying the <code>next</code> iterator member. But I don't know if there's a better way to achieve what I need, which is: since I have a thread pool which concurrently access the doe data structure, I have to provide them the next configuration to explore in a smart way. So if I'm reaching the end of the configurations (and there are still some to use) I have to return them from the begin, until I've exhausted all of them.</p>
<p>Here's the code:</p>
<pre class="lang-cpp prettyprint-override"><code>using configuration_model = std::unordered_map<std::string, std::string>;
struct doe_model {
doe_model() {}
doe_model(const doe_model& doe)
{
required_explorations = doe.required_explorations;
number_of_explorations = doe.number_of_explorations;
next = required_explorations.end();
}
inline doe_model& operator=(const doe_model& ldoe)
{
required_explorations = ldoe.required_explorations;
number_of_explorations = ldoe.number_of_explorations;
next = required_explorations.end();
return *this;
}
inline bool add_config(const std::string &config_id,
const configuration_model &config,
const int required_number_of_observations) {
bool assignment_took_place =
!required_explorations.insert_or_assign(config_id, config).second ||
!number_of_explorations
.insert_or_assign(config_id, required_number_of_observations)
.second;
next = required_explorations.end();
return assignment_took_place;
}
inline void update_config(const std::string &config_id) {
number_of_explorations.at(config_id)--;
// remove the configuration in case we exausted all the explorations
if (number_of_explorations.at(config_id) <= 0)
remove_config(config_id);
}
inline void remove_config(const std::string &config_id) {
required_explorations.erase(config_id);
number_of_explorations.erase(config_id);
}
// this method returns the next configuration to explore
// NOTE: the caller MUST check the pointer first.
inline std::map<std::string, configuration_model>::iterator get_next() {
// we may have an empty map or one with only a single configuration left
if (required_explorations.empty() || next == required_explorations.end()) {
next = required_explorations.begin();
return next;
}
next++;
return next;
}
// key is the configuration_id
std::map<std::string, configuration_model> required_explorations;
std::map<std::string, configuration_model>::iterator next;
std::map<std::string, int> number_of_explorations;
};
</code></pre>
|
[] |
[
{
"body": "<p>Because you're defining your member functions within the class declaration, you don't need to use the <code>inline</code> keyword. All member functions declared in the class declaration are implicitly inline (including the default and copy constructors) are inline.</p>\n<p>In your copy constructor, you can make use of member initializers to construct the copied maps directly, rather than default construct and assign:</p>\n<pre><code>doe_model(const doe_model& doe): required_explorations(doe.required_explorations),\n next(required_explorations.end()), number_of_explorations(doe.number_of_explorations)\n}\n</code></pre>\n<p>There are a few places where you're using two statements but they can be combined.</p>\n<p>In <code>update_config</code>, you can decrement in the test:</p>\n<pre><code>if (--number_of_explorations.at(config_id) <= 0)\n</code></pre>\n<p>In <code>get_next</code>, you can combine the iterator increment and return statement:</p>\n<pre><code>return ++next;\n</code></pre>\n<p>This also uses the preincrement on the iterator, as it avoids creating a copy of the original iterator that is returned by the postincrement version, then immediately discarded.</p>\n<p>In <code>add_config</code>, you have the potential of adding a config with a higher number of required explorations than are provided if that config already exists (if <code>required_explorations</code> is assigned to, no change is made to <code>number_of_explorations</code>). This may or may not be a problem.</p>\n<p>You should consider adding a move constructor and a move assignment operator, which can avoid creating copies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:03:24.407",
"Id": "502883",
"Score": "0",
"body": "You're talking about a \"class\" declaration but this is a struct. Does it make any difference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:59:10.470",
"Id": "502907",
"Score": "0",
"body": "@Barnercart, no, it makes no difference. A class and a struct are both aggregate objects; the only difference is whether members (and bases) are `public` or `private` by default."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:33:38.947",
"Id": "254948",
"ParentId": "254946",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T11:06:49.660",
"Id": "254946",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Design of Experiments data structure with C++17"
}
|
254946
|
<p>Due to some bug somewhere, my speaker balance kept moving off-center and it was getting annoying. So I cobbled together the code below (based on <a href="https://stackoverflow.com/questions/27290751/using-audiotoolbox-from-swift-to-access-os-x-master-volume">this question</a>) which—to my surprise—<em>does</em> compile and run on macOS 11.1 / Swift 5.3.2.</p>
<p>I am a beginner and am trying to learn, trying to avoid errors and adhere to the DRY principle. I would also like to know if there are any glaring mistakes.</p>
<p>For example, I believe there is a way to make a single function that can return the default Audio Device as well as fetch properties from it, since there are a lot of similarities between <code>getDefaultOutputDevice()</code> and <code>aPropGet()</code></p>
<p>I also am not at all sure about the use of the <code>struct {...}</code> to declare "global" variables.</p>
<p>Can anyone please pass along any pointers?</p>
<p>To compile save the code below as <code>bal-reset.swift</code> and build with <code>swiftc -O bal_reset.swift</code></p>
<pre class="lang-swift prettyprint-override"><code>import AudioToolbox
import CoreAudio
import Foundation
// global variables
struct g {
static var deviceId: AudioDeviceID = 0
static var deviceName = "" as CFString
static var eq_balance: Float32 = 0.50 // 0.0 (left) through 1.0 (right)
}
func getDefaultOutputDevice() {
var aSize = UInt32(MemoryLayout.size(ofValue: g.deviceId))
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMaster)
var err = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&aSize,
&g.deviceId)
if (err == 0) {
address.mSelector = kAudioDevicePropertyDeviceNameCFString
aSize = UInt32(MemoryLayout.size(ofValue: g.deviceName))
err = AudioObjectGetPropertyData(
g.deviceId,
&address,
0,
nil,
&aSize,
&g.deviceName)
if (err == 0) {
print("dev:", String(g.deviceName) + " [" + String(g.deviceId) + "]")
} else {
print("dev:", g.deviceId)
}
} else {
print("error [" + String(err) + "] could not determine output device")
exit(1)
}
}
getDefaultOutputDevice()
func aPropGet(selector: UInt32) -> (err: OSStatus, val: Float32) {
var val: Float32 = 0.0
var aSize = UInt32(MemoryLayout.size(ofValue: val))
var address = AudioObjectPropertyAddress(
mSelector: selector,
mScope: kAudioObjectPropertyScopeOutput,
mElement: kAudioObjectPropertyElementMaster
)
let err = AudioObjectGetPropertyData(
g.deviceId,
&address,
0,
nil,
&aSize,
&val)
return (err, val)
}
func setBalance(selector: UInt32) -> OSStatus {
let aSize = UInt32(MemoryLayout.size(ofValue: g.eq_balance))
var address = AudioObjectPropertyAddress(
mSelector: selector,
mScope: kAudioObjectPropertyScopeOutput,
mElement: kAudioObjectPropertyElementMaster
)
let err = AudioObjectSetPropertyData(
g.deviceId,
&address,
0,
nil,
aSize,
&g.eq_balance)
return err
}
func getBalance() -> (err: OSStatus, val: Float32) {
var res = aPropGet(selector: kAudioDevicePropertyStereoPan)
if (res.err != 0) {
res = aPropGet(selector: kAudioHardwareServiceDeviceProperty_VirtualMasterBalance)
}
return (res.err, res.val)
}
var res = aPropGet(selector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume)
if (res.err == 0) {
print("vol:", String(format: "%.0f", res.val*100))
}
res = getBalance()
switch res.err {
case 0:
print("old:", String(format: "%.2f", res.val))
case kAudioCodecUnknownPropertyError:
print("device does not support balance adjustment")
exit(0)
default:
print("unknown error [" + String(res.err) + "] while trying to query balance")
exit(1)
}
switch res.val {
case 0.5:
exit(0)
default:
var bal = setBalance(selector: kAudioDevicePropertyStereoPan)
if (bal != 0) {
bal = setBalance(selector: kAudioHardwareServiceDeviceProperty_VirtualMasterBalance)
}
switch bal {
case 0:
print("new:", String(format: "%.2f", g.eq_balance))
exit(0)
default:
print("error [" + String(bal) + "] while trying to set balance")
exit(1)
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Use string interpolation:</strong></p>\n<pre><code>"unknown error [" + String(res.err) + "] while trying to query balance"\n</code></pre>\n<p>is normally written like this:</p>\n<pre><code>"unknown error [\\(String(res.err))] while trying to query balance"\n</code></pre>\n<p><strong>Split out functions into pieces dealing with different issues</strong></p>\n<p>For example, your getDefaultOutputDevice function has lines to do with the mechanics of calling the API (MemoryLayout.size(ofValue... etc), and lines to do with dealing with errors (print error... etc)</p>\n<p>Splitting those things up into separate pieces unlocks the parts</p>\n<p>Use a suitable existing type or make new ones, to avoid global scope.\nYour struct "g" can be avoided completely by sticking to functions that return values. I would be wary about storing any of the values you read back from the system, like the name or the value of the balance etc because they are volatile and can change without you changing them, so for example, if name is always read afresh each time you need it then it's never stale data.</p>\n<p>Here is how you might <strong>use generics</strong> to wrap the get and set calls:</p>\n<pre><code>import AudioToolbox\nimport CoreAudio\nimport Foundation\n\n// The API uses AudioObjectPropertyAddress structs\n// Let's make some helpers to make working with these struts easier.\nextension AudioObjectPropertyAddress {\n\n /// We have to use backticks here because we want to use a swift keyword\n /// for our variable name, or we could call it something else like defaultOutput\n static var `default`: Self {\n .init(\n mSelector: kAudioHardwarePropertyDefaultOutputDevice,\n mScope: kAudioObjectPropertyScopeGlobal,\n mElement: kAudioObjectPropertyElementMaster)\n }\n \n static var masterOutput: Self {\n .init(\n mSelector: kAudioHardwarePropertyDefaultOutputDevice,\n mScope: kAudioObjectPropertyScopeOutput,\n mElement: kAudioObjectPropertyElementMaster)\n }\n \n /// Take our existing self, and return a new struct with just the scope\n /// different\n func scoped(_ s: AudioObjectPropertyScope) -> Self {\n .init(mSelector: mSelector, mScope: s, mElement: mElement)\n }\n \n /// same for element etc\n func elemented(_ e: AudioObjectPropertyScope) -> Self {\n .init(mSelector: mSelector, mScope: mScope, mElement: e)\n }\n \n func selectored(_ s: AudioObjectPropertySelector) -> Self {\n .init(mSelector: s, mScope: mScope, mElement: mElement)\n }\n}\n\n/// With these helpers in place we can be more consise at the call site,\n/// transforming these values to say something like default master output, but selecting\n/// the balance property\n//let example = AudioObjectPropertyAddress\n// .default\n// .selectored(kAudioHardwareServiceDeviceProperty_VirtualMasterBalance)\n\n\n/// The API emits errors, so wrapping it to make it more Swifty, I wrap those OSStatus errors\n/// in swift's Error\nstruct OSStatusError: Swift.Error {\n var value: Int32\n}\n\n\n/// The audio API likes to use inout arguments. These functions are of a type\n/// f(address, inout Something)\n/// these can always be converted into equivalent functions but of type f(address, something) -> something\n/// and that can make them easier to work with\n/// the pattern to use it is:\n/// make a new Float or something, pass that into GetPropertyData, check for errors\n/// let's wrap the noise involved in making one of these calls:\nextension AudioObjectID {\n /// We have to use a generic here because the function can deal with any type of\n /// data from AudioObject\n func get<T>(_ address: AudioObjectPropertyAddress,\n v: inout T) throws {\n var addr = address\n var size = UInt32(MemoryLayout.size(ofValue: v))\n let err = AudioObjectGetPropertyData(self, &addr, 0, nil, &size, &v)\n \n if err != 0 {\n throw OSStatusError(value: err)\n }\n }\n \n /// And we prefer using the f(A, V) -> V style rather than the f(A, inout V) style\n /// so let's make that\n func get<T>(_ address: AudioObjectPropertyAddress,\n v: T) throws -> T {\n var intoV = v\n \n try get(address, v: &intoV)\n \n return intoV\n }\n\n /// Set is similar, you can make this be like f(A, X) -> X if you want\n /// typically a setter would return void but there is the chance that the value is\n /// set to something other than the value you specified\n func set<T>(_ address: AudioObjectPropertyAddress,\n v: inout T) throws {\n var address = address\n let size = UInt32(MemoryLayout.size(ofValue: v))\n \n let err = AudioObjectSetPropertyData(self, &address, 0, nil, size, &v)\n \n if err != 0 {\n throw OSStatusError(value: err)\n }\n }\n}\n\n\n/// With that in place we can extend an existing type, to make it more ergonomic to use\nextension AudioDeviceID {\n static func defaultOutput() throws -> Self {\n try AudioObjectID(kAudioObjectSystemObject)\n .get(.default,\n v: AudioObjectID()) // Here we have to instantiate an instance of the type\n // that's then used in the inout getting dance\n }\n\n func name() throws -> String {\n try get(AudioObjectPropertyAddress\n .default\n .selectored(kAudioDevicePropertyDeviceNameCFString),\n v: "" as CFString) as String\n }\n \n func balance() throws -> Float {\n try get(AudioObjectPropertyAddress\n .masterOutput\n .selectored(kAudioHardwareServiceDeviceProperty_VirtualMasterBalance),\n v: Float(0))\n }\n \n func setBalance(_ target: Float) throws -> Float {\n let existing = try balance()\n guard existing != target else {\n return existing\n }\n \n var result = target\n try set(AudioObjectPropertyAddress\n .masterOutput\n .selectored(kAudioHardwareServiceDeviceProperty_VirtualMasterBalance),\n v: &result)\n return result\n }\n}\n\n/// With all these helpers in place, and with the throwing and catching,\n/// our program now reads like what it does\ndo {\n try AudioDeviceID.defaultOutput().setBalance(0.5)\n}\ncatch {\n print(error)\n exit(1)\n}\n</code></pre>\n<p><strong>Using throwing functions</strong> cleans up the code, there is one place where we deal with any errors.</p>\n<p>Overall, we split a function like getDefaultOutputDevice(andPrintErrors...) into pieces that deal with getting stuff from the audio api, the default device, and handling errors, and that breaking stuff up is normally a good idea. Avoid side effects in functions too, like your print(error)/exit in getDefaultOutputDevice, these side effects make the functions harder to test and harder to combine together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T12:52:14.877",
"Id": "255216",
"ParentId": "254952",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T14:36:09.120",
"Id": "254952",
"Score": "3",
"Tags": [
"swift",
"audio",
"macos",
"foundation"
],
"Title": "macOS: resetting balance to center (0.5) using Swift"
}
|
254952
|
<p>While trying to grasp the potentials of the collection features in F#, I encountered this one:</p>
<pre><code>let needSpecialDocument country = (not country.IsEea) && (not country.IsInSchengen)
// could also be: not (country.IsEea || country.IsInSchengen)
let wantToMoveTo country = country.Name = "CC"
let potentialDestinations =
countries
|> Seq.filter needSpecialDocument2
|> Seq.filter wantToMoveTo
</code></pre>
<p>Is there a way to combine the two filters into one? I managed the one below but it feels like there is a more <em>fsharpish</em> way to do so..</p>
<pre><code>|> Seq.filter (fun c -> (needSpecialDocument c) && (wantToMoveTo c))
</code></pre>
<p>Test data:</p>
<pre><code>type Country = {Name : string; IsEea : bool; IsInSchengen : bool}
let uk = {Name = "UK"; IsEea = false; IsInSchengen = false}
let ir = {Name = "IR"; IsEea = true; IsInSchengen = false}
let fr = {Name = "FR"; IsEea = true; IsInSchengen = true}
let ch = {Name = "CH"; IsEea = false; IsInSchengen = true}
let cc = {Name = "CC"; IsEea = false; IsInSchengen = false}
let countries = [uk;ir;fr;ch;cc]
</code></pre>
|
[] |
[
{
"body": "<p>Nope, that's pretty much the way.</p>\n<p>If you really, really want to make this shorter and less cluttered, and if you face similar situations multiple times in your codebase, you could make yourself a special operator for combining predicates:</p>\n<pre><code>let (.&&.) f g c = f c && g c\n</code></pre>\n<p>Then you can use this operator in your filter:</p>\n<pre><code>|> Seq.filter (needSpecialDocument .&&. wantToMoveTo)\n</code></pre>\n<p>But base on my own experience I wouldn't advise this. You make the program slicker and cooler looking, but you're losing some readability. Now whoever reads your program will have to look up the meaning of <code>.&&.</code>. Programs are read more often than they are written.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:45:08.573",
"Id": "254955",
"ParentId": "254954",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254955",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:21:34.797",
"Id": "254954",
"Score": "0",
"Tags": [
"f#"
],
"Title": "How to apply multiple filters in one statement"
}
|
254954
|
<p>I'm 13 years old and turning 14 years soon! I Coded this simple text game in around 30 minutes, can someone rate it? and give some feedback</p>
<pre><code>import random
import time
current_coin = 500
def play():
computer2 = random.choice(['r','p','s'])
computer1 = random.choice(['r','p','s'])
if computer2 == computer1:
return 'tie'
if is_win(computer2, computer1):
return 'computer2 wins!!'
if is_lose(computer2, computer1):
return 'computer1 wins!!'
else:
return 'it looks like you made a typo! try again'
def is_win(computer2, computer1):
if (computer2 == "r" and computer1 == "s") or (computer2 == "s" and computer1 == "p") or (computer2 == "p" and computer1 == 'r'):
return True
def is_lose(computer2, computer1):
if (computer2 == "s" and computer1 == "r") or (computer2 == "p" and computer1 == "s") or (computer2 == "r" and computer1 == 'p'):
return True
while True:
print('welcome to rock paper scissors betting simulator!\n')
time.sleep(1)
print('1 = computer1\n')
time.sleep(1)
print('2 = computer2\n')
time.sleep(1)
beton = str(input('please type 1 or 2 to bet! \n'))
coinbet = str(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\n'))
if int(str(coinbet)) > int(current_coin):
print('you dont have that much?\n')
coinbet = str(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\n'))
else:
print('you betted ' + str(int(coinbet)) + ' !')
result = play()
time.sleep(0.1)
if result == 'tie':
print('welp! they tied! you have ' + str(int(current_coin)) + ' left!!\n')
if result == 'computer2 wins!!':
print('welp, since computer2 won. . .\n')
if beton == '1':
print('you lost! you now have ' + str(int(current_coin) - int(coinbet)) + '!!')
current_coin = current_coin - int(coinbet)
if beton == '2':
print('you won! you now have ' + str(int(current_coin) + int(coinbet)) + '!!')
current_coin = current_coin + int(coinbet)
if result == 'computer1 wins!!':
print('welp, since computer1 won. . .\n')
if beton == '2':
print('you lost! you now have ' + str(int(current_coin) - int(coinbet)) + '!!')
current_coin = current_coin - int(coinbet)
if beton == '1':
print('you won! you now have ' + str(int(current_coin) + int(coinbet)) + '!!')
current_coin = current_coin + int(coinbet)
if current_coin <= 0:
print('you have no coins left! what a loser!')
break
</code></pre>
|
[] |
[
{
"body": "<p>Good start! I like that <code>is_win()</code> and <code>is_lose()</code> are separate functions. They could be improved by returning the boolean directly. In general, if you have code that looks like <code>if condition: return True else: Return False</code>, it can be written as <code>return condition</code> directly.</p>\n<p>Also, <code>is_lose()</code> can be written as <code>is_win()</code> with the parameters swapped</p>\n<pre><code>def is_win(computer2, computer1):\n return (\n (computer2 == "r" and computer1 == "s") or \n (computer2 == "s" and computer1 == "p") or \n (computer2 == "p" and computer1 == 'r')\n )\n\ndef is_lose(computer2, computer1):\n return is_win(computer1,computer2)\n</code></pre>\n<p>This breaks if the user enters an invalid amount the second time.</p>\n<pre><code>beton = str(input('please type 1 or 2 to bet! \\n'))\ncoinbet = str(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\\n'))\nif int(str(coinbet)) > int(current_coin):\n print('you dont have that much?\\n')\n coinbet = str(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\\n'))\nelse:\n print('you betted ' + str(int(coinbet)) + ' !')\n</code></pre>\n<p>This would not be an issue if it was written like so:</p>\n<pre><code>coin_bet = None\nwhile coin_bet == None:\n coin_bet_attempt = int(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\\n'))\n if coin_bet_attempt > current_coin:\n print("You don't have that much?")\n else:\n coin_bet = coin_bet_attempt\nprint('you betted ' + str(coin_bet) + ' !')\n</code></pre>\n<p>Better yet, one could write a function that ONLY exits when a valid input occurs.</p>\n<pre><code>def get_coin_bet_from_user(current_coin):\n while True:\n bet = int(input('you currently have ' + str(int(current_coin)) + ' coins! how much would you like to bet!!\\n'))\n if bet > current_coin:\n print("You don't have that much?")\n else:\n return bet\n\n# called like so\ncoinbet = get_coin_bet_from_user(current_coin)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T18:45:08.970",
"Id": "254962",
"ParentId": "254959",
"Score": "3"
}
},
{
"body": "<p>Your</p>\n<pre><code>def is_win(computer2, computer1):\n if (computer2 == "r" and computer1 == "s") or (computer2 == "s" and computer1 == "p") or (computer2 == "p" and computer1 == 'r'):\n return True\n</code></pre>\n<p>could be shorter (and always return a <code>bool</code>, instead of <code>True</code> or <code>None</code>):</p>\n<pre><code>def is_win(computer2, computer1):\n return (computer2, computer1) in [('r', 's'), ('s', 'p'), ('p', 'r')]\n</code></pre>\n<p>or</p>\n<pre><code>def is_win(computer2, computer1):\n return computer2 + computer1 in ['rs', 'sp', 'pr']\n</code></pre>\n<p>or</p>\n<pre><code>def is_win(computer2, computer1):\n return computer2 + computer1 in 'rspr'\n</code></pre>\n<p>Not sure why you have this:</p>\n<pre><code> else:\n return 'it looks like you made a typo! try again'\n</code></pre>\n<p>How is that ever supposed to be reached? Both <code>computer2</code> and <code>computer1</code> are <code>random.choice(['r','p','s'])</code>, which doesn't make typos.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T19:10:27.057",
"Id": "254963",
"ParentId": "254959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T18:24:23.147",
"Id": "254959",
"Score": "2",
"Tags": [
"python",
"beginner"
],
"Title": "Coin-flipping game"
}
|
254959
|
<p>I am testing a Spring boot service using JUnit 5 and Mockito. I haven't spent much time on unit testing in the past so I'm not sure if I'm accidentally implementing an anti-pattern or not following best practices.</p>
<p>I read multiple times that it's good practice to have one assertion per test, I have one assertion but I also have a few verify assertions that check if the method I'm testing called the correct methods with the correct input based on the conditional branch I'm testing as well as the input to the method I'm testing, is this OK/acceptable or should I split it up into one assertion/verify assertion per test? It feels like that would require a lot of code duplication... Below are four tests I wrote and the method I'm testing. For clarity I'll also add the code that sets up and handles my test application context.</p>
<p>Any ideas/advice would be much appreciated.</p>
<p>The method I am testing:</p>
<pre><code>@Transactional
override fun startSession(msisdn: String, origConnID: String, configSetName: String): StartSessionResponseDTO {
val txId = generateTxID()
val ss = sessionStatus(msisdn)
eventService.logEvent(EventType.StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
if (ss == null) {
throw ApplicationException(type = ApplicationException.Type.client_error, message = "Concurrent Access Detected: ${msisdn}")
} else {
if (ss.sessionId == null || ss.ip == null) {
//create new Nuance session
nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {
updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)
}
} else {
//check if the sessionId is still valid
if (!nuanceService.isSessionValid(txId = txId, msisdn = msisdn, sessionId = ss.sessionId, host = ss.ip, configSetName = configSetName)) {
nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {
updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)
}
}
}
}
eventService.logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
return StartSessionResponseDTO(msisdn)
}
</code></pre>
<p>My test class:</p>
<pre><code>@ExtendWith(SpringExtension::class)
@ContextConfiguration()
class VBServiceTests() {
@TestConfiguration
class testConfig {
@Bean
fun jdbcTemplate(): NamedParameterJdbcTemplate {
return mock<NamedParameterJdbcTemplate>()
}
@Bean
fun nuanceService(): NuanceService {
return mock<NuanceService>()
}
@Bean
fun appConfigProps(): AppConfigProps {
return mock<AppConfigProps>()
}
@Bean
fun eventService(): EventServiceImp {
return mock<EventServiceImp>()
}
@Bean
fun audioTrimService(): AudioTrimService {
return mock<AudioTrimService>()
}
@Bean
fun vbNuanceStagingDeletionService(): VbNuanceStagingDeletionsService {
return mock<VbNuanceStagingDeletionsService>()
}
}
@MockBean
lateinit var nuanceService: NuanceService
@MockBean
lateinit var eventService: EventServiceImp
@SpyBean
lateinit var vbServiceSpy: VbServiceImp
val msisdn = "0821234567"
val origConnID = "o123"
val sessionId = "0821234567"
val ip = "127.0.0.1"
val txId = "1234-5678"
val configSetName = "LoIvrPhraIvrHdr"
@Test
fun `startSession | When method is called with valid input a StartSessionDTO is returned, if no Nuance session exists a new Nuance session will be created and persisted`() {
doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
doReturn(txId).whenever(vbServiceSpy).generateTxID()
doReturn(SessionStatus(msisdn, origConnID, null, null)).whenever(vbServiceSpy).sessionStatus(msisdn)
given(nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))).willReturn(NuanceStartSessionRespDto(txId, sessionId, ip))
assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
verify(vbServiceSpy).generateTxID()
verify(vbServiceSpy).sessionStatus(msisdn)
verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
verify(nuanceService).startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))
verify(vbServiceSpy).updateSession(msisdn = msisdn, sessionId = sessionId, ip = ip, origConnID = origConnID)
verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
}
@Test
fun `startSession | When method is called with valid input a StartSessionDTO is returned, if existing valid Nuance session exists the existing session will be used`() {
doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
doReturn(txId).whenever(vbServiceSpy).generateTxID()
doReturn(SessionStatus(msisdn, origConnID, sessionId, ip)).whenever(vbServiceSpy).sessionStatus(msisdn)
given(nuanceService.isSessionValid(txId, msisdn, sessionId, ip, configSetName)).willReturn(true)
assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
verify(vbServiceSpy).generateTxID()
verify(vbServiceSpy).sessionStatus(msisdn)
verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
}
@Test
fun `startSession | When method is called with valid input a StartSessionDTO is returned, if existing invalid Nuance session exists a new session will be created and the existing session record will be updated`() {
doNothing().whenever(vbServiceSpy).updateSession(msisdn, origConnID, sessionId, ip)
doReturn(txId).whenever(vbServiceSpy).generateTxID()
doReturn(SessionStatus(msisdn, origConnID, sessionId, ip)).whenever(vbServiceSpy).sessionStatus(msisdn)
given(nuanceService.isSessionValid(txId, msisdn, sessionId, ip, configSetName)).willReturn(false)
given(nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))).willReturn(NuanceStartSessionRespDto(txId, sessionId, ip))
assertThat(vbServiceSpy.startSession(msisdn, origConnID, configSetName), Is(StartSessionResponseDTO(msisdn)))
verify(vbServiceSpy).generateTxID()
verify(vbServiceSpy).sessionStatus(msisdn)
verify(eventService).logEvent(StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))
verify(nuanceService).startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName))
verify(vbServiceSpy).updateSession(msisdn = msisdn, sessionId = sessionId, ip = ip, origConnID = origConnID)
verify(eventService).logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)
}
@Test()
fun `startSession - When method is called with valid input when sessionStatus returns null concurrent access is detected and an ApplicationException gets thrown`() {
doReturn(txId).whenever(vbServiceSpy).generateTxID()
doReturn(null).whenever(vbServiceSpy).sessionStatus(msisdn)
val exception = Assertions.assertThrows(ApplicationException::class.java) {
vbServiceSpy.startSession(msisdn, origConnID, configSetName)
}
assertThat(exception.message, Is("Concurrent Access Detected: ${msisdn}"))
verify(vbServiceSpy).generateTxID()
verify(vbServiceSpy).sessionStatus(msisdn)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:21:47.300",
"Id": "503597",
"Score": "0",
"body": "You could run your tests using `MockitoExtension` rather than `SpringExtension` if your code is well unit testable. Your tests will run faster. In addtion you may try to not overuse `verify`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T08:37:44.533",
"Id": "504937",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h1>Some Concepts</h1>\n<p>I'm not much experienced in the framework used but Unit Testing, Test Driven Development and Behavioral Driven Development are concepts that need to be understood well and then implemented properly.</p>\n<h3>Unit Test Definition by Michael Feathers</h3>\n<p>I've used these rules with a large number of teams. They encourage good\ndesign and rapid feedback and they seem to help teams avoid a lot of\ntrouble.</p>\n<p>A test is <strong>NOT</strong> a unit test if:</p>\n<ul>\n<li>It talks to the database</li>\n<li>It communicates across the network</li>\n<li>It touches the file system</li>\n<li>It can't run correctly at the same time as any of your other unit tests</li>\n<li>You have to do special things to your environment (such as editing\nconfig files) to run it.</li>\n</ul>\n<p>Tests that do things things aren't bad. Often they are worth writing,\nand they can be written in a unit test harness. However, it is\nimportant to be able to separate them from true unit tests so that we\ncan keep a set of tests that we can run fast whenever we make our changes.</p>\n<hr />\n<h3>The Three Laws of TDD by Robert Martin</h3>\n<ul>\n<li><p>First Law : You may not write production code until you have written a failing unit test.</p>\n</li>\n<li><p>Second Law : You may not write more of a unit test than is sufficient to fail, and not compiling is failing.</p>\n</li>\n<li><p>Third Law : You may not write more production code than is sufficient to pass the currently failing test.</p>\n</li>\n</ul>\n<p>Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only. This is opposed to software development that allows software to be added that is not proven to meet requirements. - Wiki</p>\n<hr />\n<h3>BDD</h3>\n<p>Behavior-Driven Development is a software development process that puts feature behaviors first. A behavior is how a feature operates within a well-defined scenario of inputs, actions, and outcomes. Behaviors are identified using specification by example. Behavior specs become the requirements, the acceptance criteria, and the acceptance tests. Test frameworks can directly automate specs as well – declarative specs for unique product behaviors should be the units of coverage. The most prevalent BDD test frameworks are Cucumber derivatives that write specs in the “Given-When-Then” Gherkin language.</p>\n<pre><code>Given steps should use past or present-perfect tense, because they represent an initial state that must already be established.\nWhen steps should use present tense, because they represent actions actively performed as part of the behavior.\nThen steps should use present or future tense, because they represent what should happen after the behavior actions.\n</code></pre>\n<p>Good example, clear, short and precisely does check one behavior.</p>\n<p>Feature: Google Searching</p>\n<p>Scenario: Search result linking</p>\n<pre><code> Given Google search results for "panda" are shown\n When the user clicks the first result link\n Then the page for the chosen result link is displayed\n</code></pre>\n<hr />\n<h3>Red Green Refactor by James Shore</h3>\n<ul>\n<li><p>Think: Figure out what test will best move your code towards completion. (Take as much time as you need. This is the hardest step for beginners.)</p>\n</li>\n<li><p>Red: Write a very small amount of test code. Only a few lines... usually no more than five. Run the tests and watch the new test fail: the test bar should turn red. (This should only take about 30 seconds.)</p>\n</li>\n<li><p>Green: Write a very small amount of production code. Again, usually no more than five lines of code. Don't worry about design purity or conceptual elegance. Sometimes you can just hardcode the answer. This is okay because you'll be refactoring in a moment. Run the tests and watch them pass: the test bar will turn green. (This should only take about 30 seconds, too.)</p>\n</li>\n<li><p>Refactor: Now that your tests are passing, you can make changes without worrying about breaking anything. Pause for a moment. Take a deep breath if you need to. Then look at the code you've written, and ask yourself if you can improve it. Look for duplication and other "code smells." If you see something that doesn't look right, but you're not sure how to fix it, that's okay. Take a look at it again after you've gone through the cycle a few more times. (Take as much time as you need on this step.) After each little refactoring, run the tests and make sure they still pass.</p>\n</li>\n<li><p>Repeat: Do it again. You'll repeat this cycle dozens of times in an hour. Typically, you'll run through several cycles (three to five) very quickly, then find yourself slowing down and spending more time on refactoring. Than you'll speed up again. 20-40 cycles in an hour is not unreasonable.</p>\n</li>\n</ul>\n<p>This process works well for two reasons. First, you're working in baby steps, constantly forming hypotheses and checking them. ("The bar should turn red now... now it should turn green... now it should still be green... now it should be red...") Whenever you make a mistake, you catch it right away. It's only been a few lines of code since you made the mistake, which makes the mistake very easy to find and fix. We all know that finding mistakes, not fixing them, is the most expensive part of programming.</p>\n<p>The other reason this process works well is that you're always thinking about design. Either you're deciding which test you're going to write next, which is an interface design process, or you're deciding how to refactor, which is a code design process. All of this thought on design is immediately tested by turning it into code, which very quickly shows you if the design is good or bad.</p>\n<hr />\n<h3>Reasons to Use Mocks by Baeldung</h3>\n<p>We’ll start assuming that you already code following some driven development methodology centered on tests (TDD, ATDD or BDD). Or simply that you want to create a test for an existing class that relies on dependencies to achieve its functionality.</p>\n<p>In any case, when unit-testing a class, we want to test only its functionality and not that of its dependencies (either because we trust their implementation or because we’ll test it ourselves).</p>\n<p>To achieve this, we need to provide to the object-under-test, a replacement that we can control for that dependency. This way we can force extreme return values, exception throwing or simply reduce time-consuming methods to a fixed return value.</p>\n<p>This controlled replacement is the mock, and it will help you to simplify test coding and to reduce test execution time.</p>\n<hr />\n<h1>Function Retrospect</h1>\n<pre><code>@Transactional\n override fun startSession(msisdn: String, origConnID: String, configSetName: String): StartSessionResponseDTO {\n \n val txId = generateTxID()\n val ss = sessionStatus(msisdn)\n\n eventService.logEvent(EventType.StartSessionRequest, txId, msisdn, hashMapOf("extTxId" to origConnID))\n\n if (ss == null) {\n throw ApplicationException(type = ApplicationException.Type.client_error, message = "Concurrent Access Detected: ${msisdn}")\n } else {\n if (ss.sessionId == null || ss.ip == null) {\n //create new Nuance session\n nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {\n updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)\n }\n } else {\n //check if the sessionId is still valid\n if (!nuanceService.isSessionValid(txId = txId, msisdn = msisdn, sessionId = ss.sessionId, host = ss.ip, configSetName = configSetName)) {\n nuanceService.startSession(NuanceStartSessionReqDto(txId, msisdn, configSetName = configSetName)).let {\n updateSession(msisdn = msisdn, sessionId = it.sessionId, ip = it.ip, origConnID = origConnID)\n }\n }\n }\n }\n\n eventService.logEvent(type = EventType.StartSessionResponse, txId = txId, msisdn = msisdn)\n return StartSessionResponseDTO(msisdn)\n }\n</code></pre>\nProbable Code Modifications\n<ul>\n<li><p>This function has too many if else condition. Probably break those into smaller units so that those can be Unit tested.</p>\n</li>\n<li><p>As the function is just related to starting session, Transaction ID generation dependency could be moved out of the functions scope, and passed as an input.</p>\n</li>\n<li><p>I can see a Session Class which has the variables those passes in the startSession().</p>\n<p>Class Session {\nmsisdn: String\norigConnID: String\nconfigSetName: String\ntransactionID: String\nsessionStatus: boolean</p>\n<pre><code>public Session( ALL VARIABLES ) {\n // INITIALIZE ALL VARIABLES \n} \n</code></pre>\n<p>}</p>\n</li>\n</ul>\n<p>I think startSession() is doing a lot of things. Divide and conquer.\nThe other purpose of writing test is also to find smaller functionalities which might be independent from other. With the logic, it also gives us the opportunity to check whether the datastructure and algorithms implemnted were proper previously. So the more test cases we create, cleaner our thought about what exactly the function should be doing.</p>\n<hr />\n<h1>Behavior Test Retrospect</h1>\n<p>From the first glance, the scenarios are not clear as thedefinitions are too long.</p>\n<p>fun <code>startSession | When method is called with valid input a StartSessionDTO is returned, if no Nuance session exists a new Nuance session will be created and persisted</code>() { }</p>\n<p>TO</p>\n<p>fun <code>Starts session successfully when no Nuance session exists</code></p>\n<p>fun <code>Session fails to start when msisdn exists</code></p>\n<p>fun <code>Session fails to start when Nuance session exists</code></p>\n<p>We want our test to complete fast and fail fast. The comparision of object is never a good idea. So it would be better to assert values as much as possible. Further more the number of assertions should not be more as more assertions indicates that the function is doing a lot of things, and the verification of some of those assestions needs separate function and their test.</p>\n<p>There seems to be just one of data, probably because of one scenario. It would be better to have as much varied data as possible as the data represents the test cases.</p>\n<hr />\n<p><strong>Understanding of CLEAN code and SOLID principle would be much helpful.</strong></p>\n<p>I hope the explanation is not too much long and useful to you.</p>\n<p>Cheers,</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T12:28:26.253",
"Id": "503659",
"Score": "0",
"body": "Good answer in general! But this point \"A test is NOT a unit test if:\" yields several sometime quite vague sub-points since in doubt it depends on the modularization, orthogonality and granularity level of the testing software component itself whether one should define it as a unit or rather an integration test. In doubt, the software design (and possible flaws here) itself determines the character of several test approaches, they are often not really fully separable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T13:43:50.937",
"Id": "503664",
"Score": "0",
"body": "@Secundi Thank you for reviewing my answer.\n\"A test is NOT a unit test if:\" That's the definition by a veteran in the industry. I'm sorry but I can't modify that. The nature of the software test in itself is an integral part in oveall SDLC process so I agree with your thought on idea of software design.\nThe answer does points to the necessary areas where the code and even the design of the software at hand on how it can be improved, the main part of review, and leaves the room for the developer to improve and implement their understanding. But it depends on the developer in the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T13:59:30.820",
"Id": "503665",
"Score": "0",
"body": "yes, I'm totally aware of this. Just wanted to mention that quite often, even experienced developers sometimes tend to prioritize focus on the pure testing-side instead of reviewing the own code for a high level of test-compatibility in terms of robust design decisions. Think of the often questionable usage of singletons for instance. In order to achieve a \"quite robust\" unit testing scheme, often questionable workarounds on the testing side are applied instead of redesigning the actual code that is tested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:13:36.810",
"Id": "503667",
"Score": "0",
"body": "Red-Green-Refactor is there for process improvement, that includes the systems design with the test code @Secundi. The purpose of review is a part of that process as well. And those are the basic foundations everyone adheres, experienced or fresher, it does not matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:05:48.963",
"Id": "503694",
"Score": "0",
"body": "@Anit Shrestha Manandhar thanks for the very detailed answer. This is a legacy application and refactoring isn't really an option at this stage as then we'll have to go through another test cycle etc... Regarding the assert and verify assertions in one test method, is this acceptable given the legacy code? Or am I missing something big/important?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T06:38:30.723",
"Id": "503730",
"Score": "0",
"body": "@user2094257 Doing a full TDD/BDD is difficult in a monolithic legacy application but that's the next step. As we have the opportunity/time to review the code, it is wise to refactor where possible. What this will do is give you confidence when you are writing the functional tests, and which you have started to do already. And that is really important as those functional/behavioral tests as these harness tests improves confidence of the entire team as we have something to assure us what used to work still works, the original functionalities are preserved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T06:43:07.783",
"Id": "503732",
"Score": "0",
"body": "@user2094257 We are not reengineering, it's just minor refactoring. The more we refactor the smaller parts, the more we get insightful knowledge of the systems inner working. \nRefactoring is not a random process and https://refactoring.com/catalog list many good ways to do it. \nWorking Effectively with Legacy Code by Michael Feathers book provides much insightful things which might be helpful to those who are working in legacy applications, in general every system will be legacy or will be seen as legacy, this book is useful."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T18:58:11.827",
"Id": "255258",
"ParentId": "254960",
"Score": "6"
}
},
{
"body": "<h1>One Assertion</h1>\n<p>I try to make sure that each of my tests is only testing one thing. However, that's not the same as there only being one assertion. Consider a method that takes in a list and returns a sorted version of the list. If I pass in an unsorted list of two items, then I can check that the correct sorted list has been returned by ensuring that the returned list has two items, item one has the correct value and item two has the correct value. That's three assertions, so it could be three tests. However you could take the view that the assertions are all related, so you only need one test. My preferred assertion framework AssertJ provides a helper method (<code>containsExactly</code>), so this can by a single assertion. Try to include only what's important to the test and not the bits that aren't.</p>\n<h1>Verify</h1>\n<pre><code>doReturn(null).whenever(vbServiceSpy).sessionStatus(msisdn)\n....\nverify(vbServiceSpy).sessionStatus(msisdn)\n</code></pre>\n<p>I consider this to be a bit of an anti-pattern. The <code>whenever</code> call knows more about it's arguments than it really needs to know, which sets up unnecessary duplication of knowledge in your tests and makes them more brittle than they need to be. When you are setting up your <code>doReturn</code>s, consider if you <em>really</em> need to know about the argument being supplied when deciding what to return. This can be the case when you need to have different return values for different parameters, however most of the time you can get away with using the <code>any()</code> matcher.</p>\n<pre><code>doReturn(null).whenever(vbServiceSpy).sessionStatus(any())\n</code></pre>\n<p>You already validate the correct value is being supplied to the call with your <code>verify</code>, you don't need to restrict the behaviour of your stub as well.</p>\n<h1>Duplication</h1>\n<p>When I'm structuring my tests, I try to avoid duplication of knowledge, rather than duplication of code. So, looking at your tests, all of them contain:</p>\n<pre><code>verify(vbServiceSpy).generateTxID()\n</code></pre>\n<p>To me, this is its own test (startSession generates a new transaction ID). Once you have that test, the other tests no longer need to explicitly verify it, they can assume it's tested elsewhere.</p>\n<p>All of you tests also have the corresponding:</p>\n<pre><code>doReturn(txId).whenever(vbServiceSpy).generateTxID()\n</code></pre>\n<p>Some of them care about the value <code>txId</code>, because they use it elsewhere in the test, however some of them like 'when method is called with invalid input' doesn't. Consider putting some of these repeated stubbings into a <code>BeforeTest</code> method. By using <code>any</code> for parameter matching and returning sensible defaults you can often remove a lot of noise from your test setups and the tests can focus on the individual sections of code that they are testing.</p>\n<p>So, you might have a test that validated that the generated transaction id is logged. The relevant bits from your tests would appear to be:</p>\n<pre><code>// Setup the service to return a known transaction id\ndoReturn("1111-9999").whenever(vbServiceSpy).generateTxID()\n\n// Invoke the code under test. Notice we don't need to assert anything\n// on the return value because for this test, we don't care what's returned\n// other tests care about that.\nvbServiceSpy.startSession(msisdn, origConnID, configSetName)\n\n// Verify that the known transaction id was passed to the log\n// with StartSessionRequest. This test doesn't care about the other\n// arguments.\nverify(eventService).logEvent(eq(StartSessionRequest), eq("1111-9999"), any(), any())\n</code></pre>\n<p>That's a three line test (assuming the <code>BeforeTest</code> has been stubbed correctly), that validates that the new transaction id is always logged when the method is called. You then don't need to worry about those bits in your other tests. At the moment you're testing this logging in 3 out of your 4 tests, even though the log takes place in all 4 of your scenarios, so there is a bit of a whole in your coverage, albeit one that you probably don't care about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T22:35:05.360",
"Id": "255829",
"ParentId": "254960",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T18:26:35.807",
"Id": "254960",
"Score": "4",
"Tags": [
"unit-testing",
"spring",
"kotlin",
"junit"
],
"Title": "Are these Unit tests OK or am I implementing an antipattern or not following best practices"
}
|
254960
|
<h2>Context</h2>
<p>As many of you may know I have a library that allows C++ objects to be <a href="https://codereview.stackexchange.com/q/11138/507">converted into JSON/YAML/BSON automatically</a> with a single declaration (see previous code reviews).</p>
<p>I am now (trying) using this to connect and send data to Mongo without the developer having to write any specific code to convert their C++ objects into BSON.</p>
<p>I also have a wrapper around a <a href="/q/131211">Socket</a> that makes it behave like a <code>std::iostream</code> so it can simply be used with <code>operator<<</code> and <code>operator>></code>. This <code>Socket</code> wrapper, when used in my Service Library <a href="/q/168793">(<code>Nissa</code>)</a>, allows thread (Co-Routine) switching when a read/write would block, thus making it very efficient.</p>
<h2>Usage Pattern</h2>
<p>I want to insert objects into <a href="/q/248419">Mongo</a> like this:</p>
<pre><code>struct Person
{
std::string name;
int age;
};
ThorsAnvil_MakeTraits(Person, name, age);
int main()
{
MongoConnection connection(DB, USER, PASSWORD); // Creates a connection
// It wraps a Socket stream described
// above but also sends all the
// handshaking and authentication required
// by Mongo.
// But you can think of it like a stream.
Person person{"Loki", 12};
using ThorsAnvil::DB::Mongo::make_CmdDB_Insert;
// This line below is what I am interested in.
// I will show you more usage below and how I though about implementing it
// with the code. Hoping for
connection << make_CmdDB_Insert(DB, "Collection", QueryOptions{}, person);
CmdDB_Reply reply;
connection >> reply;
}
</code></pre>
<h2>Usage of Insert</h2>
<p>I am using <code>Insert</code> as an example here. But there are several commands each with their own unique options. So I want to get some feedback on this idea before I go an implement everything for all the commands.</p>
<p>The Insert has the following extra optional parameters:
<a href="https://docs.mongodb.com/manual/reference/command/insert/#dbcmd.insert" rel="nofollow noreferrer">Full Details</a></p>
<ul>
<li><code>ordered</code><br />
Default: True<br />
Inserts are ordered.<br />
Method: <code>unordered()</code> => turns this off</li>
<li><code>writeConcern</code><br />
An object that defines how the object is written.<br />
Method: <code>setWriteConcern(int w = 1, bool j = false, std::time_t wtimeout = 0)</code></li>
<li><code>bypassDocumentValidation</code><br />
Default: false<br />
Validates the object being written to the connection.<br />
Method: <code>byPass()</code> => turn off validation (i.e. set param to true)</li>
<li><code>comment</code><br />
A string that will be written to different places in Mongo.<br />
Method: <code>setComment(std::string&& c)</code> add a comment</li>
</ul>
<p>Normally the default values are fine, but I do want the user to be able to modify them if required. The thing is that if they are not explicitly set, then I don't want to send the value over the wire (as there is a cost to convert them and write them to the socket). So I thought I could set it up like this:</p>
<p>If I try putting all the options in the constructor then it will lead to a proliferation of constructor methods. Which seems hard. So I want to try using option methods that return a reference to the object so they can be chained; like this:</p>
<pre><code>connection << make_CmdDB_Insert(DB, "Collection", QueryOptions{}, person)
.unordered()
.setComment("Hi there");
// etc Just add a call for each option you want to set.
// You should be able to use any combination of options
// in any order.
//
// The reason to do this is to avoid an explosion in constructors
// with different parameters in different orders.
//
// With Only 4 options there are 8 different constructors needed.
// With other commands (like Find) the number of options is 16
// Which would lead to thousands of constructors.
</code></pre>
<h2>Implementation</h2>
<p>Since this is code review. Here is my implementation.</p>
<p>Note: There is an underlying layer that is not provided here (for brevity). I will be positing all the code for a full review when it is done.</p>
CmdDB_Insert.h
<pre><code>#ifndef THORSANVIL_DB_MONGO_CMD_DB_INSERT_H
#define THORSANVIL_DB_MONGO_CMD_DB_INSERT_H
// https://docs.mongodb.com/manual/reference/command/insert/#dbcmd.insert
#include "CmdDB.h"
namespace ThorsAnvil::DB::Mongo
{
template<typename Document>
struct Insert
{
public:
Insert(std::string const& collection, Document const& doc);
void unordered();
void byPass();
void setWrieConcern(int w = 1, bool j = false, std::time_t wtimeout = 0);
void setComment(std::string&& c);
private:
// Allow Serialization code access to private members.
friend class ThorsAnvil::Serialize::Traits<Insert>;
friend class ThorsAnvil::Serialize::Filter<Insert>;
// What fields will not be serialized.
// Serialized if not in the filter or in the filter and value is true.
std::map<std::string, bool> filter = {{"ordered", false}, {"writeConcern", false}, {"bypassDocumentValidation", false}, {"comment", false}};
// Members that will be sent on the wire in BSON to mongo server.
std::string insert;
std::vector<Document> documents;
bool ordered = true;
WriteConcern writeConcern;
bool bypassDocumentValidation = false;
std::string comment;
};
// Wrapper around the CmdDB_Query object.
// This inherits from Op_Query:
// This handles the low level OP_QUERY object that contains the header and query flags.
//
// The CmdDB_Query
// This handles writing to the underlying connection object.
// Insert is the command it is writing (as defined above)
// Document: Is the user defined object that we are writing.
template<typename Document>
using CmdDB_Insert = CmdDB_Query<Insert<Document>>;
template<typename Document>
CmdDB_Insert<Document>
make_CmdDB_Insert(std::string const& db, std::string const& collection, QueryOptions&& options, Document const& doc)
{
using Document = typename std::iterator_traits<I>::value_type;
return CmdDB_Insert<Document>(db, collection, std::move(options), doc);
}
}
// Tells the serializing code to filter the member based on the member filter.
ThorsAnvil_Template_MakeFilter(1, ThorsAnvil::DB::Mongo::Insert, filter);
// Tells the serialization code what to send across the wire in BSON.
ThorsAnvil_Template_MakeTrait(1, ThorsAnvil::DB::Mongo::Insert, insert, documents, ordered, writeConcern, bypassDocumentValidation, comment);
#include "CmdDB_Insert.tpp"
#endif
</code></pre>
CmdDB_Insert.tpp
<pre><code>#ifndef THORSANVIL_DB_MONGO_CMD_DB_INSERT_TPP
#define THORSANVIL_DB_MONGO_CMD_DB_INSERT_TPP
#ifndef THORSANVIL_DB_MONGO_CMD_DB_INSERT_H
#error "This should only be included from CmdDB_Insert.h"
#endif
namespace ThorsAnvil::DB::Mongo
{
template<typename Document>
Insert<Document>::Insert(std::string const& collection, Document const& doc)
: insert(collection)
, documents(1, doc)
{}
template<typename Document>
void Insert<Document>::unordered()
{
ordered = false;
filter["ordered"] = true;
}
template<typename Document>
void Insert<Document>::byPass()
{
bypassDocumentValidation = false;
filter["bypassDocumentValidation"] = true;
}
template<typename Document>
void Insert<Document>::setWrieConcern(int w, bool j, std::time_t wtimeout)
{
writeConcern = WriteConcern{w, j, wtimeout};
filter["writeConcern"] = true;
}
template<typename Document>
void Insert<Document>::setComment(std::string&& c)
{
comment = c;
filter["comment"] = true;
}
}
#endif
</code></pre>
CmdDB.h
<pre><code>#ifndef THORSANVIL_DB_MONGO_CMD_DB_H
#define THORSANVIL_DB_MONGO_CMD_DB_H
// https://docs.mongodb.com/manual/reference/command/nav-crud/
#include "Op_Query.h"
#include "Op_Reply.h"
#include "ThorSerialize/SerUtil.h"
namespace ThorsAnvil::DB::Mongo
{
enum class ReadConcernLevel {local, available, majority, linearizable};
struct Collation
{
std::string locale;
bool caseLevel;
std::string caseFirst;
int strength;
bool numericOrdering;
std::string alternate;
std::string maxVariable;
bool backwards;
};
struct WriteErrors
{
std::size_t index;
int code;
std::string errmsg;
};
struct WriteConcernError
{
int code;
std::string errmsg;
};
struct CmdReply
{
double ok;
std::size_t n;
std::string errmsg;
std::string codeName;
int code;
std::vector<WriteErrors> writeErrors;
};
class CmdDB_Reply: public Op_Reply<CmdReply>
{
public:
bool replyCount() const;
virtual bool isOk() const override;
virtual std::string getHRErrorMessage() const override;
protected:
friend std::ostream& operator<<(std::ostream& stream, HumanReadable<CmdDB_Reply> const& reply);
std::ostream& printHR(std::ostream& stream) const {return Op_Reply::printHR(stream);}
};
struct WriteConcern
{
WriteConcern(int w = 1, bool j = false, std::time_t wtimeout = 0);
int w;
bool j;
std::time_t wtimeout;
};
template<typename Action>
class CmdDB_Query: public Op_Query<Action>
{
public:
template<typename... Args>
CmdDB_Query(std::string const& db, std::string const& collection, QueryOptions&& options, Args&&... args);
// Insert
CmdDB_Query& byPass();
// Options
// All these options are implemented for this object
// in the CmdDB.tpp file.
//
// But if you make a call to a method that is not implemented
// in your action object then you will get a compile time error.
// i.e. If you used .addHint("A hint") on an Insert Action
// this will fail to compile as this will call .addHint()
// on the actio but this is not implements on Insert
// but is implemented on Find document.
// Insert & Delete
CmdDB_Query& unordered();
CmdDB_Query& setWrieConcern(int w = 1, bool j = false, std::time_t wtimeout = 0);
// Insert & Find
CmdDB_Query& setComment(std::string&& c);
// Find
CmdDB_Query& addFileds(std::initializer_list<std::string> const& fieldNames);
CmdDB_Query& addHint(std::string&& hint);
CmdDB_Query& setSkip(std::size_t val);
CmdDB_Query& setLimit(std::size_t val);
CmdDB_Query& setBatchSize(std::size_t val);
CmdDB_Query& singleBatch();
CmdDB_Query& setMaxTimeout(std::size_t val);
CmdDB_Query& addReadConcern(ReadConcernLevel val);
CmdDB_Query& addMax(std::string const& field, int val);
CmdDB_Query& addMin(std::string const& field, int val);
CmdDB_Query& justKeys();
CmdDB_Query& showId();
CmdDB_Query& tailableCursor();
CmdDB_Query& tailedCursorAwait();
CmdDB_Query& setNoCursorTimeout();
CmdDB_Query& setAllowPartialResults();
CmdDB_Query& useDisk();
friend std::ostream& operator<<(std::ostream& stream, HumanReadable<CmdDB_Query> const& data);
friend std::ostream& operator<<(std::ostream& stream, CmdDB_Query const& data) {return data.print(stream);}
};
}
ThorsAnvil_MakeEnum(ThorsAnvil::DB::Mongo::ReadConcernLevel, local, available, majority, linearizable);
ThorsAnvil_MakeTrait(ThorsAnvil::DB::Mongo::Collation, locale, caseLevel, strength, numericOrdering, alternate, maxVariable, backwards);
ThorsAnvil_MakeTrait(ThorsAnvil::DB::Mongo::WriteConcern, w, j, wtimeout);
ThorsAnvil_MakeTrait(ThorsAnvil::DB::Mongo::WriteErrors, index, code, errmsg);
ThorsAnvil_MakeTrait(ThorsAnvil::DB::Mongo::WriteConcernError, code, errmsg);
ThorsAnvil_MakeTrait(ThorsAnvil::DB::Mongo::CmdReply, ok, n, writeErrors, writeConcernError, errmsg, codeName, code);
#include "CmdDB.tpp"
#endif
</code></pre>
CmdDB.tpp
<pre><code>#ifndef THORSANVIL_DB_MONGO_CMD_DB_TPP
#define THORSANVIL_DB_MONGO_CMD_DB_TPP
#ifndef THORSANVIL_DB_MONGO_CMD_DB_H
#error "This should only be included from CmdDB.h"
#endif
namespace ThorsAnvil::DB::Mongo
{
template<typename Action>
template<typename... Args>
CmdDB_Query<Action>::CmdDB_Query(std::string const& db, std::string const& collection, QueryOptions&& options, Args&&... args)
: Op_Query<Action>(db + ".$cmd", std::forward<QueryOptions>(options), 1, 0, collection, std::forward<Args>(args)...)
{}
template<typename Action>
CmdDB_Query<Action>& CmdDB_Query<Action>::unordered()
{
this->getQuery().unordered();
return *this;
}
template<typename Action>
CmdDB_Query<Action>& CmdDB_Query<Action>::byPass()
{
this->getQuery().byPass();
return *this;
}
template<typename Action>
CmdDB_Query<Action>& CmdDB_Query<Action>::setComment(std::string&& val)
{
this->getQuery().setComment(std::forward<std::string>(val));
return *this;
}
// etc.
// These all look like
// 1: Call getQuery() which gets the `Insert` object.
// 2: Call the setComment() or appropriate option method on action object.
// 3: return *this to allow chaining.
}
#endif
</code></pre>
<h2>If you are interested:</h2>
<ul>
<li><a href="https://github.com/Loki-Astari/ThorsSerializer" rel="nofollow noreferrer">ThorsSerializer</a> : Serialization of C++ objects without writting code</li>
<li><a href="https://github.com/Loki-Astari/ThorsCrypto" rel="nofollow noreferrer">ThorsCrypto</a> : Crypto to Authenticate</li>
<li><a href="https://github.com/Loki-Astari/ThorsDB" rel="nofollow noreferrer">ThorsDB</a> <a href="https://github.com/Loki-Astari/ThorsDB/tree/master/src/MySQL" rel="nofollow noreferrer">SQL</a> <a href="https://github.com/Loki-Astari/ThorsDB/tree/master/src/Mongo" rel="nofollow noreferrer">Mongo</a> : DB Accesses</li>
<li><a href="https://github.com/Loki-Astari/ThorsNisse" rel="nofollow noreferrer">ThorsNisse</a> : Server to provide non blocking reads/writes</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:29:41.593",
"Id": "502923",
"Score": "1",
"body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:25:27.127",
"Id": "502936",
"Score": "0",
"body": "Much better, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:28:19.063",
"Id": "502938",
"Score": "0",
"body": "@Toby It may not look like it at first glance, but I think the title actually explains the purpose of the code, not the concerns. The code is an attempt to reduce the constructor count. The rest of the project is much bigger."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T11:08:11.943",
"Id": "502952",
"Score": "0",
"body": "So this is a program that *tries to reduce constructor count*? I disagree; it seems to be some other kind of program/library that *has* a reduced constructor count. I'll see if I can come up with something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T11:12:48.880",
"Id": "502953",
"Score": "0",
"body": "I've edited - does the new title accurately represent this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T17:07:49.307",
"Id": "502971",
"Score": "0",
"body": "@TobySpeight Thanks. I am not sure \"Database\" is relevant. It just happens this implementation is using an underlying Database as an example. But I like the bit about creating command and the \"Builder Pattern\". Shows how long I have been away from coding that I'm forgetting the patterns. How about **\"Commands Object creation using chained Builder pattern\"**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:24:05.787",
"Id": "503007",
"Score": "0",
"body": "@Martin, that works for me. After all, you know the code best. Nice to see you're getting answers, too."
}
] |
[
{
"body": "<h1>Is it more efficient for the user of this API?</h1>\n<p>It looks nice for a single insert operation, but what if I need to insert many things, all with the same options? I would not want to have to repeat the <code>.unordered().setComment(...).anotheroption(...)</code> each time. There are several alternative ways to handle this:</p>\n<h2>Create stream manipulator objects</h2>\n<p>Just like the STL's <a href=\"https://en.cppreference.com/w/cpp/io/manip\" rel=\"nofollow noreferrer\">input/output manipulators</a>, you could make something for your connection object, so that you would write something like:</p>\n<pre><code>connection << unordered()\n << setComment("Hi there")\n << make_CmdDB_Insert(DB, "Collection", QueryOptions{}, person)\n << make_CmdDB_Insert(...);\n</code></pre>\n<h2>Move options into their own object</h2>\n<p>Instead of having <code>struct Insert</code> hold both the documents to be inserted and the options of how to insert those, split the latter of into its own <code>struct</code> that can be manipulated as before, but is passed to <code>make_CmdDb_Insert()</code> as a parameter:</p>\n<pre><code>auto options = InsertOptions().unordered().setComment("Hi there");\nconnection << make_CmdDB_Insert(..., options)\n << ...\n << make_CmdDB_Insert(..., options);\n</code></pre>\n<p>But since you mentioned C++20: instead of having to write lots of member functions, you could use <a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers\" rel=\"nofollow noreferrer\">designated initializers</a> instead, like so:</p>\n<pre><code>struct InsertOptions {\n bool ordered = true;\n WriteConcern writeConcern;\n bool bypassDocumentValidation = false;\n std::string comment;\n};\n\n...\n\nInsertOptions options = {\n .ordered = false,\n .comment = "Hi there",\n};\n\nconnection << make_CmdDB_Insert(..., options)\n << ...\n << make_CmdDB_Insert(..., options);\n</code></pre>\n<p>And you can still do it as a one-liner if necessary:</p>\n<pre><code>connection << make_CmdDB_Insert(..., {.ordered = false, .comment = "Hi there"});\n</code></pre>\n<h1>Why use <code>operator<<</code>?</h1>\n<p>For iostreams, <code>operator<<</code> and <code>operator>></code> kind of make sense. They accept any kind of object but each operator always perform the same action on that object. But on a database, you want to perform different types of actions: insert, delete, query, and so on. The object is the data you want to insert/delete/query. However, you are mixing the object and the action together just to be able to use a generic <code>operator<<</code>. And there's quite some template gymnastics involved in making that happen.</p>\n<p>As a user, I don't want to know about <em>connections</em> at all. I want to have an object that represents the MongoDB <em>instance</em> I am connected to, and then perform actions on that instance. So I think the following would just be more natural and easier to implement:</p>\n<pre><code>MongoInstance my_mongo(DB, USER, PASS);\nPerson person{"Mayura", 16};\nmy_mongo.insert("Collection", {}, person, {.ordered = false, ...});\n</code></pre>\n<p>The <code>insert()</code> member function should then of course be a template so it can accept any type of serializable object as the third parameter.</p>\n<h1>Make it easy to have options depend on variables</h1>\n<p>Your API has a problem if you don't know up front whether you want to have the operations to be ordered or unordered for example. Here is an example of the problem:</p>\n<pre><code>void somefunc(..., bool unordered) {\n if (unordered) {\n connection << make_CmdDB_Insert(...).unordered();\n } else {\n connection << make_CmdDB_Insert(...);\n }\n}\n</code></pre>\n<p>This will explode when you have multiple options that you want to conditionally apply. Of course you could work around that a bit and keep it linear:</p>\n<pre><code>void somefunc(..., bool unordered) {\n auto insert_command = make_CmdDB.Insert(...);\n if (unordered)\n insert_command.unordered();\n connection << insert_command;\n}\n</code></pre>\n<p>But much better would be to have a way to avoid conditional statements. I would have every option take a parameter, and of course you can give it a default value so you can still use it as above, but also allow:</p>\n<pre><code>void somefunc(..., bool unordered) {\n connection << make_CmdDB_Insert(...).unordered(unordered);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T22:10:17.380",
"Id": "503018",
"Score": "0",
"body": "What is the name of this feature: `{.ordered = false, ...}` what version of C++ is it available in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T22:31:42.343",
"Id": "503019",
"Score": "0",
"body": "[designated initializers](https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers), available in C++20 (although GCC and Clang support it even if you specify `-std=c++11` it seems). The only drawback is that you have to specify the options in the correct order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T16:57:37.127",
"Id": "503075",
"Score": "0",
"body": "Thanks for the excellent write up. I am seriously questioning the Builder pattern design now. I will re-think how this is going to work."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:09:02.933",
"Id": "255025",
"ParentId": "254964",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255025",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T19:37:29.053",
"Id": "254964",
"Score": "4",
"Tags": [
"c++",
"library",
"mongodb",
"constructor"
],
"Title": "Commands Object creation using chained Builder pattern"
}
|
254964
|
<p>I have a system of n oscillators which oscillate with time. To each of these oscillators I am adding a fluctuating coloured noise term with a different seed for each oscillator. Here is my code for the generation of this noise:</p>
<pre><code>#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <iostream>
#include <random>
using namespace std;
double dt = 0.01;
static normal_distribution<double> n_dist(0 , sqrt(dt));
static random_device rd;
static default_random_engine generator(rd());
static double dW ( double dt ) {
return n_dist(generator);
}
void exp_noise(double gamma, int steps, double c_sigma, float X[])
{
X[0] = 1;
for (int i = 0; i < steps; i++ ){
X[i+1] = (1 - gamma) * X[i] + c_sigma * sqrt(2*gamma) * dW(1);
}
}
int main()
{
int n = 256;
constexpr int steps = 1000;
float X[n*steps];
for( int i=0 ; i<n ; ++i ){
float X_i[steps];
memset(X_i, 0.0, sizeof X_i);
exp_noise(0.4, steps, 1, X_i);
for( int j=0 ; j<steps ; ++j ){cout << X_i[j] << '\n';}
memcpy( X + i*steps, X_i, sizeof( X_i ) );
}
cout << "total vector is" << '\n';
for( int i=0 ; i<n*steps ; ++i ){cout << X[i] << '\n';}
return 0;
}
</code></pre>
<p>Essentially my code is producing something similar to an array of noise for each oscillator, and then appending all of those arrays together. The intention is to apply to above code to my oscillators in the following way.</p>
<pre><code>for (int h = 0; h < steps; ++h){
for( int i=0 ; i<n ; ++i ){
oscillator[i] = stoch_runge_kutta( oscillator[i], X[ h + i*steps ], ... )
}
}
</code></pre>
<p>This code seems to work well for a small number of steps. This code unfortunately breaks down however for values of n * steps > 2500000 with a stack overflow error. So my first question would be whether the code can be made more stable to the value of n*steps with some minor changes, or whether I need to change everything by using vectors instead? I would also be interested in knowing whether the code would be faster or more elegant if I completely redesigned the code in some other way, for example by not creating an array of arrays, and doing something else instead? How would these things be done? It's not essential, but it's preferable to have the noise as an array so that it can be reused to for other things.</p>
<p>Any help would be greatly appreciated.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>#include <math.h>\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <iostream>\n#include <random>\n\nusing namespace std;\n</code></pre>\n</blockquote>\n<p>Please don't put all the standard identifiers into the global namespace. Use the C++ versions of the libraries, and qualified names. If you really must drag some identifiers in (as is often required for argument-dependent lookup), be specific and keep their scope small.</p>\n<p>And try not to mix C standard I/O and C++ streams if possible.</p>\n<pre><code>#include <cmath>\n#include <cstddef>\n#include <cstdlib>\n#include <iostream>\n#include <random>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T16:28:57.880",
"Id": "255009",
"ParentId": "254965",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T20:18:44.077",
"Id": "254965",
"Score": "1",
"Tags": [
"c++",
"array",
"c++11",
"random",
"numerical-methods"
],
"Title": "generating stochastic coloured noise for many oscillators"
}
|
254965
|
<p>I'm an amateur at programming and have created the following method with which I pass a lowercase string with the idea it is then returned either in it's original <code>lowercase</code> format, <code>Capitalised</code> or <code>UPPERCASE</code>. I'm not sure this is the best way or is truly "random" but does work up to a point but would like pointers on any improvements or different ways to achieve this.</p>
<pre class="lang-cs prettyprint-override"><code> //==============================================================================
// Randomise string case
//==============================================================================
private string randomCase (string word)
{
string changed;
Random r = new Random(Guid.NewGuid().GetHashCode());
int n = r.Next(1, 29);
if (n >= 1 && n <= 9)
{
// First letter capatalised
changed = char.ToUpper(word[0]) + word.Substring(1);
return changed;
}
else if (n >= 10 && n <= 19)
{
// Word capatalised
changed = word.ToUpper();
return changed;
}
else if (n >= 20 && n <= 29)
{
// Left as lower case
return word;
}
return null;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>This entire method should be static, as it clearly does not require an object</li>\n<li><code>new Random(Guid.NewGuid().GetHashCode())</code> is needlessly complicated. <code>new Random()</code> is initialized based on time by default</li>\n<li>A simpler range from <code>[0,2]</code> can be used.</li>\n<li>The <code>changed</code> variable can be entirely replaced by a <code>switch</code> and <code>return</code> structure</li>\n</ul>\n<pre><code>private static string Capitalized(string word) {\n return char.ToUpper(word[0]) + word.Substring(1);\n}\n\nprivate static string RandomCase(string word)\n{\n int choice = new Random().Next(3);\n switch(choice) {\n case 0: return Capitalized(word);\n case 1: return word.ToUpper();\n case 2: default: return word;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:02:02.057",
"Id": "503338",
"Score": "0",
"body": "Usually the parentheses are used for exclusive and the square brackets for inclusive, so that would be `[0, 2)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T00:19:26.207",
"Id": "254974",
"ParentId": "254966",
"Score": "3"
}
},
{
"body": "<p>Here are my observations:</p>\n<ul>\n<li><code>string randomCase</code>: I would suggest to start your method name with a verb and use CamelCase. For example: <code>RandomizeCase</code></li>\n<li><code>(string word)</code>: I've got your intent, but nothing prevents the consumer of your API to put a sentence into your <code>word</code> parameter. In such a general purpose method <code>input</code> can be considered as a fine parameter name.</li>\n<li><code>string changed</code>: You don't need this variable at all. You use this as an intermediate container. If you return right after you set it then you can combine these two statements into one, like: <code>return word.ToUpper();</code></li>\n<li><code>Random r</code> / <code>int n</code>: Please try to avoid to use single letter for variable names (exceptions are the loop variables).</li>\n<li><code>Random(Guid.NewGuid().GetHashCode())</code>: I've seen so many different ways how to seed a <code>Random</code>. For me the most convenient is the <code>Random((int)DateTime.Now.Ticks)</code>. But do you really need to provide a seed at all?</li>\n<li><code>r.Next(1, 29)</code>: I get it that you want to achieve something like even or fair distribution. This is unnecessary. Your current implementation is hard to maintain and hard to change in the future. Also future reader of your code (even yourself) might ask: <em>Why do we use 29 her as the upper-bound? Why not 316464616?</em>\n<ul>\n<li><code>r.Next(1,3)</code> or <code>r.Next() % 3</code> could be a viable alternative.</li>\n</ul>\n</li>\n<li><code>if ... else if ... return null</code>: Even though you have restricted the range of <code>n</code> you need to provide a <code>return null</code> at the end to make it compile. Even worse this piece of code is never reached. If you want to stick with this approach a better alternative would be to use a single return:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>string changed\nif (n >= 1 && n <= 9)\n{\n changed = char.ToUpper(word[0]) + word.Substring(1);\n}\nelse if (n >= 10 && n <= 19)\n{\n changed = word.ToUpper();\n}\nelse if (n >= 20 && n <= 29)\n{\n changed = word;\n}\n\nreturn changed;\n</code></pre>\n<ul>\n<li><code>// First letter capatalised</code>: Here you have made a huge assumption: The provided <code>word</code> is in lower case. You can't trust your input. The simplest way to ensure this is to make it lowercase by yourself:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>if(string.IsNullOrEmpty(word))\n return string.Empty; //Or throw ArgumentException if you wish\n\nstring loweredWord = word.ToLower();\n</code></pre>\n<ul>\n<li>The same assumption is present in each of your if-else branches.</li>\n</ul>\n<hr />\n<p><strong>UPDATE</strong>: Random</p>\n<p>It is not crystal clear for me why do you need this method at all, but based on the provided comment I would like highly two things regarding random:</p>\n<ul>\n<li><code>Random</code> is not thread-safe, which means that if the same instance is shared amongst different threads then <code>Next</code> may return zeros. (<a href=\"https://stackoverflow.com/questions/3049467/is-c-sharp-random-number-generator-thread-safe\">Related SO</a>)</li>\n<li>Even though <code>RNGCryptoServiceProvider</code> <a href=\"https://www.dotnetperls.com/rngcryptoserviceprovider\" rel=\"nofollow noreferrer\">is slower</a> it is stronger from cryptographic point of view. There are several really good articles and samples out there, for example:\n<ul>\n<li><a href=\"https://stackoverflow.com/a/6299708/13268855\">how to generate random number between a range</a></li>\n<li><a href=\"http://www.vcskicks.com/code-snippet/rng-int.php\" rel=\"nofollow noreferrer\">how to use it for seed generation</a></li>\n<li><a href=\"https://wubw.github.io/2018/cryptography_introduction/\" rel=\"nofollow noreferrer\">how to use it during hash generation</a></li>\n</ul>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T20:10:03.800",
"Id": "502996",
"Score": "1",
"body": "Thanks for the very useful feedback! Very insightful and appreciated. I'm building a random password generator so the string being passed will always be in lower case as all the words in my dictionary are stored in lowercase. The reason I went with `Random(Guid.NewGuid().GetHashCode())` was that when reading some online resources about being truly random, comments suggested that was the best approach. I've taken the other suggestions on board and will be sure to implement your suggestions. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T07:41:39.827",
"Id": "503042",
"Score": "1",
"body": "@Rawns I've extend my answer with some extra information regarding `Random`. Please check the suggested articles if you have time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T19:47:18.447",
"Id": "503091",
"Score": "0",
"body": "That's great, thanks! The reason for the method is the UI I have created allows the user to choose to generate a 2, 3 or 4 word long password. To try and make it as random as possible, I wanted each word randomly selected from my dictionary to then have the case randomised using this method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:00:42.967",
"Id": "503337",
"Score": "1",
"body": "Random.Next() % 3 is slightly biased. Not much, but if you'd use a value higher than 3 it may become problematic. I'd advise Next(3) instead on a secure random implementation indeed which returns 0, 1 or 2."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T09:00:29.137",
"Id": "254986",
"ParentId": "254966",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254986",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:43:13.913",
"Id": "254966",
"Score": "7",
"Tags": [
"c#",
"beginner",
"strings",
"random"
],
"Title": "Method to randomise a string's case"
}
|
254966
|
<p>The Merriam-Webster Dictionary API at some point discontinued the use of XML in favor of exclusively returning JSON. This had the unfortunate effect of making finding a definition listed by sense number (i.e. definition <code>1 a (2)</code>) much more complicated because they're trying to force a semi-arbitrary document based model into nested json.</p>
<p>After reading through the documents I was able to figure out the object nesting hierarchy they return but never directly explain. The relevant nestings I believe go:</p>
<pre><code>(arrows show what an object can be nested in i.e. dt is in a sense or sdsense
which can in turn be inside another sense. Sorry for the unclear names, thats
just what the api calls everything)
dt ============> sense ===========> sseq ========> def
\==> sdsense ==/ \ \ / ^ \==> vd ==/
\ \==> bs == |
\ \ |
\========+> pseq
</code></pre>
<p>Most fields can be either arbitrarily long arrays like <code>[['sense', {...}]]</code> or objects <code>{'sense': [{...}]}</code> depending on context which is a pain especially because sometimes they're nested, sometimes they're flat. Objects can also contain any combination of nested objects repeated any number of times. For example, an <code>sseq</code> can contain a <code>pseq</code> which contains a <code>bs</code>, a <code>bs</code> of it's own, another <code>pseq</code>, and then a few <code>sense</code> objects. Not every one is that complex but there are no restriction stopping them.</p>
<p>To make matters more complicated the sense number (a property of either <code>sense</code> or <code>sdsense</code>) can be explicit: <code>1 a (2)</code> or implicit: <code>a</code> or <code>(3)</code> which means it depends on a previous <code>sense</code> or <code>sdsense</code> that could be nested in a completely different object. They can also change between implicit and explicit as you go up and down the hierarchy.</p>
<p>And lastly that <code>vd</code> field means that instead of <code>def</code> being an array of <code>sseq</code> it is of the form <code>def: [{'vd': "[verb type]", "sseq": [...]}, {'vd': "[verb type]", "sseq": [...]}]</code> and that sense numbers can suddenly either explicitly or implicitly reference the verb type as well which is never actually nested inside anything relevant.</p>
<p>Check the offial API at <a href="https://dictionaryapi.com/products/json#sec-2.vd" rel="noreferrer">the Merriam Webster website</a> for all the quirks and exceptions.</p>
<p><strong>TLDR:</strong> json an api returns is a hot mess and there's no easy way to reference the definition <code>1 a (2)</code> of a dictionary entry. Since a project I'm working on depends on referencing definitions directly by that number I wrote the python parser below to reform the json into a well nested object that can be accessed like <code>parse_resp('word')['1']['a']['(2)']['def']</code>.</p>
<p>My approach writing the code was to start with parsing the <code>dt</code> object and then work my back through each layer, creating a better structured object as I go. <code>lists</code> and <code>dicts</code> are still mixed together inside the object because the relationship between implicit sense numbers needs to be preserved.</p>
<p>Finally, once that object is completely built, there's an admittedly gross method <code>unpack_defs</code> that uses a couple global variables to track the last well-formed sense number while it recursively pulls the entire object inside-out into one well-nested dict.</p>
<p>I'm sure I could rewrite at least that piece better but given this was supposed to be a simple API request in a larger project that the lack of xml support greatly complicated, once it was working for all the exceptions of the API I called it a day and moved on.</p>
<p><strong>Code:</strong></p>
<pre><code>import urllib.request
import json
import os
import re
# TO-DO: GET RID OF GLOBAL STATE
curr_num = ''
curr_let = ''
def reset():
global curr_let
global curr_num
curr_num = ''
curr_let = ''
# parse_resp is the main function called from other packages and accepts a Merriam Webster api response
# parse_resp defaults to returning only the definitions referenced in the first-use 'date' field because that's what the overall project is interested in
def parse_resp(resp, all_defs=False):
reset()
entries = [parse_entry(entry) for entry in resp]
if all_defs == True:
return [non_empty for non_empty in entries if non_empty]
for entry in entries:
entry['def'] = get_sense_by_sn(entry['sn'], entry['def'])
entries = [e for e in entries if e['date'] and e['def']]
return entries
def get_sense_by_sn(sense_number, entry):
def loop_entry(entry):
x = entry
for sn in sense_number:
x = x[sn]
return x['def']
try: return loop_entry(entry)
except: pass
# check for implicit references to transitive / intransitive verb if explicit path fails
try: return loop_entry(entry['t'])
except: pass
try: return loop_entry(entry['i'])
except: pass
return ''
def parse_entry(defs):
(date, sn) = parse_date(defs)
entry = unpack_defs(parse_defs(defs))
if entry is None:
return
return {
'date': date,
'sn': sn,
'def': entry
}
def unpack_defs(defs):
global curr_num
global curr_let
if isinstance(defs, dict):
(key, value) = next(iter(defs.items()))
key = str(key)
if is_verb(key):
return {key: unpack_defs(value)}
else:
return fmt_def(key, value)
if isinstance(defs, list):
def_dict = dict()
for d in defs:
if isinstance(d, list):
def_dict.update(unpack_defs(d))
if isinstance(d, dict):
(key, value) = next(iter(d.items()))
if is_number(key):
curr_num = key
def_dict.update(fmt_def(key, value))
elif is_paren(key):
def_dict[curr_num][curr_let].update(fmt_def(key, value))
else:
keys = key.split()
def nest_keys(keys):
global curr_num
global curr_let
key = keys[0]
if len(keys) > 1:
if is_number(key):
curr_num = key
if is_letter(key):
curr_let = key
return {key: nest_keys(keys[1:])}
else:
return (fmt_def(key, value))
if not curr_num or (is_number(keys[0]) and curr_num != keys[0]):
def_dict.update(nest_keys(keys))
elif curr_num:
def_dict[curr_num].update(fmt_def(key, value))
return def_dict
def fmt_def(key, value):
key = str(key)
return {key: {'def': value}}
def is_number(string):
try:
int(string)
return True
except:
return False
def is_paren(string):
return '(' in string[0]
def is_letter(string):
return string.isalpha()
def is_verb(string):
return string == 't' or string == 'i'
# First Known Use: date
# Hierarchical Context
# Top-level member of dictionary entry
# Data Model
# "date" : string
def parse_date(entry):
if isinstance(entry, dict):
if 'date' in entry.keys():
return clean_date(entry['date'])
return ('', '')
def clean_date(date_string):
date = int(re.search(r'[0-9]+', date_string).group())
sn = re.findall(r'(?<=\|)[\w()]*', date_string) or ['1']
sn = [non_empty for non_empty in sn if non_empty]
# quick and dirty conversion of centuries
if date < 100:
date = (date-1) * 100
return (date, sn)
# Definition: def
# Hierarchical Context
# Occurs as top-level member of dictionary entry and in dros.
# Data Model
# array of one or more objects
def parse_defs(defs):
if isinstance(defs, dict):
defs = defs['def']
for entry in defs:
if is_vd(entry):
return parse_vd(entry)
elif is_sseq(entry):
return parse_sseq(entry)
# Verb Divider: vd
# Hierarchical Context
# Occurs in def, preceding an sls (optional) and sseq (required)
# Data Model
# "vd" : string
def is_vd(vd):
if isinstance(vd, dict):
return 'vd' in vd.keys()
return False
# Verbs can be transititive or intransitive and referenced as 'i' or 'v' in date
def parse_vd(vd):
verb_type = 't'
if 'intransitive' in vd['vd']:
verb_type = 'i'
return {verb_type: parse_sseq(vd['sseq'])}
#
# Shared logic for sseq and pseg
#
def parse_array(array):
sense_list = []
for sense in array:
if is_sense(sense):
sense_list.append(parse_sense(sense))
elif is_bs(sense):
sense_list.append(parse_bs(sense))
elif is_pseq(sense):
sense_list.append(parse_pseq(sense))
elif isinstance(sense, list):
sense_list.append(parse_array(sense))
if len(sense_list) == 1:
return sense_list[0]
return sense_list
# Sense Sequence: sseq
# Hierarchical Context:
# Occurs in def
# Data Model:
# "sseq" : array
def is_sseq(sseq):
if isinstance(sseq, dict):
return 'sseq' in sseq.keys()
return False
def parse_sseq(sseq):
if isinstance(sseq, dict):
sseq = sseq['sseq']
sense_list=[]
for array in sseq:
sense_list.append(parse_array(array))
if len(sense_list) == 1:
return sense_list[0]
return sense_list
# Parenthesised Sense Sequence:
# Hierarchical Context:
# Occurs as an element in an sseq array.
# Data Model:
# array consisting of one or more sense elements and an optional bs element.
def is_pseq(pseq):
if isinstance(pseq, list):
return pseq[0] == 'pseq'
return False
def parse_pseq(pseq):
sense_list = []
for sense in pseq[1:]:
sense_list.append(parse_array(sense))
return sense_list
# Binding Substitution: bs
# Hierarchical Context
# Occurs as an element in an sseq or pseq array, where it is followed by one or more sense elements.
# Data Model:
# array of the form ["bs", {sense}]
def is_bs(bs):
if isinstance(bs, list):
return 'bs' == bs[0]
return False
def parse_bs(bs):
return parse_sense(bs[1])
# Sense: sense
# Hierarchical Context
# Occurs as an element in an sseq array.
# Data Model:
# object or array consisting of one dt (required) and zero or more et, ins, lbs, prs, sdsense, sgram, sls, sn, or vrs
def is_sense(sense):
if isinstance(sense, dict):
return 'sense' in sense.keys()
elif isinstance(sense, list):
return 'sense' == sense[0]
return False
def parse_sense(sense):
if isinstance(sense, dict):
sense = sense['sense']
elif isinstance(sense, list):
sense = sense[1]
else: return
sn = 1
if 'sn' in sense.keys():
sn = sense['sn']
sn = str(sn)
dt = parse_dt(sense['dt'])
if 'sdsense' in sense.keys():
dt += parse_sdsense(sense['sdsense'])
return {sn: dt}
# Divided Sense: sd
# Hierarchical Context
# Occurs within a sense, where it is always preceded by dt.
# Data Model:
# "sdsense" : object with the following members:
# "sd" : string sense divider (required)
# et, ins, lbs, prs, sgram, sls, vrs (optional)
# dt definition text (required)
def parse_sdsense(sdsense):
return parse_dt(sdsense['dt'])
# Defining Text: dt
#Hierarchical Context
# Occurs as an element in an sseq array.
# Data Model:
# "dt" : array consisting of one or more elements:
# ["text", string] where string contains the definition content (required)
# optional bnw, ca, ri, snote, uns, or vis elements
def parse_dt(dt):
for elem in dt:
if elem[0] == 'text':
### Implement text cleaning
return re.sub(r'\{[\w]*\}', '', elem[1]).strip()
</code></pre>
|
[] |
[
{
"body": "<h2>Globals</h2>\n<pre><code># TO-DO: GET RID OF GLOBAL STATE\n</code></pre>\n<p>Yep. You seem to already understand this one. Having a <code>reset</code> betrays a place in your design that would be well-suited to an object that can be thrown away and re-constructed, which is usually a more useful model than existing state that can be reset.</p>\n<p>Moving on.</p>\n<h2>Docstrings</h2>\n<p>Rather than</p>\n<pre><code># parse_resp is the main function called from other packages and accepts a Merriam Webster api response\n# parse_resp defaults to returning only the definitions referenced in the first-use 'date' field because that's what the overall project is interested in\ndef parse_resp(resp, all_defs=False):\n</code></pre>\n<p>the standard asks for</p>\n<pre><code>def parse_resp(resp, all_defs=False):\n """\n parse_resp is the main function called from other packages and accepts a Merriam Webster api response\n parse_resp defaults to returning only the definitions referenced in the first-use 'date' field because that's what the overall project is interested in\n """\n</code></pre>\n<p>There are bits of Python that actually parse the latter style for official documentation; so you really should follow that style.</p>\n<h2>Booleans</h2>\n<pre><code>if all_defs == True:\n</code></pre>\n<p>should just be</p>\n<pre><code>if all_defs:\n</code></pre>\n<p>If you're worried that that isn't explicit enough, the answer is not a comparison to a boolean literal; the answer is to mark your <code>all_defs: bool = False</code> with a type hint.</p>\n<h2>Exceptions</h2>\n<p>It doesn't matter how poorly-formed the input data are - this:</p>\n<pre><code>try: return loop_entry(entry) \nexcept: pass\n</code></pre>\n<p>is not appropriate. If you know of a specific data condition that will throw e.g. <code>KeyError</code>, then catch <code>KeyError</code> - or better yet, do a <code>.get()</code> and write logic-by-<code>if</code> instead of logic-by-exception. The current strategy of "swallow all exceptions no matter what" can turn debugging edge cases from an inconvenience into a nightmare.</p>\n<h2>Tuple unpacking</h2>\n<p>Outer parens are not needed here:</p>\n<pre><code>(date, sn) = parse_date(defs)\n</code></pre>\n<h2>Spooky utility methods</h2>\n<p>Since this is undocumented and with no type hints, I can only guess that this:</p>\n<pre><code>def is_paren(string):\n return '(' in string[0]\n</code></pre>\n<p>actually does accept a string. Since that's the case, <code>string[0]</code> will only ever be a one-character string, and so <code>==</code> is more appropriate than <code>in</code>. Better yet, simply call <code>startswith</code>.</p>\n<p>The opposite is true here:</p>\n<pre><code>def is_verb(string):\n return string == 't' or string == 'i'\n</code></pre>\n<p>can be</p>\n<pre><code>def is_verb(string: str):\n return string in {'t', 'i'}\n</code></pre>\n<h2>Date parsing</h2>\n<p><code>clean_date</code> is undocumented so I don't know what date format it expects, but it's likely that you should be using a "real" date-parsing method out of <code>datetime</code> instead of what you have now.</p>\n<h2>Overall</h2>\n<p>You need unit tests. They are not optional for a use case like this. You need examples, pulled from the wild, of JSON bodies representing all of the edge cases you know about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:13:36.863",
"Id": "254971",
"ParentId": "254969",
"Score": "16"
}
}
] |
{
"AcceptedAnswerId": "254971",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T22:22:42.307",
"Id": "254969",
"Score": "10",
"Tags": [
"python",
"parsing",
"json"
],
"Title": "Parsing overly complex JSON"
}
|
254969
|
<p>here's some code I wrote in java SE to get use to if statements and scanning. just looking for suggestions that will improve this program or/and teach me techniques that I should get use to using.</p>
<pre><code>import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.print("Enter the first value ");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
System.out.print("Enter the next value ");
int y = scan.nextInt();
System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
int z = scan.nextInt();
if (z == 1) {
int a = x * y;
System.out.println("Result: " + a);
}//end of if multiply
else if (z == 2) {
int a = x / y;
System.out.println("Result: " + a);
}//end of if divide
else if (z == 3) {
int a = x + y;
System.out.println("Result: " + a);
}// end of if add
else {
int a = x-y;
System.out.println("Result: " + a);
} //end of is subtract
}// End of main
}// End of public class
</code></pre>
<p>here's my new program, still not perfect but the class i'm taken hasn't even gone over data types and classes yet so i'm already ahead lol
Thank you every one for your help!</p>
<pre><code>import java.util.Scanner;
public class Calculatortwo {
public static void main(String[] args) {
//get imput values from user
System.out.print("Enter the first value ");
Scanner scan = new Scanner(System.in);
double x = scan.nextDouble();
System.out.print("Enter the next value ");
double y = scan.nextDouble();
System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
int operation = scan.nextInt();
//calculator logic
double result = 0;
switch (operation) {
case 1:
result = x * y;
break;
case 2:
if(y != 0) {
result = x / y;
}
else {
System.out.println("Error: Divide by 0");
}
break;
case 3:
result = x + y;
break;
case 4:
result = x - y;
break;
default:
System.out.println("Error: operation not found");
}
System.out.println("Result: " + result);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T06:58:46.757",
"Id": "502941",
"Score": "0",
"body": "Welcome to CodeReview@SE. While waiting for reviews/\"answers\", you may want to (re)visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask): the title deserves improvement. Check *to get use to `if` statements*, and if you scroll to the end of the code block, you may notice that in contrast to, say, SO, CR \"closing code fences\" still need a newline to follow it."
}
] |
[
{
"body": "<p>It would be best to codify the various operations in a separate function. This limits the opportunity for error and eliminates the redundancy of the <code>System.out.println("Result: " + a);</code> statements.</p>\n<pre><code> private static int applyOperation(int x, int y, int op) {\n switch(op) {\n case 1: return x*y;\n case 2: return x/y;\n case 3: return x+y;\n case 4: default: return x-y;\n }\n }\n public static void main(String[] args) {\n System.out.print("Enter the first value ");\n Scanner scan = new Scanner(System.in);\n int x = scan.nextInt();\n System.out.print("Enter the next value ");\n int y = scan.nextInt();\n System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");\n int op = scan.nextInt();\n int ans = applyOperation((x), y, op);\n System.out.println("Result: " + ans);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T00:37:21.790",
"Id": "254976",
"ParentId": "254970",
"Score": "3"
}
},
{
"body": "<h2>Input validation</h2>\n<p>The input validation is missing. If the user enters a letter, the program fails with <code>InputMismatchException</code>.</p>\n<p>An approach is to catch the exception, output an error message, and then either exit or ask the user to try again.</p>\n<p>Few other cases to cover:</p>\n<ul>\n<li><p>For <code>y=0</code>, the division will throw an <code>ArithmeticException</code>, so a second validation is needed in case of division.</p>\n</li>\n<li><p>The choice of the operation can only be an integer between <code>1</code> and <code>4</code> inclusive.</p>\n</li>\n<li><p>An operation on two big integers can overflow the integer result.</p>\n</li>\n</ul>\n<h2>Unnecessary comments</h2>\n<pre><code>if (z == 1) {\n ...\n}//end of if multiply\nelse if (z == 2) {\n ...\n}//end of if divide\nelse if (z == 3) {\n ...\n}// end of if add\nelse {\n ...\n} //end of is subtract\n</code></pre>\n<p>Commenting <code>// end</code> after each clause is unnecessary since it is clear that the clause ends with a <code>}</code>. If the comments are there to remember that <code>z==1</code> means multiplication, then it's a sign that the code isn't clear enough. You can use constants or enums to encode the meaning of a value. For example:</p>\n<pre><code>private static final int MULTIPLICATION = 1;\n//..\nif (z == MULTIPLICATION) {\n ...\n}\n</code></pre>\n<h2>Extract method</h2>\n<p>As @TedBrownlow pointed out, the logic of the calculator can be extracted into its own method. This makes the code more readable and easier to test. By easier to test I mean that a method like:</p>\n<pre><code>public class Calculator {\n public static int calculate(int x, int y, int operand) {\n //...\n }\n}\n</code></pre>\n<p>Can be easily tested in a unit test like:</p>\n<pre><code>public class CalculatorTest {\n @Test\n public void testMultiplication() {\n assertEquals(4, Calculator.calculate(2,2,1));\n }\n}\n</code></pre>\n<h2>Duplicated code</h2>\n<p>Printing the result is duplicated four times. It can be avoided by declaring <code>a</code> outside of the chain of if-else and then printing only at the end. From:</p>\n<pre><code>if (z == 1) {\n int a = x * y;\n System.out.println("Result: " + a);\n}//end of if multiply\nelse if (z == 2) {\n int a = x / y;\n System.out.println("Result: " + a);\n}//end of if divide\n</code></pre>\n<p>To:</p>\n<pre><code>int a = 0;\nif (z == 1) {\n a = x * y;\n}\nelse if (z == 2) {\n a = x / y;\n}\n//...\nSystem.out.println("Result: " + a);\n</code></pre>\n<h2>Naming</h2>\n<p>A better name for <code>a</code> and <code>z</code> can be <code>result</code> and <code>choice</code>.</p>\n<h2>Accuracy</h2>\n<p>The division of two integers doesn't necessarily produce an integer. Consider providing better accuracy or inform the user that it is an integer division.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T09:33:39.967",
"Id": "254987",
"ParentId": "254970",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254987",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:05:25.130",
"Id": "254970",
"Score": "2",
"Tags": [
"java",
"calculator"
],
"Title": "Still learning, looking for general advice about a 4-function calculator I programmed using java"
}
|
254970
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/250418/231235">Generic Two Dimensional Data Plane with Manipulation Methods For C#</a> and <a href="https://codereview.stackexchange.com/q/251570/231235">A SubPlane Method for Generic Two Dimensional Data Plane in C#</a>. Based on <a href="https://codereview.stackexchange.com/a/251594/231235">iSR5's suggestion</a>, in <code>SubPlane</code> method, <code>Array.Copy</code> is used instead of regular <code>for</code> loop in order to improve performance.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>[Serializable]
public class PlaneV3<T>
{
public int Width { get; }
public int Height { get; }
public T[,] Grid { get; set; }
public int Length => Width * Height;
public PlaneV3() : this(1, 1) { }
public PlaneV3(int width, int height)
{
Width = width;
Height = height;
Grid = new T[width, height];
}
public PlaneV3(PlaneV3<T> plane) : this(plane?.Grid) { }
public PlaneV3(T[,] sourceGrid)
{
if (sourceGrid is null)
{
throw new ArgumentNullException();
}
Width = sourceGrid.GetLength(0);
Height = sourceGrid.GetLength(1);
Grid = new T[Width, Height];
Array.Copy(sourceGrid, Grid, sourceGrid.Length);
}
public PlaneV3<T> ConcatenateHorizontal(PlaneV3<T> input)
{
if (input is null || input.Grid is null)
{
throw new ArgumentNullException();
}
if (this.Height.Equals(input.Height).Equals(false))
{
throw new ArgumentException();
}
var output = new PlaneV3<T>(this.Width + input.Width, this.Height);
for (int x = 0; x < this.Width; x++)
{
Array.Copy(this.Grid, x * this.Height, output.Grid, x * output.Height, this.Height);
}
for (int y = 0; y < this.Height; y++)
{
for (int x = 0; x < input.Width; x++)
{
output.Grid[this.Width + x, y] = input.Grid[x, y];
}
}
return output;
}
public PlaneV3<T> ConcatenateHorizontalInverse(PlaneV3<T> input)
{
return input.ConcatenateHorizontal(this);
}
public override bool Equals(object obj)
{
var input = obj as PlaneV3<T>;
// https://stackoverflow.com/a/12446807/6667035
return this.Grid.Rank == input.Grid.Rank &&
System.Linq.Enumerable.Range(0, this.Grid.Rank).All(dimension => this.Grid.GetLength(dimension) == input.Grid.GetLength(dimension)) &&
this.Grid.Cast<T>().SequenceEqual(input.Grid.Cast<T>());
}
public PlaneV3<T> SubPlane(int locationX, int locationY, int newWidth, int newHeight)
{
if (this.Grid == null)
{
return null;
}
PlaneV3<T> outputPlaneV3 = new PlaneV3<T>(newWidth, newHeight);
for (int y = 0; y < newHeight; y++)
{
Array.Copy(this.Grid, (y + locationY) * this.Width + locationX, outputPlaneV3.Grid, y * newWidth, newWidth);
}
return outputPlaneV3;
}
public override string ToString() => $"{nameof(PlaneV3<T>)}<{typeof(T).Name}>[{Width}, {Height}]";
public string ToDelimitedStringByHeightThenWidth(string separator = "\t")
{
return ToDelimitedString(Height, Width, separator, true);
}
public string ToDelimitedStringByWidthThenHeight(string separator = "\t")
{
return ToDelimitedString(Width, Height, separator, false);
}
private string ToDelimitedString(int outterCounter, int innerCounter, string separator, bool isHeightThenWidth)
{
var lines = new StringBuilder();
var columns = new StringBuilder();
for (int x = 0; x < outterCounter; x++)
{
var columnDelimiter = string.IsNullOrWhiteSpace(separator) ? "" : separator;
for (int y = 0; y < innerCounter; y++)
{
if (isHeightThenWidth)
{
columns.Append(columnDelimiter + Grid[y, x].ToString());
}
else
{
columns.Append(columnDelimiter + Grid[x, y].ToString());
}
if (columnDelimiter == string.Empty) // more readability
{
columnDelimiter = string.IsNullOrWhiteSpace(separator) ? "\t" : separator;
}
}
lines.AppendLine(columns.ToString());
columns.Clear(); // Clear and reuse it instead of initiating a new object.
}
return lines.ToString();
}
} // class
</code></pre>
<p><strong>Test cases</strong></p>
<p>The usage cases of <code>PlaneV3</code> class above are as follows.</p>
<pre><code>PlaneV3<string> planeV3_1 = new PlaneV3<string>(6, 6);
for (int j = 0; j < 6; j++)
{
for (int i = 0; i < 6; i++)
{
planeV3_1.Grid[i, j] = "(" + i + "," + j + ")";
}
}
Console.WriteLine(planeV3_1.SubPlane(1, 1, 3, 3).ToDelimitedStringByHeightThenWidth());
Console.WriteLine("");
Console.WriteLine(planeV3_1.SubPlane(1, 1, 3, 3).ToDelimitedStringByWidthThenHeight());
PlaneV3<string> planeV3_2 = new PlaneV3<string>(6, 6);
for (int j = 0; j < 6; j++)
{
for (int i = 0; i < 6; i++)
{
planeV3_2.Grid[i, j] = "(" + i + "," + j + ")";
}
}
Console.WriteLine(planeV3_1.Equals(planeV3_2).ToString());
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250418/231235">Generic Two Dimensional Data Plane with Manipulation Methods For C#</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251570/231235">A SubPlane Method for Generic Two Dimensional Data Plane in C#</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<ul>
<li><p>In <code>SubPlane</code> method, <code>Array.Copy</code> is used instead of regular <code>for</code> loop.</p>
</li>
<li><p>Trying to implement <code>ConcatenateHorizontal</code> based on <code>Array.Copy</code> method.</p>
</li>
</ul>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement or any other potential defect, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Major mistake <code>Grid = new T[width, height];</code>, must be <code>Grid = new T[height, width];</code>. Maybe better to use <code>Rows</code> and <code>Columns</code> e.g. <code>new T[rows, columns]</code>? In further code you made a lot of bugs related to this issue.</p>\n<h3>Properties</h3>\n<ul>\n<li>First of all make the <code>Grid</code> immutable. It looks like developer can replace the array with any other one.</li>\n<li>Every time I ask <code>Length</code>, it will be calculated from with and height. It can be done only once in constructor.</li>\n</ul>\n<h3>ConcatenateHorizontal</h3>\n<ul>\n<li>Checking <code>input.Grid is null</code> is a kind of redundancy. I can't imagine the scenario.</li>\n<li><code>throw new ArgumentNullException(nameof(input))</code> - pass the name of the argument to exception, it would be easier to debug that, especially in methods with multiple arguments. And/or pass an exception message text.</li>\n<li><code>if (someBool.Equals(false))</code> can be replaced with <code>if (!someBool)</code>.</li>\n<li>A typo in <code>Array.Copy(this.Grid, x * this.Height, output.Grid, x * output.Height, this.Height);</code> the last argument must be must be <code>this.Width</code>? Guessing that caused by <code>Width</code> and <code>Height</code> issue.</li>\n<li><code>i</code>, <code>j</code> or <code>x</code>,<code>y</code> can mislead you when you work with arrays, use <code>row</code>,<code>col</code> because it sound the same as you think about it.</li>\n<li>You changed one inner loop or <code>Array.Copy</code>, you can change both.</li>\n</ul>\n<h3>Equals</h3>\n<ul>\n<li><code>obj</code> can be <code>null</code> or wrong type, you missed a check. Also better to use pattern matching with assignment here.</li>\n<li><code>this.Grid.Rank == input.Grid.Rank</code> is redundant check.</li>\n<li><code>System.Linq.Enumerable.Range</code> - better to add <code>using System.Linq;</code> directive and write simply <code>Enumerable.Range</code> but it's faster and simpler to check <code>Width</code> and <code>Height</code> because you have known amount of dimensions and only two.</li>\n</ul>\n<h3>SubPlane</h3>\n<ul>\n<li><code>if (this.Grid == null)</code> - it can't be null.</li>\n<li>Missed checking of arguments to fit the source area.</li>\n</ul>\n<h3>ToString</h3>\n<ul>\n<li>Again <code>Height</code> and <code>Width</code></li>\n</ul>\n<h3>WithThenHeight and HeightThenWidth</h3>\n<ul>\n<li>Probably these methods created after <code>Width</code> and <code>Height</code> issue. Make a string as the array is with exact rows and columns count. I removed these methods as redundant ones.</li>\n</ul>\n<h3>ToDelimitedString</h3>\n<ul>\n<li>One <code>StringBuilder</code> is enough</li>\n<li>A kind of <code>columns.Append(columnDelimiter + Grid[y, x].ToString());</code> can be replaced with <code>columns.Append(columnDelimiter).Append(Grid[y, x].ToString());</code> because <code>StringBuilder</code> is intended to replace <code>string</code> concatenations with rather faster solution.</li>\n<li>You have arguments for size of output section but no arguments for its location. I remove that arguments as inconsistent with data.</li>\n<li>Why not Space as default <code>separator</code>? For readability. Also you may calculate a padding to avoid using <code>\\t</code> as unstable solution e.g. you need different amount of <code>\\t</code> from one to align <code>123456789012</code> and <code>0</code>. Let's make it smarter.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>[Serializable]\npublic class PlaneV3<T>\n{\n public int Width { get; }\n\n public int Height { get; }\n\n public T[,] Grid { get; }\n\n public int Length { get; }\n\n public PlaneV3() : this(1, 1) { }\n\n public PlaneV3(int width, int height)\n {\n Width = width;\n Height = height;\n Grid = new T[height, width];\n Length = Width * Height;\n }\n\n public PlaneV3(PlaneV3<T> plane) : this(plane?.Grid ?? throw new ArgumentNullException(nameof(plane))) { }\n\n public PlaneV3(T[,] sourceGrid)\n {\n if (sourceGrid is null)\n {\n throw new ArgumentNullException(nameof(sourceGrid));\n }\n\n Height = sourceGrid.GetLength(0);\n Width = sourceGrid.GetLength(1);\n Length = Width * Height;\n Grid = new T[Height, Width];\n Array.Copy(sourceGrid, Grid, sourceGrid.Length);\n }\n\n public PlaneV3<T> ConcatenateHorizontal(PlaneV3<T> input)\n {\n if (input is null)\n {\n throw new ArgumentNullException(nameof(input));\n }\n\n if (this.Height != input.Height)\n {\n throw new ArgumentException("Height isn't match", nameof(input.Height));\n }\n\n var output = new PlaneV3<T>(this.Width + input.Width, this.Height);\n for (int row = 0; row < this.Height; row++)\n {\n Array.Copy(this.Grid, row * this.Width, output.Grid, row * output.Width, this.Width);\n Array.Copy(input.Grid, row * input.Width, output.Grid, row * output.Width + this.Width, input.Width);\n }\n\n return output;\n }\n\n public PlaneV3<T> ConcatenateHorizontalInverse(PlaneV3<T> input)\n {\n return input.ConcatenateHorizontal(this);\n }\n\n public override bool Equals(object obj)\n {\n return obj is PlaneV3<T> input && this.Width == input.Width && this.Height == input.Height && this.Grid.Cast<T>().SequenceEqual(input.Grid.Cast<T>());\n }\n\n public PlaneV3<T> SubPlane(int locationX, int locationY, int newWidth, int newHeight)\n {\n if (locationX < 0 || locationX >= this.Width)\n throw new ArgumentException("Location must be inside the area", nameof(locationX));\n if (locationY < 0 || locationY >= this.Height)\n throw new ArgumentException("Location must be inside the area", nameof(locationY));\n // perform other similar checks here if needed\n\n PlaneV3<T> outputPlaneV3 = new PlaneV3<T>(newWidth, newHeight);\n for (int row = 0; row < newHeight; row++)\n {\n Array.Copy(this.Grid, (row + locationY) * this.Width + locationX, outputPlaneV3.Grid, row * newWidth, newWidth);\n }\n return outputPlaneV3;\n }\n\n public override string ToString() => $"{nameof(PlaneV3<T>)}<{typeof(T).Name}>[{Height}, {Width}]";\n\n public string ToDelimitedString(string separator = " ")\n {\n var sb = new StringBuilder();\n string[,] output = new string[this.Height, this.Width];\n int maxLength = 0;\n\n for (int row = 0; row < this.Height; row++)\n {\n for (int column = 0; column < this.Width; column++)\n {\n string s = this.Grid[row, column].ToString();\n output[row, column] = s;\n maxLength = Math.Max(maxLength, s.Length);\n }\n }\n \n for (int row = 0; row < this.Height; row++)\n {\n for (int column = 0; column < this.Width; column++)\n {\n sb.Append(output[row, column].PadLeft(maxLength)).Append(separator);\n }\n sb.Remove(sb.Length - separator.Length, separator.Length).AppendLine();\n }\n \n return sb.ToString();\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T00:52:15.467",
"Id": "503108",
"Score": "1",
"body": "Thank you for the answer. Wondering why `T[height, width]`, or `T[rows, colums]`. Is it because of the sequence of data storage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T00:53:56.357",
"Id": "503109",
"Score": "1",
"body": "@JimmyHu yes, exactly. Let me add few more improvements to the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:00:56.670",
"Id": "503111",
"Score": "1",
"body": "I appreciate your answer! Let me check it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:06:49.540",
"Id": "503114",
"Score": "1",
"body": "@JimmyHu I didn't test it because i wrote the code from my mobile phone, far away from nearest PC. :) Sorry if some typos there. As further `ToDelimitedString` improvement you can calculate `maxLength` separately for each column and store to some `int[Width]` array to make the output more compact in some cases. The idea is very easy to catch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:34:53.297",
"Id": "503140",
"Score": "1",
"body": "@JimmyHu Thanks for corrections! Checking it on my PC, made `ToDelimitedString` `public`. Looks like it works."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T00:32:24.303",
"Id": "255069",
"ParentId": "254972",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:26:25.123",
"Id": "254972",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"generics",
"classes"
],
"Title": "A Generic Two Dimensional Data Plane with SubPlane Method in C#"
}
|
254972
|
<p>I have this find function. Is it concise, efficient and readable with good logic flow?</p>
<pre><code>// findFirstStringInBracket finds the first string enclosed in brackets.
func findFirstStringInBracket(str string) string {
if len(str) > 0 {
indexFirstBracketFound := strings.Index(str, "(")
if indexFirstBracketFound >= 0 {
runes := []rune(str)
wordsAfterFirstBracket := string(runes[indexFirstBracketFound:len(str)])
indexClosingBracketFound := strings.Index(wordsAfterFirstBracket, ")")
if indexClosingBracketFound >= 0 {
runes := []rune(wordsAfterFirstBracket)
return string(runes[1 : indexClosingBracketFound-1])
} else {
return ""
}
} else {
return ""
}
} else {
return ""
}
return ""
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T13:12:44.380",
"Id": "502959",
"Score": "3",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
}
] |
[
{
"body": "<p>You took something simple and made it complicated. Keep it simple and readable.</p>\n<pre><code>func findFirstStringInBrackets(s string) string {\n i := strings.IndexByte(s, '(')\n if i < 0 {\n return ""\n }\n i++\n j := strings.IndexByte(s[i:], ')')\n if j < 0 {\n return ""\n }\n return s[i : i+j]\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T06:13:16.227",
"Id": "254983",
"ParentId": "254979",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254983",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T03:52:50.677",
"Id": "254979",
"Score": "-1",
"Tags": [
"performance",
"go"
],
"Title": "Find string enclosed in brackets"
}
|
254979
|
<p>I have this function and need to refactor it</p>
<p>Please refactor the code below to make it more concise, efficient and readable with good logic flow</p>
<pre><code>function findFirstStringInBracket($str){
if(strlen($str) > 0){
$firstbracket = strstr($str, '(');
if($firstbracket){
$firstbracket = ltrim($firstbracket, '(');
return strstr($firstbracket, ')', true);
}else{
return '';
}
}else{
return '';
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T10:01:31.637",
"Id": "502949",
"Score": "0",
"body": "Looks like a homework"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T17:20:43.767",
"Id": "502972",
"Score": "0",
"body": "The current title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T17:21:30.777",
"Id": "502973",
"Score": "0",
"body": "Please explain the code you posted. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] |
[
{
"body": "<p>I find my snippet below to be direct, concise, and readable (but I rarely have any trouble reading regex patterns).</p>\n<p>The pattern literally matches the first occurring opening parenthesis, then captures one or more non-closing-parenthesis characters, then matches the required closing parenthesis.</p>\n<p>A regex approach means a single function call solution and only one <code>return</code> in your custom function (which makes your code cleaner to read).</p>\n<p>Other devs may prefer to avoid regex, but I think this is a perfect case for employing it.</p>\n<p><strong>One note of difference between my script and yours, is that if the closing parenthesis is missing in the input string with your script, your function will return <code>false</code>. My script will always return a string.</strong> (see <a href=\"https://3v4l.org/CDeE0\" rel=\"nofollow noreferrer\">here</a>)</p>\n<p>Code:</p>\n<pre><code>function findFirstStringInBracket(string $string): string\n{\n return preg_match('~\\(([^)]+)\\)~', $string, $match) ? $match[1] : '';\n}\n</code></pre>\n<p>Unless you are doing hundreds of thousands of iterations of this call, performance probably isn't an issue. If it is a bottle neck, then you probably want to look at other ways to improve script performance.</p>\n<p><a href=\"https://3v4l.org/dRYEI\" rel=\"nofollow noreferrer\">(Demo with some test cases)</a></p>\n<pre><code>$strings = [\n 'the(crow)bar',\n 'foo()bar',\n 'handlebar()',\n '()foofighters',\n '(foobar)',\n '()',\n 'barfood',\n 'barf(oo',\n 'fooeybar)',\n ')foob(',\n];\n\n$result = [];\nforeach ($strings as $string) {\n $result[$string] = preg_match('~\\(([^)]+)\\)~', $string, $match) ? $match[1] : '';\n}\nvar_export($result);\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 'the(crow)bar' => 'crow',\n 'foo()bar' => '',\n 'handlebar()' => '',\n '()foofighters' => '',\n '(foobar)' => 'foobar',\n '()' => '',\n 'barfood' => '',\n 'barf(oo' => '',\n 'fooeybar)' => '',\n ')foob(' => '',\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T12:25:31.760",
"Id": "254995",
"ParentId": "254980",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254995",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:04:46.923",
"Id": "254980",
"Score": "2",
"Tags": [
"performance",
"php",
"strings"
],
"Title": "Extract string between first occurring set of parenthesis"
}
|
254980
|
<p>I've created binary classification model from scratch, just to understand intuition behind that.</p>
<p>However when I compare my implementation to model from tensorflow/pytorch with the same parameters and configuration I noticed that my model achieved similar results in about <strong>3 000 epochs</strong> but tensorflow/pytorch model achieved that in <strong>300 epochs</strong>.</p>
<p>I also noticed that my model calculates very small gradient when tensorflow/pytorch calculates a much higher gradient in every epoch</p>
<ul>
<li>Is there any way to optimize calculating gradient in <code>backward</code> function to make model learning faster?</li>
<li>Is there any other such field that could be optimized/simplified and how could it be implemented</li>
</ul>
<p>Below is my <code>backward</code> function responsible for calculating gradient:</p>
<pre class="lang-py prettyprint-override"><code>def backward(
y: np.ndarray,
y_pred: np.ndarray,
layers: List[ Dict[ str, np.ndarray ] ]
) -> None:
loss: np.ndarray = binary_cross_entropy_loss_prime(y, y_pred)
for layer in reversed(layers):
dZ: np.ndarray = layer['prime'](layer['z']) * loss
layer['db'] = (dZ * np.ones_like(layer['b'])).sum(axis = 0, keepdims=True) / loss.shape[0]
dU: np.ndarray = dZ * np.ones_like(layer['u'])
layer['dw'] = np.dot(layer['x'].T, dU) / loss.shape[0]
loss = np.dot(dU, layer['w'].T)
</code></pre>
<p>and also full code with data types to easier understanding:</p>
<pre class="lang-py prettyprint-override"><code>
"""# Dataset and libraries"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import List, Dict
from sklearn.datasets import make_moons
x, y = make_moons(n_samples = 1000, noise = 0.2, random_state = 100)
# expand y second dim
# before expand_dims -> y.shape = (1000, )
# after expand_dims -> y.shape = (1000, 1)
y = np.expand_dims(y, 1)
# final shapes: X -> (1000, 2), Y -> (1000, 1)
"""# Activations functions"""
def sigma(x: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-x))
def sigma_prime(x: np.ndarray) -> np.ndarray:
e = np.exp(x)
return e / (e + 1) ** 2
def relu(x: np.ndarray) -> np.ndarray:
return np.maximum(0, x)
def relu_prime(x: np.ndarray) -> np.ndarray:
return np.where(x <= 0, 0, 1)
"""# Dense layers"""
dense_layers = [
{ 'w': np.random.rand(2, 8) * 0.1, 'b': np.random.rand(1, 8) * 0.1, 'activ': relu, 'prime': relu_prime },
{ 'w': np.random.rand(8, 8) * 0.1, 'b': np.random.rand(1, 8) * 0.1, 'activ': relu, 'prime': relu_prime },
{ 'w': np.random.rand(8, 1) * 0.1, 'b': np.random.rand(1, 1) * 0.1, 'activ': sigma, 'prime': sigma_prime }
]
"""# Losses and metrics """
def binary_cross_entropy_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:
number_of_rows = y_true.shape[0] # 1000 rows
number_of_cols = y_true.shape[1] # 1 cols
return np.sum(-(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))) / number_of_rows * number_of_cols
def binary_cross_entropy_loss_prime(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
return (1 - y_true) / (1 - y_pred) - y_true / y_pred
def accuracy(y_true: np.ndarray, y_pred: np.ndarray, threshhold: float = 0.5) -> float:
return (np.where(y_pred <= threshhold, 0, 1) == y_true).mean()
"""# Forward propagation"""
def forward(x: np.ndarray, layers: List[ Dict[ str, np.ndarray ] ]) -> np.ndarray:
for layer in layers:
layer['x'] = x
layer['u'] = np.dot(x, layer['w'])
layer['z'] = layer['u'] + layer['b']
layer['a'] = layer['activ'](layer['z'])
x = layer['a']
return x
"""# Backward propagation"""
def backward(y: np.ndarray, y_pred: np.ndarray, layers: List[ Dict[ str, np.ndarray ] ]) -> None:
loss: np.ndarray = binary_cross_entropy_loss_prime(y, y_pred)
for layer in reversed(layers):
dZ: np.ndarray = layer['prime'](layer['z']) * loss
layer['db'] = (dZ * np.ones_like(layer['b'])).sum(axis = 0, keepdims=True) / loss.shape[0]
dU: np.ndarray = dZ * np.ones_like(layer['u'])
layer['dw'] = np.dot(layer['x'].T, dU) / loss.shape[0]
loss = np.dot(dU, layer['w'].T)
"""# Update weights and biases (SGD optimizer)"""
def update(layers: List[ Dict[ str, np.ndarray ] ], learning_rate: float) -> None:
for layer in layers:
layer['w'] -= learning_rate * layer['dw']
layer['b'] -= learning_rate * layer['db']
"""# Train model"""
def train(x: np.ndarray, y: np.ndarray, layers: List[ Dict[ str, np.ndarray ] ], epochs: int, learning_rate: float) -> None:
for epoch in range(epochs):
# Forward propagation
y_hat = forward(x, layers)
# Backward propagation
backward(y, y_hat, layers)
# Update layers
update(layers, learning_rate)
# show progress
if epoch % 100 == 0:
print('Iteration nr: ', epoch, ', loss: ', binary_cross_entropy_loss(y, y_hat), ', accuracy: ', accuracy(y, y_hat))
train(x, y, dense_layers, 3001, 0.01)
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T10:29:36.773",
"Id": "254988",
"Score": "2",
"Tags": [
"python",
"numpy",
"machine-learning",
"ai"
],
"Title": "Optimize binary classification model"
}
|
254988
|
<p>I have a GAMS code that represent a mathematical model which depends delay (i,p) for each job i and the period of day p. So, I have indices for represent delay and objective is minimizing of summing these delays.</p>
<p>Constraints example..</p>
<p>The structure in GAMS:</p>
<pre><code>constraint(this part means constraint covers each indice in this part)$(if condition structure)..
(constraint function is here)
</code></pre>
<p>The model constraint example:</p>
<pre><code>*jobstart, delay: variables
*readytime, distance_oven and speed_cookline: parameters
constraint1(i,j,u,p)$(param1(j,u)>0 and j=param2(i) and p = param3(i))..
jobstart(i) = readytime(i) + (distance_oven(j,u)/(speed_cookline(j,u)))*3600 + delay1(i);
constraint2(i,i2,j,j2,u,u2)$(i<>k and j=param2(i) and n=param2(i2) and param1(j,u) = 1 and param1(j2,u2) = 1 and u=u2)..
abs(jobstart(i) - jobstart(i2)) => 120
objective function: min sum(delay1(i,p))
</code></pre>
<p>Is there a ready-structure to solve the problem or do I have to code it as heuristic then implement this code into the PSO?</p>
<p>*I asked that because I define simulated annealing for another problem by approaching it as heuristic and then implement it into the simulated annealing. But, it is so exhaustive and not effective coding to control constraints for assigned random delays in the way of PSO coding.</p>
<p>Thanks,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T10:45:24.787",
"Id": "502950",
"Score": "0",
"body": "Pseudocode, stub code, hypothetical code & obfuscated code are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T11:00:50.143",
"Id": "502951",
"Score": "0",
"body": "Code what I share is not pseudocode, it is code in actually I use in GAMS so already it is a real code and rest of the part of the question has similar constraints. So, sharing all is just expanding the question size, I think it is not helping me to share the rest of them. Thanks for comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T13:12:07.680",
"Id": "502958",
"Score": "0",
"body": "I don't think so. Are you saying that `cosntraint3.....constraint14 mostly similar types.` is valid in this language?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:17:56.580",
"Id": "502979",
"Score": "0",
"body": "just think there are 3 constraints, what is the difference?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T10:32:41.420",
"Id": "254989",
"Score": "1",
"Tags": [
"object-oriented",
"matlab",
"heuristic"
],
"Title": "How to code a minimization problem with constraints and indices into PSO within MATLAB?"
}
|
254989
|
<p>I wrote a fairly simple program that grades theory-based quizzes. It is fairly straightforward. I would love to get insights and ideas on how it might be improved.</p>
<h3><code>consine_similarity.py</code></h3>
<pre><code>"""This module uses consine distance to check the similarity between two sentences"""
from nltk.corpus import stopwords
from nltk.cluster.util import cosine_distance
from nltk.tokenize import word_tokenize
def consine_similarity(sent1: str, sent2: str) -> float:
"""Consine similarity between two sentences
sent1: str
sent2: str
"""
sent1_list = word_tokenize(sent1)
sent2_list = word_tokenize(sent2)
stop_words = stopwords.words('english')
all_words = list(set(sent1_list + sent2_list))
vector1 = [0] * len(all_words)
vector2 = [0] * len(all_words)
for word in sent1_list:
if word in stop_words:
continue
vector1[all_words.index(word)] += 1
for word in sent2_list:
if word in stop_words:
continue
vector2[all_words.index(word)] += 1
return 1 - cosine_distance(vector1, vector2)
</code></pre>
<h3><code>quiz.py</code></h3>
<pre><code>"""Theory-based quiz application"""
from dataclasses import dataclass
from random import shuffle
from consine_similarity import consine_similarity
@dataclass
class Quiz:
"""Quiz data"""
quiz: str
answer: str
def __str__(self):
return '{}'.format(self.quiz)
def start_quiz(quiz_list: list) -> None:
"""Start the quiz application"""
shuffle(quiz_list)
consine_list = []
for quiz in quiz_list:
print(quiz)
answer = input('> ')
consine_list.append(consine_similarity(quiz.answer, answer))
print()
grade = sum(consine_list) / len(consine_list) * 100
print('Your grade is {:.2f}%'.format(grade))
if __name__ == "__main__":
QUIZ_LIST = [
Quiz(quiz='What is a computer?',
answer='An electronic device for storing and processing data, \
typically in binary form, according to instructions given to it'),
Quiz(quiz='What are logic gates?',
answer='These are the basic building blocks of any digital system. It is an \
electronic circuit having one or more than one input and only one output'),
Quiz(quiz='What is BIOS',
answer='This is firmware used to perform hardware initialization during the booting \
process and to provide runtime services for operating systems and programs'),
]
start_quiz(QUIZ_LIST)
</code></pre>
|
[] |
[
{
"body": "<p>There is no need to include stop words in the dictionary if they are filtered out of the vectors anyway. Thus, tokenization and stop words removal can be considered as a single step. Secondly, the vectors can be initialized with the correct values immediately by taking advantage of <code>collections.Counter</code></p>\n<pre><code>from collections import Counter\nfrom typing import List\nfrom nltk.corpus import stopwords\nfrom nltk.cluster.util import cosine_distance\nfrom nltk.tokenize import word_tokenize\n\ndef tokenize_without_stop_words(sentence:str) -> List[str]:\n return [\n word\n for word in word_tokenize(sentence)\n if word not in stopwords.words('english')\n ]\n\ndef cosine_similarity(first_sentence: str, second_sentence: str) -> float:\n first_words = tokenize_without_stop_words(first_sentence)\n second_words = tokenize_without_stop_words(second_sentence)\n\n dictionary = list(set(first_words+second_words))\n\n def encode(words: List[str]) -> List[int]:\n word_counts = Counter(words)\n return [\n word_counts[word]\n for word in dictionary\n ]\n\n first_vector = encode(first_words)\n second_vector = encode(second_words)\n\n return 1 - cosine_distance(first_vector, second_vector)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:58:14.177",
"Id": "255022",
"ParentId": "254994",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T12:20:07.727",
"Id": "254994",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Theory-based quiz grader using similarity"
}
|
254994
|
<p>I created a <code>dates_in_range()</code> function which checks if all of the dates passed to it (<code>$dates</code> array) are within <code>$start_date</code> and <code>$end_date</code>. If they aren't, it'll return false.</p>
<p>The code works fine, but I'm wondering if there's a way to refactor it better using something like <code>array_filter</code>? Or does this look fine?</p>
<pre><code>function dates_in_range( $start_date, $end_date, $dates = array() ) {
foreach ( $dates as $date ) {
if ( ! ( ( (strtotime( $date ) >= strtotime( $start_date ) ) && ( strtotime( $date ) <= strtotime( $end_date ) ) ) ) ) {
return false;
}
}
return true;
}
$dates = array(
'2021-11-19 00:00:00',
'2020-11-20 00:00:00',
);
$start_date = '2021-10-01 00:00:00';
$end_date = '2021-12-31 00:00:00';
// Returns true
if ( dates_in_range( $start_date, $end_date, $dates ) ) {
echo "In range.";
} else {
echo "Not in range.";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:25:23.540",
"Id": "502982",
"Score": "3",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T13:46:27.153",
"Id": "503065",
"Score": "0",
"body": "Do the dates come from database query results? if so, is it a flavor of SQL like MySQL?"
}
] |
[
{
"body": "<p>The function seems okay. In Javascript one could use the method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\"><code>Array.every()</code></a>, but as <a href=\"https://stackoverflow.com/q/45156664/1575353\">this StackOverflow question</a> illustrates there isn't really an equivalent method or functional approach in PHP that will stop the loop as soon as one element does not meet the requirement.</p>\n<p>You might consider adhering to the <a href=\"https://www.php-fig.org/psr\" rel=\"nofollow noreferrer\">PSR PHP Coding standards</a> - especially <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR 12</a>.</p>\n<p>PSR-12 has a section about Lines:</p>\n<blockquote>\n<h3><a href=\"https://www.php-fig.org/psr/psr-12/#23-lines\" rel=\"nofollow noreferrer\">2.3 Lines</a></h3>\n<p>There MUST NOT be a hard limit on line length.<br><br>\nThe soft limit on line length MUST be 120 characters.<br><br>\nLines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.\n<sup><a href=\"https://www.php-fig.org/psr/psr-12/#23-lines\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>Readabillity suffers because the conditional line is a bit long, partly because of the indentation but also the additional spaces separating parentheses. It may not be an issue for anyone with a wide screen but as is visible in the code snippet one must scroll to the right to see the entire line. While it may only be a micro-optimization, one could pull out the <code>strototime($date)</code> out to a variable, which would not only decrease function calls but also allow for a shorter line. Similarly the calls to <code>strtotime()</code> for the start and end dates could be pulled out of the <code>foreach</code> loop and stored in variables so they only need to be calculated once per function call and can decrease the length of that line with the conditional.</p>\n<p>I question whether the third parameter having a default of an empty array is appropriate. If the function is called without any argument, then an empty array will be used and the function will return <code>true</code>. Perhaps using type hinting would be a better technique:</p>\n<pre><code>function dates_in_range( string $start_date, string $end_date, array $dates) : bool {\n</code></pre>\n<p>Notice that method signature includes a <a href=\"https://www.php.net/manual/en/language.types.declarations.php\" rel=\"nofollow noreferrer\">return type declaration</a> <code>bool</code>. This was added in PHP 7.0 <sup><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.return-type-declarations\" rel=\"nofollow noreferrer\">2</a></sup>. Hopefully your code is running on PHP 7.3 or newer, since those are the version that are officially supported <sup><a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">3</a></sup>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T15:47:51.877",
"Id": "255004",
"ParentId": "255002",
"Score": "4"
}
},
{
"body": "<p>To me it looks fine, other than it makes me scroll the code to read it. On this ground I agree with Sam, that line ought to be shortened. To do so I would</p>\n<ul>\n<li>use the fact that you don't need to convert mysql format dates to compare them</li>\n<li>remove excessive bracing</li>\n<li>use De Morgan's law to invert the condition</li>\n</ul>\n<p>and get this</p>\n<pre><code>function dates_in_range( string $start_date, string $end_date, array $dates ): bool\n{\n foreach ( $dates as $date ) {\n if ( $date < $start_date || $date > $end_date ) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>Also, I removed the default value for the $dates as I don't see any use in calling this function with only two parameters.</p>\n<p>I am not sure about empty arrays though. Your function will return true for one, but it's hard to tell whether it's correct or not. It's like division by zero, and may be an exception must be thrown.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T08:51:18.217",
"Id": "503045",
"Score": "0",
"body": "There are pros and cons about using `strtotime`, your answer assumes the dates are properly mysql formatted dates but the OP doesn't precise it and it may not be the case, for some UI inputs, zeroes can be forgotten, then `'2021-11-19 08:00:00'` and `'2021-11-19 8:00:00'` dates would not compare the same in term of alphabetical order, while `strtotime` produces the right timestamp for both of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T09:45:47.047",
"Id": "503046",
"Score": "1",
"body": "I agree. it's better to provide DateTime instances over strings or validate the input data otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:21:21.827",
"Id": "503697",
"Score": "0",
"body": "Ditto to @YourCommonSense comment... stringified dates was prolific in our code, for comparison and otherwise. It made routine maintenance changes unnecessarily convoluted because the programmer used the date-strings instead of the DateTime class. And surrounding code looked like the coder was thinking \"string\", not \"date AND time\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:15:46.337",
"Id": "255019",
"ParentId": "255002",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T15:07:30.710",
"Id": "255002",
"Score": "6",
"Tags": [
"php",
"array",
"datetime"
],
"Title": "Checking if an array of dates are within a date range"
}
|
255002
|
<p>Compared to the recursive version e.g. on Rosetta, this is 5-10% faster and uses 50% less instructions (for N=12).</p>
<p>Only problem is the <code>goto</code>. Can it be avoided without using a function?</p>
<p>The two outer for-loops don't do much in terms of loop control. But this is how I could make it work.</p>
<p>Is there a more convincing non-recursive version? I searched quite a bit and most are recursive and/or longer.</p>
<pre><code>/* N-Queens, non-recursive, with goto */
#include <stdio.h>
//const int N = 8; //92 solutions
const int N = 12; //14200 in 0.100 s
/* Print excluding last row, plus last col */
void pr_solution(int *bq, int col) {
for (int i = 0; i < N - 1; i++)
printf("%d:", bq[i]);
printf("%d\n", col);
}
void init_board(int bq[], int v) {
for (int i = 0; i < N; i++)
bq[i] = v;
}
int main() {
int bq[N];
init_board(bq, -1);
int row, col, rd, old;
int cnt = 0;
for (row = 0; row >= 0;) {
for (col = bq[row];;) {
NEXT_col:
if (++col == N)
bq[row--] = -1;
else {
for (rd = 1; rd <= row; rd++)
if ((old = bq[row-rd]) == col || old == col+rd || old == col-rd)
goto NEXT_col;
if (row == N - 1) {
cnt++;
row--;
//pr_solution(bq, col);
}
else
bq[row++] = col;
}
break;
}
}
printf("%d SOLUTIONS (%dx%d)\n", cnt, N, N);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>void pr_solution(int *bq, int col) {\nvoid init_board(int bq[], int v) {\n</code></pre>\n</blockquote>\n<p>These could be declared with <code>static</code> linkage.</p>\n<hr />\n<blockquote>\n<pre><code>int main() {\n</code></pre>\n</blockquote>\n<p>Prefer <code>int main(void)</code> to make this declaration a prototype (takes no arguments, rather than unspecified arguments).</p>\n<hr />\n<blockquote>\n<pre><code>int row, col, rd, old;\n</code></pre>\n</blockquote>\n<p>All of these could have smaller scope. E.g.</p>\n<pre><code>for (int row = 0; row >= 0;) {\n</code></pre>\n<p>It's always best to declare and initialise at the same time, rather than leaving a window where the variable exists but is not initialised.</p>\n<hr />\n<blockquote>\n<pre><code> //pr_solution(bq, col);\n</code></pre>\n</blockquote>\n<p>Commented-out code is prone to becoming inconsistent. Either remove it, or uncomment it (and perhaps provide a command-line argument to enable/disable).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T16:24:11.777",
"Id": "255008",
"ParentId": "255003",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>Only problem is the goto. Can it be avoided without using a function?</p>\n</blockquote>\n<p>Candidate <code>goto</code> replacement</p>\n<pre><code> for (col = bq[row];;) {\n //NEXT_col: // Delete\n if (++col == N) \n bq[row--] = -1;\n else {\n for (rd = 1; rd <= row; rd++)\n if ((old = bq[row-rd]) == col || old == col+rd || old == col-rd)\n // goto NEXT_col; // Delete\n break; //ADD\n if (rd <= row) continue; // ADD\n if (row == N - 1) {\n cnt++;\n row--;\n //pr_solution(bq, col); \n }\n else \n bq[row++] = col;\n }\n break;\n }\n</code></pre>\n<p><code>if (rd <= row) continue;</code> takes advantage that <code>for (col = bq[row];;)</code> lacks a test and increment.</p>\n<blockquote>\n<p>Is there a more convincing non-recursive version?</p>\n</blockquote>\n<p>I'd re-write the loop (perhaps a <a href=\"https://en.wikipedia.org/wiki/Finite-state_machine\" rel=\"nofollow noreferrer\">state machine</a>) - need some time to think about it.</p>\n<hr />\n<p><strong>Later:</strong></p>\n<p>Code as written is quite tight. A <em>very nice</em> simple non-recursive solution.</p>\n<p>Yet (at the risk of the ire of OP) lacks clarity making it unnecessarily difficult to optimize.</p>\n<p>The <em>style</em> uses terse variable names like <code>rd</code> and <code>bq</code> which do not well convey their meaning. It is as if short variable names make faster code (it does not). <code>init_board()</code> does not initialize a board, but a single dimension of data. Use more meaningful names.</p>\n<p>Use of incomplete <code>for</code> loops like <code>for (col = bq[row];;)</code> seems like a code golf goal than a clearer <code>col = bq[row]; while (1)</code>.</p>\n<p>Helper functions like <code>pr_solution()</code> rely on the global <code>N</code>, which instead could be passed in, facilitating clearer function flow and allowing use with more than one size.</p>\n<p>Local variable instantiation would help see their limited impact.</p>\n<p>For clarity, use <code>{}</code> even for one-line blocks.</p>\n<p>Consider rectangles, not only squares. It adds clarity to code and offers other investigations for eventual optimization.</p>\n<p>Some other ideas in code below too.</p>\n<p>A first round cut:</p>\n<pre><code>int main(void) {\n for (int N = 1; N <= 8; N++) {\n const int ROW_N = N;\n const int COL_N = ROW_N;\n int queen_column[ROW_N];\n init_queen_column(ROW_N, queen_column, -1);\n long long count = 0;\n int parity[2] = { 0,0};\n int row = 0;\n while (row >= 0) {\n int col = queen_column[row];\n while (1) {\n if (++col == COL_N) {\n queen_column[row--] = -1;\n } else {\n int row_offset;\n for (row_offset = 1; row_offset <= row; row_offset++) {\n int old = queen_column[row - row_offset];\n int diff = old - col;\n if ((diff == 0) || diff == row_offset || diff == -row_offset) {\n break;\n }\n }\n if (row_offset <= row) { // From early break above\n continue; // ADD\n }\n if (row == ROW_N - 1) {\n count++;\n // print_solution(ROW_N, queen_column, col); // Print, then change state.\n row--;\n } else {\n parity[(row ^ col)&1]++; // Count parity for later optimization (stub code)\n queen_column[row++] = col;\n }\n }\n break;\n }\n }\n printf("%lld SOLUTIONS (%dx%d)\\n", count, ROW_N, COL_N);\n }\n return 0;\n}\n1 SOLUTIONS (1x1)\n0 SOLUTIONS (2x2)\n0 SOLUTIONS (3x3)\n2 SOLUTIONS (4x4)\n10 SOLUTIONS (5x5)\n4 SOLUTIONS (6x6)\n40 SOLUTIONS (7x7)\n92 SOLUTIONS (8x8)\n</code></pre>\n<hr />\n<p><strong>Other idea to speed things up</strong></p>\n<ol>\n<li><p>Keep track of the count of queen placement on black (and/or white) squares. Once that exceeds about half of <code>N</code>, time to unwind as subsequent forward iterations will all fail.</p>\n</li>\n<li><p>Look for patterns. Example: Symmetry. A solution that starts with the first queen on column 0 will have as many solutions as column <code>N-1</code>. Looks like run time can be halved in some fashion.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T06:54:40.453",
"Id": "503133",
"Score": "0",
"body": "I DID rewrite the loop - dropped it, see answer. Now there is mostly lf-else, and this makes it more state-machiney."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T00:06:01.250",
"Id": "255030",
"ParentId": "255003",
"Score": "5"
}
},
{
"body": "<p>The second for-loop does so little, it can be replaced by a label, IF you stick with the <code>goto</code>:</p>\n<pre><code>for (row = 0; row >= 0;) {\n col = bq[row];\n NEXT_col:\n if (++col == N)\n bq[row--] = -1;\n else {\n for (rd = 1; rd <= row; rd++)\n if ((old = bq[row-rd]) == col || abs(old - col) == rd)\n goto NEXT_col;\n if (row == N - 1) {\n cnt++;\n row--;\n }\n else\n bq[row++] = col;\n }\n}\n</code></pre>\n<p>No more <code>break</code> at the end. That was the <em>other</em> thing that for-loop did: getting broken at the end. The first thing was: being jumped at with <code>continue</code> (or <code>goto</code>).</p>\n<p>I am quite happy now - it is still a "goto", but now it makes sense.</p>\n<p>As they say about this N-Queens problem: <strong>simple, but not trivial</strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:36:05.290",
"Id": "255066",
"ParentId": "255003",
"Score": "1"
}
},
{
"body": "<p>It turns out that keeping track of the threats in a 2D-array is <strong>twice as fast</strong>. Now instead of incrementing the column, and checking later, the next column is found by a function.</p>\n<p>The main loop is freed from the diagonal-checking. But now it has to add and also remove threats when a queen is moved.</p>\n<pre><code>/* Returns zeroed n*n array */\nint **init_threats(int n) {\n int r;\n int **t2d = malloc(n * sizeof*t2d);\n for (r = 0; r < n; r++)\n t2d[r] = calloc(n, sizeof**t2d);\n return t2d;\n}\n/* Only needs a row from "threats[][]" */\nint next_free(int *r, int after) {\n for (int c = after + 1; c < N; c++)\n if (r[c] == 0)\n return c;\n return -1;\n}\n/* Cumulative threats - they can overlap */\nvoid change_thr(int chg, int r, int c, int **threats) {\n int tr, diag;\n for (tr = r + 1; tr < N; tr++) { \n threats[tr][c] += chg;\n diag = c + tr - r;\n if (diag < N)\n threats[tr][diag] += chg; \n diag = c - (tr - r);\n if (diag >= 0)\n threats[tr][diag] += chg; \n }\n}\nint main() {\n int queen[N];\n init_board(queen, -1); \n int **threats = init_threats(N);\n int row = 0, cnt = 0;\n int col;\n while (row >= 0) {\n col = next_free(threats[row], queen[row]);\n if (row == N - 1) { \n if (col >= 0) \n cnt++;\n row--;\n } else {\n if (queen[row] >= 0)\n change_thr(-1, row, queen[row], threats); \n if (col >= 0) {\n change_thr(1, row, col, threats); \n queen[row++] = col;\n } else \n queen[row--] = -1;\n }\n } \n printf("%d SOLUTIONS (%d-Queens)\\n", cnt, N);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:15:55.730",
"Id": "255101",
"ParentId": "255003",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T15:39:57.647",
"Id": "255003",
"Score": "5",
"Tags": [
"c",
"n-queens"
],
"Title": "N-Queens without recursion (but with one goto)"
}
|
255003
|
<p>I feel like I'm likely violating a design principal or two here so I'd appreciate any mistakes or antipatterns being named and pointed out.</p>
<p>I'm attempting to map a system in code which represents a decision tree, so based on the users input would provide them the next choice they can make, then from their input to that the next, and so on.</p>
<p>The response to each choice is either:</p>
<ul>
<li>Binary Yes/No, so two different possible follow up choices.</li>
<li>1-10 range, so multiple possible follow up choices.</li>
</ul>
<p>Any choice type can return any other choice type so I've been aiming to have the result for the follow up choice to always be a generic IChoice.</p>
<pre><code>BinaryChoice current = NotifyPersonOrNot();
IChoice next = current.MakeChoice(true); // Binary choice
IChoice next1 = next.MakeChoice(5); // Range choice
IChoice next2 = next1.MakeChoice(3); // Range Choice
</code></pre>
<p>An issue I see with my current solution is usage of the <code>dynamic</code> keyword in my <code>IChoice MakeChoice(dynamic answer)</code> function. I used this to avoid having to do a specific cast for the <code>T</code> argument in the <code>Func<T, IChoice> GetNextChoice</code> function that the <code>MakeChoice</code> function calls with it's answer input.</p>
<p>I considered adding a</p>
<p>So the IChoice interface is like so as this is the only function I want to be used.</p>
<pre><code>public interface IChoice
{
// I feel like having to use dynamic here is a sign of a mistake in the design
public IChoice MakeChoice(dynamic answer);
}
</code></pre>
<p>My base class looks like this</p>
<pre><code>public abstract class Choice<T> : IChoice
{
public Choice(Func<T, IChoice> getNextChoice)
{
GetNextChoice = getNextChoice;
}
public Func<T, IChoice> GetNextChoice { get; set; }
// This seems cleaner than type checking but I'm thinking having to use dynamic indicates a mistake in class design
public IChoice MakeChoice(dynamic answer)
{
return GetNextChoice(answer);
}
}
</code></pre>
<p>And an implementation of the base class is like so, where Choice is given a Type. The RangeChoice version implements <code>Choice<int></code></p>
<pre><code>public class BinaryChoice : Choice<bool>
{
public override ChoiceType ChoiceType => ChoiceType.Binary;
public BinaryChoice(Func<bool, IChoice> getNextChoice) : base(getNextChoice) { }
}
</code></pre>
<p>The idea is that <code>GetNextChoice</code> can be set with the unique logic required to provide correct next choice in the tree.</p>
<pre><code> private BinaryChoice NotifyPersonOrNot()
{
// If we were returning a RangeChoice here we'd have more conditions in the function
return new BinaryChoice((sendNotification) =>
{
if (!sentNotification)
{
// This is another BinaryChoice
return AskAnotherYesNoQuestion();
}
// This is a RangeChoice
return AskRatingQuestion();
});
}
</code></pre>
<p>I've considered changing the <code>GetNextChoice</code> delegate to <code>Func<object, IChoice></code> but I would like to avoid the overhead of having to cast from <code>object</code> into the required type when defining each choice. It would preferable to do it once in a single place if it must always happen.</p>
<p>I've looked at adding a abstract <code>ChoiceType</code> enum to the <code>Choice</code> class and handling the type casting in the <code>MakeChoice</code> function but I'm not sure how to do this without explicitly setting a type for the <code>GetNextChoice</code> delegate.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:33:18.163",
"Id": "503051",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>I believe your question is more aimed at a what, where, and when to use the <code>dynamic</code> keyword more than a design philosophy. It just so happens that a good explanation exists here: <a href=\"https://cloudncode.blog/2016/07/12/c-dynamic-keyword-what-why-when/\" rel=\"nofollow noreferrer\">https://cloudncode.blog/2016/07/12/c-dynamic-keyword-what-why-when/</a></p>\n<p>The short and easy from the link:</p>\n<blockquote>\n<ol>\n<li>There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.</li>\n<li>The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.</li>\n<li>Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.</li>\n<li>It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.</li>\n</ol>\n</blockquote>\n<p>In my personal opinion - These functions are accepting rather simple data types (bool, int). It's more cumbersome on the CPU/Hardware to have a <code>dynamic</code> used than to just use function overloading to accomplish the same task without the needed stress. It is true that this may eliminate the need of type checking but you run a very large risk if these functions are used in uncontrolled events.</p>\n<p>Also, your confidence in the data being entered for <code>MakeChoice()</code> or any of the other dynamic parameter functions or functions using dynamic has to be as accurate as the sun coming up tomorrow. Otherwise, you may get runtime errors.</p>\n<p>Let me know if this helps - thanks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T05:16:29.360",
"Id": "255035",
"ParentId": "255013",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:00:04.337",
"Id": "255013",
"Score": "3",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Is this usage of the dynamic keyword an indicator of a design fault?"
}
|
255013
|
<p><a href="https://i.stack.imgur.com/s11sK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s11sK.png" alt="enter image description here" /></a>I need help to optimize my code for huge lists with approx. 10000000 elements. Is there a way to improve my algorithm or should I try to build a new one using a completely different approach?
Task: given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.</p>
<pre class="lang-py prettyprint-override"><code>def sum_pairs(ints, s):
lst1 = []
for n in ints:
if n in lst1:
return [s-n, n]
lst1.append(s-n)
lst3 = list(range(1,10000000))
sum_pairs(lst3, 20000000)
*Times out :(
#Using set() every time we add new item to the list doesn't help
def sum_pairs(ints, s):
lst1 = []
for n in ints:
lst2 = set(lst1)
if n in lst2:
return[s-n, n]
lst1.append(s-n)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:07:42.800",
"Id": "502978",
"Score": "0",
"body": "What is the purpose of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:22:53.130",
"Id": "502989",
"Score": "0",
"body": "Btw you should tag this as python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:29:48.623",
"Id": "502990",
"Score": "0",
"body": "I mean that you should just completely take the lst1 list out of the program and use a set instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T20:17:58.550",
"Id": "502998",
"Score": "2",
"body": "Please replace the top image with a code block containing equivalent text."
}
] |
[
{
"body": "<p>You could use a set as lst1 instead of a list. Every time you check if n is in lst1, it’s <span class=\"math-container\">\\$ O(n) \\$</span> time complexity. Using a set instead will lower that to <span class=\"math-container\">\\$ O(1) \\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:13:28.197",
"Id": "502986",
"Score": "1",
"body": "Correct answer in last example is [3, 7], not [5, 5] because 7 appears in the list of integers before second \"5\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:16:35.463",
"Id": "502987",
"Score": "0",
"body": "You’re right, somehow I misread it. Nvm, all you need is to use a set instead of a list. Then it should work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:46:52.583",
"Id": "502991",
"Score": "1",
"body": "Thank you, I completely forgot about sets as distinct data types, remembered only function call, nevermind that :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:48:52.690",
"Id": "255018",
"ParentId": "255014",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255018",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T18:03:44.490",
"Id": "255014",
"Score": "1",
"Tags": [
"performance",
"python-3.x",
"memoization"
],
"Title": "Optimizing solution of Sum of Pairs: Codewars in Python"
}
|
255014
|
<p>So this is a blackjack game, any feedback or tips on what I should remove from the code that is not needed is very appreciated.</p>
<p>Note: some of the names of classes or variables are in Swedish but it should not interfere with understanding the code I think.</p>
<p>Blackjack.java</p>
<pre><code>import java.util.Scanner;
class Card {
private final Face face;
private final Suit suit;
public Card(Face face, Suit suit) {
this.face = face;
this.suit = suit;
}
public Face getFace() {
return face;
}
public Suit getSuit() {
return suit;
}
@Override
public String toString() {
return face + " of " + suit;
}
}
enum Face {
Ace(11), Deuce(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(10), Queen(10), King(10);
private final int value;
private Face(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
enum Suit {
hearts, spades, diamonds, clubs;
}
public class BlackJack {
public static void main(String[] args) {
int wins = 0;
int losses = 0;
Scanner scanner = new Scanner(System.in);
String input;
//Clear Terminal from file paths
System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");
//Start loop
do {
//Clear Terminal from last game
System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");
//Create players, shuffle deck and turn gameOver off
Player player = new Player("You");
Player dealer = new Player("Dealer");
Deck deck = new Deck();
deck.shuffle();
boolean gameOver = false;
//Get cards for player
player.addCard(deck.draw());
player.addCard(deck.draw());
System.out.print(player.getHandAsString(false));
System.out.println("Total: " + player.getHandSum());
System.out.println("");System.out.println("");
//Get cards for dealer
dealer.addCard(deck.draw());
dealer.addCard(deck.draw());
//Player turn
do {
if (player.getHandSum() == 21) {
System.out.println("Super lucky Blackjack! You win.");
wins = wins + 1;
gameOver = true;
break;
}
if (player.getHandSum() > 21) {
System.out.println("Super unlucky! You lost.");
losses = losses + 1;
gameOver = true;
break;
}
System.out.println("");System.out.println("");
System.out.println("Draw or stay?");
do {
input = scanner.nextLine();
} while (!input.equalsIgnoreCase("Draw") && !input.equalsIgnoreCase("Stay"));
//Draw
if (input.equalsIgnoreCase("Draw")) {
player.addCard(deck.draw());
System.out.println("");
System.out.print(player.getHandAsString(false));
System.out.println("Total: " + player.getHandSum());
System.out.println("");System.out.println("");
if (player.getHandSum() == 21) {
System.out.println("Blackjack! You win.");
wins = wins + 1;
gameOver = true;
}
if (player.getHandSum() > 21) {
System.out.println("You busted with " + player.getHandSum() + " in your hand. Dealer wins!");
losses = losses + 1;
gameOver = true;
}
}
//Stay
if (input.equalsIgnoreCase("stay")) {
System.out.println("You have chosen to stay. Your hand: " + player.getHandSum());
}
} while (input.equalsIgnoreCase("Draw") && !gameOver);
//Dealer turn
if (!gameOver) {
System.out.println("");System.out.println("");System.out.println("");System.out.println("");System.out.println("");
System.out.println("________________________________________________________________________");
System.out.println("Dealers turn");
System.out.println("________________________________________________________________________");
System.out.println("");
System.out.print(dealer.getHandAsString(false));
System.out.println(dealer.getHandSum());
System.out.println("");System.out.println("");
if (dealer.getHandSum() == 21) {
System.out.println("Blackjack! Dealer won.");
losses = losses + 1;
gameOver = true;
}
}
while (!gameOver) {
if (dealer.getHandSum() <= 17) {
//Draw card
dealer.addCard(deck.draw());
System.out.println(dealer.getVem() + " drew another card");
System.out.println("");
System.out.print(dealer.getHandAsString(false));
System.out.println(dealer.getHandSum());
System.out.println("");System.out.println("");
if (dealer.getHandSum() == 17) {
if (player.getHandSum() == 17) {
System.out.println("Dealer won.");
losses = losses + 1;
gameOver = true;
}
}
if (dealer.getHandSum() == 18) {
if (player.getHandSum() == 18) {
System.out.println("Dealer won.");
losses = losses + 1;
gameOver = true;
}
}
if (dealer.getHandSum() == 19) {
if (player.getHandSum() == 19) {
System.out.println("Dealer won.");
losses = losses + 1;
gameOver = true;
}
}
if (dealer.getHandSum() == 20) {
if (player.getHandSum() == 20) {
System.out.println("It's a draw!");
gameOver = true;
}
}
if (dealer.getHandSum() == 21) {
System.out.println("Blackjack! Dealer won.");
losses = losses + 1;
gameOver = true;
}
if (dealer.getHandSum() > 21) {
System.out.println("Dealer busted with " + dealer.getHandSum() + " in their hand. You win!");
wins = wins + 1;
gameOver = true;
}
} else {
//Stay
System.out.println("Dealer chose to stay!");
System.out.println("");
int totalDealerSum = dealer.getHandSum();
int totalPlayerSum = player.getHandSum();
if (totalDealerSum > totalPlayerSum) {
System.out.println("Both players decided to stay. The Dealer won with a total of " + totalDealerSum + " in their hand.");
losses = losses + 1;
} else {
System.out.println("Both players decided to stay. You win with a total of " + totalPlayerSum + " in your hand.");
wins = wins + 1;
}
gameOver = true;
}
}
//New game? And Score
System.out.println("");System.out.println("");System.out.println("");
if(wins==1 && losses==0){
System.out.println("You have won " + wins + " time and lost " + losses + " times.");
}
if(wins==0 && losses==1){
System.out.println("You have won " + wins + " times and lost " + losses + " time.");
}
if(wins>1 && losses>1){
System.out.println("You have won " + wins + " times and lost " + losses + " times.");
}
if(wins==0 && losses>1){
System.out.println("You have won " + wins + " times and lost " + losses + " times.");
}
if(wins>1 && losses==0){
System.out.println("You have won " + wins + " times and lost " + losses + " times.");
}
if(wins>1 && losses==1){
System.out.println("You have won " + wins + " times and lost " + losses + " time.");
}
if(wins==1 && losses==1){
System.out.println("You have won " + wins + " time and lost " + losses + " time.");
}
if(wins==1 && losses>1){
System.out.println("You have won " + wins + " time and lost " + losses + " times.");
}
System.out.println("");
System.out.println("Play again?");
do {
input = scanner.nextLine();
} while (!input.equalsIgnoreCase("Yes") && !input.equalsIgnoreCase("No"));
} while (input.equalsIgnoreCase("Yes"));
scanner.close();
}
}
</code></pre>
<p>Deck.java</p>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
public class Deck {
private final ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
// populate deck with cards
for (Suit suit : Suit.values()) {
for (Face face : Face.values()) {
cards.add(new Card(face, suit));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public Card draw() {
return cards.remove(0);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cards.size(); i++) {
sb.append(i + 1);
sb.append('/');
sb.append(cards.size());
sb.append(' ');
sb.append(cards.get(i));
sb.append('\n');
}
return sb.toString();
}
}
</code></pre>
<p>Player.java</p>
<pre><code>import java.util.ArrayList;
//Player class
public class Player {
private final String vem;
private final ArrayList<Card> hand;
public Player(String vem) {
this.vem = vem;
this.hand = new ArrayList<Card>();
}
public String getVem() {
return vem;
}
public void addCard(Card card) {
hand.add(card);
}
public int getHandSum() {
int handSum = 0;
for (Card card : hand) {
handSum += card.getFace().getValue();
}
return handSum;
}
public String getHandAsString(boolean b) {
StringBuilder sb = new StringBuilder();
sb.append(vem); //'s'\
sb.append('\n');
for (int i = 0; i < hand.size(); i++) {
if (i == 0 && b) {
sb.append('\n');
} else {
sb.append(hand.get(i));
sb.append('\n');
}
}
return sb.toString();
}
}
</code></pre>
<p>Thank you for any help, tips or feedback!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:43:54.057",
"Id": "503013",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please (re)visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) to find *why* at least one used wants to change the title of this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T22:06:46.863",
"Id": "503017",
"Score": "0",
"body": "The Main function in your Blackjack class has a lot going on. You should think about how you can break down what's going on the the loops into smaller functions. You could also add some additional objects to help with that, for example one to manage and store the Win & Loss counts could help keep that part organised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T03:45:53.033",
"Id": "503039",
"Score": "0",
"body": "It's necessary to say that enum items should be in upper snake case. Example: `Ace` should be `ACE` or `hearts` should be `HEARTS`, the reason why is because the items inside an enumeration are constants. Btw nice project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T21:53:00.403",
"Id": "503099",
"Score": "0",
"body": "Once you have an answer please don't edit the question. Please see [What should I do after after someone answers?](https://codereview.stackexchange.com/help/someone-answers). With 4 up votes on this question there isn't really a good reason to delete it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T21:57:45.393",
"Id": "503100",
"Score": "0",
"body": "In the future if you want to delete your question, you should look to the `Delete` Link to the right of the `Edit` link."
}
] |
[
{
"body": "<p>Nice project, find below my suggestions.</p>\n<h2>Clearing the terminal</h2>\n<p>There are more than 20 <code>System.out.println(" ")</code> in one line and then again a few lines below. Create a method to clear the terminal and shorten the code with a for-loop. There are also <a href=\"https://stackoverflow.com/questions/2979383/java-clear-the-console\">other ways</a> to clear the terminal.</p>\n<h2>Duplicated code</h2>\n<ul>\n<li>Requesting the input from the user is duplicated more than once. You can create a method for that which accepts a custom question.</li>\n<li>Boolean operators: there are many if conditions that test only with <code>==</code>. Make use of <code>&&</code> and <code>||</code> in combination with <code><=</code> and <code>>=</code> to reduce duplicated code.</li>\n</ul>\n<h2>Formatting with correct plurals</h2>\n<p>This part:</p>\n<pre><code>if(wins==1 && losses==0){\n System.out.println("You have won " + wins + " time and lost " + losses + " times.");\n}\nif(wins==0 && losses==1){\n System.out.println("You have won " + wins + " times and lost " + losses + " time.");\n}\n\nif(wins>1 && losses>1){\n System.out.println("You have won " + wins + " times and lost " + losses + " times.");\n}\nif(wins==0 && losses>1){\n System.out.println("You have won " + wins + " times and lost " + losses + " times.");\n}\nif(wins>1 && losses==0){\n System.out.println("You have won " + wins + " times and lost " + losses + " times.");\n}\n\nif(wins>1 && losses==1){\n System.out.println("You have won " + wins + " times and lost " + losses + " time.");\n}\nif(wins==1 && losses==1){\n System.out.println("You have won " + wins + " time and lost " + losses + " time.");\n}\nif(wins==1 && losses>1){\n System.out.println("You have won " + wins + " time and lost " + losses + " times.");\n}\n</code></pre>\n<p>Can be shortened to:</p>\n<pre><code>String pluralWins = wins == 1 ? "" : "s";\nString pluralLosses = losses == 1 ? "" : "s";\nSystem.out.printf("You have won %d time%s and lost %d time%s.%n", wins, pluralWins, losses, pluralLosses);\n</code></pre>\n<h2>Design</h2>\n<p>The main method seems to have a lot of responsibility. It includes:</p>\n<ol>\n<li>Requesting the input from the user</li>\n<li>Playing the game</li>\n<li>Updating the score</li>\n<li>Printing the output to the console</li>\n</ol>\n<p>This makes <code>BlackJack</code> hard to:</p>\n<ul>\n<li>Test: there is no easy way to unit test the game, only manually.</li>\n<li>Extend: for example, adding a player.</li>\n<li>Reuse: it's not easy to reuse <code>BlackJack</code> in another application where for example the user interacts via the network.</li>\n</ul>\n<p>To improve it, part of step 2 can be moved into the BlackJack class. Ideally, there shouldn't be user interaction in the <code>BlackJack</code> class, only in the main. This is an idea:</p>\n<pre><code>main method\n initialize score\n while user wants to play\n create a new BlackJack object\n while !blackJack.isGameOver()\n play game\n update score\n</code></pre>\n<p>A BlackJack object represents one game, and its methods allow one to start and play the game.</p>\n<p>In this way, the methods of BlackJack can be unit tested, and the class can be reused and extended more easily.</p>\n<h2>Naming</h2>\n<p>A more common name for <code>face</code> (in the class <code>Card</code>) is <code>rank</code>. The name <code>face</code> can be confused with face-up/down.</p>\n<h2>Performance</h2>\n<p>The method <code>Player#getHandSum</code> is called often and every time it calculates the sum iterating on all the cards. Consider to cache the sum and update it only when <code>Player#addCard</code> is called.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T06:56:12.600",
"Id": "255037",
"ParentId": "255021",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "255037",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T19:21:17.127",
"Id": "255021",
"Score": "7",
"Tags": [
"java",
"beginner",
"object-oriented",
"playing-cards"
],
"Title": "Blackjack game in Java"
}
|
255021
|
<p>I Have the below code that gets urls of PDF files, send them to a convert function and returns them as images, is there a way to make this code more readable?</p>
<p>Is there a way to avoid functions chaining?</p>
<pre><code>import PDFtoImages from '../PDFtoImages'
export async function convertPDF(file, category) {
const images= await PDFtoImages(file.data)
return {
category: category ? [category] : [],
images
}
}
export function fetchBlob(url, opts = {}) {
return fetch(url, opts).then(res => {
if (!res.ok) return Promise.reject(new Error(res.statusText))
return res.blob()
})
}
export async function fetchFilesAsImages(filesUrls) {
const pdfAsImages= []
await Promise.all(
filesUrls.map(async file=> {
pdfAsImages.push(
await convertPDF(
{data: await fetchBlob(file.url)},
file.category
)
)
})
)
return pdfAsImages
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T22:03:06.460",
"Id": "503016",
"Score": "1",
"body": "I [changed the title](https://codereview.stackexchange.com/posts/255024/revisions#rev-arrow-9d653aa9-079f-4790-945a-e05c584c4b5b) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate. I also moved the text from the title into the body as a question- does that look okay?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T00:17:45.687",
"Id": "503023",
"Score": "1",
"body": "Does the code in the code block reflect the actual indentation, or did you just indent the outer most statements (e.g. `import...`, `export....`, `}` so they would be pre-formatted? For more information about code blocks see [the editing help page](https://codereview.stackexchange.com/editing-help#code)"
}
] |
[
{
"body": "<p>The main issue I see with this code is in the <code>fetchFilesAsImages()</code> function. You're needlessly building a results array to return at the end of the call <code>fetchFilesAsImages()</code>. Why not just take advantage of the fact that <code>Promise.all()</code> will already return a list of what each promise resolved to. So, you could instead write <code>fetchFilesAsImages()</code> as follows:</p>\n<pre><code>export async function fetchFilesAsImages(filesUrls) {\n return await Promise.all(\n filesUrls.map(async ({ url, category }) => {\n const data = await fetchBlob(url);\n return await convertPDF({ data }, category);\n })\n );\n}\n</code></pre>\n<p>One other thing I would suggest is to just use async/await syntax everywhere. Your <code>fetchBlob()</code> could look a little cleaner with it:</p>\n<pre><code>export async function fetchBlob(url, opts = {}) {\n const res = await fetch(url, opts);\n if (!res.ok) throw new Error(res.statusText);\n return res.blob();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T03:37:08.490",
"Id": "255404",
"ParentId": "255024",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T20:43:31.527",
"Id": "255024",
"Score": "1",
"Tags": [
"javascript",
"async-await",
"promise",
"ecmascript-8"
],
"Title": "Get images for PDFs from URLs"
}
|
255024
|
<p>Code gets timed out and needs to be simplified.</p>
<p>To ensure that n = sum of squares
, To determine if n^2 = sum of squares
, I need to input 4 integers : 5881, 2048, 2670, 3482</p>
<pre><code>#To define the sum of squares
def sumSquare(n) :
i = 1
while i * i <= n :
j = 1
while(j * j <= n) :
if (i * i + j * j == n) :
return True
j = j + 1
i = i + 1
return False
#To define that the square of n is equals to the square of i added to the square of j
def Squared(n):
i = 1
while i * i <= n * n:
j = 1
while (j * j <= n * n):
if(i * i + j * j == n * n):
return True
j = j + 1
i = i + 1
return False
T = int(input())
while T>0:
T-=1
n = int(input())
if ((sumSquare(n)) and (Squared(n))):
print ("Yes")
else:
print("No")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T23:40:50.497",
"Id": "503106",
"Score": "0",
"body": "\\$n^2 = n^2 + 0^2\\$ is always a sum of two squares..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:52:20.320",
"Id": "503159",
"Score": "0",
"body": "You may also improve the performance by using formula from this post: https://math.stackexchange.com/a/1461742"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:19:23.243",
"Id": "503199",
"Score": "0",
"body": "Welcome to Code Review! Does your code work for smaller numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:47:28.700",
"Id": "503202",
"Score": "0",
"body": "it works faster for small numbers as the initial i is 1. then it keeps adding 1 until all conditions are met"
}
] |
[
{
"body": "<p>You can speed it up by saving the squares in a set. If you wrote a function to do this, you can give it a mutable default argument for it to save all the squares instead of having to calculate them repeatedly.</p>\n<pre class=\"lang-py prettyprint-override\"><code># dict used because there’s no insertion ordered set\ndef sum_squares(n, saved_squares=dict()):\n # check for sum while saving squares for future calls\n check_end = n\n if int(n**(1/2)) > len(saved_squares):\n check_end = (len(saved_squares) + 1)**2\n found_while_saving = False\n for num_to_save in range(len(saved_squares) + 1, int(n**(1/2) + 1)):\n square = num_to_save**2\n saved_squares[square] = None\n if n - square in saved_squares:\n found_while_saving = True\n if found_while_saving == True:\n return True\n # check for sum in set of already calculated squares\n for square in saved_squares:\n if n - square in saved_squares:\n return True\n # insertion order needed so early return won’t happen\n if square >= check_end:\n return False\n</code></pre>\n<p>With the numbers 5881, 2048, 2670, and 3482, it will only have to calculate any squares for the first call with the number 5881. On the other three calls it can skip to checking the set of all the already calculated squares. But no matter what order of numbers it’s called with, it will only have to calculate the square of any number once.</p>\n<p>This is how I tested it on repl.it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>nums_to_check = (2048, 2670, 3482, 5881)\nfor n in nums_to_check:\n print(sum_squares(n) and sum_squares(n**2))\n</code></pre>\n<p>It completed in under a second, so hopefully it’s fast enough for the site you’re using.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T03:12:00.693",
"Id": "503036",
"Score": "2",
"body": "Fine; but also mutable default arguments are considered risky and some linters will point that out to you. The problem is that if the default object actually _is_ mutated, that will surprise callers e.g. from other modules that expect a certain default (in this case an empty dictionary). The workaround is to accept either `None` or a sentinel object, and if that's seen, make the dict."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T11:28:25.820",
"Id": "503053",
"Score": "2",
"body": "Details about [`Multable default arguments`](https://stackoverflow.com/q/1132941/12416453) @Reinderien mentioned. For reference to future readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:02:09.863",
"Id": "503112",
"Score": "0",
"body": "Thanks. I think it should be alright to dismiss any warning about it for this since it’s only being used as a way to store values for future calls. I’ve read that’s one of the things it’s intended for. But maybe that’s not true, so correct me if I’m wrong about that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T22:18:32.130",
"Id": "255029",
"ParentId": "255026",
"Score": "2"
}
},
{
"body": "<p><strong>Style</strong></p>\n<p>Various tiny improvement can be made to make your code more aesthetically pleasing without changing the actual behavior:</p>\n<ul>\n<li><p>removing trailing whitespace</p>\n</li>\n<li><p>removing useless parenthesis</p>\n</li>\n<li><p>removing whitespace before colon</p>\n</li>\n<li><p>improving the function names for something which brings more meaning</p>\n</li>\n<li><p>defining docstrings for your methods</p>\n</li>\n</ul>\n<p>I would highly recommend having a look the the Style Guide for Python code called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> .</p>\n<p>At this stage, I have:</p>\n<pre><code>def is_sum_of_two_squares(n):\n """Check whether n can be written as i*i + j*j."""\n i = 1\n while i * i <= n:\n j = 1\n while j * j <= n:\n if i * i + j * j == n:\n return True\n j = j + 1\n i = i + 1\n return False\n\ndef n_squared_is_sum_of_two_squares(n):\n """Check whether n*n can be written as i*i + j*j."""\n i = 1\n while i * i <= n * n:\n j = 1\n while j * j <= n * n:\n if i * i + j * j == n * n:\n return True\n j = j + 1\n i = i + 1\n return False\n\nfor n in [5881, 2048, 2670, 3482]:\n print(n, is_sum_of_two_squares(n), n_squared_is_sum_of_two_squares(n))\n</code></pre>\n<p><strong>Deleting code</strong></p>\n<p>One can see that <code>n_squared_is_sum_of_two_squares</code> could be written by reusing <code>is_sum_of_two_squares</code>:</p>\n<pre><code>def n_squared_is_sum_of_two_squares(n):\n """Check whether n*n can be written as i*i + j*j."""\n return is_sum_of_two_squares(n*n)\n</code></pre>\n<p>(Maybe we could get rid of the function altogether)</p>\n<p>Now, we have a clearer view on the code to be optimised.</p>\n<p><strong>Optimisations</strong></p>\n<p>Knowing that we are looking for <code>i</code> such that <code>i * i < n</code> is a good idea. Unfortunately, we do it in a slow way as compute additions and multiplications at each step.</p>\n<p>We could compute the square root once and be done:</p>\n<pre><code>import math\n\ndef is_sum_of_two_squares(n):\n """Check whether n can be written as i*i + j*j."""\n s = int(math.sqrt(n))\n for i in range(1, 1 + s):\n j = 1\n while j * j <= n:\n if i * i + j * j == n:\n return True\n j = j + 1\n return False\n</code></pre>\n<p>Another observation is that once you are testing for a given value of <code>i</code>, there is not much option for the possible values of <code>j</code>. There is only one possible value:</p>\n<pre><code>def is_sum_of_two_squares(n):\n """Check whether n can be written as i*i + j*j."""\n s = int(math.sqrt(n))\n for i in range(1, 1 + s):\n j2 = n - i * i\n j = int(math.sqrt(j2))\n if j * j == j2 and j > 0:\n return True\n return False\n</code></pre>\n<p>Which brings a huge optimisation.</p>\n<p>A final optimisation can be to reduce once more the search space for <code>i</code>. A common technique can be to assume that we are looking for <code>(i, j)</code> such that <code>i²+j²=n</code> and <code>i <= j</code>. This works because the problem is symmetrical and any solution (i, j) leads to a solution (j, i).</p>\n<p>Then, we can stop at <span class=\"math-container\">\\$\\sqrt{\\frac{n}{2}}\\$</span> instead of <span class=\"math-container\">\\$\\sqrt{n}\\$</span>.</p>\n<pre><code>def is_sum_of_two_squares(n):\n """Check whether n can be written as i*i + j*j."""\n # Assume 1 <= i <= j\n # Then n = i*i + j*j >= 2*i*i\n # So i <= sqrt(n/2)\n s = int(math.sqrt(n/2))\n for i in range(1, 1 + s):\n j2 = n - i * i\n j = int(math.sqrt(j2))\n if j * j == j2 and j > 0:\n return True\n return False\n</code></pre>\n<p>Based on comments from AJNeufeld, one can actually go further with this idea, iterating over the "j-range" which is actually smaller:</p>\n<pre><code>def is_sum_of_two_squares2(n):\n """Check whether n can be written as i*i + j*j."""\n # Assume 1 <= i <= j\n # Then n = i*i + j*j becomes\n # n <= 2*j*j which implies j >= sqrt(n/2)\n # And n >= 1*1 + j*j which implies j <= sqrt(n-1)\n for j in range(int(math.sqrt(n/2)), 1 + int(math.sqrt(n-1))):\n i2 = n - j * j\n i = int(math.sqrt(i2))\n if i * i == i2 and i > 0:\n return True\n return False\n</code></pre>\n<p>Also, yet another brilliant idea from AJNeufeld is to use <a href=\"https://docs.python.org/3/library/math.html\" rel=\"nofollow noreferrer\"><code>math.isqrt</code></a>:</p>\n<pre><code>def is_sum_of_two_squares(n):\n """Check whether n can be written as i*i + j*j."""\n # Assume 1 <= i <= j\n # Then n = i*i + j*j becomes\n # n <= 2*j*j which implies j >= sqrt(n/2)\n # And n >= 1*1 + j*j which implies j <= sqrt(n-1)\n for j in range(math.isqrt(n//2), 1 + math.isqrt(n-1)):\n i2 = n - j * j\n i = math.isqrt(i2)\n if i * i == i2 and i > 0:\n return True\n return False\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T15:16:17.080",
"Id": "503068",
"Score": "0",
"body": "`s = math.isqrt(n / 2)` and `j = math.isqrt(j2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T16:00:30.587",
"Id": "503072",
"Score": "1",
"body": "You're going from the wrong end. `for i in range(1, 1+s):` means trying \\$\\sqrt{n/2}\\$ cases, with `j` barely changing between each case. If you varied `j` from \\$\\sqrt{n/2}\\$ to \\$\\sqrt{n}\\$, you'll only need to try \\$\\sqrt{n} - \\sqrt{n/2}\\$ cases, with the computed values of `i` varying significantly at each step. As an example, checking \\$5881^2\\$ requires up to `4158` iterations when looping over `i`, but only `1722` when looping over `j`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T19:31:15.550",
"Id": "503089",
"Score": "0",
"body": "@AJNeufeld Great idea, I'll give it a try when I have a bit of time!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T11:28:14.487",
"Id": "255048",
"ParentId": "255026",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255048",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:15:48.087",
"Id": "255026",
"Score": "2",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Determine whether a number and its square are both the sum of two squares"
}
|
255026
|
<p>I'm currently going through The Odin Project, in an attempt to learn some Javascript. I'm a junior in a CS program, and I realize that I am not very good at programming, but I want to change that.</p>
<p>I made a very simple rock-paper-scissors implementation with JS and HTML. I plan on adding CSS later and making it not look horribly ugly, but for the time being I am only concerned with the Javascript.</p>
<p>There are a few things that I am not happy with in my code, that I couldn't really figure out how to improve. One of them being the win checking; I essentially used 9 if statements for all the possible outcomes, and its very inelegant. Another thing I am not a fan of is my usage of global variables for the round results. I have been told often to avoid using global vartiables when possible. Another thing is the implementation of the eventlisteners. I wanted to just directly use the <code>playRound()</code> function on click, but I couldn't figure out how to pass in the <code>computerPlayer()</code> result as a parameter.</p>
<p>Here is the HTML:</p>
<pre><code><body>
<h1>Rock Paper Scissors</h1>
<div id="button-container">
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
</div>
<div id="results">
<p id="player-score">Your score is: 0</p>
<p id="computer-score">The computer score is: 0</p>
<p id="result-tie">Tie rounds: 0</p>
</div>
<script src="script.js"></script>
</body>
</code></pre>
<p>And here is the Javascript:</p>
<pre><code>// Accessing the buttons and text labels
const rockButton = document.getElementById("rock");
const paperButton = document.querySelector("#paper");
const scissorsButton = document.querySelector("#scissors");
const playerScore = document.getElementById("player-score");
const computerScore = document.getElementById("computer-score");
const tieText = document.getElementById("result-tie");
// Global variables to keep track of round results that I am not a fan of
let computerWinAmount = 0;
let playerWinAmount = 0;
let tieAmount = 0;
//Event listeners to monitor button press and assign
//corresponding choice
rockButton.addEventListener("click", function(){
let playerSelection = "rock";
let computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
});
paperButton.addEventListener("click", function() {
let playerSelection = "paper";
let computerSelection = computerPlay();
playRound(playerSelection, computerSelection);
});
scissorsButton.addEventListener("click", function() {
let playerSelection = "scissors";
let computerSelection = computerPlay();
playRound(playerSelection, computerSelection);
});
// Function that pseudo-randomly generates a computer selection
function computerPlay() {
// Uses Math.random() to generate a number between 0-2
let choice = Math.floor(Math.random() * 3);
// Reassigns string value depending on which number
switch(choice) {
case 0:
choice = "rock";
break;
case 1:
choice = "paper";
break;
case 2:
choice = "scissors";
break;
}
return choice;
}
// Group of functions to change text labels after rounds
function playerWin() {
++playerWinAmount;
playerScore.innerHTML = "Your score is: " + playerWinAmount;
}
function computerWin() {
++computerWinAmount;
computerScore.innerHTML = "The computer score is: " + computerWinAmount;
}
function tieWin() {
++tieAmount;
tieText.innerHTML = "Tie rounds: " + tieAmount;
}
// Function that checks winning very inelegantly
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" &&
computerSelection == "rock") {
tieWin();
} else if (playerSelection == "rock" &&
computerSelection == "scissors") {
playerWin();
} else if (playerSelection == "rock" &&
computerSelection == "paper") {
computerWin();
}
if (playerSelection == "paper" &&
computerSelection == "rock") {
playerWin();
} else if (playerSelection == "paper" &&
computerSelection == "paper") {
tieWin();
} else if (playerSelection == "paper" &&
computerSelection == "scissors") {
computerWin();
}
if(playerSelection == "scissors" &&
computerSelection == "rock") {
computerWin();
} else if (playerSelection == "scissors" &&
computerSelection == "paper") {
playerWin();
} else if (playerSelection == "scissors" &&
computerSelection == "scissors") {
tieWin();
}
if(computerWinAmount == 5) {
alert("You lost! Better luck next time :(");
reset();
} else if (playerWinAmount == 5) {
alert("You won! Congratulations! :)")
reset();
}
}
// Helper function to reset after game end
function reset() {
playerScore.innerHTML = "Your score is: 0";
computerScore.innerHTML = "The computer score is: 0";
tieText.innerHTML = "Tie rounds: 0";
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:20:41.907",
"Id": "503029",
"Score": "0",
"body": "The functions `playRound`, etc. are also in global scope. Wrap the entire JS program inside a function, say `RockAroundTheClock`. This function must be executed to instantiate all the variables, functions, etc. A technique for doing this is called IIFE - Immediately Invoked Function Expression. GoogleIt. This is rare in code examples one comes across. This is because we get lucky and don't have some other code stomping on our variable names at run time. I've had that happen. It's not fun."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:38:00.470",
"Id": "503033",
"Score": "0",
"body": "addEventListener(\"click\", function( [arguments is your friend](https://www.w3schools.com/js/js_function_parameters.asp) ) - pass 'playerSelection' and 'computerSelection' as parameters. Now only one `eventHandler` function is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:42:14.257",
"Id": "503034",
"Score": "0",
"body": "\"pass in the computerPlayer() result as a parameter.\" --- `aFunction( computerPlayer() )` passes its return value; `aFunction( computerPlayer )` passes the function itself."
}
] |
[
{
"body": "<h1></h1>\n<h1>Constants</h1>\n<p>The first thing to look at is the use of strings to represent the signs. The problem is, that if you mistype a string somewhere (for example, <code>"rook"</code> instead <code>"rock"</code>) you'll have a bug, that you'll may be difficult to find.</p>\n<p>Instead define constants, that you use in place of the string literals:</p>\n<pre><code>const ROCK = "rock";\nconst PAPER = "paper";\nconst SCISSORS = "scissors";\n</code></pre>\n<p>and that way, if you mistype the name of a constant, you'll get a runtime error with a line number so you'll know exactly where the mistake is.</p>\n<h1>Repeated code</h1>\n<p>The event listeners you are using are are fine the way they are. The problem is however you have three virtually identical listeners. Instead of hard coding the name of each sign into three copies, you can read the sign from the id of the clicked button:</p>\n<pre><code>function clickListener(event) {\n // Use `const` instead of `let` when the value of the variable doesn't change.\n const playerSelection = event.target.id;\n const computerSelection = computerPlay();\n playRound(playerSelection,computerSelection);\n }\n\nrockButton.addEventListener("click", clickListener);\npaperButton.addEventListener("click", clickListener);\nscissorsButton.addEventListener("click", clickListener);\n</code></pre>\n<p>Further more you could instead assign a single event handler to the surrounding element (<code>#button-container</code>) and check in the listener, if a button has been clicked:</p>\n<pre><code>function clickListener(event) {\n // Exit, if not a button was clicked\n if (event.target.tagName !== "BUTTON") {\n return;\n }\n const playerSelection = event.target.id;\n const computerSelection = computerPlay();\n playRound(playerSelection,computerSelection);\n }\n\ndocument.getElementbyId("#button-container").addEventListener("click", clickListener);\n</code></pre>\n<h1>Simplify <code>computerPlay()</code></h1>\n<p><code>computerPlay()</code> can be simplified by using a array instead of the switch:</p>\n<pre><code>const signs = [ROCK, PAPER, SCISSORS];\n\nfunction computerPlay() {\n // Uses Math.random() to generate a number between 0-2\n let choice = Math.floor(Math.random() * 3);\n return signs[choice];\n}\n</code></pre>\n<h1>Optimizing <code>playRound()</code></h1>\n<p>The function <code>playRound()</code> as it is, is not bad.</p>\n<p>The first three if/if-else/else blocks should be joined to one big if/if-else/else because as it's now, the conditions of the following blocks are unnecessarily checked, even if a previous block already determined a winner.</p>\n<p>Always use strict comparison (<code>===</code> instead of <code>==</code>) when comparing values in JavaScript.</p>\n<p>A bit of repetition can be avoided by first checking for a tie:</p>\n<pre><code>if (playerSelection === computerSelection) {\n tieWin();\n} else if (...) {\n</code></pre>\n<p>Also you can combine the win/lose comparisons into one if to avoid repeating the check on <code>playerSelection</code>. (Continuing from above):</p>\n<pre><code>...\n} else if (playerSelection === ROCK) {\n if (computerSelection === SCISSIORS) {\n playerWin();\n } else { // No need to check. If should be PAPER.\n computerWin();\n }\n} else if (playerSelection === PAPER) {\n if (computerSelection === ROCK) {\n playerWin();\n } else { // No need to check. If should be PAPER.\n computerWin();\n }\n} else if (...) {\n // etc.\n</code></pre>\n<h1>More repetition</h1>\n<p>You have some more minor repetition with the string <code>"Your score is:"</code>, etc. repeated three times. Instead of replacing the whole line, just change the values. Also use <code>textContent</code> instead of <code>innerHtml</code> unless you actually are writing HTML.</p>\n<pre><code><div id="results">\n <p>Your score is: <span id="player-score">0</span></p>\n <!-- ... -->\n</div>\n\nplayerScore.textContent = playerWinAmount;\n</code></pre>\n<h1>Alternative implementation</h1>\n<p>A way to simplify <code>playRound()</code> would be to use numbers instead of string to identify the signs and use some mathematics to determine the winner. (Partial) Example:</p>\n<pre><code><body>\n <h1>Rock Paper Scissors</h1>\n <div id="button-container">\n <button data-sign="0">Rock</button>\n <button data-sign="1">Paper</button>\n <button data-sign="2">Scissors</button>\n </div>\n <!-- ... -->\n <script src="script.js"></script>\n</body>\n</code></pre>\n<pre><code>function clickListener(event) {\n // Exit, if not a button was clicked\n if (event.target.tagName !== "BUTTON") {\n return;\n }\n const playerSelection = event.target.dataset.sign;\n const computerSelection = computerPlay();\n playRound(playerSelection,computerSelection);\n }\n\ndocument.getElementbyId("#button-container").addEventListener("click", clickListener);\n\nfunction computerPlay() {\n return Math.floor(Math.random() * 3);\n}\n\nfunction playRound(playerSelection, computerSelection) {\n const result = determineWinner(playerSelection, computerSelection);\n switch (result) {\n case 0: \n playerWin();\n break;\n case 1:\n computerWin();\n break;\n case 2:\n tieWin();\n break;\n }\n\n // ...\n}\n\n// Returns: \n// 0 if the first player ("a") wins\n// 1 if the second player ("b") wins\n// 2 in case of a tie\nfunction determineWinner(a, b) {\n return (a - b + 2) % 3;\n}\n</code></pre>\n<p>Explanation:</p>\n<p>The three signs are encoded (as seen in the HTML) as 0, 1 and 2. The difference (a - b) thus results in a value from 2 to -2, or (after adding 2) 4 to 0. (2 is added mostly in order to simplify the modulo operation (<code>%</code>) because modulo can be defined differently for negative numbers).</p>\n<p>In case of a tie "a" and "b" are equal, so that results in a - b = 0 and 0 + 2 = 2.</p>\n<p>In case of "a" winning, it results in 0 or 3 and both 0 % 3 and 0 % 3 result in 0.</p>\n<p>In case of "b" winning, it results in 1 or 4 and both 1 % 3 and 4 % 3 result in 1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T23:38:27.587",
"Id": "503105",
"Score": "0",
"body": "Great, thank you for this! Very thorough, and I am glad to hear that what I had was not BAD per se, just needed some improvements. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T06:26:48.587",
"Id": "506643",
"Score": "1",
"body": "`<span id=\"player-score\">0</span>` may be `<output id=\"player-score\">0</output>`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:57:39.767",
"Id": "255053",
"ParentId": "255031",
"Score": "1"
}
},
{
"body": "<h2>Code Quality</h2>\n<ul>\n<li>As already pointed out, it's preferable to use <code>===</code> over <code>==</code>.</li>\n<li>I noticed a bug where after you win/loose the entire game, you can't keep playing. You need to reset the score, not just the UI.</li>\n<li>You should almost never use .innerHTML due to ease of misuse resulting in security holes (XSS attacks). While that's not an issue with how you're using it here, it's best to get into the habit of using other DOM-manipulation functions instead. In this case, .innerText would be the better option.</li>\n<li>You're using both getElementById and querySelector to get an element by id. Be consistant and just pick one.</li>\n</ul>\n<h2>Separate view from logic</h2>\n<p>Think of it like this: If you were to also create a command-line version of rock-paper-scissors (i.e. make a second UI for the same program), what parts of this program would be shared and what parts would be unique to the UI being used? Keep the changeable UI-dependent logic completely separated from everything else. Doing this will help improve reuse-ability, test-ability, and readability, among other things.</p>\n<p>In my example rewrite I did this by following the model-view-controller pattern, but there's other ways to achieve this behavior.</p>\n<h2>Is there a better way to check for a winner?</h2>\n<p>If you were explaining the rules of rock-paper-scissors in English, how might you do it? Probably along the lines of "Paper beats rock, scissors beats paper, and rock beats scissors". We can put these win rules into a map, then do some lookups to determine a winner. The result is a very easy to read and understand.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const whatBeatsWhat = {\n paper: 'rock',\n scissors: 'paper',\n rock: 'scissors',\n}\n\nfunction getWinnerOfRound(playerSelection, computerSelection) {\n if (whatBeatsWhat[playerSelection] === computerSelection) return 'player'\n if (whatBeatsWhat[computerSelection] === playerSelection) return 'computer'\n return 'tie'\n}\n</code></pre>\n<h2>How to avoid global variables?</h2>\n<p>Sometimes it's impracticable to completely get rid of them, but there are things you can do to mitigate the issue if you're worried about it.</p>\n<ul>\n<li>Group your global data together into an object called "state". This object represents the current state of your website. This is the only global variable that needs to be modified.</li>\n<li>Make your functions as pure as possible. Instead of updating the global state, make them take a state object, and return a new, updated state object. Of course at some point you'll need to override the old state with the new state, but that can be done at the last moment possible.</li>\n<li>Don't go overboard. This is just one way to do it, it's not "the way".</li>\n</ul>\n<p>(I'm using the word "global" here to refer to module-level modifiable variables. Usually when we talk about global variables in javascript, we're referring to variables that are on the window object, and are accessible anywhere).</p>\n<h2>How to pass parameters to event listeners?</h2>\n<p>Like this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function showAlert(message) {\n alert(message)\n}\n\nelement1.addEventListener(() => showAlert('Hey There!'))\nelement2.addEventListener(() => showAlert('Hi!'))\n</code></pre>\n<p>Or this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const showAlertFactory = message => () => {\n alert(message)\n}\n\nelement1.addEventListener(showAlertFactory('Hey There!'))\nelement2.addEventListener(showAlertFactory('Hi!'))\n</code></pre>\n<p>I usually prefer the first style as it tends to be easier to follow, but on occasion I'll use the second style (I did in the example rewrite).</p>\n<h2>Rewrite</h2>\n<p>I separated out the model, view, and controller logic into these three separate files.</p>\n<p><strong>model.js</strong></p>\n<pre><code>const WINNING_SCORE = 5\n\nexport const getInitialState = () => ({\n scores: {\n computer: 0,\n player: 0,\n tie: 0,\n },\n})\n\nconst whatBeatsWhat = {\n paper: 'rock',\n scissors: 'paper',\n rock: 'scissors',\n}\n\nexport function playRound(state, playerSelection, computerSelection) {\n const getWinnerOfRound = () => {\n if (whatBeatsWhat[playerSelection] === computerSelection) return 'player'\n if (whatBeatsWhat[computerSelection] === playerSelection) return 'computer'\n return 'tie'\n }\n const winner = getWinnerOfRound({ playerSelection, computerSelection })\n const newScores = { ...state.scores, [winner]: state.scores[winner] + 1 }\n return { ...state, scores: newScores }\n}\n\nexport function getOverallWinner(state) {\n if (state.scores.player === WINNING_SCORE) return 'player'\n if (state.scores.computer === WINNING_SCORE) return 'computer'\n return null\n}\n</code></pre>\n<p><strong>view.js</strong></p>\n<pre><code>const query = selector => document.querySelector(selector)\n\nexport function init(scores) {\n updateScores(scores)\n}\n\nexport function updateScores(scores) {\n query('#player-score').innerText = `Your score is: ${scores.player}`\n query('#computer-score').innerText = `The computer score is: ${scores.computer}`\n query('#result-tie').innerText = `Tie rounds: ${scores.tie}`\n}\n\nexport function showGameOverMessage(winner) {\n alert(winner === 'player'\n ? 'You won! Congratulations! :)'\n : 'You lost! Better luck next time :('\n )\n}\n</code></pre>\n<p><strong>controller.js</strong></p>\n<pre><code>import * as model from './model.js'\nimport * as view from './view.js'\n\nconst randomChoice = list => list[Math.floor(Math.random() * list.length)]\nconst query = selector => document.querySelector(selector)\n\nlet state = model.getInitialState()\n\nconst createSelectionListener = playerSelection => () => {\n const computerSelection = randomChoice(['rock', 'paper', 'scissors'])\n state = model.playRound(state, playerSelection, computerSelection)\n view.updateScores(state.scores)\n\n const winner = model.getOverallWinner(state)\n if (winner) {\n view.showGameOverMessage(winner)\n state = model.getInitialState()\n view.updateScores(state.scores)\n }\n}\n\nquery('#rock').addEventListener('click', createSelectionListener('rock'))\nquery('#paper').addEventListener('click', createSelectionListener('paper'))\nquery('#scissors').addEventListener('click', createSelectionListener('scissors'))\nwindow.addEventListener('DOMContentLoaded', () => {\n view.init(state.scores)\n})\n</code></pre>\n<p><strong>index.html</strong></p>\n<pre><code><html>\n <body>\n <h1>Rock Paper Scissors</h1>\n <div id="button-container">\n <button id="rock">Rock</button>\n <button id="paper">Paper</button>\n <button id="scissors">Scissors</button>\n </div>\n <div id="results">\n <p id="player-score"></p>\n <p id="computer-score"></p>\n <p id="result-tie"></p>\n </div>\n <script src="controller.js" type="module"></script>\n </body>\n</html>\n</code></pre>\n<p>(you'll notice in the index.html file I'm using <code><script ... type="module"></code> - this enabled me to use import/export syntax and also puts the scripts into strict mode. This also allows me to create module-level variables without accidentally polluting the global scope)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T03:16:40.370",
"Id": "255074",
"ParentId": "255031",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255053",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T01:09:45.377",
"Id": "255031",
"Score": "5",
"Tags": [
"javascript",
"html"
],
"Title": "Basic in-browser rock paper scissors"
}
|
255031
|
<p>I'm working on getting myself comfortable with C after only working in high level languages for the past 10 years. I've done rust as well and really like the concept of notating immutability in functions.</p>
<p>That being said I'm confused on if I should use <code>const</code> wherever the compiler lets me, or just use it where it semantically makes sense (and hope no one comes behind me and does something the caller doesn't expect).</p>
<p>Several functions I am looking at right now are:</p>
<pre><code>void kcr_scene_update(const struct KCR_Scene* scene) {
scene->internal->cubeRotation.x += 0.01f;
scene->internal->cubeRotation.y += 0.01f;
scene->internal->cubeRotation.z += 0.01f;
}
void kcr_display_begin_frame(const struct KCR_Display* display) {
for (int x = 0; x < display->windowWidth * display->windowHeight; x++) {
display->pixelBuffer[x] = 0xFF000000;
}
}
</code></pre>
<p>The compiler is allowing these, presumably because it's not changing the root pointer or direct child pointers (I guess?) but is it good practice to put const in these methods when I know there's some mutation going on?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:10:07.673",
"Id": "503026",
"Score": "0",
"body": "What compiler are you using, with what flags? I'd be surprised if `-Wall` doesn't complain about this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:11:33.213",
"Id": "503028",
"Score": "0",
"body": "Anyway, this question is somewhat too narrow, with your `kcr` methods divorced from the rest of your code. Please show more of your code, so that we can give a more general code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:27:10.220",
"Id": "503030",
"Score": "0",
"body": "@reinderien: I'm using GCC with -Wall and -Wextra, and it doesn't complain (to my surprise). I'm not totally sure what extra code would be relevant. If this isn't the right SE for this question then fine, but the question only revolved around code reviewing const in this circumstance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T03:05:05.517",
"Id": "503035",
"Score": "0",
"body": "I was able to confirm your issue locally. The crux of the problem is that `const` _does_ apply to `struct` sub-instances but does _not_ apply to `struct` sub-pointers. You should put together a minimum verifiable complete compilable example, including a simple struct definition, to illustrate this - and then just post it in StackOverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T03:21:50.803",
"Id": "503038",
"Score": "1",
"body": "Will do thanks. I kept going back and forth if this would be too subjective for Stack overflow, but will do :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:31:32.227",
"Id": "503049",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:32:58.440",
"Id": "503050",
"Score": "0",
"body": "We require that the poster know why the code is written the way it is. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:51:33.313",
"Id": "503060",
"Score": "0",
"body": "Personally I think this question would be just fine on SO, but that's just me. If you get it closed both here and on SO, then maybe ask on software.codidact.com instead. It's a site much more tolerant to program design and style questions. It also allows code review questions, so you don't need to worry about which site to pick."
}
] |
[
{
"body": "<blockquote>\n<p>Should I use const in this function argument?</p>\n</blockquote>\n<p>Yes.</p>\n<ol>\n<li><p>Better conveys to a user code's functionality. Consider the user may only see the declaration <code>void kcr_scene_update(const struct KCR_Scene* scene);</code> (in some header file) and not the definition.</p>\n</li>\n<li><p>Allows increased applicability. Function can be <em>called</em> with <code>const struct KCR_Scene* some_pointer</code>. Without a <code>const</code> in the function signature, the caller is obliged to pass a non-const pointer.</p>\n</li>\n<li><p>Optimization: Some optimization will only take place when the reference data is <code>const</code>. This issue applies especially to older compilers.</p>\n</li>\n</ol>\n<blockquote>\n<p>good practice to put const in these methods when I know there's some mutation going on?</p>\n</blockquote>\n<p>Need to see detail of <code>struct KCR_Scene</code> and <code>struct KCR_Display</code> to know what changes are really occurring in code.</p>\n<hr />\n<p>I now see OP really needs to provide more info - making answer wiki.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:32:26.130",
"Id": "255052",
"ParentId": "255033",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T01:44:31.990",
"Id": "255033",
"Score": "1",
"Tags": [
"c"
],
"Title": "Should I use const in this function argument?"
}
|
255033
|
<p>To practice my C, I've written a small function in C to display an integer as an 8-bit binary number. Please let me know how to improve this function, and other C-style coding conventions. Thanks!</p>
<pre><code>/**
* Converts an integer to binary.
*
* @param num Integer to convert.
*
* @return c-string.
**/
const char* to_binary(int num) {
static char binary[10];
binary[0] = '0';
binary[1] = 'b';
int value = 128;
int number = num;
for (int i = 2; i < 10; i++) {
if (number - value >= 0) {
binary[i] = '1';
number = number - value;
} else {
binary[i] = '0';
}
value = value / 2;
}
return binary;
}
</code></pre>
<p>And here's how you call it:</p>
<pre><code>int main() {
const char* result = to_binary(146);
printf("%s\n", result);
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>More specific types are available for an eight bit number, such as <code>uint8_t</code></li>\n<li><code>static</code> keyword is dangerous (when used as an output buffer) and results in weird behaviour if your method is called twice</li>\n<li>The arithmetic can be replaced with a more simple <code>&</code> (bitwise AND)</li>\n</ul>\n<pre><code>void to_binary(uint8_t x, char *output) {\n *output++ = '0';\n *output++ = 'b';\n for (int mask = 1<<CHAR_BIT-1; mask!=0 ; mask>>=1) {\n *output++ = x & mask ? '1':'0'; \n }\n *output = 0; // null terminate the string\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T07:59:23.920",
"Id": "503043",
"Score": "1",
"body": "Yeah, `static` makes it only allocate one time. You can see that if you add the line `to_binary(147);` in the main function and print `result` again. It will print something different because the same memory space is used every time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:07:55.313",
"Id": "503047",
"Score": "6",
"body": "`static` isn't weird and dangerous. It means the data is allocated in either .DATA or the .BBS section of the binary, instead of the stack. This means a variable is allocated once, and the value \"kept\" between calls. It has legitimate uses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:05:27.777",
"Id": "503058",
"Score": "9",
"body": "@AnnoyinC, I think Ted's point is that using `static` storage makes the *function* dangerous and weird. Users don't expect such a function to be stateful like that. BTW, C standard says nothing about \"segments\" - that's a platform-specific mechanism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:11:58.613",
"Id": "503059",
"Score": "1",
"body": "`int total_bits = sizeof(uint8_t)*8;` --> `sizeof(uint8_t)*8` is always 8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T16:31:56.327",
"Id": "503074",
"Score": "2",
"body": "`2<<i` should be `1<<i` and you need to start from the MSB, `for (int i = total_bits - 1; i >= 0 ; --i)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T17:55:41.447",
"Id": "503081",
"Score": "2",
"body": "Instead of counting with `i` and generating the mask on the fly, you can do something like `for (mask = 1 << 7; mask != 0; mask >>=1)`, this is naively more efficient, but the compiler probably does this already at O1 or so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:07:56.007",
"Id": "503115",
"Score": "2",
"body": "Your placement of spaces in the code is strange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:43:37.980",
"Id": "503158",
"Score": "1",
"body": "Minor nit: I prefer the null terminator to be an actual char: `*output = '\\0';` I know it compiles the same, but it's more correctly describes the intent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T11:25:08.160",
"Id": "503163",
"Score": "0",
"body": "The static output array is completely (except for the last byte, which is 0 due to the array being statically allocated) overridden every time the function is called, isn't it? In that case, a static variable is only dangerous in multithreaded programs. That said, static variables have fallen out of favor for exactly that reason, and your inconspicuous little routine, re-used in another environment (Ariane V...), may suddenly fail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:04:42.537",
"Id": "503184",
"Score": "0",
"body": "@Peter even in a single threaded program, you'd need to copy strings out of the way to keep them safe between calls, which causes unnecessary work and might be forgotten about by the programmer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:59:40.180",
"Id": "503189",
"Score": "0",
"body": "For the ultimate portability, 8 and 7 are \"magic numbers\". <limits.h> #defines CHAR_BIT 8 and <values.h> #defines BITSPERBYTE CHAR_BIT (in Linux Mint GCC)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T15:42:07.410",
"Id": "503191",
"Score": "1",
"body": "When you edit to fix a bug in your code, don't leave a wrong copy first. Future readers don't benefit at all from seeing the `2<<i` version, just delete it. The edit history is visible if anyone wants to look at it, leave mistakes there, not as the first part of your answer."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T07:39:07.800",
"Id": "255038",
"ParentId": "255036",
"Score": "10"
}
},
{
"body": "<p><strong>Bug</strong></p>\n<p>Code attempts to form a <em>string</em>. Yet it lacks a terminating <em>null character</em> and space for it.</p>\n<pre><code>// static char binary[10];\nstatic char binary[11];\n</code></pre>\n<p>As a <code>static</code>, it is initialized to all zeros. With increased size, an explicit setting of the null character is not needed.</p>\n<p>OP's code <em>undefined behavior</em> perhaps "works" as a zero may exist just past <code>binary[10]</code>.</p>\n<p><strong>Loop Simplification</strong></p>\n<p>Iterate right (most significant) to left (least significant).</p>\n<pre><code>for (int i = 10; --i >= 2; ) {\n binary[i] = '0' + (num & 1);\n num /= 2;\n}\n</code></pre>\n<p><strong>Unclear functionality</strong></p>\n<p>When <code>num > 255</code> code prints all <code>'1'</code>.<br />\nWhen <code>num < 0</code> code prints all <code>'0'</code>.</p>\n<p>Code should 1) not use an <code>int</code> argument or 2) state functionality when <code>num</code> is outside the [0-255] range.</p>\n<p><strong>Alternative</strong></p>\n<p>I'd avoid the use of <code>static</code> and provide a buffer to the function. <a href=\"https://stackoverflow.com/a/34641674/2410359\">Example</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:02:20.277",
"Id": "503101",
"Score": "0",
"body": "Just a thought, but it might work with 10 because there could be unused bytes after for alignment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T23:11:46.570",
"Id": "503104",
"Score": "0",
"body": "@ben Agree. See \"OP's code undefined behavior perhaps \"works\" as a zero may exist just past binary[10].\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:05:58.567",
"Id": "503113",
"Score": "0",
"body": "@Ben even if there are \"unused bytes for alignment\", there is no guarantee that these bytes are initialized to 0. Still undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T13:05:49.317",
"Id": "503176",
"Score": "0",
"body": "@RolandIllig, hence the `might`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:15:21.913",
"Id": "503186",
"Score": "0",
"body": "@L.F. Agree `static` `char` are zero-initialized. Yet the bytes near, though not part of, `binary[10]` are the issue. They are not specified to be zero nor even accessible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:39:11.443",
"Id": "503188",
"Score": "0",
"body": "@L.F. OK to delete related comments then."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T12:01:11.013",
"Id": "255050",
"ParentId": "255036",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "255038",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T06:32:53.743",
"Id": "255036",
"Score": "5",
"Tags": [
"c",
"converting",
"binary"
],
"Title": "Represent integer as binary in C"
}
|
255036
|
<p>I Have this class want to practice how to write a factory method pattern</p>
<p>and I can change the <code>logPlace</code> by set the app.config,</p>
<p>and I try to improve the performance so I use static <code>List<string></code>,I want to decrease IO loading</p>
<p>Here is my question</p>
<ol>
<li>This class can call factory method pattern or not?</li>
<li>Is my code as clear as it could be?</li>
<li>I think the <code>LogBoth</code> class can be much better, but I have no idea how to improve it.</li>
</ol>
<pre class="lang-cs prettyprint-override"><code> public enum LogLevel
{
Error, Debug, Info, Fatal
}
static class Msg
{
public static List<string> msgList = new List<string>();
}
public class LogHelper
{
public static ILog Create()
{
string logPlace = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPlace"];
switch (logPlace)
{
case "DB":
return new LogDB();
case "File":
return new LogFile();
case "Both":
return new LogBoth();
default:
return new LogFile();
}
throw new NullReferenceException();
}
}
public interface ILog
{
void WriteLog(string msg);
void ExecWrite(LogLevel logLevel);
}
public class LogDB : ILog
{
public LogDB()
{
Msg.msgList.Clear();
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
public void ExecWrite(LogLevel logLevel)
{
throw new NotImplementedException();
}
}
public class LogFile : ILog
{
private static object _lockObject = new object();
public LogFile()
{
Msg.msgList.Clear();
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
public void ExecWrite(LogLevel logLevel)
{
try
{
Policy.Handle<Exception>().Retry(1).Execute(()=>WriteToFile(logLevel));
}
catch (Exception ex)
{
LogDB logDB = new LogDB();
logDB.ExecWrite(logLevel);
}
}
private void WriteToFile(LogLevel logLevel)
{
lock (_lockObject)
{
using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string msg in Msg.msgList)
{
sw.WriteLine(string.Format("{0} [{1}] {2}", DateTime.UtcNow.AddHours(08).ToString("yyyy/MM/dd HH:mm:ss"), logLevel, msg));
}
}
}
}
}
}
public class LogBoth : ILog
{
public LogBoth()
{
Msg.msgList.Clear();
}
public void ExecWrite(LogLevel logLevel)
{
LogDB logDB = new LogDB();
LogFile logFile = new LogFile();
logDB.ExecWrite(logLevel);
logFile.ExecWrite(logLevel);
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are my observations:</p>\n<h3>LogLevel</h3>\n<ul>\n<li><code>LogLevel</code>: Usually the industry calls this <a href=\"https://en.wikipedia.org/wiki/Syslog#Severity_level\" rel=\"nofollow noreferrer\">Severity Levels</a>. I would suggest to try to follow these and do not re-invent the wheel.<br />\nIn some cases it might worth to differentiate these two concepts:\n<ul>\n<li>Log Severity: The seriousness / weight / riskiness of a given event.</li>\n<li>Log Level: Usually there is a particular order between the levels. The logger should log everything which is at a given level or above\n<ul>\n<li>For example: if you have this ordering: <code>Debug</code> > <code>Information</code> > <code>Warning</code>\nand you set the level to <code>Information</code> then <code>Debug</code> logs will be omitted\nfrom persistence.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<h3>Msg</h3>\n<ul>\n<li><code>Msg</code>: Please try to avoid using abbreviations or short-forms in case of class names.</li>\n<li><code>msgList</code>: Please try to avoid <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a>.</li>\n<li><code>Msg.msgList</code>: This seems quite clumsy and stuttering.\n<ul>\n<li>Please try to come up with better naming and encapsulation.</li>\n</ul>\n</li>\n</ul>\n<h3>LogHelper</h3>\n<ul>\n<li><code>LogHelper</code>: This is a <code>LoggerFactory</code>. If you have only just <code>static</code> members then mark your class <code>static</code> as well. By the way this is more like an abstract factory than a factory method.\n<ul>\n<li>Please read <a href=\"https://codereview.stackexchange.com/questions/250222\">this related discussion</a>.</li>\n</ul>\n</li>\n<li><code>throw new NullReferenceException</code>: It is really rare to throw <code>NullReferenceException</code> manually. And fortunately this is not needed at all. You have at least two options:</li>\n<li>single return statement:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>ILog logger;\nswitch (logPlace)\n{\n case "DB":\n logger = new LogDB();\n break;\n case "File":\n logger = new LogFile();\n break;\n case "Both":\n logger = new LogBoth();\n break;\n default:\n logger = new LogFile();\n break;\n}\n\nreturn logger;\n</code></pre>\n<p>or switch expression (in case of C# 8):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>return logPlace switch\n{\n "DB" => new LogDB(),\n "File" => new LogFile(),\n "Both" => new LogBoth(),\n _ => new LogFile(),\n};\n</code></pre>\n<h3>ILog</h3>\n<ul>\n<li><code>ILog</code>: This should be <code>ILogger</code> to be precise.</li>\n<li><code>void WriteLog(string msg)</code>: Usually here should the logger receive the log level / severity. Or it has several overloads with different severity levels, like <code>LogInformation</code>, <code>LogWarning</code>, <code>LogError</code>, etc.\n<ul>\n<li>Usually loggers can accept any arbitrary data (in a form of <code>object</code>) to give the ability to include/attach any useful information to the event.</li>\n</ul>\n</li>\n<li><code>void ExecWrite(LogLevel logLevel)</code>: Usually this is called <code>Flush</code>.\n<ul>\n<li>And usually there are some automation behind the scenes, which calls\nthis periodically or when the logs count reaches a given threshold.</li>\n<li>Here you could consider to make this function asynchronous to take\nadvantage of async I/O (file and database writes are usually support\nasync I/O)</li>\n</ul>\n</li>\n</ul>\n<h3>LogDb</h3>\n<ul>\n<li><code>LogDb</code>: Yet again naming: <code>DatabaseLogger</code> would be way better in my opinion.</li>\n<li><code>Msg.msgList.Clear()</code>: This could be quite error-prone if you call it inside the ctor. Image the following situation: You have created a <code>LogDb</code> and wrote some log into it then you create a <code>LogFile</code>. Now all your logs are now gone.</li>\n<li><code>LogDb</code>'s<code>ExecWrite</code>: It might make sense to use <code>NotSupportedException</code> if you have no willing to implement it. But in that case the whole class does not make too much sense.</li>\n</ul>\n<h3>LogFile</h3>\n<ul>\n<li><code>LogFile</code>: <code>FileLogger</code> as a naming alternative.</li>\n<li><code>LogFile</code>' <code>ExecWrite</code>: This whole retry logic is quite naive. For example if the file path is invalid (pointing to a non-existing file or folder) then retrying the same action would not change anything.\n<ul>\n<li>With the current implementation of <code>LogDb</code> your <code>catch</code> block does\nnot make any sense.</li>\n<li>Also you are swallowing the exception\nwithout logging the fact that something went wrong.</li>\n</ul>\n</li>\n<li><s><code>WriteToFile</code>: What if the file does not exists? Why do you use <code>FileShare.ReadWrite</code>? Why don't use async I/O? </s></li>\n<li><code>DateTime.UtcNow.AddHours(08)</code>: This hard-coded time-zone handling makes your utility hard to maintain and even harder to make it reusable.\n<ul>\n<li>Also please bear in mind that all events will have the same timestamp\nthat are written to the file at the same time. A better approach\nwould be to add the timestamp to your log message at the time when\nthe consumer of your API calls the <code>WriteLog</code> method.</li>\n</ul>\n</li>\n</ul>\n<h3>LogBoth</h3>\n<ul>\n<li><code>LogBoth</code>: <code>DatabaseAndFileLogger</code> as a naming alternative.</li>\n<li><code>LogBoth</code>'s <code>ExecuteWrite</code>: Here you have determined the ordering. If you have to change that then you have create a new class or create an overload.\n<ul>\n<li>If you would use async I/O then you could take advantage of concurrent persistence calls.</li>\n<li>In the industry standard loggers there is no such thing like this. The consumer of your API can set up multiple <strong>sink</strong>s (persistence storage) in configuration file and the logger will take care of them.</li>\n<li>It is quite challenging to implement it in the right way, because what should happen if either of them fails?</li>\n</ul>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:17:42.683",
"Id": "503116",
"Score": "0",
"body": "Thank you for your advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:00:19.977",
"Id": "255042",
"ParentId": "255040",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T08:54:59.897",
"Id": "255040",
"Score": "2",
"Tags": [
"c#",
"factory-method"
],
"Title": "Factory Method and Log writer class"
}
|
255040
|
<p><strong>Problem Statement:</strong><br>
Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season.
<br>
<br>
<strong>Input:</strong><br>
N = 6
<br>arr[] = {3,0,0,2,0,4}
<br>
<strong>Output:</strong>
10
<br>
For complete description, please go to this <a href="https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1#" rel="nofollow noreferrer">link</a>. <br>
<br>
<strong>My Code:</strong><br></p>
<pre><code>// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// function to find the trapped water in between buildings
// arr: input array
// n: size of array
int maxValueInArray(int arr[], int start, int end){
if(start == end) return arr[start];
int mx = 0;
for(int i = start; i<=end; i++){
mx = max(arr[i], mx);
}
return mx;
}
int trappingWater(int arr[], int n){
// Your code here
int ans = 0;
for(int i = 1; i<n-1; i++){
int curr = arr[i];
int maxLeft = maxValueInArray(arr,0, i-1);
int maxRight = maxValueInArray(arr, i+1, n-1);
if(maxLeft == curr || maxRight == curr) ans += 0; // 8, 8, 3
else if(maxLeft >= curr && curr >= maxRight) ans += 0; //8, 5, 3
else if(maxLeft <= curr && curr <= maxRight) ans+= 0; //2, 4, 7
else if(maxLeft < curr && curr > maxRight) ans+= 0; //5, 7, 6
else ans += min(maxLeft, maxRight) - arr[i];
}
return ans;
}
// { Driver Code Starts.
int main(){
int t;
//testcases
cin >> t;
while(t--){
int n;
//size of array
cin >> n;
int a[n];
//adding elements to the array
for(int i =0;i<n;i++){
cin >> a[i];
}
//calling trappingWater() function
cout << trappingWater(a, n) << endl;
}
return 0;
} // } Driver Code Ends
</code></pre>
<br>
<br>
<p><strong><strong>Issue:</strong></strong>
<br>
I'm unable to understand why I'm getting a time exceeded error in this code. Can somebody tell what's going wrong?</p>
|
[] |
[
{
"body": "<p>Your current solution is <span class=\"math-container\">\\$ O(n^2) \\$</span> because of the nested loops.</p>\n<p>There are a couple ways to solve this in <span class=\"math-container\">\\$ O(n) \\$</span> time without having to use any extra arrays. One way is to go from left-to-right while keeping track of the highest wall you’ve seen so far, then do the same thing from right-to-left until you reach the last highest wall you saw when going left-to-right. It’s <span class=\"math-container\">\\$ O(n) \\$</span>, but you‘ll need to look at almost every array index twice if the wall at index 0 is the highest.</p>\n<p>The other way is to alternate between going from left-to-right or right-to-left depending on which side had the last highest wall seen. If you do it like this then you’ll always only need to look at each index one time. You can write the function like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int trappingWater(int arr[], int arr_size)\n{\n if (arr_size <= 0)\n {\n return 0;\n }\n\n int water = 0;\n \n int max_left = arr[0];\n int max_right = arr[arr_size - 1];\n \n int left_ind = 0;\n int right_ind = arr_size - 1;\n \n while (left_ind < right_ind - 1)\n {\n if (max_left <= max_right)\n {\n left_ind += 1;\n if (arr[left_ind] > max_left)\n {\n max_left = arr[left_ind];\n }\n else\n {\n water += max_left - arr[left_ind];\n }\n }\n else\n {\n right_ind -= 1;\n if (arr[right_ind] > max_right)\n {\n max_right = arr[right_ind];\n }\n else\n {\n water += max_right - arr[right_ind];\n }\n }\n }\n return water;\n}\n</code></pre>\n<p>For your current code, it would be better if you avoided <code>using namespace std;</code> to avoid possible name conflicts: <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>. You could also use better variable names in some places. There are some spots where you explain what the variable is in a comment right after making the variable. Instead of doing that, you could just give the variable a more complete name. Then you don’t have to check the comment if you forget what it is. Here’s what your current code would look like with those two things in mind:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int maxValueInArray(int arr[], int start, int end){\n if(start == end) return arr[start];\n int maxHeight = 0;\n for(int i = start; i<=end; i++){\n maxHeight = std::max(arr[i], maxHeight);\n }\n return maxHeight;\n \n}\n\nint trappingWater(int arr[], int arrSize){\n\n // Your code here\n int ans = 0;\n for(int i = 1; i<arrSize-1; i++){\n int currentWall = arr[i];\n int maxLeft = maxValueInArray(arr,0, i-1);\n int maxRight = maxValueInArray(arr, i+1, arrSize-1);\n if(maxLeft == currentWall || maxRight == currentWall) ans += 0; // 8, 8, 3\n else if(maxLeft >= currentWall && currentWall >= maxRight) ans += 0; //8, 5, 3\n else if(maxLeft <= currentWall && currentWall <= maxRight) ans+= 0; //2, 4, 7\n else if(maxLeft < currentWall && currentWall > maxRight) ans+= 0; //5, 7, 6\n else ans += std::min(maxLeft, maxRight) - arr[i];\n }\n return ans;\n}\n\n// { Driver Code Starts.\n\nint main(){\n \n int testCases;\n std::cin >> testCases;\n \n while(testCases--){\n int arrSize;\n \n std::cin >> arrSize;\n \n int arr[arrSize];\n \n //adding elements to the array\n for(int i =0; i<arrSize; i++){\n std::cin >> arr[i]; \n }\n \n //calling trappingWater() function\n std::cout << trappingWater(arr, arrSize) << std::endl;\n \n }\n \n return 0;\n} // } Driver Code Ends\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T20:13:31.973",
"Id": "255062",
"ParentId": "255041",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T08:55:36.997",
"Id": "255041",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Geeks for Geeks: Trapping Rain Water Problem - time limit exceeded"
}
|
255041
|
<p>I have a Java program that does find and replace (like when you do it in a text editor for example notepad++) in files of a folder and all sub-folders.</p>
<p>I created 4 functions: the first function has folder path in the parameters so it listed all the sub files if it's a folder then list all the sub files again: then in RecursivePrint I check the extension of the file. If it's a non readable file like images and compressed files then ignore, otherwise I open the file using BufferedReader and check for the string and replace it with the new string.</p>
<pre><code> package test;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.channels.FileChannel;
import java.nio.file.StandardCopyOption;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Scanner;
import java.net.URL;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.*;
import java.nio.file.*;
import java.io.IOException;
import java.awt.image.*;
import javax.imageio.*;
class FileSystem{
JFrame frame;
JLabel pathLabel, findLabel, replaceLabel, imageLabel, fbLabel, appLabel; // labels
JTextField path, find, replace, image, fbId, appName; // fields
JButton browse; // button that will search for files
JButton start; // button to execute the program
File fileSelectedViaChooser;
File fileDirectory;
private String findWord, replaceWord;
FileSystem(){
frame = new JFrame("File System"); // title of the Frame passed
frame.setSize(600,530); ///Frame Size 600width and 550Height
frame.setLayout(null); //No built-in layout being used
frame.setLocationRelativeTo(null); //Frame must be at centre position
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //On Closing the Frame program shall terminate
pathLabel = new JLabel("Path"); //Creating a Label for Path
pathLabel.setFont(new Font("Serif", Font.BOLD, 20)); // setting Font Style and Size for Label
pathLabel.setBounds(80,50,50,30); // Giving Label a location in Frame
frame.add(pathLabel); // adding Label in Frame
path = new JTextField(); // initialized textField here
path.setToolTipText("Add Path of the directory here"); // adding a tool tip when cursor is placed o field
path.setFont(new Font("Serif", Font.PLAIN, 18)); // setting fonts
path.setBounds(165,50,350,32); // adding position of field in the Frame
frame.add(path); // adding Field in the frame
findLabel = new JLabel("Find"); //Creating a Label for Find
findLabel.setFont(new Font("Serif", Font.BOLD, 20)); // setting Font Style and Size for Label
findLabel.setBounds(80,90,50,30); // Giving Label a location in Frame
frame.add(findLabel); // adding Label in Frame
find = new JTextField(); // initialized textField here
find.setToolTipText("Word to find"); // adding a tool tip when cursor is placed o field
find.setFont(new Font("Serif", Font.PLAIN, 18)); // setting fonts
find.setBounds(165,90,350,32); // adding position of field in the Frame
frame.add(find); // adding Field in the frame
replaceLabel = new JLabel("Replace"); //Creating a Label for Replace
replaceLabel.setFont(new Font("Serif", Font.BOLD, 20)); // setting Font Style and Size for Label
replaceLabel.setBounds(80,130,150,30); // Giving Label a location in Frame
frame.add(replaceLabel); // adding Label in Frame
replace = new JTextField(); // initialized textField here
replace.setToolTipText("Word to Replace"); // adding a tool tip when cursor is placed o field
replace.setFont(new Font("Serif", Font.PLAIN, 18)); // setting fonts
replace.setBounds(165,130,350,32); // adding position of field in the Frame
frame.add(replace); // adding Field in the frame
JRadioButton op1=new JRadioButton("FindReplace");
ButtonGroup bg = new ButtonGroup();
op1.setBounds(80,290,100,32);
bg.add(op1);
frame.add(op1);
start = new JButton("START");
start.setBounds(450,290,80,32);
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(path.getText()==null || path.getText().equals("")){
JOptionPane.showMessageDialog(null, "Enter Path First");
frame.setVisible(false);
new FileSystem();
}
fileDirectory = new File(path.getText()+""); //file path obtained from field
/// Testing method here
if(op1.isSelected()){ // Find and Replace
if(find.getText()==null || find.getText().equals("")){
JOptionPane.showMessageDialog(null, "Fill the fields first");
}
else{
findWord(fileDirectory);
JOptionPane.showMessageDialog(null, "Replaced Successfully");
}
}
else if(op2.isSelected()){ // Copy Image
if(image.getText()==null || path.getText().equals("")){
JOptionPane.showMessageDialog(null, "Fill the fields first");
}
else{
//////////////////////////////////////////////////////////////////////////////////////////////////
String filename = fileSelectedViaChooser.getName(); //name of the file that is to be copied obtained here
File newFile = new File(filename); // new file object with same name created
newFile = new File(fileDirectory.getPath()+"\\"+newFile.getPath()); // adding the destination address of file
newFile.mkdir(); // making a new file where the contents should be copied
try{ // try catch blocks because IO Files throw exceptions
fileCopy(fileSelectedViaChooser, newFile); // fileCopy method passed source and destionation
}catch(Exception exp){
exp.printStackTrace();
}
}
}
else if(!(op1.isSelected() && op2.isSelected() && op3.isSelected() && op4.isSelected())){
JOptionPane.showMessageDialog(null, "Please Choose an Action First");
}
} // end of actionPerformed
});
frame.add(start);
frame.setVisible(true); // making the Frame Visible
}
public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException { //method that resizes the Image using graphics 2D
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
return resizedImage;
}
public void fileCopy(File source, File destination)throws IOException{ // image copying method
URL imageURL = source.toURL(); //source's URL obtained because it's a picture
BufferedImage bi = ImageIO.read(imageURL); // image read from URL
//ImageIO.write(bi, "png", destination); // image copied as it is
//Resizing the Image;
BufferedImage img1 = resizeImage(bi, 72,72);
BufferedImage img2 = resizeImage(bi, 48,48);
BufferedImage img3 = resizeImage(bi, 96,96);
BufferedImage img4 = resizeImage(bi, 144,144);
BufferedImage img5 = resizeImage(bi, 192,192);
//Copying resized files twice as name ic_launcher.png and ic_launcher_round.png
//Constatn Directories
File PATH1 = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-hdpi\\ic_launcher.png");
File PATH1a = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-hdpi\\ic_launcher_round.png");
File PATH2 = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-mdpi\\ic_launcher.png");
File PATH2a = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-mdpi\\ic_launcher_round.png");
File PATH3 = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xhdpi\\ic_launcher.png");
File PATH3a = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xhdpi\\ic_launcher_round.png");
File PATH4 = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xxhdpi\\ic_launcher.png");
File PATH4a = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xxhdpi\\ic_launcher_round.png");
File PATH5 = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xxxhdpi\\ic_launcher.png");
File PATH5a = new File(path.getText()+"\\app\\src\\main\\res\\mipmap-xxxhdpi\\ic_launcher_round.png");
ImageIO.write(img1, "png", PATH1);
ImageIO.write(img2, "png", PATH2);
ImageIO.write(img3, "png", PATH3);
ImageIO.write(img4, "png", PATH4);
ImageIO.write(img5, "png", PATH5);
ImageIO.write(img1, "png", PATH1a);
ImageIO.write(img2, "png", PATH2a);
ImageIO.write(img3, "png", PATH3a);
ImageIO.write(img4, "png", PATH4a);
ImageIO.write(img5, "png", PATH5a);
JOptionPane.showMessageDialog(null,"Copied! Successfully"); // Message Printed
}
public void findWord(File pathToStart){
// find word in every sub folders and subfiles.
File[] filesInDirectory = pathToStart.listFiles(); // all sub files listed
findWord = find.getText();
replaceWord = replace.getText();
driver();
}
public void driver(){ // drive all the files
File dir = new File(path.getText());
//fill here
if(dir.exists() && dir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir
File arr[] = dir.listFiles();
// Calling recursive method
RecursivePrint(arr,0,0);
}
//showFiles(dir.listFiles());
}
/* private void findAndReplace(String currentFile) {
System.out.println("Current file: " + currentFile);
BufferedReader reader = null;
BufferedWriter writer = null;
String content = "";
try {
reader = new BufferedReader(new FileReader(currentFile));
String line = reader.readLine();
while (line != null) {
content += line + System.lineSeparator();
line = reader.readLine();
}
String updatedContent = content.replaceAll(findWord, replaceWord);
writer = new BufferedWriter(new FileWriter(currentFile));
writer.write(updatedContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
*/
public void RecursivePrint(File[] arr,int index,int level) //arr file array
{
// terminate condition
if(index == arr.length)
return;
// tabs for internal levels
for (int i = 0; i < level; i++)
System.out.print("\t");
// for files
if(arr[index].isFile()){
String fileNamee;
fileNamee=arr[index].getAbsolutePath();
if( fileNamee.contains(".png") == false && fileNamee.contains(".jpg") == false && fileNamee.contains(".jpeg") == false
&& fileNamee.contains(".rawproto") == false&& fileNamee.contains(".apk") == false && fileNamee.contains(".pro") == false){
modifyFile(fileNamee, findWord, replaceWord);
System.out.println("\nDoing The Task");
}
else{
//System.out.print("File Not Readaable might be img file or other on-readable file");
}
}
// for sub-directories
else if(arr[index].isDirectory() && !(arr[index].getName().equals(".git")))
{
// recursion for sub-directories
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}
// recursion for main directory
RecursivePrint(arr,++index, level);
}
public static void modifyFile(String filePath, String oldString, String newString){
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new FileWriter(fileToBeModified);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
//Closing the resources
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/* private static String getExtension(String filename) { // method that gets extension from a file
if (filename == null) {
return null;
}
String extension = "";
int i = filename.lastIndexOf('.');
if (i > 0) {
extension = filename.substring(i + 1);
return extension;
}
return "";
}*/
public static void main(String[] args){
new FileSystem();
//System.out.println(getExtension("MainActivity.txt"));
}
}
</code></pre>
<p>This code is working perfectly, but it takes too long. Is there any way that I can improve the performance of this program ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T15:09:02.987",
"Id": "503067",
"Score": "1",
"body": "How long is too long? Based on what dataset size? (# folders, #files, #characters/file, total MB)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T13:57:02.527",
"Id": "503183",
"Score": "0",
"body": "Get yourself a profiler tool and have it show you the hotspot (the place where your program spends 90% of time). It might be the line `oldContent = oldContent + line + System.lineSeparator();` If so, use a `StringBuilder` instead of a `String` for `oldContent`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T08:20:27.170",
"Id": "505298",
"Score": "3",
"body": "Welcome to CodeReview@SE. Advice for posting: heed the help like [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) Proof-read. Advice for presenting code: check layout of presentation, copy from there into fresh environment and check it still compiles/works. Don't write, never present undocumented/uncommented code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T14:50:32.167",
"Id": "505319",
"Score": "0",
"body": "The code should be production ready code, and should not contain commented out functions."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:14:17.277",
"Id": "255043",
"Score": "1",
"Tags": [
"java",
"performance",
"file-system",
"swing"
],
"Title": "Performance in find and replace String program java"
}
|
255043
|
<p>I have a service that converts an Excel spreadsheet file into HTML. It is working just fine, but it is quite a big method that doesn't follow any SOLID principles. Therefore I would like to improve it to follow at least the Single Responsibility Principle. But I really don't know how to apply it and find the level of abstraction in my case.</p>
<pre><code>@Service
public class xlsToHtmlImpl implements MultipartFileToHtmlService {
private final HtmlLayout htmlLayout;
@Autowired
public xlsToHtmlImpl(HtmlLayout htmlLayout) {
this.htmlLayout = htmlLayout;
}
@Override
public InputStream multipartFileToHtml(MultipartFile multipartFile, boolean hasOnlyOneSheet, boolean hasBorders) throws IOException {
String fileName = multipartFile.getOriginalFilename();
BufferedInputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
Workbook workbook;
assert fileName != null;
//Selecting workbook depending on FileType
if (fileName.toLowerCase().endsWith(htmlLayout.FILE_TYPES[0])) {
workbook = new HSSFWorkbook(inputStream);
} else {
workbook = new XSSFWorkbook(inputStream);
}
//Writing content of multipartFile to outputstream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(htmlLayout.openStyle());
//Selecting style to apply depending on user input
if (hasBorders) {
outputStream.write(htmlLayout.noBordersStyle());
} else {
outputStream.write(htmlLayout.withBordersStyle());
}
outputStream.write(htmlLayout.closeStyle());
outputStream.write(htmlLayout.openNewHtml());
outputStream.write(fileName.getBytes());
//Different algorithm for the content of the body depending on user input
Sheet sheet;
if (hasOnlyOneSheet) {
sheet = workbook.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
Iterator<Cell> cells = row.cellIterator();
outputStream.write(htmlLayout.newLine());
outputStream.write(htmlLayout.newRow());
while (cells.hasNext()) {
Cell cell = cells.next();
outputStream.write(htmlLayout.newCell());
outputStream.write(cell.toString().getBytes());
outputStream.write(htmlLayout.closeCell());
}
outputStream.write(htmlLayout.closeRow());
}
} else {
for (int i = 0; i< workbook.getNumberOfSheets(); i++) {
sheet = workbook.getSheetAt(i);
Iterator<Row> rows = sheet.rowIterator();
outputStream.write(htmlLayout.newLine());
outputStream.write(htmlLayout.newRow());
outputStream.write(htmlLayout.closeCell());
outputStream.write(htmlLayout.closeRow());
outputStream.write(htmlLayout.newLine());
while (rows.hasNext()) {
Row row = rows.next();
Iterator<Cell> cells = row.cellIterator();
outputStream.write(htmlLayout.newLine());
outputStream.write(htmlLayout.newRow());
while (cells.hasNext()) {
Cell cell = cells.next();
outputStream.write(htmlLayout.newCell());
outputStream.write(cell.toString().getBytes());
outputStream.write(htmlLayout.closeCell());
}
outputStream.write(htmlLayout.closeRow());
}
}
}
outputStream.write(htmlLayout.newLine());
outputStream.write(htmlLayout.closeHtml());
outputStream.close();
//Returning result as ByteArrayInputStream to controller
return new ByteArrayInputStream(outputStream.toByteArray());
}
</code></pre>
<p>Where <code>htmlLayout</code> contains a HTML snippet like:</p>
<p><code>public byte[] closeHtml() {return "</table></body></html>".getBytes();}</code></p>
<p>I tried to follow the advice given in <em><a href="https://www.baeldung.com/java-single-responsibility-principle#:%7E:text=As%20the%20name%20suggests%2C%20this,only%20one%20reason%20to%20change.&text=These%20classes%20are%20harder%20to%20maintain." rel="noreferrer">Single Responsibility Principle in Java</a></em>.</p>
<p>Following this article, I created different classes as follows:</p>
<pre><code>public class HtmlStyleWrapper {
private byte[] style;
public byte[] withBordersStyle() {
return ("table, td{" +
" border: 1px solid black;\n" +
" border-collapse: collapse;\n" +
" padding: 9px;\n" +
"}").getBytes();
}
public byte[] noBordersStyle() {
return ("td {" +
" padding: 9px;\n" +
"}").getBytes();
}
public byte[] openStyle() {
return "</title></head><body><style>".getBytes();
}
public byte[] closeStyle() {
return "</style><table>".getBytes();
}
public void wrapStyle(ByteArrayOutputStream outputStream, boolean hasBorders) throws IOException {
outputStream.write(openStyle());
if (hasBorders) {
outputStream.write(noBordersStyle());
} else {
outputStream.write(withBordersStyle());
}
outputStream.write(closeStyle());
}
public class HtmlBodyWrapper {
private byte[] body;
public byte[] openNewHtml() {
return "<!DOCTYPE html><html><head><title>".getBytes();
}
public byte[] newLine() {
return "\n".getBytes();
}
public byte[] closeHtml() {
return "</table></body></html>".getBytes();
}
public byte[] newRow() {
return "<tr>".getBytes();
}
public byte[] closeRow() {
return "</tr>".getBytes();
}
public byte[] newCell() {
return "<td>".getBytes();
}
public byte[] closeCell() {
return "</td>".getBytes();
}
public void wrapBody(ByteArrayOutputStream outputStream, String fileName, boolean hasOnlyOneSheet, Workbook workbook) throws IOException {
//Write to outputstream
}
</code></pre>
<p>The aim would be to get something like</p>
<pre><code>wrapHTMLBody(wrapStyle(htmlLayout.getHTML_STYLE()), table)
</code></pre>
<p>But I feel like I'm not taking the right approach and that I didn't correctly understand SRP.</p>
|
[] |
[
{
"body": "<p>To do a better design, I think you need to know what features you will need.\nThe needs should drive your API and design.\nThe danger to create new classes without a knowldege af future needs, is that you can do bad choices, bad abstractions the leads to a complicated interface / API.</p>\n<p>For now, it is most important to make your code cleaner I think : split your big parsing method in smaller ones for example, or avoid the duplication between one sheet or many sheets.</p>\n<p>That said, I wrote something that I hope can be useful.\nI have made an excel parser that raised events we can listen to. Here I used the events to generate an HtmlFile, but It could be a Markdown one.\nKeep your critical mind when reading my code : It's a draft, improvements can be done and I may be wrong in my design :)</p>\n<p>And to finish, you can have a look to this class : <a href=\"https://poi.apache.org/apidocs/dev/org/apache/poi/hssf/converter/ExcelToHtmlConverter.html\" rel=\"nofollow noreferrer\">ExcelToHtmlConverter</a>, source code <a href=\"https://github.com/apache/poi/blob/259c9967efb354a0feff2a861ac8bd20582b6562/src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToHtmlConverter.java\" rel=\"nofollow noreferrer\">here</a> : maybe you should start here if it fits your needs, even if the code is not very clean and readable.</p>\n<pre><code>public ExcelToHtml {\n public File generate(File excelFile, Style style) {\n ExcelToHtmlWriter excelToHtmlWriter = new ExcelToHtmlWriter(style);\n ExcelParser excelParser = new ExcelParser(excelFile, excelToHtmlWriter);\n excelParser.parse();\n return excelToHtmlWriter.generatedFile();\n }\n}\n\npublic class ExcelParser {\n\n private final File excelFile;\n private final ExcelFileEventListener listener;\n\n public ExcelParser(File excelFile, ExcelFileEventListener listener) {\n this.excelFile = excelFile;\n this.listener = listener;\n }\n\n public void parse() {\n try (InputStream inp = new FileInputStream(excelFile)) {\n parseWorkbook(inp);\n } catch (IOException e) {\n throw new RuntimeException("error during parsing", e);\n }\n }\n\n private void parseWorkbook(InputStream inp) throws IOException {\n listener.start();\n Workbook wb = WorkbookFactory.create(inp);\n int numberOfSheets = wb.getNumberOfSheets();\n for (int i = 0; i < numberOfSheets; i++) {\n parseSheet(wb, i);\n }\n listener.end();\n }\n\n private void parseSheet(Workbook wb, int i) {\n listener.newSheet();\n Sheet sheet = wb.getSheetAt(i);\n for (Row row : sheet) {\n parseRow(row);\n }\n listener.endSheet();\n }\n\n private void parseRow(Row row) {\n listener.newRow();\n for (Cell cell : row) {\n listener.newCell();\n listener.cellContent(cell.toString());\n listener.endCell();\n }\n listener.endRow();\n }\n}\n\npublic class ExcelToHtmlWriter implements ExcelFileEventListener {\n\n private static final String LINE_SEPARATOR = System.lineSeparator();\n private final Style style;\n\n private FileWriter writer;\n private File tmpFile;\n\n public ExcelToHtmlWriter(Style style) {\n this.style = style;\n }\n\n @Override\n public void newSheet() {\n write("<table>");\n write(LINE_SEPARATOR);\n }\n\n @Override\n public void endSheet() {\n write("</table>");\n write(LINE_SEPARATOR);\n }\n\n @Override\n public void newRow() {\n write("<tr>");\n write(LINE_SEPARATOR);\n }\n\n @Override\n public void endRow() {\n write(LINE_SEPARATOR + "</tr>" + LINE_SEPARATOR);\n }\n\n @Override\n public void newCell() {\n write("<td>");\n }\n\n @Override\n public void endCell() {\n write("</td>");\n }\n\n @Override\n public void cellContent(String value) {\n write(value);\n }\n\n @Override\n public void start() {\n try {\n tmpFile = File.createTempFile("test", ".tmp");\n writer = new FileWriter(tmpFile);\n write("<html>" + LINE_SEPARATOR);\n write("<head>" + LINE_SEPARATOR);\n write("<style>" + LINE_SEPARATOR);\n write(style.content());\n write("</style>" + LINE_SEPARATOR);\n write("</head>" + LINE_SEPARATOR);\n write("<body>" + LINE_SEPARATOR);\n } catch (IOException e) {\n throw new RuntimeException("unable to initialize file", e);\n }\n }\n\n @Override\n public void end() {\n try {\n write("</body>" + LINE_SEPARATOR);\n write("</html>" + LINE_SEPARATOR);\n writer.close();\n } catch (IOException e) {\n throw new RuntimeException("unbale to close writer", e);\n }\n }\n\n public File generatedFile() {\n return tmpFile;\n }\n\n private void write(String toWrite) {\n try {\n writer.write(toWrite);\n } catch (IOException e) {\n try {\n writer.close();\n } catch (IOException ioException) {\n } finally {\n throw new RuntimeException("unable to write to file", e);\n }\n }\n }\n}\n\npublic class Style {\n private final boolean cellBorders;\n\n public Style(boolean cellBorders) {\n this.cellBorders = cellBorders;\n }\n\n public String content() {\n StringBuilder content = new StringBuilder("td {");\n content.append(System.lineSeparator());\n content.append("padding: 9px;");\n if (cellBorders) {\n content.append(System.lineSeparator());\n content.append("border: 1px solid black;");\n content.append(System.lineSeparator());\n content.append("border-collapse: collapse;");\n }\n content.append(System.lineSeparator());\n content.append("}");\n content.append(System.lineSeparator());\n return content.toString();\n }\n}\n\ninterface ExcelFileEventListener {\n void newSheet();\n void start();\n void end();\n void endSheet();\n void newRow();\n void endRow();\n void newCell();\n void endCell();\n void cellContent(String value);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:18:17.493",
"Id": "256847",
"ParentId": "255045",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:41:21.857",
"Id": "255045",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Java service to convert xls files to HTML"
}
|
255045
|
<p>The problem statement was pretty easy and I was able to run half of the test cases, but some of the test cases in the end gave me the error of memory limit reached. What can I do here to improve the memory efficiency of my code?</p>
<p>Question: Find the min number of "usable" integers required to reach the N. The "usable integers" are those that contain only <code>4</code> or <code>5</code> in their decimal representation, e.g. <code>4</code>,<code>5</code>,<code>455</code>,<code>545454</code>.</p>
<p>So to reach <code>9</code>, answer would be <code>2</code> (4+5) My approach: Creating a vector consisting of all usable numbers up to <code>N</code> and using dynamic programming solution on that vector to find the minimum number of elements required to reach <code>N</code>.</p>
<p>My code:</p>
<pre><code>int getCount(int N) {
vector<int> vec;vec.push_back(4);vec.push_back(5);
int i = 0;int temp = 0;
while(true) {
temp = vec[i] * 10 + 4;
if(temp > N)
break;
vec.push_back(temp);
temp = vec[i] * 10 + 5;
if(temp > N)
break;
vec.push_back(temp);
i++;
}
return getCountDP(vec,vec.size(),N);
}
int getCountDP(vector<int> vec,int size, int N){
int dp[size+1][N+1];
for(int i = 0 ; i <= N; i++) {
dp[0][i] = INT_MAX - 1;
}
for(int i = 0 ; i < size+1; i++) {
dp[i][0] = 0;
}
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= N; j++) {
if (vec[i - 1] > j) {
dp[i][j]= dp[i-1][j];
}
else {
dp[i][j]= min(dp[i-1][j],dp[i][j-vec[i-1]]+1);
}
}
}
return dp[size][N];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T15:52:07.537",
"Id": "503071",
"Score": "1",
"body": "This would benefit from having a complete program and also some clarification of the intent of the code. Is addition the only operation supported?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:35:09.883",
"Id": "503152",
"Score": "0",
"body": "Yes addition is the only operation supported. The intent of the code is just to find the minimum no. of \"usable\" integers which sum up to N. The main() of the code just consisted of scanning `N` and sending it to the function `getCount(int)` so I felt like there was no real need for it. @Edward"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T15:12:43.453",
"Id": "503190",
"Score": "0",
"body": "Is there a limit on `N`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:45:38.420",
"Id": "503271",
"Score": "0",
"body": "yes, 0 < N < 10^6 @AJNeufeld"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T04:18:24.253",
"Id": "503362",
"Score": "0",
"body": "What dous `dp[i][j]` mean? What does `i` here for? Could you just make it `dp[j]`?"
}
] |
[
{
"body": "<p>Since your question is about Memory Limit Exceed. And the most memory consumed item is <code>dp</code>. You are going to make your <code>dp</code> matrix smaller. Your current memory usage is <span class=\"math-container\">\\$O(2^{log_{10}n}\\cdot n) = O(n^2)\\$</span>. And you need to reduce it to <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>Let's write down your current dp function:</p>\n<p><span class=\"math-container\">$$ dp_{i,j} = \\min \\{ dp_{i-1,j}, dp_{i, j-usable_i}+1 \\} $$</span></p>\n<p>First, consider you only need <code>dp[i]</code> and <code>dp[i-1]</code> during iteration. All previous rows are not necessarily any more. You may only declare two rows as <code>dp1[N + 1]</code> and <code>dp2[N + 1]</code>. (To make the logic for even and odd rows consistent, use two pointers point to these array.) By using this approach, memory usage may reduced into <span class=\"math-container\">\\$O(2n) = O(n)\\$</span>.</p>\n<p>Another approach may be just reduce your dp function into 1 dimension:</p>\n<p><span class=\"math-container\">$$ dp_{j} = \\min_{n \\in usable} \\{dp_{j-n}\\} + 1 $$</span></p>\n<p>So, you may only maintain <code>dp[N + 1]</code> instead. This also cost <span class=\"math-container\">\\$O(n)\\$</span> memory. The second approach also make the array reusable when this function is invoked later. If you are going to handle multiple testcases in one run. You may simply declare it as global variable <code>dp[MAX_N + 1]</code> to reduce its time consume.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nconst int MAX_N = 1000000;\nconst int MAX_VAL = 128; // 2 ^ (log10(MAX_N) + 1)\n\nint getCount(int n) {\n static int filled = 0;\n // values hold all numbers only contais 4 or 5 in 0 ~ 1e6\n static int values[MAX_VAL] = {4, 5};\n // steps is the array for dp\n // steps[i] = min(steps[i - values[j]] + 1 for every j)\n static int steps[MAX_N];\n int i, j, step, min_step;\n if (n > MAX_N) return -1; // We do not support input > 1e6\n // When first time run, we fill all values\n if (filled == 0) {\n for (i = 2, j = 0; i < MAX_VAL; j++) {\n values[i++] = values[j] * 10 + 4;\n values[i++] = values[j] * 10 + 5;\n }\n steps[0] = 0;\n filled = 1;\n }\n for (i = filled > 1 ? filled : 1; i <= n; i++) {\n // We use MAX_N+1 for values cannot be reached\n min_step = MAX_N + 1;\n for (j = 0; values[j] <= i; j++) {\n step = steps[i - values[j]] + 1;\n if (step < min_step) min_step = step;\n }\n steps[i] = min_step;\n }\n filled = n;\n if (steps[n] > n) return -1;\n return steps[n];\n}\n\nint main() {\n int n;\n for (n = 0; n < MAX_N; n++) {\n printf("%d\\n", getCount(n));\n }\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T06:31:08.317",
"Id": "255166",
"ParentId": "255047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255166",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T11:08:28.133",
"Id": "255047",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"vectors",
"dynamic-programming",
"memory-optimization"
],
"Title": "Find a sum using just two different digits"
}
|
255047
|
<p>I have created a task that I need to query database for List of String and store it in <code>neededDataList</code>. I will use <code>neededDataList</code> in a scheduled task every 10 minutes to do a simple task.</p>
<p>And I need to retrieve a fresh data of <code>neededDataList</code> every 1 hour. Will the <code>scheduledExecutorService2</code> pick up the fresh <code>neededDataList</code>?
Can someone review my code if it will cause some problem?</p>
<p>Assuming my code has its main method and it will call the <code>run(Database database)</code>:</p>
<pre><code> public class Handler {
private static final ScheduledExecutorService scheduledExecutorService1 = MDScheduledExecutorService.wrap(
new ScheduledThreadPoolExecutor(1), "ses-1-thread-%d");
private static final ScheduledExecutorService scheduledExecutorService2 = MDScheduledExecutorService.wrap(
new ScheduledThreadPoolExecutor(5), "ses-2-thread-%d");
private List<String> neededDataList;
private void run(Database database) {
scheduledExecutorService1.scheduleAtFixedRate(() -> {
neededDataList= database.getNeededData();
}, 1, 60, TimeUnit.MINUTES);
scheduledExecutorService2.scheduleAtFixedRate(new HandlerImpl(), 1, 10, TimeUnit.MINUTES);
}
private class HandlerImpl implements Runnable {
@Override
public void run() {
executeTask(neededDataList);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is not thread-safe.</p>\n<p>The <code>Handler.run()</code> method creates two services which will end up being deparate threads. These threads are accessing and updating the <code>neededDataList</code> shared variable without any synchronization. This could lead to unpredictable behavior, including the service that is reading the list seeing stale values.</p>\n<p>Also, this code won't compile because the <code>executeTask</code> method is not defined.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T14:47:46.613",
"Id": "255136",
"ParentId": "255054",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T14:20:41.230",
"Id": "255054",
"Score": "0",
"Tags": [
"java",
"multithreading"
],
"Title": "ScheduledExecutorService running a couple of scheduleAtFixedRate"
}
|
255054
|
<p>I am working on replacing a dependency in a library for System.Management and migrating to using Microsoft.Management.Infrastructure as recommended by Microsoft. The issue is that Microsoft.Management.Infrastructue does not have an equivalent for the ManagementEventWatcher class in System.Management. The management event watcher is used in this scenario to monitor for registry changes and perform an action when this occurs. Normally with managment event watcher you could do like below (crude example).</p>
<pre><code> var query = "SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE' " +
"AND KeyPath = 'SOFTWARE\\\\TESTKEY' " +
"AND ValueName = 'TestValue'";
var mgmtWatcher = new ManagementEventWatcher(query);
mgmtWatcher.EventArrived += MgmtWatcher_EventArrived;
mgmtWatcher
.Start();
Console.ReadLine();
private static void MgmtWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Detected");
}
</code></pre>
<p>I have now created the below as a replacement and am wondering if anyone can see any issues or something I am missing.</p>
<pre><code>/// <summary>
/// CimWatcher event args, which contains CimSubscriptionResult
/// </summary>
public class CimWatcherEventArgs : EventArgs
{
public CimSubscriptionResult CimSubscriptionResult { get; }
public CimWatcherEventArgs(CimSubscriptionResult cimSubscriptionResult)
{
CimSubscriptionResult = cimSubscriptionResult;
}
}
/// <summary>
/// <para>
/// A public class used to start/stop the subscription to specific indication source,
/// and listen to the incoming indications, event <see cref="EventArrived" />
/// will be raised for each cimindication.
/// </para>
/// </summary>
public class CimWatcher : IDisposable
{
internal enum CimWatcherStatus
{
Default
, Started
, Stopped
}
//Events
public event EventHandler<CimWatcherEventArgs> EventArrived = delegate { };
//Fields
private object _myLock;
private bool _isDisposed;
private CimWatcherStatus _cimWatcherStatus;
private readonly string _computerName;
private readonly string _nameSpace;
private readonly string _queryDialect;
private readonly string _queryExpression;
private CimSession _cimSession;
private CimAsyncMultipleResults<CimSubscriptionResult> _cimObservable;
private IDisposable _subscription;
internal static readonly string DefaultNameSpace = @"root\cimv2";
internal static readonly string DefaultQueryDialect = "WQL";
/// <summary>
/// Initializes a new instance of the <see cref="CimWatcher" /> class.
/// </summary>
/// <param name="queryExpression"></param>
public CimWatcher(string queryExpression)
{
if (string.IsNullOrWhiteSpace(queryExpression))
throw new ArgumentNullException(nameof(queryExpression));
_nameSpace = DefaultNameSpace;
_queryDialect = DefaultQueryDialect;
_queryExpression = queryExpression;
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="CimWatcher" /> class.
/// </summary>
/// <param name="queryDialect"></param>
/// <param name="queryExpression"></param>
public CimWatcher(string queryDialect, string queryExpression)
{
if (string.IsNullOrWhiteSpace(queryExpression))
throw new ArgumentNullException(nameof(queryExpression));
_nameSpace = DefaultNameSpace;
_queryDialect = queryDialect ?? DefaultQueryDialect;
_queryExpression = queryExpression;
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="CimWatcher" /> class.
/// </summary>
/// <param name="nameSpace"></param>
/// <param name="queryDialect"></param>
/// <param name="queryExpression"></param>
public CimWatcher(string nameSpace, string queryDialect, string queryExpression)
{
if (string.IsNullOrWhiteSpace(queryExpression))
throw new ArgumentNullException(nameof(queryExpression));
_nameSpace = nameSpace ?? DefaultNameSpace;
_queryDialect = queryDialect ?? DefaultQueryDialect;
_queryExpression = queryExpression;
Initialize();
}
/// <summary>
/// Initializes a new instance of the <see cref="CimWatcher" /> class.
/// </summary>
/// <param name="computerName"></param>
/// <param name="nameSpace"></param>
/// <param name="queryDialect"></param>
/// <param name="queryExpression"></param>
public CimWatcher(string computerName, string nameSpace, string queryDialect, string queryExpression)
{
if (string.IsNullOrWhiteSpace(queryExpression))
throw new ArgumentNullException(nameof(queryExpression));
_computerName = computerName;
_nameSpace = nameSpace ?? DefaultNameSpace;
_queryDialect = queryDialect ?? DefaultQueryDialect;
_queryExpression = queryExpression;
Initialize();
}
public void Initialize()
{
_cimWatcherStatus = CimWatcherStatus.Default;
_myLock = new object();
_cimSession = CimSession
.Create(_computerName);
_cimObservable = _cimSession
.SubscribeAsync(_nameSpace, _queryDialect, _queryExpression);
}
private void OnEventArrived(CimWatcherEventArgs cimWatcherEventArgs)
{
Volatile
.Read(ref EventArrived)
.Invoke(this, cimWatcherEventArgs);
}
public void Start()
{
lock (_myLock)
{
if (_isDisposed)
throw new ObjectDisposedException(nameof(CimWatcher));
if (_cimWatcherStatus != CimWatcherStatus.Default && _cimWatcherStatus != CimWatcherStatus.Stopped) return;
_subscription = _cimObservable
.Subscribe(cimSubscriptionResult => { OnEventArrived(new CimWatcherEventArgs(cimSubscriptionResult)); });
_cimWatcherStatus = CimWatcherStatus.Started;
}
}
public void Stop()
{
lock (_myLock)
{
if (_isDisposed)
throw new ObjectDisposedException(nameof(CimWatcher));
if (_cimWatcherStatus != CimWatcherStatus.Started) return;
_subscription
?.Dispose();
_cimWatcherStatus = CimWatcherStatus.Stopped;
}
}
public void Dispose()
{
_isDisposed = true;
_subscription?.Dispose();
_cimSession?.Dispose();
}
}
</code></pre>
<p>And it can be used like below(crude example).</p>
<pre><code> var query = "SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE' " +
"AND KeyPath = 'SOFTWARE\\\\TESTKEY' " +
"AND ValueName = 'TestValue'";
var watcher =
new CimWatcher(query);
watcher.EventArrived += Watcher_EventArrived;
watcher
.Start();
Console.ReadLine();
private static void Watcher_EventArrived(object sender, CimWatcherEventArgs e)
{
Console.WriteLine("Detected");
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T16:28:15.137",
"Id": "255055",
"Score": "0",
"Tags": [
"c#",
"event-handling"
],
"Title": "Trying to replace ManagementEventWatcher class in System.Management to switch to newer Microsoft.Management.Infrastructure"
}
|
255055
|
<p>I'm making a project that needs a simple cross-platform command-line parser. I made this. Hope you enjoy!</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#define __NUM_OF_ELEMENTS(ARR) (sizeof(ARR)/sizeof(ARR[0]))
#define __HAS_ARG(FLAGS, ARG) (FLAGS & (1 << ARG))
void panic(const char *fmt, ...){
fprintf(stderr, "error: ");
va_list arglist;
va_start( arglist, fmt );
vfprintf(stderr, fmt, arglist);
va_end( arglist );
exit(EXIT_FAILURE);
}
void help(const char * progName){
char * whoami = 0;
(whoami = strrchr(progName, '/')) ? ++whoami : (whoami = progName);
printf(
"%s is intended to do blah\n"
"Options:\n"
" --help Display This message\n"
" --file [file name] Input file to use\n",
whoami);
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
if(argc == 1){
help(argv[0]);
}
const char * args[] = {"--help", "--file", "--2cool4scool"};
enum {HELP_ARG, FILE_ARG, TOO_COOL_FOR_SCHOOL_ARG};
unsigned int flags = 0;
//skip prog name
for(unsigned int arg = 1, i = 0; arg < argc; ++arg){
for(i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i){
if(!strcmp(argv[arg], args[i])){
flags |= 1 << i;
goto CMD_ARGUMENT_FOUND;
}
}
//argument is not found / unkown arg
panic("Argument '%s' not found\n", argv[arg]);
CMD_ARGUMENT_FOUND:;
}
if(__HAS_ARG(flags, HELP_ARG)){
help(argv[0]);
}
if(__HAS_ARG(flags, TOO_COOL_FOR_SCHOOL_ARG)){
puts("Hell YA!");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Since this is a single-translation-unit program, mark your <code>panic</code> and <code>help</code> as <code>static</code>.</p>\n<p>About this:</p>\n<pre><code>(whoami = strrchr(progName, '/')) ? ++whoami : (whoami = progName);\n</code></pre>\n<p>"Yikes". Generously we call this write-only code. Unroll it to</p>\n<pre><code>char *whoami = strrchr(progName, '/');\nif (whoami)\n whoami++;\nelse\n whoami = progName;\n</code></pre>\n<p>In this loop, your <code>i</code> declaration should be moved down:</p>\n<pre><code>for(unsigned int arg = 1, i = 0; arg < argc; ++arg){\n for(i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i){\n</code></pre>\n<p>should be</p>\n<pre><code>for (unsigned int arg = 1; arg < argc; ++arg) {\n for (int i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i) {\n</code></pre>\n<p>to narrow its scope.</p>\n<p>Don't use <code>goto</code>. Factor out a function where the double loop termination is done using a <code>return</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T20:29:48.240",
"Id": "503093",
"Score": "0",
"body": "Thx, I'll keep that in mind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T16:56:14.777",
"Id": "503193",
"Score": "0",
"body": "A few things to things note is the compiler will emit a warning at `for (int i = 0; i < (unsigned int) ...` as it is comparing an `int` to an `unsigned int`; I had initially declared `i` in the 1st `for` loop as it would be *technically* faster, but as you pointed out it would be better to do it the way you stated for clarity; In this example I agree `help` should be `static`, but `panic` would probably be used later in the application. With `whoami` it does make more sense to avoid the one liner;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T16:59:20.533",
"Id": "503194",
"Score": "0",
"body": "_it would be technically faster_ - I deeply doubt this. I encourage you to profile to see whether that's the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:00:22.700",
"Id": "503195",
"Score": "1",
"body": "Perhaps you're working under the assumption that re-declaring a variable imposes a runtime cost. It would not in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:05:05.467",
"Id": "503196",
"Score": "0",
"body": "I had heard something a while ago, but it doesn't really make a difference in this case besides clarity."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T20:26:31.277",
"Id": "255063",
"ParentId": "255059",
"Score": "1"
}
},
{
"body": "<p>These names are dangerous:</p>\n<blockquote>\n<pre><code>#define __NUM_OF_ELEMENTS(ARR) (sizeof(ARR)/sizeof(ARR[0]))\n#define __HAS_ARG(FLAGS, ARG) (FLAGS & (1 << ARG))\n</code></pre>\n</blockquote>\n<p>Any identifier containing two consecutive underscores is reserved for the implementation for any purpose. The same goes for names beginning with underscore and a capital letter.</p>\n<p>Also, you slightly messed up the protective parentheses when expanding macro arguments:</p>\n<pre><code>#define NUM_OF_ELEMENTS(ARR) (sizeof (ARR) / sizeof (ARR)[0])\n#define HAS_ARG(FLAGS, ARG) ((FLAGS) & (1 << (ARG)))\n</code></pre>\n<hr />\n<p>If no arguments are passed, then we hit this:</p>\n<blockquote>\n<pre><code>if(argc == 1){\n help(argv[0]);\n}\n</code></pre>\n</blockquote>\n<p>In a portable program, we should really test <code>argc <= 1</code>, since implementations are allowed to pass 0 as <code>argc</code>. The usage message should go to <code>stderr</code>, not <code>stdout</code>. And why do we continue after this? It seems very odd to print an unasked-for usage message, but then continue and return a success status.</p>\n<hr />\n<p>Maintaining parallel lists is tedious and error-prone. So this code looks pretty straightforward with three possible options:</p>\n<blockquote>\n<pre><code>const char * args[] = {"--help", "--file", "--2cool4scool"};\nenum {HELP_ARG, FILE_ARG, TOO_COOL_FOR_SCHOOL_ARG};\n</code></pre>\n</blockquote>\n<p>It becomes unmanageable once you have a few dozen options. And it doesn't handle synonyms very well (e.g. <code>-f</code> and <code>--file</code> both being acceptable).</p>\n<blockquote>\n<pre><code>flags |= 1 << i;\n</code></pre>\n</blockquote>\n<p>That ought to be <code>1u << i</code>, since <code>flags</code> is unsigned (same goes for the corresponding macro). And this fails silently once <code>i</code> becomes greater than the width of <code>unsigned</code>, leading to a hard-to-find error.</p>\n<hr />\n<blockquote>\n<pre><code> //argument is not found / unkown arg\n</code></pre>\n</blockquote>\n<p>Typo: <strong>unknown</strong></p>\n<hr />\n<blockquote>\n<pre><code>if(__HAS_ARG(flags, HELP_ARG))\nif(__HAS_ARG(flags, TOO_COOL_FOR_SCHOOL_ARG))\n</code></pre>\n</blockquote>\n<p>It seems that the <code>--file</code> option is recognised but ignored. That's almost certainly a bug. Worse than that, the help says it should be followed by a file-name argument, but actually doing so results in an "argument not found" error.</p>\n<hr />\n<p>It's worth reading the documentation of Python's <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module (even if you don't know Python) to see what a real argument handler can and should do. For example, it automates printing the usage message so you don't end up forgetting to update it when you add a new option, like here:</p>\n<blockquote>\n<pre><code> "Options:\\n"\n " --help Display This message\\n"\n " --file [file name] Input file to use\\n",\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T19:50:43.583",
"Id": "505992",
"Score": "0",
"body": "I am impressed! Although I knew a lot of compiler macros used `__` at the beginning of the names I didn't really consider that an issue. I'll use `#define lengthof(ARR) (sizeof (ARR) / sizeof (ARR)[0])` next time. I initially thought `sizeof()` was a macro until I saw that you had said `(ARR)[0]`. As for the `--file` arg being ignored that was intentional, but I do concede that I should have tested for it and then did `printf(\"file: %s\\n\", filename)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T20:01:20.457",
"Id": "505994",
"Score": "1",
"body": "As for the section where you say `Maintaining parallel lists ...` I do agree when it gets to more than 5 args. One solution in the meantime I'd say is to do to somewhat alleviate it is `struct arg{const char* str; unsigned int id;};` and then `struct arg arglist [] = {{\"--help\", HELP_ARG}, {\"-h\", HELP_ARG}};` So everything is in one place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T20:24:11.343",
"Id": "505997",
"Score": "0",
"body": "Yes, or even perhaps `struct arg { const char *option; const char *help; enum ArgType type; void *storage;}`, where `ArgType` determines what gets written to `*storage`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T20:35:21.923",
"Id": "505999",
"Score": "0",
"body": "Well, that's a little more simple. Where you say *`... void *storage;}`, where `ArgType` determines what gets written to `*storage`* I don't understand; What would storage point to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T08:19:21.773",
"Id": "506030",
"Score": "0",
"body": "For a boolean flag, the caller would set it to point to a `bool`; for a string argument like `--file`, perhaps to a `const char*` (we can point that at one of the `argv` strings); for an integer argument, it would point to a `int` or `unsigned int` or `long`, etc. It's something you might want to experiment with - and come here for a review when you have something you're happy with!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T11:42:22.210",
"Id": "256291",
"ParentId": "255059",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T18:33:53.103",
"Id": "255059",
"Score": "2",
"Tags": [
"c",
"console"
],
"Title": "Simple command line parsing"
}
|
255059
|
<p>I wrote a matrix class in C++ with an addition and multiplication method. It works fine, but I don't think a C++ programmer would enjoy reading this. I would love some help with that.</p>
<pre><code>#include <iostream>
#include <string>
class Matrix {
public:
int rows;
int columns;
int* contents;
// Constructor
// data is the contents of the matrix in a list
// like you read a book
Matrix(int m, int n, int* data) {
rows = m;
columns = n;
// We copy data to a dynamically allocated piece of memory
// to make the program more robust.
contents = new int[m*n];
for (int i = 0; i < m*n; i++) {
contents[i] = data[i];
}
}
// Returns the element in row i, column j
int getElement(int i, int j) {
return contents[columns*i + j];
}
// Gets the i'th row of this matrix
int* getRow(int i) {
// Dynamic because we need the row outside this helper function
int* row = new int[columns];
for (int j = 0; j < columns; j++) {
row[j] = getElement(i, j);
}
return row;
}
// Gets a the j'th column of matrix other
int* getColumn(int j) {
// Dynamic because we need the column outside this helper function
int* column = new int[rows];
for (int i = 0; i < rows; i++) {
column[i] = getElement(i, j);
}
return column;
}
Matrix addition(Matrix other) {
int* sum = new int[rows*columns];
for (int i = 0; i < rows*columns; i++) {
sum[i] = contents[i] + other.contents[i];
}
Matrix sumMatrix(rows, columns, sum);
delete sum;
return sumMatrix;
}
Matrix product(Matrix other) {
int* product = new int[rows*other.columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.columns; j++) {
int* row = getRow(i);
int* column = other.getColumn(j);
int value = innerProduct(row, column, columns); // Our row and the other guy's column contain as many elements as we have columns
delete row;
delete column;
product[other.columns*i + j] = value;
}
}
Matrix productMatrix(rows, other.columns, product);
delete product;
return productMatrix;
}
void print() {
for (int i = 0; i < rows; i++) {
std::cout << '{';
for (int j = 0; j < columns; j++) {
std::cout << getElement(i, j) << ", ";
}
std::cout << "}\n";
}
}
private:
// Computes the inner product between
// vec1, vec2, both vectors of length.
int innerProduct(int* vec1, int* vec2, int length) {
int sum = 0;
for (int i = 0; i < length; i++) {
sum += vec1[i]*vec2[i];
}
return sum;
}
};
int main() {
int data1[6] = {0, 1,
1, 0,
2, 2};
Matrix mat1(3, 2, data1);
int data2[8] = {1, 2, 3, 4,
5, 6, 7, 8};
Matrix mat2(2, 4, data2);
Matrix product = mat1.product(mat2);
std::cout << "Matrix 1 looks like\n";
mat1.print();
std::cout << "Matrix 2 looks like\n";
mat2.print();
std::cout << "The product looks like \n";
product.print();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:46:41.333",
"Id": "503103",
"Score": "2",
"body": "As a learning exercise, fine; but don't do this in real life - you'll be outperformed by any self-respecting BLAS library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T18:55:23.143",
"Id": "503207",
"Score": "0",
"body": "Separate business logic from resource management. i.e. Use one class to handle resource management only (i.e. memory management) and another class to handle the business logic (matrix stuff). Mixing the two just makes things harder to validate. Also separating them allows you to check them independently. You could write your matrix class using `std::vector` to handle the resource management first. Then when the matrix code works swap in an alternative resource management class that you have written."
}
] |
[
{
"body": "<h2>Prefer std::vector to Manually Allocation of Memory</h2>\n<p>I can see you are manually handling your memory, this is good but also opens the door wide for bugs to creep in. STL container <code>std::vector</code> is your best bet here. It really makes things easier for you. It gives you the following for free:</p>\n<ol>\n<li>Copy constructor</li>\n<li>Copy assignment</li>\n<li>Move constructor</li>\n<li>Move assignment</li>\n<li>Destructor</li>\n</ol>\n<p>This is a huge favor, remember <code>less code is good code</code>\nA common definition might look like this</p>\n<pre><code>template<typename T>\nclass Matrix\n{\n public:\n Matrix(size_t row, size_t column, const std::vector<T>& data)\n {\n if((row * column) != data.size())\n throw std::invalid_argument("Data size does not match the dimension"); \n row_ = row;\n column_ = column;\n data_ = data;\n \n }\n Matrix(size_t row, size_t column, const T& val) \n : row_{row}, column{column}, data_{std::vector<T>(row * column, val)}{ }\n\n private:\n size_t row_;\n size_t column_;\n std::vector<T> data_;\n};\n\n</code></pre>\n<p>The extra check guarantees that users of our class do not construct <code>ill-formed</code> matrix objects. So we are guaranteed that our class satisfies the invariant that <code>row * column == data.size()</code></p>\n<h2>Prefer Operator Overloading for Basic Functionalities</h2>\n<p>C++ users are accustomed overloaded operators such as <code>operator+</code>, <code>operator()</code>, <code>operator<<</code>. This reduces the need of learning new method, when possible prefer function overloading to defining your own method function.\nSo we can redefine <code>getElement</code> as follow</p>\n<pre><code>T& operator()(const size_t i, const size_t j)\n{\n return data_.at(column_ * i + j);\n}\n</code></pre>\n<p>With this you get an extra out of range checks for free.\nYou could overload <code>operator()</code> that takes one argument here to display a <code>row</code> or <code>column</code> but I would choose to not overload in this scenario because it might raise confusion.</p>\n<pre><code>#include <algorithm>\nstd::vector<T> get_row(const size_t i)\n{\n if(row_ <= i)\n throw std::invalid_argument("Invalid row dimension");\n\n size_t start_index = column_ * i;\n size_t end_index = start_index + column_;\n std::vector<T> vec_(end_index - start_index);\n copy(data_.begin()+start_index, data_.begin()+end_index, vec_.begin());\n\n return vec_;\n}\n</code></pre>\n<p>As you would notice, there are extra checks for out of bound access. Same approach can be used for <code>get_column</code> also but with little changes.</p>\n<h2>Prefer pass by reference to pass by value</h2>\n<p>Most if not all of your method receives arguments by value, this can get expensive when passing maybe a 1000 x 1000 matrix, you always should prefer pass by reference and if the object is not allowed to change, pass by const reference. This avoids the copy.</p>\n<h2>Other Points to consider</h2>\n<p>In <code>addition</code>, your code breaks if we try to add unequal matrix objects, perform a check to guarantee this invariant before proceeding with addition.</p>\n<p><code>delete sum</code>, does this actually delete our dynamic array? of course not, this is the more reason you should prefer <code>std::vector</code> and even if you want to manage memory, prefer <code>std::unique_ptr</code> to raw <code>new</code>. A proper way to delete a dynamically allocated array is</p>\n<pre><code>delete [] sum\n</code></pre>\n<p>Method function <code>product</code> also does not yield expected results, you can only compute product of a matrix that satisfies the invariant that <code>A.row == B.column</code> where A and B are matrix objects. Doing otherwise produces unexpected results. So we could rewrite this to be</p>\n<pre><code>Matrix<T> operator*(const Matrix& rhs)\n{\n if(row_ != rhs.column_ )\n throw std::runtime_error("Unequal size in Matrix*");\n Matrix res(rhs.row_, column_, 0.0);\n for(int i = 0; i != rhs.row_; ++i)\n {\n for(int j = 0; j != column_; ++j)\n {\n for(int k = 0; k != row_; ++k)\n {\n res(i, j) += rhs(i, k) * this->operator()(k, j);\n }\n }\n }\n\n return res;\n}\n</code></pre>\n<p>I would skip <code>addition</code> because it is trivial. You could also implement <code>inplace product</code>, <code>inplace addition</code> both for scalar and matrix.</p>\n<p>I know we all love a nice <code>print</code> member function, but C++ programmers expect to see their objects when they use the standard output stream and might forget to call your output display function; overload <code>std::ostream</code> for output functionalities. A typical definition is</p>\n<pre><code>std::ostream& operator<<(std::ostream& os, const Matrix<int>& mat)\n{\n for (int i = 0; i != mat.row_; ++i) {\n os << '{';\n for (int j = 0; j != mat.column_; ++j) {\n os << mat(i, j) << ", ";\n }\n os << "}\\n";\n }\n return os;\n}\n</code></pre>\n<p>Note that you have to declare the function as a friend to <code>Matrix</code> class in order to access the private member data, if you don't want this behaviours, create public method and access the data via the public methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T03:19:34.287",
"Id": "503118",
"Score": "0",
"body": "You should probably be more specific about *where* to pass by ref. In `addition()` and `product()`, sure, pass by ref… but in the constructor, passing by value is the right way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T06:30:56.360",
"Id": "503128",
"Score": "0",
"body": "I think it would be better if your `Matrix` constructor accepted the vector *by value* and `std::move()` it to the `data` member. And also better to use initialisers rather than assignment. +1 for the rest of the review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T06:52:12.163",
"Id": "503132",
"Score": "1",
"body": "Your constructor size check should use `!=`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:53:05.443",
"Id": "503153",
"Score": "0",
"body": "@indi, please explain what this means `but in the constructor, passing by value is the right way to do it.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:16:50.470",
"Id": "503209",
"Score": "3",
"body": "In that constructor you wrote, taking the vector by `const&` is not the right way to do it, because it is a sink function. You end up needlessly copying the entire vector. The right way to do it is take the vector by value, and then move it into `data_`. Generally if you’re *reading* a value, you take it by `const&`… if you’re *taking* a value (taking it to keep it, rather than just reading it to use it), you should take it by value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T20:28:19.280",
"Id": "503216",
"Score": "2",
"body": "Best practice: `Matrix(std::size_t width, std::size_t height, std::vector<T> data)\n : width{width},\n height{height},\n data{std::move(data)}\n {\n if (width * height != this->data.size())\n throw std::invalid_argument(\"Data size does not match the dimension\");\n }` - that doesn't re-assign the vector after initialisation, and doesn't needlessly copy when `data` is provided as rvalue (e.g. as in `Matrix identity{2, 2, { 1, 0, 0, 1 }}`)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:41:21.670",
"Id": "255067",
"ParentId": "255061",
"Score": "3"
}
},
{
"body": "<h2>Summary</h2>\n<p>Your resource management is broken.<br />\nYou have not implemented the rule of 3 or 5 and so you are going to leak and/or do double deletes. So let's concentrate on the Matrix part rather than resource management.</p>\n<p>You can replace your resource management with <code>std::vector<></code> for now. In the future you may want to replace that with your own memory management if you have something specific you want to try and achieve but <code>std::vector</code> should work fine for now.</p>\n<h2>Design Issues</h2>\n<ol>\n<li>Copies with no ownership semantics.</li>\n<li>Only Integers (not floats). You could template this to allow other types.</li>\n<li>Using methods were operators would be more logical.</li>\n<li>General resource management failures.</li>\n</ol>\n<h2>Code Review.</h2>\n<p>I don't see any use of <code>std::string</code> in the code!</p>\n<pre><code>#include <string>\n</code></pre>\n<hr />\n<p>Sure you could initialize from a C-array (pointer) but we don't know the size of the underlying array, so we can't check and make sure that our reads are valid.</p>\n<p>It is more traditional to use <code>Iterators</code> in C++ as we know where the end of the data is. Also it allows us to abstract the underlying container (it could be array/vector/list etc...)</p>\n<pre><code> Matrix(int m, int n, int* data) {\n</code></pre>\n<hr />\n<p>Normally you want to use the initializer list to set up member variables:</p>\n<pre><code> Matrix(int m, int n, int* data) {\n rows = m;\n columns = n;\n contents = new int[m*n];\n</code></pre>\n<p>I would have written like this:</p>\n<pre><code> Matrix(int m, int n, int* data)\n : rows{m}\n , columns{n}\n , contents{new int[m*n]}\n {\n</code></pre>\n<p>In this case it does not make a difference. <strong>BUT</strong> if the members are objects and have constructors your technique adds extra work (as you default construct then call the assignment operator). By using the initializer list you always initialize exactly once using the constructor.</p>\n<p>So the best practice is to prefer the initializer list.</p>\n<hr />\n<p>Sure you can use a loop.</p>\n<pre><code> for (int i = 0; i < m*n; i++) {\n contents[i] = data[i]; \n }\n</code></pre>\n<p>But we have standard algorithms for replacing simple loops like this:</p>\n<pre><code> std::copy(std::begin(data), std::end(data), std::begin(contents));\n</code></pre>\n<hr />\n<p>Sure.</p>\n<pre><code> int getElement(int i, int j) {\n return contents[columns*i + j];\n }\n</code></pre>\n<p>But you can overload <code>operator[]</code> or <code>operator()</code> to make the code read more naturally for matrix operations.</p>\n<p>This example reads more naturally to me:</p>\n<pre><code> Matrix m(2,3,data);\n std::cout << m[1][2] << "\\n";\n</code></pre>\n<hr />\n<p>You are returning a copy of the value here. Not a big deal for <code>int</code> as this is not expensive. But it would be nice to allow people to overwrite the member in the array:</p>\n<pre><code> m[1][2] = 3; // Write a value into the vector.\n</code></pre>\n<p>To achieve this you need to return reference to the values inside the matrix.</p>\n<pre><code> // translating to your API:\n int& getElement(int i, int j);\n ^^^^ Return value by reference.\n\n // Also add a const version to allow usage in a constant context.\n // i.e. when you pass the matrix by const reference\n\n int const& getElement(int i, int j) const; // return const ref\n // mark method const\n</code></pre>\n<hr />\n<p>This has some major issues</p>\n<pre><code> int* getRow(int i)\n</code></pre>\n<p>You are returning a dynamically allocated object here. This means you are returning ownership but pointers <code>int*</code> does not indicate ownership transfer so you are not sure if you are returning ownership.</p>\n<p>If you continued implementation in the same way you can indicate transfer of ownership using smart pointers.</p>\n<pre><code> std::unique_ptr<int[]> getRow(int i)\n</code></pre>\n<p>Now I know I am being given something I own and it will be auto cleaned up when I am finished using it.</p>\n<hr />\n<p>But having said that, this is probably not the best way to implement this as you are making a copy. Might be better to create an object that refers to the data in place.</p>\n<pre><code> class RefMatrix\n {\n Matrix& parent;\n int offset;\n int skip;\n public:\n Row(Matrix& parent, int offset, int skip)\n : parent(parent)\n , offset(offset)\n , skip(skip)\n {}\n int& operator[](int i) {\n return parent.data[offset + skip * i];\n }\n };\n RefMatrix getRow(int i) {return RefMatrix(*this, i , columns);}\n</code></pre>\n<p>This returns an object that accesses the raw data in place in the original matrix without having to dynamically create an object and without having to copy.</p>\n<hr />\n<p>Like access, you can override appropriate methods:</p>\n<pre><code> Matrix addition(Matrix other) {\n</code></pre>\n<p>I would implement <code>operator+</code> and <code>operator+=</code> to do this function.</p>\n<hr />\n<p>This is a bit inefficient. You allocate memory to calculate the result, then copy the data into the array which does another allocation.</p>\n<pre><code> int* sum = new int[rows*columns];\n \n for (int i = 0; i < rows*columns; i++) {\n sum[i] = contents[i] + other.contents[i]; \n }\n \n Matrix sumMatrix(rows, columns, sum);\n \n delete sum;\n</code></pre>\n<p>We can do this a lot more simply:</p>\n<pre><code> Matrix sumMatrix(rows, columns, data); // Make a copy.\n\n for (int i = 0; i < rows*columns; i++) { // Now add the data into it\n sumMatrix.data[i]+= other.contents[i]; \n }\n \n return sumMatrix;\n }\n</code></pre>\n<hr />\n<p>Sure:\nThough I would make the function const, as the function does not change the state of the object.</p>\n<pre><code> void print() { \n \n for (int i = 0; i < rows; i++) {\n std::cout << '{';\n for (int j = 0; j < columns; j++) {\n std::cout << getElement(i, j) << ", ";\n }\n std::cout << "}\\n";\n }\n \n }\n</code></pre>\n<p>I would also add an override for <code>operator<<</code> as this is the standard way to implement streaming in C++.</p>\n<pre><code> friend std::ostream& operator<<(std::ostream& str, Matrix const& data)\n {\n data.print(str); // would need to modify print to take a stream\n return str;\n }\n void print(std::ostream& str = std::cout) const; // this would work.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T20:40:02.207",
"Id": "503217",
"Score": "0",
"body": "@TobySpeight Typo. Meant `m[1][2]` Easy way to implement. https://stackoverflow.com/a/1971207/14065"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:42:01.000",
"Id": "503226",
"Score": "0",
"body": "I don't have a strong personal position, but there are many who argue for overloading `operator()(std::size_t, std::size_t)` rather than a proxy row object. I can't remember the specific arguments, but it might be worth mentioning that there are pros and cons on both sides? I think the real problem with row views is being clear about object lifetimes - but perhaps with increasing use of view types in modern C++, we're more used to awareness of that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:46:27.200",
"Id": "503227",
"Score": "0",
"body": "An alternative is to use a [Coordinate type](//stackoverflow.com/a/49968257/4850040) as index."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:39:17.787",
"Id": "255107",
"ParentId": "255061",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255067",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T18:54:46.833",
"Id": "255061",
"Score": "6",
"Tags": [
"c++",
"object-oriented"
],
"Title": "C++ matrix class"
}
|
255061
|
<p>I haven't separated the stack code into its own header and source yet, this is just a proof of concept for now. Haven't chosen better function names yet because I ultimately want to integrate this code into a larger project where I need a way to store data into some kind of dynamic list. Settled for an stack API for now, because of the simplicity.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct CodeGroup
{
char name[256];
struct GenericNode *codes;
};
struct Code
{
char code[8+1]; //each code is supposed to have 8 as max size. +1 for the null terminator
};
struct GenericNode
{
void *data;
struct GenericNode *next;
};
void GenericPush(struct GenericNode **list, void *data)
{
struct GenericNode *new = malloc(sizeof(struct GenericNode));
new->data = data;
new->next = NULL;
if(*list)
new->next = *list;
*list = new;
return;
}
struct GenericNode * GenericPop(struct GenericNode **list)
{
struct GenericNode *item = NULL;
if(*list)
{
item = *list;
*list = item->next;
}
return item;
}
void GenericFree(struct GenericNode *item)
{
if(item && item->data)
free(item->data);
free(item);
return;
}
struct CodeGroup *newGroup(char *name)
{
struct CodeGroup *new = malloc(sizeof(struct CodeGroup));
strcpy(new->name, name);
new->codes = NULL;
return new;
}
struct Code *newCode(char *code)
{
struct Code *new = malloc(sizeof(struct Code));
strcpy(new->code, code);
return new;
}
int main (int argc, char *argv[]) {
struct GenericNode *groupList = NULL;
struct GenericNode *item = NULL;
struct GenericNode *item2 = NULL;
struct CodeGroup *codeGroup = NULL;
struct Code *code = NULL;
/*
Data is structured as follows:
group list
|
\--- group
| \--- name
| \--- codes list
| \-- code
| \-- code
| ...
|
\--- group
| \--- name
| \--- codes list
| \-- code
| \-- code
| ...
|
...
*/
codeGroup = newGroup("group one");
GenericPush(&codeGroup->codes, (void*)newCode("10000001"));
GenericPush(&codeGroup->codes, (void*)newCode("10000002"));
GenericPush(&codeGroup->codes, (void*)newCode("10000003"));
GenericPush(&codeGroup->codes, (void*)newCode("10000004"));
GenericPush(&codeGroup->codes, (void*)newCode("10000005"));
GenericPush(&groupList, (void*)codeGroup);
codeGroup = newGroup("group two");
GenericPush(&codeGroup->codes, (void*)newCode("20000001"));
GenericPush(&codeGroup->codes, (void*)newCode("20000002"));
GenericPush(&codeGroup->codes, (void*)newCode("20000003"));
GenericPush(&codeGroup->codes, (void*)newCode("20000004"));
GenericPush(&codeGroup->codes, (void*)newCode("20000005"));
GenericPush(&groupList, (void*)codeGroup);
// prints all groups and its codes, also freeing them in the process:
while(item = GenericPop(&groupList))
{
codeGroup = (struct CodeGroup*)item->data;
printf("Group name: %s\n", codeGroup->name);
printf("\'%s\' codes:\n", codeGroup->name);
while(item2 = GenericPop(&codeGroup->codes))
{
code = (struct Code*)item2->data;
printf("%s\n", code->code);
GenericFree(item2);
}
GenericFree(item);
}
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>Group name: group two
'group two' codes:
20000005
20000004
20000003
20000002
20000001
Group name: group one
'group one' codes:
10000005
10000004
10000003
10000002
10000001
</code></pre>
<p>Looking for recommendations on how to improve, simplify or standardize this code, or tips on how to make it better overall.</p>
|
[] |
[
{
"body": "<p><strong>Good formatting</strong></p>\n<p><strong>Include.h?</strong></p>\n<p>A companion <code>Generic.h</code> with the public functions definitions is a common and good exercise.</p>\n<p><strong>Consider a function to test empty-ness</strong></p>\n<pre><code>bool GenericEmpty(const struct GenericNode *list);\n</code></pre>\n<p><strong>Consider a function to peek at the top data</strong></p>\n<pre><code>void *GenericPeek(const struct GenericNode *list);\n</code></pre>\n<p><strong>Consider a pop that also frees</strong></p>\n<pre><code>void *GenericPopData(struct GenericNode **list) {\n void *data = NULL;\n if (list && *list) {\n struct GenericNode *node = *list;\n *list = node->next;\n data = node->data;\n free(node);\n }\n return data;\n}\n</code></pre>\n<p><strong>Drop unneeded cast</strong></p>\n<pre><code>// GenericPush(&codeGroup->codes, (void*)newCode("10000001"));\nGenericPush(&codeGroup->codes, newCode("10000001"));\n\n// code = (struct Code*)item2->data;\ncode = item2->data;\n</code></pre>\n<p><strong>Allocate per the referenced data</strong></p>\n<p>The 2nd form is easier to code right, review and maintain.</p>\n<pre><code>// new = malloc(sizeof(struct GenericNode));\nnew = malloc(sizeof *new);\n</code></pre>\n<p><strong>Robust code checks allocations</strong></p>\n<pre><code>p = malloc(...);\nif (p == NULL) Handle_Error();\n</code></pre>\n<p><strong>Avoid overruns</strong></p>\n<pre><code>// Best way to detect potential overrun is very case dependent.\nif (strlen(name) >= sizeof new->name) Handle_error();\nelse strcpy(new->name, name);\n</code></pre>\n<p><strong>Unneeded test</strong></p>\n<p><code>free(NULL)</code> is OK.</p>\n<pre><code>// if(item && item->data)\nif(item)\n free(item->data);\n</code></pre>\n<p><strong>Keyword</strong></p>\n<p><code>_Generic</code> is a C keyword. Recommend a different common prefix. Maybe <code>CommonNode</code>?</p>\n<p>For me, I tend avoid C++ keywords in C like <code>new</code>, <a href=\"https://www.tutorialspoint.com/Cplusplus-Keywords\" rel=\"nofollow noreferrer\">others</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T12:51:31.527",
"Id": "503170",
"Score": "0",
"body": "Thank you, great tips! The pop that also frees is a great idea, I don't need the GenericFree() function if pop works that way. Regarding the function that checks for emptiness, can't I just check the list pointer? It will contain NULL if the list is empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:09:05.283",
"Id": "503185",
"Score": "0",
"body": "@liewl \"Regarding the function that checks for emptiness, can't I just check the list pointer? It will contain NULL if the list is empty\" --> Yes that is reasonable and idiomatic - if the calling code has awareness of that when `struct GenericNode * == NULL` (and _only_ then) that that means an empty list. To promote data hiding/abstraction, a `define` or `inline` `GenericEmpty()` could hide that `NULL` test. Perhaps at a later time, code returns a special pointer to indicate the list is invalid due to out-of-memory. Then the test is `list == NULL || list == special`. Your call."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T03:49:30.260",
"Id": "255075",
"ParentId": "255065",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:04:50.600",
"Id": "255065",
"Score": "0",
"Tags": [
"c",
"stack",
"pointers"
],
"Title": "Generic stack implementation in C"
}
|
255065
|
<p>I am analyzing videos from the popular social media platform, TikTok, and extracting the songs into a Spotify playlist. Here is a gif of one of these videos: <a href="https://i.imgur.com/I0dVoac.mp4" rel="nofollow noreferrer">https://i.imgur.com/I0dVoac.mp4</a>. Full video: <a href="https://vm.tiktok.com/ZMJwqpTPq" rel="nofollow noreferrer">https://vm.tiktok.com/ZMJwqpTPq</a></p>
<p><a href="https://i.stack.imgur.com/Re3vU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Re3vU.jpg" alt="enter image description here" /></a></p>
<p>Basically, after the video is downloaded, I get unique frames in 2 steps:</p>
<ol>
<li><p>Get frames with a play button in them.
<a href="https://i.stack.imgur.com/BwP4L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BwP4L.png" alt="enter image description here" /></a></p>
</li>
<li><p>Get frames where the difference with the previous frame is significant.</p>
</li>
</ol>
<p>My code thus far is:</p>
<pre><code>import cv2
from skimage.metrics import structural_similarity as ssim
import timeit
MATCHES = [
{
'img': cv2.imread('spotify_play.jpg', cv2.IMREAD_GRAYSCALE),
'name': 'spotify',
'bounds': [.8, .94]
},
{
'img': cv2.imread('apple_play_2.jpg', cv2.IMREAD_GRAYSCALE),
'name': 'apple',
'bounds': [.7, .82]
}
]
def time_method(func):
def wrapper(*args):
start = timeit.default_timer()
val = func(*args)
elapsed = timeit.default_timer() - start
print(f'Elapsed time of {func.__name__}:', elapsed)
return val
return wrapper
@time_method
def get_music_frames(file, matches, min_sim=0.5):
video = cv2.VideoCapture(file)
phase2 = []
types = []
y = None
while True:
ret,frame = video.read()
if ret:
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, threshed = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
for i, match in enumerate(matches):
matched_result = cv2.matchTemplate(match['img'], threshed , cv2.TM_SQDIFF_NORMED)
c,_,loc,_ = cv2.minMaxLoc(matched_result)
if c < min_sim:
if y is None:
y = loc[1]
phase2.append(frame[:y, :])
types.append(i)
break
else:
break
video.release()
if len(phase2) == 0:
return [], None
n = round(sum(types) / len(types))
best_match = matches[n]
m = best_match['bounds']
final = []
for my_frame in phase2:
height, _,_ = my_frame.shape
final.append(my_frame[int(height*m[0]):int(height*m[1]), :])
return final, best_match
@time_method
def remove_duplicate_frames(frames, max_sim=0.97):
pframe = frames[0]
non_duplicate_frames = []
for frame in frames[1:]:
sim = ssim(frame, pframe, multichannel=True)
if sim < max_sim:
gray_frame = cv2.cvtColor(pframe, cv2.COLOR_BGR2GRAY)
_, bw_frame = cv2.threshold(gray_frame, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
non_duplicate_frames.append(255 - bw_frame)
pframe = frame
return non_duplicate_frames
if __name__ == '__main__':
frames, best_type = get_music_frames('input.mp4', MATCHES)
if len(frames) == 0:
exit()
frames = remove_duplicate_frames(frames)
</code></pre>
<p>My code runs really slowly:</p>
<pre><code>retep@desktop:~/repos/tiktok-analyze-js$ python3 analyze.py
Elapsed time of get_binary_from: ...
Elapsed time of get_music_frames: 18.29
Elapsed time of remove_duplicate_frames: 2.16
Elapsed time of recognize_text_in_frames: ...
</code></pre>
<p>I am looking for some optimizations to lower the time to process below 20 seconds.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:09:59.593",
"Id": "503134",
"Score": "1",
"body": "Do you really need to write each frame to `'out.jpg'`? That sounds like you will be very dependent on disk IO, but overwrite it every loop iteration."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T22:47:37.053",
"Id": "255068",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"opencv"
],
"Title": "Python - Get Unique frames of video containing object"
}
|
255068
|
<p>I'm an amateur programmer making a career change into web development. I've found Advent of Code challenges are great way to sharpen my skills. I've cleaned up this solution for Day 10, 2020 as much as I know how.</p>
<p>Here's a link to the <a href="https://adventofcode.com/2020/day/10" rel="nofollow noreferrer">description</a> of the problem and my <a href="https://github.com/kmandrus/advent-of-code-2020.git" rel="nofollow noreferrer">solution</a> on GitHub. I've also summarized the problem and attached my code below.</p>
<p><strong>Part 1:</strong></p>
<p>Begin with a list of unique ordered integers, called "joltage adapters." Find the difference between each adjacent pair of integers, and count up how many differences of 1 and how many differences of 3 there are. What is the product of the differences of 1 and differences of 3?</p>
<p>For example, examine the adapter list [0, 3, 4, 5, 7, 10, 13]. There are 2 differences of 1 and 3 differences of 3, making the answer 6.</p>
<p><strong>Part 2:</strong></p>
<p>We can connect "joltage adapters" into chains if their difference is 3 or less. For example, 8 can connect to 7, 6, or 5, but not 4. A chain of valid connections might look like:</p>
<p>15 => 14 => 12 => 11 => 9 => 8 => 5 => 4 => 3 => 1 => 0</p>
<p>Here's the question: given a list of "joltage adapters," how many valid chains can we make? As a constraint, chains must start with the greatest adapter in the list and end with the smallest.</p>
<p>I'm simplifying a few things in this description (for example: we always add the "outlet" and the "device" to the list with values of 0 and the highest value plus three), but it hopefully will be enough to understand the code.</p>
<p>The answers for part 1 and part 2 are 2380 and 48358655787008. My solution for part 2 uses both memorization and recursion. I make regular use of hashes throughout.</p>
<p><strong>Here is my solution:</strong></p>
<pre><code>class Adapter_Array
def initialize(filepath)
@adapters = load_adapters(filepath)
end
def load_adapters(filepath)
adapters = File.readlines(filepath, chomp: true)
.map(&:to_i)
.sort
add_charger_and_device(adapters)
end
def add_charger_and_device(adapters)
adapters.dup
.unshift(0)
.push(adapters.last + 3)
end
def part_1_answer
jolt_differences[1] * jolt_differences[3]
end
def jolt_differences
return @count if @count
@count = Hash.new(0)
@adapters.each_with_index do |adapter, i|
next if is_charger?(adapter)
prev_adapter = @adapters[i-1]
@count[adapter - prev_adapter] += 1
end
@count
end
def part_2_answer
ways_to_reach_charger(@adapters.last)
end
def ways_to_reach_charger(adapter)
@memorized_ways = { 0 => 1 } unless @memorized_ways
return @memorized_ways[adapter] if @memorized_ways[adapter]
@memorized_ways[adapter] = lower_jolt_connections(adapter)
.sum { |connection| ways_to_reach_charger(connection) }
end
def lower_jolt_connections(adapter)
return [] if is_charger?(adapter)
connections = []
i = (to_index(adapter) - 1)
potential_connection = @adapters[i]
while valid_connection?(adapter, potential_connection) && i >= 0
connections << potential_connection
i -= 1
potential_connection = @adapters[i]
end
connections
end
def valid_connection?(adapter_1, adapter_2)
(adapter_1 - adapter_2).abs <= 3
end
def to_index(adapter)
return @adapter_to_index_hash[adapter] if @adapter_to_index_hash
@adapter_to_index_hash = Hash.new
@adapters.each_with_index do |an_adapter, i|
@adapter_to_index_hash[an_adapter] = i
end
@adapter_to_index_hash[adapter]
end
def is_charger?(adapter)
adapter.zero?
end
end
aa = Adapter_Array.new("input.txt")
puts aa.part_1_answer
puts aa.part_2_answer
</code></pre>
<p><strong>And here is my input:</strong></p>
<pre><code>153
69
163
123
89
4
135
9
124
74
141
132
75
3
18
134
84
15
61
91
90
98
99
51
131
166
127
77
106
50
22
70
43
28
41
160
44
117
66
60
76
17
138
105
97
161
116
49
104
169
71
100
16
54
168
42
57
103
1
32
110
48
12
143
112
82
25
81
148
133
144
118
80
63
156
88
47
115
36
2
94
128
35
62
109
29
40
19
37
122
142
167
7
147
121
159
87
83
111
162
150
8
149
</code></pre>
|
[] |
[
{
"body": "<p>Advent of Code is a good idea to improve your coding skills. Good luck with switching careers. Here are some improvements.</p>\n<h1>Snake_Case vs CamelCase</h1>\n<p>In Ruby, modules and classes use CamelCase. You class name should be <code>AdapterArray</code>. Speaking of that, the class name is also not very speaking, maybe you can come up with something more descriptive?</p>\n<h1>Loading file in class</h1>\n<p>I personally would not load the file in the class but outside and just pass in the array. The advantage of this is that you can write tests easier.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class AdapterArray\n attr_reader :filepath\n\n def initialize(adapter_list)\n @adapter_list = adapter_list.sort\n end\nend\n\nadapter_list = File.readlines(filepath, chomp: true).map(&:to_i)\nAdapterArray.new(adapter_list)\n\n# in your tests you can do now\nAdapterArray.new([10, 5, 1])\n</code></pre>\n<h1>Magic value</h1>\n<p>A magic value are unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants. In your code, e.g. the 1 and 3 are magic value you should give a name with extracting to a constant / method.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>CHARGER_VALUE = 0\n\ndef adapter_list_with_charger_and_device\n adapters.unshift(CHARGER_VALUE).push(device_value)\nend\n\ndef device_value\n adapter_list.last + 3\nend\n</code></pre>\n<p><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Magic_number_(programming)</a></p>\n<h1>JoltDifferences</h1>\n<p>Good idea to memoize this! I would maybe think about splitting it into two methods and use <code>||=</code> instead of the guard clause.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def jolt_differences\n @jolt_differences ||= fetch_jolt_differences\nend\n\ndef fetch_jolt_differences\n Hash.new(0).tap do |result|\n @adapters.each_with_index do |adapter, i|\n next if is_charger?(adapter)\n\n prev_adapter = @adapters[i-1]\n result[adapter - prev_adapter] += 1\n end\n end\nend\n</code></pre>\n<h1>Use attr_readers instead of instance variable</h1>\n<p>Instead of accessing the instance variables directly you should use attribute readers.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class AdapterArray\n attr_reader :adapter_list\n\n def my_method\n adapter_list # same as @adapter_list\n end\nend\n</code></pre>\n<p># to_index method\nYour <code>to_index</code> function can be simplified with a <code>group_by</code>. Also the name is not really reflecting what it does, I would name it something like <code>adapters_grouped_by_index</code>.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def adapters_grouped_by_index\n @adapters_grouped_by_index ||= adapters_with_charger_and_device.group_by.with_index { |_, i| i }\nend\n\nadapters_grouped_by_index[adapter]\n</code></pre>\n<h1>tap method</h1>\n<p>I often see you using a pattern where you have a result object and then return it at the end of the method.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def some_method\n connections = [] # e.g. connection\n\n # do something with connection\n # connection << 1\n\n connections\nend\n</code></pre>\n<p>You could replace this pattern with the tap method.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>[].tap |connections|\n connections << 1\nend\n</code></pre>\n<p><a href=\"https://medium.com/aviabird/ruby-tap-that-method-90c8a801fd6a\" rel=\"nofollow noreferrer\">https://medium.com/aviabird/ruby-tap-that-method-90c8a801fd6a</a></p>\n<h1>or equals</h1>\n<p>Instead of a conditional assignment you can use a <code>||=</code> (or equals)</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@memorized_ways = { 0 => 1 } unless @memorized_ways\n\n# vs\n\n@memorized_ways ||= { 0 => 1 }\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby\">https://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby</a></p>\n<h1>Convention memoization value</h1>\n<p>It is a convention that the variable holding a memoized value has the same name as the method, sometimes prefixed with an underscore.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def jolt_differences\n return @count if @count\n\n @count = Hash.new(0)\n @adapters.each_with_index do |adapter, i|\n next if is_charger?(adapter)\n prev_adapter = @adapters[i-1]\n @count[adapter - prev_adapter] += 1\n end\n @count\nend\n</code></pre>\n<p>This should really be <code>@jolt_differences</code> (or <code>@_jolt_differences</code>) instead of <code>@count</code>.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def jolt_differences\n return @jolt_differences if @count\n\n @jolt_differences = Hash.new(0)\n @adapters.each_with_index do |adapter, i|\n next if is_charger?(adapter)\n prev_adapter = @adapters[i-1]\n @jolt_differences[adapter - prev_adapter] += 1\n end\n @jolt_differences\nend\n</code></pre>\n<h1>private</h1>\n<p>Make all methods except <code>part_1_answer</code> and <code>part_2_answer</code> private as they should only accessed from inside the class.</p>\n<p>By the way, I would also think about better names for these methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:12:54.577",
"Id": "503264",
"Score": "0",
"body": "Thank you! These all help make the code more readable and easier to work with. The magic value tip has me quite excited - I've always liked code that avoids them, but I didn't have a name for it until now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:37:28.207",
"Id": "503334",
"Score": "0",
"body": "Added a few more suggestions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T14:34:14.397",
"Id": "503393",
"Score": "0",
"body": "Again, these comments are much appreciated! Many of your improvements were things I felt were off in my code, but I wasn't sure how to resolve. I'm particularly surprised I didn't learn about the yield statement and tap method in the bootcamp materials I've used, and I'll be putting them to good use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T15:09:45.917",
"Id": "503927",
"Score": "0",
"body": "If my answer was helpful, please consider accepting it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T09:29:04.447",
"Id": "255128",
"ParentId": "255071",
"Score": "2"
}
},
{
"body": "<p><strong>Problem 1</strong></p>\n<p>Often the key to getting a good solution is to find the right methods to use. For this problem there are two: <a href=\"https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-each_cons\" rel=\"nofollow noreferrer\">Enumerable#each_cons</a> and <a href=\"https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-tally\" rel=\"nofollow noreferrer\">Enumerable#tally</a><sup>1</sup>.</p>\n<pre><code>def product_of_freq_of_1_and_3(adapters) \n freq = adapters.each_cons(2).map { |x,y| y-x }.tally\n freq[1].to_i * freq[3].to_i\nend\n</code></pre>\n\n<pre><code>adapters = [0, 3, 4, 5, 7, 10, 13]\n</code></pre>\n\n<pre><code>product_of_freq_of_1_and_3 adapters\n #=> 6\nproduct_of_freq_of_1_and_3 [0, 1, 10, 20]\n #=> 0\nproduct_of_freq_of_1_and_3 [0, 1, 3, 4, 5, 6, 9, 10, 11, 14, 15]\n #=> 14\n</code></pre>\n<p>Note that if <code>freq</code> has no key <code>1</code>, <code>freq[1].to_i #=> nil.to_i => 0</code>. Same for the key <code>3</code>. See <a href=\"https://ruby-doc.org/core-2.7.0/NilClass.html#method-i-to_i\" rel=\"nofollow noreferrer\">NilClass#to_i</a>. One could alternatively write <code>freq.fetch(1, 0) * freq.fetch(3, 0)</code>. See <a href=\"https://ruby-doc.org/core-2.7.0/Hash.html#method-i-fetch\" rel=\"nofollow noreferrer\">Hash#fetch</a>.</p>\n<p>The steps are as follows.</p>\n<pre><code>enum = adapters.each_cons(2)\n #=> #<Enumerator: [0, 3, 4, 5, 7, 10, 13]:each_cons(2)>\n</code></pre>\n<p>We can see the values that will be generated by this enumerator and passed to <code>tally</code> by converting it to an array:</p>\n<pre><code>enum.to_a\n #=> [[0, 3], [3, 4], [4, 5], [5, 7], [7, 10], [10, 13]]\n</code></pre>\n<p>Continuing,</p>\n<pre><code>arr = enum.map { |x,y| y-x }\n #=> [3, 1, 1, 2, 3, 3]\nfreq = arr.tally\n #=> {3=>3, 1=>2, 2=>1}\nfreq[1].to_i * freq[3].to_i\n #=> 2 * 3 => 6\n</code></pre>\n<p>You'll see that I defined no classes, accessors or instance variables. This seems to be a standalone problem, so a single method using local variables would seem to suffice.</p>\n<p><strong>Problem 2</strong></p>\n<p>Suppose:</p>\n<pre><code>joltage_adapters = [23, 22, 20, 15, 14, 12, 8, 5, 4, 3, 1, 0]\n</code></pre>\n<p>I understand a <em>chain</em> of adapters is an array of the form</p>\n<pre><code>chain = joltage_adapters[i, n]\n</code></pre>\n<p>for some integer <code>n</code> that satisfies</p>\n<pre><code>2 <= n <= joltage_adapters.size\n</code></pre>\n<p>and some <code>i</code> that satisfies</p>\n<pre><code>0 <= i < joltage_adapters.size - n\n</code></pre>\n<p>and for all <code>j</code>, <code>i <= j < n</code>,</p>\n<pre><code>chain[j] - chain[j+1] <= 3\n</code></pre>\n<p>For example, three chains in <code>joltage_adapters</code> would be <code>joltage_adapters[0, 3] #=> [23, 22, 20]</code>, <code>joltage_adapters[3, 2] #=> [15, 14]</code> and <code>joltage_adapters[9, 3] #=> [3, 1, 0]</code>. <code>[12, 8, 5]</code> is not a chain because it does not satisfy the last condition above (<code>12 - 8 > 3</code>). Neither is <code>[8]</code> a chain because it does not have at least 2 elements.</p>\n<p>As a first step, let's use <a href=\"https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-slice_when\" rel=\"nofollow noreferrer\">Enumerable#slice_when</a> to partition the elements of <code>joltage_adapters</code> into groups:</p>\n<pre><code>adapter_groups = joltage_adapters.slice_when { |x,y| x - y > 3 }\n #=> #<Enumerator: #<Enumerator::Generator:0x00007fb736118f10>:each>\n</code></pre>\n<p>We can see the objects that will be generated by this enumerator by converting it to an array.</p>\n<pre><code>adapter_groups.to_a\n #=> [[23, 22, 20], [15, 14, 12], [8, 5, 4, 3, 1, 0]]\n</code></pre>\n<p>Chains can be constructed within each of these three arrays but no chain can begin in one array and continue on to the next, because the difference between the last element of one array (e.g., <code>20</code>) and the first element of the next (e.g., <code>15</code>) is always greater than <code>3</code>. Moreover, the number of chains that can be formed in each of the three arrays depends only on the size of the array. For example, it will be the same for <code>[8, 5, 4, 3, 1, 0]</code> as it would be for <code>[ 8, 7, 5, 4, 2, 0]</code>, because the difference between successive integers never more than <code>3</code>.</p>\n<p>For the array</p>\n<pre><code>arr = [5, 4, 3, 1, 0]\n</code></pre>\n<p>we can compute the number of chains recursively:</p>\n<ul>\n<li>0 chains in <code>[0]</code></li>\n<li>1 chain in <code>[1, 0]</code>:\n<ul>\n<li><code>[1, 0]</code></li>\n</ul>\n</li>\n<li>3 chains in <code>[3, 1, 0]</code>:\n<ul>\n<li><code>[3, 1]</code> + 0 chains in [0] (1) +</li>\n<li><code>[3, 1, 0]</code> (1) +</li>\n<li><code>[1, 0]</code> (<code>3</code> not in a chain) (1)</li>\n</ul>\n</li>\n<li>8 chains in <code>[4, 3, 1, 0]</code>:\n<ul>\n<li><code>[4, 3]</code> + 1 chain in <code>[1, 0]</code> (2) +</li>\n<li><code>[4, 3, 1]</code> + 0 chains in <code>[0]</code> (1) +</li>\n<li><code>[4, 3, 1, 0]</code> (1) +</li>\n<li><code>3</code> chains in <code>[3, 1, 0]</code> (<code>4</code> not in a chain) (3) +</li>\n<li><code>1</code> chain in <code>[1, 0]</code> (<code>4</code> and <code>3</code> not in a chain) (1)</li>\n</ul>\n</li>\n<li>20 chains in <code>[5, 4, 3, 1, 0]</code>:\n<ul>\n<li><code>[5, 4]</code> + 3 chains in <code>[3, 1, 0]</code> (4) +</li>\n<li><code>[5, 4, 3]</code> + 1 chain in <code>[1, 0]</code> (2) +</li>\n<li><code>[5, 4, 3, 1]</code> and 0 chains in <code>[0]</code> (1) +</li>\n<li><code>[5, 4, 3, 1, 0]</code> (1) +</li>\n<li>8 chains in <code>[4, 3, 1, 0]</code> (<code>5</code> not in a chain) (8) +</li>\n<li>3 chains in <code>[3, 1, 0]</code> (<code>5</code> and <code>4</code> not in a chain) (3) +</li>\n<li>1 chain in <code>[1, 0]</code> (<code>5</code>, <code>4</code> and <code>3</code> not in a chain) (1)</li>\n</ul>\n</li>\n</ul>\n<p>We can write a method to perform these calculation.</p>\n<pre><code>def nbr_chains(n)\n return 0 if n == 1\n return 1 if n == 2\n (n-3).downto(0)\n .each_with_object({ n=>0, n-1=>0, n-2=>1 }) do |i, nbr_from_index|\n nbr_from_index[i] =\n # chains beginning at index i\n ((i+1)..(n-1)).sum { |j| 1 + nbr_from_index[j+1] } +\n # chains beginning at index > i\n ((i+1)..(n-2)).sum { |j| nbr_from_index[j] }\n end[0]\nend\n</code></pre>\n\n<pre><code>nbr_chains([5, 4, 3, 1, 0].size)\n #=> 20 ({5=>0, 4=>0, 3=>1, 2=>3, 1=>8, 0=>20})\nnbr_chains([23, 22, 20].size)\n #=> 3 ({3=>0, 2=>0, 1=>1, 0=>3})\nnbr_chains([15, 14, 12].size)\n #=> 3 ({3=>0, 2=>0, 1=>1, 0=>3})\nnbr_chains([8, 5, 4, 3, 1, 0].size)\n #=> 49 ({6=>0, 5=>0, 4=>1, 3=>3, 2=>8, 1=>20, 0=>49})\n</code></pre>\n<p>The hashes shown above are the final values of <code>nbr_from_index</code> before the value of <code>0</code> is extracted.</p>\n<p>We therefore can count the number of chains with the following method.</p>\n<pre><code>def count_chains(joltage_adapters)\n joltage_adapters.slice_when { |x,y| x - y > 3 }\n .sum { |a| nbr_chains(a.size) }\nend\n</code></pre>\n \n<pre><code>count_chains(joltage_adapters) #=> 55\n</code></pre>\n<p><sup>1. <code>tally</code> made its debut in v2.7. To support earlier versions write <code>freq = adapters.each_cons(2).with_object(Hash.new(0)) { |(x,y),h| h[y-x] += 1 }</code>. See the form of <a href=\"https://ruby-doc.org/core-2.7.0/Hash.html#method-c-new\" rel=\"nofollow noreferrer\">Hash::new</a> that takes a single argument (the <em>default value</em>) and no block.</sup></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T04:26:03.580",
"Id": "255456",
"ParentId": "255071",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>I'm an amateur programmer making a career change into web development.</p>\n</blockquote>\n<p>Rather than give a detailed review of the existing code, I'll give you a succinct list of the advice I would have wanted to get at this stage, based on your code.</p>\n<ol>\n<li>Avoid unnecessary abstractions. In particular....</li>\n<li>Avoid unnecessary classes.</li>\n<li>Avoid unnecessary helper methods.</li>\n<li>Identify the essential algorithm, and strip away everything else to let that shine. In problem 1, it's just a map over differences. In problem 2, it's just a reduction of the sorted list.</li>\n</ol>\n\n<pre><code># Read in the data.\nd = DATA.readlines.map(&:to_i).sort.reverse\nd = [0] + d + [d.last + 3]\n\n# Part 1\ndiffs = d.each_cons(2).map { |a, b| a - b }\npart1 = diffs.count(1) * diffs.count(3)\n\n# Part 2\npart2 = d.reduce({}) do |m, x|\n cnt = (1..3).map { |i| m[x+i] || 0 }.sum\n m.update(x => cnt == 0 ? 1 : cnt )\nend.fetch(0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T07:20:34.887",
"Id": "265497",
"ParentId": "255071",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T01:47:05.260",
"Id": "255071",
"Score": "1",
"Tags": [
"ruby",
"recursion",
"memoization"
],
"Title": "Advent of Code 2020, Day 10 in Ruby"
}
|
255071
|
<p>I have the object with values. I trying to filter based on values.</p>
<pre><code>var data = {
"map": {
"0": ["abcd"],
"1": ["efgh"],
"2": ["xyz"],
}
}
</code></pre>
<p>In above object I am trying to filter xyz which are have in array values.</p>
<p>Expecting output:</p>
<pre><code> { '0': [ 'xyz' ] }
</code></pre>
<p>I done the code but I am not sure it's efficient way. Can someone help me this.</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>const data = {
"map": {
"0": ["abcd"],
"1": ["efgh"],
"2": ["xyz"],
"3": ["abcd", "xyz"],
}
}
const filtered = Object.keys(data.map)
.filter((key) => {
return data.map[key].includes('xyz');
})
.reduce((obj, key, cIndex) => {
obj[cIndex] = data.map[key];
return obj;
}, {});
console.log('filtered', filtered);</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T06:27:23.223",
"Id": "503127",
"Score": "0",
"body": "Should I assume the input will always be a dictionary whose keys are integers from `0` to `n`, and the order should also be kept in output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:20:58.553",
"Id": "503137",
"Score": "0",
"body": "yes. the output order always should start from 0"
}
] |
[
{
"body": "<h2>Avoid use dictionary when you need <code>Array</code></h2>\n<p>I'm not sure why you would prefer to store your Array-like data in a dictionary. I would suggest use a real Array if you need an Array.</p>\n<h2>Order of <code>Object.keys</code></h2>\n<p>You may read more details about the order of <code>Object.keys</code> return values from this post: <a href=\"https://stackoverflow.com/a/30919039/2045384\">Does ES6 introduce a well-defined order of enumeration for object properties?</a> The order of <code>Object.keys</code> is defined in ES2020. It may not work as you want in older environments.</p>\n<p>Anyway, relay on the order of <code>Object.keys</code> don't seems to be a good idea to me. You may always sort the keys after <code>Object.keys</code> if you want though.</p>\n<h2>Use <code>Object.assign</code> to convert to / from <code>Array</code></h2>\n<p>When you need an Array, use an Array. You can try <code>Object.assign</code> which convert your dictionary into Array and vice versa. (But this only applied to "when you cannot change the interface due to any reason").</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function filterData(data, value) {\n const arrayData = Object.assign([], data.map);\n const filteredArrayData = arrayData.filter(list => list.includes(value));\n const result = Object.assign({}, filteredArrayData);\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:44:23.457",
"Id": "503141",
"Score": "0",
"body": "Thanks for your response. When I add this in typescript I am getting error in includes.. Error details (Property 'includes' does not exist on type 'never'.ts(2339))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:53:44.367",
"Id": "503144",
"Score": "0",
"body": "@RSKMR Maybe you want to change your question to TypeScript?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:57:29.650",
"Id": "503148",
"Score": "0",
"body": "Thanks @tsh for contributing this great answer - I hope to see more from you in future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:13:55.293",
"Id": "503150",
"Score": "0",
"body": "@RSKMR TypeScript seems not smart enough to know types correctly. So [some internal variables may help](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAJgQygmBeGBvAUDGAiAWwQAc8AuTHXfABnJgG08EAjYOPAXQBorc8AjPSYBTAGYBzABZde1fACZheAB4BPAF6y++AMzLW7PN3zqtPKgF8s1rGICuYYFACW4GGJcAbKCIBOACJICAAUiMgUGDBExJGMANYiahRg9gQs-pwU0H4uYBIMnDCWxSYAbghe9iLZULn5AJSU8qCQsAh+fghqQREwOXkFnIVoMADyLABWIs4AdAgQEC4SYCGFJuEIszENANw6rdAe3r5+InAAgp3dvSjoHV09wbOePv4hXi5HqAB8MJ-QWZ5YBVOAiCAhCpVEQNPYHcBHM4Qew+OIMRLJGCpdKZWr1IbFUYTaZzBZLFYhDCWEyvU7nK6PW5w+RnKD2PxgGBIlFQfa2Q4gLwiWZeEASEK0-y3MLBEwAcjMcth+yAA)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T06:56:18.007",
"Id": "255080",
"ParentId": "255078",
"Score": "1"
}
},
{
"body": "<h2>Review</h2>\n<ul>\n<li>the whole filter chain could be on basis of <code>value</code> instead of <code>key</code> from <code>data</code> since there's no real use of key here</li>\n</ul>\n<h3><code>filter</code> part</h3>\n<ul>\n<li>technically your approach is perfect, just that it could be concise/readable</li>\n<li>you can simplify the <code>filter</code> as in below snippet, simply because readability is one of the TOP priority of a good code IMHO</li>\n</ul>\n<h3><code>map</code> part</h3>\n<ul>\n<li><p>instead of juggling the same <code>object</code> inside <code>reduce</code> between all elements we can simply get the required objects out of it.</p>\n</li>\n<li><p>one other major thing is that <code>reduce</code> as the name suggests is for when you wish to <em>reduce</em> <strong>N</strong> elements into exactly <strong>1</strong> element by some logic, which clearly isn't the case here & thus i think <code>map</code> should be preferred.</p>\n</li>\n<li><p>we can use <code>map</code> here since at the end we want an <code>array</code> of <code>object</code>s, so here we can return <code>object</code> for <strong>each</strong> key which at end gets <strong>collected as</strong> <code>array</code></p>\n</li>\n<li><p>apart from these the redability point again applies here as well, since this can also be simplified very much, refer the snippet to get an idea</p>\n</li>\n<li><p>quoting a point from Mozilla's doc on <code>reduce</code></p>\n</li>\n</ul>\n<blockquote>\n<p>The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.</p>\n</blockquote>\n<h2>Alternate approach</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = {\n \"map\": {\n \"0\": [\"abcd\"],\n \"1\": [\"efgh\"],\n \"2\": [\"xyz\"],\n \"3\": [\"abcd\", \"xyz\"],\n }\n}\n\nconst filtered = Object.values(data.map)\n .filter(value => value.includes('xyz'))\n // the () after the \"=>\" are used to wrap returned result into object\n // the [i] inside ({..}) is used for setting the key dynamically\n .map((value, i) => ({[i]: value}));\n \nconsole.log('filtered', filtered);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ul>\n<li>The data structure seems to be object representation of <code>array</code>, so if possible prefer <code>2D array</code> over <code>object</code> with 0 based keys, this would make things more simple</li>\n</ul>\n<p>PS: answer is updated after useful suggestions of @Toby Speight & @Graipher in comments</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:56:50.293",
"Id": "503147",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T11:00:12.413",
"Id": "503161",
"Score": "2",
"body": "@TobySpeight Well, there is some review here, it is just hidden in the comments in the code. This would be a lot better answer if you pulled it out of the comments and put it into text, Harsh Gundecha."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T11:07:23.757",
"Id": "503162",
"Score": "0",
"body": "I easily miss comments in the code; I too prefer descriptive text outside of the code block. That's easier to tell apart from a review focusing on the commenting of the code, for one thing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:28:06.810",
"Id": "255083",
"ParentId": "255078",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T05:56:00.097",
"Id": "255078",
"Score": "0",
"Tags": [
"javascript",
"object-oriented",
"mapreduce"
],
"Title": "Javascript + Filter object of values"
}
|
255078
|
<p>Like most teams, we take turns to speak in our daily stand-ups. When we gather around the sprint board, it's easy to know who speaks when - we start at one end and pass the role along the line.</p>
<p>At present, we're all working remotely, so there's no physical ordering that we would agree on. And we would get tired of using the same order every day, leading to diminished engagement. So we start the meeting by publishing the day's speaking sequence. I started with a random shuffle of the team members, but soon realised it would be better if any of us could generate the list, and we'd all get the same result. So I now use the date as a seed for shuffling.</p>
<p>I use a MD5 hash to quickly spread the entropy all around the random word (just using <code>date +%F</code> unmodified resulted in the same sequence every day, because all the variation is near the end), and <code>xxd</code> to convert its hexadecimal output into raw bytes.</p>
<pre><code>#!/bin/bash
set -eu -o pipefail
team=(Alice Bob Charlie Dan Erin Frank)
# Header for today
date +%A:%n
# Team members in today's order
printf '%s\n' "${team[@]}" |
shuf --random-source <(date +%F|md5sum|xxd -r -p)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:14:16.147",
"Id": "503135",
"Score": "1",
"body": "Obviously, this is the [cryptography team](https://en.wikipedia.org/wiki/Alice_and_Bob), not my day-job team."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:10:01.687",
"Id": "503224",
"Score": "2",
"body": "That's a good idea! I'll add this one to my collection of Python \"one-liners\". `python -c \"import sys;from datetime import date;import random;team=sys.argv[1:];random.seed(date.today().toordinal());random.shuffle(team);print(' '.join(team))\" Alice Bob Charlie Dan Erin Frank\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T08:24:46.730",
"Id": "503368",
"Score": "1",
"body": "@Eric, I like the Python approach, and it has some advantages. So [I ran with it](/a/255131/75307)!"
}
] |
[
{
"body": "<p>Some suggestions:</p>\n<ol>\n<li><code>#!/usr/bin/env bash</code> is a <a href=\"https://stackoverflow.com/a/10383546/96588\">more portable shebang line</a>.</li>\n<li>I would use long options for <code>set</code> and <code>xxd</code> for readability. So <code>set -o errexit -o nounset -o pipefail</code> and <code>xxd -revert -plain</code>.</li>\n<li>If you quote the array members you can easily use full names.</li>\n<li>In case any remote workers are in another time zone offset you'll want to use a fixed one, such as <code>TZ=Pacific/Auckland date +%F</code>. If you want to be on the safe side, get the time zone where your meeting time is midday at that offset (in the same hemisphere if possible, to avoid a 2 hour offset half of the year). That way, anyone running this code within 12 hours of the meeting time will get the same result.</li>\n<li>The output of <code>md5sum</code> is already completely scrambled. Passing it to <code>xxd</code> doesn't make the randomness input any more random. As mentioned in the comments it may be that <code>shuf</code> only uses a very small part of that randomness, in which case <code>xxd</code> is justified. Unfortunately <code>man shuf</code> doesn't go into any detail about <code>--random-source</code>.</li>\n<li>You can randomize arguments to <code>shuf</code>: <code>shuf --echo --random-source <(date +%F|md5sum|xxd -r -p) -- "${team[@]}"</code> achieves the same without <code>printf</code>.</li>\n<li><code>--random-source=<(…)</code> would make it obvious that it is a key/value pair rather than a flag followed by a file argument.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:11:10.637",
"Id": "503155",
"Score": "0",
"body": "Thanks. I had to use `xxd` because the `md5sum` output is only hex digits, so lots of the bits are unvarying (`shuf`) has a tendency to use very few bits from the random source. Point 6 is new to me - I overlooked that `shuf` can use arguments as input, so thanks greatly for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:12:00.850",
"Id": "503156",
"Score": "1",
"body": "I was worried there wouldn't be enough to review in such a short script - constantly amazed by the quality of contributors here! :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T16:30:03.603",
"Id": "503192",
"Score": "0",
"body": "I agree with most of this, but the `set` line is pretty idiomatic for bash strict mode. http://redsymbol.net/articles/unofficial-bash-strict-mode/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:08:11.563",
"Id": "503208",
"Score": "0",
"body": "@chicks For sure, I just deviate from idiomatic whenever I think it makes the code better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:22:27.407",
"Id": "503210",
"Score": "0",
"body": "Fair enough. I'm usually a fan of making the code self-explanatory, but in this case I usually just drop that link in a comment above the two lines of strict mode."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:06:29.383",
"Id": "255085",
"ParentId": "255082",
"Score": "9"
}
},
{
"body": "<h1>Consider using a different language</h1>\n<p>Prompted by a comment, I chose to re-implement in Python. This has a couple of advantages:</p>\n<ul>\n<li>No external dependencies (<code>xxd</code> isn't part of a default Debian or Ubuntu system)</li>\n<li>Perhaps portable to our peer teams using non-Linux platforms.</li>\n</ul>\n<p>I didn't do anything to ensure consistent time zone handling, because my team are all in the same time zone. Even if we share with the other teams, none of those straddle the date line during working hours, so not a concern for us. But suggestions welcome in the comments to this answer, if you have them!</p>\n<p>I was able to add a couple of features:</p>\n<ul>\n<li>We have guests who are not part of the development team, but often attend and have useful information to contribute. These people always speak after the core team, in a specific order.</li>\n<li>Attempt to copy to a clipboard, if we find one. This was previously done outside of the shuffle script itself, but doing it from Python increases our portability.</li>\n</ul>\n<p>Note: I considered storing the team list in a file to separate code from data, but preferred to keep everything in the source file as it's then easier to share amongst the team.</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python\n\nteam = "Alice, Bob, Charlie, Dan, Erin, Frank".split(', ')\nguests = "Eve, Mallory".split(', ')\n\nimport sys;\nimport datetime;\nimport random;\n\ntoday = datetime.date.today()\nrandom.seed(today.toordinal())\nrandom.shuffle(team)\n\noutput = (today.strftime('%A:%n%n') +\n '\\n'.join(team + guests))\n\nprint(output)\n\n# Save to clipboard if we can (for pasting into team chat)\ntry:\n import pyperclip\n pyperclip.copy(output)\nexcept:\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:38:37.420",
"Id": "503378",
"Score": "1",
"body": "It looks good. You can remove the semicolons at the end of imports. I didn't check if the distribution is fair to every team member. You could use a for loop for the next 1000 days, to check that every team member is equally distributed to each position."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T13:25:05.490",
"Id": "503477",
"Score": "0",
"body": "The semicolons are a remnant from unrolling your one-liner; I'll remove them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T12:21:01.567",
"Id": "255131",
"ParentId": "255082",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255085",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T07:09:50.600",
"Id": "255082",
"Score": "9",
"Tags": [
"bash",
"shuffle"
],
"Title": "Daily stand-up list"
}
|
255082
|
<p>I made a skyscraper solver based on the <a href="https://www.codewars.com/kata/5671d975d81d6c1c87000022/cpp" rel="nofollow noreferrer">kata</a> on Codewars.</p>
<p>To try to understand the problem you can try to solve a 4x4 Skyscraper <a href="https://www.brainbashers.com/showskyscraper.asp?date=0122&size=4&diff=1" rel="nofollow noreferrer">here</a>. There are also instructions available.</p>
<p>Now on Codewars there are also more difficult katas were you have to solve <a href="https://www.codewars.com/kata/5679d5a3f2272011d700000d" rel="nofollow noreferrer">6x6</a> or even <a href="https://www.codewars.com/kata/5917a2205ffc30ec3a0000a8" rel="nofollow noreferrer">7x7</a> Skyscraper puzzles.</p>
<p>Why are they more difficult? You run your code against a set of hidden unit tests on the site. If you cannot execute all the unit tests in an certain amount of time you don't pass.</p>
<p>I know that 6x6 and 7x7 take a lot more time to solve than 4x4. This is because the permutations of the numbers increase not linear. Just take a look at the permutations for one row of the board:</p>
<ul>
<li>4x4 -> 24</li>
<li>6x6 -> 720</li>
<li>7x7 -> 5040</li>
</ul>
<p>I already tried to optimize my code as much as possible for speed. I'd like to here your opinion what else can be improved for the speed.</p>
<p>Also let me know if the code is readable and has bad practices.</p>
<p>My goal is to make a fast but still readable solution.</p>
<p>Please don't let me know any approaches to solve 6x6 and 7x7 I want to find a way here myself.</p>
<p>One side note. On Codewars the interface for 4x4 is not defined in modern C++ way but with int* and int**. I cannot change that:</p>
<pre><code>int** SolvePuzzle (int *clues) {
// my code here
}
</code></pre>
<p>But I wrapped it using <code>std::array</code>.</p>
<p>Also everything is in one file. No <code>Cpp</code> / <code>h</code> separation which is also an restriction from Codewars. I only included a small h to be able to run my unit tests locally.</p>
<p>The code:</p>
<p><strong>skyscrapers.h</strong></p>
<pre><code>#ifndef SKYSCRAPER_H
#define SKYSCRAPER_H
int **SolvePuzzle(int *clues);
#endif
</code></pre>
<p><strong>skyscraper.cpp</strong></p>
<pre><code>#include "skyscrapers.h"
#include <algorithm>
#include <cassert>
#include <numeric>
#include <unordered_set>
#include <chrono>
#include <iostream>
class Nopes {
public:
Nopes(int size);
void insert(int value);
bool sizeReached() const;
int missingNumberInSequence() const;
bool contains(int value) const;
bool isEmpty() const;
// for debug print
std::unordered_set<int> values() const;
private:
int mSize;
std::unordered_set<int> mValues;
};
Nopes::Nopes(int size) : mSize{size}
{
assert(size > 0);
}
void Nopes::insert(int value)
{
assert(value >= 1 && value <= mSize + 1);
mValues.insert(value);
}
bool Nopes::sizeReached() const
{
return mValues.size() == static_cast<std::size_t>(mSize);
}
int Nopes::missingNumberInSequence() const
{
assert(sizeReached());
int n = mValues.size() + 1;
int projectedSum = (n + 1) * (n / 2);
int actualSum = std::accumulate(mValues.begin(), mValues.end(), 0);
return projectedSum - actualSum;
}
bool Nopes::contains(int value) const
{
auto it = mValues.find(value);
return it != mValues.end();
}
bool Nopes::isEmpty() const
{
return mValues.empty();
}
std::unordered_set<int> Nopes::values() const
{
return mValues;
}
struct Point {
int x;
int y;
};
enum class BorderPosition { top, right, bottom, left };
void nextDirection(BorderPosition &borderPosition)
{
if (borderPosition == BorderPosition::left) {
borderPosition = BorderPosition::top;
}
else {
int dir = static_cast<int>(borderPosition);
++dir;
borderPosition = static_cast<BorderPosition>(dir);
}
}
void advanceToNextPosition(Point &point, BorderPosition borderPosition,
int clueIdx)
{
if (clueIdx == 0) {
return;
}
switch (borderPosition) {
case BorderPosition::top:
++point.x;
break;
case BorderPosition::right:
++point.y;
break;
case BorderPosition::bottom:
--point.x;
break;
case BorderPosition::left:
--point.y;
break;
}
}
class BorderIterator {
public:
BorderIterator(std::size_t boardSize);
Point point() const;
BorderPosition borderPosition() const;
BorderIterator &operator++();
private:
int mIdx = 0;
std::size_t mBoardSize;
Point mPoint{0, 0};
BorderPosition mReadDirection{BorderPosition::top};
};
BorderIterator::BorderIterator(std::size_t boardSize) : mBoardSize{boardSize}
{
}
Point BorderIterator::point() const
{
return mPoint;
}
BorderPosition BorderIterator::borderPosition() const
{
return mReadDirection;
}
BorderIterator &BorderIterator::operator++()
{
++mIdx;
if (mIdx != 0 && mIdx % mBoardSize == 0) {
nextDirection(mReadDirection);
}
advanceToNextPosition(mPoint, mReadDirection, mIdx % mBoardSize);
return *this;
}
struct Board {
Board(int size);
std::array<std::array<int, 4>, 4> skyscrapers{};
std::array<std::array<Nopes, 4>, 4> nopes;
};
Board::Board(int size)
: nopes{{
{Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}},
{Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}},
{Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}},
{Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}, Nopes{size - 1}},
}}
{
}
class Slice {
public:
Slice(Board &board, const Point &startPoint, BorderPosition borderPosition,
int clue);
void insertSkyscraper(int skyscraper, std::size_t idx);
void insertNope(int nope, std::size_t idx);
int skyscraper(std::size_t idx) const;
Nopes nopes(std::size_t idx) const;
std::size_t size() const;
int clue() const;
bool isFull() const;
private:
void addSkyscraperAndNopesFromClue();
void addNopesAndSkyscrapersIfOneSkyscraperVisible();
void addNopesIfTwoSkyscrapersVisible();
void addNopesIfThreeSkyscrapersVisible();
void addSkyscrapersIfAllSkyscrapersVisible();
Point calcPosition(int idx) const;
Board &mBoard;
Point mStartPoint;
BorderPosition mDirection;
int mClue;
std::size_t mBoardSize;
mutable bool mIsfull{false};
};
Slice::Slice(Board &board, const Point &startPoint,
BorderPosition borderPosition, int clue)
: mBoard{board}, mStartPoint{startPoint}, mDirection{borderPosition},
mClue{clue}, mBoardSize{mBoard.skyscrapers.size()}
{
assert(mClue >= 0 && mClue <= static_cast<int>(mBoardSize));
if (mClue != 0) {
addSkyscraperAndNopesFromClue();
}
/*
Clue 1 and 4 cannot give us any more information so its not best to mark
them as not existing for the follow up algorithm iterating over the slices
*/
if (mClue != 2 && mClue != 3) {
mClue = 0;
}
}
void Slice::insertSkyscraper(int skyscraper, std::size_t idx)
{
Point p = calcPosition(idx);
mBoard.skyscrapers[p.y][p.x] = skyscraper;
}
void Slice::insertNope(int nope, std::size_t idx)
{
Point p = calcPosition(idx);
mBoard.nopes[p.y][p.x].insert(nope);
if (mBoard.nopes[p.y][p.x].sizeReached()) {
int missingSkyscraper =
mBoard.nopes[p.y][p.x].missingNumberInSequence();
insertSkyscraper(missingSkyscraper, idx);
}
}
int Slice::skyscraper(std::size_t idx) const
{
Point p = calcPosition(idx);
return mBoard.skyscrapers[p.y][p.x];
}
Nopes Slice::nopes(std::size_t idx) const
{
Point p = calcPosition(idx);
return mBoard.nopes[p.y][p.x];
}
std::size_t Slice::size() const
{
return mBoardSize;
}
int Slice::clue() const
{
return mClue;
}
bool Slice::isFull() const
{
if (mIsfull) {
return mIsfull;
}
for (std::size_t i = 0; i < size(); ++i) {
if (skyscraper(i) == 0) {
return false;
}
}
mIsfull = true;
return mIsfull;
}
void Slice::addSkyscraperAndNopesFromClue()
{
switch (mClue) {
case 1:
addNopesAndSkyscrapersIfOneSkyscraperVisible();
break;
case 2:
addNopesIfTwoSkyscrapersVisible();
break;
case 3:
addNopesIfThreeSkyscrapersVisible();
break;
case 4:
addSkyscrapersIfAllSkyscrapersVisible();
break;
default:
assert(false);
}
}
void Slice::addNopesAndSkyscrapersIfOneSkyscraperVisible()
{
insertSkyscraper(mBoardSize, 0);
for (std::size_t i = 1; i < size(); ++i) {
if (skyscraper(i) == 0) {
continue;
}
insertNope(mBoardSize, i);
}
}
void Slice::addNopesIfTwoSkyscrapersVisible()
{
if (skyscraper(0) == 0) {
insertNope(mBoardSize, 0);
}
if (skyscraper(1) == 0) {
insertNope(mBoardSize - 1, 1);
}
}
void Slice::addNopesIfThreeSkyscrapersVisible()
{
if (skyscraper(0) == 0) {
insertNope(mBoardSize - 1, 0);
insertNope(mBoardSize, 0);
}
if (skyscraper(1) == 0) {
insertNope(mBoardSize, 1);
}
}
void Slice::addSkyscrapersIfAllSkyscrapersVisible()
{
for (std::size_t i = 0; i < size(); ++i) {
insertSkyscraper(i + 1, i);
}
}
Point Slice::calcPosition(int idx) const
{
Point point = mStartPoint;
if (idx == 0) {
return mStartPoint;
}
switch (mDirection) {
case BorderPosition::top:
point.y += idx;
break;
case BorderPosition::right:
point.x -= idx;
break;
case BorderPosition::bottom:
point.y -= idx;
break;
case BorderPosition::left:
point.x += idx;
break;
}
return point;
}
void debug_print(Board &board, const std::string &title = "")
{
std::cout << title << '\n';
for (std::size_t y = 0; y < board.skyscrapers.size(); ++y) {
for (std::size_t x = 0; x < board.skyscrapers[y].size(); ++x) {
if (board.skyscrapers[y][x] != 0) {
std::cout << "V" << board.skyscrapers[y][x] << '\t';
}
else if (board.skyscrapers[y][x] == 0 &&
!board.nopes[y][x].isEmpty()) {
auto nopes_set = board.nopes[y][x].values();
std::vector<int> nopes(nopes_set.begin(), nopes_set.end());
std::sort(nopes.begin(), nopes.end());
for (std::size_t i = 0; i < nopes.size(); ++i) {
std::cout << nopes[i];
if (i == nopes.size() - 1) {
std::cout << '\t';
}
else {
std::cout << ',';
}
}
}
else {
std::cout << '\t';
}
}
std::cout << '\n';
}
std::cout << '\n';
}
void addMissingNopesFromKnownSkyscrapers(Slice &slice)
{
std::vector<int> skyscrapers;
skyscrapers.reserve(slice.size());
bool foundNope = false;
for (std::size_t i = 0; i < slice.size(); ++i) {
if (slice.skyscraper(i) != 0) {
skyscrapers.emplace_back(slice.skyscraper(i));
}
else if (!foundNope) {
foundNope = true;
}
}
if (!foundNope) {
return;
}
if (skyscrapers.empty()) {
return;
}
for (std::size_t i = 0; i < slice.size(); ++i) {
if (slice.skyscraper(i) == 0) {
for (const auto &skyscraper : skyscrapers) {
slice.insertNope(skyscraper, i);
if (slice.skyscraper(i) != 0) {
break;
}
}
}
}
}
void guessSkyscraperOutOfNeighbourNopes(Slice &slice, int skyscraper)
{
int idxWithNoSkyscaper = -1;
for (std::size_t i = 0; i < slice.size(); ++i) {
if (slice.skyscraper(i) != 0) {
if (slice.skyscraper(i) == skyscraper) {
return;
}
continue;
}
else if (slice.nopes(i).contains(skyscraper)) {
continue;
}
else { // existing node does not contain skyscaper
if (idxWithNoSkyscaper != -1) {
return;
}
idxWithNoSkyscaper = i;
}
}
if (idxWithNoSkyscaper != -1) {
slice.insertSkyscraper(skyscraper, idxWithNoSkyscaper);
}
}
void guessSkyscrapersOutOfNeighbourNopes(Slice &slice)
{
for (std::size_t i = 0; i < slice.size(); ++i) {
guessSkyscraperOutOfNeighbourNopes(slice, i + 1);
}
}
/*
requires:
clue = 3
3 4 x x | 3 -> 3 4 2 1 | 3
4 3 x x | 3 -> 4 3 1 2 | 3
*/
void guessSkyscrapersIfClueIsThreeAndLastTwoSkyscrapersKnown(Slice &slice)
{
if (slice.skyscraper(3) == 0 || slice.skyscraper(2) == 0) {
return;
}
if (slice.skyscraper(3) == 3 && slice.skyscraper(2) == 4) {
slice.insertSkyscraper(2, 1);
slice.insertSkyscraper(1, 0);
}
else if (slice.skyscraper(3) == 4 && slice.skyscraper(2) == 3) {
slice.insertSkyscraper(1, 1);
slice.insertSkyscraper(2, 0);
}
}
/*
requires
clue = 3
4 N3 X X | 3 -> 4 1 3 2 | 3
*/
void guessSkyscrapersIfClueIsThreeAndLastSkyscraperIsFourAndThirdNopeIsThree(
Slice &slice)
{
if (slice.skyscraper(3) != 4) {
return;
}
if (!slice.nopes(2).contains(3)) {
return;
}
slice.insertSkyscraper(1, 2);
slice.insertSkyscraper(3, 1);
slice.insertSkyscraper(2, 0);
}
/*
requires:
clue = 2
3 4 x x | 2 -> 3 4 1 2 | 2
*/
void guessSkyscrapersIfClueIsTwoAndLastTwoSkyscrapersKnown(Slice &slice)
{
if (slice.skyscraper(3) == 3 && slice.skyscraper(2) == 4) {
slice.insertSkyscraper(1, 1);
slice.insertSkyscraper(2, 0);
}
}
/*
requires:
clue = 2
4 x x x | 2 -> 4 x x 3 | 2
*/
void guessSkyscrapersIfClueIsTwoAndLastSkyscraperIsFour(Slice &slice)
{
if (slice.skyscraper(3) == 4) {
slice.insertSkyscraper(3, 0);
}
}
void guessSkyscrapersOneSkyscraperIsMissing(Slice &slice)
{
int missingValueIdx = -1;
std::vector<int> sequence;
sequence.reserve(slice.size() - 1);
for (std::size_t i = 0; i < slice.size(); ++i) {
if (slice.skyscraper(i) != 0) {
sequence.emplace_back(slice.skyscraper(i));
}
else {
if (missingValueIdx != -1) {
return;
}
missingValueIdx = i;
}
}
if (missingValueIdx != -1) {
int n = sequence.size() + 1;
int projectedSum = (n + 1) * (n / 2);
int actualSum = std::accumulate(sequence.begin(), sequence.end(), 0);
int missingValue = projectedSum - actualSum;
slice.insertSkyscraper(missingValue, missingValueIdx);
}
}
std::vector<Slice> makeSlicesWithClues(Board &board,
const std::array<int, 16> &clues)
{
BorderIterator borderIterator{board.skyscrapers.size()};
std::vector<Slice> slices;
slices.reserve(clues.size());
for (std::size_t i = 0; i < clues.size(); ++i, ++borderIterator) {
slices.emplace_back(Slice{board, borderIterator.point(),
borderIterator.borderPosition(), clues[i]});
}
return slices;
}
void guessSkyscrapersAndNopesFromClues(Slice &slice, int clue)
{
if (clue == 2) {
guessSkyscrapersIfClueIsTwoAndLastTwoSkyscrapersKnown(slice);
guessSkyscrapersIfClueIsTwoAndLastSkyscraperIsFour(slice);
}
else if (clue == 3) {
guessSkyscrapersIfClueIsThreeAndLastTwoSkyscrapersKnown(slice);
guessSkyscrapersIfClueIsThreeAndLastSkyscraperIsFourAndThirdNopeIsThree(
slice);
}
}
std::array<std::array<int, 4>, 4> SolvePuzzle(const std::array<int, 16> &clues)
{
Board board{4};
std::vector<Slice> slices = makeSlicesWithClues(board, clues);
for (;;) {
bool allFullFirst = true;
for (std::size_t i = 0; i < slices.size() / 2; ++i) {
if (slices[i].isFull()) {
continue;
}
allFullFirst = false;
addMissingNopesFromKnownSkyscrapers(slices[i]);
guessSkyscrapersOneSkyscraperIsMissing(slices[i]);
guessSkyscrapersOutOfNeighbourNopes(slices[i]);
if (slices[i].clue() == 0) {
continue;
}
addMissingNopesFromKnownSkyscrapers(slices[i]);
guessSkyscrapersAndNopesFromClues(slices[i], clues[i]);
}
if (allFullFirst) {
break;
}
bool allFullSecond = true;
for (std::size_t i = slices.size() / 2; i < slices.size(); ++i) {
if (slices[i].isFull()) {
continue;
}
allFullSecond = false;
if (slices[i].clue() == 0) {
continue;
}
addMissingNopesFromKnownSkyscrapers(slices[i]);
guessSkyscrapersAndNopesFromClues(slices[i], clues[i]);
}
if (allFullSecond) {
break;
}
}
return board.skyscrapers;
}
int **SolvePuzzle(int *clues)
{
auto t1 = std::chrono::high_resolution_clock::now();
std::array<int, 16> cluesArray;
for (std::size_t i = 0; i < 16; ++i) {
cluesArray[i] = clues[i];
}
auto resultArray = SolvePuzzle(cluesArray);
int count = resultArray.size();
int **result = new int *[count];
for (int i = 0; i < count; ++i) {
result[i] = new int[count];
}
for (int y = 0; y < count; ++y) {
for (int x = 0; x < count; ++x) {
result[y][x] = resultArray[y][x];
}
}
auto t2 = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << "duration:\t" << duration << '\n';
return result;
}
</code></pre>
<p>Tests:</p>
<p><strong>tst_skyscrapertest.h</strong></p>
<pre><code>#ifndef TST_SKYSCRAPERETEST_H
#define TST_SKYSCRAPERETEST_H
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include "../Skyscrapers/skyscrapers.h"
#include <array>
using namespace testing;
TEST(Skyscrapers, easy)
{
int clues[16] = {2, 2, 1, 3, 2, 2, 3, 1, 1, 2, 2, 3, 3, 2, 1, 3};
int expectedResult[4][4] = {
{1, 3, 4, 2}, {4, 2, 1, 3}, {3, 4, 2, 1}, {2, 1, 3, 4}};
auto result = SolvePuzzle(clues);
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(result[y][x], expectedResult[y][x]);
}
}
}
TEST(Skyscrapers, easy_2)
{
int clues[16] = {4, 2, 3, 1, 1, 3, 2, 2, 2, 2, 2, 1, 1, 2, 2, 3};
int expectedResult[4][4] = {
{1, 3, 2, 4}, {2, 4, 3, 1}, {3, 1, 4, 2}, {4, 2, 1, 3}};
auto result = SolvePuzzle(clues);
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(result[y][x], expectedResult[y][x]);
}
}
}
TEST(Skyscrapers, hard)
{
int clues[16] = {0, 0, 1, 2, 0, 2, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0};
int expectedResult[4][4] = {
{2, 1, 4, 3}, {3, 4, 1, 2}, {4, 2, 3, 1}, {1, 3, 2, 4}};
auto result = SolvePuzzle(clues);
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(result[y][x], expectedResult[y][x]);
}
}
}
TEST(Skyscrapers, hard_2)
{
int clues[16] = {0, 3, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0};
int expectedResult[4][4] = {
{1, 2, 3, 4}, {3, 1, 4, 2}, {4, 3, 2, 1}, {2, 4, 1, 3}};
auto result = SolvePuzzle(clues);
for (int y = 0; y < 4; ++y) {
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(result[y][x], expectedResult[y][x]);
}
}
}
#endif // TST_BLAINETEST_H
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "tst_skyscraperstest.h"
#include <gtest/gtest.h>
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:17:46.563",
"Id": "255087",
"Score": "1",
"Tags": [
"c++",
"performance"
],
"Title": "4x4 Skyscraper game solver"
}
|
255087
|
<p>I've built this NodeJS server architecture 5 years ago. The project was in production all this time, I've been maintaining it actively, adding a lot of new features, and had no troubles with this architecture. So, now I have a budget to refactor it fundamentally. I'm considering if I should keep this architecture or move to the common REST architecture.</p>
<p>The project consists of a mobile app, web app, admin panel (also a web app), and a NodeJS server.</p>
<p>All 3 client-side parts are using Redux under the hood with socket.io sending actions with <code>SOCKET/</code> prefix right to the server. The server accepts those actions and responds to them as many times as needed at any time.</p>
<p>I know where to improve the code, so, pls don't waste your time reviewing the code quality.</p>
<p>What I'm looking for is a review of this architecture. What are the downsides? Why I should use stateless REST instead of a stateful socket connection? Maybe it</p>
<p>I guess I'll omit the explanation of what are the pro-s of using this architecture for me, as it's not helpful in this context.</p>
<p>Probably, relevant info about this project:</p>
<ul>
<li>This is enterprise software that will never exceed 2-3 thousand active users.</li>
<li>Vast majority of actions do not require real-time capabilities and would work just fine with question-answer model.</li>
<li>At the moment we have ~600 active users and still using $24/month GCP instance.</li>
</ul>
<p>Here is the essence:</p>
<pre class="lang-javascript prettyprint-override"><code>import http from 'http'
import express from 'express'
import socketIo from 'socket.io'
import EventEmitter from './EventEmitter'
import actions from './actions'
const socket = async (server) => {
const io = socketIo(server)
const connectedUsers = new Map()
io.use(/*authorization middleware*/)
io.on('connection', async socket => {
const eventEmitter = new EventEmitter({ socket })
console.info(`=== v.${config.version} New connection ===`)
const sessionData = new Map()
sessionData.set('role', 'notLogedInUser')
sessionData.set('clientVersion', socket.authorizationData.clientVersion)
socket.emit('connected')
const emitAction = (actionType, actionPayload) => socket.emit('action', {
type: actionType,
payload: actionPayload
})
if (socket.authorizationData.authorized) {
const user = await db.users.findById(socket.authorizationData.userId)
sessionData.set('_id', user._id.toString())
// ...assigne other important user's props to sessionData
socket.on('action', async (action = {}) => {
const { type, payload } = action
if (!actions[type]) {
return emitAction('SNACK', 'Invalid action type')
}
actions[type]({
payload,
emitAction,
sessionData
})
})
} else {
emitAction('SNACK', 'Unauthorized')
}
socket.on('disconnect', () => {
console.info(`=== ${socket.id} has disconnected ===`)
connectedUsers.delete(socket.id)
})
})
}
let app = express()
app.server = https.createServer(app)
app.server.listen(config.port, '::', () => {
socket(app.server, config.port, config.hostname)
})
export default app
</code></pre>
<p>Thanks </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:32:56.480",
"Id": "255088",
"Score": "0",
"Tags": [
"node.js",
"socket",
"redux",
"state"
],
"Title": "What are the downsides of stateful socket NodeJS server comparing to a regular stateless REST server?"
}
|
255088
|
<p>I'm preparing for junior developer interviews and am trying to come up with a more interesting/versatile solution to FizzBuzz than I've done in the past. Do you have any ideas of how I might DRY this up? Is it too difficult to read?</p>
<pre><code>const isMultiple = (num, mod) => {
return num % mod == 0
}
const fizzBuzz = (range, array) => {
return [...Array(range)].fill('').map((el,i) => {
i ++
for (let element of array) {
isMultiple(i,element.number) && (el += element.name)
}
if (el == "") el = i
return el
});
}
const objArr = [
{
number: 3,
name: "Fizz"
},
{
number: 5,
name: "Buzz"
}
]
console.log(fizzBuzz(100,objArr))
</code></pre>
|
[] |
[
{
"body": "<p>Less lines is not always better.</p>\n<blockquote>\n<p>isMultiple(i,element.number) && (el += element.name)</p>\n</blockquote>\n<p>I've only seen this technique with minified or obfuscated code. Use an if statement as normal instead.</p>\n<p><code>array</code> is not a descriptive name. <code>objArr</code> is coupled with <code>fizzBuzz</code> anyways, I would remove this parameter and use the <code>objArr</code> directly.</p>\n<p>Use semicolons to designate end of statements</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:17:47.787",
"Id": "255094",
"ParentId": "255089",
"Score": "1"
}
},
{
"body": "<h1>Concept</h1>\n<p>Most people will consider this overengineered for actual fizz buzz. If you're going to demonstrate it, it is absolutely key that you preface it with "this is how I would solve the fizz buzz type problem in general". You don't want to give an interviewer the impression that you overengineer solutions to simple problems.</p>\n<h1>Code</h1>\n<p>You appear to be applying functional patterns, but only halfheartedly. Embracing these patterns can bypass the need for building up <code>el</code> entirely. Currying can also simplify usage of functions like <code>map()</code> and <code>filter()</code>.</p>\n<pre><code>const range = start => end =>\n [...Array(end-start+1)].map((_,i)=>i+start)\n\nconst divides = num => fizz =>\n num % fizz.number === 0\n\nconst fizzBuzzAt = fizzes => index =>\n fizzes.\n filter(divides(index)).\n map(fizz=>fizz.name).join('') || index;\n\nconst fizzBuzz = fizzes => n =>\n range(1)(n).map(fizzBuzzAt(fizzes))\n\nconst fizzes = [\n {number: 3, name: "Fizz"},\n {number: 5, name: "Buzz"},\n {number: 2, name: "Weee"}\n]\n\nconsole.log(fizzBuzz(fizzes)(100))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:37:40.317",
"Id": "255095",
"ParentId": "255089",
"Score": "0"
}
},
{
"body": "<h1>Question</h1>\n<blockquote>\n<p><em>Is it too difficult to read?</em></p>\n</blockquote>\n<p>I wouldn't say it is very difficult, though the callback function to <code>.map()</code> isn't consistently indented. Some commonly adopted style guides recommend a single space following commas<sup><a href=\"https://google.github.io/styleguide/jsguide.html#formatting-horizontal-whitespace\" rel=\"noreferrer\">1</a></sup> <sup><a href=\"https://github.com/airbnb/javascript#whitespace--comma-spacing\" rel=\"noreferrer\">2</a></sup> - e.g. instead of</p>\n<blockquote>\n<pre><code>isMultiple(i,number)\n</code></pre>\n</blockquote>\n<p>add a space to separate the arguments:</p>\n<pre><code>isMultiple(i, number)\n</code></pre>\n<h1>Other review points</h1>\n<h2>Equality comparisons</h2>\n<p>A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>). The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n<h2>Prefer <code>const</code> over <code>let</code></h2>\n<p>In the <code>for</code> loop <code>element</code> is declared with <code>let</code></p>\n<blockquote>\n<pre><code>for (let element of array) { \n isMultiple(i,element.number) && (el += element.name) \n}\n</code></pre>\n</blockquote>\n<p>It can be declared with <code>const</code> because it doesn't need to be re-assigned. Using <code>const</code> when re-assignment isn't needed is a good habit because it can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>consider destructuring assignment</h2>\n<p>Furthermore, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring\" rel=\"noreferrer\">object destructuring</a> can simplify the code so only the properties needed are pulled out of each element:</p>\n<pre><code>for (const {number, name} of array) { \n isMultiple(i, number) && (el += name) \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T16:32:26.097",
"Id": "255099",
"ParentId": "255089",
"Score": "5"
}
},
{
"body": "<p>I like how you implemented it, it just needs a little polishing.</p>\n<ul>\n<li>Be consistent with semicolon use, indentation, spacing, etc. (maybe grab a pre-configured linter like prettier or standard)</li>\n<li>When doing <code>[...Array(range)].fill('')</code>, you don't actually need to destructure the array to apply the <code>.fill()</code> afterward, in this particular case</li>\n<li>Try to shy away from modifying variables. i.e. instead of <code>i++</code> either do <code>const number = i + 1</code> or use <code>i + 1</code> everywhere.</li>\n<li>Variable naming could be improved.</li>\n<li>I see no reason to pass in the fizzes list - this game is generally not configurable.</li>\n</ul>\n<p>Here's a rewrite that follows these suggestions:</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 isMultiple = (num, mod) => num % mod === 0;\n\nconst substitutions = [\n {\n factor: 3,\n replacement: 'Fizz',\n },\n {\n factor: 5,\n replacement: 'Buzz',\n },\n];\n\nconst fizzBuzz = range => [...Array(range)]\n .map((_, i) => {\n const number = i + 1;\n let result = '';\n for (const { factor, replacement } of substitutions) {\n if (isMultiple(number, factor)) result += replacement;\n }\n return result || number;\n });\n\nconsole.log(fizzBuzz(100));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I'm going to go ahead and throw in an alternative, less-engineered solution too. As the rules for the game are set, and they're simple rules, I don't think there's any reason to extract them out into a list like that.</p>\n<p>The previous solution provides a degree of freedom if additional rules are added in a similar format (i.e. if its a multiple of 7, say baz), but will get in the way if the additional rules are not what you were predicting (i.e. baz is special in that if you say baz, you don't say fizz or buzz too). This is why it's good to avoid over-engineering solutions and keep them simple.</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 isMultiple = (num, mod) => num % mod === 0;\n\nconst getSubstitution = n => {\n if (isMultiple(n, 3) && isMultiple(n, 5)) return 'FizzBuzz';\n else if (isMultiple(n, 3)) return 'Fizz';\n else if (isMultiple(n, 5)) return 'Buzz';\n else return n;\n};\n\nconst fizzBuzz = length => [...Array(length)]\n .map((_, i) => getSubstitution(i + 1));\n\nconsole.log(fizzBuzz(100))</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-22T16:58:04.230",
"Id": "255100",
"ParentId": "255089",
"Score": "1"
}
},
{
"body": "<h2>Habits and syntax</h2>\n<p>When you are learning to write code you spend a lot of time chasing bugs. For a small project like fizzBizz there is not much that can go wrong. But as the code size increases the number of bugs do to.</p>\n<p>Bad habit result in bugs, the worst type of bugs "Hard to see bugs". They are hard to see because bad habits mean poor syntax does not jump out and say WRONG!</p>\n<p>Habits tend to stick so when learning anything new it is best to pick up the good rather than the bad habits.</p>\n<h2>Bad habits.</h2>\n<p><strong>Not using semicolons</strong></p>\n<p>or using them intermittently. JavaScript requires semicolons, if you don't add them yourself the parser will add them for you. It is called ASI <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> and it has some odd ways of resolving where to put the missing semicolon. ASI does not show you where it adds semicolons, so the most common way to find out how no semicolons stuff up your code is by spending hours trying to workout what is wrong with the code.</p>\n<p>Good JS uses semicolons, it is as simple as that.</p>\n<p><strong>Not using {} to delimit code blocks</strong></p>\n<p>eg you have <code>if (el == "") el = i</code>. Yes its not required to put <code>{}</code> around <code>{ el = i; }</code> But getting used to seeing blocks without them means its hard to spot when you extend a block and forget to add them.</p>\n<p><strong>Strict equality and inequality</strong>.</p>\n<p>The number of times you may need to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality\" rel=\"nofollow noreferrer\" title=\"Equality\"><code>==</code></a> (Equality) or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality\" rel=\"nofollow noreferrer\" title=\"Inequality\"><code>!=</code></a> (Inequality) is vanishingly small. Always use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\" title=\"Strict equality\"><code>===</code></a> (Strict equality) or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\" rel=\"nofollow noreferrer\" title=\"Strict inequality\"><code>!==</code></a> (Strict inequality)</p>\n<p>Why? The reasons are long and complicated. Strict equality, inequality, compares type and value, while the standard equality, inequality operators will try to convert (<a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion\" rel=\"nofollow noreferrer\">coercion</a>) one side of the operation to the same type as the other side then it will compare the values. The list of how types are coerced is long, and not always obvious.</p>\n<p><strong>Indentation</strong></p>\n<p>Your indentation is all over the place. Indentation helps you read the code, being lax or inconsistent using indentation make code a 1000 times harder to read.</p>\n<p>It does not matter what style of indentation 2 or 4 spaces 1 or 2 tabs. Don`t mix and match, Don't forget to indent when you need to and Don't indent when you shouldn't.</p>\n<p>All IDEs will auto indent for you, make sure that this is turned on when writing code. Also learn to use the code formatters (All IDEs have them)</p>\n<p><strong>Strict mode</strong></p>\n<p>Always run code in <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/strict_mode\" rel=\"nofollow noreferrer\">strict mode</a>.</p>\n<h2>Good Style</h2>\n<p>There are many styles, where you put spaces, how you start code blocks, where you break lines, do you prefer <code>if else</code>, or <code>switch</code>, or ternaries <code>?</code>, or short circuits. Coders will go blue in the face telling you which is best.</p>\n<p>Apart from the bad habits above what style you use does not really matter, what matters is that you be consistent. If you put a space between <code>for (</code> then do it every time.</p>\n<p>Inconsistent style makes code harder to read and harder to spot bugs in.</p>\n<h2>Code noise</h2>\n<p>Code noise is anything that is not required (with the exception of points in above bad habits). Less code noise takes less effort to read and maintain.</p>\n<p>All coders have a "bugs per line" quota. As you gain experience the greater the number of lines of code you can write without having to fix bugs.</p>\n<p>There have been many studies into this, and the reality is, for every programmer, fewer lines of code means fewer bugs.</p>\n<p>JavaScript has many syntax shortcuts. Learn them and reduce the noise. It takes time to reduce your bugs per line quota, but there are many ways to reduce the number of lines you write.</p>\n<p>Code lines are all lines that are not empty. Comments count as lines.</p>\n<h2>Rewrite</h2>\n<p>I am not going to show you a better way to write fizz - buzz (there is a zillion on google). The rewrite will use your logic and structure but without the bad habits, a few name changes, removal of some noise and a sprinkling of my personal style preferences.</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>\"use strict\";\n\nconst isMultiple = (val, mod) => val % mod === 0;\nconst RULES = [{mod: 3, name: \"Fizz\"}, {mod: 5, name: \"Buzz\"}];\n\nconst fizzBuzz = (range, rules) => \n Array(range).fill(\"\").map((str, val) => {\n for (const {mod, name} of rules) { isMultiple(val + 1, mod) && (str += name) }\n return str ? str : str + (val + 1);\n });\n\nconsole.log(fizzBuzz(100, RULES).join(\", \"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:35:02.530",
"Id": "503200",
"Score": "0",
"body": "If one really wanted to make `RULES` immutable then the value could be wrapped in a call to [`Object.freeze()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:44:36.880",
"Id": "503201",
"Score": "2",
"body": "@SᴀᴍOnᴇᴌᴀ that would require both objects in the array and the array to be frozen, `Object.freeze([{mod: 3, name: \"Fizz\"}, {mod: 5, name: \"Buzz\"}].map(Object.freeze));` and I did not want to explain that in such a simple bit of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T15:14:41.980",
"Id": "503273",
"Score": "0",
"body": "Some people prefer to read and write code without unnecessary semicolons, and let semicolons be inserted by the parser automatically. Plenty of JS projects have no unnecessary semicolons. Just to give a few examples: vercel/next.js, gatsbyjs/gatsby, lodash/lodash, twbs/bootstrap, vue/vue-router/vue-cli, typicode/husky, reduxjs/redux. Is it your experience, that you are spending hours trying to figure out the problem with your code if you don't write unnecessary semicolons? Would you say projects with no-semicolon style code suffer from this problem in a measurable way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:42:37.837",
"Id": "503279",
"Score": "0",
"body": "@Fee-fi-fo-fum Popular does not equate to good. Your questions Q1 I don't spend a second dealing with ASI, that is the very point of using them Q2 Projects that don't use them are the only projects that CAN have issues with ASI. Of 50 mainstream languages 78% use `;` and of that 75% require them. Most projects use several languages, if habit is to use semicolons transitioning between language's is much smoother. When you move from C++ to JS, does ; sneak into your code? Do you spend time removing them? I don't like ; no language should require them, untill that day its best to use them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:54:13.710",
"Id": "503299",
"Score": "0",
"body": "The examples only prove that it is accepted and common amongst professionals to write in either style. Q1: Your clam isn’t coming from personal experience then? Do you know studies that convinced you that not writing unnecessary semicolons causes said problems in any measurable way? Q2: The question is though, if you know mentioned projects suffer from said problem in any measurable way? I haven’t experienced any of the problems you mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T21:42:41.670",
"Id": "503328",
"Score": "0",
"body": "@Fee-fi-fo-fum Those projects are all open source? Lets get professional! starting at the top. Google JS style guide 5.11.13 Must use semicolons. They even give a reason *\"Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that.\"* Oh dear Google how rude (these mega companies think they own the world). Microsoft, Apple, Samsung, Oracle, W3C, even NASA. all say \"USE SEMICOLONS!\" Way down the bottom is humble me 20+ years of JS, about half my career, .well you know what I think..Before one of us goes blue in the face lets agree to disagree"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T15:22:15.517",
"Id": "503396",
"Score": "0",
"body": "If you check out the most recent google style guide, it no longer gives a justification for the \"Semicolons are required\" rule, so I don't think we can rely on the above quoted statement anymore. I like the google style guide by the way. I would always prefer using a linter to enforce whichever style guide a project or organization chooses. What I am questioning here is, whether each style is a matter of opinion, which I believe it is, or if in fact, one style is better than the other, which is what you are claiming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T17:48:05.070",
"Id": "503406",
"Score": "0",
"body": "@Fee-fi-fo-fum Link to quoted test from google https://google.github.io/styleguide/javascriptguide.xml#Semicolons The first line when you open the fold. I claim nothing, I use facts to give advice to those learning JS.. Dont develop bad habits"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:29:51.133",
"Id": "255103",
"ParentId": "255089",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255103",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T09:38:39.517",
"Id": "255089",
"Score": "1",
"Tags": [
"javascript",
"interview-questions",
"ecmascript-6",
"fizzbuzz"
],
"Title": "FizzBuzz solution"
}
|
255089
|
<p>I'm making a slide sidebar with vuejs and tailwind. It works but feels kind of sluggish. Is there a way to make it smoother ?</p>
<p>working example: <a href="https://codepen.io/tuturu1014/pen/oNzRXeW" rel="nofollow noreferrer">https://codepen.io/tuturu1014/pen/oNzRXeW</a></p>
<pre><code><button @click="isOpen = !isOpen" class="bg-blue-200 p-5">
<span v-if="isOpen">Open</span>
<span v-else>Close</span>
</button>
<div class="flex flex-row max-w-7xl mx-auto min-h-screen">
<transition name="slide">
<div class="flex flex-col w-64 shadow-xl sm:rounded-lg bg-blue-200" v-if="isOpen">
<div class="min-h-screen">sidebar</div>
</div>
</transition>
<div class="flex w-full min-h-screen bg-red-400">
content
</div>
</div>
<style>
.slide-enter-active {
animation: slideIn 1s ease;
}
.slide-leave-active {
animation: slideIn 1s ease reverse;
}
@keyframes slideIn {
0% {max-width: 0%;}
50% {max-width: 50%;}
100% {max-width: 100%}
}
<style>
</code></pre>
|
[] |
[
{
"body": "<p>You should use <code>transition</code> instead of <code>animation</code> and target the <code>width</code> property :</p>\n<pre><code> .slide-enter-active, .slide-leave-active {\n transition: width 1s;\n}\n.slide-enter, .slide-leave-to{\n width:0;\n}\n</code></pre>\n<p><strong><a href=\"https://codepen.io/boussadjra/pen/ExgzKyj\" rel=\"nofollow noreferrer\">LIVE DEMO</a></strong></p>\n<p>we could consider a transition as particular case of animation, the transition is applied when an element property changes (transition), but animation could be applied on any element infinitely or for some duration, you could watch the two first free videos on vue mastery that explain that clearly</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:38:12.297",
"Id": "255276",
"ParentId": "255092",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T13:27:35.407",
"Id": "255092",
"Score": "2",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Smooth sidebar toggle animation with vuejs and tailwind"
}
|
255092
|
<p>This is my take on the guess the number game. The user has three attempts to guess the number chosen at random. The number is between 0 and 9, including. It tells the user to guess higher or lower and reveals the number if the game is lost.</p>
<p>Input that is not a number between 0 and 9, including, is not accepted and the cursor will remain on the same line.</p>
<p>Green is for win and red is for retry.</p>
<p>I have tested the code and it works correctly. Please have a go.</p>
<p><code>guess_the_number.py</code></p>
<pre><code>"""The user has three attempts to guess what number was chosen at random"""
__all__ = []
import random
import string
from colorama import deinit, init
right_answer = random.choice(string.digits)
as_int = int(right_answer)
MSG_ANS = 'The answer was ' + right_answer
MSG_ASK = 'Guess the number (0-9) '
MSG_OK = '\033[92mCorrect!\033[0m'
MSG_TRY = '\033[91mTry again *\033[0m'
def ask(msg_wrong):
"""
One attempt
Non-digits are not accepted
Digits accepted are removed from the pool
and are not accepted in subsequent attempts
"""
global pool
cursor_up = '\033[A'
cursor_up_ask = cursor_up + ' '
while True:
answer = input(MSG_ASK)
if answer and answer in pool:
break
answer_sz = len(answer)
answer_sz = answer_sz * ' '
line = cursor_up_ask + answer_sz + cursor_up
print(line)
print()
print()
print(line, end='\r')
if answer == right_answer:
print(MSG_OK)
exit()
if msg_wrong == MSG_TRY:
i = int(answer)
if i > as_int:
hint = '>'
else:
hint = '<'
msg_wrong = msg_wrong.replace('*', hint)
print(msg_wrong)
pool = pool.replace(answer, '')
if __name__ == '__main__':
pool = string.digits
init()
ask(MSG_TRY)
ask(MSG_TRY)
ask(MSG_ANS)
deinit()
</code></pre>
|
[] |
[
{
"body": "<p>Your code does work, nice try :)</p>\n<p>It's an interesting exercise. If you are open to another way of approaching the game, here's what I'd suggest:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nimport string\n\ndef possible_answers() -> list:\n #['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n return [char for char in string.digits]\n\ndef generate_answer() -> str:\n return random.choice(possible_answers())\n\ndef ask_for_input() -> str:\n print('Your guess > ', end='')\n return input()\n\ndef new_game(max_attempts: int):\n correct_answer = generate_answer()\n attempts = []\n print('Welcome to the new round :) ')\n while len(attempts) < max_attempts:\n attempt = ask_for_input()\n if attempt == correct_answer:\n print('Bingo')\n break\n elif attempt not in possible_answers():\n print(f'Invalid input, possible answers: {possible_answers()}')\n elif attempt in attempts:\n print('You already guessed that one, my friend. Try something new :)')\n else:\n attempts += [attempt]\n print('Please try again, best of luck with the next attempt :)')\n \n\nif __name__ == '__main__':\n while True:\n new_game(max_attempts = 3)\n</code></pre>\n<ul>\n<li><p>We are creating a new game after the previous game ends.</p>\n</li>\n<li><p>In Each game we:</p>\n<ul>\n<li><p>accept a <code>max_attempts</code> as the game configuration</p>\n</li>\n<li><p>generate a random correct answer</p>\n</li>\n<li><p>accept attempts and act on the attempts accordingly</p>\n</li>\n</ul>\n</li>\n<li><p>You can easily change the random set by changing the <code>possible_answers()</code> method</p>\n</li>\n<li><p>I'm ignoring output formatting here, but it can be easily added in the <code>new_game()</code> method.</p>\n</li>\n</ul>\n<p>If you don't mind doing a bit of reading, <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> is something that's worth exploring. Hope you enjoy the reading and keep up the good work :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T10:38:36.093",
"Id": "503252",
"Score": "1",
"body": "Am really considering downvoting this answer. You are providing an alternative code but without a reason why the said code is better than OP's code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:37:00.570",
"Id": "255119",
"ParentId": "255096",
"Score": "-1"
}
},
{
"body": "<p><strong>Positives</strong></p>\n<ul>\n<li>Your function docstring was informative and helped me understand the code better.</li>\n<li>Good use of variables like <code>cursor_up</code> to manage the ANSI control characters</li>\n</ul>\n<p><strong>Small improvements</strong></p>\n<ul>\n<li>As long as you're bringin in colorama, can you use any of the named constants in provides instead of the control characters?</li>\n<li>If you need to do something multiple times, I like to see if there's a good way to do <code>n</code> times instead. See if you can make the number of turns more configurable.</li>\n<li>I'm not sure what you're doing with <code>line = cursor_up_ask + answer_sz + cursor_up</code>. This would be a good place for a comment or a function with a clear name.</li>\n<li>You're taking <code>len(answer)</code>, but shouldn't that always be 1? My understanding is that you're expecting a one-digit answer. It would be nice to have some error handling so that, e.g. <code>23</code> isn't treated as a valid guess.</li>\n<li>You could eliminate the <code>pool</code> global by wrapping it and your functions together in a class. You could also eliminate the global by having more focused functions.</li>\n<li>Instead of doing a find-replace on the <code>*</code> in <code>MSG_TRY</code>, you can do something like this:</li>\n</ul>\n<pre><code>MSG_TRY = '\\033[91mTry again {}\\033[0m'\nmsg_wrong = msg_wrong.format(hint)\n</code></pre>\n<p><strong>Larger gripes</strong></p>\n<ul>\n<li>I'm finding the flow of the program hard to follow. Consider breaking it down into smaller functions so it's more clear what's going on. It could look something like:</li>\n</ul>\n<pre><code>def play_one_turn(final_turn = False):\n guess = get_player_input()\n if guess == right_answer:\n print(OK_MSG)\n return True\n if not final_turn:\n show_hint(guess)\n else:\n print(MSG_ANS)\n</code></pre>\n<p>(I'm not saying this is the best way to do things. It's showing how smaller well-named functions can give more clarity with the same structure)</p>\n<ul>\n<li><code>exit()</code> in the middle of a function is suspicious. (Is the code missing <code>from sys import exit</code>?) I'd expect to see it at the end of a main function to return a status code back to the user. It should not be used for control flow. It would make more sense to return <code>True</code> or <code>False</code> depending on whether the guess is correct, and let the caller manage things from there.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:08:58.043",
"Id": "255150",
"ParentId": "255096",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T14:49:16.867",
"Id": "255096",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"number-guessing-game"
],
"Title": "python Guess The Number"
}
|
255096
|
<p>Hello everyone this is my first post here so please do critique my post if there's anything.</p>
<p>I have made a program intended to pass a programming challenge on open.kattis.com, <a href="https://open.kattis.com/problems/knightjump" rel="nofollow noreferrer">here</a>.
It should do as title says, but with the conditions that each traversal follows the rules of a "Knight" from chess, that being plus/minus two columns/rows and plus/minus one column/row.</p>
<ol>
<li><p>_read method:
I attempted to solve this making a Node class and passing coordinate and char data into each instance of a Node object for each coordinate.</p>
</li>
<li><p>_adjacencify method:
Thereafter, I found adjacencies (neighbours) of all Node objects, with the aforementioned condition of a chess Knight.</p>
</li>
<li><p>_jump method:
Lastly, I used a BFS implementation in order to find the shortest path from the source (root) to the terminal (here represented as 'K').</p>
</li>
<li><p>find_path:
Wraps everything up.</p>
</li>
</ol>
<p>Here's the code I ended up with:</p>
<pre><code>class Nite
#attr_accessor :char, :col, :row
class Node
attr_accessor :char, :col, :row, :disc, :parent
attr_reader :adjies
def initialize(char, col, row)
@char = char
@col = col
@row = row
@adjies = [] # adjacencies
@disc = false
@parent = nil
end
def add(value)
@adjies << value
end
end
def _read
# assign each coord. to a Node-object
n = gets.to_i
nodes = Array.new
n.times do |x|
temp = gets.strip.to_s
temp.size.times do |y|
node = Node.new(temp[y], x, y)
nodes << node
end
end
nodes
end
def _adjacencify(nodes)
nodes.each do |x|
nodes.each do |y|
if y.col == x.col && y.row == x.row || y.char == '#'
next
end
# logic
if x.row == (y.row - 1) # y.row + 1
if x.col == (y.col - 2) # y.col + 2
x.add(y) # (col+2, row+1)
elsif x.col == (y.col + 2) # y.col - 2
x.add(y) # (col-2, row+1)
end
elsif x.row == (y.row + 1) # y.row - 1
if x.col == (y.col - 2) # y.col + 2
x.add(y) # (col+2, row-1)
elsif x.col == (y.col + 2) # y.col - 2)
x.add(y) # (col-2, row-1)
end
end
if x.row == (y.row - 2) # y.row + 2
if x.col == (y.col - 1) # y.col + 1
x.add(y) # (col+1, row+2)
elsif x.col == (y.col + 1) # y.col - 1
x.add(y) # (col-1, row+2)
end
elsif x.row == (y.row + 2) # y.row - 2
if x.col == (y.col - 1) # y.col + 1
x.add(y) # (col+1, row-2)
elsif x.col == (y.col + 1) # y.col - 1
x.add(y) # (col-1, row-2)
end
end
end
end
nodes
end
def _jump(nodes)
nodes = _adjacencify(nodes)
q = Queue.new
root = nodes[0]
root.disc = true
q << root
while !q.empty? do
v = q.pop
if v.char == 'K'
steps = 0
until v.parent == nil do
if !v.nil?
end
steps += 1
v.parent = v.parent.parent
end
return steps
end
v.adjies.each do |w|
if w.disc == false
w.parent = v
w.disc = true
q << w
end
end
end
return -1
end
def find_path
_jump(_read)
end
end
nite = Nite.new
puts nite.find_path
</code></pre>
<p>I suspect of course that the _adjacencify method is super time consuming, and that some loops are way too time consuming.
I failed the <1.00s time requirement in order to pass the challenge.</p>
<p>I want <strong>all</strong> types of criticism on my code, and I want tips and also, if anyone wants, different implementations that perform better.
Especially Ruby convention is something I want critique on, considering I am coming from a Java and Python background and I'm fairly fresh in Ruby.</p>
<p>Please tell me if I should edit anything in this post to make anything clearer.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T03:12:21.837",
"Id": "503638",
"Score": "2",
"body": "Welcome, and very good post."
}
] |
[
{
"body": "<p>and welcome!</p>\n<h1>Things I really like</h1>\n<ul>\n<li>Using standard Ruby indention (2 spaces)</li>\n<li>Using the attr_accessor and attr_reader helpers instead of hand-rolling these methods</li>\n<li>Using <code>n.times do</code> to loop.</li>\n<li>Using <code>next</code> at the top of a loop body instead of a nested if</li>\n<li>Short, focused methods</li>\n<li>Great use of functional decomposition (goes along with the focused methods)</li>\n</ul>\n<p>There's a lot of nit-picky things to follow, so don't be discouraged. Many of these things are minor, and I'm mostly pointing out Ruby idioms or practices you have no way to know yet. Due to time constraints, I am not going to address the algorithm itself, nor look for any major improvements. I will mostly point out the things that catch my eye as a Ruby programmer.</p>\n<h1>Naming things</h1>\n<pre><code> def _read\n # assign each coord. to a Node-object\n</code></pre>\n<p>Does the comment indicate that "read" could use a better name?</p>\n<pre><code> nodes.each do |x|\n nodes.each do |y|\n</code></pre>\n<p><code>x</code> and <code>y</code> are frequently used as coordinate names for a Cartesian grid, which a chessboard is. Here, <code>x</code> and <code>y</code> are nodes, not coordinates. Better names would be <code>a</code> and <code>b</code>, or perhaps <code>origin</code> and <code>destination</code>.</p>\n<pre><code>@adjies = [] # adjacencies\n</code></pre>\n<p>Probably just name the variable <code>@adjacencies</code> so you can lose the comment, and the code will be clearer throughout. Someone reading the code who hasn't seen this comment yet will be confused.</p>\n<h1>Formatting</h1>\n<pre><code> end\n def add(value)\n @adjies << value\n end\n end\n</code></pre>\n<p>Standard Ruby formatting separates methods with a blank line. I also prefer a blank line between a method and the end of the class:</p>\n<pre><code> end\n\n def add(value)\n @adjies << value\n end\n\n end\n</code></pre>\n<p>but the more common practice is to have no blank line after the last method in a class:</p>\n<pre><code> end\n\n def add(value)\n @adjies << value\n end\n end\n</code></pre>\n<h1>Idiomatic private methods in Ruby</h1>\n<pre><code>def _jump(nodes)\n</code></pre>\n<p>Standard Ruby does not use the underscore conversion for private methods. Instead, private methods can follow the <code>private</code> keyword:</p>\n<pre><code>\nprivate\n\ndef jump(nodes)\n</code></pre>\n<p>Note that all methods that follow "private" will be private, so you don't have to use it before every private method. Standard Ruby practice is to just give the "private" keyword once, and then follow that with all of the private methods.</p>\n<h1>Omit the "return" keyword in the last expression in a method.</h1>\n<pre><code> return -1\n</code></pre>\n<p>The result of a Ruby method is the value of the last expression in the method. So unless returning early, we usually omit the "return" keyword when it's on the last line:</p>\n<pre><code> -1\n</code></pre>\n<p>You omit the "return" keyword elsewhere, so I assume this is just an oversight.</p>\n<h1>Don't compare to <code>true</code> or <code>false</code></h1>\n<pre><code>if w.disc == false\n</code></pre>\n<p>In Ruby, <code>true</code> and <code>false</code> are a little different than in Java. Ruby considers anything that is either <code>nil</code> or <code>false</code> to be "falsey", and everything else is "truthy". Therefore, it is bad practice to compare a value with <code>false</code>, since this comparison will fail if the value is actually nil.</p>\n<p>So instead of comparing with false, do this:</p>\n<pre><code>if !w.disc\n</code></pre>\n<p>But even better, Ruby has a negating form of "if" called "unless". Idiomatic Ruby would be:</p>\n<pre><code>unless w.disc\n</code></pre>\n<h1>Getting the first element of an array or enumeration</h1>\n<pre><code>root = nodes[0]\n</code></pre>\n<p>This is fine, but this also works:</p>\n<pre><code>root = nodes.first\n</code></pre>\n<p>Ruby likes you to have multiple ways to do a thing, a philosophical shift from Python.</p>\n<h1>Redundant #to_s</h1>\n<pre><code> temp = gets.strip.to_s\n</code></pre>\n<p>The result of String#strip is a String, so there's no need for <code>.to_s</code> here.</p>\n<h1>Use Array instead of Queue (for this application)</h1>\n<pre><code>q = Queue.new\n</code></pre>\n<p>Queue is intended for multi-threaded applications; it includes locking to prevent race conditions. For a single-threaded application, you can and should just use Array. The minor reason is performance (avoid the locking). The major reason is communication: A Ruby programmer seeing Queue is going to start looking for the threading in your program.</p>\n<p>Since the methods you are calling on <code>q</code> (<code><<</code> and <code>pop</code>) are also implement on Array and have the same meaning, you can do this instead:</p>\n<pre><code>q = []\n</code></pre>\n<h1>Create empty arrays with <code>[]</code></h1>\n<pre><code>nodes = Array.new\n</code></pre>\n<p>There's nothing wrong with this, but you will more often see a new, empty array created using the array literal syntax:</p>\n<pre><code>nodes = []\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:41:45.770",
"Id": "503647",
"Score": "0",
"body": "\"Instead, private methods can follow the `private` keyword\" – [`Module#private`](https://ruby-doc.org/core/Module.html#method-i-private) is a bog-standard method, not a keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:53:32.330",
"Id": "503684",
"Score": "0",
"body": "This is really good feedback. I thought that I could save some space and indicate the nested class better by omitting white space, but I understand that I should follow convention there. Regarding 'private', should I keep all private methods at the end of the class, so that all methods above 'private' are considered public?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:08:22.350",
"Id": "503688",
"Score": "0",
"body": "@martyro Thank you, I'm glad this is helpful to you. Yes, putting all private methods at the end of the class it the usual practice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:13:33.217",
"Id": "503690",
"Score": "0",
"body": "@JörgWMittag I considered making that distinction, but then thought it might be better to gloss over that detail since it's not really important to someone learning Ruby basics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T22:03:23.290",
"Id": "503946",
"Score": "0",
"body": "Excellent answer, in part because your points are so well-written."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T03:36:49.443",
"Id": "255268",
"ParentId": "255098",
"Score": "3"
}
},
{
"body": "<p><strong>The problem</strong></p>\n<p>We are given an NxN chessboard with one cell designated as the <em>origin</em> and all others being <em>open</em> or <em>blocked</em>. One of the open cells is designated as the <em>destination</em>. If a knight begins at the origin, we wish to find the smallest number of moves among empty cells required for it to reach the destination.</p>\n<p>Specifically, we are be given an array <code>board</code> containing <code>n</code> elements, with each element being an array of <code>n</code> elements. The destination is the cell <code>[0, 0]</code>. For each pair of indices <code>i</code>, <code>0 <= i < N</code> and <code>j</code>, <code>0 <= j < N</code>, <code>board[i][j]</code> equals:</p>\n<ul>\n<li><code>'.'</code> if the cell is open;</li>\n<li><code>'#'</code> if the cell is blocked; and</li>\n<li><code>'K'</code> if the cell is the origin.</li>\n</ul>\n<p>We wish to determine if there is a path of valid knight moves among open squares from the origin to the destination, and if there is at least one, find the shortest, the length of each path being the number board locations on the path, excluding the origin. Paths are expressed as arrays of board corrdinates, each coordinate being a 2-element array containining a row and column index.</p>\n<p>The problem states that row and column indices are 1-based, but I will make them 0-based for convenience. If desired one could easily convert the indices to 1-based after an optimal path has been found.</p>\n<p><strong>Example</strong></p>\n<p>Let's construct a 6x6 example for illustrating the code below.</p>\n<pre><code>board = [\n ['.', '.', '#', '.', '.', '.'], \n ['.', '.', '.', '.', '.', '#'], \n ['#', '.', '.', '#', '.', '.'], \n ['.', '#', '.', '#', 'K', '.'], \n ['.', '.', '#', '.', '.', '.'],\n ['#', '.', '.', '#', '#', '.'],\n] \n</code></pre>\n<p>As indicated, the origin is located at <code>[3, 4]</code>.</p>\n<p><strong>Is a class needed?</strong></p>\n<p>Though opinions may differ, I see no advantage to defining classes for this problem, such as one for the board and another for the pieces. It's a standalone problem, not part of a larger one, with only two potential types of objects, the board and the cells, with only a single board instance.</p>\n<p>Moreover, looking ahead I see no need for instance variables.</p>\n<p><strong>Useful constants</strong></p>\n<p>Here are a few constants I suggest be defined:</p>\n<pre><code>OPEN = '.'\nORIGIN_CHAR = 'K'\nDESTINATION = [0, 0]\nMOVE_OFFSETS = [\n [-2, 1], [-1, 2], [1, 2], [2, 1],\n [-2, -1], [-1, -2], [1, -2], [2, -1]\n]\n</code></pre>\n<p><code>MOVE_OFFSETS</code> is represented by the eight <code>m</code>'s in the drawing below. They are the locations the knight can move to, expressed as x-y offsets from its current location, provided, of course, that the new location is on the board.</p>\n<pre><code> y\n 2| m m \n 1| m m \n 0| o \n-1| m m\n-2| m m\n _______________ \n -2 -1 0 1 1 x\n</code></pre>\n<p><strong>Determining cells to which knight can move directly from its current location</strong></p>\n<pre><code>def possible_next_moves(board, current_loc)\n last_idx = board.size-1\n cx, cy = current_loc\n MOVE_OFFSETS.each_with_object([]) do |(xo,yo),possible_next_locs|\n nx = cx + xo\n ny = cy + yo \n possible_next_locs << [nx, ny] if nx.between?(0, last_idx) &&\n ny.between?(0, last_idx) && board[nx][ny] == OPEN\n end\nend\n</code></pre>\n<p>Let's try it with the example of <code>board</code> I gave above.</p>\n<pre><code>possible_next_moves(board, [3, 4]) #=> [[5, 5], [1, 3], [2, 2]]\npossible_next_moves(board, [0, 5]) #=> [[1, 3], [2, 4]] \npossible_next_moves(board, [5, 0]) #=> [] \npossible_next_moves(board, [0, 3]) #=> [[2, 4], [1, 1], [2, 2]]\n</code></pre>\n<p>This method and all methods below other than <code>shortest_path</code> should be private.</p>\n<p><strong>Main method</strong></p>\n<p>I suggest the main method be as follows.</p>\n<pre><code>require 'set'\n</code></pre>\n\n<pre><code>def shortest_path(board)\n origin = locate_origin(board)\n predessors = solve(board, origin)\n return nil if predessors.nil?\n construct_path(predessors, origin)\nend\n</code></pre>\n<p>The method returns <code>nil</code> if there is no path from the origin to the destination.</p>\n<p>I will present and discuss the three methods, <code>locate_origin</code>, <code>solve</code> and <code>construct_path</code> in turn. (The class <code>Set</code> is needed by <code>solve</code>.)</p>\n<p><strong>Locate the origin from <code>board</code></strong></p>\n<p>Locating the origin of the path (the cell containing <code>'K'</code>) is straightforward.</p>\n<pre><code>def locate_origin(board)\n indices = (0..board.size - 1).to_a\n indices.product(indices).find { |i,j| board[i][j] == ORIGIN_CHAR }\nend\n</code></pre>\n\n<pre><code>locate_origin(board)\n #=> [3, 4]\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-product\" rel=\"nofollow noreferrer\">Array#product</a>.</p>\n<p><strong>Find a shortest path using BFS</strong></p>\n<p>Since we have an undirected, unweighted graph with no negative cycles, a breadth-first search (BFS) is an efficient way of finding a shortest path from <code>origin</code> to <code>DESTINATION</code>. The method returns a hash whose keys are all locations visited and each key's value is the location on a path from the origin that immediately precedes the location given by the key.</p>\n<p>You understand how a BFS search is performed so I won't go into details of the calculations. It terminates when the destination is found or the queue of locations to be visited becomes empty (indicating that there is no path from the origin to the destination).</p>\n<pre><code>def solve(board, origin)\n prev = {}\n queue = [origin]\n visited = [origin].to_set\n loop do \n break nil if queue.empty? # no path exists\n loc = queue.shift\n next_moves = possible_next_moves(board, loc)\n if next_moves.include?(DESTINATION)\n prev[DESTINATION] = loc\n break prev # shortest path found!\n end\n next_moves.each do |next_loc|\n unless visited.add?(next_loc).nil? # loc already visited if nil\n prev[next_loc] = loc\n queue << next_loc\n end\n end\n end\nend\n</code></pre>\n\n<pre><code>prev = solve(board, [3,4])\n #=> {[5, 5]=>[3, 4], [1, 3]=>[3, 4], [2, 2]=>[3, 4], [4, 3]=>[5, 5],\n # [0, 5]=>[1, 3], [2, 5]=>[1, 3], [0, 1]=>[1, 3], [2, 1]=>[1, 3],\n # [3, 2]=>[1, 3], [0, 3]=>[2, 2], [1, 4]=>[2, 2], [1, 0]=>[2, 2],\n # [3, 0]=>[2, 2], [4, 1]=>[2, 2], [2, 4]=>[4, 3], [3, 5]=>[4, 3],\n # [5, 1]=>[4, 3], [0, 4]=>[2, 5], [4, 4]=>[2, 5], [0, 0]=>[2, 1]}\n</code></pre>\n<p><code>prev</code> contains the information needed to construct the shortest path. Starting at the destination (<code>[0, 0]</code>) we backtrack to the origin (<code>[4, 3]</code>):</p>\n<pre><code>[0, 0], prev[[0, 0]] #=> [2, 1], prev[[2, 1]] #=> [1, 3],\n prev[[1, 3]] #=> [3, 4]\n</code></pre>\n<p>I made <code>visited</code> a set merely to speed lookups. <a href=\"https://ruby-doc.org/stdlib-2.7.0/libdoc/set/rdoc/Set.html#method-i-add-3F\" rel=\"nofollow noreferrer\">Set#add?</a> serves double-duty: when attempting to add a location to <code>visited</code> it returns <code>nil</code> if the set already contains the location; else it adds the location to the set and returns the set.</p>\n<p><strong>Build the shortest path</strong></p>\n<p>Lastly, we must build the shortest path from the hash returned by <code>solve</code>.</p>\n<pre><code>def construct_path(prev, origin)\n current_loc = DESTINATION\n path = [DESTINATION]\n until path.first == origin\n prev_loc = prev[current_loc]\n path.unshift(prev_loc)\n current_loc = prev_loc\n end\n path\nend\n</code></pre>\n\n<pre><code>construct_path(prev, [3,4])\n #=> [[3, 4], [1, 3], [2, 1], [0, 0]]\n</code></pre>\n<p><strong>Run the method <code>shortest_path</code></strong></p>\n<pre><code>shortest_path(board)\n #=> [[3, 4], [1, 3], [2, 1], [0, 0]]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T16:34:14.160",
"Id": "504068",
"Score": "0",
"body": "Nice. This solution has a kind of functional feel to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T22:57:11.387",
"Id": "504314",
"Score": "0",
"body": "Excellent! I love these solutions. I will sit down and look through this thoroughly when studies allow it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T07:23:42.187",
"Id": "255432",
"ParentId": "255098",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255268",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T15:34:18.877",
"Id": "255098",
"Score": "3",
"Tags": [
"performance",
"programming-challenge",
"ruby",
"time-limit-exceeded"
],
"Title": "Finding minimum steps required to traverse from source to terminal"
}
|
255098
|
<p>I'm conflicting about how I want my database architecture to be built.
First of all, I use a singleton pattern for the database in order to insure one instance of it (so its thread-safe), and also for me to get a workable database reference wherever I have a context.</p>
<p>All across the application I make many different db operations, for example, some activities need to change only the 'Meals' table and some need to change 'Meals' & 'MealFoods' for example.</p>
<p>For each one of this tables I've built a helper class in order to separate the CRUD operations of each table apart from the DatabaseManager class (which extends SQLiteOpenHelper). This, of course is for the sake of simplicity and to get a cleaner code.</p>
<p><strong>First approach:</strong></p>
<p>This approach saves all the helper classes inside the DatabaseManager.</p>
<p>DatabaseManager.java:</p>
<pre><code>public class DatabaseManager extends SQLiteOpenHelper {
private static String dbName = "logs.db";
private static final int dbVersion = 1;
private final Context context;
public MealsDBHelper mealsDBHelper;
public MealFoodsDBHelper mealFoodsDBHelper;
private DatabaseManager(@NonNull Context context) {
super(context, dbName, null, dbVersio);
this.context = context.getApplicationContext();//Saving as application context to avoid leaks
mealsDBHelper = new MealsDBHelper(context);
mealFoodsDBHelper = new MealFoodsDBHelper(context);
}
private static DatabaseManager instance;
public static synchronized DatabaseManager getInstance(Context context) {
if (instance == null) {
instance = new DatabaseManager(context);
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
//...
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//...
}
}
</code></pre>
<p>Let's look at the MealsDBHelper class, which pretty much all it does is to help communicate CRUD operations with the database. (For example a user wants to change his meal name)</p>
<pre><code>public class MealsDBHelper {
public static final String MEALS_TABLE_NAME = "Meals";
public static final String MEAL_ID_COLUMN = "Meal_ID";
public static final String MEAL_NAME_COLUMN = "Meal_Name";
public static final String MEAL_POS_COLUMN = "Meal_Pos";
public static final String MEAL_DATE_COLUMN = "Date";
private Context context; //A context object to pass on to the DatabaseManager.getInstance method in all the different methods inside this class
public MealsDBHelper(Context context){
this.context = context;
}
//For example one of few methods that do operations on the 'Meals' table in the database.
public void updateMealName(long mealId, String meal_name) {
UserDataDB.getInstance(context).getWritableDatabase().execSQL("UPDATE " + MEALS_TABLE_NAME + " SET " + MEAL_NAME_COLUMN + " = '" + meal_name + "' WHERE " + MEAL_ID_COLUMN + " = " + mealId);
}
}
</code></pre>
<p>Now, no matter if the activity is modifying 1 or 2 or even 3 tables, I'm able to update the meal's name like so:</p>
<pre><code>DatabaseManager.getInstance(context).mealsDBHelper.updateMealName(mealId, mealName);
</code></pre>
<p>Thats because the DatabaseManager contains a reference to <strong>all</strong> the other helper classes.</p>
<p>What I like about this approach is that I can simply access every table and do operations on it according to my needs, & what I don't like is that the DatabaseManager class holds reference for all the helpers, and I'm not sure if its best to do so..</p>
<p><strong>Second approach:</strong></p>
<p>This approach <strong>does not</strong> saves all the helper classes inside the DatabaseManager.</p>
<p>DatabaseManager.java:</p>
<pre><code>public class DatabaseManager extends SQLiteOpenHelper {
private static String dbName = "logs.db";
private static final int dbVersion = 1;
private final Context context;
private DatabaseManager(@NonNull Context context) {
super(context, dbName, null, dbVersio);
this.context = context.getApplicationContext();//Saving as application context to avoid leaks
}
private static DatabaseManager instance;
public static synchronized DatabaseManager getInstance(Context context) {
if (instance == null) {
instance = new DatabaseManager(context);
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
//...
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//...
}
}
</code></pre>
<p>Now, if my activity needs to modify both 'Meals' & 'MealFoods' tables I can construct the helpers in onCreate, such as:</p>
<pre><code>public class AddFoodActivity extends AppCompatActivity{
MealsDBHelper mealsDBHelper;
MealFoodsDBHelper mealFoodsDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(..);
mealsDBHelper = new MealsDBHelper(this);
mealFoodsDBHelper = new MealFoodsDBHelper(this);
}
//Then whenever I need to modify the table I use:
mealsDBHelper.updateMealName(mealId, mealName);
}
</code></pre>
<p>What I like about this approach is that I can use a simple line to modify a table according to my needs,
& what I don't like is that I need to define helper references for every activity, and it kind of makes the code inconsistent.</p>
<p>Basically are there any downsides for using one of the methods?</p>
<p>I'll admit I did leave a big chunk of code out of this post, but its only because I think it won't add a lot to your understanding of the problem, because its a more general one.</p>
<p>Thank you very much for any kind of help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:42:49.020",
"Id": "503270",
"Score": "0",
"body": "Welcome to the Code Review Community where we review working code and provide suggestions on how to improve that code. While we sometimes address software design in the reviews it is not something we focus on explicitly. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). You might also want to check out the [Software Engineering Community](https://softwareengineering.stackexchange.com/help/how-to-ask) that does focus on software design."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T17:22:04.893",
"Id": "255102",
"Score": "0",
"Tags": [
"android",
"database",
"sqlite"
],
"Title": "How to effectively sperate CRUD operations from the main SQLiteOpenHelper - android studio"
}
|
255102
|
<h3>The problem</h3>
<p>I have a set of dataframes where each row should have a unique ID value, but sometimes imported data has multiple rows with the same ID. I want to do a <code>groupby</code> operation or something similar that checks each ID group for special characters indicating "no data," checks that each group column has exactly one non-special value (which could be repeated in multiple rows) and then collapses ID groups into one row whose column values are either unique non-special column values from the group or special values in columns where no row in the group had data.</p>
<p>I want the code to throw an error if there are multiple different non-special values in a group column. So if the ID column label is <code>'id'</code> and special characters are in <code>'x?'</code> then <code>col2</code> below should raise an exception:</p>
<pre class="lang-bsh prettyprint-override"><code> id src col1 col2 col3
0 f x 5 m 1
1 f a 5 n ?
</code></pre>
<p>I've put together the following solution but I think there must be a way simpler method. My main question is whether I can do this with more native pandas code instead of using multiple helper functions as I've done below.</p>
<h3>My code</h3>
<p>I'm currently accomplishing this with a function called <code>merge_rows</code> that uses three helper functions:</p>
<ul>
<li><code>get_nonspecial_values</code> gets all non-special values in a column</li>
<li><code>check_column_consistency</code> checks if a column has exactly one non-special value</li>
<li><code>get_inconsistent_ids</code> gets a (hopefully empty) set of ID values whose rows conflict with each other, like with ID value <code>'f'</code> above.</li>
</ul>
<p>I think the last two lines in <code>get_inconsistent_ids</code> and <code>merge_rows</code> could probably be done with a built-in pandas operation which would then make a bunch of the code I've written unnecessary, but I can't figure out what that operation would be (I'm also not sure those are the lines to focus on when revising this code).</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
def get_nonspecial_values(series, specials):
'''
takes a series representing a column and returns all
values in the column that are not in specials
'''
counts = series.value_counts()
return [v for v in counts.index if str(v) not in specials]
def check_column_consistency(series, specials):
'''
takes a series representing a column and returns True
if there is exactly one value that is not in specials
'''
nonspecial = get_nonspecial_values(series, specials)
if len(nonspecial) not in [1, 0]:
return False
else:
return True
def get_inconsistent_ids(df, specials, id_column):
'''
takes a dataframe, special values, and a column label
returns all ID values that represent a set of rows in which
at least one column has multiple different nonspecial values
'''
where_nonunique_ids = df[id_column].duplicated(keep=False)
if not any(where_nonunique_ids):
return []
else:
rows_with_nonunique_ids = df.loc[where_nonunique_ids]
check_group = lambda x: all(x.apply(check_column_consistency, args=(specials,)))
where_ids_consistent = rows_with_nonunique_ids.groupby(id_column).apply(check_group)
return [v for v in where_ids_consistent.index if not where_ids_consistent[v]]
def merge_rows(df, specials='', id_column=''):
'''
performs the merge operation described above
'''
inconsistent_ids = get_inconsistent_ids(df, specials=specials, id_column=id_column)
if len(inconsistent_ids) > 0:
raise ValueError('found the following ID values with inconsistent rows', inconsistent_ids)
rows_with_nonunique_ids = df.loc[df[id_column].duplicated(keep=False)]
unique_column_value = lambda x: (get_nonspecial_values(x, specials) or ['x'])[0]
get_group_values = lambda x: x.apply(unique_column_value)
values_by_id = rows_with_nonunique_ids.groupby(id_column).apply(get_group_values)
return pd.DataFrame(data=values_by_id.values, columns=df.columns)
df = pd.DataFrame({'id' : ['a','b','c','c','d','d','d'],
'src': ['x','a','a','a','a','a','a'],
'col1':[ 5, 5, '?','?', 5, 5, 'x'],
'col2':['x','n','n','x','n','x','x'],
'col3':[ 1 , 3 ,'?', 9 ,'?', 8 ,'x']})
print(merge_rows(df, specials='x?', id_column='id'))
</code></pre>
<p>The code above gives me the following output</p>
<pre class="lang-bsh prettyprint-override"><code> id src col1 col2 col3
0 c a x n 9
1 d a 5 n 8
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T18:35:36.410",
"Id": "255104",
"Score": "0",
"Tags": [
"python",
"database",
"pandas"
],
"Title": "Merge rows in a pandas DataFrame while ignoring specified values and checking for conflicts"
}
|
255104
|
<p>I have created my first npm package: <a href="https://github.com/sunnysideup/stretched-bg-image" rel="nofollow noreferrer">https://github.com/sunnysideup/stretched-bg-image</a>.</p>
<p>The purpose of the package is to add a class to a div (or any other block element in the HTML) depending on the width / height ratio of the div (panorama / landscape / portrait / skyscraper)</p>
<p>Below is the code. It works fine, but does it follow best practice?</p>
<p>Also, what is the best way to include the vanilla css</p>
<p>Here is the core code:</p>
<pre class="lang-js prettyprint-override"><code>'use strict';
(
function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory)
} else if (typeof exports === 'object') {
module.exports = factory()
} else {
root.StretchedBgImages = factory()
}
}(
typeof window !== 'undefined' ? window : this,
function () {
if (typeof window === 'undefined') {
return null
}
/**
*
* @type {Function}
* @constructor
*/
const StretchedBgImages = function () {}
StretchedBgImages.apply = function (opt) {
// defaults ...
const defaultClassRanges = [
{
max: '8',
min: '2',
className: 'panorama'
},
{
max: '2',
min: '1',
className: 'landscape'
},
{
max: '1',
min: '0.5',
className: 'portrait'
},
{
max: '0.5',
min: '0.125',
className: 'skyscraper'
}
]
const defaultQueryString = '.stretched-bg-images'
const defaultErrorClass = 'stretched-bg-images-error'
// set options
opt = opt || {}
const classRanges = opt.classRanges || defaultClassRanges
const queryString = opt.queryString || defaultQueryString
const errorClass = opt.errorClass || defaultErrorClass
// observer method
const ro = new window.ResizeObserver(
entries => {
for (const entry of entries) {
if (entry.target.handleResize) {
entry.target.handleResize(entry)
}
}
}
)
// find elements...
const entries = document.querySelectorAll(queryString)
// loop elements
for (let i = 0; i < entries.length; ++i) {
const entry = entries[i]
ro.observe(entry)
// set resize Method
entry.handleResize = entry => {
const height = entry.target.clientHeight
const width = entry.target.clientWidth
const ratio = width / height
let hit = false
for (let j = 0; j < classRanges.length; ++j) {
const range = classRanges[j]
if (ratio >= range.min && ratio <= range.max) {
entry.target.classList.add(range.className)
hit = true
} else {
entry.target.classList.remove(range.className)
}
}
if (hit === false) {
entry.target.classList.add(errorClass)
} else {
entry.target.classList.remove(errorClass)
}
}
}
}
return StretchedBgImages
}
)
)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:44:29.187",
"Id": "503211",
"Score": "1",
"body": "Please describe the purpose of your package."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T20:05:54.597",
"Id": "503212",
"Score": "0",
"body": "DONE! Thank you"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:18:32.797",
"Id": "255106",
"Score": "1",
"Tags": [
"javascript",
"css"
],
"Title": "Does my first npm package follow best practices?"
}
|
255106
|
<p>I'm using the <a href="http://bitwiseshiftleft.github.io/sjcl/sjcl.js" rel="nofollow noreferrer">minified version</a> of <a href="http://bitwiseshiftleft.github.io/sjcl/" rel="nofollow noreferrer">SJCL</a> to encrypt the backup files requested by the users. It is in a <a href="https://developers.google.com/apps-script" rel="nofollow noreferrer">Google Apps Script</a> add-on for Google Sheets.</p>
<p>I'm mostly concerned with correct use, exception handling and best practices of adding the encryption part in the script. It is currently working as expected in backup and in restore process.</p>
<h2>The Backup (and Encryption)</h2>
<h3>User enter passphrase</h3>
<p>It starts by asking the user to enter and re-enter the passphrase in a prompt. 1) One concern here is that the text field of the prompt doesn't mask the passphrase. To fix that I would show a dialog with HTML and form (password input). But then I would need to work client-server call and, while that is not an issue, the prompt is much simpler, less complicated and it won't be necessary to put a HTML - that could be questionable by the user?</p>
<pre><code>const passphrase1 = ui.prompt(
'Backup',
'Enter passphrase:',
ui.ButtonSet.OK_CANCEL);
if (passphrase1.getSelectedButton() === ui.Button.CANCEL) return 0;
const passphrase2 = ui.prompt(
'Backup',
'Please re-enter this passphrase:',
ui.ButtonSet.OK_CANCEL);
if (passphrase2.getSelectedButton() === ui.Button.CANCEL) return 0;
</code></pre>
<h3>Test passphrase</h3>
<p>Here, the script tests if the passphrases match, and it also tests passphrase length and if it has at least upper, lower, numbers and special characters. It is a very simple test - so <code>pA$$w0rd00</code> pass the test - and I actually didn't want to test anything like GnuPG does. In this case, is nothing (no test, like GnuPG) better than this simple test?</p>
<pre><code>const passphrase = passphrase1.getResponseText();
if (passphrase !== passphrase2.getResponseText() || passphrase.length < 10 || testPassphrasePolicy(passphrase)) {
ui.alert(
'Backup',
'Invalid passphrase.',
ui.ButtonSet.OK);
return 1;
}
function testPassphrasePolicy (passphrase) {
if (!/[a-z]+/.test(passphrase)) return 1;
if (!/[A-Z]+/.test(passphrase)) return 1;
if (!/[0-9]+/.test(passphrase)) return 1;
if (!/[~!@#$%^*-_=+[{\]}/;:,.?]+/.test(passphrase)) return 1;
return 0;
}
</code></pre>
<h3>Encrypt data</h3>
<p>The encryption part is pretty straight forward. The <code>backup</code>is a object like <code>backup = { foe: 'abc', bar: 123 }</code>. The steps are as follow:</p>
<ol>
<li>Stringify <code>backup</code></li>
<li>Encode to base64</li>
<li>Compute SHA256</li>
<li>Concatenate the base64 with <code>:</code> and the SHA256</li>
<li>Encrypt with AES-128 in GCM mode and using the SHA256 as authentication data. If there is an error, simply return and show a generic message error.</li>
<li>Test decryption. If there is an error, simply return and show a generic message error.</li>
<li>Return a blob of the encrypted backup</li>
</ol>
<p>I suspect steps 3 and 4 are overdoing, but before the addition of encryption that is how the script was doing an simple integrity test (with SHA1).</p>
<pre><code>function encryptBackup_ (backup, passphrase) {
const string = JSON.stringify(backup);
const webSafeCode = Utilities.base64EncodeWebSafe(string, Utilities.Charset.UTF_8);
const sha = computeDigest('SHA_256', webSafeCode, 'UTF_8');
const data = webSafeCode + ':' + sha;
let encrypted = '';
try {
encrypted = sjcl.encrypt(passphrase, data, { mode: "gcm", adata: sha });
} catch (err) {
ConsoleLog.error(err);
return 0;
}
try {
const decrypted = sjcl.decrypt(passphrase, encrypted);
const parts = decrypted.split(':');
const test_sha = computeDigest('SHA_256', parts[0], 'UTF_8');
if (test_sha !== parts[1]) throw new Error('digestBackup_(): Bad decryption.');
} catch (err) {
ConsoleLog.error(err);
return 0;
}
const date = Utilities.formatDate(DATE_NOW, 'GMT', 'yyyy-MM-dd-HH-mm-ss');
const name = 'data' + date + '.backup';
const blob = Utilities.newBlob(encrypted, 'application/octet-stream', name);
return blob;
}
</code></pre>
<h2>The Restore (and Decryption)</h2>
<p>Once the user select a Drive <code>file</code>, the script requests the passphrase and tries to decrypt the file. This part is testing if it is possible to decrypt the file selected by the user.</p>
<p>The passphrase is being cached <a href="https://developers.google.com/apps-script/reference/cache/cache-service#getusercache" rel="nofollow noreferrer">in a cache instance scoped to the current user and script</a> so the script can retrieve it later to actually decrypt the file and restore the data. The cache expires in 120 seconds (session), and once it is retrieved later, it is immediately removed.</p>
<pre><code>const ui = SpreadsheetApp.getUi();
const passphrase = ui.prompt(
'Restore',
'Enter passphrase:',
ui.ButtonSet.OK_CANCEL);
if (passphrase.getSelectedButton() === ui.Button.CANCEL) return 0;
let decrypted = null;
try {
decrypted = sjcl.decrypt(passphrase.getResponseText(), data);
} catch (err) {
ConsoleLog.error(err);
return 4;
}
const address = computeDigest(
'SHA_1',
file.getId() + SpreadsheetApp2.getActiveSpreadsheet().getId(),
'UTF_8');
CacheService2.put('user', address, 'string', passphrase.getResponseText(), 120);
const parts = decrypted.split(':');
const test_sha = computeDigest('SHA_256', parts[0], 'UTF_8');
if (test_sha !== parts[1]) return 4;
const string = base64DecodeWebSafe(parts[0], 'UTF_8');
return JSON.parse(string);
</code></pre>
|
[] |
[
{
"body": "<h2>User enter passphrase</h2>\n<p>Nobody uses an OS modal dialog prompts anymore. I'd suggest a web page specific modal box such as shown <a href=\"https://jqueryui.com/dialog/#modal-form\" rel=\"nofollow noreferrer\">here</a>. You need to click "new user" to have the box show up.</p>\n<p>As for the naming, <code>passphrase1</code> and <code>passphrase1</code> seem to loose information, why not <code>passphrase</code> and <code>passphraseReentered</code> (or <code>reenteredPassprase</code>)? Now it seems like two different passwords to me.</p>\n<h2>Test passphrase</h2>\n<p>You haven't clearly documented which policy is being checked, although that might be in the design documentation or left out for now. But things like policy should not have to be derived from source code. It would be pretty tricky to validate the source code if it is leading so you would not be able to discern bugs.</p>\n<pre><code>if (passphrase !== passphrase2.getResponseText() || passphrase.length < 10 || testPassphrasePolicy(passphrase)) {\n</code></pre>\n<p>You're doing too much here, and it shows. First of all, checking if the password was correctly reentered is separate from testing the password policy. If it is a different check then it should be handled separately.</p>\n<p>This will quickly become apparent anyway when users start to complain that they first entered the password <strong>twice</strong> before you check that the password complies with the policy (d'Oh!).</p>\n<p>I'd argue that a length requirement should be part of the password policy, which removes another equation from the <code>if</code>.</p>\n<pre><code>if (!/[a-z]+/.test(passphrase)) return 1;\n</code></pre>\n<p>No, no no. First of all, at least return <code>false</code> or something similar, not <code>0</code> or <code>1</code>. But shouldn't you indicate which test failed to the user?</p>\n<p>After all these checks you perform <code>return 0</code> which would actually sounds negative to me. However, I haven't seen that it fails on specific characters. That might be fine, but I'd personally make sure that the password doesn't contain any weird characters, control characters and such.</p>\n<h2>Encrypt data</h2>\n<blockquote>\n<p>I suspect steps 3 and 4 are overdoing, but before the addition of encryption that is how the script was doing an simple integrity test (with SHA1).</p>\n</blockquote>\n<p>It is overdoing it, and since you're being incompatible with the original anyway, I'd remove the SHA-256 computation (note the dash in SHA-256).</p>\n<pre><code>const webSafeCode = Utilities.base64EncodeWebSafe(string, Utilities.Charset.UTF_8);\n</code></pre>\n<p>Why you would expand your plaintext by encoding it before encryption is beyond me, GCM handles binary just fine, thank you.</p>\n<pre><code>const sha = computeDigest('SHA_256', webSafeCode, 'UTF_8');\n</code></pre>\n<p>So what does this return so that you can put it at the end of a textual string? If it returns hexadecimals or base 64 then this should be made clear when looking at the call.</p>\n<pre><code> let encrypted = '';\n</code></pre>\n<p>If you fail to assign you will hit <code>return 0</code> and otherwise the assignment is performed in the next statement. Don't assign empty strings, or zero or null when it is not required.</p>\n<pre><code>encrypted = sjcl.encrypt(passphrase, data, { mode: "gcm", adata: sha });\n</code></pre>\n<blockquote>\n<p>JCL strengthens your passwords by a factor of 1000</p>\n</blockquote>\n<p>Yeah, that <em>might</em> have been fine when PBKDF2, the password strengthening version was first created. Nowadays you'd want to hit a million at the least, and maybe increase the work factor later. Using (just) passwords for any encryption is tricky, unfortunately.</p>\n<p>I'll not comment on the decryption part within the encryption function. I think it is overly cautious because on error I would not expect the code to hit <code>return blob</code> but since it is backup data...</p>\n<pre><code> if (test_sha !== parts[1]) throw new Error('digestBackup_(): Bad decryption.');\n</code></pre>\n<p>But I will comment on badly copied code, we're not in <code>digestBackup</code> and errors already should contain a stacktrace, so there is no need to log it additionally.</p>\n<pre><code>const date = Utilities.formatDate(DATE_NOW, 'GMT', 'yyyy-MM-dd-HH-mm-ss');\nconst name = 'data' + date + '.backup';\n</code></pre>\n<p>A date in seconds and a filename that uses that date to distinguish backups. Even <strong>if</strong> this would never happen in reality, your unit / application testers are going to despise you. You need a better way of keeping blobs apart. Worse they may not catch it and you may overwrite a previous backup - current computers are fast, you can do a lot in a second, and maybe you want to backup before and after a process was executed.</p>\n<p>Note that the encrypt function starting from the (unnecessary) SHA calculation up to the blob creation is completely ignorant of the data type. If you'd spit that out you can test the encryption / decryption separately. EDIT: On the other hand, you could use the file name as additional authenticated data (<code>adata</code>) so an attacker cannot get away with renaming the backups. Still, you could add that data as parameter to the function call.</p>\n<h2>The Restore (and Decryption)</h2>\n<p>First of all, where is the <code>decryptBackup_</code> function? Always make your applications symmetric, even if the result is just a single line method. Imagine the future developer (i.e. you) searching for it. Now you suddenly mix UI code and the code doing the actual work as well.</p>\n<pre><code>return 4;\n</code></pre>\n<p>Warning, high octarine levels detected. Don't use magic numbers!</p>\n<pre><code>const address = computeDigest(\n 'SHA_1',\n file.getId() + SpreadsheetApp2.getActiveSpreadsheet().getId(),\n 'UTF_8');\nCacheService2.put('user', address, 'string', passphrase.getResponseText(), 120);\n</code></pre>\n<p>Excuse me, what does this do? In here? At all?</p>\n<pre><code>if (test_sha !== parts[1]) return 4;\n</code></pre>\n<p>Four! Goofy golf ball error!</p>\n<p>I like that you thought about your passphrase caching and management. Key/secret management is very important in crypto.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:10:04.537",
"Id": "503295",
"Score": "0",
"body": "Hi and thank you for your time! I really appreciate it as my script needs a review before I consider merging it to the main branch. I learned new stuff and while one or two issues - see below - won't be a problem in this specific case, I'll keep your explanation in mind in other occasions. My comments on each for each issue you pointed out is too long for this box. How can I respond properly to your answer - what do you suggest?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:58:19.680",
"Id": "503300",
"Score": "0",
"body": "More boxes, handle one comment at a time. We can always move to chat if the comment section gets too long, we'll be notified automatically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:12:31.187",
"Id": "503302",
"Score": "0",
"body": "Some considerations: 1. the code from the question is running in the server-side. By the way, the add-on is for Google Sheets, so everything is running in the server-side, except for a button \"back up now\" and the passphrase prompts. 2. After encryption, the file is sent via email to the user - that is required to the owner of the spreadsheet and user of the add-on - since an owner of a spreadsheet can share with another user that has the add-on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:12:38.617",
"Id": "503303",
"Score": "0",
"body": "Now, all the following parts has the same response \"Noted, will fix!\": \"_Now it seems like two different passwords to me._\".... \"_checking if the password was correctly reentered is separate from testing the password policy_\".... \"_at least return false or something similar, not 0 or 1._\".... \"_First of all, where is the decryptBackup_ function? Always make your applications symmetric_\".... \"_Don't assign empty strings, or zero or null when it is not required._\".... \"_your unit / application testers are going to despise you_\" I don't have any testers actually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:13:07.490",
"Id": "503304",
"Score": "0",
"body": "\"_Nobody uses an OS modal dialog prompts anymore._\" To be more specific, it is using the [Apps Script prompt dialog](https://developers.google.com/apps-script/guides/dialogs#prompt_dialogs); should I still replace it with a [custom dialog](https://developers.google.com/apps-script/guides/dialogs#custom_dialogs) to show up a box?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:16:19.027",
"Id": "503306",
"Score": "0",
"body": "\"_Test passphrase_\" The \"policy\" is at least 10 characters long containing at least one of each: upper, lower, number, and special symbol. It isn't a real policy but rather a suggestion/guidelines for the user since enforcing a good policy - that doesn't allow things like `pA$$w0rd00` or `1234567Qr!` (example) - is difficult and I have no idea how to start - the add-on doesn't make third-party calls. That is why I considered an approach similar to GnuPG encryption where no warning is given - but that would require me to suppose the user will be careful to choose a good passphrase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:24:23.530",
"Id": "503307",
"Score": "0",
"body": "I would not suppose that, generally users choose pretty weak passwords (about 42 bits of entropy on average if I remember correctly - quite a long way from the 128 bits you'd like for encryption), and password based encryption is already pretty weak. As for the password box, I found [this little gem on SO](https://stackoverflow.com/q/36225756/589259)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:29:50.290",
"Id": "503310",
"Score": "0",
"body": "\"_But shouldn't you indicate which test failed to the user?_\" I'll see what I can do. The prompt dialog is similar to the GnuPG: shows a prompt, you enter a passphrase, then another prompt and re-enter passphrase. Unless you are suggest it should be a dynamic interface to show X's or Ok's for each test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:30:05.357",
"Id": "503311",
"Score": "0",
"body": "\"_make sure that the password doesn't contain any weird characters, control characters and such_\" The prompt dialog is in [sanbox mode](https://developers.google.com/apps-script/reference/html/sandbox-mode) by Google so that wouldn't be a concern? What weird characters? I'm allowing whitespaces - like GnuPG does, erm... is it bad?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:44:39.763",
"Id": "503314",
"Score": "0",
"body": "\"_Why you would expand your plaintext by encoding it before encryption is beyond me_\" I did that as a safeguard for foreing characters; I did some research on base64, but since I couldn't find anything completely clear I left it that way - as \"don't fix what is not broken\".\n\n\"_So what does this return so that you can put it at the end of a textual string?_\" Yes, it returns hexadecimals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T20:26:55.680",
"Id": "503323",
"Score": "0",
"body": "GCM operates on bytes. If they represent foreign characters is entirely inconsequential. What you are currently doing is to have binary, then encode it to text using base 64, and then use the ASCII encoding of those as binary input for the encryption routine..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T21:35:17.033",
"Id": "503325",
"Score": "0",
"body": "1/2 \"_Excuse me, what does this do? In here? At all?_\" I'm using the [CacheService](https://developers.google.com/apps-script/reference/cache/cache#putkey,-value,-expirationinseconds) to add a key/value to the cache with an expiration. The scope is `user`, the key is `address`, the value is `passphrase.getResponseText()` and the expiration is `120 (seconds)`. The passphrase is only cached after decryption succeeds. Now, the only issue - that I saw - here is how to choose the key."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T21:35:32.127",
"Id": "503326",
"Score": "0",
"body": "2/2 I'm using the SHA-1 of the concatenation of the spreadsheet ID with the Drive file ID because only a concatenation could be too large for a key. I'm combining both spreadsheet ID and file ID to be certain the script will get the value from the correct key. For example, if it was only file ID and the user decided to open a new spreadsheet, it would be possible to start the restore process by passing only the file ID. Now, if it was only the spreadsheet, it would be feasible to start the restore process without going throught (jump) the `select backup file from Drive` process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:00:51.383",
"Id": "503329",
"Score": "0",
"body": "\"_I like that you thought about your passphrase caching and management. Key/secret management is very important in crypto._\" Something you can enlight me here in this part is if there is any issue with the cache being managed in the server-side by Google. Or if it would be better to ask **again** the user for the passphrase. There is this balance between don't bother user too much/user can enter wrong passphrase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:35:37.393",
"Id": "503332",
"Score": "0",
"body": "As for 1/2 it's not so much that you're doing something there, but why isn't it at least in a well named method implementation and again, there is a problem with symmetry here. If you read the encryption function, then you don't expect this in the decryption function suddenly. I'd always at least indicate in a comment *what* is happening (how it is happening should be clear from the code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:36:09.317",
"Id": "503333",
"Score": "0",
"body": "2/2 Great, you've got your method documentation right there :)"
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:47:02.077",
"Id": "255143",
"ParentId": "255109",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255143",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T19:43:06.920",
"Id": "255109",
"Score": "2",
"Tags": [
"javascript",
"google-apps-script",
"encryption"
],
"Title": "JavaScript: proper user of SJCL encryption in Google Apps Script"
}
|
255109
|
<p>I have a couple of general purpose LocalDateTime parser methods I wrote to handle Dates flowing between a number of legacy XML based processing pipelines over to a modern Spring Boot, Mongo applications. Because both the legacy and modern applications are set in stone, I'm stuck with a narrow conversion of legacy String dates to LocalDateTime. That said I wanted to present it for review and perhaps improve the code. The various legacy String Dates we have are :</p>
<pre><code> // 200701 - 6 yyyyMM
// 032007 - 6 MMyyyy
// 2007-01 - 7 yyyy-MM
// 03-2007 - 7 MM-yyyy
// 03012007 - 8 MMddyyyy
// 20070301 - 8 yyyyMMdd
// 03-01-2007 - 10 MM-dd-yyyy
// 2007-03-01 - 10 MM-dd-yyyy
</code></pre>
<p>And the methods I came up with are : The primary method is parseDate(), I just pass in the legacy String Date and basically have it figure out the length and then try and convert it to LocalDateTime. It works and all the JUnit tests pass.</p>
<pre><code>public LocalDateTime parseDate(String dateString) {
checkArgument(!Strings.isNullOrEmpty(dateString), "Date [" + dateString + "] is empty of NULL!");
LOG.debug("parseDate.................................Date [{}]", dateString);
LocalDateTime ldateResults = null;
dateString = dateString.replace("/","-");
switch (dateString.length())
{
case 6:
try { ldateResults = getLocalDateTimeFromString ( dateString, "MMyyyy" ); }
catch ( Exception ltwoXcp ) {
LOG.warn("Date [{}] failed with format [MMyyyy], trying another", dateString);
try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyyMM" ); }
catch ( Exception loneXcp ) {
LOG.warn("Date [{}] failed with format [yyyyMM], trying another", dateString);
}
}
break;
case 7:
if ( dateString.indexOf("-") > 3 ) {
try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyy-MM" ); }
catch ( Exception loneXcp ) {
LOG.warn("Date [{}] failed with format [yyyy-MM], trying another", dateString);
}
try { ldateResults = getLocalDateTimeFromString ( dateString, "MM-yyyy" ); }
catch ( Exception ltwoXcp ) {
LOG.warn("Date [{}] failed with format [MM-yyyy], trying another", dateString);
}
}
break;
case 8:
try { ldateResults = getLocalDateTimeFromString ( dateString, "MMddyyyy" ); }
catch ( Exception loneXcp ) {
LOG.warn("Date [{}] failed with format [MMddyyyy], trying another", dateString);
try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyyMMdd" ); }
catch ( Exception ltwoXcp ) {
LOG.warn("Date [{}] failed with format [yyyyMMdd], trying another", dateString);
}
}
break;
case 10:
try { ldateResults = getLocalDateTimeFromString ( dateString, "MM-dd-yyyy" ); }
catch ( Exception loneXcp ) {
LOG.warn("Date [{}] failed with format [MM-dd-yyyy], trying another", dateString);
try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyy-MM-dd" ); }
catch ( Exception ltwoXcp ) {
LOG.warn("Date [{}] failed with format [yyyy-MM-dd], trying another", dateString);
}
}
break;
}
return ldateResults;
}
public LocalDateTime getLocalDateTimeFromString(String dateString, String dateFormat) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(dateFormat);
if ( dateFormat.length() == 6 ) {
LocalDate localDate = YearMonth.parse(dateString, dateFormatter).atDay(1);
return localDate.atStartOfDay();
}
return LocalDate.parse(dateString, dateFormatter).atStartOfDay();
}
public String getStringFromLocalDateTime(LocalDateTime date, String dateFormat) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
return formatter.format(date);
}
</code></pre>
<p>Here are some JUnit tests that run :</p>
<pre><code>@Test
public void parseDateReturnsCorrectyyyyMM() {
String dateString="200703";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
@Test
public void parseDateReturnsCorrectMMyyyy() {
String dateString="032007";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
@Test
public void parseDateReturnsCorrectyyyyMMdd() {
String dateString="20070301";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
@Test
public void parseDateReturnsCorrectMMddyyyy() {
String dateString="03012007";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
@Test
public void parseDateReturnsCorrectMM_dd_yyyy() {
String dateString="03-01-2007";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
@Test
public void parseDateReturnsCorrectyyyy_MM_dd() {
String dateString="2007-03-01";
LocalDateTime ldtValue = null;
try {
ldtValue = dateUtils.parseDate(dateString);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if ( ldtValue != null ) {
dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
}
assertEquals("03/01/2007", dateString);
}
</code></pre>
<p>Tia adym</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:48:25.730",
"Id": "503231",
"Score": "0",
"body": "Are you sure this works correctly? I believe I have spotted two potential bugs: In `case 7` the `if` should probably only surround the first `try` block and in `getLocalDateTimeFromString` the `if` should probably cover the lengths `6`and `7`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:23:26.120",
"Id": "503276",
"Score": "0",
"body": "Yup, good eye...working on a rewrite using the cached formatters...since these parseDate methods reside in a Spring Boot bean, made sense to use the cache method."
}
] |
[
{
"body": "<p>"A mess" is the first thing that comes to my mind. Why don't you just use a loop over the various formats?</p>\n<p>If you want to introduce a special guard (like the string length), create a parser objcet, which implements\nan appropriate check.</p>\n<p>Something along the lines of</p>\n<pre><code>interface DateParser {\n boolean isApplicable(String in);\n LocalDateTime parse(String in);\n}\n</code></pre>\n<p>Then create a bunch of implementations and try them all out.</p>\n<p>You could even consider implementing the various possibilities in an enum:</p>\n<pre><code>enum DateParser {\n LEGACY_1("yyyyMM"),\n LEGACY_2("MMyyyy"),\n ...;\n \n private final int length;\n private final DateTimeFormatter formatter;\n \n private DateParser(String pattern) {\n this.length = pattern.length;\n // note: format created only *once*, not every time\n this.formatter = DateTimeFormatter.ofPattern(pattern);\n }\n \n public boolean isApplicable(String in) {\n return in.length == length;\n }\n \n public LocalDateTime tryParse(String in) {\n ... do whatever you need to do using formatter ...\n }\n}\n</code></pre>\n<p>Then, just loop over the enum constants and call the methods as appropriate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T12:42:45.813",
"Id": "503262",
"Score": "0",
"body": "`LEGACY_1` I'd rather call them `YEAR_MONTH`, `MONTH_YEAR`, `DAY_MONTH_YEAR` and so forth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:40:14.913",
"Id": "503278",
"Score": "0",
"body": "Thank you for the input! Btw, I agree it was a mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T07:18:15.093",
"Id": "503365",
"Score": "0",
"body": "@Bobby I thought about a naming scheme like this, but it basically exposes an implementation detail via the name. In reality, I'd rather go for the source of the format in the enumaration constant names like MONGO, EXCEL, OLD_MAINFRAME_CRP and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T08:57:51.223",
"Id": "503371",
"Score": "0",
"body": "I see, though I'd not consider the format an implementation detail in this case, but if there is a more specific name available, one should go for that, true."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T07:06:03.347",
"Id": "255124",
"ParentId": "255111",
"Score": "4"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>public LocalDateTime parseDate(String dateString) {\n</code></pre>\n<p>Your formatting choices are partly odd, if in doubt, stick to the IDE default formatting (or the formatting of the project.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>checkArgument(!Strings.isNullOrEmpty(dateString), "Date [" + dateString + "] is empty of NULL!");\n</code></pre>\n<p>Split it into two checks, one for null and one for empty, that does make it easier to debug later.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>LOG.debug("parseDate.................................Date [{}]", dateString);\n</code></pre>\n<p>Don't make me read a long line in the log if a short one is completely sufficient:</p>\n<pre class=\"lang-java prettyprint-override\"><code>LOG.debug("MyUtilClass.parseDate(\\"{}\\")", dateString);\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>LocalDateTime ldateResults = null;\n</code></pre>\n<p>Don't shorten variable names just because you can, it makes the code harder to read and harder to maintain. Case in point is "ltwoXcp", what's that supposed to even mean?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>dateString = dateString.replace("/","-");\n</code></pre>\n<p>Do not assign to parameters, it makes the code harder to debug. Treat all parameters as <code>final</code> (you can also make all parameters <code>final</code>, but in my opinion that is too much noise for a very simple rule to follow).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>try { ldateResults = getLocalDateTimeFromString ( dateString, "MMyyyy" ); }\ncatch ( Exception ltwoXcp ) {\n</code></pre>\n<p>Same here regarding formatting. With default Java-style formatting, the code would look like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>try {\n ldateResults = getLocalDateTimeFromString ( dateString, "MMyyyy" );\n} catch (Exception ltwoXcp) {\n</code></pre>\n<p>Again, whether or not that is easier to read is up to the reader. But overall you seem to go for tenser code, which does not improve readability or maintainability as you would believe.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>LOG.warn("Date [{}] failed with format [MMyyyy], trying another", dateString);\n</code></pre>\n<p>Logging every failed parse attempt seems excessive.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public LocalDateTime getLocalDateTimeFromString(String dateString, String dateFormat) {\n DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(dateFormat);\n if ( dateFormat.length() == 6 ) {\n LocalDate localDate = YearMonth.parse(dateString, dateFormatter).atDay(1);\n return localDate.atStartOfDay();\n }\n return LocalDate.parse(dateString, dateFormatter).atStartOfDay();\n}\n</code></pre>\n<p>This seems quite costly overall. You're creating a new formatter every time you <em>try</em> to parse a string, and then an exception is thrown for every failed attempt.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> try {\n ldtValue = dateUtils.parseDate(dateString);\n } catch (Exception e) {\n e.printStackTrace();\n fail(e.getMessage());\n }\n</code></pre>\n<p>Just declare <code>throws Exception</code> on the test method and let the <code>Exception</code> go its natural course.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if ( ldtValue != null ) {\n dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");\n }\n \n assertEquals("03/01/2007", dateString);\n</code></pre>\n<p>I'd rather compare against a specific <code>LocalDateTime</code> rather than against a <code>String</code>, as that might expose unexpected behavior in the parser method.</p>\n<hr />\n<p>You return <code>null</code>, so the calling method should have an output like "Failed to parse <201202302340243> into a valid LocalDateTime." if your parser returns <code>null</code>.</p>\n<hr />\n<p>Overall your logic is too complex, but not complex enough. You're making a few assumptions about what dates you will receive and how to handle them, which might be fair to do but can lead to problems. For example, a malformed date might still get parsed, "132012" will be parsed even though it was an user input error.</p>\n<p>First, I'd cache the formatters:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final Map<String, DateTimeFormatter> FORMATTERS;\n\nstatic {\n Map<String, DateTimeFormatter> formatters = new HashMap<>();\n formatters.put("MMyyyy", new DateTimeFormatter.ofPattern("MMyyyy"));\n formatters.put("yyyyMM", new DateTimeFormatter.ofPattern("yyyyMM"));\n formatters.put("yyyy-MM", new DateTimeFormatter.ofPattern("yyyy-MM"));\n formatters.put("MM-yyyy", new DateTimeFormatter.ofPattern("MM-yyyy"));\n formatters.put("MMddyyyy", new DateTimeFormatter.ofPattern("MMddyyyy"));\n formatters.put("yyyyMMdd", new DateTimeFormatter.ofPattern("yyyyMMdd"));\n formatters.put("MM-dd-yyyy", new DateTimeFormatter.ofPattern("MM-dd-yyyy"));\n formatters.put("yyyy-MM-dd", new DateTimeFormatter.ofPattern("yyyy-MM-dd"));\n FORMATTERS = Collections.unmodifiableMap(formatters);\n}\n</code></pre>\n<p>That allows you yo easily get the cached instance based on the pattern you want to use.</p>\n<p>Next, as we don't care <em>that</em> much about the <code>DateTimeParseException</code>, we will simply ignore it in an extra method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private LocalDateTime parse(String dateString, String datePattern) {\n DateTimeFormatter formatter = FORMATTERS.get(datePattern);\n \n if (formatter == null) {\n throw new IllegalStateException("No formatter for pattern <" + datePattern + "> has been created.");\n }\n \n TemporalAccessor parsedResult = null;\n \n try {\n parsedResult = formatter.parse(dateString);\n } catch (DateTimeFormatterException ex) {\n // Ignore the exception, we don't care for it.\n return null;\n }\n \n if (!parsedResult.isSupported(ChronoField.DAYE_OF_MONTH)) {\n return YearMonth.from(parsedResult).atDay(1).atStartOfDay();\n } else {\n return LocalDate.of(parsedResult).atStartOfDay();\n }\n}\n</code></pre>\n<p>Now what we have done here is that we have ignored the <code>Exception</code> at a single point. Additionally, we've decoupled the presence of the day of the month in the parsed value from the length.</p>\n<p>Now let's return to your main logic:</p>\n<pre class=\"lang-java prettyprint-override\"><code>LocalDateTime localDateTime = null;\n\nswitch (dateString.length()) {\n case 6:\n localDateTime = parse(dateString, "MMyyyy");\n \n if (localDateTime == null) {\n localDateTime = parse(dateString, "yyyyMM");\n }\n break;\n \n case 7:\n localDateTime = parse(dateString, "yyyy-MM");\n \n if (localDateTime == null) {\n localDateTime = parse(dateString, "MM-yyyy");\n }\n break;\n \n case 8:\n localDateTime = parse(dateString, "MMddyyyy");\n \n if (localDateTime == null) {\n localDateTime = parse(dateString, "yyyyMMdd");\n }\n break;\n \n case 10:\n localDateTime = parse(dateString, "MM-dd-yyyy");\n \n if (localDateTime == null) {\n localDateTime = parse(dateString, "yyyy-MM-dd");\n }\n break;\n}\n\nreturn localDateTime;\n</code></pre>\n<p>With these simple changes, we see a pattern emerging. Yes, I dropped the check whether the hyphen is contained or not, it does not help to have it in one of the branches in none of the others, the parser will tell use whether it is valid or not.</p>\n<p>From the looks of it, it seems like we'll be able to shorten our logic considerably even more. We change our <code>parse</code> method to accept a given <code>DateTimeFormatter</code> and instead of the <code>datePattern</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (Entry<String, DateTimeFormatter> entry : FORMATTERS.entrySet()) {\n String format = entry.getKey();\n DateTimeFormatter formatter = entry.getValue();\n \n if (format.length() == dateString.length()) {\n LocalDateTime result = parse(dateString, formatter);\n \n if (result != null) {\n return result;\n }\n }\n}\n</code></pre>\n<p>Of course, that assumes that always formats are being used that match the length of the result, but as far as I can see that's a safe assumption.</p>\n<p>Last but not least, you can add safety checks to <code>parse</code> to make sure that the year 1100 is not misinterpreted as month, but it is very likely that you will never encounter such a date.</p>\n<p>Regarding your unit tests, they are insufficient in my opinion, you can make them a lot better with more examples. I'd suggest do add your won <code>assertion</code> method which allows you to write the tests quicker.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private void assertLocalDateTime(int expectedYear, int expectedMonth, LocalDateTime actualLocalDateTime) {\n assertLocalDateTime(expectedYear, expectedMonth, 1, actualLocalDateTime);\n}\n\nprivate void assertLocalDateTime(int expectedYear, int expectedMonth, int expectedDayOfMonth, LocalDateTime actualLocalDateTime) {\n Assertions.assertNotNull(actualLocalDateTime);\n Assertions.assertEquals(expectedYear, actualLocalDateTime.getYear());\n Assertions.assertEquals(expectedMonth, actualLocalDateTime.getMonth());\n Assertions.assertEquals(expectedDayOfMonth, actualLocalDateTime.getDayOfMonth());\n\n // TODO Assert midnight.\n}\n</code></pre>\n<p>With that your unit tests will look like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>@Test\npublic void parseDateMonthYear() {\n assertLocalDateTime(2010, 1, Parser.parseDate("012012"));\n assertLocalDateTime(2010, 12, Parser.parseDate("122012"));\n}\n\n@Test\npublic void parseDateYearMonth() {\n assertLocalDateTime(2010, 1, Parser.parseDate("201201"));\n assertLocalDateTime(2010, 12, Parser.parseDate("201212"));\n}\n</code></pre>\n<p>And so on...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:39:04.817",
"Id": "503277",
"Score": "0",
"body": "Thank you for the input, tried using the TemporalAccessor as you suggested, but it seemed to fail on simpler dates, 032007, 200703, 03122007. Anyway, I did get it working as you outlined with a few modifications around TemporalAccessor...Not sure, am I supposed to post the final solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:44:14.517",
"Id": "503280",
"Score": "0",
"body": "It failed because `TemporalAccessor` does only contain *certain* fields, for example for \"032007\" it only contains the month and year, and from that you can't build a `LocalDate`. That's why I took the detour in that case over `YearMonth`. And I had a typo in the logic there, it of course use `YearMonth` if no day is available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:45:59.107",
"Id": "503281",
"Score": "0",
"body": "Normally we don't post the revised code, as it adds nothing to the review process...and we're here for reviewing things (also, we might need to review your revised solution again, and so on...)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T12:39:42.417",
"Id": "255132",
"ParentId": "255111",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T20:58:28.967",
"Id": "255111",
"Score": "4",
"Tags": [
"java",
"datetime"
],
"Title": "Java - General purpose String to LocalDateTime parser"
}
|
255111
|
<h1>Flow Network Problem</h1>
<p>You've blown up the LAMBCHOP doomsday device and broken the bunnies out of Lambda's prison - and now you need to escape from the space station as quickly and as orderly as possible! The bunnies have all gathered in various locations throughout the station, and need to make their way towards the seemingly endless amount of escape pods positioned in other parts of the station. You need to get the numerous bunnies through the various rooms to the escape pods. Unfortunately, the corridors between the rooms can only fit so many bunnies at a time. What's more, many of the corridors were resized to accommodate the LAMBCHOP, so they vary in how many bunnies can move through them at a time.</p>
<p>Given the starting room numbers of the groups of bunnies, the room numbers of the escape pods, and how many bunnies can fit through at a time in each direction of every corridor in between, figure out how many bunnies can safely make it to the escape pods at a time at peak.</p>
<p>Write a function solution(entrances, exits, path) that takes an array of integers denoting where the groups of gathered bunnies are, an array of integers denoting where the escape pods are located, and an array of an array of integers of the corridors, returning the total number of bunnies that can get through at each time step as an int. The entrances and exits are disjoint and thus will never overlap. The path element path[A][B] = C describes that the corridor going from A to B can fit C bunnies at each time step. There are at most 50 rooms connected by the corridors and at most 2000000 bunnies that will fit at a time.</p>
<h3>Test Cases</h3>
<p><em>Input</em>: Solution.solution({0, 1}, {4, 5}, {{0, 0, 4, 6, 0, 0}, {0, 0, 5, 2, 0, 0}, {0, 0, 0, 0, 4, 4}, {0, 0, 0, 0, 6, 6}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}})
<em>Output</em>: 16</p>
<p><em>Input</em>: Solution.solution({0}, {3}, {{0, 7, 0, 0}, {0, 0, 6, 0}, {0, 0, 0, 8}, {9, 0, 0, 0}})
<em>Output</em>: 6</p>
<h1>Dinic's Algorithm Solution</h1>
<pre><code>import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.ArrayDeque;
import java.util.Arrays;
public class Solution {
private static final int INF = 20000;
private static class Edge {
public int from, to;
public Edge residual;
public int flow;
public final int capacity;
public Edge(int from, int to, int capacity) {
this.from = from;
this.to = to;
this.capacity = capacity;
}
public boolean isResidual() {
return capacity == 0;
}
public int remainingCapacity() {
return capacity - flow;
}
public void augment(int bottleNeck) {
flow += bottleNeck;
residual.flow -= bottleNeck;
}
}
private abstract static class NetworkFlowSolverBase {
// Inputs: n = number of nodes, s = source, t = sink
final int n, s, t;
// Indicates whether the network flow algorithm has ran. The solver only
// needs to run once because it always yields the same result.
protected boolean solved;
// The maximum flow. Calculated by calling the {@link #solve} method.
protected int maxFlow;
// The adjacency list representing the flow graph.
protected List<Edge>[] graph;
/**
* Creates an instance of a flow network solver. Use the {@link #addEdge} method to add edges to
* the graph.
*
* @param n - The number of nodes in the graph including s and t.
* @param s - The index of the source node, 0 <= s < n
* @param t - The index of the sink node, 0 <= t < n and t != s
*/
public NetworkFlowSolverBase(int n, int s, int t) {
this.n = n;
this.s = s;
this.t = t;
initializeEmptyFlowGraph();
}
// Constructs an empty graph with n nodes including s and t.
@SuppressWarnings("unchecked")
private void initializeEmptyFlowGraph() {
graph = new List[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Edge>();
}
}
/**
* Adds a directed edge (and its residual edge) to the flow graph.
*
* @param from - The index of the node the directed edge starts at.
* @param to - The index of the node the directed edge ends at.
* @param capacity - The capacity of the edge
*/
public void addEdge(int from, int to, int capacity ) {
if ( capacity <= 0 ) {
throw new IllegalArgumentException("Forward edge capacity <= 0");
}
Edge e1 = new Edge(from, to, capacity);
Edge e2 = new Edge(to, from, 0);
e1.residual = e2;
e2.residual = e1;
graph[from].add(e1);
graph[to].add(e2);
}
/**
* Returns the residual graph after the solver has been executed. This allows you to inspect the
* {@link Edge#flow} and {@link Edge#capacity} values of each edge. This is useful if you are
* debugging or want to figure out which edges were used during the max flow.
*/
public List<Edge>[] getGraph() {
execute();
return graph;
}
// Returns the maximum flow from the source to the sink.
public int getMaxFlow() {
execute();
return maxFlow;
}
// Wrapper method that ensures we only call solve() once
private void execute() {
if (solved) return;
solved = true;
solve();
}
// Method to implement which solves the network flow problem.
public abstract void solve();
}
private static class DinicsSolver extends NetworkFlowSolverBase {
private int[] level;
/**
* Creates an instance of a flow network solver.
*
* Use the {@link #addEdge} method to add edges to
* the graph.
*
* @param n - The number of nodes in the graph including
* source and sink nodes.
* @param s - The index of the source node,
* 0 <= s < n
* @param t - The index of the sink node,
* 0 <= t < n, t != s
*/
public DinicsSolver(int n, int s, int t) {
super(n, s, t);
level = new int[n];
}
@Override
public void solve() {
// next[i] indicates the next edge index to take in the adjacency list for node i. This is
// part
// of the Shimon Even and Alon Itai optimization of pruning deads ends as part of the DFS
// phase.
int[] next = new int[n];
while ( bfs() ) {
Arrays.fill(next, 0);
// Find max flow by adding all augmenting path flows.
for ( int f = dfs(s, next, INF); f != 0; f = dfs(s, next, INF)) {
maxFlow += f;
}
}
}
// Do a BFS from source to sink and compute the depth/level of each node
// which is the minimum number of edges from that node to the source.
private boolean bfs() {
Arrays.fill(level, -1);
Queue<Integer> q = new ArrayDeque<>(n);
q.offer(s);
level[s] = 0;
while ( !q.isEmpty() ) {
int node = q.poll();
for (Edge edge : graph[node]) {
if ( edge.remainingCapacity() > 0
&& level[edge.to] == -1) {
level[edge.to] = level[node] + 1;
q.offer(edge.to);
}
}
}
// Return whether we were able to reach the sink node.
return level[t] != -1;
}
private int dfs(int at, int[] next, int flow) {
if ( at == t ) {
return flow;
}
final int numEdges = graph[at].size();
while ( next[at] < numEdges ) {
Edge edge = graph[at].get(next[at]);
int cap = edge.remainingCapacity();
if ( cap > 0 && level[edge.to] == level[at] + 1) {
int bottleNeck = dfs(edge.to, next, flow > cap ? cap : flow);
if ( bottleNeck > 0 ) {
edge.augment(bottleNeck);
return bottleNeck;
}
}
next[at]++;
}
return 0;
}
}
public static int solution(int[] entrances, int[] exits, int[][] path) {
// Setup all nodes with an extra source and sink
int pathLen = path.length;
int totalNodes = pathLen + 2;
int source = totalNodes - 1;
int exit = totalNodes - 2;
NetworkFlowSolverBase solver;
solver = new DinicsSolver(totalNodes, source, exit);
// Add edges from source to entrances
for (int i : entrances) {
solver.addEdge(source, i, INF);
}
// Add edges from exists to sink
for (int j : exits) {
solver.addEdge(j, exit, INF);
}
int noExitNodes = pathLen-exits.length;
// Add edges with values > 0
for ( int i = 0; i <= noExitNodes; i++ ) {
for ( int j = 0; j < pathLen; j++ ) {
// Remove all exit rows as all exit rows
// contains 0 values
if ( path[i][j] > 0 ) {
solver.addEdge(i, j, path[i][j]);
}
}
}
return solver.getMaxFlow();
}
}
</code></pre>
<p><strong>Is there anymore optimization that can be done?</strong></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:03:49.650",
"Id": "255114",
"Score": "0",
"Tags": [
"java",
"performance"
],
"Title": "Dinic's Algorithm Implementation To Find Maximum Flow In A Flow Network"
}
|
255114
|
<p>Major Edit: I wish people threw in a comment regarding what they are expecting instead of downvoting this question. I am quite appreciative of constructive feedback. I know it is only 3 people out of 100 who have downvoted, but it still affects the poster's confidence and makes this forum unhelpful.</p>
<p>I am trying to solve <a href="https://www.hackerrank.com/challenges/torque-and-development/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=graphs" rel="nofollow noreferrer">this</a> Hackerank problem and some of my test cases are failing stating that the final answer is wrong. After going over a previous S.O <a href="https://stackoverflow.com/questions/57604159/hackerrank-roads-and-libraries-getting-wrong-answer-in-some-test-cases">question</a> for the same problem, my understanding is that HackerRank says that the answer is wrong if the code doesn't execute within the memory and time limit. I'd like to know how I can further optimize my code to reduce the run time and space complexity</p>
<pre><code>def roadsAndLibraries(n, c_lib, c_road, cities):
# The arguments to the function above are number of nodes (n), cost of a library and road (c_lib, c_road) and cities connected by an edge (cities)
graph = {}
count = 0
cc = []
visited = set()
#Adding all edges to create an Adjacency List using a dictionary
for source,dest in cities:
graph[source] = graph.get(source,[])+[dest]
graph[dest] = graph.get(dest, []) + [source]
#There is a weird condition in Hackerrank wherein the number of nodes (n) in the input can be greater than the max(cities). In that case, one needs to consider the additional nodes as an independent graph in a forest.
if max(graph, key = int)<n:
for i in range(max(graph, key = int)+1,n+1):
graph[i]=[]
# Generic Depth First Search
def depth_first_search(graph, visited, node, temp):
if node not in visited:
visited.add(node)
temp.add(node)
if node in graph:
for neighbor in graph[node]:
depth_first_search(graph, visited, neighbor, temp)
return temp
#Identify Connected Components using a Depth First Search.
#These Connected Components will subsequentially used to calculate the cost
def connected_components(graph, visited):
for key in graph:
#print("Key = ", key)
if key not in visited:
temp = set()
cc.append(depth_first_search(graph, visited, key, temp))
return cc
connected_components(graph, visited)
#Return final cost over here
cost = 0
if c_road>c_lib:
return n*c_lib
else:
for each in cc:
cost += c_lib + (len(each)-1)*c_road
return cost
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:50:47.393",
"Id": "503232",
"Score": "0",
"body": "The output information of each failed test case on HackerRank explicitly tells you whether it fails due to \"Wrong answer\" or \"Time limit exceeded\". You should check that rather than guessing the cause of failure. As a side remark, \"Time limit exceeded\" can be caused by both non-terminating and inefficient algorithm implementations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T00:08:50.270",
"Id": "503235",
"Score": "0",
"body": "Well my implementation passes the base test cases. Also the discussion sections are filled with people say that an unoptimized algorithm /unsuitable variable types returns a wrong answer instead of timeout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T00:10:11.733",
"Id": "503236",
"Score": "0",
"body": "By unsuitable variable types I mean using an int instead of long. I am not sure how to specify it here though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T04:32:13.613",
"Id": "503239",
"Score": "0",
"body": "\"Time limit exceeded\" means your program does not terminate within the time limit (10s for Python 2 / Python 3), regardless of whether it is correct or not. \"Wrong answer\" means your program terminates with an exception or without the expected answer in standard output. You can view that information for every test case that your submission went through, not only the base test cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T05:53:43.877",
"Id": "503245",
"Score": "2",
"body": "Welcome to CodeReview@SE. Consider tagging [tag:programming-challenge]. Most of those contain test cases carefully crafted to exceed a reasonable time limit unless using a decent [tag:algorithm] - improving how it is coded is a secondary concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T06:05:27.093",
"Id": "503247",
"Score": "0",
"body": "Thank you @greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T11:29:38.330",
"Id": "503255",
"Score": "0",
"body": "What in that other question makes you think that \"HackerRank says that the answer is wrong if the code doesn't execute within the time limit\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T11:43:12.087",
"Id": "503256",
"Score": "0",
"body": "I guess I was wrong. It was the memory and time limit that was affecting my answer. I will update the question accordingly @superbrain"
}
] |
[
{
"body": "<p>As Hackerank already told you, your solution is <em>wrong</em> (failing 7 out of 13 test cases). Which should make your question off-topic, not sure how to judge your pretending that they say that incorrectly.</p>\n<p>For example, you fail <code>roadsAndLibraries(3, 1, 1, [[2, 3]])</code> by returning <code>2</code> instead of <code>3</code>. What you call "weird" is just unconnected cities. And it can happen for small-numbered cities as well. In my example, it's city 1 that's unconnected. Which you don't handle because you assume that it's always the largest-numbered cities that are unconnected.</p>\n<p>If you simply start with <code>graph = {i: [] for i in range(1, n+1)}</code>, you succeed. Then you also don't need your own half-way special treatment for the "weird" unconnected cities.</p>\n<p>Also, use <code>append</code> to grow the lists so you have linear instead of quadratic runtime.</p>\n<pre><code> for source,dest in cities:\n graph[source].append(dest)\n graph[dest].append(source)\n</code></pre>\n<p>Alternatively, remove your half-way special treatment and add <code>(n - len(visited)) * c_lib</code> to the return value at the end, in order to put libraries in the not-visited (because unconnected) cities.</p>\n<p>Or as yet another alternative fix, you could fix your half-way special treatment to fill in <em>all</em> unconnected cities at that point:</p>\n<pre><code> for i in range(1, n+1):\n graph[i] = graph.get(i, [])\n</code></pre>\n<p>But I'd say <em>that</em> would be weird :-). It's simpler to just initialize all with an empty list at the start, <em>before</em> building the graph from the edges. And that's also better because it allows those simple <code>append</code>s.</p>\n<h3>Improved solution</h3>\n<p>Same basic idea, of course, placing one library in each connected component, unless libraries don't cost more than roads:</p>\n<pre><code>def roadsAndLibraries(n, c_lib, c_road, cities):\n if c_lib <= c_road:\n return n * c_lib\n\n graph = {u: [] for u in range(1, n+1)}\n for u, v in cities:\n graph[u].append(v)\n graph[v].append(u)\n \n def delete(u):\n for v in graph.pop(u, []):\n delete(v)\n\n connected_components = 0\n for u in range(1, n+1):\n if u in graph:\n connected_components += 1\n delete(u)\n \n return connected_components * c_lib + (n - connected_components) * c_road\n</code></pre>\n<p>Note:</p>\n<ul>\n<li>I handle <code>c_lib <= c_road</code> (and not just <code><</code>) right at the start. No need to get to work on the graph at all if we're going to ignore that whole work anyway.</li>\n<li>I just count the connected components, don't keep track of each component's cities. In the end we just cover <code>connected_components</code> cities with libraries and the remaining <code>n - connected_components</code> with roads. Simple formula.</li>\n<li>The roads are bidirectional and the problem calls the connected cities "u" and "v", not "source" and "dest". So both for consistency with the problem and for not implying a direction, I used <code>u</code> and <code>v</code> as well (ok ok, I also like short standard names for brevity).</li>\n<li>If I build the graph, I can tear it down. No need for an extra <code>visited</code>.</li>\n<li>No need to pass <code>graph</code> through the <code>delete</code> calls as argument. (And in yours, neither your <code>depth_first_search</code> nor your <code>connected_components</code> would've needed <code>graph</code> and <code>visited</code> as parameters).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:20:05.097",
"Id": "503435",
"Score": "0",
"body": "Thank you. Here is why I initially thought it was a glitch in Hackerank and not my fault - \"My logic was totally correct the thing where I wasn't able to guess what was happening is that HACKERRANK handles OutOfMemoryException badly, they show wrong answer instead of showing that exception\". I found this on StackOverflow (https://stackoverflow.com/questions/57604159/hackerrank-roads-and-libraries-getting-wrong-answer-in-some-test-cases) and also got this vibe in the discussions board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:26:25.197",
"Id": "503436",
"Score": "1",
"body": "@desert_ranger Well that other person had an OutOfMemoryException, clearly from their adjacency matrix (of size n\\*n). You had nothing like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:27:06.220",
"Id": "503437",
"Score": "0",
"body": "Agreed. My bad :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:30:01.440",
"Id": "503461",
"Score": "1",
"body": "`graph[i] = graph.get(i, [])` could be replaced with `graph.setdefault(i, [])`. The graph initialization could use `graph = collections.defaultdict(list)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T11:06:56.540",
"Id": "503471",
"Score": "1",
"body": "@GZ0 Yeah, I just did it that way for consistency with their other `get`s. I could've suggested a few more improvements, but the main issue was resolved and it was already late at night :-). Plus that was my least favorite fix anyway, the one I called \"weird\", and I didn't really care about making something better that can't be good anyway. Oh well... I added an improved solution now with some notes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T12:59:34.347",
"Id": "503476",
"Score": "0",
"body": "Hmm, I'm quite curious how someone voted \"This answer is not useful\" after it pointed out that the solution was indeed wrong, what was wrong, how to fix it, pointed out the quadratic runtime and how to fix it, and had already been accepted and upvoted two or three times. How does one justify declaring that \"not useful\"?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T00:40:20.757",
"Id": "255194",
"ParentId": "255117",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255194",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:53:58.980",
"Id": "255117",
"Score": "-3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"graph"
],
"Title": "HackerRank | Roads and Libraries - Code Optimization"
}
|
255117
|
<p>Not a professional coder, but my current hospital position is allowing me to code some workarounds for our abysmal EHR system. The following is part of my Python project to visualize laboratory data.</p>
<p>The following code snippet works, but I haven't figured out a way with list comprehensions or <code>np.where</code> to streamline it and potentially improve performance. I haven't found any posts yet to answer this, including among those suggested during question submission.</p>
<p>This code tests tuple[0] in a list of tuples (<code>test_and_value</code>) comprising (lab test names, test values), searching for misspelled lab test names and replacing them with standardized lab test names.</p>
<p>Common misspellings and their replacement terms live in another list of tuples (chem_fix) to preserve the order in which they are checked. Some word fragments of misspellings are used in lieu of full words, therefore testing cannot be a simple <code>==</code> statement.</p>
<p>Final product is a list of tuples, <code>test_and_value_f</code>, with correctly spelled lab tests.</p>
<p>Pertinent code excerpts:</p>
<pre><code>chem_fix = [('A/G RATIO', 'A:G RATIO'), ('ALK', 'ALKALINE PHOSPHATASE'), ('ALT', 'ALT'), ('AST', 'AST'), ('BILI', 'BILIRUBIN,TOTAL'), ('BLIL', 'BILIRUBIN,TOTAL'), ('BUN/CREAT', 'BUN/CREAT RATIO'), ('BUN', 'BLOOD UREA NITROGEN'), ('CARBON', 'CO2'), ('GLOB', 'GLOBULIN'), ('RANDOM', 'GLUCOSE'), ('PROTEIN', 'TOTAL PROTEIN')]
fix_terms = [x[0] for x in chem_fix]
test_and_value_f = []
replaced = False
for lab_test, value in test_and_value:
for count, term_needing_fix in enumerate(fix_terms):
if term_needing_fix in lab_test:
test_and_value_f.append((chem_fix[count][1], value))
replaced = True
break
if replaced == False:
test_and_value_f.append((lab_test, value))
else:
replaced = False
</code></pre>
<p>Sample <code>test_and_value</code> input: [('GLUCOSE', '77'), ('BUN', '14'), ('CREATININE', '1.4'), ('CALCULATED BUN/CREAT', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CARBON DIOXIDE', '30'), ('CALCIUM', '8.9'), ('PROTEIN, TOTAL', '6.5'), ('ALBUMIN', '3.4'), ('CALCULATED GLOBIN', '3.1'), ('CALCULATED A/G RATIO', '1.1'), ('BILIRUBIN, TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('SGOT (AST)', '3')]</p>
<p>Sample <code>test_and_value_f</code> output: [('GLUCOSE', '77'), ('BLOOD UREA NITROGEN', '14'), ('CREATININE', '1.4'), ('BUN/CREAT RATIO', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CO2', '30'), ('CALCIUM', '8.9'), ('TOTAL PROTEIN', '6.5'), ('ALBUMIN', '3.4'), ('GLOBULIN', '3.1'), ('A:G RATIO', '1.1'), ('BILIRUBIN,TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('AST', '3')]</p>
<p>Is there a more efficient way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T05:46:55.827",
"Id": "503244",
"Score": "1",
"body": "(One user suggested adding tag [tag:python-3.x].)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T06:01:28.820",
"Id": "503246",
"Score": "2",
"body": "Can you provide an example of the input (`test_and_value`) and the expected output? I think it will help reviewers"
}
] |
[
{
"body": "<p>You could use a dictionary instead of a list of tuples for <code>chem_fix</code>, and then you could get rid of fix_terms. Then you could use <code>search</code> from the re module in the list comprehension and then look up any matches in the dictionary. And you can use walrus operator to store whatever is returned from <code>search</code> since first you have to make sure it’s not <code>None</code>. Here’s an example of that:</p>\n<pre class=\"lang-py prettyprint-override\"><code># there’s already a function called “compile”\n# “import re” used so it doesn’t get overwritten\npattern = re.compile('|'.join(chem_fix))\npattern_search = pattern.search # method will be looked up faster\ntest_and_value_f = [\n (\n chem_fix[m.group(0)]\n if (m := pattern_search(lab_test)) is not None\n else lab_test,\n value\n )\n for lab_test, value in test_and_value\n]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T04:51:57.200",
"Id": "503240",
"Score": "0",
"body": "Chose list of tuples to retain order in which checking occurs. Do I need to use an ordered dict, or will the order be retained in a regular dict (running Python 3.9) Was reading 3.6+ is supposed to retain insertion order? [link](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T05:02:16.340",
"Id": "503241",
"Score": "2",
"body": "Yeah a regular dict should keep its insertion order if it’s 3.9. So the `\"|\".join` will return a string with the terms in the same order as what’s in the dictionary, so you shouldn’t have to write the pattern manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T17:28:14.367",
"Id": "503287",
"Score": "1",
"body": "Since `value` is the same in both branches, your `else` could apply on the inside of the output tuple to the first element only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T20:23:51.973",
"Id": "503322",
"Score": "0",
"body": "Had to manually deconstruct this with some test code to understand how everything fit together. \n\nLearned: 1) how to use if/else within a list comprehension to determine the values of tuple[0] within a list of tuples 2) .join on a dict joins the keys 3) walrus operator"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T00:20:22.960",
"Id": "255121",
"ParentId": "255120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255121",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:54:03.833",
"Id": "255120",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Find and replace strings in the first column of data"
}
|
255120
|
<p>A parallel map written in Rust. I am new to Rust and wondering if there is things that could be done better or more efficiently.</p>
<pre><code>use crossbeam_channel::unbounded;
use std::{thread, time};
fn parallel_map<T, U, F>(mut input_vec: Vec<T>, num_threads: usize, f: F) -> Vec<U>
where
F: FnOnce(T) -> U + Send + Copy + 'static,
T: Send + 'static,
U: Send + 'static + Default,
{
let mut output_vec: Vec<U> = Vec::with_capacity(input_vec.len());
let mut threads = Vec::new();
let (in_s, in_r) = unbounded::<(T, usize)>();
let (out_s, out_r) = unbounded::<(U, usize)>();
for _ in 0..num_threads {
let in_r = in_r.clone();
let out_s = out_s.clone();
threads.push(thread::spawn(move || {
while let Ok((value, index)) = in_r.recv() {
let res = f(value);
out_s.send((res, index)).expect("Failed to send");
}
}));
}
while let Some(val) = input_vec.pop() {
in_s.send((val, input_vec.len())).expect("Failed to send");
}
drop(in_s);
drop(out_s);
let mut collect_results: Vec<(U, usize)> = Vec::with_capacity(output_vec.capacity());
while let Ok(res) = out_r.recv() {
collect_results.push(res);
}
collect_results.sort_by(|(_, a_index), (_, b_index)| a_index.partial_cmp(b_index).unwrap());
output_vec.extend(collect_results.into_iter().map(|(val, _)| val));
for thread in threads {
thread.join().expect("Failed to join thread");
}
output_vec
}
fn main() {
let v = vec![6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 12, 18, 11, 5, 20];
let squares = parallel_map(v, 10, |num| {
println!("{} squared is {}", num, num * num);
thread::sleep(time::Duration::from_millis(500));
num * num
});
println!("squares: {:?}", squares);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The crate <a href=\"https://docs.rs/rayon/1.5.0/rayon/\" rel=\"nofollow noreferrer\"><code>rayon</code></a> implements similar functionality:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use rayon::prelude::*;\n\nlet mut par_iter = (0..5).into_par_iter().map(|x| x * x);\n\nlet squares: Vec<_> = par_iter.collect();\n</code></pre>\n<p>In your solution, the multithreading part looks OK.</p>\n<p>The part where you collect results could be done more efficiently. Specifically, one alloc and data copy could be avoided with use of a little unsafety.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut output_vec: Vec<U> = Vec::with_capacity(initial_len);\nunsafe {\n output_vec.set_len(initial_len);\n}\nwhile let Ok((res, index)) = out_r.recv() {\n let old = mem::replace(&mut output_vec[index], res);\n mem::forget(old);\n}\n</code></pre>\n<p>Same optimization could be done a little more succintly with <code>ptr::write</code>. Further, you may need to assert that <code>output_vec</code> has correct length, and <code>forget</code> the vec beforehand in case the assertion fails. My concern is that above proposed code is not protected against incorrect drops if <code>U</code> has a destructor and code <code>panic</code>s.</p>\n<p>Your bound of <code>U</code> as <code>Default</code> appears to be unnecessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T12:49:46.610",
"Id": "255133",
"ParentId": "255122",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T01:42:35.623",
"Id": "255122",
"Score": "1",
"Tags": [
"multithreading",
"rust"
],
"Title": "Parallel map in Rust"
}
|
255122
|
<p>I have over 17,000 pages that have been scanned (for a local history archive) which I have OCRed using Tesseract to individual TXT files. I want to be able to search/locate every page containing a search word of more than 3, lower case letters. So for each TXT file I need to:</p>
<ul>
<li><p>Delete all rubbish from the OCR text i.e. non-alphanumeric characters:
<code>jrepl "[^a-zA-Z0-9\s]" "" /x /f %%G /O -</code></p>
</li>
<li><p>Remove 1, 2 and 3 letter words: <code>jrepl "\b\w{1,3}\b" "" /x /f %%G /O -</code></p>
</li>
<li><p>Change all characters to lower case: <code>jrepl "(\w)" "$1.toLowerCase()" /i /j /x /f %%G /O -</code></p>
</li>
<li><p>To be able to sort the remaining words they need to be on separate new lines: <code>jrepl "\s" "\n" /x /f %%G /O -</code></p>
</li>
<li><p>Finally sort all unique words into alphabetic order and create the modified TXT file: <code>sort /UNIQUE %%G /O %%G</code></p>
</li>
</ul>
<p>I have a batch file that does the above using JREPL but it is very slow. It has been running for over 100 HOURS and I'm not even half way. Any suggestions so as to speed up the processing? I am running Windows 10.</p>
<p>This is the Batch file I am running:</p>
<pre><code>Setlocal EnableDelayedExpansion
for %%G in (*.txt) do (
set old=%%G
echo !old!
@echo on
rem remove non-alphanumeric
call jrepl "[^a-zA-Z0-9\s]" "" /x /f %%G /O -
rem remove 1, 2 and 3 letter words
call jrepl "\b\w{1,3}\b" "" /x /f %%G /O -
rem all to lowercase
call jrepl "(\w)" "$1.toLowerCase()" /i /j /x /f %%G /O -
rem replace spaces with new lines
call jrepl "\s" "\n" /x /f %%G /O -
rem reduce to unique words
sort /UNIQUE %%G /O %%G
)
pause
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:09:03.083",
"Id": "503330",
"Score": "0",
"body": "in my test the conversion to lowercase is done by sort automaticly and you could try to replace non-alphanumeric, <=3 letter words and spaces to \\n in one go `([^a-zA-Z0-9]|\\s|\\b\\w{1,3}\\b)+`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:17:07.070",
"Id": "503331",
"Score": "0",
"body": "Correction: only the uniqueness is case independent, you get one version picked out."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T08:35:47.750",
"Id": "255127",
"Score": "3",
"Tags": [
"regex",
"batch"
],
"Title": "Request for help to speed up batch program for 17,000 TXT files"
}
|
255127
|
<p>I want to test a number of different functions I have written to solve the Fizzbuzz challenge and would like to know what is the best way to check the result?</p>
<p>Each function returns a list of the answers and I want to check the list is correct. One of the functions is shown below</p>
<pre><code>def fizz_buzz_using_boolean():
fizz_buzz_list = []
for x in range(1, 101):
fizz = x % 3 == 0
buzz = x % 5 == 0
if fizz and buzz:
fizz_buzz_list.append('fizzbuzz')
continue
elif fizz:
fizz_buzz_list.append('fizz')
continue
elif buzz:
fizz_buzz_list.append('buzz')
continue
else:
fizz_buzz_list.append(x)
return fizz_buzz_list
</code></pre>
<p>My tests look like this:</p>
<pre><code>import pytest
from fizz_buzz import fizz_buzz_if_calc, fizz_buzz_using_boolean
@pytest.fixture
def fizzbuzz_expected_answer():
"""A list of the fizzbuzz answers for 1 - 100"""
fizz_buzz = [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']
return fizz_buzz
def test_fizz_buzz_using_boolean_has_correct_items(fizzbuzz_expected_answer):
actual = fizz_buzz_using_boolean()
assert actual == fizzbuzz_expected_answer
</code></pre>
<p>I have used a fixture to return the correct answer. Whilst the tests pass I can't find other examples of fixtures being used this way.</p>
<p>The other solutions come to mind is to use a global</p>
<pre><code>import pytest
from fizz_buzz import fizz_buzz_if_calc, fizz_buzz_using_boolean
FIZZBUZZ_EXPECTED_ANSWER = [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']
def test_fizz_buzz_using_boolean_has_correct_items():
actual = fizz_buzz_using_boolean()
assert actual == FIZZBUZZ_EXPECTED_ANSWER
</code></pre>
<p>Or my least favourite to use a literal in each test (which will lead to lots of duplicatation)</p>
<pre><code>def test_fizz_buzz_using_boolean_has_correct_items():
actual = fizz_buzz_using_boolean()
assert actual == [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']
</code></pre>
<p>Which method should I use?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:22:40.753",
"Id": "503266",
"Score": "0",
"body": "When you say \"Best\" what are you trying to optimize? Performance? Memory usage? You need to be clear to yourself and to the people reviewing the code about what your goal is, otherwise any answers you get will be very opinion based and not necessarily fact based."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:28:35.870",
"Id": "503267",
"Score": "0",
"body": "Apologies I should have used standard rather than best. Resource usage is not a factor in these tests. I am looking to see if there is a standard way of checking the assert. If you were reviewing my code and saw I had used fixtures in this way would you think WTF is going on here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:34:27.563",
"Id": "503268",
"Score": "0",
"body": "I'm not a python expert and can't really review the code, it just seemed to me that the question lacked focus. Have you actually implemented this and is it working? That is a requirement for the code review site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:35:52.310",
"Id": "503269",
"Score": "0",
"body": "Yeah I know. Perhaps read the question and see where I have said.....Whilst the tests pass I can't find other examples of fixtures being used this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:30:56.550",
"Id": "503452",
"Score": "0",
"body": "\"Which method should I use?\" It's Fizzbuzz. It matters not. Do you want all 3 versions reviewed? Fixtures certainly make sense sometimes, but it's impossible to tell you whether they'll help you in production without seeing the production code. Fizzbuzz is a programming exercise. It helps with practicing new designs, but it's impossible to tell you which to use simply based on the exercise. Please state the goal of the question keeping this in mind. If you're not actually looking for a review, there's not much we can help you with. Please take a look at the [help/on-topic] as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:32:40.133",
"Id": "503453",
"Score": "0",
"body": "In short: sure, we can review your Fizzbuzz. But a review may not be what you actually want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T10:01:52.673",
"Id": "503464",
"Score": "0",
"body": "@Mast Correct, a review of Fizzbuzz is not what I want. I am looking for a review of the unit test I have written and if using fixtures to retrieve the expected values is acceptable and I wasn't veering off course. From your comment it looks like they can be used in this way and I appreciate it depends on various factors."
}
] |
[
{
"body": "<p>I don't do much python, but I do find your use of a fixture to return the answer a little bizarre. For me, having the actual string in the test would be the way to go. As I understand it, what you don't like about doing this is that you end up with multiple tests, all of which are calling different implementations and then verifying that the implementation returns the same thing. This sounds like something you might want to use a parameterized test for. Rather than passing in the changing data though (since it's the same), you'd parameterize the method under test:</p>\n<pre><code>@pytest.mark.parametrize("fizzbuzzer", \n [fizz_buzz_if_calc, fizz_buzz_using_boolean])\ndef test_fizz_buzz_has_correct_items(fizzbuzzer):\n\n actual = fizzbuzzer()\n\n assert actual == [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']\n</code></pre>\n<p>If the test fails, then you get an indication as to which failed as part of the test name and the follow up information:</p>\n<pre><code>________________________________ test_fizz_buzz_has_correct_items[fizz_buzz_if_calc] _________________________________\n\nfizzbuzzer = <function fizz_buzz_if_calc at 0x7f2ff2bbab80>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-25T21:47:32.710",
"Id": "257695",
"ParentId": "255134",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T13:14:52.153",
"Id": "255134",
"Score": "2",
"Tags": [
"python",
"unit-testing"
],
"Title": "Using pytest fixtures for the expected answers to a test?"
}
|
255134
|
<p>I have this Library to control errors; I would like if you can evaluate it and make a review <strong>of the code</strong>, not about the goals of the library:</p>
<p>Everything works for me correctly, but I am also open to hear about any type of improvement that can be implemented in the code as long as it does <strong>not affect the objective of the library</strong>.</p>
<hr />
<p><strong>Introduction:</strong></p>
<p><em><strong>What does [BEH] do?</strong></em>
[BEH] is a very simple PHP error handler implementation that throws ErrorException exceptions instead of using the default PHP error handling behaviour. This means that all runtime errors including Fatal are presented to the developer in the form of an exception. It also means that any unhandled errors are delivered to a single point: the global exception handler. also includes support for login errors with error document</p>
<p><em><strong>Why use [BEH]?</strong></em>
Developers need the ability to decide how their code behaves when an error occurs. Exceptions offer the only truly consistent way to report and recover from errors in PHP.</p>
<p>This method of handling errors has proven to be extremely effective. Similar strategies are used in major PHP frameworks such as [Laravel]. [BEH] is a standalone implementation that can be used for any project, and not required third party library or software.</p>
<hr />
<p><strong>Usage:</strong>
<em><strong>[BEH] Configuration:</strong></em></p>
<ul>
<li>.htaccess: for Apache Version > 2.4.</li>
<li>.user.ini: for CGI/FPM/FastCGI.</li>
<li>error_conf.php: common configuration.
Note: not tested in NGINX</li>
</ul>
<p><em><strong>Custom [BEH] for PHP And Server Error</strong></em>
It must be configured manually in: .htaccess, .user.ini and conf.json depending on the scenario or desired host configuration; let's leave some examples:</p>
<ul>
<li>Single host server.</li>
<li>Virtual Host and name of the github project.</li>
<li>Development with Xampp in Locally or other stack</li>
</ul>
<p><em><strong>.htaccess</strong></em></p>
<pre><code># php_value auto_prepend_file "/var/www/html/error/init_error.php"
# php_value auto_prepend_file "/var/www/virtual-hostc/git-hub-project-name/error/init_error.php"
php_value auto_prepend_file "C:/xampp/htdocs/error/error_init.php"
Note: because of dependencies you must set the configuration inside <IfModule mod_php7.c> to work correctly; .htaccess file have an example
</code></pre>
<p><em><strong>.user.ini</strong></em></p>
<pre><code># auto_prepend_file = "/var/www/html/error/init_error.php"
# auto_prepend_file = "/var/www/virtual-host/git-hub-project-name/error/init_error.php"
auto_prepend_file = "C:/xampp/htdocs/error/error_init.php"
</code></pre>
<p><em>note: .user.ini files not use php_value statement.</em></p>
<pre><code>Error Server must be setting up with directive in .htaccess file:
ErrorDocument 400 /error/error_server.php
Error_conf.php
</code></pre>
<p><em><strong>skin of [BEH] must be: basic, bs4, custom.</strong></em></p>
<p><em><strong>Custom skin [BEH]</strong></em>
you must implement two files skin like.</p>
<pre><code>sk_custom_server_error.php
sk_custom_handler_error.php
</code></pre>
<p><em><strong>Content of skin for [BEH]</strong></em>
you must add the same variable print like basic skin, but you can use your own html design.</p>
<p>Skin are located in <a href="https://github.com/arcanisgk/BEH-Basic-Error-Handler/tree/main/error/skin" rel="nofollow noreferrer">Skin</a></p>
<hr />
<p><em><strong>Project Structure</strong></em></p>
<p><a href="https://i.stack.imgur.com/6eZiQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6eZiQ.png" alt="structure" /></a></p>
<hr />
<p><strong><a href="https://github.com/arcanisgk/BEH-Basic-Error-Handler" rel="nofollow noreferrer">Resource Code:</a></strong></p>
<p><em>.htaccess File</em></p>
<pre><code><Files .user.ini>
deny from all
</Files>
<Files *error.php>
deny from all
</Files>
<Files server_error.php>
Order Deny,Allow
Allow from all
</Files>
<IfModule mod_php7.c>
#php_value auto_prepend_file "/var/www/html/test1/error/init_error.php"
php_value auto_prepend_file "C:/xampp/htdocs/dev/t2/BEH-Basic-Error-Handler/error/init_error.php"
</IfModule>
ErrorDocument 400 /error/server_error.php
ErrorDocument 401 /error/server_error.php
ErrorDocument 402 /error/server_error.php
ErrorDocument 403 /error/server_error.php
ErrorDocument 404 /error/server_error.php
ErrorDocument 405 /error/server_error.php
ErrorDocument 406 /error/server_error.php
ErrorDocument 407 /error/server_error.php
ErrorDocument 408 /error/server_error.php
ErrorDocument 409 /error/server_error.php
ErrorDocument 410 /error/server_error.php
ErrorDocument 411 /error/server_error.php
ErrorDocument 412 /error/server_error.php
ErrorDocument 413 /error/server_error.php
ErrorDocument 414 /error/server_error.php
ErrorDocument 415 /error/server_error.php
ErrorDocument 500 /error/server_error.php
ErrorDocument 501 /error/server_error.php
ErrorDocument 502 /error/server_error.php
ErrorDocument 503 /error/server_error.php
ErrorDocument 504 /error/server_error.php
ErrorDocument 505 /error/server_error.php
</code></pre>
<p><em>.user.ini File</em></p>
<pre><code>auto_prepend_file = "/var/www/html/test1/error/init_error.php"
</code></pre>
<p><em>index.php</em></p>
<pre><code><?php
ob_start();
# error Example:
require_once 'test.php';
$test = new Test();
$test->testMethod();
echo '<br>No problem Detected.<br>Go to test.php and uncomment examples in test Method';
</code></pre>
<p><em>test.php</em></p>
<pre><code><?php
class Test
{
/** @noinspection PhpUnhandledExceptionInspection */
public function testMethod()
{
# TODO Test 1: Uncomment to get an Error Output
echo $foo;
# TODO Test 2: Uncomment to get an throw exception Output
#throw new Exception('This is an Example of throw Exception');
# TODO Test 3: Uncomment to get an shutdown Output
#set_time_limit(1);
#while (true) {
#}
}
}
</code></pre>
<p><em>conf_error.php</em></p>
<pre><code><?php
$conf = [
'skin' => 'bs4',
'error' => 'auto',
];
</code></pre>
<p><em>init_error.php</em></p>
<pre><code><?php
try {
if (ini_set('session.gc_maxlifetime', '0') === false) {
throw new Exception('Unable to set session.gc_maxlifetime.');
}
if (ini_set('session.use_only_cookies', '1') === false) {
throw new Exception('Unable to set session.use_only_cookies.');
}
if (ini_set('session.cookie_httponly', '1') === false) {
throw new Exception('Unable to set session.cookie_httponly.');
}
if (ini_set('error_reporting', '1') === false) {
throw new Exception('Unable to set error_reporting.');
}
if (ini_set('display_errors', '0') === false) {
throw new Exception('Unable to set display_errors.');
}
} catch (Exception $e) {
echo 'Exception catch: ', $e->getMessage(), "\n";
}
error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'] . '/error/handler_error.php';
</code></pre>
<p><em>server_error.php</em></p>
<pre><code><?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/error/conf_error.php';
$error_text = 'Unknown Error';
$code = $_SERVER['REDIRECT_STATUS'];
$codes = [
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'URI Too Long',
415 => 'Unsupported Media Type',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
];
$source_url = 'http' . ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if (array_key_exists($code, $codes) && is_numeric($code)) {
$error_text = $codes[$code];
}
/** @var array $conf */
$error_skin = $_SERVER['DOCUMENT_ROOT'] . '/error/skin/sk_' . $conf['skin'] . '_server_error.php';
if (file_exists($error_skin)) {
/** @noinspection PhpIncludeInspection */
require_once $error_skin;
} else {
require_once $_SERVER['DOCUMENT_ROOT'] . '/error/skin/sk_basic_server_error.php';
}
die;
</code></pre>
<p><em>handler_error.php</em></p>
<pre><code><?php
declare(strict_types=1);
namespace IcarosNet\BEHBasicErrorHandler;
class HandlerError
{
private static ?HandlerError $instance = null;
public function __construct()
{
register_shutdown_function([$this, "shutdownHandler"]);
set_exception_handler([$this, "exceptionHandler"]);
set_error_handler([$this, "errorHandler"]);
}
public function shutdownHandler()
{
$error = error_get_last();
if (null != $error) {
$this->CleanOutput();
$error_type = 'ShutdownHandler';
$error_level = $error['type'];
$error_desc = $error['message'];
$error_file = $error['file'];
$error_line = $error['line'];
$error_trace = array_reverse(debug_backtrace());
array_pop($error_trace);
$error_trace_smg = $this->getBacktrace($error_trace, $error_type);
$this->output($error_type, $error_level, $error_desc, $error_file, $error_line, $error_trace_smg);
}
}
public function exceptionHandler($e)
{
$this->CleanOutput();
$error_type = 'ExceptionHandler';
$error_level = ($e->getCode() == 0 ? 'Not Set' : $e->getCode());
$error_desc = $e->getMessage();
$error_file = $e->getFile();
$error_line = $e->getLine();
$error_trace = $e->getTrace();
$error_trace_smg = $this->getBacktrace($error_trace, $error_type);
$this->output($error_type, $error_level, $error_desc, $error_file, $error_line, $error_trace_smg);
}
public function errorHandler($error_level = null, $error_desc = null, $error_file = null, $error_line = null)
{
$this->CleanOutput();
$error_type = 'ErrorHandler';
$error_trace = array_reverse(debug_backtrace());
array_pop($error_trace);
$error_trace_smg = $this->getBacktrace($error_trace, $error_type);
$this->output($error_type, $error_level, $error_desc, $error_file, $error_line, $error_trace_smg);
}
private function getBacktrace($error_trace, $error_type)
{
$error_trace_smg = '';
if (!empty($error_trace)) {
foreach ($error_trace as $track) {
$error_trace_smg .= ' ' . (isset($track['file']) ? $track['file'] : '<unknown file>') . ' ' . (isset($track['line']) ? $track['line'] : '<unknown line>') . ' calling Method: ' . $track['function'] . '()' . PHP_EOL;
}
} else {
$error_trace_smg = 'No backtrace data in the ' . $error_type . '.';
}
return $error_trace_smg;
}
/**
* @param $error_type
* @param $error_level
* @param $error_desc
* @param $error_file
* @param $error_line
* @param $error_trace_smg
*/
private function output($error_type, $error_level, $error_desc, $error_file, $error_line, $error_trace_smg)
{
$conf = [];
require_once $_SERVER['DOCUMENT_ROOT'] . '/error/conf_error.php';
$out_type = $this->getRQType($conf['error']);
if ($out_type == 'plain') {
/** @var array $conf */
$error_skin = $_SERVER['DOCUMENT_ROOT'] . '/error/skin/sk_' . $conf['skin'] . '_handler_error.php';
//header('content-type: text/plain');
if (file_exists($error_skin)) {
/** @noinspection PhpIncludeInspection */
require_once $error_skin;
} else {
require_once $_SERVER['DOCUMENT_ROOT'] . '/error/skin/sk_basic_handler_error.php';
}
} else {
header('Content-Type: application/json');
echo json_encode(
[
'error_type' => $error_type,
'error_level' => $error_level,
'error_desc' => $error_desc,
'error_file' => $error_file,
'error_line' => $error_line,
'error_trace_smg' => $error_trace_smg,
]
);
}
$this->clearLastError();
}
private function cleanOutput()
{
ob_end_clean();
flush();
}
private function clearLastError()
{
error_clear_last();
exit();
}
private function getRQType($error)
{
/** @var string $error */
if ($error == 'auto') {
if (isset($_POST) && !empty($_POST)) {
return (count($_POST) > 1 ? 'plain' : ($this->isJson($_GET) ? 'json' : 'plain'));
}
if (isset($_GET) && !empty($_GET)) {
return (count($_GET) > 1 ? 'plain' : ($this->isJson($_GET) ? 'json' : 'plain'));
}
return 'plain';
} else {
return $error;
}
}
private function isJson($value)
{
json_decode(current($value));
return (json_last_error() == JSON_ERROR_NONE);
}
public static function getInstance(): HandlerError
{
if (!self::$instance instanceof self) self::$instance = new self;
return self::$instance;
}
}
HandlerError::getInstance();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:27:19.753",
"Id": "503451",
"Score": "2",
"body": "This question is discussed [on meta](https://codereview.meta.stackexchange.com/q/10621/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:26:45.040",
"Id": "507640",
"Score": "0",
"body": "Thanks guys, your contributions helped me a lot. Regards."
}
] |
[
{
"body": "<p>That's a good approach at whole, but I can see some improvements that could be made</p>\n<blockquote>\n<p>This means that all runtime errors including Fatal are presented to the developer in the form of an exception.</p>\n</blockquote>\n<p>Is not actually true. A more correct term would be "provides <em>output</em> similar to one from an exception". However, you <em>can</em> actually convert a runtime error into exception with a simple error handler like this:</p>\n<pre><code>set_error_handler(function ($level, $message, $file = '', $line = 0)\n{\n throw new ErrorException($message, 0, $level, $file, $line);\n});\n</code></pre>\n<p>Which will be much better because, since errors become actual exceptions, you will be able to <em>catch</em> them. And a you won't have to write a duplicated code for the error handler as a bonus. Unfortunately, for the fatal errors in won't work, and the currant approach is correct (other than that debug backtraces often tend to be quite big and in case of out of memory errors getting the backtrace would definitely fail).</p>\n<p>But the biggest problem oh this handler is that it doesn't have the production mode. Which surprises me, because the main purpose of error handlers is to serve in the production environment which is drastically different from the development mode. After all, there are many ways to get extended error output in the dev mode without any handler, such as using xDebug. Or just having a plain error message, most programmers are OK with it. Whereas such a handler is indeed essential the production mode, because:</p>\n<ul>\n<li>not a single error detail should be shown to a site user. A casual visitor won't get any clue from it anyway but it will be invaluable feedback for a potential attacker</li>\n<li>instead, a generic excuse page must be shown, and this is where design is indeed <em>essential</em>, following the common site design and retaining the most basic controls so a user can navigate somewhere.</li>\n<li>while the actual error message should be <strong>logged</strong> for a programmer, using <code>error_log()</code> function or some other facility</li>\n</ul>\n<p>As you can see, the production mode is drastically different from the development mode and requires totally different approach to handling errors and is a must have in any error handler.</p>\n<p>The handler code also requires some cleanup. I do understand that you are using init_error.php as sort of a universal bootstrap file for your application but apples must be sorted out from oranges. An error handler is one thing and a bootstrap file is another. Besides there are strange things such as setting error_reporting to 1 prior setting it to E_ALL and overall approach with throwing exceptions only to catch them immediately. Why not just echo the message right away, like</p>\n<pre><code>echo 'Unable to set session.use_only_cookies.';\n</code></pre>\n<p>without any exceptions? But again what a <em>site user</em> has to do with errors like this? And why a site continues to run if it cannot configure most essential settings? I believe this part of code is not well thought and you need to rethink it.</p>\n<p>Also, I don't see any purpose in the JSON output, unless there is a client library that understands it. But having such a client code only for the dev mode seems a bit strange. After all you can always use the Dev tools in your browser to check the actual error output for the AJAX call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T21:08:39.160",
"Id": "503421",
"Score": "0",
"body": "@Fran I see comments like \"contribute via github\" after a review has been made. However, reviewers are not here purely to seek repositories to contribute to. If you find valuable insights in a review, _you_ are free to implement them in the repository."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T23:19:16.653",
"Id": "503426",
"Score": "1",
"body": "Perhaps I should not speak on behalf of @YourCommonSense, but I think his stance is that the library _should_ be covering the mentioned objective -- this is certainly in the realm of a good/complete review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T14:01:28.223",
"Id": "503484",
"Score": "0",
"body": "@FranciscoNúñez this is a code review site and I wrote a review the way I see it. I am *not* your empoyee to tell me what I should write and what I should not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T14:30:50.527",
"Id": "503486",
"Score": "0",
"body": "the production mode is **not** about \"Hello user, you have omitted data\" errors but exactly the same errors your handler is about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T15:20:36.707",
"Id": "503493",
"Score": "0",
"body": "@FranciscoNúñez I am **not** confusing anything which I explicitly stated in the previous comment. But it seems only after you get some experience with production mode you'll understand what I am talking about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:26:37.343",
"Id": "507638",
"Score": "0",
"body": "Thanks guys, your contributions helped me a lot. Regards."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T07:10:59.790",
"Id": "255168",
"ParentId": "255137",
"Score": "3"
}
},
{
"body": "<p>Some notes about code styling, directness, and general clean up.</p>\n<ol>\n<li><p>Regarding your <strong>server_error.php</strong> file:</p>\n<ul>\n<li><p><code>$codes</code> is a good example of a useful lookup array, however the actual technique used to "lookup" data doesn't look right to me.</p>\n</li>\n<li><p>A default <code>$error_text = 'Unknown Error';</code> declaration is made then is conditionally overwritten, but then it doesn't ever appear to be used (unless I am missing something).</p>\n</li>\n<li><p><code>$code</code> is used as a shorter alias for an unchanged array element, so I am not convinced that there is much value in re-storing the same data in a new, redundant variable. (opinions may differ on this point)</p>\n</li>\n<li><p><code>$source_url</code> is declared and never used (unless I am missing something).</p>\n</li>\n<li><p>The condition: <code>array_key_exists($code, $codes) && is_numeric($code)</code> can be simplified using a single <code>isset()</code> or null coalescing check. I don't see any value in the <code>is_numeric()</code> check -- the value is either going to be in the lookup or not.</p>\n</li>\n<li><p>When you are writing multiple value concatenations in a single line, the syntax can become excessively wide and sometimes difficult to visually track. In these cases, it may be appropriate to wrap the concatenation onto multiple lines AND if employing ternary conditions, then <code>sprintf()</code> may be ideal.</p>\n<pre><code><?php\nrequire_once $_SERVER['DOCUMENT_ROOT'] . '/error/conf_error.php';\n$codes = [\n 400 => 'Bad Request',\n 401 => 'Unauthorized',\n 402 => 'Payment Required',\n 403 => 'Forbidden',\n 404 => 'Not Found',\n 405 => 'Method Not Allowed',\n 406 => 'Not Acceptable',\n 407 => 'Proxy Authentication Required',\n 408 => 'Request Timeout',\n 409 => 'Conflict',\n 410 => 'Gone',\n 411 => 'Length Required',\n 412 => 'Precondition Failed',\n 413 => 'Payload Too Large',\n 414 => 'URI Too Long',\n 415 => 'Unsupported Media Type',\n 500 => 'Internal Server Error',\n 501 => 'Not Implemented',\n 502 => 'Bad Gateway',\n 503 => 'Service Unavailable',\n 504 => 'Gateway Timeout',\n 505 => 'HTTP Version Not Supported',\n];\n$error_text = $codes[$_SERVER['REDIRECT_STATUS']] ?? 'Unknown Error';\n\n$source_url = 'http'\n . (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : '')\n . '://'\n . $_SERVER['HTTP_HOST']\n . $_SERVER['REQUEST_URI'];\n\n/** @var array $conf */\n$error_skin = $_SERVER['DOCUMENT_ROOT']\n . '/error/skin/sk_'\n . $conf['skin'] . '_server_error.php';\n\nif (file_exists($error_skin)) {\n /** @noinspection PhpIncludeInspection */\n require_once $error_skin;\n} else {\n require_once $_SERVER['DOCUMENT_ROOT'] . '/error/skin/sk_basic_server_error.php';\n}\ndie;\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Regarding your <strong>handler_error.php</strong> file:</p>\n<ul>\n<li><p>Edit your code to remove all instances of single-use variables. For example, delete <code>$error_level = $error['type'];</code> and just write that array element directly into the <code>$this->output</code> line. Writing <code>$this->output</code> as a multiline declaration if horizontal scrolling is a concern.</p>\n<pre><code>if ($error) {\n $this->CleanOutput();\n $error_type = 'ShutdownHandler';\n $error_trace = array_reverse(debug_backtrace());\n array_pop($error_trace);\n $error_trace_smg = $this->getBacktrace($error_trace, $error_type);\n $this->output(\n $error_type,\n $error['type'],\n $error['message'],\n $error['file'],\n $error['line'],\n $error_trace_smg\n );\n}\n</code></pre>\n</li>\n<li><p>Use a ternary assignment for <code>$error_level</code> using <code>$e->getCode()</code>:</p>\n<pre><code>$error_level = $e->getCode() ?: 'Not Set';\n</code></pre>\n</li>\n<li><p>You have a popular anti-pattern in <code>getRQType()</code>. Never use <code>isset() && !empty()</code> as a condition, there is no need for the redundant <code>isset()</code> check, just use <code>!empty()</code>.</p>\n</li>\n<li><p>You have a typo in this branch (you are mixing GET and POST):</p>\n<pre><code>return (count($_POST) > 1 ? 'plain' : ($this->isJson($_GET) ? 'json' : 'plain'));\n</code></pre>\n<p>It would be better to consolidate the conditional logic so that only one ternary is used.</p>\n<pre><code>return count($_POST) > 1 || !$this->isJson($_POST) ? 'plain' : 'json';\n</code></pre>\n</li>\n<li><p>To avoid confusion, <code>isJson()</code> should be named <code>isFirstElementJson()</code>.</p>\n</li>\n<li><p>Throughout your project, never omit curly braces -- not even if it saves you two lines of code. See <code>public static function getInstance(): HandlerError</code> <a href=\"https://www.php-fig.org/psr/psr-12/#5-control-structures\" rel=\"noreferrer\">PSR-12: Control Structures</a></p>\n</li>\n</ul>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:26:41.843",
"Id": "507639",
"Score": "0",
"body": "Thanks guys, your contributions helped me a lot. Regards."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T22:24:38.640",
"Id": "255191",
"ParentId": "255137",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "255191",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T15:09:28.107",
"Id": "255137",
"Score": "3",
"Tags": [
"php",
"error-handling",
"library"
],
"Title": "Library displaying a format with runtime errors, exceptions, and error exceptions present"
}
|
255137
|
<p>I want to start by just mentioning I'm a semi-beginner at C# and cyber security so any feedback is appreciated :)</p>
<p>What I think I need reviewing is the SQLite queries and maybe the hashing functions</p>
<p>I'm making a password manager project (sorry in advance for wall of code):</p>
<p>The supporting functions: (I probably don't need to worry about these)</p>
<pre><code>using System.Data.SQLite;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
//Just a function to check if the username/password inputted was valid format (you can probably ignore this)
private bool ValidLogin()
{
string Message = "Enter a ";
if (LoginTBUsername.Text == "")
{
Message += "username";
}
if (LoginTBPassword.Text == "")
{
if (LoginTBUsername.Text == "")
{
Message += " and a ";
}
Message += "password";
}
if (Message != "Enter a ")
{
LoginLabelError.Text = Message;
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
return false;
}
if (LoginTBPassword.Text.Length < 8)
{
LoginLabelError.Text = "Password must be 8 or more characters";
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
return false;
}
return true;
}
//Simple hash system
private string Hash(string Password, byte[] Salt, int Iteration = 12288)
{
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: Password,
salt: Salt,
prf: KeyDerivationPrf.HMACSHA512,
iterationCount: Iteration,
numBytesRequested: 256 / 8));
}
</code></pre>
<pre><code>//The login code
private void LoginButtonLog_Click(object sender, EventArgs e)
{
if (!ValidLogin())
{
return;
}
//Gets the path to the folders im using
string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string MDBPath = AppData + "\\Password Manager\\Accounts.mdb";
//Since database doesnt exist, no point continuing to login
if (!File.Exists(MDBPath))
{
LoginLabelError.Text = "Account not found";
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
return;
}
string Username = LoginTBUsername.Text;
string Password = LoginTBPassword.Text;
//Heres where i need feedback
string Command;
using (SQLiteConnection SQLite = new SQLiteConnection($"Data Source={MDBPath};Version=3"))
{
SQLite.Open();
//Checks if username exists (returns if not)
Command = $"SELECT COUNT(1) FROM Accounts WHERE Username = '{Username}'";
if ((Int64) new SQLiteCommand(Command, SQLite).ExecuteScalar() == 0)
{
LoginLabelError.Text = "Account doesn't exist";
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
return;
}
//Could probably turn these two into single statement but dont know how
Command = $"SELECT Password FROM Accounts WHERE Username = '{Username}'";
string PasswordHash = (string) new SQLiteCommand(Command, SQLite).ExecuteScalar();
Command = $"SELECT Salt FROM Accounts WHERE Username = '{Username}'";
byte[] Salt = Convert.FromBase64String((string) new SQLiteCommand(Command, SQLite).ExecuteScalar());
if (PasswordHash == Hash(Password, Salt))
{
LoginPanel.Visible = false;
LoginTBPassword.Text = "";
}
else
{
LoginLabelError.Text = "Incorrect Password";
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
}
}
}
</code></pre>
<p>The register code:</p>
<pre><code>//Register code
private void LoginButtonReg_Click(object sender, EventArgs e)
{
if (!ValidLogin())
{
return;
}
string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string MDBPath = AppData + "\\Password Manager\\Accounts.mdb";
//Creates nessacary folders
if (!File.Exists(MDBPath))
{
if (!Directory.Exists(AppData + "\\Password Manager"))
{
Directory.CreateDirectory(AppData + "\\Password Manager");
}
}
string Username = LoginTBUsername.Text;
string Password = LoginTBPassword.Text;
byte[] SaltByte = new byte[128 / 8];
using (RandomNumberGenerator RNG = RandomNumberGenerator.Create())
{
RNG.GetBytes(SaltByte);
}
Password = Hash(Password, SaltByte);
string Salt = Convert.ToBase64String(SaltByte);
//Heres where i need feedback
string Command;
using (SQLiteConnection SQLite = new SQLiteConnection($"Data Source={MDBPath};Version=3"))
{
SQLite.Open();
Command = "CREATE TABLE IF NOT EXISTS Accounts (Username varchar(32), Password varchar(32), Salt varchar(32))";
new SQLiteCommand(Command, SQLite).ExecuteNonQuery();
//Checks if account doesnt already exist
Command = $"SELECT COUNT(1) FROM Accounts WHERE Username = '{Username}'";
if ((Int64) new SQLiteCommand(Command, SQLite).ExecuteScalar() > 0)
{
LoginLabelError.Text = "Account already exists";
LoginLabelError.Left = (LoginPanel.Width - LoginLabelError.Width) / 2;
LoginLabelError.Visible = true;
return;
}
//Hides the login panel and clears the password box
LoginPanel.Visible = false;
LoginTBPassword.Text = "";
Command = $"INSERT INTO Accounts VALUES ('{Username}', '{Password}', '{Salt}')";
new SQLiteCommand(Command, SQLite).ExecuteNonQuery();
//Creates a folder with id where i store the user specific passwords
Command = "SELECT COUNT(*) FROM Accounts";
Int64 RowCount = (Int64) new SQLiteCommand(Command, SQLite).ExecuteScalar();
Directory.CreateDirectory(AppData + $"\\Password Manager\\Account{RowCount}");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:02:39.767",
"Id": "503348",
"Score": "1",
"body": "A tip: look at NuGet package \"Bouncy Castle\". It provides a lot of modern encryption and hashing algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T04:08:54.120",
"Id": "503544",
"Score": "0",
"body": "I have never been a fan of keeping the salt stored near the application or the database and neither decrypting a hashed string!. because if the app can decrypt what is encrypted, then there is no reason to encrypt it in the first place!"
}
] |
[
{
"body": "<p>As is very common for starter code of this nature, your view, model and controller are all mashed together. <code>LoginPanel.Visible = false</code> is a view obligation; file operations are a controller obligation and username/password representation are a model obligation. These all need to be teased apart - do some reading on MVC or MVVM, or more traditional ideas of "business layer" / "data layer".</p>\n<p>Don't do this:</p>\n<pre><code> Command = $"SELECT COUNT(1) FROM Accounts WHERE Username = '{Username}'";\n</code></pre>\n<p>Use <code>EXISTS</code> instead of <code>COUNT(1)</code>, and never EVER leave your commands open to injection attack by doing naive string interpolation of user data. Use prepared statements instead.</p>\n<p>These two statements here:</p>\n<pre><code> Command = $"SELECT COUNT(1) FROM Accounts WHERE Username = '{Username}'";\n Command = $"SELECT Salt FROM Accounts WHERE Username = '{Username}'";\n</code></pre>\n<p>can be combined into one statement that issues a <code>SELECT Salt</code> with a predicate for the username. If no rows are returned, the username was wrong.</p>\n<p>Rather than constructs like this:</p>\n<pre><code>Directory.Exists(AppData + "\\\\Password Manager")\n</code></pre>\n<p>use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.path?view=net-5.0\" rel=\"nofollow noreferrer\">System.IO.Path</a> for concatenation. Even if you did need a backslash, use an <code>@</code> string to avoid the need for an escape.</p>\n<p>This:</p>\n<pre><code>Command = "CREATE TABLE IF NOT EXISTS Accounts (Username varchar(32), Password varchar(32), Salt varchar(32))";\n \n</code></pre>\n<p>is something that should be done on application startup, not in the middle of a <code>LoginButtonReg_Click</code> UI call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T17:57:10.910",
"Id": "503290",
"Score": "0",
"body": "You say to create the table if not exists on application start-up. I'm really pedantic so i put it there if the table is deleted while the application is running."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:04:09.883",
"Id": "503292",
"Score": "0",
"body": "Why would that ever happen? This should be a purpose-assigned database that should never have tables deleted, never mind have concurrent users."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:04:44.920",
"Id": "503293",
"Score": "0",
"body": "The more important thing here (though I don't know whether SQLite supports it) is that your application user should not have DDL permission at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T13:35:32.370",
"Id": "503385",
"Score": "0",
"body": "what if the file gets deleted while the application is running. With my code, it creates the DB file on connection (version 3 SQLite) and creates the table. Eh its be being pedantic"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T17:14:56.703",
"Id": "255147",
"ParentId": "255138",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T15:15:54.237",
"Id": "255138",
"Score": "3",
"Tags": [
"c#",
"sqlite"
],
"Title": "C# Password Security Login System with SQLite"
}
|
255138
|
<p>This is a clone of the <code>cat</code> utility. The goal of this exercise was to get comfortable doing basic tasks in a new language, figure out how to set up testing, etc. So I'm really looking for feedback on writing more idiomatic Rust, if there are better ways to approach things, etc. In particular, my <code>TextFixture</code> class I use to manage lifetimes so I can easily create a <code>Cat</code> object and retreive the output streams, seems like not the best way to do things.Conversely, issues like "numbering will be broken if you have more than 1,000 lines" are not very important to me for this exercise.</p>
<pre><code>use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::str;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
name = "cat",
about = "concatenate files and print on the standard output"
)]
struct CatConfig {
/// Input file
#[structopt(name = "FILE", parse(from_os_str))]
input: Vec<PathBuf>,
/// display $ at the end of each line
#[structopt(short = "E", long = "show-ends")]
show_ends: bool,
/// display TAB characters as ^I
#[structopt(short = "T", long = "show-tabs")]
show_tabs: bool,
/// number all output lines
#[structopt(short = "n", long = "number")]
number: bool,
}
impl Default for CatConfig {
fn default() -> CatConfig {
CatConfig {
input: vec![],
show_tabs: false,
show_ends: false,
number: false,
}
}
}
struct Cat<'a> {
stdout: &'a mut dyn io::Write,
stderr: &'a mut dyn io::Write,
}
impl Cat<'_> {
fn new<'a>(stdout: &'a mut dyn io::Write, stderr: &'a mut dyn io::Write) -> Cat<'a> {
Cat { stdout, stderr }
}
fn cat_all(&mut self, config: CatConfig) -> () {
for path in &config.input {
match File::open(path) {
Ok(file) => {
let mut input = BufReader::new(file);
self.cat(&config, &mut input);
}
Err(_) => {
let filename = path.to_str().unwrap();
self.stderr.write(filename.as_bytes()).unwrap();
self.stderr.write(b": No such file or directory\n").unwrap();
}
}
}
}
fn cat(&mut self, config: &CatConfig, input: &mut dyn BufRead) -> () {
let mut line_number = 1;
for line in input.lines() {
let string_line = line.unwrap();
let line_ending: &str = if config.show_ends { "$\n" } else { "\n" };
let mut line_to_write = [string_line, line_ending.to_string()].concat();
if config.show_tabs {
line_to_write = line_to_write.replace("\t", "^I");
}
if config.number {
let number_string = line_number.to_string();
line_to_write = [" ", &number_string, " ", &line_to_write].concat();
}
line_number = line_number + 1;
self.stdout.write(&line_to_write.as_bytes()).unwrap();
}
}
}
fn main() -> () {
let opt = CatConfig::from_args();
Cat::new(&mut io::stdout(), &mut io::stderr()).cat_all(opt);
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::path::Path;
use tempfile::NamedTempFile;
struct TestFixture {
stdout: io::Cursor<Vec<u8>>,
stderr: io::Cursor<Vec<u8>>,
}
impl TestFixture {
fn new() -> TestFixture {
let stdout = io::Cursor::new(Vec::new());
let stderr = io::Cursor::new(Vec::new());
TestFixture { stdout, stderr }
}
fn make_cat(&mut self) -> Cat {
return Cat {
stdout: &mut self.stdout,
stderr: &mut self.stderr,
};
}
fn get_output(&self) -> String {
let clone = self.stdout.clone();
let output_vec = clone.into_inner();
String::from_utf8(output_vec).unwrap()
}
fn get_error(&self) -> String {
let clone = self.stderr.clone();
let output_vec = clone.into_inner();
String::from_utf8(output_vec).unwrap()
}
}
#[test]
fn cat_with_no_options() {
let mut source = b"abc\ndef\n" as &[u8];
let expected_output = "abc\ndef\n";
let config = CatConfig::default();
check_cat_output(&mut source, expected_output, config);
}
#[test]
fn cat_from_nonexistant_file() {
let mut fixture = TestFixture::new();
let mut catter = fixture.make_cat();
let file = Path::new("file_does_not_exist.txt");
let config = CatConfig {
input: vec![file.to_path_buf()],
..Default::default()
};
catter.cat_all(config);
let expected_error = "file_does_not_exist.txt: No such file or directory\n";
assert_eq!(expected_error, fixture.get_error());
}
#[test]
fn cat_from_file() {
let mut fixture = TestFixture::new();
let mut catter = fixture.make_cat();
let mut file = NamedTempFile::new().unwrap();
writeln!(file, "File contents").unwrap();
let config = CatConfig {
input: vec![file.path().to_path_buf()],
..Default::default()
};
catter.cat_all(config);
assert_eq!("File contents\n", fixture.get_output());
}
#[test]
fn test_cat_shows_ends() {
let mut source = b"abc\ndef\n" as &[u8];
let expected_output = "abc$\ndef$\n";
let config = CatConfig {
show_ends: true,
..Default::default()
};
check_cat_output(&mut source, expected_output, config);
}
#[test]
fn test_cat_shows_tabs() {
let mut source = b"abc\tdef\n" as &[u8];
let expected_output = "abc^Idef\n";
let config = CatConfig {
show_tabs: true,
..Default::default()
};
check_cat_output(&mut source, expected_output, config);
}
fn check_cat_output(source: &mut dyn BufRead, expected_output: &str, config: CatConfig) {
let mut fixture = TestFixture::new();
let mut catter = fixture.make_cat();
catter.cat(&config, source);
assert_eq!(expected_output, fixture.get_output());
}
#[test]
fn test_cat_number_lines() {
let mut source = b"abc\ndef\n" as &[u8];
let expected_output = " 1 abc\n 2 def\n";
let config = CatConfig {
number: true,
..Default::default()
};
check_cat_output(&mut source, expected_output, config);
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>First things first -- run <code>cargo clippy</code>! Generally speaking its suggestions are quite helpful. In this case clippy raises some errors because you are using <code>write</code> instead of <code>write_all</code> to write an entire buffer, which doesn't necessarily work. This appears to be a serious error; see <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount\" rel=\"nofollow noreferrer\">this page</a> for an explanation.</p>\n</li>\n<li><p>Also caught by <code>clippy</code>: functions don't need <code>-> ()</code> (if there's no return type, then <code>()</code> is implicit).</p>\n</li>\n<li><p>The use of <code>structopt</code> is very clean and natural and fits the task, as well as implementing <code>Default</code> for your CLI arguments for convenient initialization.</p>\n</li>\n<li><p>A stylistic point: your code is littered with <code>&'a mut dyn Trait</code> objects everywhere. Some Rust programmers write code like this, so I wouldn't say it's necessarily wrong, but I usually recommend using generics when possible because this avoids dynamic overhead at runtime. Instead you get a copy of your function for the actual concrete type that you need it, like with C++ templates. For consideration, here is what your <code>Cat</code> struct looks like using generics instead:</p>\n<pre><code>struct Cat<'a, F1, F2>\nwhere\n F1: io::Write,\n F2: io::Write,\n{\n stdout: &'a mut F1,\n stderr: &'a mut F2,\n}\n\nimpl<'a, F1, F2> Cat<'a, F1, F2>\nwhere\n F1: io::Write,\n F2: io::Write,\n{\n fn new(stdout: &'a mut F1, stderr: &'a mut F2) -> Self {\n Cat { stdout, stderr }\n }\n\n...\n</code></pre>\n<p>and in your TestFixture:</p>\n<pre><code>fn make_cat(&mut self) -> Cat<impl io::Write, impl io::Write> {\n return Cat::new(&mut self.stdout, &mut self.stderr);\n}\n</code></pre>\n<p>You can similarly replace your <code>&mut dyn BufRead</code> objects, e.g. <code>fn cat<G: BufRead>(&mut self, config: &CatConfig, input: &mut G) {</code></p>\n</li>\n<li><p>You are overusing <code>.unwrap()</code> -- fine for a toy project, but not really fine if you wanted to ship this as the real <code>cat</code> utility; it would occasionally fail and panic with no explanation.\nSince this is a binary, the easiest fix is just to use\n<code>.expect("Explain what bad happened here")</code>\ninstead of unwrap -- this should be propagated back to the user.\nFor a library you would want to return <code>Result<(), String></code> or similar for all your functions so as to make the failure model completely explicit.</p>\n</li>\n<li><p>In the <code>fn cat</code> function, you are manually incrementing a counter; consider the alternative</p>\n<pre><code>for (line_number, line) in input.lines().enumerate() {\n</code></pre>\n<p>If you do this though, you get numbering starting from zero. So to get numbering starting from 1: <code>let number_string = (line_number + 1).to_string()</code></p>\n</li>\n<li><p>I like your use of <code>TestFixture</code>: you need to collect output during the lifetime of a test, so it makes perfect sense to make an object that represents that lifetime. One simplification to consider though is avoiding the cloning shenanigans in functions <code>get_output</code> and <code>get_error</code>: instead you could consume the object after it's done (after all, once you collect the output you don't need it anymore), like this:</p>\n<pre><code>fn collect(self) -> (String, String) {\n let out = String::from_utf8(self.stdout.into_inner())\n .expect("invalid UTF8 found in stdout!");\n let err = String::from_utf8(self.stderr.into_inner())\n .expect("invalid UTF8 found in stderr!");\n (out, err)\n}\n</code></pre>\n<p>Then use it like: <code>assert_eq!(expected_error, fixture.collect().1)</code>.</p>\n</li>\n<li><p>Finally, I found it counterintuitive that running the binary with no arguments prints nothing. Printing the help would be more useful, and there is probably a way to configure <code>structopt</code> / your <code>main</code> function to have that behavior.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:56:01.643",
"Id": "255397",
"ParentId": "255148",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255397",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T17:20:31.087",
"Id": "255148",
"Score": "1",
"Tags": [
"rust"
],
"Title": "Cat clone with unit tests"
}
|
255148
|
<p>I've just finally finished implementing <code>std::vector</code>. I'm currently re-implementing whatever I can in the hope to learn more of how data structures works.</p>
<p>I tried to respect all requirements, but I probably missed a lot (or made mistakes). At first I thought implementing std::vector would be somewhat easy... but how wrong I was.</p>
<p>Anyway, I've taken some reference from cppreference.com; the template is allocator-aware, I also tried implementing a random access iterator, and tried to add exception guarantees (which I'm very bad at). This is my beginner attempt to std::vector, and I'm open to all criticism and code review.</p>
<p>N.B. I avoided re-creating the specialization of bool since I think it's really ahead of my current level of expertise.</p>
<pre><code>#ifndef VECTOR_CONTAINER
#define VECTOR_CONTAINER
#include <exception>
#include <stdexcept>
#include <algorithm>
#include <cassert>
#include <concepts>
#include <compare>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <memory>
#include <type_traits>
#include <utility>
namespace constants {
inline constexpr std::size_t realloc_factor = 2;
}
namespace random_access {
template<typename Type>
class iterator
{
private:
Type* m_iterator;
public:
using value_type = Type;
using reference = value_type&;
using pointer = value_type*;
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
//using iterator_concept = std::contiguous_iterator_tag;
constexpr iterator(Type* iter = nullptr) : m_iterator{ iter } {}
constexpr auto operator<=>(const iterator&) const = default;
constexpr reference operator*() const noexcept {
return *m_iterator;
}
constexpr pointer operator->() const noexcept {
return m_iterator;
}
constexpr iterator& operator++() noexcept {
++m_iterator;
return *this;
}
constexpr iterator operator++(int) noexcept {
iterator tmp(*this); ++(*this);
return tmp;
}
constexpr iterator& operator--() noexcept {
--m_iterator;
return *this;
}
constexpr iterator operator--(int) noexcept {
iterator tmp(*this);
--(*this);
return tmp;
}
constexpr iterator& operator+=(const difference_type other) noexcept {
m_iterator += other;
return *this;
}
constexpr iterator& operator-=(const difference_type other) noexcept {
m_iterator -= other;
return *this;
}
friend constexpr iterator operator+(difference_type first, const iterator& other) noexcept {
return other.m_iterator + first;
}
friend constexpr iterator operator+(const iterator& first, difference_type other) noexcept {
return first.m_iterator + other;
}
friend constexpr iterator operator-(const iterator& first, const difference_type other) noexcept {
return first.m_iterator - other;
}
constexpr difference_type operator-(const iterator& other) const noexcept {
return std::distance(m_iterator, other.m_iterator);
}
constexpr reference operator[](std::size_t index) const {
return m_iterator[index];
}
constexpr friend bool operator== (const iterator& first, const iterator& second) {
return first.m_iterator == second.m_iterator;
}
};
}
namespace container {
template<typename Type, typename Allocator = std::allocator<Type>>
class vector {
private:
Type* m_vector;
std::size_t m_capacity{};
std::size_t m_size{};
Allocator m_allocator;
constexpr void reset(vector& other) noexcept {
other.m_vector = nullptr;
other.m_capacity = 0;
other.m_size = 0;
}
constexpr void allocate(std::size_t capacity) {
m_capacity = capacity;
m_vector = std::allocator_traits<allocator_type>::allocate(m_allocator, capacity);
}
constexpr void deallocate(std::size_t capacity) {
std::allocator_traits<allocator_type>::deallocate(m_allocator, m_vector, capacity);
m_capacity = 0;
m_size = 0;
}
constexpr void reallocate(std::size_t old_cap, std::size_t new_cap) {
deallocate(old_cap);
allocate(new_cap);
}
constexpr void construct(std::size_t size, const Type& value) {
m_size = size;
for (std::size_t index{ 0 }; index < size; ++index)
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index, value);
}
constexpr void destruct(std::size_t size) {
for (std::size_t index{ 0 }; index < size; ++index)
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + index);
m_size = 0;
}
constexpr void allocate_and_copy_construct(std::size_t capacity, std::size_t size, const Type& value = Type()) {
allocate(capacity);
construct(size, value);
}
constexpr void construct_init_list(std::initializer_list<Type> values) {
m_size = values.size();
for (size_type index{ 0 }; const auto & currentValue : values)
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + (index++), currentValue);
}
constexpr void deallocate_and_destruct(std::size_t capacity, std::size_t size) {
destruct(size);
deallocate(capacity);
}
constexpr void deallocate_destruct_keep_size_and_capacity(std::size_t size, std::size_t capacity) {
for (std::size_t index{ 0 }; index < m_size; ++index)
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + index);
std::allocator_traits<allocator_type>::deallocate(m_allocator, m_vector, m_capacity);
m_capacity = capacity;
m_size = size;
}
constexpr void uninitialized_alloc_copy(const vector& other) {
m_size = other.m_size;
for (size_type index{ 0 }; index < m_size; ++index) {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index, *(other.m_vector + index));
}
}
constexpr void uninitialized_alloc_move(vector&& other) noexcept {
m_size = other.m_size;
m_capacity = other.m_capacity;
for (size_type index{ 0 }; index < m_size; ++index)
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index, std::move(*(other.m_vector + index)));
reset(other);
}
constexpr void copy(const vector& other) {
if (other.m_vector) {
allocate(other.m_size);
uninitialized_alloc_copy(other);
}
else
m_vector = nullptr;
}
constexpr void reallocate_strong_guarantee(std::size_t capacity) {
Type* tempVect = std::allocator_traits<allocator_type>::allocate(m_allocator, capacity);
if (std::is_nothrow_move_constructible<Type>::value || !std::is_nothrow_move_constructible<Type>::value && !std::is_copy_constructible<Type>::value) {
for (size_type index{ 0 }; index < m_size; ++index)
std::allocator_traits<allocator_type>::construct(m_allocator, tempVect + index, std::move(m_vector[index]));
}
else {
size_type copiesMade{ 0 };
try {
for (size_type index{ 0 }; index < m_size; ++index) {
std::allocator_traits<allocator_type>::construct(m_allocator, tempVect + index, *(m_vector + index));
++copiesMade;
}
}
catch (...) {
for (std::size_t index{ 0 }; index < copiesMade; ++index)
std::allocator_traits<allocator_type>::destroy(m_allocator, tempVect + index);
std::allocator_traits<allocator_type>::deallocate(m_allocator, tempVect, capacity);
throw;
}
}
size_type temp_cap = capacity;
deallocate_destruct_keep_size_and_capacity(m_size, temp_cap);
m_vector = tempVect;
tempVect = nullptr;
}
constexpr void shift_and_construct(std::size_t index_pos, const Type& value, std::size_t count = 1) {
// Should provide strong exception guarantee.
size_type copies_made{ 0 };
size_type copies_made1{ 0 };
size_type copies_made2{ 0 };
auto count_after_last_element = m_vector + size() + count;
auto last_element = m_vector + size();
auto current_pos = m_vector + index_pos;
try {
for (std::size_t index{ 0 }; index < count; ++index) {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + size() + index, m_vector[size() + index]);
++copies_made;
}
}
catch (...) {
for (std::size_t index{ 0 }; index < copies_made; ++index)
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + size() + index);
throw;
}
try {
while (current_pos++ != m_vector + size()) {
*(--(count_after_last_element)) = *(--(last_element));
++copies_made1;
}
}
catch (...) {
while (copies_made1 != 0) {
std::allocator_traits<Allocator>::destroy(m_allocator, m_vector + size() + 1 + copies_made1);
--copies_made1;
}
throw;
}
//std::copy_backward(m_vector + index_pos, m_vector + size(), m_vector + size() + count);
for (std::size_t index{ 0 }; index < count; ++index) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + index_pos + index);
}
try {
for (std::size_t index{ 0 }; index < count; ++index) {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index_pos + index, value);
++copies_made2;
}
}
catch (...) {
for (std::size_t index{ 0 }; index < copies_made2; ++index) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + size() + index);
}
throw;
}
m_size += count;
}
constexpr void shift_and_construct_init(std::size_t pos_index_position, std::initializer_list<Type> list) {
for (size_type index{ 0 }; auto value : list) {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + size() + index, m_vector[size() + index]);
++index;
}
std::copy_backward(m_vector + pos_index_position, m_vector + size(), m_vector + size() + list.size());
for (size_type index{ 0 }; auto value : list) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + pos_index_position + index);
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + pos_index_position + index, value);
++index;
}
m_size += list.size();
}
constexpr void shift_and_construct(std::size_t index_pos, Type&& value) {
if (std::is_nothrow_move_constructible<Type>::value || !std::is_nothrow_move_constructible<Type>::value && !std::is_copy_constructible<Type>::value) {
auto one_after_last_element = m_vector + size() + 1;
auto last_element = m_vector + size();
auto current_pos = m_vector + index_pos;
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + size(), std::move(*(m_vector+size())));
std::move_backward(m_vector + index_pos, m_vector + size(), m_vector + size() + 1);
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index_pos, std::move(value));
m_size += 1;
}
else shift_and_construct(index_pos, value);
}
constexpr void insert_end_strong_guarantee(const Type& value) {
try {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + m_size, value);
}
catch (...) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + m_size);
throw;
}
m_size += 1;
}
constexpr void insert_end_strong_guarantee(Type&& value) {
if constexpr (std::is_nothrow_move_constructible<Type>::value)
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + m_size, std::move(value));
else
insert_end_strong_guarantee(value);
m_size += 1;
}
public:
// Aliases
using value_type = Type;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = Type*;
using const_pointer = const pointer;
using allocator_type = Allocator;
using const_alloc_reference = const allocator_type&;
using size_type = std::size_t;
using init_list_type = std::initializer_list<Type>;
using iterator = random_access::iterator<Type>;
using const_iterator = random_access::iterator<const Type>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using difference_type = std::ptrdiff_t;
// Constructors
constexpr vector() noexcept : m_vector{ nullptr } {}
constexpr explicit vector(const_alloc_reference allocator) noexcept
: m_allocator{ allocator }, m_vector{ nullptr } {}
constexpr explicit vector(size_type length, const_alloc_reference allocator = Allocator())
: m_allocator{ allocator } {
allocate_and_copy_construct(length, length);
}
constexpr explicit vector(size_type length, const_reference value, const_alloc_reference allocator = Allocator())
: m_allocator{ allocator } {
allocate_and_copy_construct(length, length, value);
}
constexpr explicit vector(init_list_type values, const_alloc_reference allocator = Allocator())
: m_allocator{ allocator } {
allocate(values.size());
construct_init_list(values);
}
template<typename input_iter>
constexpr vector(input_iter first, input_iter last, const_alloc_reference allocator = Allocator()) {
size_type size = std::distance(last, first);
allocate(size);
for (size_type index{ 0 }; index < size; ++index) {
std::allocator_traits<Allocator>::construct(m_allocator, m_vector + index, *(first + index));
++m_size;
}
}
// Copy semantics
constexpr vector(const vector& other) {
m_allocator = std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator());
copy(other);
}
constexpr vector(const vector& other, const_alloc_reference allocator)
: m_allocator{ allocator } {
copy(other);
}
constexpr vector& operator=(const vector& other) {
if (this == &other) { return *this; }
destruct(size());
if (other.m_vector)
{
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
m_allocator = other.get_allocator();
}
if (other.size() > capacity()) {
reallocate(capacity(), other.size());
}
uninitialized_alloc_copy(other);
}
else {
m_vector = nullptr;
m_size = 0;
}
return *this;
}
// Move semantics
constexpr vector(vector&& other) noexcept
: m_vector{ other.m_vector }, m_size{ other.m_size }, m_capacity{ other.m_capacity }, m_allocator{ std::move(other.m_allocator) } {
reset(other);
}
constexpr vector(vector&& other, const_alloc_reference allocator) noexcept
: m_size{ other.m_size }, m_capacity{ other.m_capacity }, m_allocator{ std::move(allocator) } {
if (allocator != other.get_allocator()) {
uninitialized_alloc_move(std::move(other));
}
else
m_vector = other.m_vector;
reset(other);
}
constexpr vector& operator=(vector&& other) noexcept {
if (this == &other) { return *this; }
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {
deallocate_and_destruct(capacity(), size());
m_allocator = other.get_allocator();
m_vector = other.m_vector;
reset(other);
}
else if (m_allocator == other.m_allocator) {
deallocate_and_destruct(capacity(), size());
m_vector = other.m_vector;
reset(other);
}
else {
destruct(size());
reallocate(capacity(), other.capacity());
uninitialized_alloc_move(std::move(other));
}
m_size = other.m_size;
m_capacity = other.m_capacity;
return *this;
}
~vector() noexcept { deallocate_and_destruct(m_capacity, m_size); }
// Overloaded operators
constexpr vector& operator=(init_list_type values) {
destruct(m_size);
if (values.size() > capacity()) {
reallocate(capacity(), values.size());
}
construct_init_list(values);
return *this;
}
// Operator<=> doesn't seem to work this way...
//constexpr auto operator<=>(const vector&) = default;
constexpr friend bool operator== (const vector& first, const vector& second) {
return (first.m_size == second.m_size &&
std::equal(first.m_vector, first.m_vector + first.size(), second.m_vector, second.m_vector + second.size()));
}
constexpr bool operator!= (const vector& other) const {
return !(*this == other);
}
constexpr bool operator< (const vector& other) const {
return std::lexicographical_compare(m_vector, m_vector+size(), other.begin(), other.end());
}
constexpr bool operator> (const vector& other) const {
return !(*this < other);
}
constexpr bool operator<=(const vector& other) const {
return !(other < *this);
}
constexpr bool operator>=(const vector& other) const {
return !(*this < other);
}
// Member functions
constexpr void assign(size_type size, const_reference value) {
destruct(m_size);
if (size > capacity()) {
reallocate(capacity(), size);
}
construct(size, value);
}
constexpr void assign(init_list_type values) {
destruct(m_size);
if (values.size() > capacity())
{
reallocate(capacity(), values.size());
}
construct_init_list(values);
}
template<typename input_iter>
constexpr void assign(input_iter first, input_iter last) {
size_type size = std::distance(last, first);
destruct(size);
if (size > capacity()) {
reallocate(capacity(), size);
}
for (size_type index{ 0 }; index < size; ++index) {
std::allocator_traits<Allocator>::construct(m_allocator, m_vector + index, *(first + index));
++m_size;
}
}
constexpr allocator_type get_allocator() const noexcept { return m_allocator; }
// Access functions
constexpr reference at(size_type index) {
return index < size() ? m_vector[index] : throw std::out_of_range("Index out of range");
}
constexpr const_reference at(size_type index) const {
return index < size() ? m_vector[index] : throw std::out_of_range("Index out of range");
}
constexpr reference operator[](size_type index) {
assert(index < size() && "Index out of range"); return m_vector[index];
}
constexpr const_reference operator[](size_type index) const {
assert(index < size() && "Index out of range"); return m_vector[index];
}
constexpr pointer data() noexcept {
return (size() != 0) ? m_vector : nullptr;
}
constexpr const_pointer data() const noexcept {
return (size() != 0) ? m_vector : nullptr;
}
constexpr reference back() {
return *(end() - 1);
}
constexpr const_reference back() const {
return *(end() - 1);
}
constexpr reference front() {
return *(begin());
}
constexpr const_reference front() const {
return *(begin());
}
// Iterators
constexpr iterator begin() noexcept {
return m_vector;
}
constexpr const_iterator begin() const noexcept {
return m_vector;
}
constexpr const_iterator cbegin() const noexcept {
return m_vector;
}
constexpr reverse_iterator rbegin() noexcept {
return reverse_iterator(m_vector + size());
}
constexpr const_reverse_iterator crbegin() const noexcept {
return const_reverse_iterator(m_vector + size());
}
constexpr iterator end() noexcept {
return m_vector + size();
}
constexpr const_iterator end() const noexcept {
return m_vector + size();
}
constexpr const_iterator cend() const noexcept {
return m_vector + size();
}
constexpr reverse_iterator rend() noexcept {
return reverse_iterator(m_vector);
}
constexpr const_reverse_iterator rend() const noexcept {
return reverse_iterator(m_vector);
}
// Capacity related
constexpr size_type size() const noexcept {
return m_size;
}
constexpr size_type max_size() const noexcept {
return std::numeric_limits<difference_type>::max();
}
constexpr size_type capacity() const noexcept {
return m_capacity;
}
constexpr bool empty() const noexcept {
return m_size == 0;
}
constexpr bool is_null() const noexcept {
return m_vector == nullptr;
}
constexpr void reserve(size_type capacity) {
if (capacity > max_size())
throw std::length_error("Capacity allocated exceeds max_size()");
else if (capacity > m_capacity)
reallocate_strong_guarantee(capacity);
}
constexpr void shrink_to_fit() {
if (m_capacity != m_size) {
reallocate_strong_guarantee(m_size);
}
}
// Modifier functions
constexpr void clear() noexcept {
destruct(m_size);
}
constexpr iterator insert(const iterator pos, const_reference value) {
return emplace(pos, value);
}
constexpr iterator insert(const iterator pos, value_type&& value) {
return emplace(pos, std::move(value));
}
constexpr iterator insert(const iterator pos, init_list_type values) {
size_type pos_index_position = std::distance(pos, begin());
if (size() + values.size() < capacity()) {
shift_and_construct_init(pos_index_position, values);
}
else {
do {
if (m_capacity == 0) m_capacity = 1;
m_capacity *= constants::realloc_factor;
} while (m_capacity < values.size() + m_size);
reallocate_strong_guarantee(m_capacity);
shift_and_construct_init(pos_index_position, values);
}
return values.size() == 0 ? pos : iterator(m_vector + pos_index_position);
}
constexpr iterator insert(const iterator pos, size_type count, const_reference value) {
size_type pos_index_position = std::distance(pos, begin());
if (size() + count < capacity()) {
if (pos == end()) {
insert_end_strong_guarantee(value);
}
else
shift_and_construct(pos_index_position, value, count);
}
else {
do {
if (m_capacity == 0) m_capacity = 1;
m_capacity *= constants::realloc_factor;
} while (m_capacity < m_size);
reallocate_strong_guarantee(m_capacity);
shift_and_construct(pos_index_position, value, count);
}
return count == 0 ? pos : iterator(m_vector + pos_index_position);
}
constexpr iterator erase(const iterator pos) {
assert(pos <= end() && "Vector subscript out of range");
size_type pos_index_position = std::distance(pos, begin());
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + pos_index_position);
if constexpr (std::is_nothrow_move_constructible<Type>::value) {
std::move(m_vector + pos_index_position + 1, m_vector + size(), m_vector + pos_index_position);
}
else
std::copy(m_vector + pos_index_position + 1, m_vector + size(), m_vector + pos_index_position);
--m_size;
return (end() == pos) ? end() : iterator(m_vector + pos_index_position);
}
constexpr iterator erase(const iterator first, const iterator last) {
bool last_equals_end = (last == end());
assert(first <= end() && "Vector's first argument out of range");
assert(last <= end() && "Vector's second argument out of range");
assert(first <= last && "Vector's first argument smaller than second argument");
size_type first_position = std::distance(first, begin());
size_type last_position = std::distance(last, begin());
size_type difference{ last_position - first_position };
for (size_type index{ first_position }; index < last_position; ++index) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + index);
}
if constexpr (std::is_nothrow_move_constructible<Type>::value) {
std::move(m_vector + last_position, m_vector + size(), m_vector + first_position);
}
else
std::copy(m_vector + last_position, m_vector + size(), m_vector + first_position);
m_size -= difference;
return (last_equals_end) ? iterator(m_vector + last_position) : iterator(m_vector + first_position);
}
constexpr void pop_back() noexcept {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + size() - 1);
m_size -= 1;
}
constexpr void resize(size_type count, const_reference value = value_type()) {
auto temp_size = size();
if (count < size()) {
for (size_type index{ count }; index < temp_size; ++index)
pop_back();
}
else {
if (count > capacity())
reallocate_strong_guarantee(count);
for (size_type index{ temp_size }; index < count; ++index)
insert_end_strong_guarantee(value);
}
}
template<typename...Args>
constexpr iterator emplace(const iterator pos, Args&&...args) { // Provide strong guarantee
assert(pos <= end() && "Vector's argument out of range");
size_type pos_index_position = std::distance(pos, begin());
if (size() + 1 < capacity()) {
if (pos == end()) {
try {
std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + size(), std::forward<Args>(args)...);
}
catch (...) {
std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + size());
throw;
}
++m_size;
}
else {
shift_and_construct(pos_index_position, std::forward<Args>(args)...);
}
}
else {
do {
if (m_capacity == 0) m_capacity = 1;
m_capacity *= constants::realloc_factor;
} while (m_capacity < 1 + size());
reallocate_strong_guarantee(m_capacity);
shift_and_construct(pos_index_position, std::forward<Args>(args)...); // Checks if move constructor is noexcept. Otherwise does copy
}
return iterator(m_vector + pos_index_position);
}
template<typename...Args>
constexpr reference emplace_back(Args...args) {
emplace(end(), std::forward<Args>(args)...);
return *(m_vector + size() - 1);
}
constexpr void push_back(const Type& value) {
emplace_back(value);
}
constexpr void push_back(Type&& value) {
emplace_back(std::move(value));
}
constexpr void swap(vector& other) noexcept {
if (this == &other) { return; }
if (std::allocator_traits<allocator_type>::propagate_on_container_swap::value
|| std::allocator_traits<allocator_type>::is_always_equal::value) {
std::swap(m_allocator, other.m_allocator);
}
std::swap(m_vector, other.m_vector);
std::swap(m_capacity, other.m_capacity);
std::swap(m_size, other.m_size);
}
};
// Erase, erase_if
template<typename Type, typename Allocator, typename Val>
constexpr auto erase(container::vector<Type, Allocator>& vec, const Val& value) {
auto iter = std::remove(vec.begin(), vec.end(), value);
auto dist = std::distance(iter, vec.end());
vec.erase(iter, vec.end());
return dist;
}
template<typename Type, typename Allocator, typename Predicate>
constexpr auto erase_if(container::vector<Type, Allocator>& vec, Predicate predicate) {
auto iter = std::remove_if(vec.begin(), vec.end(), predicate);
auto dist = std::distance(iter, vec.end());
c.erase(iter, vec.end());
return dist;
}
namespace pmr {
template <class T>
using vector = container::vector<T, std::pmr::polymorphic_allocator<T>>;
}
}
#endif
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:14:14.067",
"Id": "503296",
"Score": "0",
"body": "That's a lot of code for a beginner!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:17:47.330",
"Id": "503297",
"Score": "1",
"body": "@MartinYork This made me laugh actually haha. Well, remember, length and code correctness are two different things... :S"
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>One of the good implementations of vector I have seen. Still a couple of bugs.</p>\n<hr />\n<p>You make an attempt at strong exception gurantees but I don't think you get there. The standard pattern for achieving this will make you much more successful.</p>\n<ol>\n<li>Create Temporary.<br />\nCopy/Move data into Temporary.</li>\n<li>Swap (Exception safe)</li>\n<li>Destroy old state.</li>\n</ol>\n<p>Note: You can use the constructor/destructor to achieve steps 1 and 3 which just means you need to implement the swap semantics.</p>\n<p>Have a read of this article I wrote: <a href=\"https://lokiastari.com/blog/2016/03/12/vector-resize/index.html\" rel=\"nofollow noreferrer\">https://lokiastari.com/blog/2016/03/12/vector-resize/index.html</a></p>\n<hr />\n<p>You should add a swap method and swap function. It will make several standard pattern easier.</p>\n<hr />\n<h2>Questions</h2>\n<p>Why are you using three different namespaces? <code>constants</code>, <code>random_access</code> and <code>container</code>. Seems like they are all part of the same namespace to me.</p>\n<h2>Common Patterns</h2>\n<p>I see a lot of this pattern:</p>\n<pre><code>for (size_type index{ 0 }; index < m_size; ++index)\n std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index, std::move(*(other.m_vector + index)));\n</code></pre>\n<p>Where you don't use braces around the code inside a <code>for()</code> loop. This is a bad habit and going to burn you one day. Best practice is to always add the braces to make sure that you never accidentally only execute one statement. Your gellow coders will appreciate it.</p>\n<h2>Code Review</h2>\n<p>First time I have seen the <code>space ship operator</code> used by somebody in code.</p>\n<pre><code> constexpr auto operator<=>(const iterator&) const = default;\n</code></pre>\n<hr />\n<p>You seem to have missed a new line.<br />\nYou have the newline in the <code>--operator</code></p>\n<pre><code> constexpr iterator operator++(int) noexcept { \n iterator tmp(*this); ++(*this); \n return tmp; \n }\n</code></pre>\n<hr />\n<p>Never seen this in user defined iterator before.</p>\n<pre><code> friend constexpr iterator operator+(difference_type first, const iterator& other) noexcept { \n return other.m_iterator + first;\n }\n</code></pre>\n<p>It will lead to this:</p>\n<pre><code> iterator y = con.begin();\n iterator x = 5 + y; \n</code></pre>\n<p>But it is supported by the standard iterators (though I had to write code to check std::vector). So It seems to fit logically.</p>\n<hr />\n<p>Normally when you override the <code>operator==</code> you symmetrically also provide the <code>operator!=</code> version.</p>\n<pre><code> constexpr friend bool operator== (const iterator& first, const iterator& second) { \n return first.m_iterator == second.m_iterator; \n }\n };\n</code></pre>\n<hr />\n<p>To match C-Array (which is what std::vector also does) you should destroy the objects in reverse order of creation.</p>\n<pre><code> constexpr void destruct(std::size_t size) {\n for (std::size_t index{ 0 }; index < size; ++index)\n std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + index);\n m_size = 0;\n }\n</code></pre>\n<hr />\n<p>You learn something new every day:</p>\n<pre><code>for (size_type index{ 0 }; const auto & currentValue : values)\n</code></pre>\n<p>I have never seen that <code>for()</code> loop construct before. That is actually quite usefull.</p>\n<hr />\n<p>Again I would destroy in reverse order of creation.</p>\n<pre><code>constexpr void deallocate_destruct_keep_size_and_capacity(std::size_t size, std::size_t capacity);\n</code></pre>\n<hr />\n<p>I believe there is a bug here:</p>\n<pre><code> constexpr void uninitialized_alloc_move(vector&& other) noexcept {\n m_size = other.m_size;\n m_capacity = other.m_capacity;\n for (size_type index{ 0 }; index < m_size; ++index)\n std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + index, std::move(*(other.m_vector + index)));\n\n\n // This call to reset sets all the members of `other` to 0/nullptr\n // I believe you just leaked all the memory from `other.\n reset(other);\n\n // Note: Simply deallocating other is not enough either.\n // The members of the `other` container are still valid\n // objects so they need to be destroyed.\n //\n // I think this needs:\n // other.deallocate_and_destruct();\n\n }\n</code></pre>\n<hr />\n<p>This does work. But you made me look it up.</p>\n<pre><code>if (std::is_nothrow_move_constructible<Type>::value || \n !std::is_nothrow_move_constructible<Type>::value && \n !std::is_copy_constructible<Type>::value)\n</code></pre>\n<p>Better to make clear your intention to the reader using braces.</p>\n<hr />\n<p>This does not provide the strong gurantee.</p>\n<pre><code> constexpr void reallocate_strong_guarantee(std::size_t capacity) {\n Type* tempVect = std::allocator_traits<allocator_type>::allocate(m_allocator, capacity);\n\n // This is known at compile time.\n // You should use the `constepxr if` or SFINE to make sure\n // only one piece of code is actually planted by the compiler.\n if (/*MOVABLE NOTHROW*/) {\n // STUFF\n } \n else {\n size_type copiesMade{ 0 };\n try {\n // STUFF\n }\n\n catch (...) {\n // Don't forget reverse order of destruction.\n for (std::size_t index{ 0 }; index < copiesMade; ++index)\n // Note this can also potentially throw.\n // You don't know what the destructor of T will do.\n std::allocator_traits<allocator_type>::destroy(m_allocator, tempVect + index);\n \n // If the `destroy()` above throws for any member\n // you are goint to leak the `tempVect` object here.\n // A simple solution is to place the `tempVect` inside `std::unique_ptr`\n // while you are working on it (and release it when you assign to `m_vector`.\n std::allocator_traits<allocator_type>::deallocate(m_allocator, tempVect, capacity);\n\n throw;\n }\n }\n size_type temp_cap = capacity;\n\n // Again you have a issue with destruction of the members\n // If anything goes wrong during this function call and\n // an exception escapes this object is now in a bad state\n // (some members are in a bad state and tempVect is leaked.\n deallocate_destruct_keep_size_and_capacity(m_size, temp_cap);\n m_vector = tempVect;\n tempVect = nullptr;\n }\n</code></pre>\n<p>The classic way to provide the strong exception gurantee is to do this in three distinct phases.</p>\n<pre><code> 1: Allocate Temporary state.\n Copy/Move all data into the Temporary state.\n 2: SWAP the temporary state and the current state.\n 3: Deallocate and release the Temporary state.\n</code></pre>\n<p>If something goes wrong in phase 1 or 3 the current state of the object is not affected. Unfortunately because you attempt to deallocate before swapping the state you potentially are left with an object in an inconsistent state.</p>\n<hr />\n<p>Interesting attempt!</p>\n<pre><code> constexpr void shift_and_construct(std::size_t index_pos, const Type& value, std::size_t count = 1) {\n</code></pre>\n<p>I don't think you can provide this gurantee.</p>\n<pre><code> // Should provide strong exception guarantee.\n</code></pre>\n<p>You can only provide as much of a guarantee as the <code>T</code> type provides. This is because you are copying over elements. If something goes wrong one way it can go just as bad trying to put it back.</p>\n<hr />\n<p>Declare variables as close to their place of use as possible.</p>\n<pre><code> size_type copies_made{ 0 };\n size_type copies_made1{ 0 };\n size_type copies_made2{ 0 };\n</code></pre>\n<hr />\n<pre><code> try {\n while (current_pos++ != m_vector + size()) {\n *(--(count_after_last_element)) = *(--(last_element));\n ++copies_made1;\n }\n }\n catch (...) {\n while (copies_made1 != 0) {\n\n // If you destroy objects then they are not in a valid state.\n\n // The best you can do is copy them back.\n // But I would not even try and do that as copying them\n // back could also result in an exception.\n //\n // Your move is only as good as the guarantees that are provided by T\n\n std::allocator_traits<Allocator>::destroy(m_allocator, m_vector + size() + 1 + copies_made1);\n --copies_made1;\n }\n throw;\n }\n</code></pre>\n<hr />\n<p>BUG: You can not destroy an object that does not exist.</p>\n<pre><code> constexpr void insert_end_strong_guarantee(const Type& value) {\n try {\n std::allocator_traits<allocator_type>::construct(m_allocator, m_vector + m_size, value);\n }\n catch (...) {\n // You can not call the destructor on an object that has\n // failed in construction.\n //\n // The constructor either works or it fails.\n // If it fails the object does not exist and thus can\n // can nto be destoryed.\n\n std::allocator_traits<allocator_type>::destroy(m_allocator, m_vector + m_size);\n throw;\n }\n</code></pre>\n<hr />\n<p>Personally I dislike when you initialize half the variables in the declaration and half in the initializer list. As a maintainer I need to keep flicking back to check what was done in the variable list above.</p>\n<pre><code> constexpr vector() noexcept : m_vector{ nullptr } {}\n</code></pre>\n<hr />\n<p>Here you are assuming that <code>input_iter</code> is actually a <code>Random Accesses Iterator</code>.</p>\n<pre><code> template<typename input_iter>\n constexpr vector(input_iter first, input_iter last, const_alloc_reference allocator = Allocator()) {\n size_type size = std::distance(last, first);\n allocate(size);\n for (size_type index{ 0 }; index < size; ++index) {\n\n // Note: first + index is not always valid on all iterator\n // types.\n std::allocator_traits<Allocator>::construct(m_allocator, m_vector + index, *(first + index));\n ++m_size;\n }\n }\n</code></pre>\n<hr />\n<p>This does not provide the strong exception guarantee. You destroy the current object before you even attempt to make a copy. Thus if the copy fails your object is in an invalid state.</p>\n<p>Also the use of self assignment is code pesimization for the normal (expect) assignment situations (yes you should account for self assignment but it is rare in real code so explicitly optimizing for it actually makes normal code worse).</p>\n<pre><code> constexpr vector& operator=(const vector& other) {\n if (this == &other) { return *this; }\n destruct(size());\n if (other.m_vector)\n {\n if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {\n m_allocator = other.get_allocator();\n }\n if (other.size() > capacity()) {\n reallocate(capacity(), other.size());\n }\n uninitialized_alloc_copy(other);\n }\n else {\n m_vector = nullptr;\n m_size = 0;\n }\n return *this;\n }\n</code></pre>\n<p>The standard way fo doing the assignemnt operator copes with both situations:</p>\n<pre><code> constexpr vector& operator=(vector const& other)\n {\n vector tmp(other); // Copy\n other.swap(*this); // Swap current and other state.\n return *this;\n } // Tmp state cleaned up.\n</code></pre>\n<p>Strong exception guarantee. Does not have pesimizzing self assignment check.</p>\n<hr />\n<p>Sure this works:</p>\n<pre><code> constexpr vector(vector&& other) noexcept\n : m_vector{ other.m_vector }, m_size{ other.m_size }, m_capacity{ other.m_capacity }, m_allocator{ std::move(other.m_allocator) } {\n \n reset(other);\n }\n</code></pre>\n<p>But the standard implementation is easier to read:</p>\n<pre><code> constexpr vector(vector&& other) noexcept\n : m_vector(nullptr)\n , m_size(0)\n , m_capacity(0)\n {\n other.swap(*this);\n }\n</code></pre>\n<hr />\n<p>Again this does not provide the strong exception guarantee. Because you destroy the state of this object before swapping. This leaves your object in a an invalid state if something goes wrong during the destruction of the members.</p>\n<pre><code> constexpr vector& operator=(vector&& other) noexcept {\n if (this == &other) { return *this; }\n\n if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {\n deallocate_and_destruct(capacity(), size());\n m_allocator = other.get_allocator();\n m_vector = other.m_vector;\n reset(other);\n }\n else if (m_allocator == other.m_allocator) {\n deallocate_and_destruct(capacity(), size());\n m_vector = other.m_vector;\n reset(other);\n }\n else {\n destruct(size());\n reallocate(capacity(), other.capacity());\n uninitialized_alloc_move(std::move(other));\n }\n m_size = other.m_size;\n m_capacity = other.m_capacity;\n\n return *this;\n }\n</code></pre>\n<p>The standard pattern for this:</p>\n<pre><code> constexpr vector& operator=(vector&& other) noexcept\n {\n other.swap(*this);\n // If you feel inclined you can now reset the state of other.\n other.clear(); // This destroys all the objects.\n // But should leave the capacity in place.\n // The other object can potentially be re-used\n // without having to reallocate space.\n // And if it is not re-used its destructor\n // will clean up capacity.\n return *this;\n }\n</code></pre>\n<hr />\n<p>Again not exception safe and thus does not provide the strong gurantee.</p>\n<pre><code> // Overloaded operators\n constexpr vector& operator=(init_list_type values) {\n destruct(m_size);\n if (values.size() > capacity()) {\n reallocate(capacity(), values.size());\n }\n\n construct_init_list(values);\n return *this;\n }\n</code></pre>\n<p>Do it like this:</p>\n<pre><code> constexpr vector& operator=(init_list_type values) {\n vector tmp(values);\n tmp.swap(*this);\n return *this;\n }\n</code></pre>\n<hr />\n<p>Sure:</p>\n<pre><code> constexpr pointer data() noexcept {\n return (size() != 0) ? m_vector : nullptr; \n }\n</code></pre>\n<p>BUT that seems like an over complex way of saying:</p>\n<pre><code> constexpr pointer data() noexcept {return m_vector;}\n</code></pre>\n<p>Why does it have to be <code>nullptr</code> if the size is zero?</p>\n<hr />\n<p>Is this true:</p>\n<pre><code> constexpr size_type max_size() const noexcept { \n return std::numeric_limits<difference_type>::max(); \n }\n</code></pre>\n<p>You can really allocate this amount of memory?</p>\n<hr />\n<p>Is this a way of asking if <code>capacity == 0</code> ?</p>\n<pre><code> constexpr bool is_null() const noexcept { \n return m_vector == nullptr; \n }\n</code></pre>\n<p>Why do you want to be able to do this. Personally I think you have overcomplicated your code by using <code>nullptr</code> to represent a zero capacity vector. I would have always allocated space (I assume if you declare it will be used).</p>\n<hr />\n<p>In your case can this ever fail (<code>capacity > max_size()</code>)?</p>\n<pre><code> constexpr void reserve(size_type capacity) {\n if (capacity > max_size())\n throw std::length_error("Capacity allocated exceeds max_size()");\n\n else if (capacity > m_capacity)\n reallocate_strong_guarantee(capacity);\n }\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T20:59:17.743",
"Id": "503324",
"Score": "1",
"body": "“Normally when you override the `operator==` you symmetrically also provide the `operator!=` version.” Not anymore. In fact, since `operator<=>` is defaulted in `iterator`, even `operator==` is unnecessary. In the `vector` class, you could also get away with just `operator<=>` and `operator==` (you need `operator==` in `vector` because `operator<=>` can’t be defaulted, due to the allocator member)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T21:37:05.093",
"Id": "503327",
"Score": "0",
"body": "Woah, thanks a lot for the review! I'll have to read this carefully and fix whatever has to be fixed. Regarding the last question (capacity > max_size()), I implemented that according to Cppreference - although it's true that hardly ever can that happen, especially in a custom implementation. Once again, thanks a lot for the feedback & review, it's really helpful and appreciated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:50:01.410",
"Id": "255154",
"ParentId": "255149",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255154",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:07:16.333",
"Id": "255149",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"vectors",
"stl"
],
"Title": "std::vector Allocator-Aware Implementation"
}
|
255149
|
<p>I have a Connect Four game with a board that I made with a bunch of print functions, which is incredibly inefficient:</p>
<pre><code> print(" 0 1 2 3 4 5 6")
print(" " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][
4] + " | " + board[0][5] + " | " + board[0][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][
4] + " | " + board[1][5] + " | " + board[1][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board[2][
4] + " | " + board[2][5] + " | " + board[2][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board[3][
4] + " | " + board[3][5] + " | " + board[3][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board[4][
4] + " | " + board[4][5] + " | " + board[4][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board[5][
4] + " | " + board[5][5] + " | " + board[5][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[6][0] + " | " + board[6][1] + " | " + board[6][2] + " | " + board[6][3] + " | " + board[6][
4] + " | " + board[6][5] + " | " + board[6][6])
print()
</code></pre>
<p>I want to know how I can replace my board using <code>for</code> loops such that the code will look neater and easier to change. <a href="https://paste.pythondiscord.com/buriritebe.md" rel="nofollow noreferrer">Here</a> is the rest of my code if you need any references.</p>
|
[] |
[
{
"body": "<p>I think like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(" 0 1 2 3 4 5 6")\nfor row in board:\n print(" " + " | ".join(row))\n print(" ---+---+---+---+---+---+---")\nprint()\n</code></pre>\n<p>You could put the whole thing into a single call to print by using "\\n".join and more string concatenation, but that would most likely make it a lot less readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:15:54.820",
"Id": "503305",
"Score": "0",
"body": "Thank you! Do you know how I can create a diagonal check for the winner function? I don't know how to do that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:26:47.950",
"Id": "503308",
"Score": "0",
"body": "That’s better for stackoverflow, this site is for reviewing and making suggestions for finished and working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:34:35.393",
"Id": "503313",
"Score": "0",
"body": "I suppose so, but no one's answering my question lopl"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T20:20:36.340",
"Id": "503321",
"Score": "0",
"body": "You could just use another pair of nested loops since it looks like that’s what you’re using for checking vertical and diagonal lines. But I think you could also set it up so it only checks around the space a piece was placed in. That would be cool to do because it would make it so it would take the same amount of time to check no matter how big the board is."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:56:59.833",
"Id": "255152",
"ParentId": "255151",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:42:12.667",
"Id": "255151",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Replacing Connect Four code with a for loop"
}
|
255151
|
<p>I’ve the following function which should be run in production
I read some config If valid add the runner otherwise just return,
the function is working!
Is there a cleaner/better way to do it in go? error handling...</p>
<p><a href="https://play.golang.org/p/QcU9YHDXo36" rel="nofollow noreferrer">https://play.golang.org/p/QcU9YHDXo36</a></p>
<pre><code>func (z *zmp) Add(val string, runner Runner) {
vmap := viper.GetStringMap(val)
if len(vmap) > 0 {
if val, ok := configs["active"]; ok {
if !val.(bool) {
log.info(“not valid”)
return
}
}
}
z.Add(runner)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T17:23:46.873",
"Id": "504291",
"Score": "0",
"body": "Also: using viper, I'd not bother with manually checking my own map, doing all the type assertions etc... I'd use `viper.SetDefault(key, values)`, where values can be a map, or a single value. I would also avoid relying on `map[string]interface{}` as much as possible, in favour of dedicated config types with `json` or `yaml` tags instead."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T21:10:48.963",
"Id": "255155",
"Score": "1",
"Tags": [
"beginner",
"go"
],
"Title": "Read value from config and return function"
}
|
255155
|
<p>This is a matrix class with addition and multiplication. I tried incorporating all the helpful advice I got on my previous attempt <a href="https://codereview.stackexchange.com/questions/255061/c-matrix-class">C++ matrix class</a> , specifically using std::vector for memory management, overloading operators, adding error messages and adhering to the rule of 5.</p>
<pre><code>#include <iostream>
#include <vector>
template<typename T>
class Matrix {
public:
// Default constructor
Matrix();
// Constructor
Matrix(int m, int n, std::vector<T> data): rows_{m}, columns_{n} {
if (m*n != (int) data.size()) {
throw "Dimensions do not match data!";
}
data_ = data;
}
// Copy constructor (makes a copy of the argument)
Matrix(const Matrix<T>& other): rows_{other.rows_}, columns_{other.columns_} {
data_ = other.data_;
}
// Move constructor (moves the information of the argument to the created object, the
// argument is destroyed)
Matrix(Matrix<T>&& other): rows_{other.rows_}, columns_{other.columns_}, data_{other.data_} {
other.data_.~vector();
}
// Copy assignment operator (overloads = when we have an object on the other side of =)
Matrix<T>& operator=(const Matrix<T>& other) {
if (this != &other) {
rows_ = other.rows_;
columns_ = other.columns_;
data_ = other.data_;
}
return *this;
}
// Move assignment operator (overloads = when we have a reference on the other side =)
Matrix<T>& operator=(Matrix<T>&& other) {
if (this != &other) {
rows_ = other.rows_;
columns_ = other.columns_;
data_ = &other.data_;
other.data_.~vector();
}
return *this;
}
// Destructor
~Matrix() {
data_.~vector();
}
// Returns a reference to the entry at (i, j), so we can change it.
T& operator()(int i, int j) {
return data_.at(columns_*i + j);
}
Matrix<T> operator+(const Matrix<T>& other) {
if (columns_ != other.columns_ || rows_ != other.rows_) {
throw "Addition failure: dimensions do not match";
}
// (Why doesn't 'Matrix<T> sum = this' work as an application of the copy constructor?)
Matrix<T> sum(rows_, columns_, data_);
for (int i = 0; i < rows_*columns_; i++) {
sum.data_[i] += other.data_[i];
}
return sum;
}
// Design question: how can I change operator() to allow other to be constant?
Matrix<T> operator*(Matrix<T>& other) {
if (columns_ != other.rows_) {
throw "Multiplication error: dimensions do not match";
}
std::vector<T> product;
for (int i = 0; i < rows_; i++) {
for (int j = 0; j < other.columns_; j++) {
T sum = 0;
for (int k = 0; k < columns_; k++) {
sum += other(k, j) * this->operator()(i, k);
}
product.push_back(sum);
}
}
return Matrix(rows_, columns_, product);
}
private:
int rows_;
int columns_;
std::vector<T> data_;
template<typename U>
friend std::ostream& operator<<(std::ostream& outputStream, Matrix<U>& matrix);
};
template<typename U>
std::ostream& operator<<(std::ostream& outputStream, Matrix<U>& matrix) {
for (int i = 0; i < matrix.rows_; i++) {
outputStream << '{';
for (int j = 0; j < matrix.columns_ - 1; j++) {
outputStream << matrix(i, j) << ", ";
}
outputStream << matrix(i, matrix.columns_ - 1) << "}\n";
}
return outputStream;
}
int main() {
std::vector<int> data{1, 2, 3, 4};
Matrix<int> mat(2, 2, data);
Matrix<int> sum = mat + mat;
Matrix<int> product = mat * mat;
std::cout << mat << "+\n" << mat << "=\n" << sum;
std::cout << "------------------" << std::endl;
std::cout << mat << "*\n" << mat << "=\n" << product;
mat(0, 0) = 0;
std::cout << "Changed mat:\n" << mat;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:41:09.580",
"Id": "503347",
"Score": "1",
"body": "If you use `std::vector` the compiler generated copy and move constructor, copy and move assignment is okay, you do not need to redefine it except you manually manage your memory."
}
] |
[
{
"body": "<ul>\n<li><p>The default constructor <code>Matrix()</code> is declared, but I don't see it defined anywhere. It should initialize <code>rows_</code> and <code>columns_</code> to zero.</p>\n</li>\n<li><p>Throwing a <code>std::runtime_error</code> or <code>std::invalid_argument</code> exception object would be better than a plain string literal (it's useful to have type information about what went wrong, and easier to use when <code>catch</code>ing, since they derive from <code>std::exception</code>).</p>\n</li>\n<li><p>The move and copy constructors and assignment operators do the same things that we can make the compiler generate with <code>= default;</code>:</p>\n<pre><code>Matrix(const Matrix&) = default;\nMatrix(Matrix&&) = default;\nMatrix& operator=(const Matrix&) = default;\nMatrix& operator=(Matrix&&) = default;\n</code></pre>\n<p>Note that inside the class, we can use <code>Matrix</code> to mean the same as <code>Matrix<T></code>.</p>\n</li>\n<li><p><strong>bug:</strong> We must not call the vector destructor explicitly (e.g. <code>data_.~vector()</code>). Member destructors (i.e. including the <code>data_</code> destructor) are called automatically after the class destructor. We don't need to do it manually. This means we can omit the <code>~Matrix()</code> function, as the compiler generated version will work fine.</p>\n</li>\n<li><p>We need a <code>const</code> version of the element access operator, i.e. <code>T const& operator()(int i, int j) const;</code>. This allows us to access elements in a <code>const Matrix</code> object. (Note: this is why <code>operator*</code> doesn't currently work with a <code>const Matrix&</code>).</p>\n</li>\n<li><p>To invoke the copy constructor inside <code>operator+</code>, we need <code>Matrix sum = *this;</code> (Remember that <code>this</code> is a pointer so we have to dereference it).</p>\n</li>\n<li><p>We should use <code>std::size_t</code>, not <code>int</code>, for <code>rows_</code> and <code>columns_</code> and the corresponding index arguments. This matches the <code>size_type</code> of our vector member. It's also safer: right now <code>Matrix(-2, -2, { 0, 1, 2, 3 })</code> doesn't trigger the size check exception!</p>\n</li>\n<li><p>We could do with some more functionality: it would be useful to have <code>const</code> member functions to return the number of <code>rows()</code>, <code>columns()</code> and the overall <code>size()</code> (<code>rows() * columns()</code>).</p>\n<p>We could also add <code>begin()</code>, <code>end()</code>, <code>rbegin()</code> and <code>rend()</code> functions, so that we could iterate over all the members in a matrix easily (e.g. <code>for (auto v : matrix)</code>). These could call the corresponding <code>std::vector</code> member functions and return <code>std::vector<T>::iterator</code>s.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T02:11:12.610",
"Id": "503442",
"Score": "1",
"body": "It is very ill advised to make move-ctor/assignment to be defaulted in such cases. As then moved-from object is in an invalid state where rows/cols don't match with the vector it contains leading to variety of bugs that users will encounter. While it is not strictly required by the language standard, it is a poor design choice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:31:32.247",
"Id": "255174",
"ParentId": "255157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255174",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T22:56:59.900",
"Id": "255157",
"Score": "1",
"Tags": [
"c++",
"beginner",
"object-oriented"
],
"Title": "C++ matrix class follow up"
}
|
255157
|
<p>Given a int optimumMemory and int[] array with list of available memories find the pair of indexes of memories whose sum of the values will be equal to the optimumMemory?</p>
<p>If there exists more than one such pair whose sum of values are equal to the optimumMemory then filter out the indexes for the below conditions</p>
<p><strong>condition1:</strong> find the pair of indices which has maximumMemory</p>
<p><strong>condition2:</strong> If there exists 2 pairs with same maximumMemory then select the pair with lowest index</p>
<p>Example: int optimumMemory = 10MB int[] availableMemories= [6,3,8,1,1,4,9,2,9,7]</p>
<p>The pair of indices whose sum is equal to 10MB ={(0,5),(1,9),(2,7),(3,6),(3,8),(4,6),(4,8)};</p>
<p>applying condition1 to the above list ={(3,6),(3,8),(4,6),(4,8)};</p>
<p>applying condition2 to the above list will result in only one order pair = {(3,6)}</p>
<pre><code>import com.sun.tools.javac.util.Pair;
public class Test(){
public static void main(String[] args){
int optimumMemory = 10;
int[] list = new int[]{6,3,8,1,1,4,9,2,9,7};
Pair<Integer,Integer> result = new Pair<>(Integer.MIN_VALUE,Integer.MIN_VALUE);
//2 pointer approach
for(int i=0;i<list.length;i++){
for(int j=i+1;j<list.length;j++){
//checking if the sum of memory is equal to optimumMemory
if(list[i]+list[j] == optimumMemory){
Pair<Integer,Integer> pair = new Pair<>(i,j);
//this happens only once, when the very first pair that satisfies the condition is found
if(result.fst==Integer.MIN_VALUE && result.snd == Integer.MIN_VALUE)
{
result = pair;
continue;
}
int maximumMemoryInResult = Math.max(list[result.fst],list[result.snd]);
int maximumMemoryInPair = Math.max(list[pair.fst],list[pair.snd]);
//applying **condition1**
if(maximumMemoryInResult < maximumMemoryInPair){
result = pair;
continue;
}//end of condition1
//applying **condition2**
else if(maximumMemoryInResult == maximumMemoryInPair){
int minIndexInResult = Math.min(result.fst,result.snd);
int minIndexInPair = Math.min(pair.fst,pair.snd);
if(minIndexInPair<minIndexInResult){
result = pair;
continue;
}
}//end of condition2
}
}//end of j loop
}// end of i loop
}// end of main method
}
</code></pre>
<p>Is there any way to improve the code I posted?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:06:30.687",
"Id": "503339",
"Score": "1",
"body": "You can at least try and indent correctly, introduce some methods and make it runnable code, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:13:25.113",
"Id": "503340",
"Score": "0",
"body": "Where is your \"Pair\" implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:24:08.407",
"Id": "503345",
"Score": "0",
"body": "I used Pair class that is available in the core Java libraries"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:33:52.063",
"Id": "503346",
"Score": "0",
"body": "That would be `com.sun.tools.javac.util.Pair` then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:25:16.290",
"Id": "503349",
"Score": "0",
"body": "Yes, I have added the imports section in the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T02:19:12.970",
"Id": "503358",
"Score": "2",
"body": "Alright. Maybe you can change the title of your question though, as asking for a better coding practice is *way* too generic for [codereview.se] :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T12:14:24.180",
"Id": "503381",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>First, lets show how I'd solve this. Of course, I've got a bit more experience with classes and such.</p>\n<p>Note that I have left out quite a few checks, e.g. of negative sizes, invalid references and <code>MemoryReferences</code> without references.</p>\n<pre><code>package com.stackexchange.codereview;\n\nimport java.util.Optional;\n\npublic class Memories {\n\n public static class MemoryReferences implements Comparable<MemoryReferences> {\n \n private int[] memorySizes;\n private int[] refs;\n\n public MemoryReferences(int[] list, int ... refs) {\n this.memorySizes = list;\n this.refs = refs;\n }\n \n public int totalMemory() {\n int total = 0;\n for (int ref : refs) {\n total += memorySizes[ref];\n }\n return total;\n }\n \n private int refWithMax() {\n int refWithMax = refs[0];\n int max = memorySizes[refWithMax];\n for (int refIndex = 1; refIndex < refs.length; refIndex++) {\n int curRef = refs[refIndex];\n int curValue = memorySizes[curRef]; \n if (curValue > max) {\n refWithMax = curRef;\n max = curValue;\n }\n }\n return refWithMax;\n }\n\n @Override\n public int compareTo(MemoryReferences that) {\n int totalCompared = Integer.compare(this.totalMemory(), that.totalMemory());\n if (totalCompared != 0) {\n return totalCompared;\n }\n \n return Integer.compare(memorySizes[this.refWithMax()], memorySizes[that.refWithMax()]);\n }\n \n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (int ref : refs) {\n if (sb.length() != 0) {\n sb.append(", ");\n }\n sb.append(Integer.toString(ref));\n }\n \n return sb.toString();\n }\n }\n \n public static Optional<MemoryReferences> getLocationsWithOptimumMemory(int[] memorySizes, int optimumMemory) {\n Optional<MemoryReferences> optMem = Optional.empty();\n \n for (int i = 0; i < memorySizes.length; i++) {\n for (int j = i + 1; j < memorySizes.length; j++) {\n MemoryReferences curMem = new MemoryReferences(memorySizes, i, j);\n \n if (curMem.totalMemory() == optimumMemory) {\n if (optMem.isEmpty()) {\n optMem = Optional.of(curMem);\n } else if (curMem.compareTo(optMem.get()) > 0) {\n optMem = Optional.of(curMem);\n }\n }\n } \n }\n return optMem;\n }\n\n public static void main(String[] args) {\n {\n int optimumMemory = 10;\n int[] memorySizes = new int[] { 6, 3, 8, 1, 1, 4, 9, 2, 9, 7 };\n\n Optional<MemoryReferences> optMem = getLocationsWithOptimumMemory(memorySizes, optimumMemory);\n \n if (optMem.isPresent()) {\n System.out.println(optMem.get());\n } \n }\n }\n}\n</code></pre>\n<p>The main idea of this class is to get rid of the overly complex code within the loops and if statements.</p>\n<p>It uses a little trick by referencing <code>memorySizes</code> (previously <code>list</code>). As it is a reference, it won't actually consume any additional memory. Instead of making it a pair I allowed any number of references as it was actually easier to program it that way.</p>\n<p>It's slightly slow because it always calculates the <code>total</code> and such but hey, maybe <code>memorySizes</code> changes dynamically, right? It implements <code>Comparable</code> to look for the best option out there.</p>\n<hr />\n<p>Great, that out of the way, let's do the review:</p>\n<p>First of all, there is way too little white-space in the code, compare your code with mine, e.g. put spaces between the memory sizes in <code>list</code>.</p>\n<pre><code>import com.sun.tools.javac.util.Pair;\n</code></pre>\n<p>That's a Java implementation class. You should never use any classes within <code>com.sun</code> packages unless they have explicitly been indicated as being a public API.</p>\n<pre><code>int[] list = new int[]{6,3,8,1,1,4,9,2,9,7};\n</code></pre>\n<p>Please don't call an array <code>list</code>. And always name containers after the elements they contain.</p>\n<pre><code>Pair<Integer,Integer> result = new Pair<>(Integer.MIN_VALUE,Integer.MIN_VALUE);\n</code></pre>\n<p>Never use magics to indicate a bad result. Use <code>null</code> if you have to. But now the result will be set to this result if there isn't an <code>optimalMemory</code>. That's not correct, how are you going to check this?</p>\n<pre><code>Pair<Integer,Integer> pair = new Pair<>(i,j);\n</code></pre>\n<p>Again with the naming, what does <code>pair</code> mean, and a pair of what? At least call it <code>pairOfReferences</code> or <code>curPairOfReferences</code>. Don't be afraid of longer names, as long as they are functional.</p>\n<pre><code> //this happens only once, when the very first pair that satisfies the condition is found\n</code></pre>\n<p>Great comment, very helpful. However it would be even better if you can code in such a way that such comments are not needed at all (hence my use of <code>Optional</code> in the code above).</p>\n<pre><code>int maximumMemoryInResult = Math.max(list[result.fst],list[result.snd]);\nint maximumMemoryInPair = Math.max(list[pair.fst],list[pair.snd]);\n</code></pre>\n<p>Here you show a much better control over variable names, great!</p>\n<pre><code>else if(maximumMemoryInResult == maximumMemoryInPair){\n</code></pre>\n<p>Do you really need the confusing <code>else</code> if you just did a <code>continue</code> on the previous line?</p>\n<pre><code>int minIndexInResult = Math.min(result.fst,result.snd);\nint minIndexInPair = Math.min(pair.fst,pair.snd);\n</code></pre>\n<p>Think about this: when will <code>result.snd</code> ever be smaller than <code>result.fst</code>? Same for <code>pair</code>?</p>\n<pre><code> continue;\n }\n}//end of condition2\n</code></pre>\n<p>Yeah, that continue is a bit wasted on me, we're at the end anyway.</p>\n<pre><code>}// end of main method\n</code></pre>\n<p>I personally dislike end of line comments with a passion. But besides that, loops and if statements should not need them to indicate where they end. You can do that by moving code out of the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T03:42:17.160",
"Id": "503361",
"Score": "0",
"body": "Thank-you for the reply"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T13:32:15.707",
"Id": "503384",
"Score": "0",
"body": "\"At least call it pairOfReferences or curPairOfReferences\" For many cases I'd even go further: Pairs are often horrible to understand (not only in Java) when re-reading even own code. If not quite closely located and used to according semantic types like maps, you often have to think about them at least twice again and again. Self-explaining classes/structs are often the better alternative here I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T15:48:26.363",
"Id": "503398",
"Score": "0",
"body": "Yeah, that's kind of why I created just such a thing. They don't scale either."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T01:42:22.407",
"Id": "255163",
"ParentId": "255158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T23:04:06.053",
"Id": "255158",
"Score": "0",
"Tags": [
"java",
"algorithm",
"comparative-review"
],
"Title": "need some guidance for better coding practice"
}
|
255158
|
<p>I'm writing a program that has the possibility of outputting a large amount of text on a single logical line to the console. In that scenario, I would like to wrap the text at word ends so that words are not split on the end of the line:
i.e., the string <code>lorem ipsum dolor sit amet</code> should print:</p>
<pre><code>lorem ipsum dolor
sit amet
</code></pre>
<p>as opposed to</p>
<pre><code>lorem ipsum dolor si
t amet
</code></pre>
<p>I wrote the following function</p>
<pre><code>/* print a string, wrapping lines at word breaks */
void
print_long(const char *s, int maxlen)
{
int pos, len;
pos = 0;
while (pos < strlen(s)) {
len = maxlen;
for (int i = maxlen; i > 0; i--) {
if (s[pos + i] == '\n') {
len = i;
break;
}
}
if (len == maxlen) {
for (int i = maxlen; i > 0; i--) {
if (s[pos + i] == ' ') {
len = i;
break;
}
}
}
printf("%.*s\n", len, s + pos);
pos += len + 1;
}
}
</code></pre>
<p>This works on my limited test cases, but it seems overly complex and repetitive. I'm also concerned it could break on scenarios that I haven't tested for. How can I shorten this?</p>
<p>Thanks!</p>
<p><strong>Edit: Additional Test Cases</strong></p>
<p>Lorem ipsum from <a href="https://lipsum.com/" rel="nofollow noreferrer">https://lipsum.com/</a>, maxlen = 80.</p>
<pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sed ultricies diam. Sed auctor nisl libero, a rutrum leo dapibus eu. Aliquam sit amet elit enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl massa.
Integer placerat odio ut sagittis suscipit. Sed placerat bibendum tellus, nec tempus nulla dignissim at. Integer semper laoreet lacinia. Proin vitae volutpat justo, eget maximus erat. Ut lobortis, lectus bibendum ornare cursus, sem enim vehicula felis, vel iaculis mi eros vitae justo. Duis vel auctor massa. Pellentesque tincidunt vehicula ligula, sit amet pharetra metus vestibulum in. Aliquam aliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus. Nulla in magna ante.
Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis. Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum. Donec a elementum massa, nec porttitor tortor. Aenean dignissim tortor eget lacus fringilla, auctor hendrerit turpis hendrerit. Vivamus mattis purus ac malesuada luctus.
Sed ullamcorper arcu consectetur ex interdum semper. Integer blandit risus turpis, tempor porttitor augue porttitor et. Nunc sit amet consequat augue. Nullam malesuada risus eu neque elementum ullamcorper. Morbi volutpat leo vitae lacus sagittis, vel viverra lorem scelerisque. Nulla enim ipsum, cursus accumsan magna quis, imperdiet semper orci. Phasellus nisl dui, vehicula ac venenatis vel, imperdiet vitae tortor. Vestibulum eget consequat urna. Etiam id lectus sed velit dignissim iaculis. Nam ac lacus non nisi feugiat suscipit. Nullam eleifend ultricies sapien, eget faucibus erat sollicitudin in. Phasellus sed tellus id diam interdum iaculis. Curabitur vulputate, ante ut commodo tristique, metus lacus rutrum magna, ut pulvinar orci augue ac orci. Ut a felis libero. Integer mattis magna quis diam blandit, in auctor urna hendrerit.
Curabitur vestibulum ex in erat euismod, in lacinia neque vestibulum. Phasellus bibendum nunc sed nibh aliquam, suscipit fringilla dolor semper. Nulla vel felis scelerisque, iaculis velit in, gravida turpis. Cras dolor lacus, convallis et ex a, rutrum pretium mauris. Nam dapibus interdum ipsum, et scelerisque magna. Pellentesque tincidunt viverra consequat. Ut finibus nibh et enim lacinia, non sagittis felis viverra. Nulla laoreet mollis dui. Fusce erat lacus, bibendum ac urna in, pretium elementum velit.
</code></pre>
<p>Shold result in</p>
<pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sed ultricies
diam. Sed auctor nisl libero, a rutrum leo dapibus eu. Aliquam sit amet elit
enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus
bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit
non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl
massa.
Integer placerat odio ut sagittis suscipit. Sed placerat bibendum tellus, nec
tempus nulla dignissim at. Integer semper laoreet lacinia. Proin vitae volutpat
justo, eget maximus erat. Ut lobortis, lectus bibendum ornare cursus, sem enim
vehicula felis, vel iaculis mi eros vitae justo. Duis vel auctor massa.
Pellentesque tincidunt vehicula ligula, sit amet pharetra metus vestibulum in.
Aliquam aliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus.
Nulla in magna ante.
Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis.
Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat
venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum.
Donec a elementum massa, nec porttitor tortor. Aenean dignissim tortor eget
lacus fringilla, auctor hendrerit turpis hendrerit. Vivamus mattis purus ac
malesuada luctus.
Sed ullamcorper arcu consectetur ex interdum semper. Integer blandit risus
turpis, tempor porttitor augue porttitor et. Nunc sit amet consequat augue.
Nullam malesuada risus eu neque elementum ullamcorper. Morbi volutpat leo vitae
lacus sagittis, vel viverra lorem scelerisque. Nulla enim ipsum, cursus accumsan
magna quis, imperdiet semper orci. Phasellus nisl dui, vehicula ac venenatis
vel, imperdiet vitae tortor. Vestibulum eget consequat urna. Etiam id lectus sed
velit dignissim iaculis. Nam ac lacus non nisi feugiat suscipit. Nullam eleifend
ultricies sapien, eget faucibus erat sollicitudin in. Phasellus sed tellus id
diam interdum iaculis. Curabitur vulputate, ante ut commodo tristique, metus
lacus rutrum magna, ut pulvinar orci augue ac orci. Ut a felis libero. Integer
mattis magna quis diam blandit, in auctor urna hendrerit.
Curabitur vestibulum ex in erat euismod, in lacinia neque vestibulum. Phasellus
bibendum nunc sed nibh aliquam, suscipit fringilla dolor semper. Nulla vel felis
scelerisque, iaculis velit in, gravida turpis. Cras dolor lacus, convallis et ex
a, rutrum pretium mauris. Nam dapibus interdum ipsum, et scelerisque magna.
Pellentesque tincidunt viverra consequat. Ut finibus nibh et enim lacinia, non
sagittis felis viverra. Nulla laoreet mollis dui. Fusce erat lacus, bibendum ac
urna in, pretium elementum velit.
</code></pre>
<pre><code>Loremipsumdolorsitamet,consecteturadipiscingelit.Phasellussedultriciesdiam.Seductornislibero,arutrumleodapibus eu. Aliquam sit amet elit enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl massa.
Integerplaceratodiout sagittis suscipit. Sed placerat bibendum tellus, nec tempus nulla dignissim atInteger emper laoreetcinia.Proinvitaejusto,egeterat.Ut lobortis, lectus bibendum ornare cursus,sem enim vehicula felis,veliaculismi eros vitaejusto. Duisvelauctorssa. Pellentesquetinciduntvehiculaligulasitmetpharetrametusvestibulumin. Aliquamaliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus. Nulla in magna ante.
Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis. Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum. Donec a elementum massa, nec porttitor tortor. Aenean dignissimtortoregetlacusfringilla,auctorhendreritturpishendreritVivamusmattispurusacmalesuadaluctus.
</code></pre>
<p>Should result in</p>
<pre><code>Loremipsumdolorsitamet,consecteturadipiscingelit.Phasellussedultriciesdiam.Seductorni
libero,arutrumleodapibus eu. Aliquam sit amet elit enim. Pellentesque
pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque
tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar.
Fusce commodo vel ligula et porttitor. Duis eget nisl massa.
Integerplaceratodiout sagittis suscipit. Sed placerat bibendum tellus, nec
tempus nulla dignissim atInteger emper laoreetcinia.Proinvitaejusto,egeterat.Ut
lobortis, lectus bibendum ornare cursus,sem enim vehicula felis,veliaculismi
eros vitaejusto. Duisvelauctorssa.
Pellentesquetinciduntvehiculaligulasitmetpharetrametusvestibulumin.
Aliquamaliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus.
Nulla in magna ante.
Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis.
Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat
venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum.
Donec a elementum massa, nec porttitor tortor. Aenean
dignissimtortoregetlacusfringilla,auctorhendreritturpishendreritVivamusmattispur
sacmalesuadaluctus.
</code></pre>
<p>The second is identical to the previous case, but spaces are randomly removed to increase word length.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:32:18.363",
"Id": "503350",
"Score": "1",
"body": "Two problems: You're accessing past the end of your string, which results Undefined Behavior. And your code does not properly handle a word that is longer than your line length."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:37:02.723",
"Id": "503351",
"Score": "1",
"body": "Could you add your unit tests to the question? Having a single test case example for such a long function is not enough, by far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:38:51.823",
"Id": "503352",
"Score": "0",
"body": "@1201ProgramAlarm `s + pos` is never going to go past the end of the string due to the while loop, and, if the string is properly null-terminated, printf should never go past the bounds either, right? As for a word longer than line length, it should split at maxlen as if there was no wrapping, which is what I observed in testing. Am I misinterpreting my code or what you've said?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T01:06:55.967",
"Id": "503353",
"Score": "1",
"body": "The first character you access is `s[pos + maxlen]` (because `i` starts at `maxlen`) which can be past the end. For long words, `len` will be `maxlen`, and you add that +1 to pos so you'll skip a character (the first line of your second example shows this, as you lose an 's')."
}
] |
[
{
"body": "<h1>First, the bug</h1>\n<p>Consider this: what happens if you have a string that is shorter than <code>maxlen</code> as your input?</p>\n<p>Assume that <code>maxlen=78</code>, and the input string <code>s</code> is <code>"foo bar"</code>. You have <code>strlen(s) == 7</code>. So then <code>pos = 0</code> at first matches <code>(pos < maxlen)</code>, so the while loop starts, the for loop runs, and <code>s[pos + i]</code> is <code>s[0 + maxlen]</code> is <code>s[0 + 78]</code> which is considerably larger than <code>s[7]</code> where the terminal NUL character is stored in the input string.</p>\n<p>This is easy enough to fix, just compare the length against <code>maxlen</code> before you start looping. You might be done before you've begun!</p>\n<p>But this problem also appears when your string is longer than <code>maxlen</code>. If you have <code>maxlen=78</code> and <code>strlen(s) == 84</code> and <code>s[70] = '\\n'</code>, then your first pass consumes <code>s[0..70]</code> and the second pass starts with <code>pos = 71</code>, enters the first <code>for</code> loop with <code>i = maxlen</code> and accesses <code>s[pos + i]</code> which is <code>s[71 + 78]</code>, far outside the <code>s[84]</code> that you know is safe.</p>\n<p>This is less easy. You need to compare maxlen against the length remaining, and drop down to a lower value if need be. You can probably solve both cases by using something like <code>min(maxlen, strlen(s) - pos)</code>. You might want to cache <code>strlen(s)</code> though.</p>\n<h1>Next, the signature</h1>\n<p>You are receiving your <code>maxlen</code> parameter as an <code>int</code>. This probably makes some sense due to pointer subtraction, but you should convert that to a <code>size_t</code> either in the declaration or as soon as you validate the value (which you are presently not doing) inside the function.</p>\n<h1>Scan forwards</h1>\n<p>Right now you have two loops that both scan backwards from an arbitrary point. In the case where the line is long, you scan the entire string once looking for newlines, don't find one, then scan looking for spaces.</p>\n<p>You can combine your loops if you remember the last space, but automatically print on newline:</p>\n<pre><code>for (size_t i = 0; i < maxlen; ++i) {\n char ch = s[pos + i];\n if ('\\n' == ch) {\n len = i;\n break;\n }\n else if (' ' == ch) {\n len = i;\n /* NB: no break! */\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:28:38.610",
"Id": "503438",
"Score": "0",
"body": "There is a bug here that prevents endings from being correctly processed. Also, scanning forward is not a great idea - scanning backward is still more efficient."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T04:14:02.650",
"Id": "255164",
"ParentId": "255160",
"Score": "3"
}
},
{
"body": "<p>This was... rough.</p>\n<ul>\n<li>Your method is incorrect</li>\n<li>@aghast's method is incorrect</li>\n<li>Your reference outputs are incorrect</li>\n<li>You're missing unit tests; if you had included some, this would have been caught.</li>\n</ul>\n<p>First, all three methods along with the unit testing code:</p>\n<pre><code>#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\n#define LONG_OUTPUT 0\n\n\n// print a string, wrapping lines at word breaks\nstatic void lincoln(const char *s, size_t maxlen, FILE *out)\n{\n size_t len;\n\n for (size_t pos = 0; pos < strlen(s); pos += len + 1)\n {\n len = maxlen;\n\n for (size_t i = maxlen; i > 0; i--)\n {\n if (s[pos + i] == '\\n')\n {\n len = i;\n break;\n }\n }\n\n if (len == maxlen) \n {\n for (int i = maxlen; i > 0; i--) \n {\n if (s[pos + i] == ' ') \n {\n len = i;\n break;\n }\n }\n }\n\n fprintf(out, "%.*s\\n", (int)len, s + pos);\n }\n}\n\nstatic void aghast(const char *s, size_t maxlen, FILE *out)\n{\n size_t len;\n\n for (size_t pos = 0; pos < strlen(s); pos += len + 1)\n {\n len = maxlen;\n\n for (size_t i = 0; i < maxlen; ++i) {\n char ch = s[pos + i];\n if ('\\n' == ch) {\n len = i;\n break;\n }\n else if (' ' == ch) {\n len = i;\n /* NB: no break! */\n }\n }\n\n fprintf(out, "%.*s\\n", (int)len, s + pos);\n }\n}\n\n\nstatic void reinderien(const char *s, size_t maxlen, FILE *out)\n{\n for (size_t len = strlen(s); len > 0;)\n {\n if (len <= maxlen)\n {\n fwrite(s, 1, len, out);\n fputc('\\n', out);\n break;\n }\n\n // The memrchr() function is a GNU extension, available since glibc 2.1.91. \n // It would be better here, but anyway...\n size_t end, next;\n for (end = maxlen;; end--)\n {\n if (end == 0)\n {\n end = maxlen;\n next = maxlen;\n break;\n }\n if (s[end] == ' ')\n {\n next = end + 1;\n break;\n }\n }\n\n fwrite(s, 1, end, out);\n fputc('\\n', out);\n s += next;\n len -= next;\n }\n}\n\nconst char *method_names[] = { "lincoln", "aghast", "reinderien" };\nvoid(*methods[])(const char *s, size_t maxlen, FILE *out) = {\n lincoln,\n aghast,\n reinderien,\n};\n\n\nconst char *test_in[] = {\n "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sed ultricies diam. Sed auctor nisl libero, a rutrum leo dapibus eu. Aliquam sit amet elit enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl massa.",\n "Integer placerat odio ut sagittis suscipit. Sed placerat bibendum tellus, nec tempus nulla dignissim at. Integer semper laoreet lacinia. Proin vitae volutpat justo, eget maximus erat. Ut lobortis, lectus bibendum ornare cursus, sem enim vehicula felis, vel iaculis mi eros vitae justo. Duis vel auctor massa. Pellentesque tincidunt vehicula ligula, sit amet pharetra metus vestibulum in. Aliquam aliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus. Nulla in magna ante.",\n "Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis. Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum. Donec a elementum massa, nec porttitor tortor. Aenean dignissim tortor eget lacus fringilla, auctor hendrerit turpis hendrerit. Vivamus mattis purus ac malesuada luctus.",\n "Sed ullamcorper arcu consectetur ex interdum semper. Integer blandit risus turpis, tempor porttitor augue porttitor et. Nunc sit amet consequat augue. Nullam malesuada risus eu neque elementum ullamcorper. Morbi volutpat leo vitae lacus sagittis, vel viverra lorem scelerisque. Nulla enim ipsum, cursus accumsan magna quis, imperdiet semper orci. Phasellus nisl dui, vehicula ac venenatis vel, imperdiet vitae tortor. Vestibulum eget consequat urna. Etiam id lectus sed velit dignissim iaculis. Nam ac lacus non nisi feugiat suscipit. Nullam eleifend ultricies sapien, eget faucibus erat sollicitudin in. Phasellus sed tellus id diam interdum iaculis. Curabitur vulputate, ante ut commodo tristique, metus lacus rutrum magna, ut pulvinar orci augue ac orci. Ut a felis libero. Integer mattis magna quis diam blandit, in auctor urna hendrerit.",\n "Curabitur vestibulum ex in erat euismod, in lacinia neque vestibulum. Phasellus bibendum nunc sed nibh aliquam, suscipit fringilla dolor semper. Nulla vel felis scelerisque, iaculis velit in, gravida turpis. Cras dolor lacus, convallis et ex a, rutrum pretium mauris. Nam dapibus interdum ipsum, et scelerisque magna. Pellentesque tincidunt viverra consequat. Ut finibus nibh et enim lacinia, non sagittis felis viverra. Nulla laoreet mollis dui. Fusce erat lacus, bibendum ac urna in, pretium elementum velit.",\n\n "Loremipsumdolorsitamet,consecteturadipiscingelit. Phasellussedultriciesdiam. Seductornislibero,arutrumleodapibus eu. Aliquam sit amet elit enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl massa.",\n "Integerplaceratodiout sagittis suscipit. Sed placerat bibendum tellus, nec tempus nulla dignissim atInteger emper laoreetcinia. Proinvitaejusto,egeterat. Ut lobortis, lectus bibendum ornare cursus,sem enim vehicula felis,veliaculismi eros vitaejusto. Duisvelauctorssa. Pellentesquetinciduntvehiculaligulasitmetpharetrametusvestibulumin. Aliquamaliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus. Nulla in magna ante.",\n "Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis. Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum. Donec a elementum massa, nec porttitor tortor. Aenean dignissimtortoregetlacusfringilla,auctorhendreritturpishendreritVivamusmattispurusacmalesuadaluctus.",\n};\n\nconst char *test_out[] = {\n "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sed ultricies\\n"\n "diam. Sed auctor nisl libero, a rutrum leo dapibus eu. Aliquam sit amet elit\\n"\n "enim. Pellentesque pellentesque orci at dolor placerat, vitae eleifend metus\\n"\n "bibendum. Pellentesque tristique venenatis orci a dapibus. Suspendisse blandit\\n"\n "non lorem eu pulvinar. Fusce commodo vel ligula et porttitor. Duis eget nisl\\n"\n "massa.\\n",\n\n "Integer placerat odio ut sagittis suscipit. Sed placerat bibendum tellus, nec\\n"\n "tempus nulla dignissim at. Integer semper laoreet lacinia. Proin vitae volutpat\\n"\n "justo, eget maximus erat. Ut lobortis, lectus bibendum ornare cursus, sem enim\\n"\n "vehicula felis, vel iaculis mi eros vitae justo. Duis vel auctor massa.\\n"\n "Pellentesque tincidunt vehicula ligula, sit amet pharetra metus vestibulum in.\\n"\n "Aliquam aliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus.\\n"\n "Nulla in magna ante.\\n",\n\n "Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis.\\n"\n "Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat\\n"\n "venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum.\\n"\n "Donec a elementum massa, nec porttitor tortor. Aenean dignissim tortor eget\\n"\n "lacus fringilla, auctor hendrerit turpis hendrerit. Vivamus mattis purus ac\\n"\n "malesuada luctus.\\n",\n\n "Sed ullamcorper arcu consectetur ex interdum semper. Integer blandit risus\\n"\n "turpis, tempor porttitor augue porttitor et. Nunc sit amet consequat augue.\\n"\n "Nullam malesuada risus eu neque elementum ullamcorper. Morbi volutpat leo vitae\\n"\n "lacus sagittis, vel viverra lorem scelerisque. Nulla enim ipsum, cursus accumsan\\n"\n "magna quis, imperdiet semper orci. Phasellus nisl dui, vehicula ac venenatis\\n"\n "vel, imperdiet vitae tortor. Vestibulum eget consequat urna. Etiam id lectus sed\\n"\n "velit dignissim iaculis. Nam ac lacus non nisi feugiat suscipit. Nullam eleifend\\n"\n "ultricies sapien, eget faucibus erat sollicitudin in. Phasellus sed tellus id\\n"\n "diam interdum iaculis. Curabitur vulputate, ante ut commodo tristique, metus\\n"\n "lacus rutrum magna, ut pulvinar orci augue ac orci. Ut a felis libero. Integer\\n"\n "mattis magna quis diam blandit, in auctor urna hendrerit.\\n",\n\n "Curabitur vestibulum ex in erat euismod, in lacinia neque vestibulum. Phasellus\\n"\n "bibendum nunc sed nibh aliquam, suscipit fringilla dolor semper. Nulla vel felis\\n"\n "scelerisque, iaculis velit in, gravida turpis. Cras dolor lacus, convallis et ex\\n"\n "a, rutrum pretium mauris. Nam dapibus interdum ipsum, et scelerisque magna.\\n"\n "Pellentesque tincidunt viverra consequat. Ut finibus nibh et enim lacinia, non\\n"\n "sagittis felis viverra. Nulla laoreet mollis dui. Fusce erat lacus, bibendum ac\\n"\n "urna in, pretium elementum velit.\\n",\n\n "Loremipsumdolorsitamet,consecteturadipiscingelit. Phasellussedultriciesdiam.\\n"\n "Seductornislibero,arutrumleodapibus eu. Aliquam sit amet elit enim. Pellentesque\\n"\n "pellentesque orci at dolor placerat, vitae eleifend metus bibendum. Pellentesque\\n"\n "tristique venenatis orci a dapibus. Suspendisse blandit non lorem eu pulvinar.\\n"\n "Fusce commodo vel ligula et porttitor. Duis eget nisl massa.\\n",\n\n "Integerplaceratodiout sagittis suscipit. Sed placerat bibendum tellus, nec\\n"\n "tempus nulla dignissim atInteger emper laoreetcinia. Proinvitaejusto,egeterat.\\n"\n "Ut lobortis, lectus bibendum ornare cursus,sem enim vehicula felis,veliaculismi\\n"\n "eros vitaejusto. Duisvelauctorssa.\\n"\n "Pellentesquetinciduntvehiculaligulasitmetpharetrametusvestibulumin.\\n"\n "Aliquamaliquam viverra vehicula. Quisque fermentum pulvinar massa non tempus.\\n"\n "Nulla in magna ante.\\n",\n\n "Morbi non mattis elit. Donec non sagittis lorem. Donec at commodo turpis.\\n"\n "Maecenas quis libero a metus rutrum efficitur. Duis fermentum iaculis erat\\n"\n "venenatis porttitor. Cras tortor nibh, commodo in mi a, venenatis commodo ipsum.\\n"\n "Donec a elementum massa, nec porttitor tortor. Aenean\\n"\n "dignissimtortoregetlacusfringilla,auctorhendreritturpishendreritVivamusmattispur\\n"\n "usacmalesuadaluctus.\\n",\n};\n\n\nint main(void)\n{\n char fn[128];\n snprintf(fn, sizeof(fn), "%s/test-temp.txt", getenv("TEMP"));\n FILE *ftest = fopen(fn, "wb+");\n assert(ftest);\n\n size_t start = 0;\n\n for (int i_test = 0; i_test < sizeof(test_in) / sizeof(*test_in); i_test++)\n {\n for (int i_method = 0; i_method < sizeof(methods) / sizeof(*methods); i_method++)\n {\n methods[i_method](test_in[i_test], 80, ftest);\n\n size_t end = ftell(ftest),\n len = end - start;\n assert(end != -1);\n assert(fseek(ftest, start, SEEK_SET) == 0);\n\n char *buffer = malloc(len + 1);\n assert(buffer);\n assert(fread(buffer, 1, len, ftest) == len);\n buffer[len] = '\\0';\n\n if (memcmp(test_out[i_test], buffer, len))\n {\n fprintf(\n stderr,\n "Method %s test %d failed"\n#if LONG_OUTPUT\n ":\\n%s"\n "\\tactual != expected\\n"\n "%s"\n#endif\n "\\n",\n method_names[i_method], i_test\n#if LONG_OUTPUT\n , buffer, test_out[i_test]\n#endif\n );\n }\n else printf(\n "Method %s test %d passed\\n"\n#if LONG_OUTPUT\n "\\n"\n#endif\n , method_names[i_method], i_test);\n\n free(buffer);\n start = end;\n }\n\n printf("\\n");\n }\n\n fclose(ftest);\n remove(fn);\n\n return 0;\n}\n</code></pre>\n<p>Test results for each entry and method:</p>\n<pre><code>Method lincoln test 0 passed\nMethod aghast test 0 failed\nMethod reinderien test 0 passed\n\nMethod lincoln test 1 passed\nMethod aghast test 1 passed\nMethod reinderien test 1 passed\n\nMethod lincoln test 2 passed\nMethod aghast test 2 failed\nMethod reinderien test 2 passed\n\nMethod lincoln test 3 passed\nMethod aghast test 3 failed\nMethod reinderien test 3 passed\n\nMethod lincoln test 4 failed\nMethod aghast test 4 failed\nMethod reinderien test 4 passed\n\nMethod lincoln test 5 failed\nMethod aghast test 5 failed\nMethod reinderien test 5 passed\n\nMethod lincoln test 6 passed\nMethod aghast test 6 passed\nMethod reinderien test 6 passed\n\nMethod lincoln test 7 failed\nMethod aghast test 7 failed\nMethod reinderien test 7 passed\n</code></pre>\n<p>The test data shown here are now correct (so far as I can tell). Changes in my suggested method:</p>\n<ul>\n<li>Do indeed scan backward from the end of each line</li>\n<li>Use a file pointer rather than assuming <code>stdout</code> for testing purposes</li>\n<li>Only have one inner loop, not two</li>\n<li>Do pointer-incrementing and a diminishing <code>len</code> rather than an increasing <code>pos</code></li>\n<li>Prefer <code>for</code> loops when maintaining a running counter</li>\n</ul>\n<p>The full test output is very long; you can see it if you toggle <code>LONG_OUTPUT</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:33:57.087",
"Id": "255196",
"ParentId": "255160",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255196",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T00:11:10.077",
"Id": "255160",
"Score": "1",
"Tags": [
"c",
"strings"
],
"Title": "C text word-wrapping"
}
|
255160
|
<p>I have an interface Animal with a class that implements it, Cat.</p>
<pre><code>public interface Animal {
public int price();
public Breed.BreedType breedType();
}
public class Cat implements Animal {
private int price;
private Breed.BreedType breedType;
public Cat(int price) {
this.price = price;
}
public Cat(int price, Breed.BreedType breedType) {
this.price = price;
this.breedType = breedType;
}
@Override
public int price() {
return price;
}
@Override
public Breed.BreedType breedType() {
return breedType;
}
}
</code></pre>
<p>I have decorated the Animal class with the following interface, Breed.</p>
<pre><code>import java.util.List;
public interface Breed {
public enum BreedType {
RARE,
EXOTIC
}
public int calculatePrice(List<Animal> animals);
}
</code></pre>
<p>The concrete decorator class looks as follows:</p>
<pre><code>import java.util.List;
public class Exotic implements Breed {
@Override
public int calculatePrice(List<Animal> animals) {
return animals.stream()
.mapToInt(Animal::price)
.map(i -> i * 2)
.sum();
}
}
</code></pre>
<p>Finally I iterate over a collection of animals and apply the decorator to them to work out their total cost of special breed animals.</p>
<pre><code>import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Cat cat1 = new Cat(100);
Cat cat2 = new Cat(100, Breed.BreedType.EXOTIC);
Cat cat3 = new Cat(100, Breed.BreedType.EXOTIC);
Map<Breed.BreedType, List<Animal>> map = Stream.of(cat1, cat2, cat3)
.filter(animal -> animal.breedType() != null)
.collect(Collectors.groupingBy(Animal::breedType, Collectors.toList()));
int total = 0;
for(Breed.BreedType breedType : map.keySet()) {
if(breedType.equals(Breed.BreedType.EXOTIC)) {
total += new Exotic().calculatePrice(map.get(breedType));
}
}
System.out.println(total);
}
}
</code></pre>
<p>This does not seem particularly flexible as I will end up with a giant if statement as more breeds are added. Is there a better way to do this? My enum and the corresponding method for the Exotic breed seem a bit disconnected.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T02:24:00.877",
"Id": "503359",
"Score": "1",
"body": "When you say \"I have decorated the Animal class with the following interface, Breed.\", are you referring to the [decorator pattern](https://refactoring.guru/design-patterns/decorator/java/example#:~:text=Decorator%20is%20a%20structural%20pattern,decorators%20follow%20the%20same%20interface.), or do you mean something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T09:29:34.323",
"Id": "503376",
"Score": "1",
"body": "Yeah I was referring to the decorator pattern, apologies that wasnt clear"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:03:52.247",
"Id": "503377",
"Score": "1",
"body": "Micro review: `public` modifier is redundant on methods and inner classes of an interface, so it can be removed."
}
] |
[
{
"body": "<p>I'm not much of a stream fan and your code itself seems rather good, so I'll skip directly to your architecture.</p>\n<p>One note, through:</p>\n<pre class=\"lang-java prettyprint-override\"><code>total += new Exotic().calculatePrice(map.get(breedType))\n</code></pre>\n<p><code>a += b</code> is not shorthand for <code>a = a + b</code>, it is shorthand for <code>a = (TYPE_A)(a + b)</code>. This is something to keep in mind, as it might silently truncate data, for example if <code>a</code> is an <code>int</code> and <code>b</code> is a <code>float</code>, no warning will be emitted by the compiler.</p>\n<hr />\n<p>Let's sum it up:</p>\n<pre><code>interface Breed\n enum BreedType\n\ninterface Animal\n\nclass Cat implements Animal\n</code></pre>\n<p>What is odd here is that you have a <code>Breed</code> type, then decide not to use it and instead use a specialized enum for representing the breed. So what I'd rather expect would be to have a <code>Cat</code> which has the property <code>Breed</code>. Additionally, your handling of the price of a cat is odd. The cat gets assigned a price, which is then changed afterwards based on the breed, which means it really is more of a "base price" then the actual price of <em>this</em> cat.</p>\n<p>So what I'd expect is the following setup:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Breed {}\n\npublic class Cat implements Animal {\n public Breed getBreed();\n public int getPrice();\n}\n</code></pre>\n<p>With <code>getPrice</code> here returning the <em>actual</em> price of this single cat. Or, an alternative would be to have an extra price calculator:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Breed {}\n\npublic class Cat implements Animal {\n public Breed getBreed();\n}\n\npublic class CatPriceCalculator {\n public int calculatePrice(Cat cat);\n}\n</code></pre>\n<p>Depending on what you're trying to achieve, both solutions might be viable. But let's go with the first for now. To mimic your original code, let's implement <code>Breed</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Breed {\n // TODO Note that we do not support fractions here.\n public int getPriceMultiplier();\n}\n\npublic class RegularBreed implements Breed {\n public int getPriceMultiplier() {\n return 1;\n }\n}\npublic class ExitocBreed implements Breed {\n public int getPriceMultiplier() {\n return 2;\n }\n}\n</code></pre>\n<p>This will allow us to calculate the price of a single cat by doing <code>cat.getBasePrice() * cat.getBreed().getPriceMultiplier()</code>. We could also map breeds as enum, similar to how you've done it:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public enum Breed {\n EXOTIC(2),\n REGULAR(1);\n \n private int priceMultiplier;\n \n private Breed(int priceMultiplier) {\n this.priceMultiplier = priceMultiplier;\n }\n \n public int getPriceMultiplier() {\n return priceMultiplier;\n }\n}\n</code></pre>\n<p>But this has the downside that it is not extensible from the outside, as enums cannot be extended. So I'd suggest to stick with the interface for this one.</p>\n<p>Looking again at my second suggestion to use an extra price calculator, this would have the upside that you can map the price of a single cat base on more properties, for example weight, color and so forth:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Cat extends Animal {\n public int getAge();\n public Breed getBreed();\n public Color getFurColor();\n public Quality getFurQuality();\n public int getWeight();\n}\n</code></pre>\n<p>Now if we have an extra calculator class, all these properties can be weighted in there. Having an extra class for this might for example be necessary if we plan to support different markets. For example, a market of a cat-show will assess fur and color higher than other properties. On the other side, a meat market will assess age and weight higher than other properties. So decoupling the price calculation from your model classes might be preferable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T09:28:44.913",
"Id": "255170",
"ParentId": "255162",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "255170",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T01:12:51.980",
"Id": "255162",
"Score": "4",
"Tags": [
"java",
"design-patterns"
],
"Title": "Applying functions to decorated objects"
}
|
255162
|
<p>I have come across a problem on cyclic permutations. It is about swapping numbers around.</p>
<p>It starts out with input N < 100,000 which makes the first N natural numbers as orders: 1 2 3 ... N-1 N</p>
<p>Then we get the next input K < 200,000 as the period</p>
<p>Next N input lines are the swaps:</p>
<p>For example, the input is</p>
<pre><code>5 4
1 3
1 2
2 3
2 4
</code></pre>
<p>There are 5 numbers and the swap period is 4. The first swap switches number at position 1 with position 3. The second swap is between position 1 and position 2. The third swap is between position 2 and position 3. The fourth swap is between 2 and 4. K+1th swap is same as first. K+2th swap is same as second. Etc.</p>
<p>The simulation for this is:</p>
<pre><code>1 2 3 4 5
3 2 1 4 5
2 3 1 4 5
2 1 3 4 5
2 4 3 1 5
3 4 2 1 5
4 3 2 1 5
4 2 3 1 5
4 1 3 2 5
3 1 4 2 5
1 3 4 2 5
1 4 3 2 5
1 2 3 4 5
</code></pre>
<p>We can see that the original number at position 3 can go to positions 1, 2, and 3. The original number at position 1 can go to positions 1, 2, 3, 4. The original number at position 2 can go to positions 1, 2, 3, 4. The original number at position 4 can go to positions 1, 2, 3, 4. The original number at position 5 can go to positions 5.</p>
<p>Position 1 goes to 4 positions. Position 2 goes to 4 positions. Position 3 goes to 3 positions. Position 4 goes to 4 positions. Position 5 goes to 1 position.</p>
<p>Given that each output line is represented by y, the output is the number of totals positions the yth original position goes to. Output for this example is:</p>
<pre><code>4
4
3
4
1
</code></pre>
<p>The memory limit is 256MB and the time limit is 2 seconds for noninterpreted languages such as C++ and 4 seconds for interpreted languages such as Java.</p>
<pre><code>
z, d = map(int, input().split())
S = []
pos = {}
for i in range(1, z+1):
pos[i] = [i,]
permute = list(range(1, z+1))
for i in range(d):
S.append(list(map(int, input().split())))
Flag = True
while Flag:
Flag = False
for i in S:
if i[0] not in pos[permute[i[1]-1]]:
Flag = True
pos[permute[i[1]-1]].append(i[0])
if i[1] not in pos[permute[i[0]-1]]:
Flag = True
pos[permute[i[0]-1]].append(i[1])
permute[i[0]-1], permute[i[1]-1] = permute[i[1]-1], permute[i[0]-1]
for i in pos:
print(len(pos[i]))
</code></pre>
<p>My solution takes too much space/time. Can you help me fix this?</p>
<p>I know this problem has DFS but I don't know what the graph to do DFS on looks like?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T15:03:14.147",
"Id": "503488",
"Score": "3",
"body": "If this is a programming challenge please post the link."
}
] |
[
{
"body": "<h1>Naming</h1>\n<p>The question starts off talking about <code>N</code> and <code>K</code>. Your code begins with reading in <code>z</code> and <code>d</code>. The question text is ready-made documentation for your code; use the same names for the variables!</p>\n<p><code>n, k = map(int, input().split())</code></p>\n<p>Guilty, I said <code>N</code> and <code>K</code> but used <code>n</code> and <code>k</code>. PEP 8, the <a href=\"https://pep8.org\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> recommends using <code>snake_case</code> for variables. So we should also change <code>S</code> and <code>Flag</code> to <code>s</code> and <code>flag</code>.</p>\n<p>But ... what is <code>flag</code>? Obviously, it is a flag, but a flag for what? Perhaps <code>changed</code> would be a better name; you are looping while a change was made in the previous iteration.</p>\n<p>Similarly, <code>S</code> is your list of swaps. Why not call it <code>swaps</code>?</p>\n<h1>Don't relookup values</h1>\n<p>Python is an interpreted language. It doesn't do any data-flow analysis to determine if the value of an expression will be used again. It can't, since the meaning of operations can be changed on the fly.</p>\n<p>In the <code>for i in S</code> loop, how many times is <code>i[0]</code> and <code>i[1]</code> used? Six times each. Each time, the interpreter looks up the object stored in <code>i</code>, and calls the <code>__getitem__</code> method to fetch the value. Let's fix this by looking up the value only once, and storing the values in (say) <code>p</code> and <code>q</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for p, q is swaps:\n if p not in pos[permute[q - 1]]:\n changed = True\n pos[permute[q - 1]].append(p)\n ...\n</code></pre>\n<p>That is immediately clearer. No extra <code>[0]</code> and <code>[1]</code> to confuse the issue.</p>\n<h1>Use O(1) lookups instead of O(K) searches</h1>\n<p>You're using <code>if thing not in container: container.append(thing)</code>. This is a lot like a <code>set</code>. A set can only contain one instance of an item. But unlike a list, <code>if thing not in container</code> is O(1) on a set, where as the with a list, the entire list has to be searched to ensure the thing is not inside the list.</p>\n<p>Two simple changes. First, instead of <code>pos[i] = [i,]</code> (the comma is actually unnecessary), initialize it with <code>pos[i] = {i}</code>. Second, instead of <code>.append()</code>, use <code>.add()</code> to add the value to the set.</p>\n<p>Note: sets are more complex than lists. This may actually slow things down and use more memory, if the number of things in the containers is small. The sets gain their speed advantage when they contain many elements. So profile this change, especially using larger problem sets.</p>\n<h1>Explicit is better than implicit</h1>\n<pre class=\"lang-py prettyprint-override\"><code>swaps = []\nfor i in range(k):\n swaps.append(list(map(int, input().split())))\n</code></pre>\n<p>What happens if an input line has more than two numbers? The input will be split into whole bunch of terms, each term will be mapped (converted) to an integer, and stored as a list inside the swaps list!</p>\n<p>Oops.</p>\n<p>If the program crashes, it will happen well after this point in the code.</p>\n<p>It is better to crash early. You expect exactly two values. Be explicit.</p>\n<pre class=\"lang-py prettyprint-override\"><code>swaps = []\nfor i in range(k):\n swaps.append(list(map(int, input().split(maxsplit=1))))\n</code></pre>\n<p>If given more than two numbers, say <code>12 23 34</code>, then <code>split</code> will return <code>"12"</code> and <code>"23 34"</code>, and <code>int("23 34")</code> will raise a <code>ValueError</code>. The bug will be caught earlier.</p>\n<h1>Map the problem to Python, if possible</h1>\n<p>Python uses 0-based indexing. The problem uses 1-based indexing. You can get rid of the <code>+1</code> in <code>range</code> statements, and <code>-1</code> in the solution code by mapping the problem into a more Pythonic version.</p>\n<p>For example, instead of swapping numbers at positions <code>1</code> and <code>3</code>, we'll swap them at positions <code>0</code> and <code>2</code>. This just requires adjusting the swap positions as we read them in:</p>\n<pre class=\"lang-py prettyprint-override\"><code>swaps = []\nfor i in range(k):\n p, q = map(int, input().split())\n swaps.append([p - 1, q - 1])\n</code></pre>\n<p>Note. The explicit <code>maxsplit=1</code> went away because we are assigned the result of map to a tuple of two variables, which requires exactly two values. Explicit is better than implicit ... especially when the it can be expressed implicitly!</p>\n<h1>Reworked Code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>n, k = map(int, input().split())\n\npos = {}\nfor i in range(n):\n pos[i] = {i}\n\npermute = list(range(n))\n\nswaps = []\nfor i in range(k):\n p, q = map(int, input().split())\n swaps.append([p - 1, q - 1])\n\nchanged = True\n\nwhile changed:\n changed = False\n for p, q in swaps:\n if p not in pos[permute[q]]:\n changed = True\n pos[permute[q]].add(p)\n if q not in pos[permute[p]:\n changed = True\n pos[permute[p]].add(q)\n permute[p], permute[q] = permute[q], permute[p]\n\nfor i in pos: # Note: relies on ordered dictionary\n print(len(pos[i]))\n</code></pre>\n<h1>Algorithmic improvement</h1>\n<p><code>1 2 3 4 5</code></p>\n<p>After one iteration of swaps, you end up with this:</p>\n<p><code>2 4 3 1 5</code></p>\n<p>We can see we have moved</p>\n<ul>\n<li>1 -> 2, 2 -> 4, 4 -> 1. (length 3)</li>\n<li>3 -> 3</li>\n<li>5 -> 5</li>\n</ul>\n<p>The 1 visited locations 1, 3, 2 and 4. The 2 visited locations 2, and 1. The 4 visited locations 4 and 2. On subsequent iterations, the 2 will have moved into the 1's starting position and will visit 1, 3, 2 and 4, and so on. So we have 1, 2, and 4 all visiting locations 1, 2, and 3 and 4 ... for a total of 4 locations</p>\n<p>3 will visit 3, 1, and 2 and return to 3.</p>\n<p>5 stays at 5.</p>\n<p>All that is required is one pass through the swaps array to determine which positions each starting point visits, and what ending position it will have. From that, the "rings" can be determined. All starting positions in each ring will visit all the locations visited by every position in the ring.</p>\n<p>With only one pass through the swaps array required, we don't need to save the swaps into a <code>swaps</code> list; it can be processed on the fly. This helps the solution stay within the memory constraint.</p>\n<pre class=\"lang-py prettyprint-override\"><code>n, k = map(int, input().split())\n\npos = [{i} for i in range(n)]\npermute = list(range(n))\n\n# Perform swaps, recording which values appear in which positions\nfor _ in range(k):\n p, q = map(int, input().split())\n p -= 1 \n q -= 1\n\n pos[permute[q]].add(p)\n pos[permute[p]].add(q)\n permute[p], permute[q] = permute[q], permute[p]\n\n# Implementation of final steps left to student\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T04:38:10.943",
"Id": "256124",
"ParentId": "255169",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T07:19:52.607",
"Id": "255169",
"Score": "2",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Count the different positions reached in a cycle of permutations"
}
|
255169
|
<p>Due that fact that SwiftUI has poor <code>ScrollView</code> customization and doesn't support snap interval from the box I decided to implement my custom component to support such behaviour.</p>
<p>Example</p>
<p><a href="https://i.stack.imgur.com/fMKUn.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fMKUn.gif" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/wPxrQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wPxrQ.png" alt="enter image description here" /></a></p>
<p>I know, there are many hard coded values that should be replaced with dynamically calculated values. But for my debug purposes is enough.</p>
<p>I would like to ask if it possible to simplify my code? Or is there any better approach of creating such component.</p>
<p>The thing that confuses me the most is <code>lastTimePoint</code>. The variable which stores the last shift of content. It needs to prevent content jumps on scroll. I will leave more comments in a code to help you understand what's going on.</p>
<pre><code>struct CustomScrollView<Content: View>: View {
var height: CGFloat
var content: () -> Content
@State private var offset = CGFloat.zero
@State private var lastTimePoint = CGFloat.zero // lastTimePoint the same as offset. I use it to populate value.translation.height and value.predictedEndTranslation.height to prevent content jumps. I want to remove it if it possible.
var body: some View {
VStack(alignment: .leading, spacing: 0) {
content()
.offset(y: offset) // Scrolls content depending on the this value
.contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 0)
.onChanged(handleDragGestureChange)
.onEnded(handleDragGestureEnded)
)
}
.frame(height: height, alignment: .top) // clip the content to make content scrollable. height is equal to 250
.clipped()
}
private func handleDragGestureChange(value: DragGesture.Value) { // Updates offset value
offset = value.translation.height + lastTimePoint // If I remove lastTimePoint content will jump to the top of the list (if user started to scroll from any other place)
}
private func handleDragGestureEnded(value: DragGesture.Value) { // I use this function to calculate closest row where offset should stop.
let predictedY = value.predictedEndTranslation.height + lastTimePoint // Again add lastTimePoint to prevent content jump
withAnimation(.spring()) { // Animates list scrolling after user stops interacting
if predictedY > 0 { // If list is going beyond his boundaries stop at the most top visible point (first element)
offset = 0
} else if predictedY < -1750 { // 1750 is the size of the content inside (red rectangles). I calculated it by 40 items * 50 item height = 2000 - 250 = 1750 where 1750 total height of all items within 250 height clipped scrollable component
offset = -1750
} else { // In this block I calculate the closest row where scrollable view should stop.
// My rows heights
// 0
// -50
// -100
// -150
// -200
// ...
// -1750
//
// If offset position is 120 (which is closer to 100 than to 150) I calculate it like this
// -120 % 50 = remainder -20
// remainder -20 is less then -25 go to the bottom, otherwise to to the top
let remainder = predictedY.truncatingRemainder(dividingBy: 50)
if remainder < -25 {
offset = predictedY - (50 + remainder)
} else {
offset = predictedY - remainder
}
}
}
lastTimePoint = offset
}
}
struct CustomScrollView_Previews: PreviewProvider {
static var previews: some View {
CustomScrollView(
height: 250
) {
Text("View")
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T09:51:57.453",
"Id": "255171",
"Score": "2",
"Tags": [
"swift",
"swiftui"
],
"Title": "SwiftUI custom ScrollView with snap interval"
}
|
255171
|
<p>I'm in the process of learning Windows kernel programming and I'm focusing on writting clean C code that handles and propagates errors correctly. The following piece of code is quite simple, but I'd like to have feedbacks on it before I apply this interface and coding style to the rest of the code.</p>
<p>The code bellow is responsible for initializing process objects, reading and writting in their memory, and cleaning them up.</p>
<p>process.h:</p>
<pre><code>#pragma once
#include <ntdef.h>
#include <ntifs.h>
typedef enum {
EProcessSuccess,
EProcessInvalid,
EProcessInvalidArgs,
EProcessAccessDenied,
EProcessFail
} EProcessStatus;
#define PROCESS_STATUS_SUCCESS(EValue) (EValue == EProcessSuccess)
typedef struct _Process {
HANDLE id;
PEPROCESS process;
BOOLEAN initialized;
} Process;
EProcessStatus processInit(HANDLE processId, Process* process);
EProcessStatus processDestroy(Process* process);
EProcessStatus processReadMemory(Process* process, PVOID sourceAddress, PVOID targetAddress, SIZE_T size);
EProcessStatus processWriteMemory(Process* process, PVOID sourceAddress, PVOID targetAddress, SIZE_T size);
EProcessStatus processGetId(Process* process, HANDLE* id);
</code></pre>
<p>process.c</p>
<pre><code>#include "process.h"
#include "log.h"
NTSTATUS NTAPI MmCopyVirtualMemory(
PEPROCESS SourceProcess,
PVOID sourceAddress,
PEPROCESS TargetProcess,
PVOID targetAddress,
SIZE_T BufferSize,
KPROCESSOR_MODE PreviousMode,
PSIZE_T ReturnSize
);
void printErrorRW(char* msg, HANDLE id, NTSTATUS status, PVOID address, SIZE_T size) {
DEBUG_LOG("[ERROR] %s - %x \n", msg, status);
DEBUG_LOG("\t\tProcess: %p\n", id);
DEBUG_LOG("\t\tSourceAddress: %p\n", address);
DEBUG_LOG("\t\tBytes: %p\n", size);
}
BOOLEAN isValid(Process* process) {
return process && process->initialized;
}
EProcessStatus processInit(HANDLE processId, Process* process) {
DEBUG_VERBOSE("Create process with PID %d\n", processId);
if (process == NULL) {
DEBUG_LOG("[ERROR] Can't initialize NULL Process.\n");
return EProcessInvalid;
}
process->id = processId;
process->initialized = NT_SUCCESS(PsLookupProcessByProcessId(processId, &process->process));
if (!process->initialized) {
DEBUG_LOG("[ERROR] Unable to initialize process with PID %d\n", processId);
return EProcessInvalid;
}
return EProcessSuccess;
}
EProcessStatus processDestroy(Process* process) {
if (isValid(process) && process->initialized) {
ObDereferenceObject(process->process);
}
return EProcessSuccess;
}
EProcessStatus processReadMemory(Process* process, PVOID sourceAddress, PVOID targetAddress, SIZE_T size) {
if (!isValid(process)) {
DEBUG_LOG("[ERROR] Can't read memory from invalid process\n");
return EProcessInvalid;
}
DEBUG_VERBOSE("Read memory from process %d at address %p\n", process->id, sourceAddress);
SIZE_T Bytes = 0;
NTSTATUS Status = STATUS_SUCCESS;
__try
{
Status = MmCopyVirtualMemory(process->process, sourceAddress, PsGetCurrentProcess(), targetAddress, size, KernelMode, &Bytes);
if (!NT_SUCCESS(Status))
{
printErrorRW("readMemory", process->id, Status, sourceAddress, Bytes);
return EProcessFail;
}
return EProcessSuccess;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
printErrorRW("readMemory exception", process->id, Status, sourceAddress, Bytes);
return EProcessAccessDenied;
}
}
EProcessStatus processWriteMemory(Process* process, PVOID sourceAddress, PVOID targetAddress, SIZE_T size) {
if (!isValid(process)) {
DEBUG_LOG("[ERROR] Can't write memory from invalid process\n");
return EProcessInvalid;
}
DEBUG_VERBOSE("Write memory from process %d at address %p\n", process->id, sourceAddress);
SIZE_T Bytes = 0;
NTSTATUS Status = STATUS_SUCCESS;
__try
{
Status = MmCopyVirtualMemory(PsGetCurrentProcess(), sourceAddress, process->process, targetAddress, size, KernelMode, &Bytes);
if (!NT_SUCCESS(Status))
{
printErrorRW("writeMemory", process->id, Status, sourceAddress, Bytes);
return EProcessFail;
}
return EProcessSuccess;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
printErrorRW("writeMemory exception", process->id, Status, sourceAddress, Bytes);
return EProcessAccessDenied;
}
}
EProcessStatus processGetId(Process* process, HANDLE* id) {
if (process == NULL) {
DEBUG_LOG("[ERROR] Can't get PID of invalid process\n");
return EProcessInvalid;
}
if (id == NULL) {
DEBUG_LOG("[ERROR] processGetId - NULL id pointer\n");
return EProcessInvalidArgs;
}
*id = process->id;
return EProcessSuccess;
}
</code></pre>
<p>Thank you for your time.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:20:02.780",
"Id": "255172",
"Score": "0",
"Tags": [
"c",
"windows",
"kernel"
],
"Title": "Basic process management in Windows kernel"
}
|
255172
|
<p>I'm sure there are several profilers written in C++ on here already, though with this one the goals are quite different. I attempted to make it as robust as possible, or 'fool-proof' if you will so that it is nearly impossible to crash via an unhandled exception or undefined behaviour.</p>
<p>It supports redirection of stdin, stdout and stderr to files as well.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <boost/process.hpp>
#include <boost/chrono.hpp>
#include <exception>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <stdexcept>
#include <cstdio>
typedef boost::chrono::steady_clock bench_clock;
// Defined map of acceptable arguments to integer for switch
const static std::unordered_map<std::string, int> string_map{
{"--count", 1},
{"--in", 2},
{"--out", 2},
{"--err", 2},
{"process", 3}
};
// Return code of argument, or 0 if it's not defined
int string_case(std::string& s_case)
{
return string_map.count(s_case) ? string_map.at(s_case) : 0;
}
// Check if string is numeric
bool is_digits(const std::string& str)
{
return str.find_first_not_of("0123456789") == std::string::npos;
}
int main(int argc, char* argv[])
{
namespace bp = boost::process;
if(argc < 2)
{
std::cout << "No runnable executable specified.\n";
return EXIT_FAILURE;
}
std::vector<std::string> arguments(argv + 1, argv + argc);
auto it = std::begin(arguments);
const auto executable_path = *it;
std::vector<std::string> proc_arguments;
unsigned long long count = 1;
std::string string_num;
std::string in_path; // Default initialized to ""
std::string out_path;
std::string err_path;
for(const auto end = std::end(arguments); it+1 != end;)
{
switch(string_case(*(++it)))
{
default:
std::cout << "Unexpected or illegal argument encountered: " << *it << "\n";
return EXIT_FAILURE;
case 1:
if (it + 1 == end)
{
std::cout << "Unexpected end of argument list.\n";
return EXIT_FAILURE;
}
string_num = *(++it);
if(!is_digits(string_num))
{
std::cout << "Argument for --count is either negative or contains non-numeric characters.\n";
return EXIT_FAILURE;
}
try {
count = std::stoull(string_num);
} catch(std::out_of_range&)
{
std::cout << "Number too large for --count.\n";
return EXIT_FAILURE;
} catch (std::invalid_argument&)
{
std::cout << "--count can only accept numeric values.\n";
return EXIT_FAILURE;
}
if(count == 0)
{
std::cout << "Count must be larger than 0.\n";
return EXIT_FAILURE;
}
break;
case 2:
if (it + 1 == end)
{
std::cout << "Unexpected end of argument list.\n";
return EXIT_FAILURE;
}
if (*it == "--in")
in_path = *(++it);
else if (*it == "--out")
out_path = *(++it);
else if (*it == "--err")
err_path = *(++it);
break;
case 3:
while(it + 1 != end)
{
proc_arguments.push_back(*(++it));
}
break;
}
}
auto out_stream = out_path.empty() ? (bp::std_out > stdout) : (bp::std_out > out_path);
auto err_stream = out_path.empty() ? (bp::std_err > stderr) : (bp::std_err > err_path);
if (!out_path.empty()) {
std::ofstream ofs_out(out_path);
if (!ofs_out.is_open())
{
std::cout << "STD_OUT file cannot be opened for writing.\n";
return EXIT_FAILURE;
}
ofs_out.close();
}
if (!err_path.empty()) {
std::ofstream ofs_err(err_path);
if (!ofs_err.is_open())
{
std::cout << "STD_ERR file cannot be opened for writing.\n";
return EXIT_FAILURE;
}
ofs_err.close();
}
if (!in_path.empty()) {
std::ifstream ifs_in(in_path);
if (!ifs_in.is_open())
{
std::cout << "STD_IN file cannot be opened for writing.\n";
return EXIT_FAILURE;
}
ifs_in.close();
}
auto first = true;
long double duration = 0;
long double n = 1;
int exit_code = 0;
for (unsigned long long iter = 0; iter < count; iter++)
{
if (!in_path.empty() && !out_path.empty() && !err_path.empty() && count > 1) {
std::string s(7, '\0');
auto str_out = std::snprintf(&s[0], s.size(), "%.2f", (static_cast<double>(iter + 1) / static_cast<double>(count)) * 100);
s.resize(str_out);
std::cout << "Progress: " << iter + 1 << "/" << count << " ... " << s << "% done." << '\r' << std::flush;
}
std::unique_ptr<bp::child> proc;
boost::chrono::time_point<boost::chrono::steady_clock> start;
boost::chrono::time_point<boost::chrono::steady_clock> end;
if(in_path.empty())
{
std::cout << "Child process may be awaiting input from stdin:\n";
}
try
{
if (in_path.empty()) {
start = bench_clock::now();
proc = std::make_unique<bp::child>(bp::exe(executable_path), bp::std_in < stdin, out_stream, err_stream, bp::args(proc_arguments));
}
else {
start = bench_clock::now();
proc = std::make_unique<bp::child>(bp::exe(executable_path), bp::std_in < in_path, out_stream, err_stream, bp::args(proc_arguments));
}
(*proc).wait();
end = bench_clock::now();
exit_code = proc->exit_code();
}
catch (std::exception const& e)
{
std::cout << e.what();
return EXIT_FAILURE;
}
if(count == 1)
{
std::cout << "Program completed with exit code " << exit_code << "\n";
}
if (iter == 1 && count >= 5)
continue;
n++;
auto interval = static_cast<long double>(boost::chrono::duration_cast<boost::chrono::microseconds>(end - start).count());
if (first) {
duration += interval;
first = false;
}
else
duration = (duration * (n - 1) + interval) / n;
}
if(exit_code != 0)
{
std::cout << "Warning, program may have crashed or thrown an exception mid run, profiling may be inaccurate.\n";
}
if(duration <= 0)
std::cout << "\nMeasured duration: " << duration*1000 << " nanoseconds\n";
else if(duration <= 1000)
std::cout << "\nMeasured duration: " << duration << " microseconds\n";
else if(duration <= 1000000)
std::cout << "\nMeasured duration: " << duration / 1000 << " milliseconds\n";
else
std::cout << "\nMeasured duration: " << duration / 1000000 << " seconds\n";
return EXIT_SUCCESS;
}
</code></pre>
<p>Would be happy for any feedback as to what can further be improved!
A readme with running instructions is <a href="https://github.com/slobodaapl/Simple-executable-profiler" rel="nofollow noreferrer">available on my github page</a> for the code</p>
|
[] |
[
{
"body": "<p>This appears to be more of a "timer" than a "profiler". (It provides no information about what is actually taking time inside the child process).</p>\n<hr />\n<p><strong>Program structure</strong>:</p>\n<ul>\n<li><p>We could make the program more readable by moving nearly all of the code out of <code>main</code>. We should have separate functions for parsing the command line args, and doing the actual timing. e.g.:</p>\n<pre><code> int main(int argc, char** argv)\n {\n auto options = parse_args(argc, argv); // returns std::optional<program_options>\n\n if (!options)\n return EXIT_FAILURE;\n\n run_process(options.value());\n }\n</code></pre>\n</li>\n<li><p>There are other places where code should be split into separate functions, e.g. parsing an unsigned int from a string, outputting progress, launching the child process.</p>\n</li>\n</ul>\n<hr />\n<p><strong>Parsing arguments</strong>:</p>\n<ul>\n<li><p>If the user enters invalid arguments, it's common to show usage instructions, with a list of valid arguments, rather than just an error message.</p>\n</li>\n<li><p>I don't think there's much benefit to looking up the argument strings in a map, translating the string into an <code>int</code>, and then using that <code>int</code> in a switch statement.</p>\n<p>We can put the argument into a <code>std::string</code> (or <code>std::string_view</code>) and then do <code>if (arg == "--count") { ... } else if (arg == "--in") { ... } ...</code> instead.</p>\n</li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stoul\" rel=\"nofollow noreferrer\"><code>std::stoull</code></a> will parse partial strings to unsigned integers. We should probably ensure that the whole string was used, to avoid something like "123.~sdfkshjidf" being accepted as "123". We can do that by checking the 2nd argument (<code>pos</code>) indicates the end of the string after the function call.</p>\n<p>With that check in place, we probably don't need the <code>is_digits</code> check beforehand.</p>\n</li>\n<li><p>Doing <code>*(++it)</code> and comparing <code>it + 1 == end</code> is perhaps a little unusual. A more common idiom is to check for <code>it == end</code> before reading, and then do <code>*it++</code> to read from and increment the iterator.</p>\n</li>\n</ul>\n<p>We can make the intent of the code a bit clearer by parsing individual types in separate functions, e.g. <code>parse_string</code> or <code>parse_ull</code>. I'd probably go for something like:</p>\n<pre><code>struct program_options\n{\n std::string m_exe_path;\n std::uint64_t m_count = 1;\n std::string m_in_path, m_out_path, m_err_path;\n std::vector<std::string> m_process_args;\n};\n\nstd::optional<program_options> parse_args(int argc, char** argv)\n{\n auto print_usage = [&] ()\n {\n std::cout << "usage: ...\\n";\n };\n \n auto parse_string = [&] (char**& arg, char** end, char const* error_str) -> std::optional<std::string>\n {\n if (arg == end)\n {\n std::cout << error_str << "not enough arguments.\\n";\n print_usage();\n return { };\n }\n\n return *arg++;\n };\n\n auto parse_ull = [&] (char**& arg, char** end, char const* error_str) -> std::optional<std::size_t>\n {\n if (arg == end)\n {\n std::cout << error_str << "not enough arguments.\\n";\n print_usage();\n return { };\n }\n\n try\n {\n auto str = std::string(*arg++);\n auto pos = std::size_t{ 0 };\n auto value = std::stoull(str, &pos);\n\n if (pos != str.size())\n {\n std::cout << error_str << "expected an integer.\\n";\n print_usage();\n return { };\n }\n\n return value;\n }\n catch (std::invalid_argument&)\n {\n std::cout << error_str << "expected an integer.\\n";\n print_usage();\n return { };\n }\n catch (std::out_of_range&)\n {\n std::cout << error_str << "value out of valid range.\\n";\n print_usage();\n return { };\n }\n };\n\n auto arg = argv + 1; // argv[0] is the current program name\n auto const end = argv + argc;\n\n auto options = program_options();\n\n auto exe_path = parse_string(arg, end, "Failed to read executable path: ");\n if (!exe_path) return { };\n options.m_exe_path = exe_path.value();\n\n for ( ; arg != end; )\n {\n auto arg_sv = std::string_view(*arg++);\n\n if (arg_sv == "--count")\n {\n auto count = parse_ull(arg, end, "Failed to read --count: ");\n if (!count) return { };\n options.m_count = count.value();\n }\n else if (arg_sv == "--in")\n {\n auto in_path = parse_string(arg, end, "Failed to read --in: ");\n if (!in_path) return { };\n options.m_in_path = in_path.value();\n }\n else if (arg_sv == "--out")\n {\n auto out_path = parse_string(arg, end, "Failed to read --out: ");\n if (!out_path) return { };\n options.m_out_path = out_path.value();\n }\n else if (arg_sv == "--err")\n {\n auto err_path = parse_string(arg, end, "Failed to read --err: ");\n if (!err_path) return { };\n options.m_err_path = err_path.value();\n }\n else if (arg_sv == "process")\n {\n options.m_process_args.assign(arg, end);\n arg = end;\n }\n }\n\n return options;\n}\n</code></pre>\n<p>(C++ is always a bit awkward for things like this. We either have to use exception handling for flow control (although weird user input is never really "exceptional"), a boolean return value (or error code) paired with a reference output argument (kinda old-fashioned), or <code>std::optional</code> (annoyingly verbose).)</p>\n<hr />\n<p>I don't think there's a lot of point opening and then closing the input / output / error files before hand. Even if it succeeds here, it could still fail later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T14:07:29.853",
"Id": "503387",
"Score": "0",
"body": "Thanks for the awesome feedback! I will make sure to learn from it into the future. The `strtoull` had to be parsed with `is_digit()` because it can convert negative numbers which is unwanted behavior, without throwing an exception. So instead of adding a separate check for '-' at the beginning I just parsed the whole thing. As for opening and closing the input/output files.. boost process itself doesn't report any issues when trying to open them even if ti fails, so it's good to have at least a small check in place to see if the file can at least be created, I think"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T13:23:46.660",
"Id": "255177",
"ParentId": "255173",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:28:38.917",
"Id": "255173",
"Score": "0",
"Tags": [
"c++17",
"boost"
],
"Title": "Simple runtime profiler for executable files"
}
|
255173
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.