body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I want to document every exception handled in my code and some states of the code when it works properly.
What I've done is two functions, one that creates an 'error report' (function: <code>error</code>) and one that creates a 'state report'(function: <code>state</code>), and they work by being called in functions where there's stuff I'd like to have documented, they have a <code>code</code> parameter which I use to select the message of the report (apart from the exception, in the case of it being an <em>error</em> report) and then they call another function which takes this information and loads it to a JSON file(function: <code>writeReport</code>). <strong>If I'm being clear so far, you can skip all the code examples, my question is at the end.</strong></p>
<p>Here I show you the functions I mentioned before (messages are in spanish because its my main language):</p>
<pre><code># Exception mesagges (this is the one that records exceptions)
def error(code, exception, extra=None):
if code == 0:
stateReport.message = ('Error indefinido')
elif code == 1:
stateReport.message = ('Error en la conexion o creacion de la base de datos')
elif code == 2:
stateReport.message = ('No se pudieron crear las tablas o ya existen')
elif code == 3:
stateReport.message = (f'No se pudo recuperar la tabla {extra}')
elif code == 4:
stateReport.message = (f'Error indefinido que no afecta al funcionamiento')
elif code == 5:
stateReport.message = (f'Error en manipulacion de GUI que no afecta al funcionamiento')
elif code == 100:
stateReport.message = (f'Error desconocido al presionar una tecla')
stateReport.function = (inspect.stack()[1].function)
stateReport.date_time = date_time
stateReport.error = str(exception)
writeReport()
return
# State messages (this I use when some special case goes right)
def state(code, extra=None):
if code == 0:
stateReport.message = (f'El programa funciono correctamente')
elif code == 1:
stateReport.message = (f'Se accedio a la base de datos')
elif code == 2:
stateReport.message = (f'Se creo exitosamente la nueva tabla')
elif code == 3:
stateReport.message = (f'Valores ingresados incorrectos. Valor incorrecto: {extra}')
stateReport.function = (inspect.stack()[1].function)
stateReport.date_time = date_time
stateReport.error = '---------->Sin errores<----------' #This means "No errors"
writeReport()
def writeReport():
report = {'date': stateReport.date_time,
'function': stateReport.function,
'message': stateReport.message,
'error': stateReport.error}
if not os.path.exists(reportsFile):
with open(reportsFile, 'w', newline='') as file:
json.dump(report, file, indent=4)
else:
with open(reportsFile, 'a', newline='') as file:
json.dump(report, file, indent=4)
return
</code></pre>
<p>Now, heres a function where I use this feature on, just so you see how I actually implemented it:</p>
<pre><code>table = 'clientes'
## This is the creation of a <new> table in an sqlite database
try:
c.execute(f'''CREATE TABLE {table} (
id integer,
nombre text,
apellido text,
valoracion real)''')
state(2)
##If the table is successfully created a state report is saved with this info
except Exception as e:
error(2, e, table)
##On the contrary, if an exception occurs, en error report is recorded
</code></pre>
<p>This works great, but today I ran into the <code>logging</code> library (im kinda new in python) and it made me think. Is it better to use loggings in all of this cases? It would create a file with everything, it's allready a python library and I would avoid having three separate functions just for recording stuf, but I dont know if it's <code>logging</code> proper way of using it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T21:55:39.680",
"Id": "467653",
"Score": "2",
"body": "Why not doing both?"
}
] |
[
{
"body": "<p>Yes <code>logging</code> could replace <code>writeReport</code>, but it wouldn't write JSON. It would not be able to replace the other two functions.</p>\n\n<p><em>But</em> <code>logging</code> is a complex library, and can be rather daunting to get it to work correctly as a beginner. And overall the majority of your code would still be the same. Given that you're mutating globals than I think you may be overwhelmed when implementing it.</p>\n\n<hr>\n\n<p>However I have never needed a function like <code>error</code>, as if I raise an error it's either mission critical - exiting the program. Or it's for control flow. And so I believe the rest of your system is misconfigured, as you shouldn't need <code>error</code>.</p>\n\n<p>Additionally both <code>error</code> and <code>state</code> should be passed the message as an argument. If you need to use existing error messages then you can put them in a module:</p>\n\n<p><code>states.py</code></p>\n\n<pre><code>CODE_0 = 'El programa funciono correctamente'\nCODE_1 = 'Se accedio a la base de datos'\n...\n</code></pre>\n\n<pre><code>import states\n\nstate(states.CODE_0)\n</code></pre>\n\n<p>Or just a list:</p>\n\n<pre><code>STATES = [\n 'El programa funciono correctamente'\n]\n\nstate(STATES[0])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:38:02.277",
"Id": "238457",
"ParentId": "238452",
"Score": "2"
}
},
{
"body": "<p>The Python community favors having just one way to do something. As <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">the Zen of Python</a> puts it: </p>\n\n<blockquote>\n <p>There should be one-- and preferably only one --obvious way to do it.</p>\n</blockquote>\n\n<p>Other people and packages will be using the <code>logging</code> module, in general. That makes it much easier for your code to interoperate with other packages, use consistent configuration, avoid non-obvious mistakes (like writing error messages to stdout), etc. As such, it's probably to your (and your code's) long-term advantage to use the <code>logging</code> module.</p>\n\n<p>I'll say, one handy tip for logging in this particular case is the <code>exc_info</code> argument to <a href=\"https://docs.python.org/3/library/logging.html#logging.debug\" rel=\"nofollow noreferrer\"><code>.error</code></a>, which makes it easy to log exceptions and stack traces while also printing your own messages.</p>\n\n<p>@Peilonrayz responded first with a couple points that I planned to mention, so I'll just re-affirm those points:</p>\n\n<ol>\n<li><p>You should use exceptions with messages properly; don't just log something and move on as if nothing happened. Whoever called your code (I don't care if you're the only one calling your functions) deserves to know that what they asked for didn't happen, and you're begging for bugs if you don't throw an exception to tell them.</p></li>\n<li><p>Don't use a pile of if/else statements just to convert an integer into a string for an error message. Use named strings or a dictionary to store this data somewhere else in your code. (Once you do that, it'll make a whole lot more sense to just pass the error message to any handler function rather than have a custom function to look up error codes. This feels very much like an old habit from C/C++; welcome to Python, please don't use error codes that people need to look up, use <a href=\"https://docs.python.org/3/library/exceptions.html\" rel=\"nofollow noreferrer\">one of the many excellent error types</a> initialized with useful messages to communicate errors.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:46:24.500",
"Id": "238458",
"ParentId": "238452",
"Score": "3"
}
},
{
"body": "<p>Your assumption is right: the <strong>logging library</strong> should cover your needs. I use it in every script.</p>\n\n<p>Here is some semi-borrowed code that I use in some scripts:</p>\n\n<pre><code># define logging options\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# create a file handler\nhandler = logging.FileHandler(current_dir + log_file)\nhandler.setLevel(logging.DEBUG)\n# create a logging format\nformatter = logging.Formatter('%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s', \"%Y-%m-%d %H:%M:%S\")\nhandler.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(handler)\n</code></pre>\n\n<p>Note that I am logging the <strong>line numbers</strong> as well so it's pretty easy to find the line that generated an exception and figure out the context.</p>\n\n<p>The log looks like this:</p>\n\n<pre><code>2020-02-12 15:51:02 - script.py:507 - __main__ - <module> - INFO - Result: 1500, Message: User logged out\n</code></pre>\n\n<p>There is more code actually, because I also log text <strong>to the console</strong> but in a different format, and only the INFO or ERROR messages. The DEBUG level messages on the other hand are logged to the file, which contains much more information than the console.</p>\n\n<p>Of course the exception handlers use the same logging routine. What I like is the flexibility and the ability to <a href=\"https://docs.python.org/3/howto/logging-cookbook.html#logging-to-multiple-destinations\" rel=\"nofollow noreferrer\">log to multiple destinations</a>.</p>\n\n<p>Obviously, in addition to this technique, you could also have <strong>multiple exception handlers</strong> rather than one single all-purpose <code>except Exception</code> block.</p>\n\n<p>For example to handle key violations in SQLite you could have: </p>\n\n<pre><code>except sqlite3.IntegrityError:\n # do something\n</code></pre>\n\n<p>It depends on opportunity and the complexity of your application. For small scripts one single handler is usually sufficient.</p>\n\n<p>If you really want to add your own special sauce or have special needs not immediately addressed you can still implement your own class by deriving from (or overriding) logging.Logger. Since <code>logging</code> is already widespread in Pythonland I would stick with it.</p>\n\n<p>When an exception occurs you will usually log the Python <strong>stacktrace</strong>.\nBut your exception handling is implemented in such a way that you are missing out on a lot of information that would really help for debugging purposes. The only information available is what you are effectively passing to your function:</p>\n\n<pre><code>except Exception as e:\n error(2, e, table) \n</code></pre>\n\n<p>You are discarding all the exception information available from Python. The Python stacktrace is quite verbose and when you look at it you usually understand very quickly what's wrong, or at least <em>where</em> things went wrong. Here debugging becomes a guessing game because exception handling is being underutilized.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:47:46.420",
"Id": "238459",
"ParentId": "238452",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T21:38:34.723",
"Id": "238452",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"error-handling",
"logging"
],
"Title": "Custom exception handling function or logging library?"
}
|
238452
|
<p>This was born out of a need to create database users on a new server to allow views to be created correctly when restoring databases. This is designed to be run from a command line NOT via a web server. It works with MySQL and MariaDB.</p>
<p>It creates 2 files, one that contains the grants to create the users and a second that creates the grants specific to databases when users only have access to specific commands and/or databases. A sample of each of the output files is included after the code.</p>
<p>I'm just looking for another set of eyes (or several dozen) to see if there is anything that I might be able to do to improve it.</p>
<pre><code><?php
declare(strict_types=1);
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
//
// You must modify the 4 variables below for your environment
//
$dbuser = 'root'; // DB user with authority to SHOW GRANTS from mysql.user
$dbpassword = 'password'; // password for the DB user
$useroutfile = '/temp/Users.sql'; // where to write the user file that may be imported on new server
$grantoutfile = '/temp/Grants.sql'; // where to write the grant file that may be imported on new server
$ignore_users = ['root']; // array of users that should NOT be exported
//
// No reason to modify anything below this comment
//
$dsn = 'mysql:host=localhost;charset=utf8mb4';
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ,
PDO::ATTR_EMULATE_PREPARES => true ,
];
try {
$ourdb = new PDO ($dsn,$dbuser,$dbpassword,$opt);
} catch (PDOException $e) {
error_log('Error ' . $e->getCode() . ' on line ' .
$e->getLine() . ' in ' .
$e->getFile() . ' -> ' .
$e->getMessage()); // log the error so it may be looked at later
echo 'Could not connect to the SQL server';
exit;
} // end of the try/catch block
$notuser = implode(',',array_map('add_quotes',$ignore_users));
//
// We got connected to the database so now let's make sure we can open the
// output files for writing - note that using mode w will overwrite any
// existing files so we'll always start off cleanly
//
$userout = fopen($useroutfile,'w');
if ($userout === false) { // could not open the output file for writing for some reason
echo 'Could not open the output file for writing (' . $useroutfile . ')';
error_log('Could not open the output file for writing (' . $useroutfile . ')');
exit;
} // end of if we could not open the output file for writing
$grantout = fopen($grantoutfile,'w');
if ($grantout === false) { // could not open the output file for writing for some reason
echo 'Could not open the output file for writing (' . $grantout . ')';
error_log('Could not open the output file for writing (' . $grantout . ')');
exit;
} // end of if we could not open the output file for writing
$Query = $ourdb->query("
SELECT CONCAT('SHOW GRANTS FOR ''', user, '''@''', host, ''';') AS query
FROM mysql.user
WHERE user NOT IN(" . implode(',',array_map('add_quotes',$ignore_users)) . ")
");
$users = $Query->fetchAll(PDO::FETCH_COLUMN);
foreach ($users as $GrantQ) { // go through each of the users found
$UserQ = $ourdb->query("$GrantQ"); // retrieve the grants for a user
$grants = $UserQ->fetchAll(PDO::FETCH_COLUMN);
foreach ($grants as $grant) { // go through each of the grants found for this user
if (stripos($grant,'IDENTIFIED BY PASSWORD') === false) {
fwrite($grantout,$grant . ';' . PHP_EOL);
} else {
fwrite($userout,$grant . ';' . PHP_EOL);
}
} // end of foreach through the grants found
} // end of foreach through the queries to show the grants for each user
fwrite($userout ,'FLUSH PRIVILEGES;' . PHP_EOL); // make sure SQL knows about the new users and privileges
fwrite($grantout,'FLUSH PRIVILEGES;' . PHP_EOL); // make sure SQL knows about the new users and privileges
fclose($userout); // close our output file
fclose($grantout); // close our output file
echo 'The grants for ' . count($users) . ' users were written to ' . $useroutfile . PHP_EOL;
function add_quotes($str) {return sprintf("'%s'", $str);}
</code></pre>
<p>Example of the Users.sql file that is created.</p>
<pre><code>GRANT SELECT ON *.* TO 'blah1'@'localhost' IDENTIFIED BY PASSWORD '*73259F6BF87CF1DD3D9B6070AD869CA8972ACA23';
GRANT ALL PRIVILEGES ON *.* TO 'blah2'@'localhost' IDENTIFIED BY PASSWORD '*3BE30E0E232031AD5ED5B33C6A96EB1357A533AD' WITH GRANT OPTION;
GRANT SELECT, INSERT, UPDATE, CREATE TEMPORARY TABLES ON *.* TO 'blah3'@'localhost' IDENTIFIED BY PASSWORD '*2F1649FADAF4E72546D4AE902AE3FABD9AA047EF';
</code></pre>
<p>Example of the Grants.sql file that is created.</p>
<pre><code>GRANT ALL PRIVILEGES ON `abcdb`.* TO 'user'@'10.%';
GRANT SELECT, CREATE TEMPORARY TABLES, SHOW VIEW ON `efgdb`.* TO 'user'@'10.%';
GRANT DELETE ON `hijdb`.`table1` TO 'user1'@'localhost';
</code></pre>
|
[] |
[
{
"body": "<h1>General thoughts</h1>\n\n<p>The script looks decent. I like how most lines have sufficient spacing that lends itself to readability and there are ample comments throughout the code. </p>\n\n<p>It is good that the script exits early when it cannot connect to the database or cannot open a file for writing. Initially I thought about suggesting that <code>file_put_contents()</code> be used instead of <code>fopen()</code>, <code>fwrite()</code> and <code>fclose()</code> but that would require dramatic changes to the structure of the script and might lead to queries being run before the file paths could be checked.</p>\n\n<h1>Suggestions</h1>\n\n<h2>Constants</h2>\n\n<p>While it appears you intend to have users of this script modify them, <code>$useroutfile</code> and <code>$grantoutfile</code> could be declared as constants, since the value is never re-assigned. The same would also apply to the values stored in variables for the database connection info (e.g. <code>$dbuser</code>, <code>$dbpassword</code>).</p>\n\n<p>Another thing to consider for those values is to get them from command line arguments or else user input.</p>\n\n<h2>Database Server name hard-coded</h2>\n\n<p>The value for <code>$dsn</code> contains <code>localhost</code> for the host name:</p>\n\n<blockquote>\n<pre><code>$dsn = 'mysql:host=localhost;charset=utf8mb4';\n</code></pre>\n</blockquote>\n\n<p>Some users might need to modify a database server other than <em>localhost</em>. It may be wise to support a different host name with a variable/constant that can be configured at the top of the script.</p>\n\n<h2>Unused variable <code>$notuser</code></h2>\n\n<p>This variable doesn't appear to be used after it is assigned:</p>\n\n<blockquote>\n<pre><code>$notuser = implode(',',array_map('add_quotes',$ignore_users));\n</code></pre>\n</blockquote>\n\n<p>I presume you intended to use that in the <code>WHERE</code> condition inside the string assigned to <code>$Query</code>.</p>\n\n<h2>Use consistent variable naming patterns</h2>\n\n<p>I see most variables are in all lowercase, but there are a couple outliers:</p>\n\n<ul>\n<li><code>$ignore_users</code></li>\n<li><code>$Query</code></li>\n</ul>\n\n<p>It is best to stick to a common convention for naming variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T09:54:53.847",
"Id": "467692",
"Score": "0",
"body": "Thanks very much Sam. I changed the variables to constants as suggested and added the host name as a constant so it may be changed too. Totally missed that `$notuser` and removed it. It was a leftover and I had moved what was being created into the actual query itself. Changed the case of `$Query` too. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T09:56:02.680",
"Id": "467693",
"Score": "0",
"body": "I had considered supporting command line options but could not justify, in my mind, the additional code required to do that. This isn't something that is likely to be used frequently so I made the decision to have it be modified if needed more than once."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:12:13.790",
"Id": "238460",
"ParentId": "238454",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:05:54.030",
"Id": "238454",
"Score": "2",
"Tags": [
"php",
"mysql",
"console",
"pdo"
],
"Title": "Extract users and privileges from MariaDB and MySQL"
}
|
238454
|
<p>This weekend I've been working on a small asynchronous web crawler built on top of asyncio. The webpages that I'm crawling from have Javascript that needs to be executed in order for me to grab the information I want. Hence, I'm using pyppeteer as the main driver for my crawler.</p>
<p>I'm looking for some feedback on what I've coded up so far, as async, asyncio, and pyppeteer are all still fairly new to me and I feel I'm making some pretty big, naive mistakes in my approach. I'm also using this as an opportunity to learn. Any feedback is greatly appreciated! Thanks.</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
import lxml.html as html
from pyppeteer import launch
seed = 'https://example.com' # Base seed URL
def get_links(url, text):
""""Returns a list of valid URLs from a given document.
Args:
url: the url of the page
text: the HTML document
Returns:
l: a list of valid urls to crawl
"""
h = html.fromstring(text)
l = [a.attrib['href'] for a in h.xpath('//a')]
l = [seed+a for a in filter(lambda a: 'http' not in a, l)] # Removes external URLs.
return l
async def _crawl(browser, que):
"""Crawls a webpage.
Args:
browser: a pyppeteer browser object
que: the main task queue
"""
page = await browser.newPage() # Creates a new page
seen = set()
while not que.empty():
url = await que.get() # Retrieves a url from the task queue
if url in seen: # If the url has already been crawled, complete the task and continue
que.task_done()
continue
seen.add(url)
await page.goto(url, timeout=10000) # go to the current url
text = await page.content() # get the page content
links = get_links(page.url, text) # retrieve valid links to be crawled
for link in links:
if link in seen:
continue
que.put_nowait(link) # put an unseen link into the task queue
print('put %3d links from %s into queue' % (len(links), url))
que.task_done() # complete the task
class CrawlerPool:
"""A worker pool for managing crawlers."""
def __init__(self, loop, coro, max_crawlers):
self.loop = loop
self.q = asyncio.Queue(loop=self.loop)
self.coro = coro
self.max_crawlers = max_crawlers
async def run(self):
browser = await launch()
crawlers = []
for _ in range(self.max_crawlers):
crawlers.append(asyncio.create_task(self.coro(browser, self.q)))
await self.q.join()
for c in crawlers:
c.cancel()
await browser.close()
print('done.')
loop = asyncio.get_event_loop()
cp = CrawlerPool(loop, _crawl, 5)
cp.q.put_nowait(seed)
loop.run_until_complete(cp.run())
</code></pre>
<p><strong>Edit</strong> Added additional comments to code and concerns.</p>
<p>The concerns I have are mostly a result of my ignorance to asynchronous functions in Python and the pyppeteer library. I'm ideally just looking for feedback if what I've written makes sense in an asynchronous model.</p>
<p><strong>Additional Edit</strong></p>
<p>After looking over and reviewing it with a coworker, this snippet seems to work fine. I believe that the for loop containing all the <code>c.cancel()</code> calls can even be removed as they are redundant.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:46:37.380",
"Id": "467671",
"Score": "0",
"body": "Could you add a short explanation for how your code works, and why you made any unorthodox choices if you did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T01:28:01.490",
"Id": "467673",
"Score": "2",
"body": "See edit. I wish I could give a better sense of my concerns - I'm still learning and so the I'm afraid that my questions won't make sense and feel that if someone could point to anything that doesn't seem right, that'd be appreciated. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T22:33:00.390",
"Id": "238456",
"Score": "2",
"Tags": [
"python",
"asynchronous"
],
"Title": "Asynchronous Web Crawler with Pyppeteer - Python"
}
|
238456
|
<p>I've written a relatively small abstract class in Java which keeps track of all instances of it's sublasses. Any class which extends this abstract class will automatically have all its instances stored (via a weak reference) in a Set, which can be retrieved if a subclass ever wants to get references to all it's instances.</p>
<p>Although this class is relatively short and simple, I have never made anything like it and so I want to ensure that I'm not doing something terribly wrong or giving in to any bad practices:</p>
<pre><code>import java.util.*;
public abstract class InstanceRecorder {
private static Map<Class<? extends InstanceRecorder>, Set<InstanceRecorder>> instances;
static {
instances = new HashMap<>();
}
{
instances.putIfAbsent(this.getClass(), Collections.newSetFromMap(new WeakHashMap<>()));
instances.get(this.getClass()).add(this);
}
protected static int countInstances(Class<? extends InstanceRecorder> key) {
if (instances.containsKey(key))
return instances.get(key).size();
return 0;
}
@SuppressWarnings("unchecked")
protected static <T extends InstanceRecorder> Set<T> getInstances(Class<T> key) {
if (instances.containsKey(key))
return Collections.unmodifiableSet((Set<T>) instances.get(key));
return new HashSet<>();
}
}
</code></pre>
<p>As I said above, I've never made a class like this before and so any feedback or insight would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T07:19:43.027",
"Id": "467685",
"Score": "2",
"body": "Can you give an example of when you think this might be useful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T21:46:59.110",
"Id": "467758",
"Score": "1",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T21:48:57.223",
"Id": "467760",
"Score": "0",
"body": "@Sᴀᴍ Onᴇᴌᴀ, You're correct - It says \"Do not add an improved version of the code.\" My mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T22:06:33.617",
"Id": "467762",
"Score": "0",
"body": "@forsvarir, I was imagining that this would be useful in cases where a programmer would want to call an instance method or change the value of an instance variable on all instances of a certain class. The programmer could, of course, simply use an array for this task, however this class stores instances automatically and also illuminates the risk of a memory leak as it utilizes weak references."
}
] |
[
{
"body": "<p>in my opinion, the code is good, but I have some suggestions.</p>\n\n<ol>\n<li>Instead of using <code>java.util.Map#containsKey</code>, you can directly use <code>java.util.Map#get</code> and check if the value is null.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>protected static int countInstances(Class<? extends InstanceRecorder> key) {\n Set<InstanceRecorder> instanceRecorders = instances.get(key);\n\n if (instances != null) \n return instanceRecorders.size();\n\n return 0;\n}\n\n@SuppressWarnings(\"unchecked\")\nprotected static <T extends InstanceRecorder> Set<T> getInstances(Class<T> key) {\n Set<InstanceRecorder> instanceRecorders = instances.get(key);\n\n if (instanceRecorders != null)\n return Collections.unmodifiableSet((Set<T>) instanceRecorders);\n\n return new HashSet<>();\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>In my opinion, it's a bad practice not to put the braces when you have a single instruction coupled with <code>if</code>, <code>while</code>, <code>for</code>, etc. This can make the code harder to read and can cause confusion.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T02:43:39.407",
"Id": "238466",
"ParentId": "238461",
"Score": "3"
}
},
{
"body": "<p>Two very small details:</p>\n\n<p>Instead of using <code>putIfAbsent</code> / <code>get</code>, you can use the single function <code>computeIfAbsent</code>:</p>\n\n<pre><code>instances.computeIfAbsent(\n this.getClass(),\n ign -> Collections.newSetFromMap(new WeakHashMap<>())\n).add(this);\n</code></pre>\n\n<p>Instead of a <code>new HashSet</code> for a not-found-result, you can simply return <code>Collections.emptySet()</code>. As your return value is immutable anyway this is more consistent and does not create an additional object for nothing.</p>\n\n<p>(And just to give another opinion: I prefer not to have braces around single statements - only so that you know there is no unambiguos truth out there :-))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T17:03:22.267",
"Id": "467730",
"Score": "0",
"body": "Yes, this makes the code look far cleaner, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T04:51:53.480",
"Id": "238468",
"ParentId": "238461",
"Score": "8"
}
},
{
"body": "<p>Your code is not thread-safe. You should use <code>ConcurrentHashMap</code> instead of <code>HashMap</code>, if this code is ever run in a multithreaded environment.</p>\n\n<p>In Java 8 there was a <a href=\"https://bugs.openjdk.java.net/browse/JDK-8161372\" rel=\"noreferrer\">terrible performance bug</a> in <code>ConcurrentHashMap.computeIfAbsent</code>, which would lock the whole map even if the key already exists. That bug has been fixed in Java 9. See also <a href=\"https://stackoverflow.com/questions/26481796/concurrenthashmap-computeifabsent/26483476\">this question</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T17:04:12.797",
"Id": "467731",
"Score": "0",
"body": "I completely forgot about Thread safety! Nice catch"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T07:12:29.763",
"Id": "238469",
"ParentId": "238461",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "238468",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:38:56.420",
"Id": "238461",
"Score": "9",
"Tags": [
"java",
"object-oriented"
],
"Title": "Subclass instance recorder in Java"
}
|
238461
|
<p>I am not a developer, but I needed to write a script. </p>
<p>So I wrote it. Since I can't find an accessible tool that fulfills the same purpose, which I think may be helpful to others, I decided to publish it: <a href="https://github.com/gabriel-de-luca/simil/blob/master/simil.py" rel="nofollow noreferrer">https://github.com/gabriel-de-luca/simil/blob/master/simil.py</a></p>
<p>I am open to review it completely, but I would particularly like to consult on the way I am checking the validity of the data. </p>
<p>The main function is called <code>process</code> and has two positional parameters: <code>source_points</code> and <code>target points</code>, of <code>array_like</code> (<em>numpy</em>) type. </p>
<p>The first thing I do is convert the inputs into numpy arrays and transpose them, because all the code requires one row per coordinate (<em>X</em>, <em>Y</em> and <em>Z</em>) and one column per point. </p>
<p>In addition to transposing it, I verify that it has three coordinates, and if it has just two coordinates I allow myself to fill the <em>Z</em> with zeroes.</p>
<pre><code>import numpy as np
def _get_coords(points):
coords = np.array(points, dtype=float, ndmin=2).T
if coords.shape[0] != 3:
if coords.shape[0] == 2:
coords = np.concatenate((coords, np.zeros((1, coords.shape[1]))))
else:
raise
return coords
def process(source_points, target_points, alpha_0=None, scale=True, lambda_0=1):
"""
Find similarity transformation parameters given a set of control points
"""
print('Processing...')
# false outputs to return if an exception is raised
false_lambda_i = 0
false_r_matrix = np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
false_t_vector = np.array([[0], [0], [0]])
# checks
try:
source_coords = _get_coords(source_points)
except:
print('ERROR:\n' +
f'source_points = {source_points}' +
'\n could not be broadcasted as a numerical array' +
'\n with shape = (n, 3).')
return false_lambda_i, false_r_matrix, false_t_vector
</code></pre>
<p>Then, the code continues to do other checkups, and if everything goes well, it returns valid values in the output variables: </p>
<pre><code> print('Done.')
return lambda_i, r_matrix, t_vector
</code></pre>
<p>If I did not do this check, many errors of different types could occur in other private functions when the data is processed. </p>
<hr>
<p>I run this script from other scripts, and this is what happens if I send invalid data: </p>
<pre><code>import simil
source_points = [[0]]
target_points = [[1]]
m, r, t = simil.process(source_points, target_points)
print('\nm value returned = ' + str(m))
</code></pre>
<p>Returns: </p>
<pre class="lang-none prettyprint-override"><code>Processing...
ERROR:
source_points = [[0]]
could not be broadcasted as a numerical array
with shape = (n, 3).
m value returned = 0
</code></pre>
<p>It works fine to me, because I can check if <code>m == 0</code> in the other script to stop it, but I am publishing my script and I don't know if this is the right way to handle the exception, or how to improve it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:07:19.823",
"Id": "467724",
"Score": "1",
"body": "Welcome to Code Review! 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": "2020-03-06T19:57:34.450",
"Id": "467746",
"Score": "0",
"body": "@TobySpeight, The purpose of the code would be the evaluation of the input values? A thousand apologies but I don't understand what you mean. Feel free to edit the title of my question or please try to be more specific."
}
] |
[
{
"body": "<p>To me you're kind of handling the exception in two ways:</p>\n\n<ul>\n<li>you are acting like a library in the sense that you <em>talk</em> about an exception to be raised;</li>\n<li>you are acting like an application in the sense that you print out error messages and then continue running.</li>\n</ul>\n\n<p>I think you are mainly having the script / function be used as a library, as you return the matrix rather than printing it out. If you talking about handling the exception for a library function, which seems most reasonable, then you should <code>raise</code> an exception rather than returning a <em>magic value</em> (<code>m = 0</code>) that you can check. Make sure that the exception has a clear message that may be put into a stacktrace in case it isn't handled. So you <em>catch and re-raise</em>.</p>\n\n<p>In your case it is probably best to throw a more specific exception in <code>_get_coords</code> though, e.g.:</p>\n\n<pre><code>raise ValueError(f'source_points = {source_points}' +\n '\\n could not be broadcasted as a numerical array' +\n '\\n with shape = (n, 3).')\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>It works fine to me, because I can check if m == 0 in the other script to stop it</p>\n</blockquote>\n\n<p>That's <em>exactly</em> what exceptions are for. Just let the other script catch it and stop. The situation could be different if you would want to keep on running with a different matrix.</p>\n\n<p>Magic values are often unclear to the reader, and may be skipped on accident. Try to avoid them as much as possible. You don't want to run on with the magic value as <em>invalid state</em>, so raise and make sure you don't.</p>\n\n<hr>\n\n<p>The same thing happens when you print <code>Processing...</code> to the output stream. Generally library functions don't print to the output stream. If you want to have a progress indication, then allow some kind of progress reporting function to be present as parameter or class field, and report progress that way. If you just want to indicate that it started progressing then you should however just let the <em>user of the library</em> report that a function is called.</p>\n\n<p>Using a logger rather than output stream would be highly advisable.</p>\n\n<p>You can find more information about listeners <a href=\"https://python-can.readthedocs.io/en/master/listeners.html\" rel=\"nofollow noreferrer\">here</a>. Logging is also mentioned over there, which is likely not coincidental.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T10:09:04.357",
"Id": "467694",
"Score": "0",
"body": "Thank you very much for your answer. It would be very helpful for me if you could also exemplify, from: _\"then you should `raise` an exception ...\"_ to _\"... that the exception has a clear message\"_ , about how to impement it in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T10:12:35.977",
"Id": "467696",
"Score": "0",
"body": "No need to be in my code, just an example on a function about how to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T12:00:48.730",
"Id": "467711",
"Score": "0",
"body": "@MaartenBodewes The easiest way to get access to numpy and lots of other useful scientific Python packages is to use something like [Anaconda Python](https://www.anaconda.com/distribution/), in case you haven't heard of it. The process is relatively painless and fast ;-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T09:11:35.150",
"Id": "238472",
"ParentId": "238465",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238472",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T02:41:12.663",
"Id": "238465",
"Score": "4",
"Tags": [
"python",
"error-handling",
"numpy"
],
"Title": "How to stop a Python script if the input values do not make sense within the environment in which they will be analyzed?"
}
|
238465
|
<p>This is a follow up to
<a href="https://codereview.stackexchange.com/questions/238253/chunking-strings-to-binary-output">Chunking strings to binary output</a></p>
<p>I found the reviews quite helpful in pinpointing what to fix with my code. Here's the result of that update. The format of the output is the same as documented there, but to briefly recap:</p>
<p>The stream format consists of <em>blocks</em>, each 256 bytes long. Each block begins with a fixed 4-byte block identifier and ends with a 4-byte checksum. Everything between them is data.</p>
<p>The data is in the form of <em>counted strings</em>. A counted string is a one byte unsigned integer <span class="math-container">\$n\$</span> followed by that many bytes of data. A counted string may or may not be NUL character terminated. All counted strings are 0 to 255 bytes long with a length of 0 signifying a blank line.</p>
<p>The test program reads in a text file, the name of which is passed on the command line. Each line is then converted to a counted string and output as Blocks to the binary output file, also passed as a command line argument.</p>
<h2>Questions</h2>
<p>I think the separation is much better, but I'd really rather have hidden the entire definition of <code>Block</code> within the <code>Chunkster.cpp</code> file. There didn't seem to be an elegant way to do that. I tried a version that used the <a href="https://en.cppreference.com/w/cpp/language/pimpl" rel="nofollow noreferrer">pimpl</a> idiom, but it seemed ugly to me.</p>
<h2>Chunkster.h</h2>
<pre><code>#ifndef CHUNKSTER_H
#define CHUNKSTER_H
#include <iostream>
#include <fstream>
#include <string_view>
#include <cstdint>
#include <algorithm>
#include <numeric>
#include <array>
class Block {
public:
//! each block is this many bytes
static constexpr std::size_t mysize{0x100};
//! read a block
friend std::istream& operator>>(std::istream& in, Block& blk);
//! write a block
friend std::ostream& operator<<(std::ostream& out, const Block& blk);
//! append passed data to this Block and return bytes actually written
std::size_t append(const void *mydata, std::size_t len);
//! reset the Block by clearing data
void reset();
//! fix the Block's checksum to correct value
uint32_t fixSum() { return checksum = sumcalc(); }
//! returns true if checksum is correct
bool isGood() const { return sumcalc() == checksum; }
//! returns true if no more bytes can be stored in Block
bool isFull() const { return remaining == 0; }
private:
//! calculates the checksum of the block
uint32_t sumcalc() const;
//! the magic value used for each block
static constexpr uint32_t magic{0xfecaadbe};
//! the id value (should always equal magic)
uint32_t id = magic;
//! checksum of Block
uint32_t checksum = magic;
//! size of data portion of Block in bytes
static constexpr std::size_t datasize{mysize - sizeof(id) - sizeof(checksum)};
//! the data portion of the Block
std::array<char, datasize> data;
//! number of unused bytes remaining in the data section of this Block
std::size_t remaining{datasize};
//! pointer to the next unused byte in the data section of this Block
char *curr = &data[0];
};
class Chunkster {
public:
//! constructor for writing chunks
Chunkster(const char *filename, std::ios_base::openmode mode = std::ios_base::out);
//! write passed string to chunkified output
bool write(std::string_view str);
//! destructor
virtual ~Chunkster();
private:
//! flush the last written chunk if the current Block is full
void flushIfFull();
//! unconditionally flush output
void flush();
//! output file
std::ofstream out;
//! current Block used for output
Block current;
};
#endif // CHUNKSTER_H
</code></pre>
<h2>Chunkster.cpp</h2>
<pre><code>#include "Chunkster.h"
// will have this in C++20, but not yet implemented
#define HAVE_SPAN 0
#if HAVE_SPAN
#include <span>
#endif
std::istream& operator>>(std::istream& in, Block& blk) {
blk.data.fill(0);
in.read(blk.data.begin(), sizeof(blk.data));
in.read(reinterpret_cast<char *>(&blk.checksum), sizeof(blk.checksum));
return in;
}
std::ostream& operator<<(std::ostream& out, const Block& blk) {
out.write(reinterpret_cast<const char *>(&blk.id), sizeof(blk.id));
out.write(blk.data.begin(), sizeof(blk.data));
out.write(reinterpret_cast<const char *>(&blk.checksum), sizeof(blk.checksum));
return out;
}
// append passed data to this Block and return bytes actually written
std::size_t Block::append(const void *mydata, std::size_t len) {
len = std::min(len, remaining);
auto ptr{reinterpret_cast<const char *>(mydata)};
std::copy(ptr, ptr+len, curr);
remaining -= len;
curr += len;
return len;
}
void Block::reset() {
data.fill(0);
remaining = datasize;
curr = &data[0];
}
uint32_t Block::sumcalc() const {
#if HAVE_SPAN
std::span as_u32{reinterpret_cast<std::uint32_t*>(data.begin()),
reinterpret_cast<std::uint32_t*>(data.end())};
return std::accumulate(as_u32.begin(), as_u32.end(), std::uint32_t{});
#else
return std::accumulate(
reinterpret_cast<const std::uint32_t*>(data.begin()),
reinterpret_cast<const std::uint32_t*>(data.end()),
id);
#endif
}
Chunkster::Chunkster(const char *filename, std::ios_base::openmode mode) :
out{filename, mode}
{}
bool Chunkster::write(std::string_view str) {
if (str.length() < 256) {
uint8_t n = str.length();
current.append(&n, 1);
flushIfFull();
std::size_t index{0};
while(n) {
auto written = current.append(&str[index], n);
//current.dump(std::cout);
n -= written;
index += written;
flushIfFull();
}
}
return out.good();
}
Chunkster::~Chunkster() {
flush();
}
void Chunkster::flushIfFull() {
if (current.isFull()) {
flush();
current.reset();
}
}
void Chunkster::flush() {
current.fixSum();
out << current;
}
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "Chunkster.h"
#include <string>
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]) {
std::string line;
if (argc != 3) {
std::cerr << "Usage: encode infile outfile\n";
return 1;
}
std::ifstream in(argv[1]);
Chunkster out{argv[2], std::ios_base::binary};
while (std::getline(in, line)) {
out.write(line);
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Pass a <code>std::ostream</code> to <code>Chunkster()</code> instead of a filename</h1>\n\n<p>The goal of your <code>class Chunkster</code> is to convert the format of one stream to another, it shouldn't have to open and close files. Just pass a <code>std::ostream</code> to the constructor instead of a filename and open mode. This makes your class simpler and at the same time more flexible, because now you could have it write to a <code>std::stringstream</code> or any other type that inherits from <code>std::ostream</code>.</p>\n\n<h1>Be more thorough handling errors</h1>\n\n<p>There is some attempt at error handling in your code, but it falls short. For example, <code>write()</code> returns a boolean to indicate whether the output stream is still good, but <code>flush()</code> and <code>flushIfFull()</code> do no such thing. Either have all functions that potentially do I/O return something indicating success, or add a separate function that can be used to check the current error state, perhaps a <code>bool Chunkster::good()</code>.</p>\n\n<p>Another issue is that <code>write()</code> returns success if you give it a string longer than 255 characters. You should return an error in this case.</p>\n\n<h1>Move <code>class Block</code> into <code>class Chunkster</code></h1>\n\n<p>Since a <code>Block</code> is only a utility class for <code>Chunkster</code>, and not meant to be used by anything else but a <code>Chunkster</code>, it is better to move this into <code>Chunkster</code> itself, so it doesn't pollute the global namespace. So it would look like:</p>\n\n<pre><code>class Chunkster {\n ...\n\n private:\n class Block {\n ...\n } current;\n};\n</code></pre>\n\n<p>If you really want to keep them separate, I recommend you put both <code>Block</code> and <code>Chunkster</code> in their own namespace.</p>\n\n<h1>Avoid clearing <code>data</code> unnecessarily</h1>\n\n<p>Every time you flush a block, you the call <code>reset()</code>, which fills the block with zero bytes. However, in normal use, you would fill the whole block with new strings, so all zeroes are overwritten. It might be more efficient to just zero the unused bytes of a block right before calculating the checksum.</p>\n\n<h1>Avoid writing multiple implementations of a function for different versions of C++</h1>\n\n<p>In <code>sumcalc()</code>, you have two implementations, one for C++20 where you use spans, and one for earlier versions of C++, and you use <code>#ifdefs</code> to select which version to use at compile time. I would avoid doing this, because there is absolutely no difference in performance here, and the non-span version works just as well on C++20.</p>\n\n<p>In general, set a minimum C++ version for your project, and code against that. The only time you should use <code>#ifdefs</code> to provide alternative implementations is when you want to provide a different <em>interface</em> for your classes, so it is easier to use with newer versions of C++. For example, if your minimum version was C++11, then it would make sense to provide a version of <code>write()</code> that takes a const reference to a <code>std::string</code>, and then also provide a <code>write()</code> function that takes a <code>std::string_view</code>, but only compile that one conditionally.</p>\n\n<p>Code duplication can lead to errors. For example, depending on whether or not you have spans, you use a different initial value for the accumulation: <code>std::uint32_t{}</code> for the span version, <code>id</code> for the other version.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T10:10:11.407",
"Id": "239606",
"ParentId": "238474",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239606",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T13:17:43.290",
"Id": "238474",
"Score": "2",
"Tags": [
"c++",
"stream",
"c++20"
],
"Title": "Chunking strings to binary block-based output"
}
|
238474
|
<p>I'd like a review of my design for an Instagram-like application where users can post and comment on pictures. </p>
<p>I just finished a freecodecamp crash course on database design and this is the first ERD I make. If you also have suggestions for readings on this topic I'd appreciate it.</p>
<p><a href="https://i.stack.imgur.com/JTbP5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JTbP5.png" alt="enter image description here"></a></p>
<p>This is my SQL code:</p>
<pre><code>CREATE TABLE users
(
id SERIAL PRIMARY KEY,
username VARCHAR(30) UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
salted_password TEXT NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP
);
CREATE TABLE photos
(
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
caption VARCHAR(150),
latitude DECIMAL,
longitude DECIMAL,
src TEXT NOT NULL,
size INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE avatars
(
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
src TEXT NOT NULL,
size INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE comments
(
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
photo_id INTEGER NOT NULL,
comment VARCHAR(300) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(photo_id) REFERENCES photos(id) ON DELETE CASCADE
);
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T14:30:03.657",
"Id": "238478",
"Score": "1",
"Tags": [
"sql",
"database",
"postgresql"
],
"Title": "Database design for Instagram-like post/comments"
}
|
238478
|
<p>I have the following scenario where most of my functions require to return different things based on a condition. </p>
<pre><code>def get_root_path(is_cond_met=False):
if is_cond_met:
return "something"
else
return "something else"
def get_filename(is_cond_met=False):
if is_cond_met:
return "file name A"
else
return "file name B"
</code></pre>
<p><strong>is_cond_met</strong> is going to be common for all the functions I am calling. I have just put two here however I have more than 15. </p>
<p>The above code works, however, doesn't seem optimal, or pythonic. Is there a better solution for this? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:50:21.677",
"Id": "467726",
"Score": "0",
"body": "Are all those functions depend on the same \"global\" boolean variable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:51:57.143",
"Id": "467727",
"Score": "0",
"body": "@RomanPerekhrest global are error-prone in python and so I don't want to use them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:53:56.327",
"Id": "467728",
"Score": "0",
"body": "Then why did you write \"is_cond_met is going to be **common** for all the functions I am calling\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T16:07:13.980",
"Id": "467729",
"Score": "0",
"body": "Globals are error prone because they make it hard to track the data flow in and out of functions. If you simply use them as a \"read-only\" flag, they can be perfectly fine."
}
] |
[
{
"body": "<p>Your example is a little too example-y for me to know if this is actually right for whatever you're actually doing, but if you have two parallel implementations of a set of behavior within the same set of functions, you might think about moving them into classes:</p>\n\n<pre><code>from abc import ABC, abstractmethod\n\n\nclass CondFile(ABC):\n\n @abstractmethod\n def get_root_path(self) -> str:\n pass\n\n @abstractmethod\n def get_filename(self) -> str:\n pass\n\n\nclass CondTrueFile(CondFile):\n\n def get_root_path(self) -> str:\n return \"something\"\n\n def get_filename(self) -> str:\n return \"file name A\"\n\n\nclass CondFalseFile(CondFile):\n\n def get_root_path(self) -> str:\n return \"something else\"\n\n def get_filename(self) -> str:\n return \"file name B\"\n\n\nif is_cond_met:\n cond_file = CondTrueFile()\nelse:\n cond_file = CondFalseFile()\nprint(cond_file.get_root_path())\nprint(cond_file.get_filename())\n</code></pre>\n\n<p>It really depends what the condition represents, but if it results in completely different behavior across fifteen functions, it's a good clue that it represents a different \"kind of\" thing that your program is dealing with, i.e. a <strong>type</strong>, which is in turn a good clue that you want a different class to represent that type in your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T16:15:28.310",
"Id": "238484",
"ParentId": "238480",
"Score": "2"
}
},
{
"body": "<p>If the functions are simply returning constants as in your example you could make a dictionary as a <em>lookup table</em> and do something like this:</p>\n\n<pre><code>ANSWERS = {\n 'root_path' : { True: 'something' , False: 'something else' },\n 'file_name' : { True: 'file name A' , False: 'file name B' },\n}\n\ndef get_answer(question, is_cond_met=False):\n return ANSWERS[question][is_cond_met]\n\n# usage example\nprint(get_answer('file_name', True))\n</code></pre>\n\n<p>Perhaps you want to add some more specific error checking:</p>\n\n<pre><code>def get_answer(question, is_cond_met=False):\n try:\n answers = ANSWERS[question]\n except KeyError:\n msg = \"Unknown question '{}' for get_answer\".format(question)\n raise ValueError(msg)\n return answers[is_cond_met]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T18:46:01.187",
"Id": "238492",
"ParentId": "238480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:11:51.373",
"Id": "238480",
"Score": "2",
"Tags": [
"python"
],
"Title": "Better pythonic way to pass condition to multiple functions"
}
|
238480
|
<p>Given an array of integers, find two numbers such that they add up to a specific target number.</p>
<p>The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.</p>
<p>If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.</p>
<pre><code>twoSum : function(A, B){
var tempA = A;
var index1 = [];
var index2 = [];
var Results = [];
for(var i = 0; i < A.length - 1; i++){
var temp = B - A[i];
for(var j = i; j < A.length - 1; j++){
if(temp == A[j]){
if(j - i > 0){
if(j < Results[1] || Results.length == 0){
if(A[j] != A[Results[1]-1] && A[i] != A[Results[0]-1]){
Results[0] = i + 1;
Results[1] = j + 1;
}
}
}
}
}
}
return Results;
}<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T17:26:11.957",
"Id": "467735",
"Score": "0",
"body": "Could you change your title to a more general explanation of what your code does? A question about how to improve your code is implied in all code review question, and is therefore unnecessary."
}
] |
[
{
"body": "<p>Variables <code>tempA</code>, <code>index1</code> and <code>index2</code> seem to be unused.</p>\n\n<p>Since you are only interested in <code>if(j - i > 0){</code>, you can start right there\n<code>for (int j = i + 1;</code> and omit the conditional.</p>\n\n<p>Further the condition <code>if(j < Results[1] || Results.length == 0){</code> should be flipped around to <code>if(Results.length == 0 || j < Results[1]){</code> to avoid accessing undefined index.</p>\n\n<p>But actually the variable Results is uselesss because you can return the pair as soon as you find it. Just iterate in the desired directions.</p>\n\n<pre><code>function twoSum(input, targetSum){\n const limit = input.length;\n for(var j = 1; j < limit; ++j){\n var temp = targetSum - input[j];\n for(var i = 0; i < j; ++i){\n if(temp == input[i]){\n return [i + 1, j + 1];\n }\n }\n }\n return [];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T16:33:22.903",
"Id": "238485",
"ParentId": "238481",
"Score": "2"
}
},
{
"body": "<p>Yes, this should be more efficient asymptotically</p>\n\n<pre><code>function myTwoSum(A, B) {\n const invertedArrayMap = A.reduce((acc, curr, i) => {\n acc[curr] = acc.hasOwnProperty(curr) ? Math.min(i, acc[curr]) : i;\n return acc;\n }, {});\n\n const secondIndex = A.findIndex(\n (w, i) =>\n invertedArrayMap.hasOwnProperty(B - w) && invertedArrayMap[B - w] < i\n );\n\n if (secondIndex === -1) {\n return [];\n }\n return [invertedArrayMap[B - A[secondIndex]], secondIndex];\n}\n</code></pre>\n\n<p>We use an object to allow O(1) lookups for the corresponding value, allowing us to not have this nested O(n^2) computation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T20:30:46.970",
"Id": "238583",
"ParentId": "238481",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T15:12:01.203",
"Id": "238481",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Is there any more efficient way to code this “2 Sum” Questions"
}
|
238481
|
<p>I got tired of the boilerplate and tedium restoring formatting context, so I made an RAII stasher that relies on the destroy-at-end-of-full-statement temporary semantics. With C++17 I can get it down to a single type, no helpers:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
template< template<typename, class> class streamtmp, typename charT, class traits >
struct fmtstash {
typedef streamtmp<charT,traits> streamtype;
streamtype &from;
std::ios_base::fmtflags flags;
std::streamsize width;
std::streamsize precision;
charT fill;
fmtstash(streamtype &str)
: from(str), flags(str.flags()), width(str.width())
, precision(str.precision()), fill(str.fill()) {}
~fmtstash() { from.flags(flags), from.width(width), from.precision(precision), from.fill(fill); }
template<typename T> streamtype &operator<<(const T &rhs) { return from << rhs; }
template<typename T> streamtype &operator>>( T &rhs) { return from >> rhs; }
};
int main(int c, char **v)
{
using namespace std;
fmtstash(cout) << hex << 51901 <<'\n';
cout << 51901 <<'\n';
return 0;
}
</code></pre>
<p>which produces about the easiest-to-write-and-read formatting I can manage.</p>
<p>Am I missing any bets here? Shorter or more robust is what I'm after.</p>
<p>The biggest improvement I found since I first wrote it is to use <code>from << rhs</code> instead of the <code>from.operator<<(rhs)</code> I had, since user-defined stream insert/extractors have to be free functions and of course an explicit member callout breaks those.</p>
<p>I could make the template args simpler, just <code>template<class streamtmp></code>, the full breakout is a holdover from when I had the internal reference as <code>ios_base<charT,traits> &from;</code> instead of the full original type, but I ran across a broken inserter that wanted to be first or only and took an ostream reference as its left operand.</p>
<p>And of course the boost savers don't supply the inserter and extractor templates at all. Is this an oversight or is there some argument against using the destroy-at-end-of-full-expression semantics this way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:24:13.863",
"Id": "467935",
"Score": "1",
"body": "I posted [something similar](/q/189753/75307) a couple of years ago, so you might want to compare approaches. I do like the simple usability of your code; I wish I'd thought of making it usable as a stream itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:40:55.137",
"Id": "467982",
"Score": "0",
"body": "@TobySpeight I missed yours in searching for dups (iostream vs stream, my bad), so I missed all the great comments and discussion there. Locales and afaics never locally changed, and changing them seems so expensive, I left them out. Also seems I should be using && not &, to get the value-or-ref deduction working."
}
] |
[
{
"body": "<p>Since you aren't using the full template form of the stream, just drop it. <code>charT</code> can be replaced by <code>stream::char_type</code>.</p>\n\n<p>There is an rvalue overload for standard stream types.</p>\n\n<p>The parameters to <code>main</code> are conventionally named <code>argc</code> and <code>argv</code>. Since you aren't using these parameters, omit them to avoid unused parameter warnings.</p>\n\n<p>I think the code may be more readable if you avoid squeezing everything on one line:</p>\n\n<pre><code>~fmtstash()\n{\n from.flags(flags);\n from.width(width);\n from.precision(precision);\n from.fill(fill);\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>~fmtstash() { from.flags(flags), from.width(width), from.precision(precision), from.fill(fill); }\n</code></pre>\n\n<p>Similarly,</p>\n\n<pre><code>template <typename T>\nstreamtype& operator<<(const T& rhs)\n{\n return form << rhs;\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>template<typename T> streamtype &operator<<(const T &rhs) { return from << rhs; }\n</code></pre>\n\n<blockquote>\n <p>And of course the boost savers don't supply the inserter and extractor\n templates at all. Is this an oversight or is there some argument\n against using the destroy-at-end-of-full-expression semantics this\n way?</p>\n</blockquote>\n\n<p>Probably because the \"destroy-at-end-of-full-expression semantics\" is not very useful — boost savers work with scopes, which allow for more flexible state saving. If you really want the full expression semantics, you can do it like this:</p>\n\n<pre><code>boost::io::ios_flags_saver(std::cout),\nstd::cout << std::hex << 51901 <<'\\n';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T08:42:10.983",
"Id": "238522",
"ParentId": "238487",
"Score": "2"
}
},
{
"body": "<p>One tiny improvement I'd suggest is that the stored state can all be declared <code>const</code>:</p>\n\n<pre><code>const std::ios_base::fmtflags flags;\nconst std::streamsize width;\nconst std::streamsize precision;\nconst charT fill;\n</code></pre>\n\n<p>There are no implications for assignability of <code>fmtstash</code> objects, as we already had a reference member.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:28:10.103",
"Id": "238613",
"ParentId": "238487",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T16:38:18.663",
"Id": "238487",
"Score": "5",
"Tags": [
"c++",
"c++17",
"stream",
"raii"
],
"Title": "Concisely, robustly, temporarily stashing c++ iostream formats"
}
|
238487
|
<p>I have written script that does the following. It uses <code>cbl-log</code> program to decode several log files in binary format. <code>cbl-log</code> only decodes 1 file at a time, so the script decodes files in bulk. If no arguments are given, it assumes log files (with extension .cbllog) are in the current directory, and it'll output files to <code>decoded</code> directory. Otherwise you need to give 2 arguments. The first is the directory with all cbllog files, and the second is the output directory.</p>
<pre><code>#!/usr/bin/env bash
if (( $# == 1 || $# > 2 )); then
echo "Usage: cbldecode"
echo " cbldecode <source directory> <target directory>"
exit 1
fi
cmd="$(command -v {./,}cbl-log | head -n1)"
if [[ -z "$cmd" ]] ; then
echo "cbl-log should be in PATH or current directory"
exit 1
fi
log_dir=${1:-$PWD}
out_dir=${2:-"decoded"}
count=$(find "$log_dir" -maxdepth 1 -name "*.cbllog" | wc -l)
if (( "$count" == 0 )); then
echo "no cbllog files in source directory"
exit 1
fi
if ! [[ -d "$out_dir" ]]; then
mkdir -p "$out_dir"
elif ! [[ -w "$out_dir" ]]; then
echo "no write permission to $out_dir"
exit 1
fi
for path in "$log_dir"/*.cbllog; do
file=${path//$log_dir/}
out_file="${file%.cbllog}"
"$cmd" logcat "$path" "$out_dir"/"$out_file"
done
</code></pre>
<p>While this works, I'm looking for ways to make the code more compact and optimize for speed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T17:22:54.757",
"Id": "467733",
"Score": "0",
"body": "Can you add the specific things you want to be reviewed for this question, such as if you followed general practices and/or if you want to know how to optimize it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T17:41:27.923",
"Id": "467736",
"Score": "0",
"body": "@K00lman looking for ways to make code more compact, and any time optimizations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T20:07:40.670",
"Id": "467750",
"Score": "0",
"body": "Could you add that to the question?"
}
] |
[
{
"body": "<p>Use the <code>-u</code> and <code>-e</code> switches to bash, when possible, because they help to find bugs. Your log decoder may return errors that you want to ignore (making <code>-e</code> unhelpful) but <code>-u</code> is safe here.</p>\n\n<p>Move the <code>echo … exit</code> pattern into a function:</p>\n\n<pre><code>die() { printf \"%s\\n\" \"$@\" >&2; exit 1; }\n</code></pre>\n\n<p>Quotes aren't needed on the left-hand side of <code>[[</code> tests. For \"die unless foo\" assertions, consider writing them in the form <code>foo || die \"test failed\"</code>:</p>\n\n<pre><code>[[ -z $cmd ]] && die \"…\"\n</code></pre>\n\n<p><code>(( $# == 1 || $# > 2 ))</code> is more clearly written in the affirmative, as <code>(( $# == 0 || $# == 2 ))</code></p>\n\n<p>Collect the file list once instead of twice. Use globbing instead of <code>find</code> to get proper handling of filenames with spaces in them. Include contributing variables in error messages. Do a <code>cd</code> first so that you don't need to decompose filenames later. <code>((</code> expressions return false when zero so there's usually no need to explicitly write <code>x == 0</code>:</p>\n\n<pre><code>shopt -s nullglob\npushd \"$log_dir\" || die \"can't chdir to $log_dir\"\ndeclare -a in=( *.cbllog )\npopd || die \"can't return to original working directory\"\n(( ${#in} )) || die \"no cbllog files in $log_dir\"\n…\nfor path in \"${in[@]}\"; do\n</code></pre>\n\n<p>Your command detector has a bug if <code>cbl-log</code> is an alias or function. Use <code>type -P</code> instead. If you truncate using <code>read</code> instead of <code>head</code>, the assignment doubles as an emptyness test:</p>\n\n<pre><code>read cmd < <( type -P {./,}cbl-log ) || die \"cbl-log should be in PATH or current directory\"\n</code></pre>\n\n<p>Your basename implementation has a bug if <code>log_dir</code> contains globbing characters. This is obsoleted by the <code>pushd</code> above but something like <code>file=${path##*/}</code> or <code>file=$( basename \"$path\" )</code> would work.</p>\n\n<p><code>mkdir -p</code> is a no-op when the directory exists; no need to test for that yourself.</p>\n\n<p>You'll need execute permission on <code>$out_dir</code> along with write.</p>\n\n<p>Putting it all together:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code> #!/bin/bash -u \n die() { printf \"%s\\n\" \"$@\" >&2; exit 1; }\n\n (( ${#} == 0 || ${#} == 2 )) || die \"Usage: cbldecode\" \" cbldecode <source directory> <target directory>\"\n log_dir=${1:-$PWD}\n out_dir=${2:-\"decoded\"}\n read cmd < <( type -P {./,}cbl-log ) || die \"cbl-log should be in PATH or current directory\"\n\n pushd \"$log_dir\" || die \"can't chdir to $log_dir\"\n shopt -s nullglob\n declare -a in=( *.cbllog )\n popd || die \"can't return to original working directory\"\n (( ${#in} )) || die \"no cbllog files in $log_dir\"\n\n mkdir -p \"$out_dir\"\n [[ -w $out_dir && -x $out_dir ]] || die \"insufficient permissions on $out_dir\"\n\n for basename in \"${in[@]}\"; do \n \"$cmd\" logcat \"$log_dir/$basename\" \"$out_dir/${basename%.cbllog}\"\n done\n</code></pre>\n\n<p>For faster conversion, add <code>&</code> to the <code>cbl-log</code> invocation, or adapt the script to send basenames to <code>xargs -P</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T00:22:18.277",
"Id": "467768",
"Score": "1",
"body": "Fantastic feedback. I noticed `pushd` displays stack in stdout so added `1>/dev/null` to it. I think we can use `-e` if we add `|| true` to the line that does log decoding, right? Finally I'm using macos so 'type -P` is invalid, unfortunately. Any alternatives?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T01:23:39.580",
"Id": "467770",
"Score": "1",
"body": "Yes `|| true` will satisfy `-e`. Prepend `.` to `$PATH` and invoke the command with a do-nothing switch like `-v` or `-help`. If that fails, throw error. Adding cwd to PATH is not a safe practice in general. It's fine here since the whole script is shell builtins. To make it safer declare a function like `cmd(){ local PATH=.:$PATH; cbl-log \"$@\"; }` so only that one command is affected by the unsafe PATH."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T00:12:10.493",
"Id": "468108",
"Score": "1",
"body": "That worked for me. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T18:22:48.253",
"Id": "238491",
"ParentId": "238488",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238491",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T16:54:52.250",
"Id": "238488",
"Score": "3",
"Tags": [
"bash",
"linux"
],
"Title": "bash script to bulk decode files"
}
|
238488
|
<p>I've ended up with some pretty ugly code while doing some bitmasking:</p>
<pre><code> if (BitmaskIntersection(north, south, west, east)) { } //Logic is executed inside these methods, and return true or false.
else if (BitmaskTCross(north, south, west, east)) { }
else if (BitmaskStraightBend(north, south, west, east)) { }
else if (BitmaskEnd(north, south, west, east)) { }
else
{
meshFilter.mesh = single;
}
ExecuteOnceAnIfReturnsTrue();
}
</code></pre>
<p>As you can see I've ended up with several empty brackets here. The code works since I always bitmask the highest number of neighbors first, but it feels ugly. Can it be improved? How should this be handled?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:47:37.890",
"Id": "467744",
"Score": "3",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231/42632)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:48:16.767",
"Id": "467745",
"Score": "1",
"body": "The site standard is for the title to simply state the task accomplished by the code, not your concers about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>Just put everything in the same if using \"or\"</p>\n\n<pre><code>if (!(BitmaskIntersection(north, south, west, east) || \n BitmaskTCross(north, south, west, east) ||\n BitmaskStraightBend(north, south, west, east) ||\n BitmaskEnd(north, south, west, east))) \n{\n meshFilter.mesh = single;\n}\n</code></pre>\n\n<p>In C#, \"or\" are short-circuited, which means it stops when it reaches the first <code>true</code> statement</p>\n\n<p>or use \"and\":</p>\n\n<pre><code>if (!BitmaskIntersection(north, south, west, east) &&\n !BitmaskTCross(north, south, west, east) &&\n !BitmaskStraightBend(north, south, west, east) &&\n !BitmaskEnd(north, south, west, east)) \n{\n meshFilter.mesh = single;\n}\n</code></pre>\n\n<p>In C#, \"and\" are also short-circuited, which means it stops when it reaches the first <code>false</code> statement</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:28:57.917",
"Id": "238495",
"ParentId": "238494",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238495",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:24:13.347",
"Id": "238494",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "C# - What should I do with empty if-brackets?"
}
|
238494
|
<p>As a basic project, I've programmed the game of noughts and crosses (tic-tac-toe) using classes. I made three classes: <code>Board</code>, <code>Player</code> and <code>LazyRobot</code>, as well as the main game file.</p>
<p>I would like to know any improvements to code or any best practices I have neglected. I know there is some repetition within the code, but I would like to hear your thoughts.</p>
<p><strong>Below is the main game.py file:</strong></p>
<pre><code>from copy import deepcopy
from board import Board, PositionError
from player import Player
from lazyrobot import LazyRobot
def game(player1, player2):
board = Board()
game_winner = None
turn = player1
print('Starting new game.')
print('{} is playing noughts.'.format(player1.getname()))
print('{} is playing crosses.'.format(player2.getname()))
board.display_board()
while len(board.available_positions()) != 0:
if turn == player1:
nought_turn(player1, board)
if board.is_winner() is True:
game_winner = player1
break
else:
turn = player2
else:
cross_turn(player2, board)
if board.is_winner() is True:
game_winner = player2
break
else:
turn = player1
if game_winner is None:
print('Game is tied.')
else:
print('{} has won the game!'.format(game_winner.getname()))
print('End of game.')
def nought_turn(player, board):
print('It is now {}\'s turn. (o)'.format(player.getname()))
while True:
try:
move = player.getmove(deepcopy(board))
board.add_nought(move)
break
except PositionError:
print('Sorry, the space has been taken. '
'Please try another space.')
board.display_board()
def cross_turn(player, board):
print('It is now {}\'s turn. (x)'.format(player.getname()))
while True:
try:
move = player.getmove(deepcopy(board))
board.add_cross(move)
break
except PositionError:
print('Sorry, the space has been taken. '
'Please try another space.')
board.display_board()
</code></pre>
<p><strong>Here is the <code>Board</code> class:</strong></p>
<pre><code>class PositionError(Exception):
pass
class Board(object):
def __init__(self):
self.board = {1: ' ', 2: ' ', 3: ' ', 4: ' ',
5: ' ', 6: ' ', 7: ' ', 8: ' ', 9: ' '}
self.nought_positions = []
self.cross_positions = []
def display_board(self):
line_1 = ' {} | {} | {} '.format(self.board[1],
self.board[2], self.board[3])
line_2 = ' {} | {} | {} '.format(self.board[4],
self.board[5], self.board[6])
line_3 = ' {} | {} | {} '.format(self.board[7],
self.board[8], self.board[9])
print(line_1)
print('-----------')
print(line_2)
print('-----------')
print(line_3)
def add_nought(self, position):
if self.board[position] == ' ':
self.board[position] = 'o'
self.nought_positions.append(position)
else:
raise PositionError('Space is occupied.')
def add_cross(self, position):
if self.board[position] == ' ':
self.board[position] = 'x'
self.cross_positions.append(position)
else:
raise PositionError('Space is occupied.')
def is_winner(self):
winning_positions = [{1,2,3}, {4,5,6},
{7,8,9}, {1,4,7},
{2,5,8}, {3,6,9},
{1,5,9}, {3,5,7}]
nought_set = set(self.nought_positions)
cross_set = set(self.cross_positions)
for position in winning_positions:
if nought_set & position == position:
return True
elif cross_set & position == position:
return True
return False
def available_positions(self):
nought_set = set(self.nought_positions)
cross_set = set(self.cross_positions)
all_positions = {1,2,3,4,5,6,7,8,9}
available_positions = (all_positions - nought_set) - cross_set
return list(available_positions)
</code></pre>
<p><strong>Here is the <code>Player</code> class:</strong></p>
<pre><code>class PositionError(Exception):
pass
class NumberError(Exception):
pass
class Player(object):
def __init__(self, name):
self.name = name
def getname(self):
return self.name
def getmove(self, board):
available_positions = board.available_positions()
print('{}, make your next move.'.format(self.getname()))
while True:
try:
move = int(input('Number: '))
if move > 9 or move < 1:
raise NumberError
if move not in available_positions:
raise PositionError
return move
except ValueError:
print('Sorry, please type a number.')
except NumberError:
print('Sorry, please type a number between 1 and 9.')
except PositionError:
print('Sorry, the space has been taken. '
'Please try another space.')
</code></pre>
<p><strong>And here is the <code>LazyRobot</code> class:</strong> (I'm not too worried about this, as I will make a robot with better strategy.)</p>
<pre><code>from random import randint
class LazyRobot(object):
def __init__(self, name):
self.name = name
def getname(self):
return self.name
def getmove(self, board):
available_positions = board.available_positions()
index = randint(0, len(available_positions)-1)
return available_positions[index]
</code></pre>
|
[] |
[
{
"body": "<h1>PEP 8</h1>\n<p>Overall, your code is very clean. However, there are a few minor <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> deviations:</p>\n<ol>\n<li><p><code>.getname()</code> should be <code>.get_name()</code>, as it is two words.</p>\n</li>\n<li><p>In several places, where a statement continues over multiple lines, the indentation is not PEP-8 compliant, such as:</p>\n<pre><code> self.board = {1: ' ', 2: ' ', 3: ' ', 4: ' ',\n 5: ' ', 6: ' ', 7: ' ', 8: ' ', 9: ' '}\n</code></pre>\n</li>\n</ol>\n<p>should be:</p>\n<pre><code> self.board = {1: ' ', 2: ' ', 3: ' ', 4: ' ',\n 5: ' ', 6: ' ', 7: ' ', 8: ' ', 9: ' '}\n</code></pre>\n<p>(But perhaps this was an artifact of copying the code to the Code Review site.)</p>\n<ol start=\"3\">\n<li><p>Commas should be followed by one space. Eg)</p>\n<pre><code> all_positions = {1,2,3,4,5,6,7,8,9}\n</code></pre>\n<p>should be:</p>\n<pre><code> all_positions = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n</code></pre>\n</li>\n<li><p>Raise Objects not Classes</p>\n<pre><code> raise PositionError\n</code></pre>\n<p>should be:</p>\n<pre><code> raise PositionError()\n</code></pre>\n<p>or:</p>\n<pre><code> raise PositionError("Your message here")\n</code></pre>\n</li>\n</ol>\n<h1>Classes</h1>\n<p>Deriving from <code>object</code> is implicit:</p>\n<pre><code>class Board(object):\n ...\n</code></pre>\n<p>should simply be written as:</p>\n<pre><code>class Board:\n ...\n</code></pre>\n<h1>Imports</h1>\n<p>Both <code>board.py</code> and <code>player.py</code> define the class:</p>\n<pre><code>class PositionError(Exception):\n pass\n</code></pre>\n<p><code>player.py</code> should simply import <code>PositionError</code> from <code>board</code>, like was done in <code>game.py</code>:</p>\n<pre><code>from board import Board, PositionError\n</code></pre>\n<h1>f-strings</h1>\n<p>Beginning with Python 3.6, formatting strings has become easier. Instead of separating the format code and the format argument be a large distance, like <code>"...{}...{}...{}".format(a, b, c)"</code>, f-strings allow you to embed the argument inside the format code: <code>f"...{a}...{b}...{c}"</code>. Note the leading <code>f</code> in <code>f"..."</code>.</p>\n<p>So this code:</p>\n<pre><code> print('{} is playing noughts.'.format(player1.getname()))\n</code></pre>\n<p>can be rewritten like this:</p>\n<pre><code> print(f'{player1.getname()} is playing noughts.')\n</code></pre>\n<p>(Note: I'll be revisiting this below, and make it even cleaner.)</p>\n<h1>Code Duplication</h1>\n<p><code>game()</code> has virtually identical code in both branches of the <code>if ... else</code> inside the <code>while</code> loop. The largest difference is one branch calls <code>nought_turn()</code> while the other calls <code>cross_turn()</code>.</p>\n<p><code>nought_turn()</code> and <code>cross_turn()</code> also have virtually identical code. The first difference is one displays a nought <code>(o)</code> while the other displays a cross <code>(x)</code>. The second being the former calls <code>.add_nought()</code> and the latter calls <code>.add_cross()</code>.</p>\n<p><code>add_nought()</code> and <code>add_cross()</code> also have virtually identical code. The first difference being one stores '<code>o</code>' in <code>self.board</code> while the other stores <code>'x'</code>. The second difference being the position is added to either <code>self.nought_positions</code> or <code>self.cross_positions</code>.</p>\n<p>The code above is the same, only the data (the symbol) is different. Let's pass the symbol down. Instead of <code>nought_turn(player1, board)</code>, we could use <code>player_turn(player1, board, 'o')</code> and instead of <code>cross_turn(player2, board)</code>, we could use <code>player_turn(player2, board, 'x')</code>. <code>player_turn()</code> might look like this:</p>\n<pre><code>def player_turn(player, board, symbol):\n print(f"It is now {player.getname()}'s turn. ({symbol})")\n \n while True:\n try:\n move = player.getmove(deepcopy(board))\n board.add_symbol(move, symbol)\n break\n except PositionError:\n print('Sorry, the space has been taken. '\n 'Please try another space.')\n \n board.display_board()\n</code></pre>\n<p>Tiny changes. We've added <code>{symbol}</code> to the print statement, and changed <code>.add_nought(...)</code> and <code>.add_cross(...)</code> to <code>.add_symbol(..., symbol)</code>. But a big change; we've removed an entire duplicate code function.</p>\n<p><code>add_symbol()</code> would replace <code>add_nought()</code> and <code>add_cross()</code>:</p>\n<pre><code> def add_symbol(self, position, symbol):\n if self.board[position] == ' ':\n self.board[position] = symbol\n if symbol == 'o':\n self.nought_positions.append(position)\n else:\n self.cross_positions.append(position)\n else:\n raise PositionError('Space is occupied.')\n</code></pre>\n<p>We've had to add an <code>if ... else</code> in the <code>add_symbol()</code> to append the position to the correct positions list, but again we've removed an entire extra duplicate code function, so that's a win.</p>\n<p>Let's look at that revised main loop again:</p>\n<pre><code> turn = player1\n while len(board.available_positions()) != 0:\n if turn == player1:\n player_turn(player1, board, 'o')\n if board.is_winner() is True:\n game_winner = player1\n break\n else:\n turn = player2\n\n else:\n player_turn(player2, board, 'x')\n if board.is_winner() is True:\n game_winner = player2\n break\n else:\n turn = player1\n</code></pre>\n<p>We're passing <code>player1</code> or <code>player2</code> into the <code>player_turn()</code> function. But <code>turn</code> is the current player, so we could just pass in <code>turn</code>. Or better: rename the variable to <code>player</code>! Ditto for <code>game_winner = ...</code>. Then we just need to determine the correct symbol for the current player.</p>\n<pre><code> player = player1\n while len(board.available_positions()) != 0:\n symbol = 'o' if player == player1 else 'x'\n\n player_turn(player, board, symbol)\n if board.is_winner() is True:\n game_winner = player\n break\n\n player = player2 if player == player1 else player1\n</code></pre>\n<h1>nought & cross positions</h1>\n<p>What are these?</p>\n<pre><code> self.nought_positions = []\n self.cross_positions = []\n</code></pre>\n<p>You <code>.append(position)</code> to them when moves are successfully made. But they are only ever used in:</p>\n<pre><code> nought_set = set(self.nought_positions)\n cross_set = set(self.cross_positions)\n</code></pre>\n<p>and <code>nought_set</code> and <code>cross_set</code> are never modified or destroyed.</p>\n<p>So you are maintaining a <code>list</code> and generating the corresponding <code>set</code> when used. Why not just maintain sets from the get-go?</p>\n<pre><code> self.nought_set = set()\n self.cross_set = set()\n</code></pre>\n<p>and use <code>.add(position)</code> to add <code>position</code> to the set when a move is successfully made.</p>\n<h1>Available positions</h1>\n<p>You are doing too much work with <code>all_positions</code>:</p>\n<pre><code> all_positions = {1,2,3,4,5,6,7,8,9}\n</code></pre>\n<p>The keys of <code>self.board</code> are all of the positions. So the above statement can be replaced with simply:</p>\n<pre><code> all_positions = set(self.board)\n</code></pre>\n<p>If you changed the keys to be 0 through 8, or 'A' through 'I', using <code>set(self.board)</code> would automatically construct the correct set; you wouldn't need to change the hard-coded <code>{1,2,3,4,5,6,7,8,9}</code> set to the correct values, so is a win for program maintenance.</p>\n<p>But wait. From <code>all_positions</code>, you subtract <code>nought_set</code> and <code>cross_set</code>. This leaves all the <code>self.board</code> positions which still have the value <code>" "</code>. There is an easier way:</p>\n<pre><code> def available_positions(self):\n return [position for position, value in self.board.items() if value == " "]\n</code></pre>\n<p>No need for the <code>nought_set</code> or <code>cross_set</code> here!</p>\n<h1>Is Winner</h1>\n<p>Each call, you are checking if noughts has won or crosses has won. This is double the required work. Nought can only win on nought's turn, and cross can only win on cross's turn.</p>\n<p>If you pass in the <code>symbol</code> that just played, you could eliminate half of the checks:</p>\n<pre><code> def is_winner(self, symbol):\n winning_positions = [{1,2,3}, {4,5,6},\n {7,8,9}, {1,4,7},\n {2,5,8}, {3,6,9},\n {1,5,9}, {3,5,7}]\n\n if symbol == 'o':\n player_set = set(self.nought_positions)\n else:\n player_set = set(self.cross_positions)\n\n for position in winning_positions:\n if player_set & position == position:\n return True\n\n return False\n</code></pre>\n<p><code>player_set & position == position</code> takes two sets, constructs a new set which is the intersection of the two sets, and compares the result with the second set. This is, effectively, an "is <code>position</code> a subset of <code>player_set</code>" test. And <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=issubset#frozenset.issubset\" rel=\"nofollow noreferrer\"><code>.issubset(other)</code></a> is built-in to Python:</p>\n<pre><code> for position in winning_positions:\n if position.issubset(player_set):\n return True\n\n return False\n</code></pre>\n<p>The <code>position.issubset(player_set)</code> test can also be written as <code>position <= player_set</code>.</p>\n<p>Looping over a collection of items and testing if a condition is <code>True</code> for any of the items is an <a href=\"https://docs.python.org/3/library/functions.html?highlight=any#any\" rel=\"nofollow noreferrer\"><code>any()</code></a> test ... also built into Python:</p>\n<pre><code> return any(position <= player_set for position in winning_positions)\n</code></pre>\n<p>But do we really need the <code>nought</code>/<code>cross</code> <code>_positions</code>/<code>_set</code>? We got rid of them in <code>available_positions()</code>.</p>\n<p>We want any <code>winning_positions</code> where all positions have the current players <code>symbol</code>. If we move <code>winning_positions</code> out of the function and made it a global constant:</p>\n<pre><code>WINNING_POSITIONS = ((1, 2, 3), (4, 5, 6), (7, 8, 9),\n (1, 4, 7), (2, 5, 8), (3, 6, 9),\n (1, 5, 9), (3, 5, 7))\n</code></pre>\n<p>Then,</p>\n<pre><code> def is_winner(self, symbol):\n\n return any(all(self.board[cell] == symbol for cell in position)\n for position in WINNING_POSITIONS)\n</code></pre>\n<p>Now, there is no more references to <code>nought_positions</code> or <code>cross_set</code>. Those can be removed globally!</p>\n<h1>Private members</h1>\n<p>In the <code>Board</code> class, <code>self.board</code> is a private member; no external class should manipulate it. In Python, there are no private/public access modifiers which will enforce a member being private. But there are conventions.</p>\n<p>Members with a leading underscore are - by convention - private. Many IDE's will omit those identifiers when providing auto-complete hints. Additionally <code>from some_module import *</code> will not import any items beginning with an underscore, so it is a bit more than convention.</p>\n<p>So:</p>\n<ul>\n<li><code>self.board</code> should be changed to <code>self._board</code></li>\n<li><code>self.name</code> should be changed to <code>self._name</code></li>\n</ul>\n<p>When they existed:</p>\n<ul>\n<li><code>self.nought_positions</code> should have been <code>self._nought_positions</code></li>\n<li><code>self.cross_positions</code> should have been <code>self._cross_positions</code></li>\n</ul>\n<h1>Properties</h1>\n<p>In <code>Player</code>, the method <code>getname()</code> exists because <code>player.name</code> is supposed to be a private member, not accessed directly. You wouldn't want external code to accidentally, or maliciously change a player's name:</p>\n<pre><code>if game_winner != player1:\n player1.name = "The loser"\n</code></pre>\n<p>But <code>player1.name</code> is so convenient to use. It is the player's name. What could be simpler than typing <code>player1.name</code>?</p>\n<p>We can do that. Safely.</p>\n<pre><code>class Player:\n\n def __init__(self, name):\n self._name = name\n\n @property\n def name(self):\n return self._name\n</code></pre>\n<p>Now we can access a <code>Player</code> objects <code>.name</code> property safely, and simply. We can fetch the value, but we can't change it:</p>\n<pre class=\"lang-none prettyprint-override\"><code>>>> p = Player("Fred")\n>>> p.name\n'Fred'\n>>> p.name = "Bob"\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nAttributeError: can't set attribute\n>>> \n</code></pre>\n<p>Which leads to even clearer print format statement I hinted about earlier:</p>\n<pre><code> print(f'{player1.name} is playing noughts.')\n</code></pre>\n<h1>Deep Copy</h1>\n<pre><code> move = player.getmove(deepcopy(board))\n</code></pre>\n<p>Neither <code>Player</code> nor <code>LazyRobot</code> modify <code>board</code> during <code>getmove(board)</code>. Why the deep copy?</p>\n<p>If it is when you make a better robot player, perhaps the robot player should do the deep copy? Or add a <code>board.copy()</code> method which can return a duplicate <code>Board</code> for the player to scribble on while they try to determine the optimal move.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:10:56.627",
"Id": "467841",
"Score": "0",
"body": "Would I then need to declare `WINNING_POSITIONS` as a global variable within the `Board` class: `global WINNING_POSITIONS`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:42:15.007",
"Id": "467845",
"Score": "0",
"body": "Also, I'm worried that if the robot was passed `board` through `getmove(board)`, it might hack the board to a winning position. My `LazyRobot` uses `board.available_positions()`, so I think I would need to pass a copy of the board with all of its methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T00:04:47.547",
"Id": "467846",
"Score": "1",
"body": "You do not need to use the `global` keyword. Because you have a `board.py` file, it is fine to have “board specific” constants declared at file level; they are encapsulated in the `board.py` module scope. If you want to declare it within the `class Board` scope, that is fine too. You would refer to it as either `Board.WINNING_POSITIONS` or `self.WINNING_POSITIONS` inside `Board.is_winner(self)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T00:16:38.960",
"Id": "467847",
"Score": "1",
"body": "I would add to `class Board` the method `def copy(self): return deepcopy(self)`, and then use `move = player.get_move(board.copy())`. This is cleaner & will allow you to change `copy()` in the future if desired. I wouldn’t be worried that a `Robot` could hack the board. This is Python; the `Robot` can do anything, including changing `WINNING_POSITIONS` to `((2,4,9),)`. Or intercept `sys.stdout` and change the game’s output text! Or redefine the game.py’s `player_turn()` method, to give the Robot two or more turns in a row! But passing a copy to prevent accidental scribbles is reasonable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T18:40:04.073",
"Id": "238538",
"ParentId": "238496",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "238538",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:35:51.973",
"Id": "238496",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"tic-tac-toe"
],
"Title": "A Python based Tic-Tac-Toe game"
}
|
238496
|
<p>The objective of the game is to guess the hue, saturation, and lightness values of a given color swatch across ten rounds.</p>
<ul>
<li><a href="https://github.com/shreyasminocha/guess-the-hsl" rel="nofollow noreferrer">https://github.com/shreyasminocha/guess-the-hsl</a></li>
<li><a href="https://guess-the-hsl.now.sh" rel="nofollow noreferrer">https://guess-the-hsl.now.sh</a></li>
</ul>
<p>This being my first svelte project, I'd like some insight into best practices, especially svelte-specific ones.</p>
<h2>Versions</h2>
<ul>
<li><code>svelte</code>: <code>^3.0.0</code></li>
</ul>
<h2>Specific questions</h2>
<ol>
<li>Are my choices of abstraction adequate? Are there things that should or shouldn't be components of their own?</li>
<li>In <code>src/components/swatch.svelte</code>, is it okay to style just <code>div</code> (as opposed to adding a class <code>.swatch</code> to the div and styling that), given that svelte scopes styles to the file?</li>
<li>In <code>src/components/results.svelte</code>, I'm a bit concerned about how complicated the score calculation line looks. Is there a way to clean that up a little bit? To my best knowledge I can't assign variables in svelte's template syntax.</li>
<li>Is it standard/acceptable to use an array of length <code>3</code> to represent an HSL colour or should I switch to an object with three keys, say <code>h</code>, <code>s</code>, and <code>l</code>?</li>
<li>I was considering using a <code>@svelte/store</code> to store the solution and input history, but eventually decided against it because I thought it was overkill for this. When would one use <code>@svelte/store</code>?</li>
</ol>
<p>I'm using prettier for linting, so please avoid feedback on code formatting.</p>
<p>Any other feedback is also welcome.</p>
<h2>File structure</h2>
<pre><code>.
├── package-lock.json
├── package.json
├── public
│ ├── build
│ │ └── …
│ ├── favicon.png
│ ├── global.css
│ └── index.html
├── readme.md
├── rollup.config.js
└── src
├── app.svelte
├── components
│ ├── results.svelte
│ ├── slider.svelte
│ └── swatch.svelte
└── main.js
</code></pre>
<h2>Code</h2>
<p>I have replaced the contents of <code><style></code> tags with <code>…</code> for brevity.</p>
<h3><code>src/main.js</code></h3>
<pre class="lang-js prettyprint-override"><code>import App from "./app.svelte";
const app = new App({
target: document.body,
props: {}
});
export default app;
</code></pre>
<h3><code>src/app.svelte</code></h3>
<pre><code><script>
import Swatch from "./components/swatch.svelte";
import Slider from "./components/slider.svelte";
import Results from "./components/results.svelte";
import random from "random-int";
import "../node_modules/milligram/dist/milligram.min.css";
let solution = randomColor();
let input = [0, 0, 0];
let history = [];
const totalRounds = 10;
let round = 1;
function save() {
const solutionCopy = [...solution];
const inputCopy = [...input];
history.push({
solution: solutionCopy,
input: inputCopy
});
round++;
solution = randomColor();
}
function randomColor() {
return [random(0, 255), random(0, 100), random(0, 100)];
}
</script>
<style>
…
</style>
<h1>Guess the HSL</h1>
{#if round <= totalRounds}
<label for="progress">Round {round} / {totalRounds}</label>
<progress id="progress" value={round} max={totalRounds} />
<div class="main">
<Swatch color={solution} inline={false} />
<Slider name="Hue" bind:value={input[0]} range={[0, 360]} step={1} />
<Slider
name="Saturation"
bind:value={input[1]}
range={[0, 100]}
step={1} />
<Slider
name="Lightness"
bind:value={input[2]}
range={[0, 100]}
step={1} />
</div>
<input type="submit" on:click={save} value="Submit" />
{:else}
<Results {history} />
{/if}
</code></pre>
<h3><code>src/components/swatch.svelte</code></h3>
<pre><code><script>
export let width = 50;
export let color = [0, 0, 0];
export let inline = true;
</script>
<style>
…
</style>
<div
style=" width: {width}px; height: {width}px; background: hsl({color[0]}, {color[1]}%,
{color[2]}%);"
class={inline ? '' : 'display'} />
</code></pre>
<h3><code>src/components/slider.svelte</code></h3>
<pre><code><script>
export let name;
export let value;
export let range = [0, 100];
export let step = 1;
</script>
<style>
…
</style>
<fieldset>
<legend>{name}</legend>
<input
type="range"
{name}
bind:value
min={range[0]}
max={range[1]}
{step} />
<input
type="number"
name="hue"
bind:value
min={range[0]}
max={range[1]}
{step} />
</fieldset>
</code></pre>
<h3><code>src/components/results.svelte</code></h3>
<pre><code><script>
import Swatch from "./swatch.svelte";
import round from "round-to";
import convert from "color-convert";
import { differenceCiede2000 as ciede2000 } from "d3-color-difference";
export let history = [];
</script>
<style>
…
</style>
<table>
<thead>
<th>Solution</th>
<th>Input</th>
<th>Score</th>
</thead>
{#each history as { solution, input }}
<tr>
<td>
<Swatch color={solution} width="25" />
<code>hsl({solution[0]}, {solution[1]}%, {solution[2]}%)</code>
</td>
<td>
<Swatch color={input} width="25" />
<code>hsl({input[0]}, {input[1]}%, {input[2]}%)</code>
</td>
<td>
{round(100 - ciede2000(`#${convert.hsl.hex(solution)}`, `#${convert.hsl.hex(input)}`), 2)}
</td>
</tr>
{/each}
</table>
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T19:48:20.850",
"Id": "238497",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"game",
"node.js"
],
"Title": "HSL Guessing Game in Svelte"
}
|
238497
|
<p>I'm using this right now to count the number of discrete values in a given <code>[]string</code>. Is there a faster way to do this?</p>
<pre class="lang-golang prettyprint-override"><code>func CountDiscrete(x []string) int {
discrete := 0
for i,xi := range x {
is_discrete := true
for j,xj := range x {
if i != j {
if xi == xj {
is_discrete = false
break
}
}
}
if is_discrete {
discrete = discrete + 1
}
}
return discrete
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T20:50:57.500",
"Id": "467754",
"Score": "2",
"body": "If you're downvoting the question can you please leave a comment explaining why so that I can make any necessary changes or remove the question if it is not within the guidelines of this forum"
}
] |
[
{
"body": "<p>Code review:<br>\n1. Use <code>discrete++</code> instead of <code>discrete = discrete + 1</code><br>\n2. Use <code>if i != j && xi == xj</code> instead of </p>\n\n<pre><code>if i != j {\n if xi == xj {\n is_discrete = false\n break\n }\n}\n</code></pre>\n\n<ol start=\"3\">\n<li><p>Don't use underscores in Go names: <code>is_discrete</code>, simply use <code>discrete</code> or <code>isDiscrete</code>.</p></li>\n<li><p>You may use <code>slice ...string</code> instead of <code>slice []string</code> like the following code:</p></li>\n</ol>\n\n<pre><code>// O(n**2)\nfunc distincts(x ...string) int {\n result := 0\n for i, xi := range x {\n unique := 1\n for j, xj := range x {\n if i != j && xi == xj {\n unique = 0\n break\n }\n }\n result += unique\n }\n return result\n}\n</code></pre>\n\n<p>Also note the <code>result += unique</code> instead of <code>if ...</code>.</p>\n\n<ol start=\"5\">\n<li>Using map, the following code has the time complexity (asymptotic notation): <code>O(n)</code></li>\n</ol>\n\n<pre><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n r := distincts(\"a\", \"b\", \"c\", \"a\")\n fmt.Println(r) // 2\n\n}\n\n// O(n)\nfunc distincts(slice ...string) int {\n result := 0\n m := map[string]int{}\n for _, str := range slice {\n m[str]++\n }\n for _, v := range m {\n if v == 1 {\n result++\n }\n }\n return result\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T20:34:47.097",
"Id": "238501",
"ParentId": "238498",
"Score": "2"
}
},
{
"body": "<p>You're currently iterating over the slice each once, and then again for each value. That's understandable, but not ideal. Why not simply sort the data, and then check whether or not the next value is the same as the current one?</p>\n\n<pre><code>func distinct(values []string) int {\n if len(values) == 0 {\n return 0\n }\n // the loop doesn't count the last value\n // add if the slice isn't empty\n distinct := 1\n // sort the values\n sort.Strings(values)\n // stop iterating at the next to last element\n for i := 0; i < len(values)-1; i++ {\n // if the current value is distinct from the next, this is a unique word\n if values[i] != values[i+1] {\n distinct++\n }\n }\n return distinct\n}\n</code></pre>\n\n<p>Other, more general comments on your code:</p>\n\n<ul>\n<li>Variables like <code>is_discrete</code> is not in line with golang's coding conventions. Golang prefers <code>camelCased</code> variable names. <code>isDiscrete</code>.</li>\n<li>Your nested <code>if</code> checking <code>i != j</code> and then <code>xi == xj</code> can, and should be combined: <code>if i != j && xi == xj</code></li>\n<li>Personally, I'd probably use the indexes, and just use <code>for i := range x</code> and <code>for j := range x</code>.</li>\n<li><p>Although it doesn't make the code perform any better, it does get rid of that rather clunky looking <code>if isDiscrete</code>, you could use either one of the following snippets:</p>\n\n<p>for i := range x {\n inc := 1\n for j := range x {\n for i != j && x[i] == x[j] {\n inc = 0\n break\n }\n }\n discrete += inc\n}</p></li>\n</ul>\n\n<p>You could also increment <code>discrete</code> beforehand, and just replace <code>inc = 0</code> with <code>discrete--</code> in the inner loop.</p>\n\n<hr>\n\n<p>While we're on the subjects of other approaches, while not efficient, it is a very easy approach:</p>\n\n<pre><code>func Discrete(vals []string) int {\n unique := map[string]struct{}{}\n for i := range vals {\n unique[vals[i]] = struct{}{}\n }\n return len(unique)\n}\n</code></pre>\n\n<p>In this code, any duplicate string value is just reassigning the same key in the map. At the end, getting the length of the map will give you the total of unique string values. Maps cause memory allocations, so it's not the most efficient way, but it's a solid way to test your code. You can pass some data to your function, and use a map to calculate what the return for any given slice of strings should be. </p>\n\n<hr>\n\n<p>Last thoughts on efficiency: the golang toolchain packs a couple of really handy tools that will help you determine which approach is more efficient (writing benchmarks). If memory consumption is a worry, you can use <code>pprof</code>. Not just to determine how much memory any given piece of code uses, but also which part of the code is the most likely bottleneck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T13:48:14.060",
"Id": "468571",
"Score": "0",
"body": "\"Why not simply sort the data?\" Because sorting is O(n log n). While O(n log n) is better than O(n*n), we want O(n). See [Wikipedia: Big O notation](https://en.wikipedia.org/wiki/Big_O_notation). See texts on algorithms, for example, Sedgewick, CLRS, Knuth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-16T10:46:24.993",
"Id": "468687",
"Score": "0",
"body": "@peterSO: Compared to the OP's implementation (which is `O(n*n)`, and requires manually writing more code), simply using `sort` is easier, and requires less code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T02:28:19.673",
"Id": "238864",
"ParentId": "238498",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T20:01:01.260",
"Id": "238498",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"go"
],
"Title": "Count the number of discrete values in a slice"
}
|
238498
|
<p>This is a revision of a previous question that I asked (i.e. <a href="https://codereview.stackexchange.com/questions/237357/check-browser-compatibility-for-requestanimationframe-and-vanilla-javascript-an">Check browser compatibility for RequestAnimationFrame and Vanilla JavaScript .animate() API</a>), with new aspects that I have learnt in Javascript. It is I think better than the previous implementation as it is using <code>switch</code> statement's which will only run if certain conditions are met, which means a performance gain I guess. Can anyone spot any issues with what I have so far? A link to the original Question is posted at the bottom of this one for reference. </p>
<pre><code> const LoadScreen = document.getElementById("Temp");
const LoadRing = document.querySelector(".loader");
setTimeout(() => {
LoadScreen.style.display = "none";
LoadRing.style.display = 'none';
}, 875);
let webAnimSupport = (window.Element.prototype.animate !== undefined);
let rafSupport = (window.requestAnimationFrame !== undefined);
let cssFallback = false;
function animeFallBack(){
switch(rafSupport ? true : false){
case true:
console.log('.raf(); Support = true');
runRAFAnime();
// .animate Not Supported Fallback to `request animation frame`.
// Add Callback or Promises in here which holds RAF Anime Code.
// Put the RAF Code in an External File to reduce the size of this one.
// When Learnt more move the Animations into there Own WebWorker...
break;
case false:
console.log('.raf(); Support = false');
let requestAnimationFrame = (
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60)
}
);
// Fallback option or alert enable Js
// Wrap this in a Try Catch Block & fallBack to Css Anime.
break;
default: // Default to Css Fallback.
var AnimeStyle = document.createElement("link"); // Default Classes to be added back in.
AnimeStyle.setAttribute("rel", "stylesheet");
AnimeStyle.setAttribute("type", "text/css");
AnimeStyle.setAttribute("href", "FallBack.css");
document.getElementsByTagName("head")[7].appendChild(AnimeStyle);
return false;
}
}
switch(webAnimSupport ? true : false){
case true:
console.log('.animate(); Support = true');
RunAnimeApi();
// Run .animate() functions as normal via Callbacks or Promises.
break; // break; 4 WebAnimSupport = True;
case false:
console.log('.animate(); Support = false');
animeFallBack();
// Move onto requestAnimationFrame();
break; // break; 4 WebAnimSupport = False;
default:
return false;
// Default to Css Fallback. ie ``Add Back in the Classes`` That governed the original Animation.
}
</code></pre>
<p>Ideally I would like to include promises within this block but these are something I'm still struggling to wrap my head around. Can anybody spot any mistakes, performance gains or security issues with this current implementation?</p>
<p>Related Articles:<br>
<a href="https://gist.github.com/paulirish/1579671" rel="nofollow noreferrer">paul irish polyfill</a><br>
<a href="https://github.com/web-animations/web-animations-js" rel="nofollow noreferrer">.animate polyfill();</a><br>
<a href="https://www.npmjs.com/package/request-animation-frame-polyfill" rel="nofollow noreferrer">requestAnimationFrame(); polyfill</a><br>
<a href="https://stackoverflow.com/questions/9493954/game-loop-crashing-my-browser">Game Loop Crashing my Browser</a><br>
<a href="https://stackoverflow.com/questions/34607703/does-this-requestanimationframe-polyfill-produce-a-timestamp-aswell">requestAnimationFrame polyfill produce a timestamp aswell</a><br>
<a href="https://stackoverflow.com/questions/43604058/requestanimationframe-polyfill-error-in-jest-tests">requestAnimationFrame polyfill error in jest tests</a><br>
<a href="https://stackoverflow.com/questions/52508261/do-we-need-to-clear-a-timeout-when-using-requestanimationframe-polyfill">Do we need to clear a timeout when using requestAnimationFrame polyfill</a><br>
<a href="https://stackoverflow.com/questions/32134775/requestanimationframe-polyfill-argument">requestAnimationFrame polyfill argument</a><br>
Maybe Related:<br>
<a href="https://codereview.stackexchange.com/questions/203545/check-if-two-elements-exist-in-array-with-older-browser-support">Check if two elements exist in an array with older browser support</a><br>
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/animate" rel="nofollow noreferrer">mozilla.org/en-US/docs/Web/API/Element/animate</a><br>
<a href="https://www.devbridge.com/articles/waapi-better-api-web-animations" rel="nofollow noreferrer">Waapi better api web animations</a><br>
Kind of related:<br>
<a href="https://stackoverflow.com/questions/26732765/what-is-the-best-polyfill-for-requestanimationframe-out-there">What is the best polyfill for requestanimationframe out there</a><br>
<a href="https://www.jsdelivr.com/package/npm/request-animation-frame-polyfill" rel="nofollow noreferrer">Npm request-animation-frame-polyfill</a><br>
<a href="https://www.emberobserver.com/addons/ember-cli-requestanimationframe-polyfill" rel="nofollow noreferrer">Ember Cli requestAnimationFrame Polyfill</a> </p>
<p>Test Browser Support in Older Broswers:<br>
<a href="http://browsershots.org" rel="nofollow noreferrer">browsershots.org</a><br>
<a href="https://www.browserling.com" rel="nofollow noreferrer">browserling.com</a><br>
<a href="https://www.sitepoint.com/cross-browser-testing-tools" rel="nofollow noreferrer">sitepoint.com/cross-browser-testing-tools</a></p>
<p>Will Update soon.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T06:40:37.987",
"Id": "468122",
"Score": "0",
"body": "You put a bounty on your question, but the end of the question still states \"Will Update soon\". Please note that modifying the question after answers come in can be problematic. Doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T10:37:05.173",
"Id": "468139",
"Score": "0",
"body": "@Mast ok, thanks if i find a more optimal solution I will repost it as a new question & link to it here.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T10:38:14.110",
"Id": "468140",
"Score": "0",
"body": "@Mast, oh actually. only ment that I'd update the links section if and when i find more resources on the subject.."
}
] |
[
{
"body": "<p>Like I mentioned in <a href=\"https://codereview.stackexchange.com/a/238606/120114\">my answer to your post <em>Check browser compatibility for RequestAnimationFrame and Vanilla JavaScript .animate() API</em></a>, many <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like arrow functions and the <code>let</code> and <code>const</code> keywords are used, which <strong>cause errors</strong> in some browsers the code aims to target - e.g. IE 10 and older. So instead of an arrow function in the callback to <code>setTimeout()</code> use a regular <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function\" rel=\"nofollow noreferrer\">function expression</a> or the name of a function declared with a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\" rel=\"nofollow noreferrer\">function declaration</a>, and instead of the <code>const</code> and <code>let</code> keywords, use <code>var</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>const LoadRing = document.querySelector(\".loader\");\n</code></pre>\n</blockquote>\n\n<p>Is there only one element with that class name? If so, it would likely be more appropriate to use an <em>id</em> selector instead of a class name to select it. </p>\n\n<hr>\n\n<blockquote>\n<pre><code>switch(rafSupport ? true : false){\n</code></pre>\n</blockquote>\n\n<p><code>rafSupport</code> is a boolean (see snippet below for proof) and thus there is no need to use the ternary expression here</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let rafSupport = (window.requestAnimationFrame !== undefined);\nconsole.log('typeof rafSupport: ',typeof rafSupport )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The whole <code>switch</code> statement seems like <strong>overkill for a boolean condition</strong> - most developers would stick to <code>if</code>/<code>else</code> statements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>default: // Default to Css Fallback.\n var AnimeStyle = document.createElement(\"link\"); // Default Classes to be added back in.\n AnimeStyle.setAttribute(\"rel\", \"stylesheet\");\n AnimeStyle.setAttribute(\"type\", \"text/css\");\n AnimeStyle.setAttribute(\"href\", \"FallBack.css\");\n document.getElementsByTagName(\"head\")[7].appendChild(AnimeStyle);\n return false;\n</code></pre>\n</blockquote>\n\n<p>This section of the <code>switch</code> statement <strong>is unreachable</strong> because:</p>\n\n<ul>\n<li>the previous cases are <code>true</code> and <code>false</code>, and</li>\n<li>the previous cases both contain <code>break</code> at the end</li>\n</ul>\n\n<p>And are there really 8+ elements with the tag name <code>head</code>??</p>\n\n<hr>\n\n<blockquote>\n<pre><code>default:\n return false;\n // Default to Css Fallback. ie ``Add Back in the Classes`` That governed the original Animation.\n</code></pre>\n</blockquote>\n\n<p>This leads to an error:</p>\n\n<blockquote>\n <p>'return' statement outside of function</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:42:38.897",
"Id": "468083",
"Score": "0",
"body": "Yes the arrow functions maybe an issue. not sure how to fix this yet. will research or just remove them.. No, i didn't notice that head issue i ment to input the css after the 8th meta/link tag ie after charset, title etc. will look into fixing this aswell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:45:29.520",
"Id": "468084",
"Score": "0",
"body": "would if(!rafSupport){...code} be more optimal.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T17:39:01.737",
"Id": "238683",
"ParentId": "238500",
"Score": "4"
}
},
{
"body": "<p>Sᴀᴍ Onᴇᴌᴀ has <a href=\"https://codereview.stackexchange.com/a/238683\">already pointed out</a> several major issues in your code. Besides those, your code also includes unused variables (e.g. <code>cssFallback</code>) and hard-to-read back and forth control flow (since, for some reason, you've decided to stick the <code>animeFallBack</code> function between the definition of <code>webAnimSupport</code> and the switch statement that uses it and possibly calls the function). Your code also has several likely bugs, as pointed out by Sᴀᴍ Onᴇᴌᴀ, and it's not even a complete, testable program (which means that there might well be more bugs that we can't easily spot). In fact, it's doubtful whether your code even qualifies as \"working as intended\", as required by <a href=\"https://codereview.stackexchange.com/help/on-topic\">the Code Review SE topic guidelines</a>.</p>\n\n<p>Based on what you've written in your question, it also looks like you probably don't really understand how basic JavaScript syntax features like <code>if</code> and <code>switch</code> statements actually work. Meanwhile, you've listed a whole bunch of \"related articles\" in your question, all of which appear to be dealing with considerably more advanced topics than basic JavaScript syntax, and which are probably taking a working knowledge of such syntax for granted.</p>\n\n<p><strong>To be brutally honest</strong>, it looks like you've jumped into the deep end of the pool before you've learned how to swim, and that you're now basically just copy-pasting and mixing up random bits of code that you've found online together without actually understanding them, and hoping that they'll somehow magically work.</p>\n\n<p>So my suggestion for you would be to start by finding a good and comprehensive JavaScript tutorial for beginners — I'd personally recommend a printed book, as they're more likely to come as a complete and self-contained package, although there are some fairly decent online tutorials around, too — and reading through it. Since you say you're interested in maintaining compatibility with older browsers, an old pre-ES6 tutorial would suit you fine, although a modern tutorial that covers <em>both</em> styles would be OK too.</p>\n\n<p>You can find plenty of Javascript tutorials — both printed books and online — <a href=\"https://www.google.com/search?q=list+of+javascript+tutorials\" rel=\"nofollow noreferrer\">via Google</a>. I'm not going to even try to provide any specific recommendations, although the first result I got (<a href=\"https://javascript.info/\" rel=\"nofollow noreferrer\">javascript.info</a>) at least looks fairly decent at a glance (and seems to cover both pre-ES6 and modern syntax, although with an emphasis mostly on the latter).</p>\n\n<p>Once you've picked up a better grasp of the basics, you should be able to come back and apply the suggestions from the references you've listed in your question to come up with a clean and working solution. FWIW, it'll probably end up looking a lot like the code in <a href=\"https://codereview.stackexchange.com/a/237522\">Adam Taylor's answer to your earlier question</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:30:30.167",
"Id": "468231",
"Score": "0",
"body": "Thanks, Duly noted...."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:51:26.353",
"Id": "238720",
"ParentId": "238500",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T20:18:40.493",
"Id": "238500",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6",
"api",
"animation",
"cross-browser"
],
"Title": "Javascript Anime Support Switch Statement for .animate() Api"
}
|
238500
|
<blockquote>
<p>Read a sequence of <strong>double</strong> values into a <strong>vector</strong>. Think of each value as the distance between two cities along a given route. Compute and print the total distance (the sum of all distances). Find and print the smallest and greatest distance between two neighboring cities. Find and print the mean distance between two neighboring cities.</p>
</blockquote>
<p>from Programming Principles and Practice using C++ by Bjarne Stroustrup</p>
<p>Since always entering values seems stupid, I decided to read the values from a file named "distances.txt".</p>
<p><code>print_distances_mean_max_min</code> is what concerns me, how could I split the computing of min,max,mean and printing it while not spreading the code too thinly? Or is it fine as it is?</p>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <algorithm>
using std::vector;
using std::string;
using std::fstream;
using std::ios_base;
using std::runtime_error;
using std::cout;
using std::max_element;
using std::min_element;
const string distances_file_name = "distances.txt";
vector<double> load_file_of_doubles_to_vector ( string file_name )
{
vector<double> distances;
fstream my_file ( file_name, ios_base::in );
double temporary_number;
while ( my_file >> temporary_number )
{
distances.push_back ( temporary_number );
}
if ( !my_file.is_open() )
{
throw runtime_error ( string ( "Failed to load " ) + file_name );
}
return distances;
}
void print_distances_mean_max_min ( const vector<double>& distances_vector )
{
if ( distances_vector.empty() )
{
throw runtime_error ( string ( "There are no entries in " ) + distances_file_name );
}
double total_distance = 0;
for ( auto& n : distances_vector )
{
total_distance += n;
}
cout << "The sum of all distances is: " << total_distance << "\n";
double max_distance = 0;
max_distance = *max_element ( distances_vector.begin(), distances_vector.end() );
cout << "The maximum distance is: " << max_distance << "\n";
double min_distance = 0;
min_distance = *min_element ( distances_vector.begin(), distances_vector.end() );
cout << "The minimum distance is: " << min_distance << "\n";
double mean_distance = 0;
mean_distance = total_distance / distances_vector.size();
cout << "The average(mean) distance is: " << mean_distance << "\n";
}
int main()
{
print_distances_mean_max_min ( load_file_of_doubles_to_vector ( distances_file_name ) );
return 0;
}
</code></pre>
<p>distances.txt</p>
<pre><code>8.7
6.3
9.0
3.142
2.7
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T22:37:02.857",
"Id": "467764",
"Score": "0",
"body": "In Java, I would create my own type to throw, and I'd use a checked exception, not a run time error. But the protocol in C++ might be different, it's something to look into."
}
] |
[
{
"body": "<p>Here are some suggestions for you to improve your code.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#include <iostream>\n#include <vector>\n#include <fstream>\n#include <stdexcept>\n#include <algorithm>\n</code></pre>\n</blockquote>\n\n<p>Sort the <code>#include</code> directives in alphabetical order. This helps navigation.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>using std::vector;\nusing std::string;\nusing std::fstream;\nusing std::ios_base;\nusing std::runtime_error;\nusing std::cout;\nusing std::max_element;\nusing std::min_element;\n</code></pre>\n</blockquote>\n\n<p>This is much better than <code>using namespace std;</code>, but I still suggest getting into the habit of explicitly qualifying the names with <code>std::</code> as soon as possible (especially for those names which you only use once, e.g., <code>max_element</code>). For small programs like this it doesn't matter, but for larger programs, qualification adds clarify — when I see <code>string</code>, does it mean <code>std::string</code>? <code>Jewelry::string</code>, a string of pearls? Or <a href=\"https://minecraft.gamepedia.com/String\" rel=\"nofollow noreferrer\"><code>Minecraft::string</code></a>, used to craft bows and fishing rods? This problem is especially evident for common identifiers, like <code>count</code>, <code>arg</code>, or <code>data</code> — these are all top level names in <code>std</code>!</p>\n\n<p>Moreover, using unqualified names sometimes cause ADL (argument dependent lookup), an additional phase for name lookup, to kick in. As a result, an attempt to call a function in the standard library may end up inadvertently calling a function in an irrelevant namespace. Such problems come up often in large programs, so again, it's better to get into the habit of using <code>std::</code>.</p>\n\n<p>It is acceptable to use <code>using</code> declarations or derivatives <strong>in reduced scopes</strong>, to reduce clutter. But using them globally for the whole program is likely to cause problems. Moreover, <code>std::</code> is only 5 characters — reducing clutter is more relevant for things like</p>\n\n<pre><code>boost::math::double_constants::pi\n</code></pre>\n\n<p>or </p>\n\n<pre><code>boost::multiprecision::number<\n boost::multiprecision::mpfr_float_backend<300>,\n boost::multiprecision::et_off\n>;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>const string distances_file_name = \"distances.txt\";\n</code></pre>\n</blockquote>\n\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/language/constexpr\" rel=\"nofollow noreferrer\"><code>constexpr</code></a> <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> (defined in header <a href=\"https://en.cppreference.com/w/cpp/header/string_view\" rel=\"nofollow noreferrer\"><code><string_view></code></a>) for string constants:</p>\n\n<pre><code>constexpr std::string_view file_name{\"distances.txt\"};\n</code></pre>\n\n<p>or</p>\n\n<pre><code>using namespace std::literals;\nconstexpr auto file_name = \"distances.txt\"sv;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>vector<double> load_file_of_doubles_to_vector ( string file_name )\n{\n vector<double> distances;\n fstream my_file ( file_name, ios_base::in );\n double temporary_number;\n while ( my_file >> temporary_number )\n {\n distances.push_back ( temporary_number );\n }\n if ( !my_file.is_open() )\n {\n throw runtime_error ( string ( \"Failed to load \" ) + file_name );\n }\n return distances;\n}\n</code></pre>\n</blockquote>\n\n<p>The parameter type should be <code>std::string_view</code> to avoid redundant copies.</p>\n\n<p>The file stream should be of type <a href=\"https://en.cppreference.com/w/cpp/io/basic_ifstream\" rel=\"nofollow noreferrer\"><code>std::ifstream</code></a> instead of <code>std::fstream</code> because it is used for input only. Then, you can omit the <code>in</code> option, which is the default for <code>std::ifstream</code>.</p>\n\n<p><code>string ( \"Failed to load \" ) + file_name</code> is too verbose. Use <code>\"Failed to load \"s</code>.</p>\n\n<p>Consider using <a href=\"https://en.cppreference.com/w/cpp/iterator/istream_iterator\" rel=\"nofollow noreferrer\"><code>std::istream_iterator</code></a>, <a href=\"https://en.cppreference.com/w/cpp/iterator/back_inserter\" rel=\"nofollow noreferrer\"><code>std::back_inserter</code></a> (both defined in <a href=\"https://en.cppreference.com/w/cpp/header/iterator\" rel=\"nofollow noreferrer\"><code><iterator></code></a>), and <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"nofollow noreferrer\"><code>std::copy</code></a> to read the values:</p>\n\n<pre><code>// requires NTBS as argument\nauto load_file(std::string_view file_name)\n{\n // std::string_view doesn't have c_str()\n std::ifstream in{file_name.data()};\n if (!in.is_open()) {\n // assuming 'using namespace std::literals;'\n throw std::runtime_error{\"the file doesn't exist\"};\n }\n\n std::vector<double> data;\n std::copy(std::istream_iterator<double>{in},\n std::istream_iterator<double>{},\n std::back_inserter(data));\n return data;\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>void print_distances_mean_max_min ( const vector<double>& distances_vector )\n{\n if ( distances_vector.empty() )\n {\n throw runtime_error ( string ( \"There are no entries in \" ) + distances_file_name );\n }\n double total_distance = 0;\n for ( auto& n : distances_vector )\n {\n total_distance += n;\n }\n cout << \"The sum of all distances is: \" << total_distance << \"\\n\";\n double max_distance = 0;\n max_distance = *max_element ( distances_vector.begin(), distances_vector.end() );\n cout << \"The maximum distance is: \" << max_distance << \"\\n\";\n double min_distance = 0;\n min_distance = *min_element ( distances_vector.begin(), distances_vector.end() );\n cout << \"The minimum distance is: \" << min_distance << \"\\n\";\n double mean_distance = 0;\n mean_distance = total_distance / distances_vector.size();\n cout << \"The average(mean) distance is: \" << mean_distance << \"\\n\";\n}\n</code></pre>\n</blockquote>\n\n<p>IMO, this function is unnecessary and can be built into <code>main</code> directly, because it doesn't have a coherent logic — it just shows what the program does.</p>\n\n<p>Catching exceptions in the main function and printing the messages helps the end user know what kind of error happened.</p>\n\n<p>Don't reinvent the wheel — use <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> or <a href=\"https://en.cppreference.com/w/cpp/algorithm/reduce\" rel=\"nofollow noreferrer\"><code>std::reduce</code></a> (defined in header <a href=\"https://en.cppreference.com/w/cpp/header/numeric\" rel=\"nofollow noreferrer\"><code><numeric></code></a>) to calculate sums.</p>\n\n<p>You can calculate the minimum and maximum values simultaneously in\n<span class=\"math-container\">\\$\\lfloor 3(N-1)/2 \\rfloor\\$</span> comparisons using <a href=\"https://en.cppreference.com/w/cpp/algorithm/minmax_element\" rel=\"nofollow noreferrer\"><code>std::minmax_element</code></a>, which returns a <a href=\"https://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a> of iterators pointing to the minimum and maximum elements respectively. Then, we can use a <a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\" rel=\"nofollow noreferrer\">structured binding</a> to conveniently obtain the two iterators and dereference them to get the values:</p>\n\n<pre><code>int main()\ntry {\n auto data = load_file(file_name);\n if (data.empty()) {\n throw std::runtime_error{\"no entries\"};\n }\n\n auto sum = std::accumulate(data.begin(), data.end(), 0.0);\n auto mean = sum / data.size();\n auto [min_it, max_it] = std::minmax_element(data.begin(), data.end());\n\n std::cout << \"The sum of all distances is: \" << sum << '\\n'\n << \"The maximum distance is: \" << *max_it << '\\n'\n << \"The minimum distance is: \" << *min_it << '\\n'\n << \"The average (mean) distance is: \" << mean << '\\n';\n} catch (std::runtime_error& error) {\n std::cerr << \"Runtime error: \" << error.what() << '\\n';\n return 1;\n} catch (...) {\n std::cerr << \"Unknown error\\n\";\n return 2;\n}\n</code></pre>\n\n<hr>\n\n<p>I've made an <a href=\"https://wandbox.org/permlink/p9dRR8dL5tugZO3n\" rel=\"nofollow noreferrer\">online demo</a> by putting everything together so that you can play with the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T12:38:36.420",
"Id": "467811",
"Score": "0",
"body": "Hi, thanks for your answer. What are \"ADL problems\"? Doesn't add \"using std::string\" a little readability, especially if you got for example std::vector<std::string> ? Which type \"auto [min_it, max_it]\" will get, and why use \"auto\"? Why does putting a function into the main add more ability to catch errors, can't I do the \"try\"-block inside a function? Bonuspoints for showing me Wandbox, this site is neat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T13:30:12.833",
"Id": "467817",
"Score": "0",
"body": "@SAJW You're welcome. I've updated the answer address your questions. The part about catching exceptions in the main function was worded poorly; I've tried clarify it - where you catch the exceptions is not important in this case, as long as you catch them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T14:15:59.277",
"Id": "467819",
"Score": "0",
"body": "I think you got a typo here \"when I see vector, does it mean std::string? \" i think you mean: \"when I see string...\" or? Also I'm not quite sure if alphabeticly ordering of the #includes is what I want, see the comments in this topic: https://stackoverflow.com/questions/60578003/automatically-sorting-includes-with-codeblocks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T16:23:25.240",
"Id": "467821",
"Score": "0",
"body": "You asked a very good question in the link you provided \"but if the order of the #includes does matter, is this not a sign that at least one header is written badly and should be changed?\" Yes, it does signify that if there is dependency. With these standard headers, there is no such dependency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T02:43:46.147",
"Id": "467850",
"Score": "0",
"body": "@SAJW That's indeed a typo - thanks for spotting! Alphabetically ordering headers is just a general guideline; there are (rare) cases where include order is important, but this is not the case for standard headers (which are just regular and self-contained headers). So you probably shouldn't let your editor do it automatically. It's common for large programs to require many headers in one translation unit, so sorting is still beneficial for readability."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T08:26:19.023",
"Id": "238520",
"ParentId": "238502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238520",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T21:06:22.587",
"Id": "238502",
"Score": "3",
"Tags": [
"c++",
"beginner",
"c++17"
],
"Title": "Exercise: Reading doubles from a file and printing mean, max and min (from Programming Principles and Practice using C++)"
}
|
238502
|
<p>I've been working on an incremental game that I will need to store extremely large scientific numbers. as a part of this game, precision is only important for numbers within similar magnitudes. If a number is 10^20 times larger than another one, then adding or subtracting these numbers has a "negligible" impact on the overall value. </p>
<p>I've built a struct that can be used to represent these impressively massive numbers. ScienceNums can represent a number up to a magnitude of <strong>10^2,147,483,647</strong> or as small as <strong>10^-2,147,483,647</strong>. These numbers can be made further precise and further scaled by using doubles in place of floats, and bigger integers like Int64.</p>
<p>In order for this struct to do more than just store data, I overrode the standard operators for +,-,/,* and implemented them using this struct. Unfortunately, these are not totally lossless operations. Addition and subtractions are ignored for magnitude differences greater than 10^8. Multiplication and division do not ignore any operations, but do run the risk of losing some floating point precision. For most applications (like an incremental game that scales into massive numbers), this shouldn't impact the functionality at all.</p>
<p>There is a Conversion() method that converts numbers back to a float. This is primarily used when a division results in a reasonably sized number and needs to be used for game logic (like HP%, for example).</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BigNums
{
[Serializable]
public struct ScienceNum
{
//Should always be between 1 and 9.9999
public float baseValue;
public int eFactor;
public static ScienceNum operator +(ScienceNum sn1, ScienceNum sn2)
{
//Bring the 2 numbers to the same power of 10.
int factorDiff = sn1.eFactor - sn2.eFactor;
//arbitrary limit, but if the difference in factors is more than 10^8, ignore the operation
if (factorDiff >= 8)
return sn1;
sn2.baseValue /= Mathf.Pow(10, factorDiff);
sn2.eFactor += factorDiff;
//Add
sn1.baseValue += sn2.baseValue;
//If 0, then 0 can be returned now to avoid div/0 errors
if(sn1.baseValue == 0)
return sn1;
//Convert resulting baseValue back to single digit range
int eChange = Mathf.FloorToInt(Mathf.Log10(Mathf.Abs(sn1.baseValue)));
sn1.baseValue /= Mathf.Pow(10, eChange);
sn1.eFactor += eChange;
return sn1;
}
public static ScienceNum operator -(ScienceNum sn1, ScienceNum sn2)
{
//Bring the 2 numbers to the same power of 10.
int factorDiff = sn1.eFactor - sn2.eFactor; //1
//arbitrary limit, but if the difference in factors is more than 10^8, ignore the operation.
if (factorDiff >= 8)
return sn1;
sn2.baseValue /= Mathf.Pow(10,factorDiff);
sn2.eFactor += factorDiff;
//Subtract
sn1.baseValue -= sn2.baseValue;
//If 0, then 0 can be returned now to avoid div/0 errors
if (sn1.baseValue == 0)
return sn1;
//Convert resulting baseValue back to single digit range
int eChange = Mathf.FloorToInt(Mathf.Log10(Mathf.Abs(sn1.baseValue)));
sn1.baseValue /= Mathf.Pow(10, eChange);
sn1.eFactor += eChange;
return sn1;
}
public static ScienceNum operator *(ScienceNum sn1, ScienceNum sn2)
{
sn1.baseValue *= sn2.baseValue;
sn1.eFactor += sn2.eFactor;
if (sn1.baseValue >= 10f)
{
sn1.eFactor += 1;
sn1.baseValue /= 10;
}
return sn1;
}
public static ScienceNum operator /(ScienceNum sn1, ScienceNum sn2)
{
sn1.baseValue /= sn2.baseValue;
sn1.eFactor -= sn2.eFactor;
if (sn1.baseValue < 1f)
{
sn1.eFactor -= 1;
sn1.baseValue *= 10;
}
return sn1;
}
public float Conversion()
{
return baseValue * Mathf.Pow(10, eFactor);
}
public override string ToString()
{
return String.Format("{0}e{1}", baseValue, eFactor);
}
public static ScienceNum FromString(string str)
{
ScienceNum scienceNum = new ScienceNum();
var split = str.Split('e');
scienceNum.baseValue = Convert.ToSingle(split[0]);
scienceNum.eFactor = Convert.ToInt32(split[1]);
return scienceNum;
}
}
}
</code></pre>
<p>The following are my questions:</p>
<ul>
<li>The ToString and FromString are for storing these numbers to a database. <strong>Is there a more efficient way to store these?</strong></li>
<li><strong>Are there additional risks to the above logic aside from loss of precision?</strong></li>
<li><strong>Is a performant way to perform square root/power functions using these numbers?</strong></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T16:28:19.547",
"Id": "467822",
"Score": "1",
"body": "For + and -, behavior is asymmetric: you handle the case where `sn1` is much greater than `sn2`, but not the other way around. As a consequence, `a + b != b + a`, which can lead to subtle problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T19:21:55.963",
"Id": "467832",
"Score": "0",
"body": "Thank you @Aganju ! I completely overlooked that. Please consider writing that as a formal answer so that I may award a vote to it."
}
] |
[
{
"body": "<p>Not a full review, but a relevant point:<br>\nFor + and -, behavior is asymmetric: you handle the case where <code>sn1</code> is much greater than <code>sn2</code>, but not the other way around. As a consequence, <code>a + b != b + a</code>, which can lead to subtle problems.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:24:12.777",
"Id": "238628",
"ParentId": "238503",
"Score": "3"
}
},
{
"body": "<p>In <a href=\"https://en.wikipedia.org/wiki/Scientific_notation\" rel=\"nofollow noreferrer\">Scientific notation</a> your <code>baseValue</code> is called <code>coefficient</code> while <code>eFactor</code> is called <code>exponent</code>. You should use the conventional naming.</p>\n\n<hr>\n\n<p>I would definitely make the type immutable in order to make it behave like any other numerical type - as a constant/literal. It will avoid misunderstandings and minimize errors:</p>\n\n<p>You could define it like:</p>\n\n<pre><code> [Serializable]\n public struct ScienceNum\n {\n //Should always be between 1 and 9.9999\n private readonly float coefficient;\n private readonly int exponent;\n\n public ScienceNum(float coefficient, int exponent)\n {\n this.coefficient = coefficient;\n this.exponent = exponent;\n }\n\n public float Coefficient => coefficient;\n public int Exponent => exponent;\n\n // ...\n }\n</code></pre>\n\n<p>You'll then have to modify your operator implementations so they don't make the calculations on the fields of the arguments.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> //Should always be between 1 and 9.9999\n public float baseValue;\n</code></pre>\n</blockquote>\n\n<p>You should protect against overflow of the coefficient (baseValue) in the constructor:</p>\n\n<pre><code>public ScienceNum(float coefficient, int exponent)\n{\n if (coefficient < 1f || coefficient > 9.9999f) throw new ArgumentOutOfRangeException(nameof(coefficient));\n\n this.coefficient = coefficient;\n this.exponent = exponent;\n}\n</code></pre>\n\n<hr>\n\n<p>It would be convenient if you implement cast operators for the primitive numerical types (int, float, long, double etc.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:56:43.447",
"Id": "238669",
"ParentId": "238503",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238669",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T22:06:21.240",
"Id": "238503",
"Score": "2",
"Tags": [
"c#",
"unity3d"
],
"Title": "Storing and calculating extremely large/small numbers in C# using a Scientific Notation struct"
}
|
238503
|
<p>Full code can be found on my <a href="https://github.com/Webbarrr/WoWSelector" rel="nofollow noreferrer">GitHub</a> but more details are included here.</p>
<p>I decided I'd like to level up some new characters on WoW Classic & I thought it would be fun if I randomly generated some combinations.</p>
<p>The idea is that you would generate a random faction (<code>Horde</code> or <code>Alliance</code>), then one of the races & finally one of the available classes.</p>
<p>I can't put my finger on why, but I'm not overly happy with the outcome. It's a combination of things really. The code works of course, but I can't help but feel it could be better.</p>
<p>So - the gist of it is this.</p>
<p>We have factions -</p>
<pre><code>using System.Collections.Generic;
using WoWSelector.Library.Races;
namespace WoWSelector.Library.Factions
{
public class Alliance : IFaction
{
public List<IRace> GetRaces()
{
var races = new List<IRace>
{
new Human(),
new Dwarf(),
new NightElf(),
new Gnome()
};
return races;
}
}
}
</code></pre>
<p>And we have races -</p>
<pre><code>using System.Collections.Generic;
namespace WoWSelector.Library.Races
{
public class Human : AllianceBase, IRace
{
public List<string> GetClasses()
{
return this.GetPlayableClasses();
}
}
}
</code></pre>
<p>I think this is where it gets quite messy. All races inherit from a corresponding base class -</p>
<pre><code>using System.Collections.Generic;
using WoWSelector.Library.Classes;
namespace WoWSelector.Library.Races
{
public class AllianceBase : ClassBase
{
public List<string> GetPlayableClasses()
{
var dict = new Dictionary<IRace, string>();
var classes = new List<string>
{
Warrior,
Paladin,
Rogue,
Priest,
Mage,
Warlock
};
foreach (var item in classes)
{
dict.Add(new Human(), item);
}
classes = new List<string>
{
Warrior,
Paladin,
Hunter,
Rogue,
Priest
};
foreach (var item in classes)
{
dict.Add(new Dwarf(), item);
}
classes = new List<string>
{
Warrior,
Hunter,
Rogue,
Priest,
Druid
};
foreach (var item in classes)
{
dict.Add(new NightElf(), item);
}
classes = new List<string>
{
Warrior,
Rogue,
Mage,
Warlock
};
foreach (var item in classes)
{
dict.Add(new Gnome(), item);
}
return this.GetPlayableCLasses(dict, this.GetType().Name);
}
}
}
</code></pre>
<p>And the faction specific base classes inherit from -</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using WoWSelector.Library.Races;
namespace WoWSelector.Library.Classes
{
public class ClassBase
{
public const string Warrior = "Warrior";
public const string Paladin = "Paladin";
public const string Rogue = "Rogue";
public const string Priest = "Priest";
public const string Mage = "Mage";
public const string Warlock = "Warlock";
public const string Hunter = "Hunter";
public const string Druid = "Druid";
public const string Shaman = "Shaman";
protected List<string> GetPlayableCLasses(Dictionary<IRace, string> keyValuePairs, string raceName)
{
var playableClasses = keyValuePairs.Where(d => d.Key.GetType().Name == raceName);
var listOfPlayableClasses = new List<string>();
foreach (var item in playableClasses)
{
listOfPlayableClasses.Add(item.Value);
}
return listOfPlayableClasses;
}
}
}
</code></pre>
<p>I dislike how much I've repeated steps in the example <code>AllianceBase</code> class. I'm sure there's a smarter way of doing it but I couldn't figure it out.</p>
<p>And of course, how it all comes together in the form of a controller class to be called in my main method -</p>
<pre><code>using System;
using System.Collections.Generic;
using WoWSelector.Library.Factions;
using WoWSelector.Library.Races;
namespace WoWSelector.Library
{
public class SelectorController
{
private readonly Random random;
public SelectorController()
{
random = new Random();
}
public IFaction GetFaction()
{
var factions = new List<IFaction>
{
new Alliance(),
new Horde()
};
return factions[random.Next(0, factions.Count)];
}
public IRace GetRace(IFaction faction)
{
if (faction is null)
throw new ArgumentNullException(nameof(faction));
var races = faction.GetRaces();
return races[random.Next(0, races.Count)];
}
public string GetClass(IRace race)
{
if (race is null)
throw new ArgumentNullException(nameof(race));
var classes = race.GetClasses();
return classes[random.Next(0, classes.Count)];
}
}
}
</code></pre>
<p>Appreciate this is on the chunky side but would appreciate any feedback people are willing to give to help me improve.</p>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<p>I think the main problem you have here is that you have very tight coupling, and you've made a <strong>bunch</strong> of classes that don't really do anything. Just because you can make a class/object doesn't mean you should. In this case, your use-case is straightforward enough that the simplest solution is likely the best.</p>\n\n<p>For example - the fact that you have 8 classes to represent the race, that are all <em>literally</em> identical besides for the class name is a huge code smell. Despite this, you then seem to fallback to strings all the time, for no apparent reason. </p>\n\n<p>I also noticed that you instantiate your classes all over the place, despite there not being any instance-specific behavior it actually drives.</p>\n\n<p>For your limited use case, just making some switch statements is going to be your best bet:</p>\n\n<pre><code>enum RaceEnum {\n Gnome,\n Dwarf,\n Human,\n NightElf,\n Orc,\n Tauren,\n Troll,\n Undead\n}\n\nenum ClassEnum {\n Warrior,\n Paladin,\n Rogue,\n Priest,\n Mage,\n Warlock,\n Hunter,\n Druid,\n Shaman\n}\n\nenum FactionEnum {\n Alliance,\n Horde\n}\n\nclass WowClassicCharacter {\n public RaceEnum Race { get; set; }\n\n public ClassEnum Class { get; set; }\n\n public FactionEnum Faction { get; set; }\n\n public WowClassicRace(RaceEnum race, ClassEnum klass, FactionEnum faction) {\n if (!WowClassicCharacter.raceIsValidForFaction(race, faction)) {\n throw new Exception(\"The given race and faction are not compatible\");\n }\n if (!WowClassicCharacter.classIsValidForRace(klass, race) {\n throw new Exception(\"The given class and race are not compatible\");\n }\n Race = race;\n Class = klass;\n Faction = faction;\n }\n\n public static boolean raceIsValidForFaction(RaceEnum race, FactionEnum faction) {\n return faction switch\n {\n FactionEnum.Alliance => race switch \n {\n RaceEnum.Human => true,\n RaceEnum.Dwarf => true,\n RaceEnum.NightElf => true,\n RaceEnum.Gnome => true,\n _ => false\n },\n FactionEnum.Horde => race switch\n {\n RaceEnum.Orc => true,\n RaceEnum.Troll => true,\n RaceEnum.Tauren => true,\n RaceEnum.Undead => true,\n _ => false\n }\n };\n }\n\n public static boolean classIsValidForRace(ClassEnum klass, RaceEnum race) {\n return race switch\n {\n RaceEnum.Human => klass switch\n {\n ClassEnum.Warrior => true,\n ClassEnum.Paladin => true,\n ClassEnum.Rogue => true,\n ClassEnum.Priest => true,\n ClassEnum.Mage => true,\n ClassEnum.Warlock => true,\n _ => false\n },\n RaceEnum.Dwarf => klass switch\n {\n ClassEnum.Warrior => true,\n ClassEnum.Paladin => true,\n ClassEnum.Hunter => true,\n ClassEnum.Rogue => true,\n ClassEnum.Priest => true,\n _ => false\n },\n // etc\n _ => false\n };\n }\n}\n</code></pre>\n\n<p>It would be relatively straightforward to make a config file, or a database, or whatever back this up instead of hardcoded switch statements, but it seems like your use case doesn't require the complexity, so keep it simple.</p>\n\n<p>Then your controller looks like this:</p>\n\n<pre><code>public class SelectorController\n{\n private readonly Random random;\n\n public SelectorController()\n {\n random = new Random();\n }\n\n private T GetRandomEnumValue<T>() where T: system.Enum\n {\n return random.Next(0, Enum.GetNames(typeof(T)).Length);\n }\n\n public FactionEnum GetFaction()\n {\n return GetRandomEnumValue<FactionEnum>();\n }\n\n public RaceEnum GetRace(FactionEnum faction)\n {\n RaceEnum race;\n do \n {\n race = GetRandomEnumValue<RaceEnum>();\n }\n while (!WowClassicCharacter.raceIsValidForFaction(race, faction));\n return race;\n }\n\n public ClassEnum GetClass(RaceEnum race)\n {\n ClassEnum klass;\n do \n {\n klass = GetRandomEnumValue<ClassEnum>();\n }\n while (!WowClassicCharacter.classIsValidForRace(klass, race));\n return klass;\n }\n}\n</code></pre>\n\n<p>You could pretty easily make some smarter methods than just randomly generating until it is valid, but this gets the point across.</p>\n\n<p>Final takeaways:</p>\n\n<ol>\n<li>Don't make and use classes just because you can</li>\n<li>Enums are better than strings</li>\n<li>When in doubt, prefer simple solutions</li>\n</ol>\n\n<p>Apologies for any errors - my C# is rusty and I wrote this all in the answer box.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:35:43.377",
"Id": "467938",
"Score": "0",
"body": "Sorry for the delay in getting back to you - your feedback was appreciated.\n\nI appreciate the final takeaways. I think 1 & 3 are definitely an issue that I create for myself by trying to over-engineer things from the start of a project. I did toy with using Enums to begin with but couldn't figure out a way of getting it to work with the way I was trying to lay things out. Thank you again for your help"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T00:51:58.250",
"Id": "238508",
"ParentId": "238507",
"Score": "4"
}
},
{
"body": "<p>Not sure why you've gone this far using the classes instead of <code>Enum</code>. I can understand if you're planning to include some functionalities to each class, but if is it just for the current context, then it would be useless.</p>\n<p>For instance, Warrior, Hunter, Rogue ..etc. are some work descriptions to Races like Human, Orc, Troll...etc. And Alliance, Horde... are another type of these races. So Race is the main type, while others are just some descriptive types of these races.</p>\n<p>Since they're all descriptive types, we can use <code>Enum</code> :</p>\n<pre><code>public enum RaceType\n{\n Warrior,\n Paladin,\n Rogue,\n Priest,\n Mage,\n Warlock,\n Hunter,\n Druid,\n Shaman\n}\n\npublic enum RaceName\n{\n Orc,\n Troll,\n Tauren,\n Undead,\n Human,\n Dwarf,\n NightElf,\n Gnome\n}\n\npublic enum RaceFaction\n{\n Horde,\n Alliance\n}\n</code></pre>\n<p>Now, we can make a model class which will hold all that information</p>\n<pre><code>public class Race\n{\n public RaceType Type { get; set; }\n\n public RaceName Name { get; set; }\n\n public RaceFaction Faction { get; set; }\n\n public Race() { }\n\n public Race(RaceType type, RaceName name, RaceFaction faction) \n {\n Type = type;\n Name = name;\n Faction = faction;\n }\n}\n</code></pre>\n<p>Now, we use it on the main class :</p>\n<pre><code>public class WoWSelector\n{\n private readonly List<Race> Races = new List<Race>();\n \n private Random _random = new Random();\n\n private int _randomIndex => _random.Next(0, Races.Count);\n\n private IEnumerable<Race> GetAlliance()\n {\n // I have never played WOW, but I assumed it's a fixed data since you've defined it on your Alliance class.\n return new List<Race>\n {\n new Race(RaceType.Warrior, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Paladin, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Rogue, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Priest, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Mage, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Warlock, RaceName.Human, RaceFaction.Alliance),\n new Race(RaceType.Warrior, RaceName.Dwarf, RaceFaction.Alliance),\n new Race(RaceType.Paladin, RaceName.Dwarf, RaceFaction.Alliance),\n new Race(RaceType.Hunter, RaceName.Dwarf, RaceFaction.Alliance),\n new Race(RaceType.Rogue, RaceName.Dwarf, RaceFaction.Alliance),\n new Race(RaceType.Priest, RaceName.Dwarf, RaceFaction.Alliance),\n new Race(RaceType.Warrior, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Hunter, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Rogue, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Priest, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Druid, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Druid, RaceName.NightElf, RaceFaction.Alliance),\n new Race(RaceType.Warrior, RaceName.Gnome, RaceFaction.Alliance),\n new Race(RaceType.Rogue, RaceName.Gnome, RaceFaction.Alliance),\n new Race(RaceType.Mage, RaceName.Gnome, RaceFaction.Alliance),\n new Race(RaceType.Warlock, RaceName.Gnome, RaceFaction.Alliance)\n };\n\n }\n\n private IEnumerable<Race> GetHorde()\n {\n return new List<Race>\n {\n new Race(RaceType.Warrior, RaceName.Orc, RaceFaction.Horde),\n new Race(RaceType.Hunter, RaceName.Orc, RaceFaction.Horde),\n new Race(RaceType.Rogue, RaceName.Orc, RaceFaction.Horde),\n new Race(RaceType.Shaman, RaceName.Orc, RaceFaction.Horde),\n new Race(RaceType.Warlock, RaceName.Orc, RaceFaction.Horde),\n new Race(RaceType.Warrior, RaceName.Undead, RaceFaction.Horde),\n new Race(RaceType.Priest, RaceName.Undead, RaceFaction.Horde),\n new Race(RaceType.Rogue, RaceName.Undead, RaceFaction.Horde),\n new Race(RaceType.Mage, RaceName.Undead, RaceFaction.Horde),\n new Race(RaceType.Warlock, RaceName.Undead, RaceFaction.Horde),\n new Race(RaceType.Warrior, RaceName.Tauren, RaceFaction.Horde),\n new Race(RaceType.Hunter, RaceName.Tauren, RaceFaction.Horde),\n new Race(RaceType.Shaman, RaceName.Tauren, RaceFaction.Horde),\n new Race(RaceType.Druid, RaceName.Tauren, RaceFaction.Horde),\n new Race(RaceType.Warrior, RaceName.Troll, RaceFaction.Horde),\n new Race(RaceType.Hunter, RaceName.Troll, RaceFaction.Horde),\n new Race(RaceType.Rogue, RaceName.Troll, RaceFaction.Horde),\n new Race(RaceType.Priest, RaceName.Troll, RaceFaction.Horde),\n new Race(RaceType.Mage, RaceName.Troll, RaceFaction.Horde),\n new Race(RaceType.Shaman, RaceName.Troll, RaceFaction.Horde)\n };\n }\n\n public WoWSelector()\n {\n Races.AddRange(GetAlliance());\n Races.AddRange(GetHorde());\n }\n\n public Race GetRandomRace()\n {\n return Races[_randomIndex];\n }\n} \n</code></pre>\n<p>For <code>GetAlliance</code> and <code>GetHorde</code> basically, I extracted your classes into methods. If you're expecting to initiate a <code>new</code> random <code>Race</code>, then you can get rid of them, and just use random to generate new <code>Race</code> instead.</p>\n<p>Then you can do this :</p>\n<pre><code>var wow = new WoWSelector();\n\nfor(int x=0; x < 5; x++)\n{\n var race = wow.GetRandomRace();\n\n Console.WriteLine($"{race.Type} : {race.Name} : {race.Faction}");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:37:31.383",
"Id": "467939",
"Score": "0",
"body": "Sorry for the delay in getting back to you, busy weekend, but did appreciate your feedback.\n\nAs I mentioned on the other answer I was given, I did try to use Enums to start with but I think that I'm very guilty of over-engineering things from the beginning of a project & my biggest takeaway should be to think more around more elegant solutions.\n\nI've taken away your comments on Enum & applied it to another project I'm working on at the moment & it's making life easier to not just create classes for the sake of it. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T14:08:38.997",
"Id": "484912",
"Score": "0",
"body": "I would move methods like `GetAlliance()` to their own class (e.g. `AllianceRetriever`) perhaps even have them as static properties instead of methods, and use loops to construct the various `Race` objects."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T04:47:13.150",
"Id": "238515",
"ParentId": "238507",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T00:15:18.903",
"Id": "238507",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Randomly generating a WoW Classic character"
}
|
238507
|
<p>I am trying to write a small function to safely create dir until dir until full path of file exists. I'm trying to do it in a recursing function and would love to get some feedback.</p>
<pre><code>def makedir(filepath: str) -> bool:
if os.path.exists(os.path.dirname(filepath)):
return
os.makedirs(os.path.dirname(filepath), exist_ok=True)
makedir(filepath)
makedir('/a/b/c/d/x.text')
#should create a then b then c then d
makedir('/a/b/c/e/y.text')
#should create e only since a, b,c already exist
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T03:05:37.850",
"Id": "467775",
"Score": "0",
"body": "How is that question to do with mine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T03:30:36.063",
"Id": "467777",
"Score": "0",
"body": "I don't see the connection either. Maybe they posted the wrong link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T09:55:14.147",
"Id": "467803",
"Score": "0",
"body": "Sorry, that was the wrong link."
}
] |
[
{
"body": "<p>First, <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\"><code>os.makedirs</code></a> already creates all the intermediate directories in the path. That is its job. So there is no need to use recursion.</p>\n\n<p>There is also no need to use <code>os.path.exists</code>, because you are using the <code>exist_ok=True</code> argument with <code>os.makedirs</code>. This means that <code>os.makedirs</code> will not error out if the directory already exists.*</p>\n\n<p>Your type hint for the return type should be <code>None</code>, since you are not returning any values.</p>\n\n<p>I would also change the name of your function. I think the name <code>makedir</code> is too close to <code>os.makedirs</code>, which is confusing.</p>\n\n<pre><code>import os\n\ndef makedirs_for_file(filepath: str) -> None:\n os.makedirs(os.path.dirname(filepath), exist_ok=True)\n</code></pre>\n\n<hr>\n\n<p>*Unless you are using a Python version before 3.4.1. In this case, <code>os.makedirs</code> may still error out, depending on the mode of the existing directory. See the documentation for more details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T04:01:23.213",
"Id": "467780",
"Score": "0",
"body": "Hm..I do try to use os.makedirs But it doesn't work. Seems thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T13:52:50.020",
"Id": "470543",
"Score": "0",
"body": "What do you mean by doesn't work ? Do you have an error message ?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T03:35:21.593",
"Id": "238514",
"ParentId": "238510",
"Score": "3"
}
},
{
"body": "<p>This function does not actually return anything.\nWhat is good is that you use type hinting for your function. So I was really expecting that you would return a boolean value, because you obviously want some kind of feedback for your request. The problem is that the function <code>makedirs</code> does not have a return value that you could directly utilize.</p>\n\n<p>So I would approach the problem like this: if an exception occurs, return false otherwise assume everything is alright. Thus the code becomes:</p>\n\n<pre><code>import os, sys\n\ndef makedir(filepath: str) -> bool:\n try:\n if os.path.exists(filepath):\n # dir already exists\n print(f\"FYI Dir already exists: {filepath}\")\n return False\n else:\n # attempt to create dir\n os.makedirs(filepath)\n return True\n\n except (OSError) as e:\n # log the details of the exception somewhere (console, file)\n print(f\"OSError exception occurred while attempting to create directory: {filepath}\")\n print(\"Unexpected error:\", sys.exc_info()[0])\n return False\n\n# testing\nret=makedir('/tmp')\nprint(f\"Return from function: {ret}\")\n</code></pre>\n\n<p>Here I have decided to discard the argument <code>exist_ok=True</code> and deliberately fail if the directory already exists, because I like to be strict and consider there should be no reason for doing this in the first place, but it's your choice. </p>\n\n<p>I have tried to be as specific as possible and not catch any type of exception. The relevant exception within the scope of this operation is <code>OSError</code>.\nThis should suffice, but if necessary you can handle multiple exceptions on the same line like this:</p>\n\n<pre><code>except (OSError, ValueError) as e:\n</code></pre>\n\n<p>You can also decide to handle the exceptions at module level, anyway the main module should always have its own mechanism to handle exceptions you are not explicitly addressing in specific parts of your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T14:49:08.347",
"Id": "239874",
"ParentId": "238510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238514",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T01:51:55.873",
"Id": "238510",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Recursing function to create dir in python"
}
|
238510
|
<p>Sometimes I would like use word count to describe someone's contribution, so, I wrote a query to stat the word count for a given stackexchange user, based on SEDE. <a href="https://data.stackexchange.com/ell/query/1206589/word-count-a-user" rel="nofollow noreferrer">click to run it online</a> </p>
<pre><code>DECLARE @total_count int, @post_id int, @post_body nvarchar(max);
SET @total_count = 0;
DECLARE vendor_cursor CURSOR FOR
SELECT id, Body
FROM posts
WHERE posts.OwnerUserId = 9872;
OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor
INTO @post_id, @post_body
PRINT FORMATMESSAGE(' id | count | total count')
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @count int;
SELECT @count = (LEN(@post_body ) - LEN(replace(@post_body , ' ', '')))
SELECT @total_count = @total_count + @count
PRINT FORMATMESSAGE('%6d | %5d | %d', @post_id, @count, @total_count)
FETCH NEXT FROM vendor_cursor
INTO @post_id, @post_body
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T13:28:42.737",
"Id": "467816",
"Score": "0",
"body": "Could you add a general explanation of how your code works, as well as adding what you want specifically to be reviewed in this question?"
}
] |
[
{
"body": "<p>Reviewing your T-SQL script I see that you have a cursor to iterate over Posts from a specific owner. For each body you use a neat trick to determine the word count of the body and use an extra variable to keep the running sum. You use FORMATMESSAGE to shape the data in each row.</p>\n<p>Do know that the neat trick for the word count doesn't compensate for cases where two or more spaces are used, or where words are not separated by spaces but by other characters, like line-breaks for example. I'll ignore the fact here that in case of Posts.Body not only the text is stored but also the HTML markup.</p>\n<p>I find the script clear and well structured.<br />\nIf you're looking for an alternative way to accomplish the same output (I ignore the formatting here) I can offer <a href=\"https://data.stackexchange.com/ell/query/1258431?UserId=+9872&opt.textResults=true&opt.withExecutionPlan=true#executionPlan\" rel=\"nofollow noreferrer\">this SEDE query</a>:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @UserId int = ##UserId## -- SDE parameter syntax\n\nSELECT Id\n , LEN(Body ) - LEN(replace(Body , ' ', '')) [count]\n , SUM(LEN(Body ) - LEN(replace(Body , ' ', ''))) \n OVER (ORDER BY id) [total count]\nFROM posts \nWHERE posts.OwnerUserId = @UserId\nORDER BY Id\n</code></pre>\n<p>I have started with your base query as found in the CURSOR but instead added the third column with an <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\"><code>OVER( ORDER BY id)</code> clause</a> which enables the calculation of running totals over sets. I'm a firm believer that when there is a feature available in the language it should be the preferred option, instead of running your own version in script. There is also a higher chance this gets better optimized by the query plan, if not today then possible in the future. Looking at wall-time and the query plan for your version and mine seems to support my gut feeling.</p>\n<p>If you want to address the neat trick there are different ways to solve that, for example by evaluation the answers on <a href=\"https://stackoverflow.com/questions/5794183/removing-repeated-duplicated-characters\">Removing repeated duplicated characters</a> but all of those have pros and cons and without confirmation if this is an area you want to have addressed I assume for now you're fine with your method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:57:34.813",
"Id": "244944",
"ParentId": "238517",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T06:18:10.557",
"Id": "238517",
"Score": "2",
"Tags": [
"sql",
"stackexchange"
],
"Title": "stat the word count for a given stackexchange user"
}
|
238517
|
<p>I am slowly digesting React.js, found couple of ways to write the same piece of code:
Please tell where all I went wrong in below code.</p>
<ol>
<li>I try to put logic inside <code>render()</code>, is that Ok?</li>
<li>Not using React life cycles for simple components?</li>
<li>Use Functional components instead of class components?</li>
</ol>
<p>File 1: batch_progress.js</p>
<p>Description: Shows batch progress, expects 3 values:</p>
<ol>
<li>current batch.</li>
<li>target batch count.</li>
<li>state of the batch (based on which the progress bar color changes). </li>
</ol>
<pre><code>import React, { Component } from 'react';
import ProgressBar from '../progress_bar/progress_bar';
export default class BatchStatus extends Component {
constructor(props) {
super(props);
}
render() {
let color;
let percentage = (this.props.batch.number / this.props.targetBatchCount) * 100;
switch (this.props.batch.status) {
case 100:
color = '#e7e4f1';
break;
case 200:
color = '#c3dcec';
break;
case 300:
color = '#ecc6eb';
break;
case 400:
color = '#ecdec3';
break;
case 500:
color = '#c8ecc7';
break;
default:
color = '#e7e4f1';
}
return (
<ProgressBar foregroundColor={color} percentage={percentage}>
{this.props.batch.number}&nbsp;/&nbsp;{this.props.targetBatchCount}
</ProgressBar>
);
}
}
</code></pre>
<p>File 2: progress_bar.js</p>
<pre><code>import React, { Component } from 'react';
import './progress_bar.css';
export default class ProgressBar extends Component {
constructor(props) {
super(props);
}
render() {
let foregroundColor = this.props.foregroundColor || '#e7e4f1';
let percentage = this.props.percentage || 0;
let backgroundColor = this.props.backgroundColor || '#eceeef';
let style = {
backgroundImage:
'linear-gradient(to right, ' +
foregroundColor +
' ' +
percentage +
'%, ' +
backgroundColor +
' 0%)'
};
return (
<div className="progress-bar-container" style={style}>
{this.props.children}
</div>
);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T08:25:06.403",
"Id": "467791",
"Score": "3",
"body": "Please edit your question to include some details of what the code Is supposed to do. Also a brief description should go to the title. People Are more likely to want to review a progrese bar in react than they want to review random shapeless react code that they dont know what should be doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T16:21:57.183",
"Id": "467989",
"Score": "2",
"body": "Your title is too generic. It should state what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T05:30:27.940",
"Id": "468018",
"Score": "0",
"body": "@BCdotWEB edited the question... if not good you can edit it as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:17:00.937",
"Id": "468049",
"Score": "2",
"body": "@Pure'ajax I don't know what your code does, you're supposed to tell us. The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:37:03.063",
"Id": "468053",
"Score": "0",
"body": "Ok Sure will do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T15:31:16.820",
"Id": "477126",
"Score": "1",
"body": "I [changed the title](https://codereview.stackexchange.com/posts/238518/revisions) 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."
}
] |
[
{
"body": "<p>The function <code>render()</code> in only supposed to <strong>render</strong>. It is not supposed to compute some style, set variables, have any logic other than <strong>render</strong>: (<a href=\"https://moderatemisbehaviour.github.io/clean-code-smells-and-heuristics/general/g30-functions-should-do-one-thing.html\" rel=\"noreferrer\">Functions Names Should Say What They Do</a>). This should respect the SRP (Single Responsiblity Principle), as well as another clean code rule: <a href=\"https://moderatemisbehaviour.github.io/clean-code-smells-and-heuristics/general/g30-functions-should-do-one-thing.html\" rel=\"noreferrer\">'A Function Should Do One Thing'</a>.</p>\n\n<p>What could be code smell in your first file:</p>\n\n<ul>\n<li>A unused constructor should not be there at all,</li>\n<li>The percentage calculation should be put in a function of its own</li>\n<li>The color choice should be placed in a function of its own</li>\n</ul>\n\n<p>What could be code smell in your second file:</p>\n\n<ul>\n<li>A unused constructor should be removed</li>\n</ul>\n\n<p>For both files, you could also add some prop types verifications using the library <a href=\"https://www.npmjs.com/package/prop-types\" rel=\"noreferrer\">'prop_types'</a>.</p>\n\n<p>As for your questions, with short answers:</p>\n\n<ol>\n<li>Not it's not Ok</li>\n<li>Depends on what you intend to do!</li>\n<li>This article should help you choose: <a href=\"https://programmingwithmosh.com/react/react-functional-components/\" rel=\"noreferrer\">React Functional or Class components ?</a> - even though you can use hooks now as well :)</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T12:07:28.727",
"Id": "467809",
"Score": "3",
"body": "welcome @Orlyyn - keep up the good work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T13:36:27.810",
"Id": "467882",
"Score": "0",
"body": "@Orlyyn So Whatever received in props, should it be updated to state variable in componentDidMount()?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:55:58.420",
"Id": "467930",
"Score": "0",
"body": "Short answer: No, because `componentDidMount` does not fire when your component receives updated props, so if you get updated props (like changed props overtime), your component won't update. Instead, you could use `componentDidUpdate`. However it also depends, again, on what you want to do..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T08:53:43.287",
"Id": "238523",
"ParentId": "238518",
"Score": "6"
}
},
{
"body": "<p>File 1: batch_progress.js</p>\n\n<pre><code>import React, { Component } from 'react';\nimport ProgressBar from '../progress_bar/progress_bar';\n\nexport default class BatchStatus extends Component {\n constructor(props) {\n super(props);\n this.state = {\n color: ''\n }\n }\n\n componentDidUpdate = (prevProps, prevState) => {\n if (this.props === prevProps) {\n return;\n }\n\n this.buildProgressBar();\n }\n\n componentDidMount = () => {\n this.buildProgressBar();\n }\n\n buildProgressBar = () => {\n let color;\n let percentage = (this.props.batch.number / this.props.targetBatchCount) * 100;\n\n switch (this.props.batch.status) {\n case 100:\n color = '#e7e4f1';\n break;\n case 200:\n color = '#c3dcec';\n break;\n case 300:\n color = '#ecc6eb';\n break;\n case 400:\n color = '#ecdec3';\n break;\n case 500:\n color = '#c8ecc7';\n break;\n default:\n color = '#e7e4f1';\n }\n\n this.setState({\n color: color,\n percentage: percentage\n })\n }\n\n render() {\n return (\n <ProgressBar foregroundColor={this.state.color} percentage={this.state.percentage}>\n {this.props.batch.number}&nbsp;/&nbsp;{this.props.targetBatchCount}\n </ProgressBar>\n );\n }\n}\n</code></pre>\n\n<p>File 2: progress_bar.js</p>\n\n<pre><code>import React, { Component } from 'react';\nimport './progress_bar.css';\n\nexport default class ProgressBar extends Component {\n render() {\n let foregroundColor = this.props.foregroundColor || '#e7e4f1';\n let percentage = this.props.percentage || 0;\n let backgroundColor = this.props.backgroundColor || '#eceeef';\n\n let style = {\n backgroundImage:\n 'linear-gradient(to right, ' +\n foregroundColor +\n ' ' +\n percentage +\n '%, ' +\n backgroundColor +\n ' 0%)'\n };\n\n return (\n <div className=\"progress-bar-container\" style={style}>\n {this.props.children}\n </div>\n );\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T13:24:07.417",
"Id": "238563",
"ParentId": "238518",
"Score": "1"
}
},
{
"body": "<p>The answer by <strong>Orlyyn</strong> explains it well. Just adding to it: </p>\n\n<ul>\n<li>You can probably destructure your variables, this helps with readability and reuse.</li>\n<li>Since you are not using the state of the class you can convert that into <code>Functional Component</code></li>\n<li>Use <code>template string</code> instead of doing it in bits.</li>\n<li>Still no need to add <code>this.state</code> and call <code>setState</code> in your <code>componentDidMount()</code>. What Orlyyn meant by <em>single responsibility principle</em> was that there shouldn't be any other <strong>logic</strong> in there, simply. You can still get the variables that you need for that function to work.</li>\n</ul>\n\n<p>The <code>State</code> is useful when you need to manipulate it within your very class or function.</p>\n\n<p>So, a refactor of your code <em>batch_progress.js</em> could be as following: </p>\n\n<pre><code>import React from 'react';\nimport PropTypes from 'prop-types';\nimport ProgressBar from '../progress_bar/progress_bar';\n\nconst statusCodeColors = {\n 100: '#e7e4f1',\n 200: '#c3dcec',\n 300: '#ecc6eb',\n 400: '#ecdec3',\n 500: '#c8ecc7',\n};\n\nconst getStatusColor = (code) => statusCodeColors[code] || '#e7e4f1';\nconst getPercentage = (num, total) => (num / total) * 100;\n\nconst BatchStatus = ({ batch: { number, status }, targetBatchCount }) => {\n const color = getStatusColor(status);\n const percentage = getPercentage(number, targetBatchCount);\n\n return (\n <ProgressBar foregroundColor={color} percentage={percentage}>\n {`${number} / ${targetBatchCount}`}\n </ProgressBar>\n );\n};\n\nBatchStatus.defaultProps = {\n batch: {\n number: 50,\n status: 100,\n },\n targetBatchCount: 100,\n};\n\nBatchStatus.propTypes = {\n batch: PropTypes.shape({\n number: PropTypes.number,\n status: PropTypes.number,\n }),\n targetBatchCount: PropTypes.number,\n};\n\nexport default BatchStatus;\n</code></pre>\n\n<p>Included the <code>prop-types</code> there. Might help you in getting started with it. Though react has a great <a href=\"https://reactjs.org/docs/typechecking-with-proptypes.html\" rel=\"nofollow noreferrer\">documentation</a> for it. </p>\n\n<p>I have also replaced your <code>switch-case</code> statement there with something more cleaner. You can read about it in following articles: </p>\n\n<ul>\n<li><a href=\"https://dev.to/potouridisio/probably-the-hottest-code-refactoring-you-ever-saw-3072\" rel=\"nofollow noreferrer\">\"Probably the hottest code refactor...\"</a></li>\n<li><a href=\"https://dev.to/tomazlemos/keeping-your-code-clean-by-sweeping-out-if-statements-4in8\" rel=\"nofollow noreferrer\">\"Keeping your code clean by sweeping out \"if\" statements\"</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:47:45.897",
"Id": "467928",
"Score": "0",
"body": "Orlyyn is a \"she\" ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:11:37.740",
"Id": "467978",
"Score": "0",
"body": "haha. my bad will edit that. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T15:27:09.970",
"Id": "238567",
"ParentId": "238518",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238523",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T07:42:19.827",
"Id": "238518",
"Score": "4",
"Tags": [
"react.js",
"jsx"
],
"Title": "batch progress visualization In React.js"
}
|
238518
|
<p>I just read about Wiki game on Wikipedia and wanted to implement it as a fun project for myself using python.</p>
<p>Task:To reach Mathematics Wikipedia page using wikipedia hyperlinks randomly.</p>
<p>Using Beautiful Soup documentation,I was able to create following crude code which is quite slow for my purpose.</p>
<pre><code>import random
import requests
from bs4 import BeautifulSoup
r = requests.get("https://en.wikipedia.org/wiki/Main_Page")
soup = BeautifulSoup(r.content)
a = [link.get('href') for link in soup.find_all('a')]
del a[0:6]
while(soup.title.text != 'Mathematics - Wikipedia'):
a = [link.get('href') for link in soup.find_all('a')]
del a[0:6]
if (a == []):
add = "/wiki/Special:Random"
else:
add = random.choice(a)
if(add == None):
add = random.choice(a)
url = "https://en.wikipedia.org/"+add
r = requests.get(url)
soup = BeautifulSoup(r.content)
print(soup.title.text)
</code></pre>
<p><strong>First,I would like to reduce the useless links that this program goes through such as About Wiki,user login,etc.</strong>
I knew I can simply use if-else statements but wanted to know if there is another simpler or faster implementation for it in beautiful soup or something else. </p>
<p><strong>Secondly,Any suggestions to improve code would be welcome including additional reading resources.</strong></p>
|
[] |
[
{
"body": "<p>Wikipedia has an API available. You can make calls to e.g. <code>\"https://en.wikipedia.org/w/api.php?action=query&prop=links&titles={title}&pllimit=500\"</code> and get back a list of titles the Wikipedia page <code>title</code> links to, without all the internal links (but with non-existing pages and things like categories).</p>\n\n<p>Incidentally, there is even a python package available that makes using it a lot easier, <a href=\"https://pypi.org/project/Wikipedia-API/\" rel=\"nofollow noreferrer\"><code>Wikipedia-API</code></a>. With this your code would become:</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup\nimport wikipediaapi\nimport random\nfrom itertools import count\n\nWIKI = wikipediaapi.Wikipedia('en')\n\ndef random_page():\n r = requests.get(\"https://en.wikipedia.org/wiki/Special:Random\")\n soup = BeautifulSoup(r.content)\n page = WIKI.page(soup.title.text[:-12])\n assert page.exists()\n return page\n\nBLACKLISTED = [\"Wikipedia:\", \"Category:\", \"Template:\", \"Template talk:\", \"User:\",\n \"User talk:\", \"Module:\", \"Help:\", \"File:\", \"Portal:\"]\ndef blacklisted(title):\n return any(title.startswith(x) for x in BLACKLISTED)\n\ndef random_walk(target_title):\n page = random_page()\n for i in count():\n print(i, page)\n if page.title == target_title:\n return i\n links = list(page.links.values())\n # print(f\"{len(links)} links\")\n if not links:\n return None\n page = random.choice(links)\n while blacklisted(page.title) or not page.exists():\n page = random.choice(links)\n\n\nif __name__ == \"__main__\":\n print(random_walk('Mathematics'))\n</code></pre>\n\n<p>This still needs to blacklist some pages (see <code>BLACKLISTED</code> constant, the content of which I found by trial-and-error) and I'm not quite happy about the trial and error way of getting a random page, but filtering for existing pages needs to fetch them all, which is quite slow.</p>\n\n<p>In any case, this <em>should</em> be a bit faster than actually getting the whole page and parsing it yourself.</p>\n\n<p>I also put the code into function and guarded the calling under a <code>if __name__ == \"__main__\":</code> to allow reusing of the code. In doing this I took the liberty of adding a counter and returning it in case the target page is found (12000 pages and counting...).</p>\n\n<hr>\n\n<p>Another question is if this is the best/most fun way to play this game. The way I know it, the goal is to reach a target page as fast as possible. In that case you will want to do a breadth-first search of all links instead (depth-first would fail because there are loops, meaning you could get lost forever). Although I have to admit, it is fun watching the bot and seeing where it wanders...</p>\n\n<p>A good compromise might be checking if any of the links on the current page is to Mathematics, and only randomly jumping to the next page if not.</p>\n\n<hr>\n\n<p>Some generic comments about your code:</p>\n\n<ul>\n<li>You don't need parenthesis around your conditions, and they are discouraged unless needed to make the condition span multiple lines.</li>\n<li>Empty lists are falsey, so you can replace <code>if (a == []):</code> with <code>if not a:</code>.</li>\n<li>Your code only tries twice to get a random page, which will work most of the time but will fail eventually. Instead use a <code>while</code> loop that continues indefinitely.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T18:34:26.600",
"Id": "467827",
"Score": "1",
"body": "Wouldn't it be `if not a:`, since `a` as an empty list will be`False`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T18:40:19.963",
"Id": "467828",
"Score": "0",
"body": "@Linny Indeed, fixed!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T19:55:11.410",
"Id": "467833",
"Score": "1",
"body": "Great answer!And to answer your question about the most fun way to play this game,I think,this is also a pretty fun just to see totally weird pages show up in your quest for Mathematics"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T14:44:29.247",
"Id": "238532",
"ParentId": "238519",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238532",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T08:25:14.480",
"Id": "238519",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Reach certain Wiki page through random links"
}
|
238519
|
<p>This script tries to parse <code>.csv</code> files and returns an iterable object to fetch one row at a time to do some process. It works fine but I think it needs improvements to make it efficient.</p>
<pre><code> import os
from csv import DictReader
class CSVHandler:
DELIMIT = ',' # delimiter for csv
FIELDS = set(list(['foo', 'bar'])) # fields that I want
def __init__(self, file_path: str):
self.file_path = file_path
self.file_obj = None
self.reader = DictReader([])
def read_file(self):
if self._is_file_ok:
try:
self.file_obj = open(self.file_path, newline='')
self.reader = DictReader(self.file_obj)
unmatched = self._is_fields_ok
if isinstance(unmatched, set):
print(f"Warning : field set's unmatched! {unmatched}")
except IOError:
print(f'Unable to open/read file : "{self.file_path}"')
else:
print(f'Invalid file : "{self.file_path}"')
return self
@property
def _is_file_ok(self):
if os.path.isfile(self.file_path):
if os.path.exists(self.file_path):
if self.file_path.endswith('.csv'):
return True
return False
@property
def _is_fields_ok(self):
if self.reader or not self.FIELDS:
return self.FIELDS - set(self.reader.fieldnames)
return False
def _trim_row(self, row: dict):
trimmed_row = dict.fromkeys(self.FIELDS, None)
for field in self.FIELDS:
if field in row:
trimmed_row[field] = row[field]
return trimmed_row
def __enter__(self):
return self
def __iter__(self):
return (self._trim_row(dict(row)) for row in self.reader)
def __next__(self):
return self._trim_row(dict(next(self.reader)))
def __len__(self):
return len(list(self.reader))
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file_obj is not None:
self.file_obj.close()
if __name__ == '__main__':
with CSVHandler('file_name.csv').read_file() as csv_h:
for rows in csv_h:
pass
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T10:40:38.670",
"Id": "467806",
"Score": "0",
"body": "Is using [pandas](https://pandas.pydata.org/pandas-docs/stable/) an option?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T10:41:35.687",
"Id": "467807",
"Score": "2",
"body": "Please consider adding your real code and telling us more about what it's doing and why you wrote it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T13:23:30.260",
"Id": "467814",
"Score": "0",
"body": "Could you also remove the request for help in your title. Asking for code imporvment is implied in all questions."
}
] |
[
{
"body": "<p>Welcome to CR!</p>\n\n<p>As others recommended, you need to be more clear. I can give you some stylistic critique.</p>\n\n<p>I like that you are using type hinting in the parameters. I recommend you also hint the return types for your functions like:</p>\n\n<pre><code>def _trim_row(self, row: dict) -> list:\n trimmed_row = dict.fromkeys(self.FIELDS, None)\n for field in self.FIELDS:\n if field in row:\n trimmed_row[field] = row[field]\n return trimmed_row\n</code></pre>\n\n<p>Now, more importantly I recommend you <a href=\"https://realpython.com/documenting-python-code/\" rel=\"nofollow noreferrer\">create strong documentation</a> for your code so that we can understand the idea behind it, what bugs it has, as well as its efficiency failures (you can use <a href=\"https://www.python.org/dev/peps/pep-0350/\" rel=\"nofollow noreferrer\">codetags</a> such as <code># BUG:</code> or <code># FIXME:</code>).</p>\n\n<p>For your convenience, you can also edit your code in an <a href=\"https://en.wikipedia.org/wiki/Pylint\" rel=\"nofollow noreferrer\">IDE that enables pylinting</a>, where you can get suggestions about how stylistically good your code is, I recommend VS Code with the <a href=\"https://marketplace.visualstudio.com/items?itemName=ms-python.python\" rel=\"nofollow noreferrer\">Python</a> and <a href=\"https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring\" rel=\"nofollow noreferrer\">autoDocstring</a> extensions. </p>\n\n<p>By putting your code in VS Code, I got the following suggestions for improvements:</p>\n\n<pre><code>\"\"\" [INSERT MODULE DESCRIPTION] \"\"\"\n\nimport os\nfrom csv import DictReader\n\n\nclass CSVHandler:\n \"\"\"[INSERT CLASS DESCRIPTION]\n \"\"\"\n DELIMIT = ',' # delimiter for csv\n FIELDS = set(list(['foo', 'bar'])) # fields that I want\n\n def __init__(self, file_path: str):\n \"\"\"[summary]\n\n Arguments:\n file_path {str} -- [description]\n \"\"\"\n self.file_path = file_path\n self.file_obj = None\n self.reader = DictReader([])\n\n def read_file(self):\n \"\"\"[summary]\n\n Returns:\n [type] -- [description]\n \"\"\"\n if self._is_file_ok:\n try:\n self.file_obj = open(self.file_path, newline='')\n self.reader = DictReader(self.file_obj)\n unmatched = self._is_fields_ok\n if isinstance(unmatched, set):\n print(f\"Warning : field set's unmatched! {unmatched}\")\n except IOError:\n print(f'Unable to open/read file : \"{self.file_path}\"')\n else:\n print(f'Invalid file : \"{self.file_path}\"')\n return self\n\n @property\n def _is_file_ok(self):\n \"\"\"[summary]\n\n Returns:\n [type] -- [description]\n \"\"\"\n if os.path.isfile(self.file_path):\n if os.path.exists(self.file_path):\n if self.file_path.endswith('.csv'):\n return True\n return False\n\n @property\n def _is_fields_ok(self):\n \"\"\"[summary]\n\n Returns:\n [type] -- [description]\n \"\"\"\n if self.reader or not self.FIELDS:\n return self.FIELDS - set(self.reader.fieldnames)\n return False\n\n def _trim_row(self, row: dict):\n \"\"\"[summary]\n\n Arguments:\n row {dict} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n trimmed_row = dict.fromkeys(self.FIELDS, None)\n for field in self.FIELDS:\n if field in row:\n trimmed_row[field] = row[field]\n return trimmed_row\n\n def __enter__(self):\n return self\n\n def __iter__(self):\n return (self._trim_row(dict(row)) for row in self.reader)\n\n def __next__(self):\n return self._trim_row(dict(next(self.reader)))\n\n def __len__(self):\n return len(list(self.reader))\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self.file_obj is not None:\n self.file_obj.close()\n\n\nif __name__ == '__main__':\n with CSVHandler('file_name.csv').read_file() as csv_h:\n for rows in csv_h:\n pass\n</code></pre>\n\n<p>Another suggestion that I can give you is to know what you are importing and import just what you need. So, <code>import os</code> should be replaced with <code>from os import path</code> and remove <code>os.</code> from <code>if os.path.isfile(self.file_path):</code> and <code>if os.path.exists(self.file_path):</code>.</p>\n\n<p>Following this, you will understand your code better, and you will be able to ask more specific questions about it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T03:46:49.920",
"Id": "467915",
"Score": "1",
"body": "Thank you, your suggestions helped me a lot"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T01:28:25.700",
"Id": "238546",
"ParentId": "238524",
"Score": "2"
}
},
{
"body": "<p>In a fully-fledged class, <code>DELIMIT</code> and <code>FIELDS</code> could have been defined as <strong>parameters</strong> rather than left hardcoded like this:</p>\n\n<pre><code>DELIMIT = ',' # delimiter for csv\nFIELDS = set(list(['foo', 'bar'])) # fields that I want\n</code></pre>\n\n<p>Regarding <strong>exception handling</strong>, I recommend that you keep the full details including the stack trace - you don't have to display it to the user but it's good to have a <strong>log</strong> somewhere to investigate errors. Debugging can be difficult if you have to rely only on what your program outputs. For example, if an <code>except IOError</code> is raised it will not be immediately apparent what happened: was it a permission issue or the file does not exist or something else ?</p>\n\n<p>Using the <code>logger</code> module you can output messages to <em>multiple destinations</em> at the same time, for example show a simplified message on the console but log more details to a file, also the <a href=\"https://docs.python.org/2/library/logging.html#levels\" rel=\"nofollow noreferrer\">logging levels</a> can be different for each destination.</p>\n\n<p>In this function <code>os.path.exists</code> is redundant, <code>isfile</code> will suffice:</p>\n\n<pre><code>def _is_file_ok(self):\n if os.path.isfile(self.file_path):\n if os.path.exists(self.file_path):\n if self.file_path.endswith('.csv'):\n return True\n return False\n</code></pre>\n\n<p>From the <a href=\"https://docs.python.org/3/library/os.path.html#os.path.isfile\" rel=\"nofollow noreferrer\">doc:</a></p>\n\n<blockquote>\n <p><em>os.path.isfile(path)</em></p>\n \n <p>Return True if path is an <strong>existing</strong> regular file. This follows symbolic\n links, so both islink() and isfile() can be true for the same path.</p>\n</blockquote>\n\n<p><code>isfile</code> and <code>endswith</code> are boolean functions, so you can directly return the result of the function. In a slightly more concise way:</p>\n\n<pre><code>def _is_file_ok(self):\n if os.path.isfile(self.file_path):\n return self.file_path.endswith('.csv')\n else:\n return False\n</code></pre>\n\n<p>On a final note, I also agree that Pandas would do the job fine with much less code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T03:57:15.903",
"Id": "467917",
"Score": "0",
"body": "great suggestions, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T04:15:00.310",
"Id": "467919",
"Score": "0",
"body": "I meant to ask if this approach is right to read .csv file and return an iterable. If an error occurs in any part of the script it should log and return an empty iterable"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T11:57:48.987",
"Id": "238561",
"ParentId": "238524",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T09:51:32.293",
"Id": "238524",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"csv"
],
"Title": "Read .csv files and convert the rows into dict for looping"
}
|
238524
|
<p>so i made a python program for my calculator's micro-python that lets you enter a value for any 3 of these variables</p>
<pre><code>s - displacement/distance
u - initial velocity
v - final velocity
a - acceleration
t - time
</code></pre>
<p>and returns the other two, and i know there are many repeated sections but i want to know how to make it more compact and efficient, and coding tricks.</p>
<p>oh and for your information, the stopper() function responds to the string "x" because the x button is very easily accessible on the calculator</p>
<pre class="lang-py prettyprint-override"><code># Original SUVAT equations
# v = u + at
# s = 0.5(u+v)*t
# v^2 = u^2 + 2a*s
# s = ut + 0.5at^2
from math import sqrt, pi
def input_pi_replacer(prompt):
return input(prompt).replace("pi", str(pi))
def stopper():
stop_or_continue = input("Stop?: ")
if stop_or_continue == "x":
raise SystemExit
print("Suvat Calculator:")
print("if variable not\ngiven then type\n'x'\n")
def suvatsolver():
while True:
# this will keep track of how many variables are known, since three are required.
variable_count = 0
[s_known, u_known, v_known, a_known, t_known] = [False, False, False, False, False]
distance = input_pi_replacer("Distance in metres\n: ")
# this assumes that the input is actually acceleration number.
# then it says the variable is known and adds 1 to the variable count.
if distance != "x":
s_known = True
distance = float(eval(distance))
variable_count += 1
initial_velocity = input_pi_replacer("Initial velocity\nin metres/second\n: ")
if initial_velocity != "x":
u_known = True
initial_velocity = float(eval(initial_velocity))
variable_count += 1
final_velocity = input_pi_replacer("Final velocity\n in metres/second\n: ")
if final_velocity != "x":
v_known = True
final_velocity = float(eval(final_velocity))
variable_count += 1
else:
pass
acceleration = input_pi_replacer("Acceleration\n in metres/second squared\n: ")
if acceleration != "x":
a_known = True
acceleration = float(eval(acceleration))
variable_count += 1
else:
pass
time = input_pi_replacer("Time\nin seconds\n: ")
if time != "x":
t_known = True
time = float(eval(time))
variable_count += 1
else:
pass
if variable_count < 3:
print("not enough variables")
break
# this next bunch of statements pretty much goes through
# all possible combinations of three variables
# and calculates the remaining unknowns (I solved the equations myself)
if s_known and u_known and v_known:
acceleration = (final_velocity ** 2 - initial_velocity ** 2) / (2 * distance)
time = 2 * distance / (initial_velocity + final_velocity)
print("")
print("Acceleration =\n", acceleration)
print("Time =\n", time)
elif s_known and u_known and a_known:
final_velocity = sqrt(initial_velocity ** 2 + 2 * acceleration * distance)
t1 = -initial_velocity / acceleration + sqrt(2 * acceleration * distance + initial_velocity ** 2) / acceleration
t2 = -initial_velocity / acceleration - sqrt(2 * acceleration * distance + initial_velocity ** 2) / acceleration
print("")
print("Final velocity =\n", final_velocity, "\nor ", -final_velocity)
print("Time =\n", t1, "\nor ", t2)
elif s_known and u_known and t_known:
final_velocity = 2 * distance / time - initial_velocity
acceleration = 2 * (distance - initial_velocity * time) / time ** 2
print("")
print("Final velocity =\n", final_velocity)
print("Acceleration =\n", acceleration)
elif s_known and v_known and a_known:
initial_velocity = sqrt(final_velocity ** 2 - 2 * acceleration * distance)
t1 = 2 * distance / (final_velocity + sqrt(final_velocity ** 2 - 2 * acceleration * distance))
t2 = 2 * distance / (final_velocity - sqrt(final_velocity ** 2 - 2 * acceleration * distance))
print("")
print("Initial velocity =\n", initial_velocity, "\nor", -initial_velocity)
print("Time =\n", t1, "\nor", t2)
elif s_known and v_known and t_known:
initial_velocity = 2 * distance / time - final_velocity
acceleration = (final_velocity - initial_velocity) / time
print("")
print("Initial velocity =\n", initial_velocity)
print("Acceleration =\n", acceleration)
elif s_known and a_known and t_known:
initial_velocity = (distance - 0.5 * acceleration * time ** 2) / time
final_velocity = initial_velocity + acceleration * time
print("")
print("Initial velocity =\n", initial_velocity)
print("Final velocity =\n", final_velocity)
elif u_known and v_known and a_known:
distance = (final_velocity ** 2 - initial_velocity ** 2) / (2 * acceleration)
time = (final_velocity - initial_velocity) / acceleration
print("")
print("Distance =\n", distance)
print("Time =\n", time)
elif u_known and v_known and t_known:
distance = 0.5 * (initial_velocity + final_velocity) * time
acceleration = (final_velocity - initial_velocity) / time
print("")
print("Distance =\n", distance)
print("Acceleration =\n", acceleration)
elif u_known and a_known and t_known:
final_velocity = initial_velocity + acceleration * time
distance = initial_velocity * time + 0.5 * acceleration * time ** 2
print("")
print("Final velocity =\n", final_velocity)
print("Distance =\n", distance)
elif v_known and a_known and t_known:
initial_velocity = final_velocity - acceleration * time
distance = 0.5 * (2 * final_velocity - acceleration * time) * time
print("")
print("Initial velocity =\n", initial_velocity)
print("Distance =\n", distance)
print("")
break
while True:
suvatsolver()
stopper()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T10:22:59.670",
"Id": "238526",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "a kinematics(suvat) equation solver for micropython"
}
|
238526
|
<p>I made a program for my calculator for A levels that acquires the value of the angle and radius of a sector and gives:</p>
<ol>
<li>Area of Sector</li>
<li>Area of inner Triangle</li>
<li>Arc Length</li>
<li>Chord Area</li>
<li>Chord Length</li>
<li>Sector Perimeter</li>
</ol>
<p>I need some advice on compacting and making it more efficient, it would be also nice to have some coding tricks.</p>
<p>Disclaimer: my calculator uses <a href="https://micropython.org/" rel="nofollow noreferrer"><strong>micropython</strong></a> which lacks alot of functions, and modules however some functions from <code>math</code> work, check the documentary about it to confirm.</p>
<pre class="lang-py prettyprint-override"><code>from math import pi, sin
def input_pi_replacer(prompt):
return float(eval(input(prompt).replace("pi", str(pi))))
def stopper():
stop_or_continue = input("Stop?: ")
if stop_or_continue == "x":
raise SystemExit
print("Sector Quantities\nCalculator:\n")
C_Factor = 0
Area = 0
B = 0
while True:
C_Factor = 0
Area = 0
Unit = ""
# + = degrees , - = radians
while Unit not in ['+', '-']:
Unit = input("For Deg, enter '+',\nFor Rad, enter '-'\n: ")
if Unit == "+":
C_Factor = pi/180
break
elif Unit == "-":
C_Factor = 180/pi
break
elif Unit == ".":
raise SystemExit
# R = Radius, A = theta/angle in deg/rads, C_Angle = Converted Angle, C_Factor = Conversion Factor of Angle
R = input_pi_replacer("\nEnter Radius: ")
A = input_pi_replacer("Enter Theta/Angle: ")
if Unit == "+":
C_Angle = A * C_Factor
Angle_In_Deg = A
elif Unit == "-":
C_Angle = A
Angle_In_Deg = A * C_Factor
print()
Sector_Area = 1/2 * (R**2) * C_Angle
Triangle_Area = 1/2 * (R**2) * sin(C_Angle)
Arc_Length = R * C_Angle
Chord_Area = Sector_Area - Triangle_Area
Chord_Length = 2 * R * sin(C_Angle/2)
Perimeter_Sector = 2 * R + Arc_Length
print("Area of Sector\n= ", Sector_Area)
print("Area of inner Triangle\n= ", Triangle_Area)
print("Arc Length\n= ", Arc_Length)
print("Chord Area\n= ", Chord_Area)
print("Chord Length\n= ", Chord_Length)
print("Sector Perimeter\n= ", Perimeter_Sector)
print()
stopper()
</code></pre>
|
[] |
[
{
"body": "<h1>Naming</h1>\n\n<p>Variable and function names should be <code>snake_case</code>, not <code>This_Format</code> or <code>This</code>. <code>Uppercase</code> and <code>PascalCase</code> are reserved for class names.</p>\n\n<h1>Checking inside lists vs strings</h1>\n\n<p>If you're checking for a single character, it's better to use a string rather than a list. Have a look:</p>\n\n<pre><code>if unit in \"+-\":\n ...\n</code></pre>\n\n<h1>The walrus operator</h1>\n\n<p>If you're using <code>python-3.8</code> you can use the walrus operator. It's another way of saying assignment expressions. It's a way to assign a variable within an expression. In your case, you can utilize the walrus operator to assign <code>input</code> to a variable, and use that. Have a look:</p>\n\n<pre><code>while unit := input(\"For Degrees, enter '+',\\nFor Radians, enter '-'\\n: \"):\n if unit in \"+-\":\n ...\n</code></pre>\n\n<p>So <code>unit</code> is assigned whatever the output of the <code>input</code> call is.</p>\n\n<h1>Unneeded function</h1>\n\n<p>If your function is simply an <code>input</code> call, you don't really need it. Just put it at the end of the <code>while</code> loop.</p>\n\n<h1>Ternary operators</h1>\n\n<p>You can use these to greatly shorten the length of your code. It's an easier way to assign values based on conditions. Take a look at the final code to see what I'm saying.</p>\n\n<h1>f-strings</h1>\n\n<p>You should use <code>f\"\"</code> to directly implement variables in your strings. It's a cool feature that keeps you from having to <code>+</code> or call a <code>.format</code> on your strings. Have a look:</p>\n\n<pre><code>print(f\"Area of Sector = {sector_area}\")\nprint(f\"Area of inner Triangle = {triangle_area}\")\n...\n</code></pre>\n\n<h1>Final code</h1>\n\n<p>After all these suggestions, you code would look something like this:</p>\n\n<pre><code>from math import pi, sin\n\ndef input_pi_replacer(prompt):\n return float(eval(input(prompt).replace(\"pi\", str(pi))))\n\nprint(\"Sector Quantities Calculator:\\n\")\nwhile True:\n\n while unit := input(\"For Degrees, enter '+',\\nFor Radians, enter '-'\\n: \"):\n if unit in \"+-.\":\n if unit == \".\":\n raise SystemExit\n c_factor = (pi / 180) if unit == \"+\" else (180 / pi)\n break\n\n radians = input_pi_replacer(\"\\nEnter Radius: \")\n angle = input_pi_replacer(\"Enter Theta/Angle: \")\n\n c_angle = angle * c_factor if unit == \"+\" else angle\n\n print()\n sector_area = 1 / 2 * (radians ** 2) * c_angle\n triangle_area = 1 / 2 * (radians ** 2) * sin(c_angle)\n arc_length = radians * c_angle\n chord_area = sector_area - triangle_area\n chord_length = 2 * radians * sin(c_angle / 2)\n perimeter_sector = 2 * radians + triangle_area\n\n print(f\"Area of Sector = {sector_area}\")\n print(f\"Area of inner Triangle = {triangle_area}\")\n print(f\"Arc Length = {arc_length}\")\n print(f\"Chord Area = {chord_area}\")\n print(f\"Chord Length = {chord_length}\")\n print(f\"Sector Perimeter = {perimeter_sector}\")\n print()\n\n if input(\"Stop?: \").lower() == \"x\":\n raise SystemExit \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T23:30:49.223",
"Id": "470251",
"Score": "0",
"body": "hmm walrus operator, thats new, and fyi micropython doesn't support f\" strings, its sad i know, however thanks for the rest!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:47:54.873",
"Id": "239643",
"ParentId": "238527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T10:58:59.190",
"Id": "238527",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "A geometry Sector Solver, Value finder for my calculator's micropython"
}
|
238527
|
<p>I'm fairly new to Scala and I would like to learn it properly. My current task is to create a type to represent a heap, as seen in interpreters: a mapping from addresses in memory to values stored there. </p>
<p>A heap of that kind is very much like Map, but I would like to hide implementation details and only expose the interface consisting of a few methods, which in pseudo code would be:</p>
<pre><code>* update :: address value -> Heap
* free :: address -> Heap
* alloc :: value -> (Heap, Address)
* addresses :: () -> Set[Address]
* lookup :: address -> [Value]
</code></pre>
<p>Here is what I came up with:</p>
<pre><code>trait Heap[T] {
def update(address: Address, value: T): Heap[T]
def free(address: Address): Heap[T]
def alloc(value: T): (Heap[T], Address)
def addresses(): Set[Address]
def lookup(address: Address): Option[T]
}
private case class HeapImpl[T](map: Map[Address, T]) extends Heap[T] {
override def update(address: Address, value: T): Heap[T] = HeapImpl[T](map.updated(address, value))
override def free(address: Address): Heap[T] = HeapImpl[T](map.removed(address))
override def alloc(value: T): (Heap[T], Address) = {
val nextFreeAddress = addresses().maxOption.getOrElse(0) + 1
(HeapImpl(map.updated(nextFreeAddress, value)), nextFreeAddress)
}
override def addresses(): Set[Address] = map.keys.toSet
override def lookup(address: Address): Option[T] = map.get(address)
}
object Heap {
def apply[T](): Heap[T] = HeapImpl(Map())
}
</code></pre>
<p>I would like to know if this is proper idiomatic Scala or should I approach it differently. </p>
|
[] |
[
{
"body": "<p>Your code, as posted, doesn't compile because there is no definition for the <code>Address</code> type. However, given the code for <code>nextFreeAddress</code> in the <code>alloc()</code> method, it's pretty obvious that <code>Address</code> can only be type <code>Int</code>, so that's easy to fix.</p>\n\n<p>Also, <code>HeapImpl</code> is <code>private</code> to ... what? A surrounding <code>object</code> I assume, but that's also missing from the posted code so it's a bit unclear. You say you \"would like to hide implementation details,\" which is a good thing, but I don't know that a private implementation class is significantly more hidden than having private members of a public class. Is the implementation class separate because you envision multiple different implementations available to the end user?</p>\n\n<p>It's a bit unusual to have a factory method that takes no parameters except for a type parameter. It wouldn't be difficult to enhance the \"constructor\" to take optional initial values.</p>\n\n<pre><code>object Heap {\n def apply[T](ts:T*): Heap[T] = HeapImpl(ts.indices.map(x => x -> ts(x)).toMap)\n}\n</code></pre>\n\n<p>Then you can have it both ways:</p>\n\n<pre><code>Heap[Char]() //res0: Heap[Char] = HeapImpl(Map())\nHeap(3L, 5L, 12L, 2L) //res1: Heap[Long] = HeapImpl(Map(0 -> 3, 1 -> 5, 2 -> 12, 3 -> 2))\n</code></pre>\n\n<p>(Notice that the REPL has leaked a bit of your implementation detail.)</p>\n\n<p>At first I was confused by the term <code>Heap</code>. Then I re-read the posting and realized that this isn't a <a href=\"https://en.wikipedia.org/wiki/Heap_(data_structure)\" rel=\"nofollow noreferrer\">heap data structure</a> but is, instead, a chunk of memory for dynamic allocation and requiring <a href=\"https://en.wikipedia.org/wiki/Memory_management\" rel=\"nofollow noreferrer\">memory management</a>.</p>\n\n<p>But your code doesn't actually do any of the things that makes a real heap challenging/interesting: dynamic allocation for heterogeneous data, handle fragmentation, etc. It sort of <em>pretends</em> to be a heap, but not very convincingly (your <code>alloc()</code> doesn't really act like <code>malloc()</code>, <code>calloc()</code>, or <code>realloc()</code>). It's just a thin wrapper around a highly restricted <a href=\"https://en.wikipedia.org/wiki/Associative_array\" rel=\"nofollow noreferrer\">associative array</a>.</p>\n\n<p>So, while I find little to fault in the code, I can't see where it serves much purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:42:46.380",
"Id": "468203",
"Score": "0",
"body": "\"Also, HeapImpl is private to ... what? A surrounding object I assume\" -- The package. This is what I have at the top level in a file, the only thing missing was a package declaration. \n\nAnyway, thanks! Good point that I might have as well have a class with public methods instead of a trait (since I don't expect alternative implementations)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T08:19:30.760",
"Id": "238698",
"ParentId": "238528",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238698",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T11:03:35.477",
"Id": "238528",
"Score": "4",
"Tags": [
"scala"
],
"Title": "A simple data class based on an existing collection (Scala)"
}
|
238528
|
<p>Most of my development experience is in the .NET world. I started learning Golang again a few months ago, and decided to build a super simple flashcard app.</p>
<p>This project was mainly to get used to golang syntax, some common idiosyncrasies and conventions, improve my ability to locate code smells etc.</p>
<p>The code is split into two code files, and reads data from a txt file (I have provided a sample file for reference).</p>
<p>I am trying to improve my Golang programming skills (and wider programming skills in general), so please let me know if I can make any improvements.</p>
<p><strong>main.go</strong></p>
<pre><code>package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strconv"
"strings"
)
const FlashcardFilePath = "flashcards.txt"
type Flashcard struct {
Definition string
Answer string
}
type UserFlashcard struct {
Definition string
Answer string
UserAnswer string
}
func main() {
quit := false
for !quit {
//Flashcards should be loaded on each menu "tick"
flashcards := GetFlashcards()
switch GetMenuItem() {
case 1:
CreateFlashcard()
case 2:
PracticeFlashcards(flashcards)
case 3:
DisplayFlashcards(flashcards)
case 4:
quit = true
}
}
}
func CreateFlashcard() {
fmt.Println()
definition := GetUserInput("Definition: ")
answer := GetUserInput("Answer: ")
WriteFlashcardToFile(Flashcard{
Definition: definition,
Answer: answer,
})
fmt.Println()
fmt.Println("Flashcard created")
fmt.Println()
}
func GetFlashcards() []Flashcard {
stream := string(ReadFlashcardStreamFromFile())
return ParseFlashcardsFromString(stream)
}
func PracticeFlashcards(flashcards []Flashcard) {
numberOfQuestions, err := strconv.Atoi(strings.Trim(GetUserInput("Enter the number of questions you would like: "), "\r\n"))
var correctFlashcards []Flashcard
var incorrectFlashcards []UserFlashcard
HandleError(err)
if numberOfQuestions == 0 {
return
}
for i := 0; i < numberOfQuestions; i++ {
randomFlashcard := flashcards[rand.Intn(len(flashcards))]
result, answer := AskQuestion(randomFlashcard)
if result {
correctFlashcards = append(correctFlashcards, randomFlashcard)
} else {
incorrectFlashcards = append(incorrectFlashcards, ConvertFlashcardToUserFlashcard(randomFlashcard, answer))
}
}
ShowGameReport(correctFlashcards, incorrectFlashcards)
}
func ConvertFlashcardToUserFlashcard(flashcard Flashcard, userAnswer string) UserFlashcard {
return UserFlashcard {
Answer: flashcard.Answer,
Definition: flashcard.Definition,
UserAnswer: userAnswer,
}
}
///This returns whether the user correctly answered the question or not
func AskQuestion(flashcard Flashcard) (bool, string) {
fmt.Println("Definition: ", flashcard.Definition)
userAnswer := GetUserInput("Answer: ")
return CheckAnswer(flashcard.Answer, userAnswer), userAnswer
}
func CheckAnswer(correctAnswer string, userAnswer string) bool {
return strings.EqualFold(strings.TrimSpace(correctAnswer), strings.TrimSpace(userAnswer))
}
func ShowGameReport(correctFlashcards []Flashcard, incorrectFlashcards []UserFlashcard) {
fmt.Println()
fmt.Println()
fmt.Println("~~~~~~~~~~Report~~~~~~~~~~")
fmt.Println()
fmt.Println("You got ", len(correctFlashcards), " correct and ", len(incorrectFlashcards), " incorrect.")
if len(correctFlashcards) > 0 {
fmt.Println("~~~Correct Answers~~~")
for _, correct := range correctFlashcards {
fmt.Println(" Definition: ", correct.Definition)
fmt.Println(" Answer: ", correct.Answer)
}
}
if len(incorrectFlashcards) > 0 {
fmt.Println("~~~Incorrect answers~~~")
for _, incorrect := range incorrectFlashcards {
fmt.Println(" Definition: ", incorrect.Definition)
fmt.Println(" Answer: ", incorrect.Answer)
fmt.Println(" Your answer: ", incorrect.UserAnswer)
}
}
fmt.Println()
fmt.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~")
fmt.Println()
fmt.Println()
}
func DisplayFlashcards(flashcards []Flashcard) {
fmt.Println()
fmt.Println("~~~~~~~~~~~~~~~~~~ F L A S H C A R D S ~~~~~~~~~~~~~~~~~~")
for _, card := range flashcards {
fmt.Println(" ")
for i := 0; i < 25-len(card.Definition); i++ {
//Formatting - pad left
fmt.Print(" ")
}
fmt.Printf(card.Definition)
fmt.Print(" means ", card.Answer)
}
fmt.Println()
fmt.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
fmt.Println()
GetUserInput("Finished?")
}
func GetMenuItem() int {
PrintMenu()
input := GetUserInput("Numeric option: ")
option, err := strconv.Atoi(input[0:1])
HandleError(err)
return option
}
func PrintMenu() {
fmt.Println("=======================")
fmt.Println(" M E N U ")
fmt.Println("=======================")
fmt.Println("1. Create new flashcard")
fmt.Println("2. Practice flashcard")
fmt.Println("3. Display all flashcards")
fmt.Println("4. Quit program")
}
func ReadFlashcardStreamFromFile() []byte {
file, err := os.Open(FlashcardFilePath)
HandleError(err)
defer file.Close()
b, err := ioutil.ReadAll(file)
return b
}
func ParseFlashcardsFromString(input string) []Flashcard {
lines := strings.Split(input, ",")
var flashcards []Flashcard
for line := 0; line < len(lines)-1; line++ {
flashcards = append(flashcards, ParseSingleFlashcard(lines[line]))
}
return flashcards
}
func ParseSingleFlashcard(input string) Flashcard {
parts := strings.Split(input, "|")
if parts != nil && len(parts) > 0 {
return Flashcard{
Definition: strings.TrimSpace(parts[0]),
Answer: strings.TrimSpace(parts[1]),
}
}
fmt.Println("Error: empty string was passed into ParseSingleFlashcard")
var f Flashcard
return f
}
func WriteFlashcardToFile(flashcard Flashcard) {
text := BuildFlashcardString(flashcard)
AppendLineToFile(FlashcardFilePath, text)
}
func BuildFlashcardString(flashcard Flashcard) string {
return flashcard.Definition + " | " + flashcard.Answer + ","
}
func AppendLineToFile(filepath string, line string) {
f, err := os.OpenFile(filepath, os.O_APPEND|os.O_WRONLY, 0644)
HandleError(err)
_, err = fmt.Fprintln(f, line)
HandleError(err)
err = f.Close()
HandleError(err)
}
</code></pre>
<p><strong>utility.go</strong></p>
<pre><code>package main
import (
"bufio"
"fmt"
"os"
)
func GetUserInput(promptText string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Print(promptText)
input, _ := reader.ReadString('\n')
return input
}
func HandleError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(2)
}
}
</code></pre>
<p><strong>Flashcards.txt</strong></p>
<pre><code>Heiße
| Hot
,
Frei
| Free
,
Flugzeug
| Airplane
,
Essen
| Food
,
Spielzeug
| Toy
,
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T13:23:53.603",
"Id": "238531",
"Score": "2",
"Tags": [
"game",
"console",
"go"
],
"Title": "Flashcard app in Golang"
}
|
238531
|
<p>A student was having problems with memory management so I put together an overload of global <code>operator new</code> and global <code>operator delete</code> to explicitly check for memory leaks and freeing invalid memory. This uses <code>boost/stacktrace.hpp</code> to point out exactly where you messed up. It is just for educational and possibly debugging purposes:</p>
<pre><code>#include <boost/stacktrace.hpp> // boost::stacktrace
#include <cstdio> // fprintf
#include <type_traits> // decay_t
#include <unordered_map> // unordered_map
#include <utility> // move
// An allocator that uses malloc as its memory source
#include "MallocAllocator.h"
// Hash map that uses malloc to avoid infinite recursion in operator new
template<typename Key, typename T>
using MallocHashMap =
std::unordered_map<Key,
T,
std::hash<Key>,
std::equal_to<Key>,
MallocAllocator<std::pair<const Key, T>>>;
// Stack trace that uses malloc to avoid infinite recursion in operator new
using MallocStackTrace = boost::stacktrace::basic_stacktrace<
MallocAllocator<boost::stacktrace::frame>>;
// Memory allocation info with, address, size, stackTrace
struct MemoryAllocation
{
// the constructor is so that we can use emplace in unordered_map
MemoryAllocation(void const* const address_,
std::size_t const size_,
MallocStackTrace trace_) noexcept
: address{ address_ }
, size{ size_ }
, stackTrace{ std::move(trace_) }
{}
void const* address;
std::size_t size;
MallocStackTrace stackTrace;
};
// new/delete -> Object vs new[]/delete[] -> Array
enum class AllocationType
{
Object,
Array,
};
// returns AllocationType::Object for AllocationType::Array and
// AllocationType::Array for AllocationType::Object
static constexpr AllocationType
otherAllocType(AllocationType const at) noexcept
{
switch (at) {
case AllocationType::Object:
return AllocationType::Array;
case AllocationType::Array:
return AllocationType::Object;
}
}
// Keeps track of the memory allocated and freed.
template<AllocationType at>
static MallocHashMap<void*, MemoryAllocation>&
get_mem_map()
{
struct Mem // wrapper around std::unordered_map to check for memory leaks in
// destructor
{
std::decay_t<decltype(get_mem_map<at>())> map; // return type
~Mem() noexcept
{
if (!map.empty()) { // If map isn't empty, we've leaked memory.
for (auto const& p : map) {
auto const& memAlloc = p.second;
std::fprintf(stderr,
"-------------------------------------------------------"
"----------\n"
"Memory leak! %zu bytes. Memory was allocated in\n%s"
"-------------------------------------------------------"
"----------\n\n",
memAlloc.size,
to_string(memAlloc.stackTrace).c_str());
}
}
}
};
static Mem mem;
return mem.map;
}
// test if the memory was allocated with new or new[]
template<AllocationType at>
static bool
allocatedAs(void* const ptr)
{
auto& memmap = get_mem_map<at>();
auto const it = memmap.find(ptr);
return it != memmap.end();
}
template<AllocationType at>
static void* // template for new and new[]
new_base(std::size_t const count)
{
void* p = std::malloc(count);
if (!p)
throw std::bad_alloc{};
auto& mem_map = get_mem_map<at>();
mem_map.emplace(std::piecewise_construct,
std::forward_as_tuple(p),
std::forward_as_tuple(p, count, MallocStackTrace{ 3, 100 }));
return p;
}
template<AllocationType at>
static void // template for delete and delete[]
delete_base(void* const ptr) noexcept
{
if (ptr) { // it's fine to delete nullptr
if (!allocatedAs<at>(ptr)) { // check for invalid memory free
std::fprintf(
stderr,
"-----------------------------------------------------------------\n"
"Invalid memory freed memory at %p\n",
ptr);
if (allocatedAs<otherAllocType(at)>(ptr)) {
auto constexpr myNew = at == AllocationType::Object ? "" : "[]";
auto constexpr otherNew = at == AllocationType::Array ? "" : "[]";
std::fprintf(
stderr,
"\tNote: this memory was allocated with `new%s` but deleted with "
"`delete%s` instead of `delete%s`\n",
otherNew,
myNew,
otherNew);
}
std::fprintf(
stderr,
"%s\n---------------------------------------------------------"
"--------\n\n",
to_string(MallocStackTrace{ 3, 100 }).c_str());
std::_Exit(-1); // If we've messed up, exit
}
std::free(ptr); // free the pointer
get_mem_map<at>().erase(ptr); // remove from the map
}
}
void*
operator new(std::size_t const count)
{
return new_base<AllocationType::Object>(count);
}
void*
operator new[](std::size_t const count)
{
return new_base<AllocationType::Array>(count);
}
void
operator delete(void* const ptr) noexcept
{
delete_base<AllocationType::Object>(ptr);
}
void
operator delete[](void* const ptr) noexcept
{
delete_base<AllocationType::Array>(ptr);
}
</code></pre>
<p><code>MallocAllocator</code> is a simple allocator that uses <code>malloc</code> to avoid <code>operator new</code> calling itself recursively for it's own bookkeeping purposes. Here's <code>MallocAllocator.h</code>:</p>
<pre><code>#ifndef MALLOC_ALLOCATOR_H
#define MALLOC_ALLOCATOR_H
#pragma once // Won't hurt
#include <cstdlib> // malloc/free
#include <stdexcept> // bad_alloc
template<class T>
struct MallocAllocator
{
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = T;
MallocAllocator() noexcept = default;
MallocAllocator(const MallocAllocator&) noexcept = default;
template<class U>
MallocAllocator(const MallocAllocator<U>&) noexcept
{}
~MallocAllocator() noexcept = default;
T* allocate(size_type const s, void const* = nullptr) const
{
if (s == 0)
return nullptr;
T* temp = static_cast<T*>(std::malloc(s * sizeof(T)));
if (!temp)
throw std::bad_alloc();
return temp;
}
void deallocate(T* p, size_type) const noexcept { std::free(p); }
};
#endif // !MALLOC_ALLOCATOR_H
</code></pre>
<p>I am well aware that this is not thread-safe because of the static map. This should be enough for simple debugging and educational purposes, but I'd be happy to hear if you have comments about improving thread-safety.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T02:45:13.373",
"Id": "467851",
"Score": "0",
"body": "Just curious: why `#pragma once // Won't hurt` + manual include guards?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T08:37:05.823",
"Id": "467855",
"Score": "0",
"body": "@L. F. It speeds up the compilation a tiny bit sometimes. https://stackoverflow.com/a/1144110/10147399"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:20:03.793",
"Id": "467934",
"Score": "1",
"body": "You do know that Valgrind is already a much more capable memory allocation debugger (and more)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:38:07.063",
"Id": "467950",
"Score": "0",
"body": "@TobySpeight not if you are on Windows..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:43:36.350",
"Id": "467951",
"Score": "0",
"body": "Does Windows not have an equivalent? I can't imagine it's much good as a development platform if it doesn't come with something similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:46:38.593",
"Id": "467952",
"Score": "0",
"body": "@TobySpeight I bountied [this](https://stackoverflow.com/q/4790564/10147399) question a couple of days ago, still no suggestions. I don't claim Windows is great to develop on. It's just what most users use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T20:58:10.963",
"Id": "467999",
"Score": "1",
"body": "@Ayxan Maybe most users \"you\" know. I would argue that it is a minor platform compared to Linux. Most people I know build services and Windows machines are non existing in all of the work places I have worked in 15 years. (Note: I am not saying that windows is not used. I am pointing out my view is as biased as yours because of what I see around me :-) )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:01:44.753",
"Id": "468001",
"Score": "0",
"body": "@MartinYork we can look up [last year's survey](https://insights.stackoverflow.com/survey/2019#technology-_-developers-primary-operating-systems) to see what most developers use: Windows 47.5%. Unbiased hard data :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:02:53.347",
"Id": "468002",
"Score": "0",
"body": "@MartinYork In any case, I meant to say it's what most (non-developer) desktop users use. So someone has to develop Windows software."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:59:30.330",
"Id": "468007",
"Score": "0",
"body": "@Ayxan Why do you think MS built a Javascript layer on top of Windows. Its so you can write Windows applications in Javascript with knowing low level languages like C++"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T22:08:03.597",
"Id": "468008",
"Score": "0",
"body": "@MartinYork Well, yes. That's a pity though. Windows applications written in JavaScript (looking at you, Visual Studio Code) are terribly slow and inefficient. If a text editor uses 2GB of RAM to display text, I'd rather not use it."
}
] |
[
{
"body": "<pre><code>MallocAllocator(const MallocAllocator&) noexcept = default;\n//...\n~MallocAllocator() noexcept = default;\n</code></pre>\n\n<p>These two will be defined implicitly anyway. I suggest following the rule-of-zero and not declaring them at all. It will not make a difference here, but as general rule this is relevant, because e.g. the declared destructor inhibits declaration of the implicit move operations.</p>\n\n<hr>\n\n<p>The <em>Allocator</em> requirements require that <code>MallocAllocator<T></code> and <code>MallocAllocator<U></code> be comparable with <code>==</code> and <code>!=</code> and that the comparison indicates whether the two instances can be used to deallocate the other's allocations. So you should add:</p>\n\n<pre><code>template<class T, class U>\nbool operator==(MallocAllocator<T> const&, MallocAllocator<U> const&) noexcept\n{\n return true;\n}\n\ntemplate<class T, class U>\nbool operator!=(MallocAllocator<T> const&, MallocAllocator<U> const&) noexcept\n{\n return false;\n}\n</code></pre>\n\n<p>(or similar)</p>\n\n<hr>\n\n<p>You probably should add</p>\n\n<pre><code>using propagate_on_container_move_assignment = std::true_type;\n</code></pre>\n\n<p>to <code>MallocAllocator</code>. Otherwise containers cannot generally statically assert that moving a container with this allocator does not require reallocation.</p>\n\n<hr>\n\n<pre><code>static constexpr AllocationType\notherAllocType(AllocationType const at) noexcept\n{\n switch (at) {\n case AllocationType::Object:\n return AllocationType::Array;\n case AllocationType::Array:\n return AllocationType::Object;\n }\n}\n</code></pre>\n\n<p>This function is ill-formed in C++11, because control flow statements like <code>switch</code> were not allowed in <code>constexpr</code> functions. You would need to rewrite it as single return statement using the conditional operator.</p>\n\n<hr>\n\n<pre><code>std::decay_t<decltype(get_mem_map<at>())> map;\n</code></pre>\n\n<p>This is also ill-formed in C++11, because the <code>_t</code> helpers for type traits were only introduced in C++14. So use</p>\n\n<pre><code>typename std::decay<decltype(get_mem_map<at>())>::type map;\n</code></pre>\n\n<p>instead. In either case this looks very awkward to me and I would probably rather alias the type and type it twice, or if you decide to drop the C++11 support in favor of C++14, you might want to consider making the return type <code>auto&</code> and spelling out the type for <code>map</code> instead.</p>\n\n<hr>\n\n<pre><code> if (!map.empty()) { // If map isn't empty, we've leaked memory.\n</code></pre>\n\n<p>The test is redundant. I don't think it really improves readability either.</p>\n\n<hr>\n\n<pre><code>MallocStackTrace{ 3, 100 }\n</code></pre>\n\n<p>These are magic constants that should be defined as named variables instead. Probably it would also be a good idea to wrap this construction into a function that doesn't take any parameters or has defaulted parameters, given that it is used twice.</p>\n\n<hr>\n\n<p>Your approach using a local <code>static</code> to construct and destruct the allocation map is not always safe when other static storage duration objects are used. Consider for example the test program:</p>\n\n<pre><code>std::vector x;\n\nint main() {\n x.push_back(1);\n}\n</code></pre>\n\n<p>The initialization of <code>x</code> will (dependent on the implementation) probably not call <code>operator new</code>, because no allocation is needed yet.\nThen <code>push_back</code> requires allocation and calls <code>operator new</code> for the first time, constructing the corresponding <code>static Mem mem;</code>.</p>\n\n<p>Now <code>x</code>'s construction has completed before <code>mem</code>'s and so <code>mem</code> will be destroyed before <code>x</code> will. This causes the allocation done by <code>x</code> to be reported as memory leak and it also causes undefined behavior when the destructor of <code>x</code> is called, because it will access <code>mem</code> when its lifetime has already ended.</p>\n\n<p>I am not sure whether there is any way to completely avoid this though.</p>\n\n<p>The best I can think of is to mimic <code>#include<iostream></code>'s behavior and require that all translation units include a header file at the beginning which contains dummy global static objects that call <code>get_mem_map</code> for both allocation types in their initializer, but even then there may be static storage duration objects with unordered dynamic initialization, e.g. in class template specializations, which may execute before those.</p>\n\n<hr>\n\n<p>For thread-safety, assuming performance isn't really important, I would suggest simply to use a single global mutex and to scope-lock it in both <code>delete_base</code> and <code>new_base</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T04:53:20.013",
"Id": "467853",
"Score": "2",
"body": "Hi walnut, welcome to Code Review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T03:45:56.717",
"Id": "238548",
"ParentId": "238533",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238548",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T16:27:51.580",
"Id": "238533",
"Score": "6",
"Tags": [
"c++",
"c++11",
"memory-management"
],
"Title": "Safe new/delete"
}
|
238533
|
<p>I am playing with learning PowerShell classes, and I have a validation situation that kind of lends itself to Enums, as shown in the first example.
<strong>With Enum</strong></p>
<pre><code>Enum pxPathType {
FileSystem_Folder = 0
FileSystem_File = 1
Registry_Key = 2
Registry_Property = 3
}
class PxConstant {
# Static Properties
static [string] $RegExPathWithWildcard = '\\\*\.\*$|\\\*|\\.\.\*$|\*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.\*$'
}
class PxPath {
# Properties
[string]$Type = $null
# Constructors
PxPath ([string]$path) {
$this.Type = [PxPath]::PathType($path)
}
PxPath ([string]$path, [string]$pathType) {
#$pathTypeEnum = try {
$this.Type = try {
[pxPathType] $pathType
} catch {
Throw "Not a valid path type: $pathType"
}
}
static [String] PathType ([String]$path) {
[string]$pathType = $null
if ($path -match [PxConstant]::RegExPathWithWildcard) {
$pathWithoutWildcard = $path -replace [regex]::escape($matches[0]), ''
Write-Host $pathWithoutWildcard
}
return $pathType
}
}
$pathType = 'FileSystem_Folders'
$path = try {
[PxPath]::New("C:\", $pathType)
} catch {
Write-Host "$($_.Exception.Message)"
}
$path = try {
[PxPath]::New("\\Server\Folder\*")
} catch {
Write-Host "$($_.Exception.Message)"
}
</code></pre>
<p>The issue I have is that the Enum is only EVER used in the PxPath class, and I feel like that means I should have the Enum in the class, so it's self contained. However, PS5 doesn't allow an Enum in a class. The workaround I have come up with is to instead use an array as a hidden Property of the class instead, as in this second example.</p>
<p><strong>With Array in Class</strong></p>
<pre><code>class PxConstant {
# Static Properties
static [string] $RegExPathWithWildcard = '\\\*\.\*$|\\\*|\\.\.\*$|\*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.\*$'
}
class PxPath {
# Properties
hidden [string[]]$validPathTypes = @('FileSystem_Folder', 'FileSystem_File', 'Registry_Key', 'Registry_Property')
[string]$Type = $null
# Constructors
PxPath ([string]$path) {
$this.Type = [PxPath]::PathType($path)
}
PxPath ([string]$path, [string]$pathType) {
if ($this.validPathTypes -contains $pathType) {
$this.Type = $pathType
} else {
Throw "Not a valid path type: $pathType"
}
}
static [String] PathType ([String]$path) {
[string]$pathType = $null
if ($path -match [PxConstant]::RegExPathWithWildcard) {
$pathWithoutWildcard = $path -replace [regex]::escape($matches[0]), ''
Write-Host $pathWithoutWildcard
}
return $pathType
}
}
$pathType = 'FileSystem_Folders'
$path = try {
[PxPath]::New("C:\", $pathType)
} catch {
Write-Host "$($_.Exception.Message)"
}
$path = try {
[PxPath]::New("\\Server\Folder\*")
} catch {
Write-Host "$($_.Exception.Message)"
}
</code></pre>
<p>I'm wondering if there is a performance or functional argument for one over the other? Or perhaps a strong Best Practice argument in favor? Or is this coders choice really?</p>
|
[] |
[
{
"body": "<p>The best argument for using an <code>enum</code> in this context is the ability to:</p>\n\n<ol>\n<li>Early input validation</li>\n<li>Allowing users to discover valid inputs</li>\n</ol>\n\n<p>In order to take advantage of that, your first example needs a slight change to use the <code>enum</code> type as the parameter type:</p>\n\n<pre><code>class PxPath {\n PxPath ([string]$path, [pxPathType]$pathType) {\n # if user input a string that doesn't correspond \n # to a [pxPathType] name, we won't even get this far!\n }\n}\n</code></pre>\n\n<p>Now, your user has the option to pass either a <code>[pxPathType]</code> value or a corresponding string value:</p>\n\n<pre><code>$pxPath = [PxPath]::new(\"some\\path\", [pxPathType]::FileSystem_Folder)\n# or\n$pxPath = [PxPath]::new(\"some\\path\", 'FileSystem_Folder')\n</code></pre>\n\n<p>But this would fail even before we reach inside the constructor:</p>\n\n<pre><code>$pxPath = [PxPath]::new(\"some\\path\", 'not_a_valid_enum_name')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T10:03:13.403",
"Id": "241485",
"ParentId": "238534",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T16:34:58.917",
"Id": "238534",
"Score": "3",
"Tags": [
"object-oriented",
"enum",
"powershell"
],
"Title": "Enum in PowerShell Class"
}
|
238534
|
<p>I started learning Java recently. Currently I'm trying to improve my spaghetti code by solving different programming puzzles. </p>
<p>It would be amazing if someone could give me feedback on the <a href="http://codingdojo.org/kata/StringCalculator/" rel="noreferrer">String Calculator Kata specified at Coding Dojo</a>.</p>
<p>Any feedback for improvement would be awesome...</p>
<pre><code>// StringCalculator.java
public class StringCalculator {
private float result;
private String customDelimiter;
private static final String DEFAULT_DELIMITER = ",";
private static final String NEWLINE = "\n";
private static final String CUSTOM_DELIMITER_PREFIX = "/";
private static final String CUSTOM_DELIMITER_SUFFIX = NEWLINE;
StringCalculator() {
result = 0;
customDelimiter = "";
}
public String sum(String numbers) {
if (numbers.isEmpty())
return String.format("%.0f", result);
if (isInvalidLastCharacterIn(numbers))
return "Number expected but EOF found.";
if (numbers.startsWith(CUSTOM_DELIMITER_PREFIX))
numbers = setCustomDelimiter(numbers);
if (isNewlineAtInvalidPositionIn(numbers))
return String.format("Number expected but '\n' found at position %d.", numbers.lastIndexOf('\n'));
if (containsNegative(numbers).length() > 0)
return String.format("Negative not allowed: %s", containsNegative(numbers));
calculateSumOf(getStringArray(numbers));
return hasDecimalPlaces() ? printFloat() : printInteger();
}
private boolean isInvalidLastCharacterIn(String numbers) {
return Character.digit(numbers.charAt(numbers.length() - 1), 10) < 0;
}
private boolean isNewlineAtInvalidPositionIn(String numbers) {
return numbers.lastIndexOf(NEWLINE) > numbers.lastIndexOf(DEFAULT_DELIMITER);
}
private StringBuilder containsNegative(String numbers) {
StringBuilder negativeNumbers = new StringBuilder();
for (String number : getStringArray(numbers))
if (Float.valueOf(number) < 0) negativeNumbers.append(number + ",");
boolean commaIsLastChar = negativeNumbers.length() > 0 && negativeNumbers.charAt(negativeNumbers.length() -1) == ',';
return commaIsLastChar ? negativeNumbers.deleteCharAt(negativeNumbers.length() - 1)
: negativeNumbers;
}
private String setCustomDelimiter(String numbers) {
int customDelimiterStart = numbers.lastIndexOf(CUSTOM_DELIMITER_PREFIX) + 1;
int customDelimiterEnd = numbers.indexOf(CUSTOM_DELIMITER_SUFFIX);
customDelimiter = numbers.substring(customDelimiterStart, customDelimiterEnd);
return numbers.substring(customDelimiterEnd + 1).replace(customDelimiter, DEFAULT_DELIMITER);
}
private String[] getStringArray(String numbers) {
return numbers.replace(NEWLINE, DEFAULT_DELIMITER).split(DEFAULT_DELIMITER);
}
private void calculateSumOf(String[] numbers) {
for (String number : numbers)
result = Float.sum(result, Float.parseFloat(number));
}
private boolean hasDecimalPlaces() {
return result % 1 != 0;
}
private String printFloat() {
return Float.toString((float) (Math.round(result * 100.0) / 100.0));
}
private String printInteger() {
return String.valueOf((int) result);
}
}
</code></pre>
<pre><code>// StringCalculatorShould.java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringCalculatorShould {
@Test
public void
return_0_when_input_is_empty() {
assertEquals("0", given(""));
}
@Test
public void
return_3_when_input_is_1_2() {
assertEquals("3", given("1,2"));
}
@Test
public void
sum_floats_and_return_float() {
assertEquals("6.6", given("2.2,4.4"));
}
@Test
public void
treat_newLine_as_a_delimiter() {
assertEquals("6", given("1\n2,3"));
}
@Test
public void
return_error_msg_when_newLine_at_invalid_position() {
assertEquals("Number expected but '\n' found at position 6.", given("1,2,5,\n3"));
}
@Test
public void
return_error_msg_when_delimiter_at_last_position() {
assertEquals("Number expected but EOF found.", given("2,3,4.2,"));
}
@Test
public void
return_correct_sum_when_custom_delimiter_is_used() {
assertEquals("3", given("//;\n1;2"));
assertEquals("3", given("//|\n1|2"));
assertEquals("8", given("//@@\n1@@2@@5"));
assertEquals("5", given("//sep\n2sep3"));
}
@Test
public void
return_string_of_negative_numbers_when_negative_numbers_are_used_as_input() {
assertEquals("Negative not allowed: -1", given("-1,2"));
assertEquals("Negative not allowed: -4,-5", given("2,-4,-5"));
}
private String given(String number) {
StringCalculator stringCalculator = new StringCalculator();
return stringCalculator.sum(number);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T01:24:13.253",
"Id": "467849",
"Score": "0",
"body": "You asked below for good ideas for problems to work on. First, *Learning Java* by O'Rielly was a good resource when I first learned Java, and the examples at least were far more cogent that most other resources. Second, you might try *The C++ Programming Language* by Bjarne Stroustrup. It's written as a text book, doesn't suck, and translate the C++ problems he gives to Java. It will be illuminating at least. Good luck."
}
] |
[
{
"body": "<h2>The challenge</h2>\n\n<p>First of all, a method called <code>String add(String number)</code> is just wrong in every way that you look at it. It may be a \"classic\" Kata, but for me that's classic stupidity, especially if you consider that the method needs to add the numbers <em>within</em> the <code>number</code> given.</p>\n\n<hr>\n\n<p>The challenge really leads you into returning strings for anything. In program jargon, we call that <code>stringly typed</code> and it is something that should be avoided.</p>\n\n<hr>\n\n<p>You've created a <code>sum</code> method which is great, but it is failing the challenge which requires an <code>add</code> method. I'd always keep to the requirements.</p>\n\n<p>That also goes for \"Allow the add method to handle an unknow number of arguments.\" (I didn't create the typo). However, I expect that the author meant that the single string can contain multiple arguments. No way to know for sure.</p>\n\n<hr>\n\n<p>Using the same output for errors and common return values should be avoided, printing out to a different stream (standard error rather than standard out) would be one method of handling that.</p>\n\n<hr>\n\n<p>The idea that a class would return multiple errors for the same input is weird, most classes would just generate a single error, also because one error may beget other errors: fixing the first one may fix both (e.g. you could see this for using a dot instead of a comma as separator).</p>\n\n<hr>\n\n<p>The challenge basically also requires you to allow trash input, and then return a correct result. Generally we test our input before we <em>accept</em> it, explicitly not allowing trash input. Otherwise we default to \"garbage in / garbage out\" principles.</p>\n\n<hr>\n\n<p>The challenge isn't symmetric in the sense that empty input should return <code>0</code> as return value, but it doesn't allow empty number strings.</p>\n\n<hr>\n\n<p>Similarly, you need to include a position when a number is expected at a certain position, but then you also need to return \"negative number\" errors without a position.</p>\n\n<h2>Class design</h2>\n\n<p>Having a calculator class is alright, but it is weird that the calculator stores the result and a custom delimiter. Both values seem to be specific to the <code>sum</code> method, which means that they should be kept <em>local</em> to the sum method.</p>\n\n<p>An example of a good field would be a delimiter, which could <em>default to</em> the <code>DELIMITER</code> constant.</p>\n\n<p>I could see an <code>Addition</code> class that has an <code>add(float)</code> method and returns a <code>total</code> class, but the assignment is really more about input validation than anything else. So a <code>total</code> variable local to the <code>add</code> / <code>sum</code> method seems more logical.</p>\n\n<hr>\n\n<p>The assignment clearly states (under \"error management\") that multiple errors may need to be returned. To me that shows that you may want to generate a list of errors, and that you should keep on testing rather than using <code>return</code> on any error.</p>\n\n<hr>\n\n<p>This is about test driven design. You probably want to test the validation strategies <em>separately</em>. If you create <code>public static</code> validation methods then you can create separate tests for them (I'd also blame the setup of the challenge for this). Creating a <code>Validator</code> class and a separate <code>ValidatorResult</code> may also be a good idea if your class gets too complicated otherwise.</p>\n\n<h2>Code review</h2>\n\n<pre><code>if (numbers.isEmpty())\n return String.format(\"%.0f\", result);\n</code></pre>\n\n<p>Always try and use braces after an <code>if</code> branch:</p>\n\n<pre><code>if (numbers.isEmpty()) {\n return String.format(\"%.0f\", result);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>if (numbers.startsWith(CUSTOM_DELIMITER_PREFIX))\n numbers = setCustomDelimiter(numbers);\n</code></pre>\n\n<p>Try not to mix error handling with normal code. First check for errors, then handle the correct values. You don't want to perform any side effects (setting the custom delimiter) before you are sure that the input is correct.</p>\n\n<hr>\n\n<pre><code>private boolean isNewlineAtInvalidPositionIn(String numbers) {\n return numbers.lastIndexOf(NEWLINE) > numbers.lastIndexOf(DEFAULT_DELIMITER);\n}\n</code></pre>\n\n<p>If I look at the assignment you may need to store the location of the errors as well. Returning just a <code>boolean</code> is probably not going to do this; you may need to perform the same test again to find the error position.</p>\n\n<hr>\n\n<pre><code>private StringBuilder containsNegative(String numbers) {\n</code></pre>\n\n<p>Now a private method has a bit more leeway when it comes to side effects and return values / types. However, a <code>contains</code> method should return a <code>boolean</code> and not a <code>StringBuilder</code>. A <code>StringBuilder</code> should really never be returned; it could be consumed as parameter though.</p>\n\n<hr>\n\n<pre><code>private String setCustomDelimiter(String numbers) {\n</code></pre>\n\n<p>Please answer these questions, without looking at your code:</p>\n\n<ul>\n<li>What would <code>setCustomDelimiter</code> require as parameter?</li>\n<li>What does a setter use as return value?</li>\n</ul>\n\n<hr>\n\n<pre><code>private String[] getStringArray(String numbers) {\n</code></pre>\n\n<p>No, the method is named badly. Call it <code>separateInputString</code> or something similar, but <code>getStringArray</code> doesn't specify what the method <em>does</em>, it just indicates what it <em>returns</em>.</p>\n\n<hr>\n\n<p>Similarly:</p>\n\n<pre><code>private void calculateSumOf(String[] numbers) {\n for (String number : numbers)\n result = Float.sum(result, Float.parseFloat(number));\n}\n</code></pre>\n\n<p>No return value? Why not just use the <code>+</code> operator?</p>\n\n<pre><code>private boolean hasDecimalPlaces() {\n return result % 1 != 0;\n}\n</code></pre>\n\n<p>Again working on the result. But I don't get the calculation either. This is <code>isOdd</code> it seems to me.</p>\n\n<hr>\n\n<pre><code>private String printFloat() {\n return Float.toString((float) (Math.round(result * 100.0) / 100.0));\n}\n</code></pre>\n\n<p>Generally we try and print to stream. This is about <em>formatting</em> a float. You could use <code>formatResultAsFloat()</code>. This should also give you a hint that you could use <code>String.format</code> instead of performing such coding yourself.</p>\n\n<h2>Model</h2>\n\n<p>It seems to me that you've started coding a little bit early. First you should try and create some model first. E.g. you could decide to first validate the input string (as you also need positions for the errors), then split, then perform the calculations on the separate values.</p>\n\n<h2>Conclusion</h2>\n\n<p>Do I think there is a lot to be improved? Certainly. Do I think that this is spaghetti code? Certainly not. Furthermore, the identifiers are well named, and if you don't include the way parameters are handled, so are the methods. The code is nicely split up, even if some reordering may be a good idea.</p>\n\n<p>The Kata or challenge on the other hand is beyond saving and should be destroyed. But that's just my opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T19:18:10.857",
"Id": "467831",
"Score": "0",
"body": "Thank you so much for the effort! \nI'll go about the code again to fix and rethink with that input in mind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T21:53:55.717",
"Id": "467839",
"Score": "1",
"body": "I'd not overspend time on this; the use case, the error handling, the whole idea of what this does is all terrible. Don't trust that entire site. The \"peoples\" there seem well willing enthusiasts, but this cannot have been written by any expert."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:02:45.783",
"Id": "467840",
"Score": "0",
"body": "Hope this is not off-topic, but can you recommend any resources / material that I can use instead to practice? I liked the idea of small coding exercises, but without mentors / senior devs it's not easy to progress"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:11:51.847",
"Id": "467842",
"Score": "0",
"body": "To be honest, no, I cannot. I've been out of that game for too long. Maybe check out this site for other contests and ideas. Or try and find something that you care about and try that. In the end the practice is what makes perfect. Do however try and find problems that seem logical. Having numbers separated by a separator that can be defined in the same string is not a logical problem; it is needlessly complex and allows too many exceptional circumstances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:13:03.377",
"Id": "467843",
"Score": "0",
"body": "Quick test: try and ask at least 10 questions that cannot be answered by the description of the problem. If you can do that, then the problem is not likely to be logical or complete. I can easily come up with 10 for this particular Kata."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T23:20:13.813",
"Id": "467844",
"Score": "0",
"body": "Thank you for the feedback and the time you took. I really did learn something today!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:37:40.090",
"Id": "467940",
"Score": "1",
"body": "Small note: if I look at the assignment it seems that it always needs to distinguish between different types. That means that it may be a good idea to *tokenize*: look at the syntax before anything else. For instance, at each position of an element, you look if it is a number or separator rather than assuming a number or separator at a specific location. Bottom up instead of top down approach, in other words. This is a separator, but I'm expecting a number rather than I'm looking for a number, but this is not a number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T19:08:24.260",
"Id": "468086",
"Score": "0",
"body": "That's a great idea! Thank you.. I'm gonna try another implementation using this approach"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T18:33:34.597",
"Id": "238536",
"ParentId": "238535",
"Score": "6"
}
},
{
"body": "<p>In addition to @MaartenBodewes brilliant answer some words to your unit tests:</p>\n\n<h1>what I like</h1>\n\n<ul>\n<li>the fact that you have unit tests at all.</li>\n<li>the naming is well thought of.</li>\n</ul>\n\n<h1>what I don't like</h1>\n\n<ul>\n<li><p>Do not reduce the content of a test method to a single line.</p>\n\n<p>Unit tests are <strong>documentation</strong>. You should write your unit test in a way, that they describe the testes expectation in detail. One formal way to do that is to keep the <em>arrange</em>, <em>act</em>, <em>assert</em> structure of each test. </p>\n\n<pre><code> @Test\n public void return_0_when_input_is_empty() {\n // arrange \n String input = \"\";\n String expectedOutput = \"0\"\n // act \n String testResult = new StringCalculator().sum(input);\n // assert \n assertEquals(expectedOutput, testResult);\n }\n</code></pre>\n\n<p>For the same reason prefer the <code>assert*</code> methos with that extra <code>String</code> parameter so that you get a more descriptive output when the test fails:</p>\n\n<pre><code> @Test\n public void return_0_when_input_is_empty() {\n // ...\n // assert \n assertEquals(\"empty string\",expectedOutput, testResult);\n }\n</code></pre></li>\n<li><p>verify only one expectation on your code with every test method.</p>\n\n<p>While the testing framework will execute all test methods regardless of whether they fail or not a test method will stop a the first failing <code>assert</code> instruction. \nThis will reduce the information you get about the reason why your code failed.</p>\n\n<pre><code> @Test\n public void\n return_correct_sum_when_delimiter_is_semicolon() {\n assertEquals(\"3\", given(\"//;\\n1;2\"));\n }\n\n @Test\n public void\n return_correct_sum_when_delimiter_is_pipe() {\n assertEquals(\"3\", given(\"//|\\n1|2\"));\n }\n\n @Test\n public void\n return_correct_sum_when_delimiter_is_newline() {\n assertEquals(\"8\", given(\"//@@\\n1@@2@@5\"));\n }\n\n @Test\n public void\n return_correct_sum_when_delimiter_is_string() {\n assertEquals(\"5\", given(\"//sep\\n2sep3\"));\n }\n</code></pre>\n\n<p>For the time being this will force you to create more test methods, but soon you'll find out how to do this with <em>parameterized tests</em>.</p>\n\n<p><strong>Disclaimer</strong> \"one assert per test method\" is a <em>rule of thumb</em>, not a natural law. There might be situations where more that one assert per method is needed, but if you're going to do that you should have a really good reason to do so.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T19:10:37.367",
"Id": "468087",
"Score": "0",
"body": "Thanks a lot for the feedback! I'm gonna change my test suit accordingly"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:22:46.437",
"Id": "238638",
"ParentId": "238535",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238536",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T16:38:14.320",
"Id": "238535",
"Score": "5",
"Tags": [
"java",
"strings"
],
"Title": "Java Kata - String Calculator"
}
|
238535
|
<p><strong>IMPORTANT:</strong></p>
<p>I made another version with some improvements: <a href="https://dotnetfiddle.net/YjIoH5" rel="nofollow noreferrer"><strong>Version 2</strong></a></p>
<hr>
<p>Since some months ago I disagree with the native/code methods to manipulate <code>dynamic</code> or <code>ExpandoObject</code> in C# .Net Core, it's quite messy trying to manipulate, read, write props in <code>ExpandoObject</code> in a dynamic way.</p>
<p>So, searching on Internet I can't found a solution that satisfies my needs.
I'm searching for your opinion and feedback to rate the following code and the results.</p>
<p>And help me to understand if, I'm trying to invent the hot water? or if exists something similar in the core.</p>
<p>...if not, and I'm in the right approach, I want to listen to suggestions on how to improve my code, just because I will implement in a REST API service, and any additional tweak that makes this class faster will be better.</p>
<p>So, the full and functional example could find it <a href="https://dotnetfiddle.net/TeIRww" rel="nofollow noreferrer">here</a></p>
<p>The C# code:</p>
<pre><code>namespace FW {
public class Expando
{
public Expando(dynamic value)
{
expando = ToExpando(value);
}
public ExpandoObject root { get => expando; }
private ExpandoObject expando { get; set; }
private ExpandoObject ToExpando(dynamic dynamicObject)
{
if ((dynamicObject as object).GetType().Name == "ExpandoObject") return dynamicObject;
if (!(dynamicObject as object).GetType().IsGenericType) throw new Exception("No generic type");
ExpandoObject expando = new ExpandoObject();
((object)dynamicObject)
.GetType()
.GetProperties()
.ToList()
.ForEach(p => expando.fwAddProperty(p.Name, p.GetValue(dynamicObject) as object));
return expando;
}
public dynamic this[string prop]
{
get => expando.fwReadProperty(prop);
set => expando.fwAddProperty(prop, value as object);
}
public dynamic this[params string[] props]
{
get
{
ExpandoObject returnValue = expando;
foreach (string prop in props)
{
var temp = returnValue.fwReadProperty(prop);
try { returnValue = ToExpando(temp); }
catch { return temp as object; }
}
return returnValue;
}
set
{
List<ExpandoObject> list = new List<ExpandoObject>();
list.Add(expando);
foreach (var prop in props)
{
var newProp = list.Last().fwReadProperty(prop);
if (newProp != null)
{
try { list.Add(ToExpando(newProp)); }
catch { }
}
else if (prop != props.Last())
{
ExpandoObject expandoTemp = new ExpandoObject();
list.Add(expandoTemp);
}
}
List<string> nodeProps = props.ToList();
list.Last().fwAddProperty(nodeProps.Last(), value as object);
nodeProps.RemoveAt(nodeProps.Count - 1);
ExpandoObject ExpandoTemp = list.Last();
list.RemoveAt(list.Count - 1);
while (list.Count != 0)
{
var node = list.Last();
list.RemoveAt(list.Count - 1);
node.fwAddProperty(nodeProps.Last(), ExpandoTemp as object);
nodeProps.RemoveAt(nodeProps.Count - 1);
ExpandoTemp = node;
}
expando = ExpandoTemp;
}
}
}
public static class extExpandoObject
{
public static void fwAddProperty(this ExpandoObject expando, string propertyName, object propertyValue)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
public static object fwReadProperty(this ExpandoObject expando, string propertyName)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
return expandoDict[propertyName];
else
return null;
}
}
}
</code></pre>
<p>Implementation</p>
<pre><code>public class Program
{
public static void Main()
{
FW.Expando dynamicObject =
new FW.Expando(new
{
a = new int[] { 1, 2 },
b = "String val",
c = 10,
d = new { sa = 1, sb = "abv", sc = new int[] { 1, 2, 3 } }
});
// Add new props
const string newProp = "e";
dynamicObject[newProp] = "New val";
dynamicObject["f"] = false;
dynamicObject["d", "sd"] = "SDSDSD";
var a = dynamicObject["d", "sd"];
dynamicObject["d", "se"] = null;
// Modify props
const string prop = "a";
dynamicObject[prop] = (dynamicObject[prop] as int[]).Append(3).ToArray();
dynamicObject["b"] += " ABCD";
// Modify children props of another prop
dynamicObject["d", "sb"] = new string[] { "New", "Array" };
dynamicObject["d", "sa"] += 5;
dynamicObject["d", "sa"] = new { dz = "ABA", zz = "WCC", ZXXX = new { Y1 = "1", Y2 = "2" } };
dynamicObject["parent", "node"] = "New field";
dynamicObject["parent-node", "node-lvl1", "node-lvl1.1"] = "P > 1 > 1.1";
dynamicObject["parent-node", "node-lvl1", "node-lvl1.2"] = "P > 1 > 1.2";
dynamicObject["parent-node", "node-lvl2", "node-lvl2.1"] = "P > 2 > 2.1";
dynamicObject["parent-node", "m-node", "sub1", "sub2", "sub3"] = "3 Sublevels";
// Read props
object propValue = dynamicObject[prop];
object propValueString = dynamicObject["b"];
string result = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicObject.root);
// CHECK MORE EASILY THE RESULT: https://jsonformatter.curiousconcept.com/
Console.WriteLine("\r\n" + result + "\r\n");
}
}
</code></pre>
<p>JSON Result: </p>
<pre><code>{
"a":[
1,
2,
3
],
"b":"String val ABCD",
"c":10,
"d":{
"sa":{
"dz":"ABA",
"zz":"WCC",
"ZXXX":{
"Y1":"1",
"Y2":"2"
}
},
"sb":[
"New",
"Array"
],
"sc":[
1,
2,
3
],
"sd":"SDSDSD",
"se":null
},
"e":"New val",
"f":false,
"parent":{
"node":"New field"
},
"parent-node":{
"node-lvl1":{
"node-lvl1.1":"P > 1 > 1.1",
"node-lvl1.2":"P > 1 > 1.2"
},
"node-lvl2":{
"node-lvl2.1":"P > 2 > 2.1"
},
"m-node":{
"sub1":{
"sub2":{
"sub3":"3 Sublevels"
}
}
}
}
}
</code></pre>
<p>Thanks and regards to taking the time to read it.</p>
|
[] |
[
{
"body": "<p>I like the simplicity of this code. It may needs some improvements, but these are just to make it more flexible to be adopted to other projects (if it's intended for that). </p>\n\n<p>For most part, you've put the main functionalities on an extension class, which is something I wouldn't do myself. I think It would be better if Add, Remove, Get, and Set functionalities to be inside the main class. Then, if you want to make an extension to them, just call them back. This would make them more maintainable and easy to expand for future projects.</p>\n\n<p>Also, the code missing the <code>null</code> validations, which you must consider all the time. </p>\n\n<p>Another thing that I've noticed, there are many <code>boxing</code> and <code>unboxing</code> (dynamic to object and vise versa). try to minimize these castings.</p>\n\n<p>Final part, I would suggest readjusting the class to be a thin layer on top of <code>ExpandoObject</code> that meant to simplify its functionalities, and use interface to make a contract that would help in future uses. </p>\n\n<p>Here is what I have in my mind, something might be useful (I hope) : </p>\n\n<pre><code>public interface IExpando\n{\n void AddOrUpdateProperty(string propertyName, object propertyValue);\n\n dynamic GetProperty(string propertyName);\n\n bool RemoveProperty(string propertyName);\n\n IDictionary<string, dynamic> GetProperties();\n // any other properties or methods that you think it's a must have\n}\n\npublic class Expando : IExpando\n{\n private readonly ExpandoObject _root;\n\n public Expando(dynamic value) { _root = InitiateInstance(value); }\n\n public dynamic this[string propertyName] \n {\n get => GetProperty(propertyName);\n set => AddOrUpdateProperty(propertyName, value);\n }\n\n private ExpandoObject InitiateInstance(dynamic value)\n {\n if (value is null) { throw new ArgumentNullException(nameof(value)); }\n\n if (value.GetType() == typeof(ExpandoObject)) { return value; }\n\n if (!value.GetType().IsGenericType) { throw new Exception(\"No generic type\"); }\n\n _root = new ExpandoObject();\n\n (value as object)?\n .GetType()\n .GetProperties()\n .ToList()\n .ForEach(p => AddOrUpdateProperty(p.Name, p.GetValue(value)));\n\n return _root;\n } \n\n public void AddOrUpdateProperty(string propertyName, object propertyValue) { ... }\n\n public bool RemoveProperty(string propertyName) { ... }\n\n public dynamic GetProperty(string propertyName) { ... }\n\n public IDictionary<string, dynamic> GetProperties() => _root as IDictionary<string, dynamic>;\n\n}\n\npublic static class ExpandoExtension\n{\n public static Expando ToExpando(this ExpandoObject expando)\n {\n return new Expando(expando); \n }\n}\n</code></pre>\n\n<p>these are just a sketch, you can implement even something better, and make it a more suitable for an open-source library that would be easy to use. For the extension, my thought is just you want one extension to return a new <code>Expando</code>, with that you're enforcing the usage of your class. </p>\n\n<p>Also, you can define a private <code>Dictionary<string, dynamic></code> and use it instead of casting the expandoObject on each method, and just store the results inside the _root. </p>\n\n<p>I hope this would be useful. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T16:21:27.313",
"Id": "238571",
"ParentId": "238537",
"Score": "2"
}
},
{
"body": "<p>If you want a cleaner version of dynamic/ExpandoObject, I would go step by step and fix what you don't like. Let's say you want to do something close to a Javascript-like syntax:</p>\n\n<pre><code>obj = {};\nobj.a = 123;\nobj.b = \"message\";\nobj.c = [ 456, \"something\", {} ];\nobj.d = {\n x: 50,\n y: [ \"a\", \"b\", \"c\" ],\n z: null\n};\n\nobj.e = \"eeee\";\nobj.d.z = { z: \"zz\" };\nobj.d.y.Add(\"d\");\n</code></pre>\n\n<p>Converting this to the equivalent syntax using out-of-the-box dynamic/ExpandoObject:</p>\n\n<pre><code>dynamic obj = new ExpandoObject();\nobj.a = 123;\nobj.b = \"message\";\nobj.c = new List<dynamic> { 456, \"something\", new ExpandoObject() };\nobj.d = new ExpandoObject();\nobj.d.x = 50;\nobj.d.y = new List<dynamic> { \"a\", \"b\", \"c\" };\nobj.d.z = null;\n\nobj.e = \"eeee\";\nobj.d.z = new ExpandoObject();\nobj.d.z.z = \"zz\";\nobj.d.y.Add(\"d\");\n</code></pre>\n\n<p>The first major issue with the syntax is that there is no shortcut syntax for creating an ExpandoObject and giving it properties like a normal object:</p>\n\n<pre><code>// Can't do this...\nobj.d = new ExpandoObject()\n{ \n x = 50,\n y = new List<dynamic> { \"a\", \"b\", \"c\" },\n z = null\n}\n</code></pre>\n\n<p>One attempt would be to create and then convert an anonymous object (like you did in your code), however this requires reflection which is slow and can bring on other challenges. Instead, I think the cleanest solution would be to create a helper for creating an ExpandoObject and initializing it in some way, before returning it:</p>\n\n<pre><code>public static class Dynamic\n{\n public static dynamic Object(Action<dynamic> init)\n {\n var obj = new ExpandoObject();\n init(obj);\n return obj;\n }\n}\n</code></pre>\n\n<p>This makes inline objects much nicer:</p>\n\n<pre><code>dynamic obj = new ExpandoObject();\nobj.a = 123;\nobj.b = \"message\";\nobj.c = new List<dynamic> { 456, \"something\", new ExpandoObject() };\nobj.d = Dynamic.Object(o =>\n{\n o.x = 50;\n o.y = new List<dynamic> { \"a\", \"b\", \"c\" };\n o.z = null;\n});\n\nobj.e = \"eeee\";\nobj.d.z = Dynamic.Object(o => o.z = \"zz\");\nobj.d.y.Add(\"d\");\n</code></pre>\n\n<p>From here, the syntax is very close, and I would only add a few things to make things more consistent in naming/style:</p>\n\n<pre><code>public static class Dynamic\n{\n public static dynamic Object(Action<dynamic> init)\n {\n var obj = new ExpandoObject();\n init(obj);\n return obj;\n }\n\n public static dynamic Object() => Object(_ => {});\n\n public static List<dynamic> List(params dynamic[] items) => items.ToList();\n}\n\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>dynamic obj = Dynamic.Object();\nobj.a = 123;\nobj.b = \"message\";\nobj.c = Dynamic.List(456, \"something\", Dynamic.Object());\nobj.d = Dynamic.Object(o =>\n{\n o.x = 50;\n o.y = Dynamic.List(\"a\", \"b\", \"c\");\n o.z = null;\n});\n\nobj.e = \"eeee\";\nobj.d.z = Dynamic.Object(o => o.z = \"zz\");\nobj.d.y.Add(\"d\");\n\nConsole.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj,\n Newtonsoft.Json.Formatting.Indented));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>{\n \"a\": 123,\n \"b\": \"message\",\n \"c\": [\n 456,\n \"something\",\n {}\n ],\n \"d\": {\n \"x\": 50,\n \"y\": [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ],\n \"z\": {\n \"z\": \"zz\"\n }\n },\n \"e\": \"eeee\"\n}\n</code></pre>\n\n<p>There are other strategies you could use to implement Dynamic.Object and the other helpers, but they would all depend on your own personal style/preferences. Let me know if there is some key functionality that this is missing, and I'd be happy to add in a few more helpers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T23:30:24.623",
"Id": "238856",
"ParentId": "238537",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238856",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T18:37:19.720",
"Id": "238537",
"Score": "2",
"Tags": [
"c#",
"json",
"generics",
"dynamic-programming",
".net-core"
],
"Title": "C# - Reapply the manipulation of JS Object in .Net Core"
}
|
238537
|
<p>I'm attempting to rewrite the classic <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)" rel="noreferrer">snake game</a> in <code>c++</code>. What I am inquiring about is my implementation for a 2D collision detection function. I am utilizing <a href="https://www.sfml-dev.org/" rel="noreferrer"><code>SFML</code></a> to create the window and shapes. The two objects that I am checking are squares of the same size. I would really appreciate any feedback that is given, as I'm still a beginner when it comes to <code>c++</code>. </p>
<p>This function works as intended. I'm looking for performance improvements, and general <code>c++</code> practices that I should follow. If I need to add any more code, please let me know.</p>
<p><strong>Game.h</strong></p>
<pre><code>#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
class Game {
// Some code omitted for brevity //
private:
sf::RectangleShape enemy;
sf::RectangleShape player;
public:
const bool isColliding(sf::RectangleShape player, sf::RectangleShape enemy) const;
// Some code omitted for brevity //
};
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>/*
Determines if the player is colliding with the enemy.
@param sf::RectangleShape player - Player object.
@param sf::RectangleShape enemy - Enemy object.
@return bool - True if colliding, False otherwise.
*/
const bool Game::isColliding(sf::RectangleShape player, sf::RectangleShape enemy) const {
sf::Vector2f playerPosition = this->player.getPosition();
sf::Vector2f enemyPosition = this->enemy.getPosition();
float playerWidth = this->player.getSize().x;
float playerHeight = this->player.getSize().y;
return (
((playerPosition.x + playerWidth) > enemyPosition.x && (playerPosition.x - playerWidth) < enemyPosition.x) &&
((playerPosition.y + playerHeight) > enemyPosition.y && (playerPosition.y - playerHeight) < enemyPosition.y)
);
}
</code></pre>
|
[] |
[
{
"body": "<p><code>const bool Game::isColliding(...</code></p>\n\n<p>This indicates that the returned type is <code>const</code>, and should not be modified by any part of your code. But it's not a reference, so it doesn't make sense. It should compile, but it's a little confusing. Removing that <code>const</code> is clearer.</p>\n\n<p>see <a href=\"https://stackoverflow.com/questions/1443659/should-i-return-bool-or-const-bool\">this SO question</a> for more information on that.</p>\n\n<hr>\n\n<p>Your parameters to <code>isColliding</code> should be <code>const</code> references:</p>\n\n<pre><code>bool Game::isColliding(const sf::RectangleShape& player, const sf::RectangleShape& enemy) const\n</code></pre>\n\n<p>because you don't modify them, and references will prevent each object form being copied.</p>\n\n<hr>\n\n<p>You never use the <code>player</code> parameter that you pass to the <code>isColliding</code> function. <code>this->player</code> is not the same as <code>player</code> in this context. It seems like you want to check the <code>Game</code>'s current <code>player</code> object against collisions with arbitrary objects. You either</p>\n\n<ol>\n<li>Make the function static (so it doesn't rely on a particular <code>Game</code> state) and pass two arbitrary objects to be checked for collision, or</li>\n<li>Change the function name to something that indicates it will only be used with the <code>player</code> object.</li>\n</ol>\n\n<p>One of:</p>\n\n<pre><code>static bool Game::isColliding(const sf::RectangleShape& a, const sf::RectangleShape& b)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>bool Game::isPlayerColliding(const sf::RectangleShape& other) const\n</code></pre>\n\n<hr>\n\n<p>These <code>Vector2d</code> assignments can be made into <code>const</code> references to prevent copy construction.</p>\n\n<pre><code> const sf::Vector2f& playerPosition = this->player.getPosition();\n const sf::Vector2f& enemyPosition = this->enemy.getPosition();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:48:30.483",
"Id": "468118",
"Score": "0",
"body": "I wish I could accept this answer too. I will take these into account while continuing to learn `c++`. Thanks for the review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T21:09:28.403",
"Id": "238543",
"ParentId": "238540",
"Score": "15"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/238543/56343\">John's answer</a> is correct on programming matters. I want to comment on the logic of your code.</p>\n\n<p>I found the collision detection calculation difficult to interpret. Which point on the square is represented by <code>playerPosition</code>? The documentation for SFML says it's the upper-left corner (<a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Transformable.php#a56c67bd80aae8418d13fb96c034d25ec\" rel=\"noreferrer\">although in a roundabout way</a>), but it could also reasonably be the center. I can see that <code>playerPosition.x + playerWidth</code> is the right edge of the player, but what does <code>playerPosition.x - playerWidth</code> represent? This is a random point off to the left of the player.</p>\n\n<p>Giving parts of the calculation good names will make the logic much easier to understand and debug should the need arise.</p>\n\n<pre><code>float playerLeftEdge = player.getPosition().x;\nfloat playerRightEdge = playerLeftEdge + player.getSize().x;\nfloat playerTopEdge = player.getPosition().y;\nfloat playerBottomEdge = playerTopEdge + player.getSize().y;\n\nfloat enemyLeftEdge = enemy.getPosition().x;\nfloat enemyRightEdge = enemyLeftEdge + enemy.getSize().x;\nfloat enemyTopEdge = enemy.getPosition().y;\nfloat enemyBottomEdge = enemyTopEdge + enemy.getSize().y;\n\nreturn playerRightEdge > enemyLeftEdge && playerLeftEdge < enemyRightEdge &&\n playerTopEdge < enemyBottomEdge && playerBottomEdge > enemyTopEdge;\n</code></pre>\n\n<p>Case in point regarding debugging, according to the documentation:</p>\n\n<blockquote>\n <p>In addition to the position, rotation and scale, sf::Transformable provides an \"origin\" component, which represents the local origin of the three other components. Let's take an example with a 10x10 pixels sprite. By default, the sprite is positioned/rotated/scaled relatively to its top-left corner, because it is the local point (0, 0). But if we change the origin to be (5, 5), the sprite will be positioned/rotated/scaled around its center instead. And if we set the origin to (10, 10), it will be transformed around its bottom-right corner.</p>\n</blockquote>\n\n<p>So, the bottom edge coordinate will be greater than the top edge, requiring a reversal of the logic for y-coordinate collisions (hence my latest edit).</p>\n\n<p>The logic in your code only works because the player and enemy have the same width, which may not always be true in future iterations of your game. Even if it never changes and <code>playerWidth</code> is always equal to <code>enemyWidth</code>, giving different names to conceptually different quantities makes for more understandable code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T06:47:07.440",
"Id": "238552",
"ParentId": "238540",
"Score": "10"
}
},
{
"body": "<p>SFML implements functionalities that allow you to determine if two rectangles intersect. You can significantly shorten your current code:</p>\n\n<pre><code>const bool Game::isColliding(const sf::RectangleShape& player, const sf::RectangleShape& enemy) const \n{\n return player.getGlobalBounds().intersects(enemy.getGlobalBounds());\n}\n</code></pre>\n\n<p>See more: </p>\n\n<ul>\n<li><a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Rect.php#ac77531698f39203e4bbe023097bb6a13\" rel=\"noreferrer\">sf::FloatRect::intersects</a></li>\n<li><a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Shape.php#ac0e29425d908d5442060cc44790fe4da\" rel=\"noreferrer\">sf::RectangleShape::getGlobalBounds</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:48:46.773",
"Id": "468119",
"Score": "0",
"body": "Wow, I had no idea it was that simple. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T23:51:50.290",
"Id": "238592",
"ParentId": "238540",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "238592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T20:55:41.793",
"Id": "238540",
"Score": "15",
"Tags": [
"c++",
"beginner",
"collision",
"sfml",
"c++20"
],
"Title": "2D Collision Detection in C++"
}
|
238540
|
<p>I am working on a library which does DOM hide and show based on other DOM elements.</p>
<p>I have written a basic structure for the library.</p>
<p>The below is the code to handle DOM elements hiding when a checkbox is checked and unchecked.</p>
<p>My overall goal is to make this library extensible and maintainable.</p>
<p>Am I following SOLID principles?
Is there any better way to do it?
Are there any design patterns to follow?</p>
<pre><code>// basic data structure of config object
var rules = [
{
sourceId: 'mainCheckbox',
targetId: 'exampleDiv1',
ruleType: 'onlyOnChecked',
targetVisibilityOnChecked: 'hide', // show / hide
targetVisibilityOnUnchecked: 'show',
doNotReset: false
}
]
var ruleToProcessorMap = {
onlyOnChecked: OnlyOnCheckedRuleProcessor
}
var RuleEngine = {}
RuleEngine.run = function(rules) {
var ruleIndex
for (ruleIndex = 0; ruleIndex < rules.length; rules++) {
this.processRule(rules[ruleIndex])
}
}
RuleEngine.processRule = function(ruleObj) {
var ruleProcessor = new ruleToProcessorMap[ruleObj.ruleType](ruleObj)
ruleProcessor.process()
}
function OnlyOnCheckedRuleProcessor(options) {
this.options = options || {}
}
OnlyOnCheckedRuleProcessor.prototype.process = function() {
var $sourceId = $id(this.options.sourceId),
ctx = this
$sourceId.on('click', onSourceClick)
function onSourceClick() {
var elementVisibilityHandler = new ElementVisibilityHandler({
elementId: ctx.options.targetId,
doNotReset: ctx.options.doNotReset
}),
show = elementVisibilityHandler.show,
hide = elementVisibilityHandler.hide
var visibilityMap = {
show: show,
hide: hide
}
var onCheckedFunc = visibilityMap[ctx.options.targetVisibilityOnChecked]
var onUncheckedFunc = visibilityMap[ctx.options.targetVisibilityOnUnchecked]
if ($sourceId.is(':checked')) {
onCheckedFunc.call(elementVisibilityHandler)
} else {
onUncheckedFunc.call(elementVisibilityHandler)
}
}
}
function ElementVisibilityHandler(options) {
this.options = options || {}
this.$element = $id(options.elementId)
}
ElementVisibilityHandler.prototype.show = function() {
if (isContainerElement(this.$element)) {
if (this.options.doNotReset) {
simpleShow(this.$element)
} else {
showWithChildren(this.$element)
}
}
}
ElementVisibilityHandler.prototype.hide = function() {
if (isContainerElement(this.$element)) {
if (this.options.doNotReset) {
simpleHide(this.$element)
} else {
hideAndResetChildren(this.$element)
}
}
}
function simpleHide($element) {
return $element.hide()
}
function hideAndResetChildren($element) {
var $children = simpleHide($element)
.children()
.hide()
$children.find('input:checkbox').prop('checked', false)
$children.find('textarea, input').val('')
}
function simpleShow($element) {
return $element.show()
}
function showWithChildren($element) {
simpleShow($element)
.children()
.show()
}
function $id(elementId) {
return $('#' + elementId)
}
function isContainerElement($element) {
if (typeof $element === 'string') {
$element = $id($element)
}
return $element.prop('tagName').toLowerCase()
}
// execution starts here
RuleEngine.run(rules)
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T20:58:17.397",
"Id": "238541",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Config based Hide Show Rules Processor in JavaScript"
}
|
238541
|
<p>I Rewrote all code, aimed at a variable reduction, and reduced complexity. removed all extraneous code unnecessary to the operation, reduced indexing surfaces, tests all work consistently. Added midpoint matching to search, combined Reader and Searching into a class.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace ActiveScreenMatch
{
public unsafe class ThisScreenSearch
{
internal Bitmap BitmapToMap { get; }
internal BitmapData BitmapToMapData { get; }
private BiDirectionalReader DesktopReader { get; }
/// <summary>
/// Class reads bitmap and stores combined index of top,bot to midpoint and cache the resulting binary lines as Memory<bool>
/// </summary>
internal class BiDirectionalReader
{
internal int SetWidth { get; }
internal int SetHeight { get; }
private byte* Bits { get; }
private int Stride { get; }
internal List<(int TopIndex, int BottomIndex)> BiDirectionalIndex { get; }
internal SortedList<int, Memory<bool>> CachedItems { get; }
public BiDirectionalReader(byte* mapPointer, int mapWidth, int mapHeight, int mapStride)
{
Bits = mapPointer;
SetWidth = mapWidth;
SetHeight = mapHeight;
Stride = mapStride;
CachedItems = new SortedList<int, Memory<bool>>(SetHeight);
BiDirectionalIndex = new List<(int, int)>();
List<byte> Masks = new List<byte>();
// PreProcess mask for line
for (int x = 0; x < SetWidth - 1; x++)
{
Masks.Add((byte)(0x80 >> (x & 0x7)));
}
// iterate forward and back over bitmap to create index and parse bytes to bools
int top = -1, bot = SetHeight;
while (++top <= (SetHeight - 1) / 2 && --bot >= (SetHeight - 1) / 2)
{
// declare array to hold results
var topLine = new bool[SetWidth];
var botLine = new bool[SetWidth];
// iterate over the width of the bitmap on both lines
for (int x = 0; x < SetWidth - 1; x++)
{
var mask = Masks[x];
byte tret = *(Bits + (top * Stride) + (x >> 3));
byte bret = *(Bits + (bot * Stride) + (x >> 3));
tret &= mask;
bret &= mask;
topLine[x] = tret > 0;
botLine[x] = bret > 0;
}
// store index
BiDirectionalIndex.Add((top, bot));
// store lines parse in cache
CachedItems.Add(top, new Memory<bool>(topLine));
CachedItems.Add(bot, new Memory<bool>(botLine));
}
}
}
public Point CompressSearch(Bitmap target)
{
// parse the target bitmap using out reader
var TargetData = target.LockBits(new Rectangle(0, 0, target.Width, target.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
var TScan0 = TargetData.Scan0;
var TargetReader = new BiDirectionalReader((byte*)TScan0, TargetData.Width, TargetData.Height, TargetData.Stride);
// clean up.
target.UnlockBits(TargetData);
int FoundTop = -1;
int FoundBottom = -1;
// Parse the Index to check if top and bottom line contain set bits
// probably not the most optimal solution, but it doesn't use linq
foreach ((int TopIndex, int BottomIndex) in TargetReader.BiDirectionalIndex)
{
(Memory<bool> TopLine, Memory<bool> BottomLine) = (TargetReader.CachedItems[TopIndex], TargetReader.CachedItems[BottomIndex]);
if (FoundTop == -1 && TopLine.Span.IndexOf(true) > -1)
{
FoundTop = TopIndex;
}
if (FoundBottom == -1 && BottomLine.Span.IndexOf(true) > -1)
{
FoundBottom = BottomIndex;
}
if (FoundTop > -1 && FoundBottom > -1)
{
break;
}
}
// if top and bottom are not -1 start searching.
if (FoundTop > -1 && FoundBottom > -1)
{
// get target lines by the index found above
var TargetTop = TargetReader.CachedItems[FoundTop];
var TargetBottom = TargetReader.CachedItems[FoundBottom];
// calculate the offset between top and bottom
var Offset = FoundBottom - FoundTop;
// if offset > 1 locate use the offset /2 as midpoint else return default line(all false)
Memory<bool> TargetMid = Offset > 1 ? TargetReader.CachedItems[FoundTop + (Offset / 2)] : new Memory<bool>(new bool[TargetReader.SetWidth]);
// Iterate over the provided index for the searched bitmap
foreach ((int Top, int Bot) in DesktopReader.BiDirectionalIndex)
{
// check index
// if index > - 1 slice to point and check for match on mid and bottom
var Index = DesktopReader.CachedItems[Top].Span.IndexOf(TargetBottom.Span);
if (Index > -1
&& DesktopReader.CachedItems[Top - (Offset / 2)].Span.Slice(Index).IndexOf(TargetMid.Span) == 0
&& DesktopReader.CachedItems[Top - Offset].Span.Slice(Index).IndexOf(TargetTop.Span) == 0)
{
return new Point(Index + (TargetReader.SetWidth / 2), Top - (TargetReader.SetHeight / 2));
}
Index = DesktopReader.CachedItems[Bot].Span.IndexOf(TargetTop.Span);
if (Index > -1
&& DesktopReader.CachedItems[Bot + (Offset / 2)].Span.Slice(Index).IndexOf(TargetMid.Span) == 0
&& DesktopReader.CachedItems[Bot + Offset].Span.Slice(Index).IndexOf(TargetBottom.Span) == 0)
{
return new Point(Index + (TargetReader.SetWidth / 2), Bot + (TargetReader.SetHeight / 2));
}
}
}
return default;
}
public ThisScreenSearch(Bitmap desktop)
{
BitmapToMap = desktop ?? throw new ArgumentNullException(nameof(desktop));
BitmapToMapData = desktop.LockBits(new Rectangle(0, 0, desktop.Width, desktop.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
var DScan0 = BitmapToMapData.Scan0;
DesktopReader = new BiDirectionalReader((byte*)DScan0, BitmapToMapData.Width, BitmapToMapData.Height, BitmapToMapData.Stride);
BitmapToMap.UnlockBits(BitmapToMapData);
}
}
}
</code></pre>
<p>How it can be used.</p>
<pre><code> var p = new ThisScreenSearch(NativeMethods.PrintWindow())
.CompressSearch(NativeMethods.GetBlackWhiteAt(new Point(1815,1044), new Size(16,16)));
</code></pre>
<p>It probably won't handle odd-sized bitmaps. But I am happy with the success so far.</p>
<p>Thank you for reading this and bearing with me as I sorted it out. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:00:03.063",
"Id": "469162",
"Score": "0",
"body": "Is there a specific aspect or portion of the code you feel requires more attention?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T17:20:31.380",
"Id": "469362",
"Score": "0",
"body": "It's all about the performance of the operation. I want to go fast enough to do video eventually, any steps in the direction to make it simpler, and more robust I would accept."
}
] |
[
{
"body": "<p>I am not familiar with C#.</p>\n\n<p>Here are some of my observations:</p>\n\n<ol>\n<li><p><code>++top <= (SetHeight - 1) / 2 && --bot >= (SetHeight - 1) / 2</code> is hard to read for two reasons:</p>\n\n<ol>\n<li>There are inline pre-/post-increments (<code>++top</code> and <code>--bot</code>)\n\n<ul>\n<li>Short circuiting may make the behaviour not obvious for beginners</li>\n</ul></li>\n<li>There are two conditions (<code>++top <= (SetHeight - 1) / 2</code> and <code>--bot >= (SetHeight - 1) / 2</code>)\n\n<ul>\n<li>what it is checking is not obvious</li>\n<li>I would replace it with:</li>\n</ul></li>\n</ol></li>\n</ol>\n\n<pre><code>++top\nisBottomHalf = (top <= (SetHeight - 1) / 2)\n\nif (isBottomHalf) {\n --bot\n isTopHalf = (bot >= (SetHeight - 1) / 2)\n if (isTopHalf) {\n // your code here\n }\n}\n</code></pre>\n\n<ol start=\"2\">\n<li><p>I found it odd that some variables start with capitals (<code>Bits</code>, <code>SetWidth</code>, ...) and some with lowercase (<code>topLine</code>, <code>botLine</code>, ...)</p></li>\n<li><p>The naming is inconsistent: <code>topLine</code>/<code>botLine</code> and <code>tret</code>/<code>bret</code> (the latter should be <code>topRet</code>/<code>botRet</code>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T02:40:35.177",
"Id": "469382",
"Score": "0",
"body": "Not a bad answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T19:37:07.930",
"Id": "239245",
"ParentId": "238545",
"Score": "3"
}
},
{
"body": "<p>In the <code>BiDirectionalReader</code> constructor, the while loop condition can be shortened to <code>while (++top <= --bot)</code> (or replaced with a for loop). If the bitmap height is odd, the middle row will have duplicate entries in <code>CachedItems</code>.</p>\n\n<p>It is unclear to me why you're excluding the last column when constructing the <code>BiDirectionalIndex</code> and <code>CachedItems</code> data.</p>\n\n<p>The three duplicated statements in the inner for loop can be reduced to one line each:</p>\n\n<pre><code>topLine[x] = (Bits[top * Stride + (x >> 3)] & mask) != 0;\nbotLine[x] = (Bits[bot * Stride + (x >> 3)] & mask) != 0;\n</code></pre>\n\n<p>The declaration <code>(Memory<bool> TopLine, Memory<bool> BottomLine)</code> in <code>CompressSearch</code> would be more readable if written as two separate declarations, which also allows easy use of <code>var</code>:</p>\n\n<pre><code>var TopLine = TargetReader.CachedItems[TopIndex];\nvar BottomLine = TargetReader.CachedItems[BottomIndex];\n</code></pre>\n\n<p>The <code>if (FoundTop > -1 && FoundBottom > -1)</code> check could be split up and moved into the two earlier ifs. This would allow for only checking one value (since you just assigned one value, you only need to check the other), and would then only do this check when it needs to be done, rather than every loop iteration.</p>\n\n<p>There is a bit of inconsistency in the naming style, as sometimes your identifiers start with a capital letter, other times lowercase. I had initially though this was a distinction between member variables and parameters or local variables, but I see this is not the case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T04:46:55.770",
"Id": "469328",
"Score": "0",
"body": "I'm not certain that the `while` condition can be replaced with `++top <= --bot`. On the last iteration, I think yours would increment `top` and decrement `bottom` whereas the original code and my suggestion would only increment `top`, and leave `bot` unchanged if the part before `&&` is false (because of short-circuit evaluation). These two variables are not used below the `while` loop, but may use them if the code is changed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T02:39:22.650",
"Id": "469381",
"Score": "0",
"body": "Good catch! < height -1; should be <= height - 1;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T17:35:11.723",
"Id": "469419",
"Score": "0",
"body": "@BanMe For integer types, rather than using `<= height - 1`, you can use `< height`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:15:40.827",
"Id": "239251",
"ParentId": "238545",
"Score": "2"
}
},
{
"body": "<p>This is the nth version, it is broken down into smaller functions, but uses more CPU to operate.\nI took the above advice to reduce comparisons and also attacked the Collections namespace and And Tuples.</p>\n\n<p>I also changed it from eagerly parsing the entire bitmap search area upfront to only parsing 4 lines at a time. </p>\n\n<p>In an attempt to make it more readable, I broke down operations that could take 1 line into multiline statements.</p>\n\n<p>Small improvements over last version.updates: Fourth Cache Line(QuadCache) Coding conventions followed, removed stackalloc and resulting copy from the stack, added summaries and comments.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing NoAlloq;\n\nnamespace SlidingBitmap\n{\n /// <summary>\n /// Ref struct reads bitmap and stores boolean caches of input to search for, and iterates over the internal bitmap passed in constructor\n /// Expanding Span with some NoAllog's Linq functionality for Span\n /// </summary>\n\n public ref struct SlidingBitmapCache\n {\n /// <summary>\n /// QuadCache holds Spans to 4 blocks of memory\n /// </summary>\n private ref struct QuadCache\n {\n public Span<bool> CacheFirst;\n public Span<bool> CacheSecond;\n public Span<bool> CacheThird;\n public Span<bool> CacheFourth;\n\n public QuadCache(Span<bool> cacheFirst, Span<bool> cacheSecond, Span<bool> cacheThird, Span<bool> cacheFourth)\n {\n CacheFirst = cacheFirst;\n CacheSecond = cacheSecond;\n CacheThird = cacheThird;\n CacheFourth = cacheFourth;\n }\n }\n\n // Desktop QuadCache\n private QuadCache DesktopCache;\n\n // Target QuadCache\n private QuadCache TargetCache;\n\n // Storage for localizing the Bitmaps width passed in Constructor to SlidingBitmapCache\n private readonly int DesktopWidth;\n // Indexes for Desktop and Target bitmaps\n private Span<int> DesktopIndexes;\n private Span<int> TargetIndexes;\n\n // Storage for holding the Locked Bitmap Data for unlocking \n // I can't unlock bits unless I cache input from the constructor, \n // caching leads to parsing entire bitmap upfront, not the path I want to take.\n private BitmapData DesktopData { get; }\n\n /// <summary>\n /// SlidingBitmapCache \n /// Initializes all the necessary variables Start the operation \n /// </summary>\n /// <param name=\"desktop\"></param>\n public SlidingBitmapCache(Bitmap desktop)\n {\n DesktopData = desktop.LockBits(new Rectangle(0, 0, desktop.Width, desktop.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);\n\n DesktopWidth = desktop.Width;\n\n DesktopIndexes = new int[4] { 0, 1, desktop.Height - 2, desktop.Height - 1 };\n\n TargetIndexes = new int[4] { 0, 0, 0, 0 };\n\n DesktopCache = new QuadCache(new Span<bool>(new bool[DesktopWidth]),\n new Span<bool>(new bool[DesktopWidth]),\n new Span<bool>(new bool[DesktopWidth]),\n new Span<bool>(new bool[DesktopWidth]));\n\n TargetCache = new QuadCache(Span<bool>.Empty,\n Span<bool>.Empty,\n Span<bool>.Empty,\n Span<bool>.Empty);\n\n CacheLinesAt(DesktopData, DesktopIndexes, DesktopCache);\n }\n\n /// <summary>\n /// CacheLinesAt \n /// copies lines referenced by indexes in data to cache\n /// </summary>\n /// <param name=\"data\"></param>\n /// <param name=\"indexes\"></param>\n /// <param name=\"cache\"></param>\n private void CacheLinesAt(BitmapData data, Span<int> indexes, QuadCache cache)\n {\n var dataStride = data.Stride;\n // iterate over the width of the bitmap on all lines\n for (int x = 0; x <= data.Width - 1; x++)\n {\n unsafe\n {\n byte* ptr = (byte*)data.Scan0;\n byte* calcPtr = ptr + (indexes[0] * dataStride) + (x >> 3);\n byte firstRet = *calcPtr;\n calcPtr = ptr + ((indexes[1]) * dataStride) + (x >> 3);\n byte secondRet = *calcPtr;\n calcPtr = ptr + (indexes[2] * dataStride) + (x >> 3);\n byte thirdRet = *calcPtr;\n calcPtr = ptr + (indexes[3] * dataStride) + (x >> 3);\n byte fourthRet = *calcPtr;\n byte Mask = (byte)(0x80 >> (x & 0x7));\n firstRet &= Mask;\n secondRet &= Mask;\n thirdRet &= Mask;\n fourthRet &= Mask;\n cache.CacheFirst[x] = firstRet > 0;\n cache.CacheSecond[x] = secondRet > 0;\n cache.CacheThird[x] = thirdRet > 0;\n cache.CacheFourth[x] = fourthRet > 0;\n }\n }\n }\n\n /// <summary>\n /// GetLineAt is used for inline repositioning of a Single Cache line.\n /// Works the same as above.\n /// </summary>\n /// <param name=\"data\"></param>\n /// <param name=\"index\"></param>\n /// <param name=\"cache\"></param>\n private void GetLineAt(BitmapData data, int index, Span<bool> cache)\n {\n unsafe\n {\n void* ptr = (byte*)data.Scan0;\n // iterate over the width of the bitmap on both lines\n for (int x = 0; x <= data.Width - 1; x++)\n {\n byte ret = *((byte*)ptr + (index * data.Stride) + (x >> 3));\n ret &= (byte)(0x80 >> (x & 0x7));\n cache[x] = ret > 0;\n }\n }\n }\n\n /// <summary>\n /// GetGoodCacheLinesAt is designed for pulling cache lines with bits set for top and bottom Cache Lines\n /// as well as setting 2nd and 3rd lines.\n /// </summary>\n /// <param name=\"target\"></param>\n /// <returns name =\"Span<int>\"></returns>\n private Span<int> GetGoodCacheLines(Bitmap target)\n {\n int targetWidth = target.Width;\n int targetHeight = target.Height - 1;\n TargetIndexes = new int[] { 0, 1, targetHeight -2, targetHeight -1 };\n TargetCache = new QuadCache(new Span<bool>(new bool[targetWidth]),\n new Span<bool>(new bool[targetWidth]),\n new Span<bool>(new bool[targetWidth]),\n new Span<bool>(new bool[targetWidth]));\n\n Span<int> result = new int[] { -1, -1, -1, -1 };\n\n BitmapData Data = target.LockBits(new Rectangle(0, 0, targetWidth, targetHeight), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);\n\n while (TargetIndexes[1] <= (target.Height - 1) / 2)\n {\n CacheLinesAt(Data, TargetIndexes, TargetCache);\n\n if (result[0] == -1 && TargetCache.CacheFirst.AnyTrue())\n {\n result[0] = TargetIndexes[0];\n }\n\n if (result[3] == -1 && TargetCache.CacheFourth.AnyTrue())\n {\n result[3] = TargetIndexes[3];\n }\n\n if( result[0] > -1 && result[3] > -1)\n {\n target.UnlockBits(Data);\n result[1] = TargetIndexes[1];\n result[2] = TargetIndexes[2];\n return result;\n }\n\n ++TargetIndexes[0];\n ++TargetIndexes[1];\n --TargetIndexes[2];\n --TargetIndexes[3];\n }\n target.UnlockBits(Data);\n return result;\n }\n // TODO:\n /// <summary>\n /// Check 4 Cached lines of target against that of search area\n /// offsets desktop caches to find matches restoring changes\n /// I want to avoid allocations and copying here as much as feasible\n /// </summary>\n /// <param name=\"offsets\"></param>\n private Point CheckCaches(Span<int> offsets)\n {\n int firstIndex = DesktopCache.CacheFirst.IndexOf(TargetCache.CacheFourth);\n if (firstIndex > -1)\n {\n\n }\n int secondIndex = DesktopCache.CacheSecond.IndexOf(TargetCache.CacheFourth);\n if (secondIndex > -1)\n {\n\n }\n int thirdIndex = DesktopCache.CacheThird.IndexOf(TargetCache.CacheFirst);\n if (thirdIndex > -1)\n {\n\n }\n int fourthIndex = DesktopCache.CacheFourth.IndexOf(TargetCache.CacheFirst);\n if (fourthIndex > -1)\n {\n\n }\n return default;\n }\n\n /// <summary>\n /// The public API for \n /// this takes target bitmap and iterates of iternal search area\n /// checking the cache at each iteration\n /// </summary>\n /// <param name=\"target\"></param>\n /// <returns>Point</returns>\n public Point LineCachingSearch(Bitmap target)\n {\n Span<int> indexes = GetGoodCacheLines(target);\n while (DesktopIndexes[1] <= (DesktopData.Height - 2) / 2)\n {\n if (CheckCaches(indexes) == default)\n {\n ++DesktopIndexes[0];\n ++DesktopIndexes[1];\n --DesktopIndexes[2];\n --DesktopIndexes[3];\n CacheLinesAt(DesktopData, DesktopIndexes, DesktopCache);\n }\n }\n return default;\n }\n }\n}\n</code></pre>\n\n<p>Not complete, just POC, Search algorithm with NoAlloq LINQ on Span forthcoming.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T19:15:52.457",
"Id": "239376",
"ParentId": "238545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239251",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T01:27:43.273",
"Id": "238545",
"Score": "5",
"Tags": [
"c#"
],
"Title": "CompressSearch algorithm"
}
|
238545
|
<pre><code>public sealed class Class1
{
Class1()
{
}
private static readonly object padlock = new object();
private static Class1 instance = null;
public static Class1 Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Class1();
}
}
}
return instance;
}
}
public bool EncryptFile(string path)
{
string ext = Path.GetExtension(path).Replace(".","");
string filename = Path.GetFileNameWithoutExtension(path);
byte[] b= System.Text.ASCIIEncoding.ASCII.GetBytes(ext);
string encrypted = Convert.ToBase64String(b);
var newPath = path.Replace(filename+"."+ext, filename+"_"+ encrypted + ".vik");
try
{
string password = @"vik12389"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = newPath;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(path, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
File.Delete(path);
return true;
}
catch(Exception e)
{
return false;
}
}
public bool DecryptFile(string path)
{
string ext = Path.GetExtension(path).Replace(".", "");
string filename = Path.GetFileNameWithoutExtension(path);
string[] splitFilename = filename.Split('_');
byte[] b = Convert.FromBase64String(splitFilename[1]);
string decryptedfileext = System.Text.ASCIIEncoding.ASCII.GetString(b);
var newPath = path.Replace(filename + ".vik", splitFilename[0] + '.'+ decryptedfileext);
try
{
string password = @"vik12389"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(path, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(newPath, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
</code></pre>
<p>My Project Link on GitHub :<a href="https://github.com/vivianm94/EncryptFile" rel="nofollow noreferrer">https://github.com/vivianm94/EncryptFile</a>.
how do I improve my code any suggestion.any features that could be added to the project</p>
|
[] |
[
{
"body": "<p>So, the most interesting bits about this code are the wildly differing styles throughout. It seems as it's almost copy-and-pasted from several sources. The reason I bring this up is because <strong>consistency</strong> is a hallmark of clean and maintainable code. A few things I noticed:</p>\n\n<ol>\n<li><p>There's a debunked use of \"double-checked locking\" to attempt to use a lazily-instantiated singleton. Two things with this: A. This class doesn't have state and could be <code>static</code> to begin with, and thus do not need to worry about instances at all, and B. There's a very easy way these days to have a lazy singleton: the <code>Lazy<T></code> class. You'll see its usage below.</p></li>\n<li><p>There's a mish-mash of <code>ASCIIEncoding.ASCII</code> and <code>new UnicodeEncoding()</code>. The canonical way to access predefined encodings is through static members of the <code>Encoding</code> class: <code>Encoding.ASCII</code> and <code>Encoding.Unicode</code>.</p></li>\n<li><p><code>Path.Combine()</code> is wisely used to, of course, combine paths. But then string concatenation is used to pop an extension on the file name. <code>Path.ChangeExtension()</code> exists for just this task.</p></li>\n<li><p><code>x.Close()</code> isn't needed if you wrap your <code>IDisposable</code> resources in <code>using</code> blocks. This also has the benefit of guaranteeing disposal/closing in the case of an exception (it's syntactic sugar for a <code>try..finally</code> construct`.</p></li>\n<li><p>There's a mix of using and not using <code>var</code> for variable declarations. Since the latter is less than the former, standardize on just using the actual type name for declarations.</p></li>\n<li><p>I added two more - you don't need to read/write the file byte by byte. These are streams for a reason, and .NET gives us a handy method <code>CopyTo</code> to take care of the details. Also, <code>CreateEncrpytor</code> and <code>CreateDecryptor</code> return <code>IDisposable</code>-implementing classes, so I extracted them into their own <code>usings</code>.</p></li>\n</ol>\n\n<p>Putting all that together, the class now looks like (note that I went with <code>Lazy<T></code> rather than <code>static</code> class):</p>\n\n<pre><code>public sealed class Class1\n{\n private static readonly Lazy<Class1> instance = new Lazy<Class1>(() => new Class1());\n public static Class1 Instance => instance.Value;\n\n public bool EncryptFile(string path)\n {\n string ext = Path.GetExtension(path).Replace(\".\", string.Empty);\n string filename = Path.GetFileNameWithoutExtension(path);\n\n byte[] b = Encoding.ASCII.GetBytes(ext);\n string encrypted = Convert.ToBase64String(b);\n string newPath = path.Replace(Path.ChangeExtension(filename, ext), filename + \"_\" + encrypted + \".vik\");\n\n try\n {\n string password = @\"vik12389\"; // Your Key Here\n byte[] key = Encoding.Unicode.GetBytes(password);\n\n string cryptFile = newPath;\n using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create))\n using (RijndaelManaged RMCrypto = new RijndaelManaged())\n using (ICryptoTransform ct = RMCrypto.CreateEncryptor(key, key))\n using (CryptoStream cs = new CryptoStream(fsCrypt,\n ct,\n CryptoStreamMode.Write))\n using (FileStream fsIn = new FileStream(path, FileMode.Open))\n {\n fsIn.CopyTo(cs);\n }\n\n File.Delete(path);\n\n return true;\n\n }\n catch(Exception e)\n {\n return false;\n }\n }\n\n public bool DecryptFile(string path)\n {\n string ext = Path.GetExtension(path).Replace(\".\", string.Empty);\n string filename = Path.GetFileNameWithoutExtension(path);\n\n string[] splitFilename = filename.Split('_');\n\n byte[] b = Convert.FromBase64String(splitFilename[1]);\n\n string decryptedfileext = Encoding.ASCII.GetString(b);\n\n string newPath = path.Replace(Path.ChangeExtension(filename, \"vik\"), splitFilename[0] + '.'+ decryptedfileext);\n try\n {\n string password = @\"vik12389\"; // Your Key Here\n\n byte[] key = Encoding.Unicode.GetBytes(password);\n\n using (FileStream fsCrypt = new FileStream(path, FileMode.Open))\n using (RijndaelManaged RMCrypto = new RijndaelManaged())\n using (ICryptoTransform ct = RMCrypto.CreateDecryptor(key, key))\n using (CryptoStream cs = new CryptoStream(fsCrypt,\n ct,\n CryptoStreamMode.Read))\n using (FileStream fsOut = new FileStream(newPath, FileMode.Create))\n {\n cs.CopyTo(fsOut);\n }\n\n return true;\n\n }\n catch (Exception e)\n {\n return false;\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T14:52:33.317",
"Id": "467885",
"Score": "0",
"body": "Thank you for your feedback. I will improve it. can you give me any suggestion regarding and feature which could be added to the project"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T14:18:57.253",
"Id": "238564",
"ParentId": "238547",
"Score": "6"
}
},
{
"body": "<p>I'll not go into the C# coding part as much, as Jesse already covered that part.</p>\n\n<p>It' not clear to me why any class should be called <code>Class1</code>. That a bad name. Even if it is just used for a particular function, then it should be named after this particular function.</p>\n\n<p>It's not a good idea to have two instances <code>instance</code> and <code>Instance</code>.</p>\n\n<hr>\n\n<p>There is nothing to indicate that a new filename is generated, nor how it will be generated. And possibly that's a good thing, as none of it makes sense. The extension is not encrypted but encoded. The filename + extension is replaced by calling <code>replace</code>, which means that if the file + extension is present elsewhere that the function will fail. Furthermore, there are a lot of changes to extension and filename just to create it back again.</p>\n\n<p>The key should be configurable, and not be in code. Keys are not strings, they should be bytes where the bytes are not predictable to an adversary. Strings cannot hold any byte value, and therefore the precondition fails. Even worse, if you use <code>Unicode</code> then you will get 2 bytes for each character. If those characters are common ASCII then one of those bytes will simply be valued zero. Basically you have about 33% of the key space left.</p>\n\n<p>Even worse, people are terrible at creating strong passwords, so the amount of entropy and password space to search is likely to be low enough to make the scheme easy to break. If you want to use a password, then use e.g. PBKDF2, a salt and a high iteration count. As it is, your password will be easier to crack than single DES.</p>\n\n<p>You are using the same key as IV. The key should never ever be used as IV. The IV is considered public, and the key is not. It is unlikely that the platform will even try to keep the IV a secret. For instance, such values are more likely to be kept unprotected in memory. Any CPA secure cipher requires a unique IV / key pair, and CBC - which you're using - requires more: a fully unpredictable IV. As you fail to provide that it will be easy to guess information within files that start with the same plaintext.</p>\n\n<p>Generally we nowadays try and use an authenticated mode such as GCM by default. If that's not available to you, then calculating an additional HMAC over IV and ciphertext can be used to generate an authentication tag. This tag can be verified before the data is decrypted again. This requires you to store the IV with the ciphertext. Note that verification should be performed using a time-constant compare.</p>\n\n<p>Changes of the file can be detected if you use an authentication tag. Currently, your decryption may successfully finish <em>even if the wrong key is used</em>. PKCS#7 padding - which is used by default for CBC mode in .NET (and most other frameworks / crypto libs) - has about a 1 in 256 chance to unpad successfully given random bytes. In that case you would get a random plaintext, and <em>no error</em> whatsoever.</p>\n\n<p>I really don't like the <code>false</code> that is returned if <em>anything</em> fails. The possible error conditions are just swept under the rug. So there is no chance of cleaning up problems when something fails.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:35:16.467",
"Id": "238587",
"ParentId": "238547",
"Score": "3"
}
},
{
"body": "<p>As others have covered the technical details of the encodings and encryption, here's example of a more object-oriented approach (via inheritance rather than encapsulation). As encrypting and decrypting have a lot of common elements, this example also aims to reduce code duplication.</p>\n\n<pre><code>class App_FileEncryption\n{\n public void Run()\n {\n var originalFile = new UnencryptedFile(@\"c:\\temp\\myFile.txt\", \"vik123\");\n originalFile.Encrypt();\n\n var encryptedFile = new EncryptedFile(@\"c:\\temp\\myFile_encrypted.txt\", \"vik123\");\n encryptedFile.Decrypt();\n }\n}\n\npublic abstract class File\n{\n protected string path;\n protected string password;\n\n protected FileStream fsCrypt => new FileStream(path, FileMode.Open);\n protected byte[] key => new UnicodeEncoding().GetBytes(password);\n protected RijndaelManaged RMCrypto = new RijndaelManaged();\n protected string targetPath => getTargetPath();\n protected string ext => Path.GetExtension(path).Replace(\".\", \"\");\n protected string filename => Path.GetFileNameWithoutExtension(path);\n\n protected abstract CryptoStream cs { get; }\n\n protected File(string path, string password)\n {\n this.path = path;\n this.password = password;\n }\n\n protected abstract string getTargetPath();\n}\n\npublic class EncryptedFile : File\n{\n protected override CryptoStream cs =>\n new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Read);\n\n public EncryptedFile(string path, string password) : base(path, password)\n {\n }\n\n public void Decrypt()\n {\n ///do stuff, output to targetPath\n }\n\n protected override string getTargetPath()\n {\n var splitFilename = filename.Split('_');\n var b = Convert.FromBase64String(splitFilename[1]);\n var decryptedfileext = ASCIIEncoding.ASCII.GetString(b);\n return path.Replace(filename + \".vik\", splitFilename[0] + '.' + decryptedfileext);\n }\n}\n\npublic class UnencryptedFile : File\n{\n protected override CryptoStream cs =>\n new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);\n\n public UnencryptedFile(string path, string password) : base(path, password)\n {\n }\n\n public void Encrypt()\n {\n ///do stuff, output to targetPath\n }\n\n protected override string getTargetPath()\n {\n var b = ASCIIEncoding.ASCII.GetBytes(ext);\n var encrypted = Convert.ToBase64String(b);\n return path.Replace(filename + \".\" + ext, filename + \"_\" + encrypted + \".vik\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T20:45:26.880",
"Id": "239076",
"ParentId": "238547",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T02:54:35.793",
"Id": "238547",
"Score": "2",
"Tags": [
"c#",
"cryptography"
],
"Title": "App to Encrypt and Decrypt file"
}
|
238547
|
<p>I have a input with some transaction data in json input (in this case a file)</p>
<pre><code>{ "timestamp": "2019-01-01 12:00:00", "customer": "customer-1", "page": "product", "product": "product-1" }
{ "timestamp": "2019-01-01 12:02:00", "customer": "customer-1", "page": "basket", "product": "product-1" }
{ "timestamp": "2019-01-01 12:04:00", "customer": "customer-1", "page": "checkout" }
{ "timestamp": "2019-01-01 13:00:00", "customer": "customer-2", "page": "product", "product": "product-2" }
{ "timestamp": "2019-01-01 13:02:00", "customer": "customer-2", "page": "basket", "product": "product-2" }
{ "timestamp": "2019-01-01 14:00:00", "customer": "customer-3", "page": "product", "product": "product-3" }
{ "timestamp": "2019-01-01 14:05:00", "customer": "customer-3", "page": "basket", "product": "product-3" }
{ "timestamp": "2019-01-01 14:10:00", "customer": "customer-3", "page": "product", "product": "product-4" }
{ "timestamp": "2019-01-01 14:16:00", "customer": "customer-3", "page": "product", "product": "product-5" }
{ "timestamp": "2019-01-01 14:20:00", "customer": "customer-3", "page": "basket", "product": "product-4" }
{ "timestamp": "2019-01-01 14:21:00", "customer": "customer-3", "page": "checkout" }
{ "timestamp": "2019-01-01 15:00:00", "customer": "customer-9", "page": "product", "product": "product-3" }
{ "timestamp": "2019-01-01 15:11:00", "customer": "customer-9", "page": "basket", "product": "product-3" }
</code></pre>
<p>The idea is be able to identify abandoned sessions, for example with more than 10 minutes idle. Transactions <strong>checkedout</strong> cannot be considered abandoned. The code to process is is below</p>
<pre><code>import argparse
import json
import logging
import os
import arrow
import apache_beam as beam
from apache_beam.io import ReadFromText, WriteToText
from apache_beam import ParDo, Pipeline, Map, GroupByKey, Partition
from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions
class JsonCoder:
"""A simple encoder/decoder for JsonNL format"""
@staticmethod
def encode(stream):
return bytes(json.dumps(stream.as_dict()), 'utf8')
@staticmethod
def decode(stream):
return json.loads(stream)
class PageViews:
"""Datastructure to handle, store and view PageViews entries"""
def arrow_to_json(self):
return self.timestamp.format('YYYY-MM-DD HH:mm:ss')
def __init__(self, timestamp, customer, page, product=None):
self.timestamp = arrow.get(timestamp)
self.customer = customer
self.page = page
self.product = product
def as_dict(self):
json_dict = {'customer': self.customer,
'page': self.page,
'timestamp': self.arrow_to_json()}
if self.product is not None:
json_dict['product'] = self.product
return json_dict
def __str__(self):
return f'{self.customer};{self.arrow_to_json()};{self.page};{self.product} '
def __repr__(self):
repr_fmt = 'PageViews(customer={}, timestamp={}, page={}, product={}'
return repr_fmt.format(self.customer, self.arrow_to_json(), self.page, self.product)
class JsonToPageViews(beam.DoFn):
"""A simple processor to be used while converting Json entries to PageViews struct"""
def process(self, element, **kwargs):
# Necessary to "normalize" the Json readings
if 'product' not in element:
element['product'] = None
pv = PageViews(timestamp=element['timestamp'],
customer=element['customer'],
page=element['page'],
product=element['product'])
yield pv
class OnlyExpired(beam.DoFn):
def process(self, element, **kwargs):
customer, entries = element
o_timestamp = entries[0].timestamp.timestamp
checkout = False
expired = False
last_entry = None
for num, entry in enumerate(entries[0:]):
n_timestamp = entry.timestamp.timestamp
d_timestamp = n_timestamp - o_timestamp
o_timestamp = n_timestamp
if d_timestamp > 60*10:
expired = True
if entry.page == 'checkout':
checkout = True
last_entry = entry
if not checkout:
expired = True
if expired:
yield last_entry
class GetTimestamp(beam.DoFn):
"""A Process just to check if timestamps where correctly assigned"""
def process(self, element, timestamp=beam.DoFn.TimestampParam, **kwargs):
yield '{} - {}'.format(timestamp.to_utc_datetime(), element)
def partition_fn(pageview, num_partitions=1):
"""Partition the customer based on customer_id"""
customer_id = int(pageview.customer.split('-')[1])
return customer_id % num_partitions
def run(argv=None, save_main_session=True):
"""Entry point for main code"""
# Processing Command Line Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--input', help='Input files', default='input/page-views.json')
parser.add_argument('--output', help='Output dir', default='output')
known_args, pipeline_args = parser.parse_known_args(argv)
pipeline_options = PipelineOptions(pipeline_args)
pipeline_options.view_as(SetupOptions).save_main_session = save_main_session
# Create the pipeline
p = Pipeline(options=pipeline_options)
res = (p
| 'Read JSON files' >> ReadFromText(known_args.input, coder=JsonCoder())
| 'Convert JSON to Pageview' >> ParDo(JsonToPageViews())
| 'Add Timestamps' >> Map(lambda entry: beam.window.TimestampedValue(entry, entry.timestamp.timestamp))
| 'Create Group Key' >> Map(lambda entry: (entry.customer, entry))
| GroupByKey()
| 'Only Expired' >> ParDo(OnlyExpired())
| 'Partition' >> Partition(partition_fn, 2)
)
res[0] | 'Save Part0' >> WriteToText(os.path.join(known_args.output, "abandoned-carts-part0"), file_name_suffix='.json', coder=JsonCoder())
res[1] | 'Save Part1' >> WriteToText(os.path.join(known_args.output, 'abandoned-carts-part1'), file_name_suffix='.json', coder=JsonCoder())
p.run()
if __name__ == '__main__':
logging.getLogger().setLevel(logging.WARN)
run()
</code></pre>
<p>I personally didn't like the way I have handled the idle sessions with a custom class <code>OnlyExpired</code>, since I need to save a session variable. I think is a bottleneck in case of streaming. How can I improve this code?</p>
<p>I also added a partition to split data when needed (in this case my customer name).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T09:58:43.077",
"Id": "467858",
"Score": "0",
"body": "please, some moderator can create and assign the tag: `apache-beam` ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T04:31:19.543",
"Id": "238549",
"Score": "2",
"Tags": [
"python",
"data-mining",
"apache-beam"
],
"Title": "How to avoid bottlenecks json processing with Apache Beam?"
}
|
238549
|
<p>My code works, but it seems to be running exceptionally slow.</p>
<p>I have an array of values to search, and I have a JSON that I'm filtering.</p>
<pre><code>var JSONPull;
var FilterJSON = [];
var TypeIDs = [34,35,36,37,38,39,40,11399,1230,17470,17471,1228,17463,17464,1224,17459,17460,18,17455,17456,1227,17867,17868,20,17452,17453,1226,17448,17449,21,17440,17441,1231,17444,17445,1229,17865,17866,1232,17436,17437,19,17466,17467,1225,17432,17433,1223,17428,17429,22,17425,17426,11396,17869,17870];
fetch('URL API')
.then(res => res.json())
.then((out) => {
JSONPull = out;
TypeIDs.forEach(function (index){
FilterJSON = JSONPull.filter((element) => {
console.log("index: "+index);
console.log(element);
console.log("type_id: "+ element.type_id);
element.type_id === index;
});
})
})
</code></pre>
<p>The console.logs are more just to watch the code while testing, but definitely shouldn't be causing these performance issues.</p>
<p>Thanks in advance for any help/assistance</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T13:01:16.230",
"Id": "467881",
"Score": "1",
"body": "logging to console is notoriously slow. If you remove the console.log calls, what's your performance benefit roughly like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:02:45.447",
"Id": "467948",
"Score": "0",
"body": "is `type_id` is unique? or there are duplicates? if it's unique you can use `indexOf` / `includes` to filter. Also after you match an item you can splice the matched `typeID` out of the array. Because with filter you will walk through entire array even after you have a match. So your complexity is O(n^2)"
}
] |
[
{
"body": "<p>You are basically making your object filtering into an <span class=\"math-container\">\\$0(m * n)\\$</span> complexity function ( where <span class=\"math-container\">\\$m\\$</span> is number of type id’s) that your are filtering against and <span class=\"math-container\">\\$n\\$</span> is number of objects in the fetched result set. This function should only be <span class=\"math-container\">\\$0(n)\\$</span>. </p>\n\n<p>To do this, make type id’s into a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\"><code>Set</code></a> which allows <span class=\"math-container\">\\$O(1)\\$</span> lookup and then use this <code>Set</code> to filter the fetched objects.</p>\n\n<p>For example:</p>\n\n<pre><code>const typeIds = new Set([ /* ids here */ ]);\nconst isFilteredType = (element) => typeIds.has(element.type);\n\n// and later when filtering results\n.then( (out) => out.filter(isFilteredType) );\n</code></pre>\n\n<p>It is also customary in javascript to use lowercase first letter for variable names. Your code would look odd to most JS developer for this reason. </p>\n\n<p>There is really not much of a reason to use <code>var</code> in modern JavaScript. You should primarily use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> being used where the variable needs to be reassignable.</p>\n\n<p>It is not really clear here why <code>JSONpull</code> and <code>FilterJSON</code> are even needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T04:19:28.633",
"Id": "238750",
"ParentId": "238550",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T06:00:58.377",
"Id": "238550",
"Score": "0",
"Tags": [
"javascript",
"performance",
"json"
],
"Title": "Filtering JSON objects from array of values"
}
|
238550
|
<p>After watching a recent <a href="https://www.youtube.com/watch?v=G_UYXzGuqvM" rel="nofollow noreferrer">computerphile video</a> on building a very simple sudoku solver I tried to implement the same in Haskell. From <a href="https://codereview.stackexchange.com/q/9281/51266">this CR question</a> I learned that it is probably a better idea to use Vectors instead of just lists to represent a <em>grid</em> of numbers that is gonna be mutated. (But it is supposedly still worse than using a sparse representation.) And from <a href="https://codereview.stackexchange.com/q/164317/51266">this one</a> (and <a href="https://codereview.stackexchange.com/questions/166865/puzzle-game-solver-via-backtracking">another question of mine</a>) I learned about <code>Control.Lens</code>, but I decided against using it to avoid using many different packages that I'm not familiar with.</p>
<p>Now the program I wrote is close to the original in python, but very slow. So I would like to get some feedback on how to speed it up without deviating form this very simple aproach too much.</p>
<h3>The Program</h3>
<p>The code defines a <code>Board</code> that represents a (solved or unsolved) state, with zeros for the entries that area yet to be determined. It can be indexed using <code>Coordinates</code>. Then there are a few setters and getters that probably could be replaced by using <code>Control.Lens</code> - but I'd like to avoid that for now as I just want to focus on the performance. Then there is a <code>possible</code> function which takes a <code>Board</code>, <code>Coordinates</code> and a candidate number an just reports whether it is possible to put the candidate at some given coordinates. Finally there is <code>solve</code> that does the backtracking.</p>
<p>So far I tried to add a <code>take 1 $</code> or <code>take 1 $!</code> to speed it up (but only returning at most a single solution), but without success.</p>
<pre class="lang-hs prettyprint-override"><code>--https://www.youtube.com/watch?v=G_UYXzGuqvM
import qualified Data.Vector as V
data Board = Board (V.Vector (V.Vector Integer))
type Coordinates = (Int, Int)
instance Show Board where
show (Board b)=unlines . V.toList $ V.map show b
fromList :: [[Integer]] -> Board
fromList l = Board $ V.fromList $ V.fromList <$> l
-- a few setters and getters
(!):: Board -> Coordinates -> Integer
(Board b) ! (i,j) = (b V.! j)V.! i
getColumn :: Board -> Coordinates -> [Integer]
getColumn b (i, _) = [b ! (i, j) | j<-[0..8]]
getRow :: Board -> (Int, Int) -> [Integer]
getRow b (_, j) = [b ! (i, j) | i<-[0..8]]
getSquare :: Board -> Coordinates -> [Integer]
getSquare b (i, j) = [b ! (i'*3 + u, j'*3 + v) | u<-[0..2],v<-[0..2]]
where i' = i `div` 3
j' = j `div` 3
insert :: Board -> Coordinates -> Integer -> Board
insert (Board b) (i, j) k = Board b'
where v = b V.! j
v' = v V.// [(i, k)]
b' = b V.// [(j, v')]
-- check whether it is possible to insert candidate at given position
possible :: Board -> Coordinates -> Integer -> Bool
possible b coords@(i, j) k
|i < 0 || i >= 9 || j < 0 || j >= 9 || k < 0 || k > 9 = undefined
|b ! coords > 0 = False
|k `elem` getRow b coords = False
|k `elem` getColumn b coords = False
|k `elem` getSquare b coords = False
|otherwise = True
-- check whether board is already full
full :: Board -> Bool
full b = 0 `notElem` [b ! (i,j) | i<-[0..8], j<-[0..8]]
-- recursion to find all solutions to a given board
solve :: Board -> [Board]
solve b
|full b = [b]
|otherwise = concat[ solve $! (insert b (x, y) n)|
x<-[0..8],
y<-[0..8],
n<-[1..9],
possible b (x,y) n]
main = print $ solve b
-- normal sudoku
b :: Board
b = fromList [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
]
-- only one a few entries are missing
c :: Board
c = fromList [
[0,0,0,0,9,4,5,6,1],
[9,2,1,5,3,6,8,7,4],
[4,5,6,7,8,1,9,2,3],
[1,4,7,3,5,9,2,8,6],
[2,8,3,6,1,7,4,5,9],
[5,6,9,8,4,2,3,1,7],
[6,7,4,9,2,5,1,3,8],
[8,9,2,1,7,3,6,4,5],
[3,1,5,4,6,8,7,9,2]]
</code></pre>
<p><a href="https://tio.run/##jVVrb@JGFP0@v@JGihS8Na8AAaKQVt12V5XaL91utJVlhbE9hAEzw9pjs1T89/Te8dhA9hlHznDm3DPnPoYseb4Wafr83G4vjdnmt93ubrfr7HVhikh0Yr3p7riJlz@Xs7eP7//98N/b4mP5F5Obrc4MfCx4KhdSJPAbN7zzIGKjM@A5PDCWIAK/ap4lMHN/Ww815bj6QxnxJDLPY2a/FfBa6yyRihuRY1gLd32ieIxJlRuuYgHvlnrnBHdLkQkGOSGtCoq8WaFSqTC@Aw8do/@UuYFLXG74tmJGjC0yvbEbt7cQBM5DGEL7vlI@EtLGPWk08NmHu8t7SBlrt4HDQuwgF8aILAeuEniq1qx14eFZlRKecponfnQOWJMEXEBL@iuPihABHnYBK4/ekjGUfK3TYqPgG4pNUif0iDThkUSDqDoBVeEAq7t20Ot0JmFo1f/GIp1KH9vwmTJRUfbRCr2Uleey73BcMvHDph09qvUa9atXA/gJCgSrVUlnFdVZ16Ff1quQVQMC8gqDJcwTWc5hwKD6WRG6alAaMJEZ@H6XjlPiQo5dc1bXzdBEV7WJErGoamTtoCQHJWLdLgQUuvbCei@6cny7t/KRfNy0sxYvRbwmcYP6IA3IHLY6z2WUCjAanLkYp1DiZRTADTzJUihiSSO1Yg39R5PW6TEmgpiY@S910gwOEu6gBwdsPdzPYEqrVQ2tGmhdQ2u4R2QGhUrEAu9sghLU40oYN3u4@YanOV7ywxrmIhWbOTRj52hfpjQz/01WM2SfsTSVdSdzgdg/WSG@UPPIlgzLztNM8GQPiyJNGb3OCmrLZtEItXowV9r8bg3U1@X8tvhn9xFPzURcZDk2jNqKdUrwwBRyTJC6mBPKXWutJYZb5XlTA7sK3U6E@TWGgih8kS4WQ8XcBFCxL8ljNUx4GT/5sPdAeYd6GF/@fGry@Bpj/12GQka/05l@nXEyhmiJHGGtNlwq9L/NpKKv6DpZqqHS2YZj0YpErwsWNcVhVILmmzxgEIz8gd/DZ2zf@JCJ4Mau@/7UH52gPfw8qXn@jUMnx8/2GVh0aNe0V@n3LVqfcl3HON2bRvWaYhxKz9C6oNXoBO05H2N/iu3EX0paq3SPL@H@LwllMom3miZ@I7F@6onFx0rELytRK0/xzBE6qhxP0VHfpyrd4Jljf@iyI8YYEXJ37XLuY@QYmSOLTVx2tKLoPkXTnkUpnqo5pGjac3UnDkWPEBv4E1fhysXY6gxdJQbW19D5Qgben@fn/wE" rel="nofollow noreferrer" title="Haskell – Try It Online">Try it online!</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T10:31:42.043",
"Id": "467862",
"Score": "0",
"body": "Since I don't have a Haskell environment at hand, just a short question instead of a full-answer: did you profile your program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T10:49:57.567",
"Id": "467864",
"Score": "1",
"body": "@Zeta No I haven't, thanks for the suggestion. Can you recommend a place to start out with profiling? I have never profiled Haskell programs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T11:18:47.370",
"Id": "467868",
"Score": "0",
"body": "That's from the top of my head, but try `-prof -fprof-auto -O<optimization-level>` via GHC. If you use `stack`, there should be `--profile` for `stack`'s build command. Afterwards, you have to tell the runtime to write a profile. On your application, use `+RTS -p`. That's the quick gist. I believe some of my old answers here on CR contain examples on profiling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T11:22:49.697",
"Id": "467869",
"Score": "0",
"body": "Keep in mind that you need to compile all your dependencies (e.g. `vector` and probably `primitive`) also with profiling enabled, which can take a while."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T11:28:14.067",
"Id": "467870",
"Score": "0",
"body": "@Zeta Thanks, I'm trying this right now - I do have some errors to figure out but I'll report back as soon as I get it running:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T11:31:01.207",
"Id": "467871",
"Score": "1",
"body": "*\"Now the program I wrote is close to the original in python, but very slow. \"* I'm currently running your program on a Windows 10 machine with profiling enabled, and thus far it took more than 7 minutes without any result. How slow is \"very slow\" on your site?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T12:27:40.347",
"Id": "467878",
"Score": "0",
"body": "It never let it terminate. I now realized I made a mistake: Even in the event of success no sudoku is returned - I now fixed that and added a trivial test case `c` just as a sanity check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T12:48:32.240",
"Id": "467880",
"Score": "0",
"body": "@Zeta Thanks for your advice, it turns out I misunderstood something in the way the python program worked that I should have caught when testing. With a small modification it runs fine."
}
] |
[
{
"body": "<p>It turns out I made some crucial mistakes: The iteration in <code>solve</code> can stop as soon we have tried all possibilities for <em>one</em> coordinate <code>(x,y)</code> that is not set yet. If we iterate further over <code>(x,y)</code> we get duplicate solutions which makes things blow up, so with following little modification we get results immediately:</p>\n\n<pre><code>isEmpty :: Board -> Coordinates -> Bool\nisEmpty b coords = b ! coords == 0\n\n-- check whether board is already full\nfull :: Board -> Bool\nfull b = 0 `notElem` [b ! (i,j) | i<-[0..8], j<-[0..8]]\n\n-- recursion to find all solutions to a given board\nsolve :: Board -> [Board]\nsolve b\n |full b = [b]\n |otherwise = concat[ solve $! (insert b (x, y) n)|\n (x,y) <- take 1 empty,\n n <- [1..9],\n possible b (x,y) n]\n where empty = [(x,y) | x<-[0..8],y<-[0..8], isEmpty b (x, y)]\n</code></pre>\n\n<p><a href=\"https://tio.run/##jVVra9swFP2uX3ELhcabk6XPtaMpYy8Y7NM6@sWYRY6VVrEjZZacLpD/nt0r2XLSdtlicOWjo3MfOpc@cFOIstxs5HyhKwu/al7KqRQ5fOKWD@7ExOoKuIE7xnJE4IPmVQ6j5m/vrqV0q6/KintRRRGzq4WAj1pXuVTcCoPHergbEyViTCpjuZoIuH3Qj43g44OoBANDSM9DWTSqVSkVnh/A3cDqb9JYOMTlnC88M2NsWum523j3DpKkySFNoX/jlTtCGbInjQDvfFwf3kDJWL8PHKbiEYywVlQGuMrh3q9Z7yDCWF4Jo2zXiZ9NBiwUAQfQk/EsoiZkgMEOYBbRWzKGkh91Wc8V7FEMRW3RM9KEnySaZD4CqsIaZtf9ZDgYXKapU/@OTdqW7q7hmTJRUfanE3oqK3dlb9EulfjvpBt61uoF9aNXp/AaagT9akmxah/rJI2X7Spl3iAgj/CwhHEul2M4ZeB/M0JnASWDicrCv2@pc0lzpLu1JtUimCY7apNYIpb5i2wzWFIGS8TevIGEjhZR2u5lRw3f7c1iJHebzmuTBzEpSNyiPkgL0sBCGyOzUoDV0CQ3QRdKHEYB3MK9XApFLGmlVizQ/7doXXZnMpgQ07xvi2awlnANQ1jj1cPNCK5oNWuhWYCKFirgBpER1CoXU5zZHCWUpumS5vN8YVchCJK@8NLgsK8LGItSzMcQ7LeXEry/lxXM9oylqb2P0gjEflS1QKM0ue1pmuvUCzWQgduPEQxfuMfMKeJV8rISPF/BtC5LRq@deC6AQzOUHcIY2/bZFdOO4O4ExjszjlErMakrgyYgq2DvcwxYgsFmkTMMobyxi0uJ4dZy1yiJW6XNToa9CgklWfqkdVi2mnCbgGcfUo7eoDjgv2NYRaCidWvwpz9kIOG6D5YXAo5BUGPjv7EVMZPjweAq/Stny8ZeXLnp8rPq5KkMv7WG36GPq66j3f36ArCxcy4VnltUUpGL285Qw5Wu5hw7XOe6qFkWOsmoX@FfScIgOY9P4yE@b90bH6oiuXDr4/gqPt9Ch/h92fLiiwa97L7dc@rQM7emPa9/7NA2ykl7ptG9CKondKZB6TlzWdDqfAsdhjyusJPpZvMH\" rel=\"nofollow noreferrer\" title=\"Haskell – Try It Online\">Try it online!</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T12:47:07.693",
"Id": "238562",
"ParentId": "238558",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238562",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T10:16:17.570",
"Id": "238558",
"Score": "1",
"Tags": [
"performance",
"beginner",
"haskell",
"sudoku",
"backtracking"
],
"Title": "Speeding up naive backtracking Sudoku Solver in Haskell"
}
|
238558
|
<p>I'm new to c++ and that is my list-based stack implementation.
It works, but i'm not sure that my code is good. </p>
<p>Please help me to improve this code, any advices are welcome.</p>
<pre><code>#include <iostream>
struct Node {
int data;
struct Node *next;
};
class Stack {
private:
Node *top;
public:
Stack()
{
top = nullptr;
}
void push(int value)
{
Node *n = new Node;
n->data = value;
n->next = top;
top = n;
};
void pop()
{
if (top != nullptr)
{
Node *n = top;
top = top->next;
delete n;
}
}
bool isEmpty() {
return top == nullptr;
}
int getTop()
{
if (top != nullptr)
return top->data;
else return INT32_MIN; // my value is in range [-100; 100]
}
void display()
{
Node *n = top;
while (n != nullptr)
{
if (n == top) std::cout << "\t\t\tTOP ELEMENT" << std::endl;
else {
std::cout << " |" << std::endl;
std::cout << " \\|/" << std::endl;
}
// i need to print data, address of element and address to next element
std::cout << "---------------------------------------------------------" << std::endl;
std::cout << "Data: " << n->data << "\t\tAddress: " << n <<"\tNext: " << n->next << std::endl;
std::cout << "---------------------------------------------------------" << std::endl;
n = n->next;
}
}
};
</code></pre>
|
[] |
[
{
"body": "<p>First, I'll show you some essential feature your class is missing, then I'll show you a way to use modern features of C++ to automate parts of your code.</p>\n\n<h1>Fixing your current code</h1>\n\n<h3>Use const to have the compiler check your logic</h3>\n\n<p>If a method does not modify the class, then it should be declared <code>const</code> so that other functions can call it when acting on an instance that is not allowed to be changed. For example,</p>\n\n<pre><code>bool isEmpty() const\n{\n return top == nullptr;\n}\n</code></pre>\n\n<p>Now, a function that takes a <code>const Stack&</code> parameter can check if the <code>Stack</code> instance is empty. Similarly, the <code>getTop()</code> and <code>display()</code> methods should be marked <code>const</code> since neither modify the stack.</p>\n\n<h3>Clean up your resources</h3>\n\n<p>First, some sample code:</p>\n\n<pre><code>int main()\n{\n int sizeOfStack;\n std::cin >> sizeOfStack; // ask user for a number\n if(sizeOfStack < 10)\n {\n Stack stack;\n for(int i = 0; i < sizeOfStack; ++i)\n {\n stack.push(i);\n }\n stack.display();\n } // All data added to stack is leaked here\n else\n {\n std::cout << \"Too large for this example.\\n\";\n }\n\n // The memory taken up by the stack cannot be released\n // until the program exits.\n}\n</code></pre>\n\n<p>As your code is now, when your program exits a scope (a part of code that is enclosed in curly braces like a function, loop, or if-else-block), all of the data you created with <code>new</code> will be leaked. This means that the data will still exist and take up memory and other resources, but there will be no way to access it to clean it up.</p>\n\n<p>In C++, every class that has a data member that does not have its own destructor (usually pointers) needs a <a href=\"https://en.cppreference.com/w/cpp/language/destructor\" rel=\"noreferrer\">destructor</a> to manually clean it up. This is a method named like a constructor but prefixed with a tilde: <code>~Stack()</code>. For your <code>Stack</code> class, you would need something like</p>\n\n<pre><code>~Stack()\n{\n while( ! isEmpty())\n {\n pop();\n }\n}\n</code></pre>\n\n<h3>Write constructors to ensure data is always valid</h3>\n\n<p>In C++, a <code>class</code> and a <code>struct</code> are nearly identical concepts. The only difference is that the data in a <code>class</code> is private by default and data in a <code>struct</code> is public by default. Otherwise, anything you can write in a <code>class</code> you can write in a <code>struct</code>. So, you can write a constructor for your <code>Node</code> class.</p>\n\n<pre><code>Node(int inputData, Node* inputNext)\n{\n data = inputData;\n next = inputNext;\n}\n</code></pre>\n\n<p>A better way to write this is to use an <a href=\"https://en.cppreference.com/w/cpp/language/initializer_list\" rel=\"noreferrer\">initializer list</a>:</p>\n\n<pre><code>Node(int inputData, Node* inputNext) : data(inputData), next(inputNext)\n{\n}\n</code></pre>\n\n<p>Similarly, for the <code>Stack</code> class:</p>\n\n<pre><code>Stack() : top(nullptr)\n{\n}\n</code></pre>\n\n<p>It's not so important with <code>int</code>s and pointers, but with more complex classes you'll write in the future, using intializer lists will avoid some unnecessary work.</p>\n\n<p>Now that <code>Node</code>s have a constructor, you can simplify your <code>push()</code> method.</p>\n\n<pre><code>push(int value)\n{\n top = new Node(value, top);\n}\n</code></pre>\n\n<p>The constructor of the <code>Node</code> class centralizes the logic of creating a new <code>Node</code> so you don't have to rewrite it everywhere.</p>\n\n<h3>Use methods and other named code to make your intent clear</h3>\n\n<p>Many places in your code check if <code>top == nullptr</code>. You should use the <code>isEmpty()</code> to tell readers of your code (including you in the future) what you actually care about.</p>\n\n<pre><code>void pop()\n{\n if ( ! isEmpty())\n {\n Node *n = top;\n top = top->next;\n delete n;\n }\n}\n</code></pre>\n\n<p>This goes for <code>getTop()</code> as well.</p>\n\n<h3>Decide how to handle copying and assignment</h3>\n\n<p>As it is now, when an instance of <code>Stack</code> is copied, both instances will refer to the same data and modifications to one instance may affect the other.</p>\n\n<pre><code>Stack s1;\ns1.push(7);\nStack s2 = s1;\ns2.push(21);\ns1.display();\nstd::cout << \"\\n\\n\\n\";\ns2.display();\n</code></pre>\n\n<p>This will result in the following output before crashing:</p>\n\n<pre><code> TOP ELEMENT\n---------------------------------------------------------\nData: 7 Address: 007AF1C0 Next: 00000000\n---------------------------------------------------------\n\n\n\n TOP ELEMENT\n---------------------------------------------------------\nData: 21 Address: 007AF230 Next: 007AF1C0\n---------------------------------------------------------\n |\n \\|/\n---------------------------------------------------------\nData: 7 Address: 007AF1C0 Next: 00000000\n---------------------------------------------------------\n</code></pre>\n\n<p>Notice that both nodes with the value 7 have the same pointer address. Now that the <code>Stack</code> class has a destructor, <a href=\"https://en.cppreference.com/w/cpp/language/copy_constructor\" rel=\"noreferrer\">copying</a> and <a href=\"https://en.cppreference.com/w/cpp/language/copy_assignment\" rel=\"noreferrer\">assignment</a> need to be handled to avoid deleting the same pointer address more than once. The simplest way is to disallow both.</p>\n\n<pre><code>Stack(const Stack& other) = delete; // delete the copy constructor\nStack& operator=(const Stack& other) = delete; // delete the assignment operator\n</code></pre>\n\n<p>With these lines in your class declaration, the following code will not compile:</p>\n\n<pre><code>Stack s1;\nStack s2 = s1; // error: Stack cannot be copied\nStack s3(s1); // error Stack cannot be copied\n\nStack s4;\ns4 = s1; // error: Stack cannot be assigned to.\n</code></pre>\n\n<p>If you want your <code>Stack</code> class to be copyable, then you need to explicitly copy all of the data from one to the other.</p>\n\n<pre><code>Stack(const Stack& other) : top(nullptr)\n{\n if( ! other.isEmpty())\n {\n top = new Node(other.top->data, nullptr);\n }\n else\n {\n return;\n }\n\n Node* bottom = top;\n for(Node* n = other.top->next; n != nullptr; n = n->next)\n {\n bottom->next = new Node(n->data, nullptr);\n bottom = bottom->next;\n }\n}\n</code></pre>\n\n<p>After adding the copy constructor, you can rerun the code with <code>s1</code> and <code>s2</code> and see that the nodes containing the value 7 are at different addresses.</p>\n\n<p>I'll leave writing the assignment operator as an exercise for you.</p>\n\n<h3>Tell the user when a request cannot be completed</h3>\n\n<p>Right now, when a user calls <code>getTop()</code> on an empty <code>Stack</code>, the user still gets an answer. Unless the user of this class sees the comment that <code>INT32_MIN</code> is never a valid value, there's no indication that anything went wrong. You may not have need of data values outside of [-100, 100], but what about future users (including your future self)? Why should your class not be allowed to store <code>INT32_MIN</code> as a valid piece of data?</p>\n\n<p>It is better to tell the user that there is no data to be had. One way, if you are using C++17 (which may require a compiler flag or changing an IDE option), is to return a <code>std::optional<int></code> (<a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"noreferrer\">reference</a>).</p>\n\n<pre><code>#include <optional>\n\n// ...\n\nstd::optional<int> getTop()\n{\n if(isEmpty())\n {\n return std::nullopt;\n }\n else\n {\n return top->data;\n }\n}\n</code></pre>\n\n<p>The other option is to <a href=\"https://en.cppreference.com/w/cpp/language/throw\" rel=\"noreferrer\">throw an exception</a> in the empty case.</p>\n\n<p>This way the caller of <code>getTop()</code> has to check if there is any data to be had.</p>\n\n<h3>Other notes</h3>\n\n<p>In the <code>display()</code> method, you can use a for-loop instead of a while loop to centralize all of the looping logic.</p>\n\n<pre><code>void display()\n{\n for(Node* n = top; n != nullptr; n = n->next)\n {\n // output\n }\n}\n</code></pre>\n\n<p>One more nitpick, you don't need the keyword struct in the <code>Node::next</code> declaration.</p>\n\n<pre><code>struct Node {\n Node(int inputData, Node* inputNext) : data(inputData), next(inputNext) {}\n int data;\n Node* next;\n};\n</code></pre>\n\n<h1>Using modern C++ features</h1>\n\n<p>A great way of improving this code is to use smart pointers. The <code>std::unique_ptr</code> (<a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\">reference</a>) tells readers, users, and the compiler that the variable or class containing the <code>unique_ptr</code> is responsible for cleaning up the variable when it is no longer needed.</p>\n\n<p>So, you can change your <code>Node</code> class to</p>\n\n<pre><code>#include <memory>\n\nstruct Node {\n Node(int inputData, Node* inputNext) : data(inputData), next(inputNext) {}\n int data;\n std::unique_ptr<Node> next;\n};\n</code></pre>\n\n<p>And the <code>Stack</code> class turns into</p>\n\n<pre><code>class Stack {\nprivate:\n std::unique_ptr<Node> top;\n// ...\n</code></pre>\n\n<p>Now, when a stack instance leaves the scope where it was created, the <code>top</code> node is automatically <code>delete</code>d. When <code>top</code> is <code>delete</code>d, <code>top->next</code> is automatically <code>delete</code>d, and then <code>top->next->next</code>, and then <code>top->next->next->next</code>, etc. So, you no longer need an explicit destructor (<code>~Stack</code>). The compiler will generate the correct destructor for you.</p>\n\n<p>Now, you no longer have to call <code>delete</code> on any pointers. For example, the <code>pop()</code> method is now reduced to</p>\n\n<pre><code>void pop()\n{\n if( ! isEmpty())\n {\n top = std::move(top->next);\n }\n}\n</code></pre>\n\n<p>The <code>std::move()</code> call means that the contents of <code>top->next</code>--both the data and the pointer to the <code>top->next->next</code> node--will be stolen and moved into <code>top</code>. The previous contents of <code>top</code> will be deleted as this happens.</p>\n\n<p>The other places where pointer manipulation changes is anywhere <code>new</code> is called. The <code>push()</code> method is now written with smart pointers as</p>\n\n<pre><code>void push(int value)\n{\n top = std::make_unique<Node>(value, top.release());\n};\n</code></pre>\n\n<p>The <code>release()</code> method returns the raw (non-smart) pointer held by the smart pointer and removes all responsibility for deleting it from that smart pointer. This happens so that the new smart pointer being added takes over responsibility for deleting the data when it is no longer needed. Assigning the new <code>std::unique_ptr</code> to <code>top</code> means that the <code>Stack</code> instance is now responsible for deleting the newly created <code>Node</code>.</p>\n\n<p>Finally, if you don't want your <code>Stack</code> class to be copyable or assignable, you no longer need to delete those functions, since they will no longer be automatically generated. Instances of <code>std::unique_ptr</code> are not copyable or assignable, so any class they are a part of will lose those qualities as well. If you want to make your class copyable, you'll need the <code>get()</code> method of the <code>std::unique_ptr</code>. This returns the raw pointer like the <code>release()</code> method, but the <code>std::unique_ptr</code> retains responsibility for deleting the <code>Node</code>. This will allow your program to follow the linked list chain without copying <code>std::unique_ptr</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T20:35:34.740",
"Id": "467903",
"Score": "0",
"body": "Thank you very much.\nCan you explain me code for disable copying and assignment?\n\n`Stack(const Stack& other) = delete; // delete the copy constructor\nStack& operator=(const Stack& other) = delete; // delete the assignment operator`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:03:36.023",
"Id": "467904",
"Score": "1",
"body": "@f0xeri You're welcome. I've added some information about the deleted copy and assignment operators. Let me know if it makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:15:48.287",
"Id": "467905",
"Score": "0",
"body": "Thanks, i mean i can't understand how this two lines of code code works. What is \"other\" and why it's const?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:21:52.937",
"Id": "467906",
"Score": "1",
"body": "@f0xeri The first line `Stack(const Stack& other)` declares a copy constructor. This constructor is used to create a copy of an already existing Stack instance. That already existing instance is passed to the `other` parameter. The parameter is const because the copy constructor should not modify the already existing Stack. In the example code, `s1` would have been the `other` parameter to the `s2` and `s3` copy constructors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:27:11.347",
"Id": "467907",
"Score": "1",
"body": "@f0xeri The second line `Stack& operator(const Stack& other)` is the assignment operator. In a line like `s1 = s2`, its purpose is to overwrite the data in one Stack (`s1` in this case) with data from another (`s2` in this case). The `other` parameter is `s2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:34:43.550",
"Id": "467908",
"Score": "0",
"body": "I got it, thanks for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:45:34.807",
"Id": "467909",
"Score": "1",
"body": "@f0xeri You're welcome! Good luck with your project!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T19:44:27.227",
"Id": "238580",
"ParentId": "238565",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "238580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T14:28:49.487",
"Id": "238565",
"Score": "6",
"Tags": [
"c++",
"beginner"
],
"Title": "List-based stack implementation in C++"
}
|
238565
|
<h1>What I want to do</h1>
<p>Make my code cleaner.</p>
<hr>
<h1>What my code does</h1>
<p>Thanks to Stack overflow, I finally wrote a code which creates option tags dynamically (OptionTime). The value of data-range attribute for Year was static. I wanted to set the years range dynamically, and I did it (See between //start and //End). However, I feel my code is lengthy. Can anyone make my code better, please?</p>
<hr>
<h1>Here is my code</h1>
<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>// Start
/* Fetch DOM */
const selectYear = document.querySelector('select[name="Year"]');
/* Set years */
const now = new Date();
const year = now.getFullYear();
const startYear = year - 50;
const endYear = year - 18;
/* Change Year's data-range */
function overwriteYears() {
let dataRange = selectYear.dataset.range;
let [start, end, unit] = dataRange.split(' ');
start = startYear;
end = endYear;
selectYear.setAttribute('data-range', `${start} ${end} ${unit}`);
}
overwriteYears();
// End
/* Create <option> tags */
class OptionTime extends HTMLSelectElement {
constructor() {
super();
}
connectedCallback() {
let [start, end, unit] = this.dataset.range.split(' ');
for (let i = start; i <= end; i++) {
this.add(new Option(`${i}${unit}`, `${i}${unit}`));
}
}
};
customElements.define('option-time', OptionTime, {
extends: 'select'
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select is="option-time" name="Year" data-range="%startYear% %endYear% 年">
<option value="" disabled selected>Year</option>
</select>
<select is="option-time" name="Month" data-range="1 12 月">
<option value="" disabled selected>Month</option>
</select>
<select is="option-time" name="Day" data-range="1 31 日">
<option value="" disabled selected>Day</option>
</select></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>I hope this helps. Made some comments in the snippet.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/* Create <option> tags */\nclass OptionTime extends HTMLSelectElement {\n constructor() {\n super();\n this.setDateRange();\n }\n\n setDateRange() {\n const now = new Date();\n const year = now.getFullYear();\n const unit = this.dataset.range.split(' ')[2]; \n const startYear = year - 50; // No need to deconstruct start/end and assign years again.\n const endYear = year - 18;\n\n // `this` give access to HTML element directly.\n this.setAttribute('data-range', `${startYear} ${endYear} ${unit}`);\n\n for (let i = startYear; i <= endYear; i++) {\n this.add(new Option(`${i}${unit}`, `${i}${unit}`));\n }\n }\n};\n\ncustomElements.define('option-time', OptionTime, {\n extends: 'select'\n});\n</code></pre>\n\n<pre class=\"lang-html prettyprint-override\"><code><select is=\"option-time\" name=\"Year\" data-range=\"%startYear% %endYear% 年\">\n <option value=\"\" disabled selected>Year</option>\n</select>\n<select is=\"option-time\" name=\"Month\" data-range=\"1 12 月\">\n <option value=\"\" disabled selected>Month</option>\n</select>\n<select is=\"option-time\" name=\"Day\" data-range=\"1 31 日\">\n <option value=\"\" disabled selected>Day</option>\n</select>\n</code></pre>\n\n\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T10:32:01.607",
"Id": "238615",
"ParentId": "238566",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238615",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T14:39:19.970",
"Id": "238566",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Dynamically change attribute value with split() (JavaScript)"
}
|
238566
|
<p>I have a set of XML documents that have a rather long list of tags and corresponding values that I am interested in. For simplicity, I decided to create a class that would let me get an object with all the relevant attributes parsed from the XML file.
Having little experience with OOP in Python, I guess I might have made mistakes or suboptimal choices in terms of class design.
Probably, my decision to have a separate utility class for <code>XMLParser</code> was a bad idea, but at least I couldn't come up with a better one. </p>
<p>To sum up, I would appreciate any type of criticism, advice or suggestions with regard to how the classes are designed, as well as code quality in general. Even though it seems that everything works as I expected, I feel like it's a good opportunity to learn new approaches, concepts and level-up my understanding of OOP in Python. Thanks in advance! </p>
<pre><code>from xml.dom import minidom
class XMLDoc:
def __init__(self, path_to_xml):
self.tree = minidom.parse(path_to_xml)
self.parser = XMLParser(self.tree)
self.goods = self._make_goods_list()
self.language = self.parser._get('language')
self.service_type = self.parser._get('serviceType')
self.trader_declaration_number = self.parser._get('traderDeclarationNumber')
self.trader_reference = self.parser._get('traderReference')
self.clearance_location = self.parser._get('clearanceLocation')
self.declaration_time = self.parser._get('declarationTime')
self.declaration_type = self.parser._get('declarationType')
self.correction_code = self.parser._get('correctionCode')
self.customs_office_number = self.parser._get('customsOfficeNumber')
self.dispatch_country = self.parser._get('dispatchCountry')
self.transport_in_container = self.parser._get("transportInContainer")
self.previous_document = PreviousDocument(self.tree, self.parser)
self.consignor = Consignor(self.tree,self.parser)
self.consignee = Consignee(self.tree, self.parser)
self.importer = Importer(self.tree, self.parser)
self.transport_means = Transport(self.tree,self.parser)
self.business = BusinessData(self.tree, self.parser)
def __repr__(self):
return f"XMLDoc {self.trader_reference}"
def _make_goods_list(self):
goods_list = []
all_goods = self.parser.get_goods()
for g in all_goods:
fields_list = self.parser.filter_nested_items(g)
goods_item = GoodsItem(fields_list,self.parser)
goods_list.append(goods_item)
return goods_list
class Consignor:
def __init__(self, tree, parser):
self.tree = tree
self.parser = parser
self.name = self.parser._get("consignor", "name")
self.street = self.parser._get("consignor", "street")
self.postal_code = self.parser._get("consignor", "postalCode")
self.city = self.parser._get("consignor", "city")
self.country = self.parser._get("consignor", "country")
def __repr__(self):
return f"Consignor object: {self.name}"
class Importer:
def __init__(self, tree, parser):
self.tree = tree
self.parser = parser
self.name = self.parser._get("importer", "name")
self.street = self.parser._get("importer", "street")
self.postal_code = self.parser._get("importer", "postalCode")
self.city = self.parser._get("importer", "city")
self.country = self.parser._get("importer", "country")
self.trader_id = self.parser._get("importer", "traderIdentificationNumber")
self.reference = self.parser._get("importer", "importerReference")
def __repr__(self):
return f"Importer object: {self.name}"
class Consignee:
def __init__(self, tree, parser):
self.tree = tree
self.parser = parser
self.name = self.parser._get("consignee", "name")
self.street = self.parser._get("consignee", "street")
self.postal_code = self.parser._get("consignee",
"postalCode")
self.city = self.parser._get("consignee", "city")
self.country = self.parser._get("consignee", "country")
self.trader_id = self.parser._get("consignee",
"traderIdentificationNumber")
def __repr__(self):
return f"Consignee object: {self.name}"
class Transport:
def __init__(self, tree, parser):
self.tree = tree
self.parser = parser
self.mode = self.parser._get("transportMeans",
"transportMode")
self.transportation_type = self.parser._get("transportMeans",
"transportationType")
self.transportation_country = self.parser._get("transportMeans",
"transportationCountry")
self.transportation_number = self.parser._get("transportMeans",
"transportationNumber")
class GoodsItem:
def __init__(self, fields_list, parser):
self.fields_list = fields_list
self.parser = parser
self.trader_item_id = self._get("traderItemID")
self.description = self._get("description")
self.commodity_code = self._get("commodityCode")
self.gross_mass = self._get("grossMass")
self.net_mass = self._get("netMass")
self.permit_obligation = self._get("permitObligation")
self.non_customs_law_obligation = self._get("nonCustomsLawObligation")
self.origin_country = self._get("origin", "originCountry")
self.origin_preference = self._get("origin", "preference")
self.package_type = self._get("packaging", "packagingType")
self.package_quantity = self._get("packaging", "quantity")
self.package_reference_number = self._get("packaging",
"packagingReferenceNumber")
# self.document_type = self._get("producedDocument","documentType")
# self.document_reference_number = self._get("producedDocument","packagingReferenceNumber")
# self.document_issue_date = self._get("producedDocument","issueDate")
self.vat_value = self._get("valuation", "VATValue")
self.vat_code = self._get("valuation", "VATCode")
def _get_inner_field(self, external, field):
matching_tags = self.parser.search_dom_list(self.fields_list, external)
filtered_matching_tags = self.parser.filter_nested_items(matching_tags)
inner_tag = self.parser.search_dom_list(filtered_matching_tags, field)
return inner_tag
def _get(self, field_name, inner_field=None):
if not inner_field:
return self.parser.search_dom_list(self.fields_list,
field_name).firstChild.nodeValue
else:
return self._get_inner_field(field_name,
inner_field).firstChild.nodeValue
class BusinessData:
def __init__(self,tree,parser):
self.tree = tree
self.parser = parser
self.incoterms = self.parser._get("business", "incoterms")
self.customs_account = self.parser._get("business",
"customsAccount")
self.vat_account = self.parser._get("business", "VATAccount")
self.vat_number = self.parser._get("business", "VATNumber")
self.vat_suffix = self.parser._get("business", "VATSuffix")
self.invoice_currency_type = self.parser._get("business",
"invoiceCurrencyType")
class PreviousDocument:
def __init__(self, tree, parser):
self.tree = tree
self.parser = parser
self.doctype = self.parser._get("previousDocument",
"previousDocumentType")
self.reference = self.parser._get("previousDocument",
"previousDocumentReference")
class XMLParser:
def __init__(self, tree):
self.tree = tree
def get_nested_tag(self, parent_tag, element):
reference = [item.firstChild.nodeValue for item in
self.tree.getElementsByTagName(parent_tag)[0].childNodes
if item.nodeType != 3 and item.tagName == element]
try:
return reference[0]
except IndexError:
return None
def get_single_tag(self, element):
reference = self.tree.getElementsByTagName(element)[0].firstChild.nodeValue
return reference
def get_goods(self):
goods = self.tree.getElementsByTagName('goodsItem')
return goods
def search_dom_list(self, dom_list, name):
dom_list = self.filter_items(dom_list)
for item in dom_list:
if item.tagName == name:
return item
def filter_nested_items(self, goods_item):
values = [item for item in goods_item.childNodes if item.nodeType != 3]
return values
def filter_items(self, items):
return [item for item in items if item.nodeType != 3]
def _get(self, field_name, inner_field=None):
if not inner_field:
return self.get_single_tag(field_name)
else:
return self.get_nested_tag(field_name, inner_field)
</code></pre>
|
[] |
[
{
"body": "<p>You could save yourself a lot of repetition by defining a generic class that takes elements of the tree and saves them. This way you can separate the class from the data needed to build it.</p>\n\n<p>In one file you can have all your fields defined:</p>\n\n<pre><code>XMLDOC_FIELDS = {\"language\": (\"language\",),\n \"service_type\": (\"serviceType\",),\n \"trader_declaration_number\": (\"traderDeclarationNumber\",),\n \"trader_reference\": (\"traderReference\",),\n \"clearance_location\": (\"clearanceLocation\",),\n \"declaration_time\": (\"declarationTime\",),\n \"declaration_type\": (\"declarationType\",),\n \"correction_code\": (\"correctionCode\",),\n \"customs_office_number\": (\"customsOfficeNumber\",),\n \"dispatch_country\": (\"dispatchCountry\",),\n \"transport_in_container\": (\"transportInContainer\",)}\n\nCONSIGNOR_FIELDS = {\"name\": (\"consignor\", \"name\"),\n \"street\": (\"consignor\", \"street\"),\n \"postal_code\": (\"consignor\", \"postalCode\"),\n \"city\": (\"consignor\", \"city\"),\n \"country\": (\"consignor\", \"country\")}\n\nIMPORTER_FIELDS = {\"name\": (\"importer\", \"name\"),\n \"street\": (\"importer\", \"street\"),\n \"postal_code\": (\"importer\", \"postalCode\"),\n \"city\": (\"importer\", \"city\"),\n \"country\": (\"importer\", \"country\"),\n \"trader_id\": (\"importer\", \"traderIdentificationNumber\"),\n \"reference\": (\"importer\", \"importerReference\")}\n\nCONSIGNEE_FIELDS = {\"name\": (\"consignee\", \"name\"),\n \"street\": (\"consignee\", \"street\"),\n \"postal_code\": (\"consignee\", \"postalCode\"),\n \"city\": (\"consignee\", \"city\"),\n \"country\": (\"consignee\", \"country\"),\n \"trader_id\": (\"consignee\", \"traderIdentificationNumber\")}\n\n...\n</code></pre>\n\n<p>Which you can then use like this in your main file:</p>\n\n<pre><code>from fields import *\n\nclass Entity:\n def __init__(self, cls_name, parser, fields):\n self.cls_name = cls_name\n self.name = \"\"\n for field_name, path in fields.items():\n setattr(self, field_name, parser._get(*path))\n\n def __repr__(self):\n return f\"{self.cls_name}: {self.name}\"\n\nclass XMLDoc(Entity):\n def __init__(self, path_to_xml):\n self.tree = minidom.parse(path_to_xml)\n self.parser = XMLParser(self.tree)\n self.goods = self._make_goods_list()\n super().__init__(\"XMLDoc\", self.parser, XMLDOC_FIELDS)\n self.name = self.trader_reference\n self.consignor = Entity(\"Consignor\", self.parser, CONSIGNOR_FIELDS)\n self.importer = Entity(\"Importer\", self.parser, IMPORTER_FIELDS)\n self.consignee = Entity(\"Consignee\", self.parser, CONSIGNEE_FIELDS)\n ...\n</code></pre>\n\n<p>Only the <code>GoodsItem</code> class cannot be replaced with this, for that you probably still need a separate class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:50:53.733",
"Id": "467974",
"Score": "0",
"body": "Thank you. That definitely helps get rid of duplication. You added the `name` attribute to XMLDoc for some reason as `self.trader_reference`. Was that intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:59:33.053",
"Id": "467975",
"Score": "1",
"body": "@DonDraper: It was, because it will be picked up by the `Entity.__repr__` method, in order to (almost) replicate your current different implementations of `__repr__` for the different classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:06:21.383",
"Id": "467976",
"Score": "1",
"body": "I got it. At first, I thought that you had renamed the attribute, but you just set the `name` attribute to avoid duplication in `__repr__` implementation. \nOther than that, do you think that the code is clean enough and, well, Pythonic?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:10:39.857",
"Id": "238625",
"ParentId": "238569",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T15:45:14.897",
"Id": "238569",
"Score": "3",
"Tags": [
"python",
"object-oriented"
],
"Title": "Class to encapsulate an XML document"
}
|
238569
|
<p><a href="https://beam.apache.org/get-started/beam-overview/" rel="nofollow noreferrer">In their own words:</a></p>
<p>Apache Beam is an open source, unified model for defining both batch and streaming data-parallel processing pipelines. Using one of the open source Beam SDKs, you build a program that defines the pipeline. The pipeline is then executed by one of Beam’s supported distributed processing back-ends, which include <a href="https://apex.apache.org/" rel="nofollow noreferrer">Apache Apex</a>, <a href="https://flink.apache.org/" rel="nofollow noreferrer">Apache Flink</a>, <a href="https://spark.apache.org/" rel="nofollow noreferrer">Apache Spark</a>, and <a href="https://cloud.google.com/dataflow" rel="nofollow noreferrer">Google Cloud Dataflow</a>.</p>
<p>Beam is particularly useful for <a href="https://en.wikipedia.org/wiki/Embarassingly_parallel" rel="nofollow noreferrer">Embarrassingly Parallel</a> data processing tasks, in which the problem can be decomposed into many smaller bundles of data that can be processed independently and in parallel. You can also use Beam for Extract, Transform, and Load (ETL) tasks and pure data integration. These tasks are useful for moving data between different storage media and data sources, transforming data into a more desirable format, or loading data onto a new system.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T17:51:44.423",
"Id": "238573",
"Score": "0",
"Tags": null,
"Title": null
}
|
238573
|
Apache Beam is an open source, unified model for defining both batch and streaming data-parallel processing pipelines.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T17:51:44.423",
"Id": "238574",
"Score": "0",
"Tags": null,
"Title": null
}
|
238574
|
<p>I'm trying to create a user while adding data to a second table via one form:</p>
<p><strong>users table:</strong></p>
<pre><code>Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
</code></pre>
<p><strong>info table:</strong></p>
<pre><code>Schema::create('infos', function (Blueprint $table) {
$table->id();
$table->string('fname');
$table->string('lname');
$table->string('dateofbirth');
$table->string('phonenumber')
$table->timestamps();
});
</code></pre>
<p><strong>info_user table:</strong></p>
<pre><code>Schema::create('info_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('info_id');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('info_id')->references('id')->on('infos')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
</code></pre>
<p><strong>User.php Model</strong></p>
<pre><code>public function infos() {
return $this->belongsToMany(Info::class)->withTimestamps();;
}
</code></pre>
<p><strong>Info.php Model</strong></p>
<pre><code>public function users() {
return $this->belongsToMany(User::class)->withTimestamps();
}
</code></pre>
<p><strong>And my attempt at InfoController</strong></p>
<pre><code>public function store(Info $info, User $user, Request $request)
{
User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$data = new Info;
$data->fname = $request->fname;
$data->lname = $request->lname;
$data->dateofbirth = $request->dateofbirth;
$data->phonenumber = $request->phonenumber;
$data->save();
return redirect('/');
}
</code></pre>
<p>I'm trying to figure out how to register a user while adding info to the second table so they have a common <code>info_user</code> table.</p>
<p>I think I succeeded, but only if it is right and especially safe.</p>
<pre><code>public function store(Info $info, User $user, Request $request)
{
$user = User::create([
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$data = new Loan;
$data->fname = $request->fname;
$data->lname = $request->lname;
$data->dateofbirth = $request->dateofbirth;
$data->phonenumber = $request->phonenumber;
$data->save();
$user->infos()->attach($data);
return redirect('/');
}
</code></pre>
|
[] |
[
{
"body": "<p>It's a correct way to do it like this.\nFew suggestions:</p>\n\n<p>Add validation before creating user. You don't want to fail on save for duplicate user email. For better UX if you can it's a good idea to do it even before form submit (with ajax request when email field is changed).</p>\n\n<p>If your app has more user related things like user profile, user control panel I will suggest you to auto login user after form submit. Just before redirect() add <code>Auth::login($user)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T07:11:19.547",
"Id": "241986",
"ParentId": "238575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T17:52:53.503",
"Id": "238575",
"Score": "2",
"Tags": [
"php",
"laravel"
],
"Title": "Create user in users table and insert data into second table with one form in Laravel Relationships"
}
|
238575
|
<p>I needed this function for a project I'm currently working on. I think there is definitely a way to make this prettier and have tickle more performance out of it, but how?</p>
<pre class="lang-py prettyprint-override"><code>def nthofchar(string: str, char: str, n: int = 2) -> list:
l = [] # New list
temp = "" # temp value
count = 0 # Counter, that get will be reset, each time the temp get`s appended to the list
for value in string.split(char):
temp += value + char # Add char to have it still in the string
# Incrementing
count += 1
if count >= n:
l.append(temp[:len(char) * -1]) # Remove last char
# Reset
count = 0
temp = ""
return l
print(nthofchar("25:hellwdasd:64:da:12:yeah:1:y", ":", 2))
# Output: ['25:hellwdasd', '64:da', '12:yeah', '1:y']
print(nthofchar("1;a;2;b;3;c;4;d;5;e;6;f", ";", 2))
# Output: ['1;a', '2;b', '3;c', '4;d', '5;e', '6;f']
</code></pre>
|
[] |
[
{
"body": "<p>A python idiom for iterating over a sequence in groups it to use <code>zip()</code> like so:</p>\n\n<pre><code>group_iter = zip(*[iter(seq)]*n)\n</code></pre>\n\n<p>where <code>seq</code> is the sequence and <code>n</code> is the size of each group. Note that the last group will be dropped if it doesn't have <code>n</code> elements.</p>\n\n<p>Using that idiom, your function could be coded:</p>\n\n<pre><code>def nthofchar(string: str, char: str, n: int = 2) -> list:\n chunks = string.split(char)\n groups = zip(*[iter(chunks)]*n)\n\n return [char.join(group) for group in groups]\n</code></pre>\n\n<p>Added a test case for n != 2:</p>\n\n<pre><code>print(nthofchar(\"1;a;b;2;c;d;3;e;f;4;g;h;5;i;j;6;k;l\", \";\", 3))\n# Output: ['1;a;b', '2;c;d', '3;e;f', '4;g;h', '5;i;j', '6;k;l']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:12:07.020",
"Id": "467926",
"Score": "0",
"body": "This fails for `n != 2`, because then the tuple unpacking in your return line does not work anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:28:42.063",
"Id": "467970",
"Score": "0",
"body": "@Graipher, fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:30:27.627",
"Id": "467971",
"Score": "1",
"body": "Now the last sentence is not true anymore, but otherwise, nice!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T20:20:35.680",
"Id": "238582",
"ParentId": "238577",
"Score": "6"
}
},
{
"body": "<p>You can simply take advantage from builtin <a href=\"https://docs.python.org/3/library/stdtypes.html#range\" rel=\"nofollow noreferrer\"><code>range(start, stop[, step])</code></a> and collect the needed chunks passing input <code>n</code> size as <em>range</em>'s <code>step</code> parameter:</p>\n\n<pre><code>def split_nth(inp_str: str, sep: str, n: int = 2) -> list:\n chunks = inp_str.split(sep)\n return [sep.join(chunks[i: i + n]) for i in range(0, len(chunks), n)]\n\n\nprint(split_nth(\"25:hellwdasd:64:da:12:yeah:1:y\", \":\", 3))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>['25:hellwdasd:64', 'da:12:yeah', '1:y']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T20:50:15.710",
"Id": "238584",
"ParentId": "238577",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T18:52:52.090",
"Id": "238577",
"Score": "5",
"Tags": [
"python"
],
"Title": "Python - Split nth occurence of a character in string"
}
|
238577
|
<pre><code>typedef struct Stack {
char v;
int x;
int y;
struct Stack* next;
} Stack;
</code></pre>
<p>Above is my stack struct.</p>
<pre><code>Stack* helper (char val, int x, int y)
{
Stack* node = (Stack*)malloc(sizeof(Stack));
node->v = val;
node->x = x;
node->y = y;
return node;
}
void push (Stack** top,char val,int x,int y)
{
Stack* node = helper(val,x,y);
node->next = *top;
*top = node;
printf("%c pushed to stack\n",val);
}
void pop (Stack** top,char *val,int *w,int *h)
{
if (checkempty(*top))
return;
Stack* temp = *top;
*top = (*top)->next;
*val = temp->v;
*w = temp->x;
*h = temp->y;
free(temp);
}
int checkempty(Stack* top)
{
return !top;
}
</code></pre>
<p>Above are my push and pop functions.
I was wondering if there are better ways to do this ? Or is what I am doing the standard way ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T19:49:36.300",
"Id": "467901",
"Score": "2",
"body": "It would be better if your whole program was provided to allow us to test the code as you tested the code. It also isn't clear what the variables `x` and `y` mean in the structure."
}
] |
[
{
"body": "<pre><code>Stack* helper (char val, int x, int y)\n {\n</code></pre>\n\n<p>Your indentation and whitespace are kind of funky; I recommend looking at what some popular open-source code on GitHub does, and trying to copy them as closely as possible. Or, just run your code through a formatter such as <code>clang-format</code>.</p>\n\n<pre><code>Stack *helper(char val, int x, int y)\n{\n</code></pre>\n\n<p>This function is only ever used in one place, so why do you have it? Right now it's kind of unsafe, because <code>helper</code> returns a <code>Stack *</code> which:</p>\n\n<ul>\n<li><p>must be freed by the caller to avoid memory leaks, and</p></li>\n<li><p>has uninitialized garbage in its <code>next</code> field.</p></li>\n</ul>\n\n<p>If you inlined it into <code>push</code>, you'd have a complete unit of work, without either of those dangerous sharp edges.</p>\n\n<hr>\n\n<p>Look into proper library organization. You should have a <code>.h</code> file that defines <code>struct Stack</code> and declares <code>push</code> and <code>pop</code>, and a <code>.c</code> file with the implementations.</p>\n\n<p>You should probably name the functions something like <code>stack_push</code> and <code>stack_pop</code>, since <code>push</code> and <code>pop</code> are likely to be common names; e.g. you might later want to write a <code>struct Queue</code> with a <code>queue_push</code> and <code>queue_pop</code>. This kind of \"manual namespacing\" is common in C libraries.</p>\n\n<hr>\n\n<p>Of course <code>push</code> shouldn't call <code>printf</code> (there's no \"I\" in \"TEAM\" and there's no \"printf\" in \"push data onto a stack\").</p>\n\n<p>In <code>pop</code>'s argument list, you use <code>w</code> and <code>h</code> where you meant <code>x</code> and <code>y</code>.</p>\n\n<p><code>pop</code> has interesting behavior on an empty stack: it just returns without initializing <code>*x</code> and <code>*y</code>. This is a problem for the caller, because the caller doesn't have any indication that anything went wrong! You should probably make <code>pop</code> return a <code>bool</code> to indicate whether it was successful.</p>\n\n<hr>\n\n<p>Compare a pointer for null with <code>(top == NULL)</code>, not <code>!top</code>. Clarity counts!</p>\n\n<hr>\n\n<p>Here's an idea if you want to push yourself harder: Right now you're passing <code>x</code>, <code>y</code>, and <code>value</code> as individual arguments to <code>push</code>, and retrieving them individually from <code>pop</code>. Package them up into a struct!</p>\n\n<p>Here's the struct definitions and function declarations for a different stack implementation. Can you see how to implement these functions?</p>\n\n<pre><code>struct Data { int x, y, value; };\n\nstruct DataStack { struct Data data; struct DataStack *next; }\n\nstruct DataStack *datastack_push(struct DataStack *, struct Data);\nstruct DataStack *datastack_pop(struct DataStack *);\nstruct Data datastack_top(const struct DataStack *);\nbool datastack_empty(const struct DataStack *);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T22:20:50.713",
"Id": "238586",
"ParentId": "238578",
"Score": "4"
}
},
{
"body": "<p>Consider separating the stack from the stack entries. Right now, you have to pass a pointer to a pointer to the stack to your push & pop routines. <a href=\"https://codereview.stackexchange.com/a/238586/100620\">Quuxplusone’s solution</a> requires the caller to do the work of assigning the return value to the stack pointer. Both of these are harder to use.</p>\n\n<p>Moreover, with Quuxplusone’s solution, you can’t pass an empty stack to another function, and have it fill in entries for the caller.</p>\n\n<p>Separating the stack from the stack entries allows the stack to store additional meta data about the stack. Eg)</p>\n\n<pre><code>typedef struct StackEntry {\n char v;\n int x, y;\n struct StackEntry *next;\n} StackEntry;\n\ntypedef struct Stack {\n StackEntry *top;\n int num_entries;\n} Stack;\n</code></pre>\n\n<p>Now, <code>push</code>, <code>pop</code> & <code>check_empty</code> would all just take a <code>Stack*</code>, which is easier to remember. Stacks can be passed & shared, even if they are empty, since they wouldn’t just be a null pointer. And you can determine the depth of a stack in <span class=\"math-container\">\\$O(1)\\$</span> time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T23:34:51.393",
"Id": "238590",
"ParentId": "238578",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>Stack* helper (char val, int x, int y)\n {\n Stack* node = (Stack*)malloc(sizeof(Stack));\n node->v = val;\n node->x = x;\n node->y = y;\n return node;\n }\n</code></pre>\n</blockquote>\n\n<p>That's not a very descriptive name - something in keeping with the existing scheme might be <code>stack_node_create()</code>.</p>\n\n<p>Since <code>malloc()</code> returns a <code>void*</code>, there's no need to scare readers by inserting a cast operator.</p>\n\n<p>We must check that <code>malloc()</code> didn't give us a null pointer before we dereference it.</p>\n\n<p>Fixing those issues gives us:</p>\n\n<pre><code>#include <stdlib.h>\n\n/**\n * Return a newly-created node, or a null pointer on failure.\n */\nStack *stack_node_create(char val, int x, int y)\n{\n Stack *const node = malloc(sizeof *node);\n if (!node) { return node; }\n node->v = val;\n node->x = x;\n node->y = y;\n return node;\n}\n</code></pre>\n\n<p>When we call this, we do need to remember that it can return a null pointer, and handle that accordingly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:57:35.113",
"Id": "238609",
"ParentId": "238578",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T19:03:38.393",
"Id": "238578",
"Score": "3",
"Tags": [
"c",
"linked-list",
"stack"
],
"Title": "Stack implementation using linked-list"
}
|
238578
|
<p>I am trying to create my first eav system that can handle updates as well.</p>
<p>The user can create models with list and objects inside and with references other models. the user can then create instances of the model ModelDataFields.</p>
<p>First we have the ModelParameteres. that will store all the models and their parameters and the fields and their parameters.</p>
<p>A parameter is like 'name'or 'islist' or 'order' or whatever. We have a enum for that.
UpdateType is 'created' or 'updated' or 'deleted'.
updatedby is UserId.
Updated is datetime stamp and delta for what is updated.
Model is ModelId
Value is some user data for the parameter like the name value when parameter is 'name'.</p>
<pre><code> CREATE TABLE [dbo].[ModelParameters]
(
[UpdateType] [TINYINT] NOT NULL,
[UpdatedBy] [uniqueidentifier] NOT NULL,
[Updated] [datetime2](0) NOT NULL,
[Model] [uniqueidentifier] NOT NULL,
[Field] [uniqueidentifier] NULL,
[Parameter] [smallint] NOT NULL,
[Value] [nvarchar](MAX) NULL
);
CREATE CLUSTERED INDEX [IX_ModelParameters]
ON [dbo].[ModelParameters]([Updated] DESC, [Model], [Field]);
</code></pre>
<p>Then we have the ModelDataFields that holds data records for each of the fields in a model. the ModelData is the id of each instance of the model.
the index is when we have a user list of some field soo we know what data belongs together in a dynamic list. </p>
<p>UpdateType is 'created' or 'updated' or 'deleted'.
updatedby is UserId.
Updated is datetime stamp and delta for what is updated.</p>
<p>Value is the current value for the modeldata => field => index?.
LastValue is for undo and restoring in case of deleting.</p>
<pre><code> CREATE TABLE [dbo].[ModelDataFields] (
[UpdateType] [TINYINT] NOT NULL,
[UpdatedBy] [uniqueidentifier] NOT NULL,
[Updated] [datetime2](0) NOT NULL,
[ModelData] UNIQUEIDENTIFIER NOT NULL,
[ModelField] UNIQUEIDENTIFIER NOT NULL,
[Index] INT NULL,
[Value] NVARCHAR (MAX) NULL,
[LastValue] NVARCHAR (MAX) NULL,
);
CREATE CLUSTERED INDEX [IX_ModelDataFields]
ON [dbo].[ModelDataFields]([Updated] DESC, [ModelData], [ModelField]);
</code></pre>
<p>Do i need multi tables for the ModeldataFields like for each model or is this fine? do you see something else wrong, We are gonna go with EAV so it not a question about EAV vs setting up tables. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T23:17:02.843",
"Id": "238588",
"Score": "2",
"Tags": [
"sql"
],
"Title": "Entity - Model (EAV) system with delta updates"
}
|
238588
|
<p>At a high level, I'm writing a Ruby class that compares <em>components</em> on two differing versions of the same JSON structure, which in turn decides whether or not said elements should be updated on a PDF file. Every <em>component</em> has a 'componentUuid' attribute which is used to identify components. The comparison is between the first and last versions of the JSON, and has the following business logic:</p>
<ol>
<li>If an element exists in the first JSON, and doesn't in the last, then it's been deleted.</li>
<li>If an element exists in both versions, but it's offset has changed, then it's been updated.</li>
<li><em>Updating</em> an element means to delete it, and create it with new attributes.</li>
</ol>
<p>My implementation of said business logic was using a hash where I assign each component's componentUuid to it for the first JSON, and then use that as reference for diffing against the last JSON. I later refactored it to make the code more 'clean'. However, I can't help but think that it's increased the complexity of the code, and reads far less linearly to me at least.</p>
<p>Any suggestions on how I can better refactor the code to be more performant, or clean would greatly be appreciated.</p>
<p><strong>Problem domain notes</strong>:</p>
<ul>
<li>We only care about <code>row_element</code> components</li>
<li>A <code>form_component</code> is a component that wraps a <code>row_element</code></li>
</ul>
<p><strong>Original Code:</strong></p>
<pre><code>class SetPdfFieldsToUpdate
def call(document_content, first_document_content)
latest_form_json = document_content.form_json
original_form_json = first_document_content.form_json
@pdf_field_uuids_to_remove = []
@page_to_fd_components_hash = {}
original_form_json_component_uuid_lookup = {}
original_form_json["pages"].each_with_index do |original_form_page, original_form_page_index|
original_form_page["floating_components"].each do |component|
if component["element_origin"] == "pdf"
component_uuid = component["field_rows"][0]["row_elements"][0]["componentUuid"]
original_form_json_component_uuid_lookup[component_uuid] = component["field_rows"][0]["row_elements"][0]
end
end
latest_form_page = latest_form_json["pages"][original_form_page_index]
latest_form_page["floating_components"].each do |component|
if component["element_origin"] == "pdf"
current_component = component["field_rows"][0]["row_elements"][0]
component_uuid = current_component["componentUuid"]
if original_form_json_component_uuid_lookup.key?(component_uuid)
origin_component_offset = original_form_json_component_uuid_lookup[component_uuid]["offset"]
current_component_offset = current_component["offset"]
unless origin_component_offset == current_component_offset
recreate_pdf_component_with_new_attributes(current_component, component_uuid, original_form_page_index)
end
original_form_json_component_uuid_lookup.except!(component_uuid)
end
end
end
end
@pdf_field_uuids_to_remove.concat(original_form_json_component_uuid_lookup.keys)
end
private
def recreate_pdf_component_with_new_attributes(component, component_uuid, page_index)
@pdf_field_uuids_to_remove.push(component_uuid)
@page_to_fd_components_hash[page_index.to_s].push(component)
end
end
</code></pre>
<p><strong>Refactored Code:</strong></p>
<pre><code>class SetPdfFieldsToMoveAndRemove
def call(document_content, first_document_content)
latest_form_json = document_content.form_json
original_form_json = first_document_content.form_json
@page_to_fd_components_hash = {}
@pdf_field_uuids_to_remove = []
@original_pdf_components_by_uuid_lookup = {}
original_form_json["pages"].each_with_index do |original_form_page, original_form_page_index|
update_pdf_component_lookup_with_page(original_form_page)
latest_form_page_by_original_match = get_matching_page_from_latest_form_json(
latest_form_json,
original_form_page_index
)
latest_form_page_by_original_match["floating_components"].each do |form_component|
if is_element_origin_pdf?(form_component)
row_element_attr = get_row_element_from_form_component(form_component)
row_element_uuid = row_element_attr["componentUuid"]
if @original_pdf_components_by_uuid_lookup.key?(row_element_uuid)
check_component_for_offset_shift(row_element_attr, original_form_page_index)
# check_component_for_type_toggle(current_component)
# ... add methods for checking if component should be recreated
end
end
end
end
delete_pdf_components_not_in_latest_form
end
private
def update_pdf_component_lookup_with_page(form_page)
form_page["floating_components"].each do |form_component|
if is_element_origin_pdf?(form_component)
row_element_attr = get_row_element_from_form_component(form_component)
row_element_uuid = row_element_attr["componentUuid"]
@original_pdf_components_by_uuid_lookup[row_element_uuid] = row_element_attr
end
end
end
def get_row_element_from_form_component(form_component)
form_component["field_rows"][0]["row_elements"][0]
end
def is_element_origin_pdf?(form_component)
form_component["element_origin"] == "pdf"
end
def get_matching_page_from_latest_form_json(latest_form_json, original_form_page_index)
latest_form_json["pages"][original_form_page_index]
end
def check_component_for_offset_shift(component, page_index)
component_uuid = component["componentUuid"]
origin_component_offset = @original_pdf_components_by_uuid_lookup[component_uuid]["offset"]
current_component_offset = component["offset"]
unless origin_component_offset == current_component_offset
recreate_pdf_element_with_new_attributes(component_uuid, component, page_index)
end
update_lookup_for_existing_component_in_latest_form(component_uuid)
end
def update_lookup_for_existing_component_in_latest_form(component_uuid)
@original_pdf_components_by_uuid_lookup.except!(component_uuid)
end
def recreate_pdf_element_with_new_attributes(component_uuid, component, page_index)
@pdf_field_uuids_to_remove.push(component_uuid)
@page_to_fd_components_hash[page_index.to_s].push(component)
end
def delete_pdf_components_not_in_latest_form
components_uuids_remaining = @original_pdf_components_by_uuid_lookup.keys
@pdf_field_uuids_to_remove.concat(components_uuids_remaining)
end
end
</code></pre>
|
[] |
[
{
"body": "<p>The big thing I would do here is add some classes to make this more object oriented and easier to read and understand. When I have super complex code that I have trouble understanding and I want to refactor it for readability, I sit down with what the code is supposed to be doing and then write what I wish the code would look like to do that. From there, I start adding or changing whatever needs to happen in the code base to make the code I wish I had the code I have. Doing so with this code (assuming I understand it all correctly), the <code>call</code> method ended up becoming something like:</p>\n\n<pre><code> def call(document_content, first_document_content)\n latest_pages = pages_from document_content\n original_pages = pages_from first_document_content\n\n original_pages.zip(latest_pages).each do |original_page, latest_page|\n original_page.row_elements.each do |row_element|\n # BR1: If an element exists in the first JSON, and doesn't in the last,\n # then it's been deleted\n original_page.delete(row_element) unless latest_page[row_element]\n\n # BR2: If an element exists in both versions, but it's offset has\n # changed, then it's been updated.\n unless row_element.offset == latest_page[row_element].offset\n original_page.update(latest_page[row_element])\n end\n end\n end\n end\n</code></pre>\n\n<p>and now I just start going through and implementing the methods required to reach that, so first line in this method, I need to add <code>pages_from</code>:</p>\n\n<pre><code>private\ndef pages_from(document)\n document.form_json['pages'].map { |page| Page.new(page) }\nend\n</code></pre>\n\n<p>And that makes up the totality of that file, now I just need to start going through the rest of the method and adding the classes and methods on those classes to achieve this goal:</p>\n\n<pre><code>class Row\n # expose the underlying data, so we can modify it later as needed\n attr_reader :row_element\n\n def initialize(row_element)\n @row_element = row_element\n end\n\n def uuid\n @row_element['componentUuid']\n end\n\n def offset\n @row_element['offset']\n end\nend\n\nclass Page\n def initialize(page)\n @page = page\n # still not happy with this block, but overall the code is a lot nicer,\n # so it can stay, for now\n @row_elements = page['floating_components'].map do |fc|\n next unless fc['element_origin'] == 'pdf'\n\n Row.new(fc['field_rows'][0]['row_elements'][0])\n end.compact.group_by(&:uuid).transform_values(&:first)\n\n @fields_to_remove = []\n @fields_to_update = []\n end\n\n def [](row)\n @row_elements[row.uuid]\n end\n\n def row_elements\n return to_enum(:row_elements) unless block_given?\n\n @row_elements.each_value do |row|\n yield row\n end\n end\n\n def delete(row)\n @fields_to_remove << row\n end\n\n def update(row)\n delete row\n\n @fields_to_update << row\n end\nend\n</code></pre>\n\n<p>Not being able to run some examples and make sure everything was working correctly and not having the full scope of everything going on, there's probably some issues with this code, but it should at least get you pointed in a direction or thought process to help clean it up some. As for the performance of the code, that's not my forte, but my general philosophy is to write legible code first and then optimize as needed to meet the business needs</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:16:45.133",
"Id": "467980",
"Score": "0",
"body": "I like your take on it! Upvoted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:17:55.790",
"Id": "467981",
"Score": "0",
"body": "For more context, `@pdf_field_uuids_to_remove` and `@page_to_fd_components_hash` are parameters that I send to another application actually - so maybe casting the components into classes might be overkill in this circumstance since I'd have to serialize them back during my request."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T04:30:30.287",
"Id": "238603",
"ParentId": "238589",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-08T23:33:40.237",
"Id": "238589",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Comparing verbosity of algorithmic Ruby class"
}
|
238589
|
<p>I was wondering why the following implementation of a Suffix Tree is 2000 times slower than using a similar data structure in C++ (I tested it using python3, pypy3 and pypy2). I know the bottleneck is the <code>traverse</code> method, do you spot chance of optimisation in the following code? Thanks!</p>
<pre><code>from sys import stdin, stdout, stderr, setrecursionlimit
setrecursionlimit(100000)
def read():
return stdin.readline().rstrip()
def readint():
return int(read())
def make_node(_pos, _len):
global s, n, sz, to, link, fpos, slen, pos, node
fpos[sz] = _pos
slen[sz] = _len
sz += 1
return sz-1
def go_edge():
global s, n, sz, to, link, fpos, slen, pos, node
while (pos > slen[to[node].get(s[n - pos], 0)]):
node = to[node].get(s[n - pos], 0)
pos -= slen[node]
def add_letter(c):
global s, n, sz, to, link, fpos, slen, pos, node
s[n] = c
n += 1
pos += 1
last = 0
while(pos > 0):
go_edge()
edge = s[n - pos]
v = to[node].get(edge, 0)
t = s[fpos[v] + pos - 1]
if (v == 0):
to[node][edge] = make_node(n - pos, inf)
link[last] = node
last = 0
elif (t == c):
link[last] = node
return
else:
u = make_node(fpos[v], pos - 1)
to[u][c] = make_node(n - 1, inf)
to[u][t] = v
fpos[v] += pos - 1
slen[v] -= pos - 1
to[node][edge] = u
link[last] = u
last = u
if(node == 0):
pos -= 1
else:
node = link[node]
def init_tree(st):
global slen, ans, inf, maxn, s, to, fpos, slen, link, node, pos, sz, n
inf = int(1e9)
maxn = len(st)*2+1 #int(1e6+1)
s = [0]*maxn
to = [{} for i in range(maxn)]
fpos, slen, link = [0]*maxn, [0]*maxn, [0]*maxn
node, pos = 0, 0
sz = 1
n = 0
slen[0] = inf
ans = 0
for c in st:
add_letter(ord(c))
text = "TTTTTTTTTT" + 1777*"A" + "$"
query = 1750*"A"
def traverse_edge(st, idx, start, end):
global len_text, len_st
k = start
while k <= end and k < len_text and idx < len_st:
if text[k] != st[idx]:
return -1
k += 1
idx += 1
if idx == len_st:
return idx
return 0
def edgelen(v, init, e):
if(v == 0):
return 0
return e-init+1
def dfs(node, leafs, off):
if not node:
return
k, tree = node
if not isinstance(tree, int): # it is a node pointing to other nodes
for kk, value in tree.items():
if slen[value] > 190000000:
leafs.append(fpos[value]-off)
else:
dfs((kk, to[value]), leafs, off+slen[value])
def traverse(v, st, idx, depth=0):
global len_st
result = cache.get((v, st), -2)
if result != -2:
return result
r = -1
init = fpos[v]
end = fpos[v]+slen[v]
e = end-1
if v != 0:
r = traverse_edge(st, idx, init, e)
if r != 0:
if r == -1:
cache[(v, st)] = []
return []
depth += r
# Here is when we found a match
leafs = []
dfs((v, to[v]), leafs, depth)
#return reversed(leafs)
return leafs
idx = idx + edgelen(v, init, e)
if idx > len_st:
cache[(v, st)] = []
return []
k = ord(st[idx])
children = to[v]
if k in children:
vv = children.get(k, 0)
matches = traverse(vv, st, idx, depth)
cache[(v, st)] = matches
return matches
return []
def main():
global text, len_st, len_text, cache
init_tree(text)
len_text = len(text)
len_st = len(query)
r = []
#cache = {}
for runs in range(1000):
cache = {}
matches = traverse(0, query, 0)
r.append("\n".join(str(m) for m in matches))
stdout.write("\n".join(r)+"\n")
main()
</code></pre>
|
[] |
[
{
"body": "<p>So, about all those <code>global</code>s. They make your code <em>really</em> hard to read, I have almost no idea what is going on (after having read it twice). The general recommendation is to only use <code>global</code> objects if you really have to. Otherwise pass the objects either as arguments to the function, or write a class which has the relevant variables as attributes and keep the state like this.</p>\n\n<p>Another thing that makes your code a lot easier to understand (both for other people and for yourself in two months time), are <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code>s</a>, which document what each function does, the parameters it takes and what it returns or modifies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:20:36.053",
"Id": "473652",
"Score": "0",
"body": "Thanks for the suggestions. I was just porting this code http://ideone.com/sT8Vd1, explained in https://codeforces.com/blog/entry/16780. In the original code they were using global variables (which is very common in competitive programming implementations) so I tried to keep it the closer I could so it could be easier to compare in my tests. I appreciate your advise about docstrings to make the code clear also"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:47:47.040",
"Id": "238622",
"ParentId": "238594",
"Score": "5"
}
},
{
"body": "<p>I finally gave up trying to optimize Pypy and wrote the code I needed just in C++. Here is it in case somebody is curious:</p>\n\n<pre><code>#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define fpos adla\nconst int inf = 1e9;\nconst int maxn = 1e6+1;\n//#define maxn 100005\n\nchar s[maxn];\nmap<int,int> to[maxn];\nint slen[maxn], fpos[maxn], link[maxn];\nint node, pos;\nint sz = 1, n = 0;\n\nint text_len;\nchar text[maxn];\nint query_len;\nchar query[maxn];\n\nint make_node(int _pos, int _len) {\n fpos[sz] = _pos;\n slen[sz] = _len;\n return sz++;\n}\n\nvoid go_edge() {\n while(pos > slen[to[node][s[n - pos]]]) {\n node = to[node][s[n - pos]];\n pos -= slen[node];\n }\n}\n\nvoid add_letter(int c) {\n s[n++] = c;\n pos++;\n int last = 0;\n while(pos > 0) {\n go_edge();\n int edge = s[n - pos];\n //int &v = to[node][edge];\n int v = to[node][edge];\n int t = s[fpos[v] + pos - 1];\n if(v == 0) {\n //v = make_node(n - pos, inf);\n to[node][edge] = make_node(n - pos, inf);\n link[last] = node;\n last = 0;\n }\n else if(t == c) {\n link[last] = node;\n return;\n }\n else {\n int u = make_node(fpos[v], pos - 1);\n to[u][c] = make_node(n - 1, inf);\n to[u][t] = v;\n fpos[v] += pos - 1;\n slen [v] -= pos - 1;\n // v = u;\n to[node][edge] = u;\n link[last] = u;\n last = u;\n }\n if(node == 0)\n pos--;\n else\n node = link[node];\n }\n}\n\nint traverse_edge(char st[], int st_len, int idx, int start, int end) {\n int k = start;\n while (k <= end && k < text_len && idx < st_len) {\n if (text[k] != st[idx]) {\n return -1;\n }\n k += 1;\n idx += 1;\n }\n if (idx == st_len) {\n return idx;\n }\n return 0;\n}\n\nint edgelen(int v, int init, int e) {\n if (v == 0) {\n return 0;\n }\n return e-init+1;\n}\n\nvoid dfs(map<int, int> tree, vector<vector<int>> leafs, int off) {\n if (tree.empty()) {\n return;\n }\n /* for ( auto [k, value] : tree) { */ // C++17\n for ( auto it : tree) {\n int value = it.second;\n if (slen[value] > maxn / 10) {\n vector<int> leaf;\n leaf.push_back(fpos[value]);\n leaf.push_back(slen[value]);\n leaf.push_back(fpos[value]-off);\n leafs.push_back(leaf);\n } else {\n dfs(to[value], leafs, off+slen[value]);\n }\n }\n}\n\npair<bool, vector<int>> traverse(int v, map<int,int> tree, char st[], int idx, int depth) {\n int r = -1;\n int init = fpos[v];\n int end = fpos[v]+slen[v];\n int e = end - 1;\n if (v != 0) {\n r = traverse_edge(st, query_len, idx, init, e);\n if (r != 0) {\n if (r == -1) {\n return {false, vector<int>{}}; \n }\n vector<int> matches;\n return {true, matches};\n }\n }\n idx = idx + edgelen(v, init, e);\n if (idx > query_len) {\n return {false, vector<int>{}}; \n }\n int k = int(st[idx]);\n map<int,int> children = to[v];\n /* if (children.contains(k)) { */ // C++20 \n if (children.find(k) != children.end()) {\n int vv = tree[k];\n return traverse(vv, to[vv], st, idx, depth);\n }\n return pair<bool, vector<int>>(false, vector<int>{});\n}\n\n\nint main() {\n int t;\n scanf(\"%d\", &t);\n while (t--) {\n scanf(\"%s\", text);\n text_len = strlen(text);\n\n for (int i=0; i<maxn; i++) {\n to[i] = map<int,int>{};\n }\n sz = 1;\n n = 0;\n pos = 0;\n node = 0;\n slen[0] = inf;\n\n for (int i=0; i<text_len; i++) {\n add_letter((int)text[i]);\n }\n add_letter((int)'$');\n\n int q;\n scanf(\"%d\", &q);\n while (q--) {\n scanf(\"%s\", query);\n query_len = strlen(query);\n pair<bool, vector<int>> results = traverse(0, to[0], query, 0, 0);\n printf(\"%s\\n\", results.first ? \"y\" : \"n\");\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T15:34:00.980",
"Id": "241375",
"ParentId": "238594",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T00:02:27.143",
"Id": "238594",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"tree"
],
"Title": "Suffix Tree in Python"
}
|
238594
|
<p>I think I may have come across a good use of goto in my code. From when I started programming in C it was driven into me that goto was akin to summoning the devil himself and use of goto should be avoided at all costs. Here is the code </p>
<pre><code>/*
Attempts to get the physical address from a virtual one by
1. Consulting the TLB
2. Consulting the PageTable
3. If both fail, request data be read into memory
Returns the address of the requested virtual address in physical memory
*/
unsigned int getAddress(unsigned int virtualAddress)
{
const unsigned int pageNumber = getPageNumber(virtualAddress);
const unsigned int pageOffset = getPageOffset(virtualAddress);
// first consult the TLB
int frame = getFrameFromTLB(pageNumber);
if (frame != SENTINEL)
{
TLBHits++;
goto TLB_HIT;
}
// if a TLB miss occurs, consult page table
frame = getFramePageTable(pageNumber);
if (frame != SENTINEL)
{
goto PAGE_HIT;
}
//miss on tlb and page table, page fault occured
pageFaults++;
goto PAGE_FAULT;
PAGE_FAULT:
//page table miss, value not in memory, request physical memory to load value
frame = loadValueFromBackingStore(pageNumber);
//update page table with new frame
insertIntoPageTable(pageNumber, frame);
PAGE_HIT:
insertIntoTLB(pageNumber, frame);
TLB_HIT:
return frame * PAGE_SIZE + pageOffset;
}
</code></pre>
<p>As you can see the code has a cascading execution pattern that a goto seems to model really well. I am wondering is there a clean and similarly sized way to write this without goto? Should that be something I even try to do?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T04:10:12.283",
"Id": "467918",
"Score": "1",
"body": "This looks like Fanuc TP programming"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:08:32.910",
"Id": "467932",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T12:35:14.220",
"Id": "467957",
"Score": "3",
"body": "This question, along with its answer turns out to be a good demonstration of why gotos should (and can) be avoided most of the time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:41:20.620",
"Id": "467973",
"Score": "2",
"body": "@th33lf I agree, seemed to make sense in the moment but upon further inspection theres always a way around them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:41:07.380",
"Id": "467983",
"Score": "1",
"body": "In error conditions there occasionally is a semi reasonable use of goto, but generally it can and should be avoided most of the time."
}
] |
[
{
"body": "<pre><code>goto PAGE_FAULT;\nPAGE_FAULT:\n</code></pre>\n\n<p>This code seems almost like a troll. You can certainly rewrite it to use no <code>goto</code>s; all you have to do is un-flip the conditions that you must have flipped when you inserted the <code>goto</code>s in the first place. For example:</p>\n\n<pre><code> if (frame != SENTINEL) {\n goto PAGE_HIT;\n }\n pageFaults++;\n frame = loadValueFromBackingStore(pageNumber);\n insertIntoPageTable(pageNumber, frame);\nPAGE_HIT:\n</code></pre>\n\n<p>can be rewritten in \"structured programming\" style as</p>\n\n<pre><code> if (frame == SENTINEL) {\n pageFaults++;\n frame = loadValueFromBackingStore(pageNumber);\n insertIntoPageTable(pageNumber, frame);\n }\n</code></pre>\n\n<p>Your whole function boils down to this:</p>\n\n<pre><code>unsigned int getAddress(unsigned int virtualAddress)\n{\n const unsigned int pageNumber = getPageNumber(virtualAddress);\n const unsigned int pageOffset = getPageOffset(virtualAddress);\n\n int frame = getFrameFromTLB(pageNumber);\n if (frame == SENTINEL) {\n frame = getFramePageTable(pageNumber);\n if (frame == SENTINEL) {\n pageFaults += 1;\n frame = loadValueFromBackingStore(pageNumber);\n insertIntoPageTable(pageNumber, frame);\n }\n insertIntoTLB(pageNumber, frame);\n } else {\n TLBHits += 1;\n }\n return frame * PAGE_SIZE + pageOffset;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T01:25:06.487",
"Id": "467913",
"Score": "0",
"body": "I realize the `goto PAGE_FAULT; PAGE_FAULT:` is redundant, its mostly for readability. Regardless thanks for the answer"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T01:18:46.937",
"Id": "238598",
"ParentId": "238595",
"Score": "7"
}
},
{
"body": "<p>The consensus from the never-ending goto debate is pretty much that \"yeah there are cases where you can use goto harmlessly when branching non-conditionally downwards, but those cases could as well be written without goto too\".</p>\n\n<p>So your code isn't horrible, but it isn't pretty either - it looks like the old \"on error goto...\" error handling pattern used by BASIC. At any rate, all the jumping around is redundant and makes the code needlessly hard to read.</p>\n\n<p>Since you are updating global variables in several places, you might as well have rewritten the function as this:</p>\n\n<pre><code>unsigned int getAddress(unsigned int virtualAddress)\n{\n const unsigned int pageNumber = getPageNumber(virtualAddress);\n const unsigned int pageOffset = getPageOffset(virtualAddress);\n\n if(getFrameFromTLB(pageNumber) != TLB_HIT)\n {\n if(getFramePageTable(pageNumber) != PAGE_HIT)\n {\n //page table miss, value not in memory, request physical memory to load value\n frame = loadValueFromBackingStore(pageNumber);\n\n //update page table with new frame\n insertIntoPageTable(pageNumber, frame);\n }\n }\n\n return frame * PAGE_SIZE + pageOffset;\n}\n</code></pre>\n\n<p>This assuming that the called functions update the global variables instead, and <code>TLB_HIT</code> and so on is some enum with error codes. There are other ways you can rewrite it too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:15:38.380",
"Id": "468174",
"Score": "1",
"body": "Also, not to be underestimated: avoiding goto means you are avoiding having yet another tiresome goto debate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:15:30.997",
"Id": "238710",
"ParentId": "238595",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238598",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T00:10:44.887",
"Id": "238595",
"Score": "-3",
"Tags": [
"c"
],
"Title": "Good use of goto?"
}
|
238595
|
<p>I got some good feedback from the <a href="https://codereview.stackexchange.com/questions/237601/simple-python-turn-based-battle-game">last code I posted</a> which I have incorporated in to this project (enum, try, f string formatting), so again just looking for some feedback on how the code could be improved. My teenage son came home with a Computer Science project for Rock Paper Scissors with an advanced option to add Lizard and Spock, keep score, ask for users name and give meaningful feedback on result. Not sure what he has come up with yet, I'm guessing a lot of if / elif statements! However, this is my effort. Any suggestions greatly appreciated.</p>
<pre><code>from enum import Enum
from random import choice
Weapon = Enum("Weapon", "Rock, Paper, Scissors, Lizard, Spock")
# Add a list attribute to each weapon of the weapons it can beat
Weapon.Rock.beats = [Weapon.Scissors, Weapon.Lizard]
Weapon.Paper.beats = [Weapon.Spock, Weapon.Rock]
Weapon.Scissors.beats = [Weapon.Paper, Weapon.Lizard]
Weapon.Lizard.beats = [Weapon.Spock, Weapon.Paper]
Weapon.Spock.beats = [Weapon.Scissors, Weapon.Rock]
# Add an dictionary attribute to each weapon of the action verbs it is capable of
Weapon.Rock.actions = {Weapon.Scissors: "blunts", Weapon.Lizard: "crushes"}
Weapon.Paper.actions = {Weapon.Spock: "disproves", Weapon.Rock: "covers"}
Weapon.Scissors.actions = {Weapon.Paper: "cut", Weapon.Lizard: "decapitates"}
Weapon.Lizard.actions = {Weapon.Spock: "poisons", Weapon.Paper: "eats"}
Weapon.Spock.actions = {Weapon.Scissors: "smashes", Weapon.Rock: "vapourizes"}
# Set up player class
class Player:
def __init__(self, name):
self.name = name
self.weapon = None
self.score = 0
def display_results(self, opponent, message):
print(f"{self.name} chose {self.weapon.name} and {opponent.name} chose {opponent.weapon.name}")
print(f"{self.weapon.name} {self.weapon.actions[opponent.weapon]} {opponent.weapon.name}")
print(message)
def win(self):
self.score += 1
def display_instructions():
''' Function to display instructions when game starts'''
print("""
____________________________________________________________________
First the human player choses a weapon, after that the computer
will chose a weapon at random
The object of the game is to pick a weapon that will beat the weapon
the computer has chosen
Rock - beats Sciccors and Lizard
Paper - beats Spock and Rock
Scissors - beats Paper and Lizard
Lizard - beats Spock and Paper
Spock - beats Scissors and Rock
Have fun!\n
_____________________________________________________________________
""")
def display_score(human, ai):
""" Function to display score after each turn """
print("------------------------------------------------------")
print(f"{human.name} - {human.score} - Computer - {ai.score}\n")
#Main Game
print("Welcome to Rock, Paper, Scissors, Lizard, Spock\n")
player_name = input("What is your first name: ").title()
yes_no = input(f"\nHello {player_name}, do you want to see the instructions (Y or N)? ")
if yes_no.upper() == "Y":
display_instructions()
# Create player objects
human = Player(player_name)
ai = Player("Computer")
# Main Game loop
while True:
# User choses weapon
# Catches the error if user enters an invalid option and loops until valid or QUIT
try:
menu_options = [f"{weapon.value} - {weapon.name}" for weapon in Weapon]
menu_options = "\n".join(menu_options)
print(menu_options)
user_choice = input("Make you selection (1 - 5) or type QUIT: ")
human.weapon = Weapon(int(user_choice))
except:
if user_choice.upper() == "QUIT":
print("Thank you for playing")
exit()
else:
print("Sorry, that was not one of the options, try again!\n")
continue
# Computer chooses weapon
ai.weapon = choice(list(Weapon))
# Decides who won, displays results and increases score of wining player
if human.weapon == ai.weapon:
print(f"You chose {human.weapon.name} and the computer chose {ai.weapon.name}")
print("It was a DRAW\n")
elif ai.weapon in human.weapon.beats:
human.display_results(ai, "You WIN\n")
human.win()
else:
ai.display_results(human, "You LOSE\n")
ai.win()
display_score(human, ai)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:35:03.547",
"Id": "467937",
"Score": "1",
"body": "Standard advice not really worthy of a separate answer: enclose the logic in a function (i.e. main()) and call it inside an `if __name__ == \"__main__\"` block. This will allow you to import the module without executing it for both (unit-)tests and future extensions (e.g.: a GUI version might want to re-use the main game loop or some part of it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T12:30:25.230",
"Id": "467956",
"Score": "1",
"body": "Not worth a full answer, but you misspelled \"Scissors\" in the instructions describing what Rock beats. \"beats Sciccors and Lizard\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T12:46:59.843",
"Id": "467958",
"Score": "0",
"body": "Your `Weapon` enum is being passed 2 arguments. Add quotes!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:22:06.310",
"Id": "467962",
"Score": "1",
"body": "Somehow, I feel obliged to answer this particular question! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:48:46.357",
"Id": "467966",
"Score": "1",
"body": "Minor nitpick: I would `textwrap.dedent(...)` the string literal in `display_instructions` for left-aligned output while preserving the satisfying code layout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:05:58.860",
"Id": "467968",
"Score": "0",
"body": "Thanks to everyone for their great suggestions. This is such a helpful community. Coders should really run world, it would probably be a much better place!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T16:39:40.840",
"Id": "467991",
"Score": "0",
"body": "There's a relevant xkcd for programmers creating the world, but I can't find it"
}
] |
[
{
"body": "<h1>One Source of Truth</h1>\n\n<p><code>Weapon.XXX.beats</code> is redundant. <code>Weapon.XXX.actions</code> provides the same information.</p>\n\n<pre><code>elif ai.weapon in human.weapon.actions:\n # Human's weapon has an action -vs- ai's weapon, so human's weapon wins!\n</code></pre>\n\n<p>Therefore, you can remove all of the <code>Weapon.XXX.beats = [YYY, ZZZ]</code> code. Having only one source of truth avoids the possibility of contradictory information.</p>\n\n<p>Alternatively, you can generate all of the <code>.beats</code> information:</p>\n\n<pre><code>for weapon in Weapon:\n weapon.beats = { inferior for inferior in Weapon if inferior in weapon.actions }\n</code></pre>\n\n<p>Note: I've used a <code>set</code> for <code>.beats</code>, for efficient <code>in</code> testing.</p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/203765/g%C3%A1bor-fekete\">Gábor Fekete</a> points out in a comment below, this could be generated with slightly less code:</p>\n\n<pre><code>for weapon in Weapon:\n weapon.beats = set(weapon.actions.keys())\n</code></pre>\n\n<h1>Enhanced Enums</h1>\n\n<p>An enums is a class, and like any other class, you can extend it to enhance its behaviour.</p>\n\n<p>In this project and the last project, you used <code>\"# - name\"</code> as a choice option. We can add a <code>__str__</code> method this to the <code>Enum</code> class:</p>\n\n<pre><code>class Weapon(Enum):\n Rock = 1\n Paper = 2\n Scissors = 3\n Lizard = 4\n Spock = 5\n\n def __str__(self):\n return f\"{self.value} - {self.name}\"\n</code></pre>\n\n<p>Now, <code>str(weapon)</code> or <code>f\"{weapon}\"</code> would would produce the <code>\"# - name\"</code> string. Of course, you'd still use <code>weapon.name</code> when you want just the weapon's name.</p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/219945/marco-capitani\">Marco Capitani</a> mentions in the comments, we can define a <code>.beats()</code> method (instead of a <code>.beats</code> data member) which gives us \"<em>a single source of truth AND the useful minimal abstraction \"beats\" provides</em>\".</p>\n\n<pre><code> def beats(self, other_weapon):\n return other_weapon in self.actions\n</code></pre>\n\n<p>which allows a more natural looking:</p>\n\n<pre><code> elif human.weapon.beats(ai.weapon):\n</code></pre>\n\n<p>Extending this: A weapon that beats another weapon is \"better than\" another weapon, so we could define the <code>></code> and <code><</code> comparison operators in the <code>Weapon</code> class.</p>\n\n<pre><code> def __gt__(self, other_weapon):\n if isinstance(other_weapon, Weapon):\n return self.beats(other_weapon)\n return NotImplemented\n\n def __lt__(self, other_weapon):\n if isinstance(other_weapon, Weapon):\n return other_weapon.beats(self)\n return NotImplemented\n</code></pre>\n\n<p>which allows an even more natural looking:</p>\n\n<pre><code> elif human.weapon > ai.weapon:\n</code></pre>\n\n<p>But use caution, restraint and common sense when it comes to defining these <a href=\"https://docs.python.org/3/reference/datamodel.html?highlight=__gt_#object.__lt__\" rel=\"nofollow noreferrer\">rich comparison</a> operators. You should only do so if there is a strict ordering possible between the objects, or you can create strange, non-transitive relationships, like:</p>\n\n<pre><code>>>> Weapon.Rock > Weapon.Lizard > Weapon.Spock > Weapon.Rock\nTrue\n</code></pre>\n\n<p>which means sorting, which relies on these comparison operations, will fail spectacularly. Again, use common sense. While the non-transitive nature of these weapons will break sorting, you aren't likely to be sorting, so I feel the clarity of the <code>human.weapon > ai.weapon</code> wins out in this case.</p>\n\n<p>The <code>isinstance(...)</code> check ensures that things like <code>Weapon.Rock > 0</code> will still return a <code>TypeError</code>, instead of a meaningless <code>False</code> value.</p>\n\n<p>In this project and the last project, you have an AI choosing weapons at random. We can add a class method to do this into the <code>Weapon</code> class as well:</p>\n\n<pre><code> @classmethod\n def random(cls):\n return choice(list(cls))\n</code></pre>\n\n<p>which you would use like <code>ai.weapon = Weapon.random()</code>.</p>\n\n<h1>AI's name</h1>\n\n<p>You've made the AI a <code>Player</code> with the name <code>\"Computer\"</code>. But then you display the score with:</p>\n\n<pre><code> print(f\"{human.name} - {human.score} - Computer - {ai.score}\\n\") \n</code></pre>\n\n<p>You should probably use:</p>\n\n<pre><code> print(f\"{human.name} - {human.score} - {ai.name} - {ai.score}\\n\") \n</code></pre>\n\n<p>in case you want to change the name of your AI to something else, like \"HAL9000\", \"Deep Thought\" or \"GLaDOS\".</p>\n\n<p>Same issue here, but now you've got a problem with \"the\". You probably wouldn't want \"... and the Deep Thought chose ...\", but simply dropping the word \"the\" is awkward if the name is \"Computer\" (you wouldn't want \"... and Computer chose ...\"):</p>\n\n<pre><code> print(f\"You chose {human.weapon.name} and the computer chose {ai.weapon.name}\")\n</code></pre>\n\n<h1>Instructions</h1>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/129260/malivil\">Malivi</a> points out, you spelt \"scissors\" incorrectly, which made me realize you still have multiple sources of truth: the <code>Enum</code> data & the instructions. If you modified the game to include more Weapons (Rock-Paper-Scissors-Lizard-Spock-Well-Plant), you'd have to update both areas!</p>\n\n<p>Instead, you could change the code to display instructions based directly on the <code>Enum</code> data:</p>\n\n<pre><code>def display_instructions(): \n print(f\"\"\"\n {'_'*68}\n First the human player chooses ...\n \"\"\")\n\n for weapon in Weapon:\n losers = \", \".join(w.name for w in weapon.actions)\n print(f\"{weapon.name} - beats {losers}\")\n\n print(f\"\"\"\n Have fun!\n\n {'_'*68}\n \"\"\")\n</code></pre>\n\n<p>Joining a list of weapons, with commas between each one, with <code>\" and \"</code> before the last <code>weapon</code>, possibly using an <a href=\"https://en.wikipedia.org/wiki/Serial_comma\" rel=\"nofollow noreferrer\">Oxford comma</a>, left as exercise for the student. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T03:04:05.513",
"Id": "467914",
"Score": "1",
"body": "Seems so obvious when you point it out. As usual awesome feedback. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:30:25.323",
"Id": "467936",
"Score": "1",
"body": "Also, combining point 1 + 3: you can have \"beats\" be a method on the Weapon class:\ndef beats(self, otherWeapon):\\n return otherWeapon in self.actions\nThis lets you have a single source of truth AND the useful minimal abstraction \"beats\" provides"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T10:27:24.870",
"Id": "467943",
"Score": "1",
"body": "The loop to set the `.beats` could use the `weapon.actions.keys()` instead of the comprehension. It would be still type `dict_keys` so converting it to a `set` will produce the same result."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T02:46:28.180",
"Id": "238600",
"ParentId": "238596",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T00:53:56.957",
"Id": "238596",
"Score": "17",
"Tags": [
"python",
"beginner",
"python-3.x",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors Lizard Spock"
}
|
238596
|
<p>Im implementing and designing a workflow that performs both HTTP and BLE requests. </p>
<p>Im having trouble figuring out the best approach to design a service to handle both types of requests, and manage state. </p>
<p>I thought to make a base class <code>Request</code> with an <code>execute</code> method that all types of requests will conform to.</p>
<p>BLE and HTTP are quite different and dont share any attributes, so I made an enum to handle their associated values. It includes a <code>provider</code> which is a client that exposes api to perform actual <code>BLE</code> or <code>HTTP</code> request.</p>
<pre><code>enum RequestCode: UInt {
case getStatus = 0x01
case download = 0x02
case confirm = 0x03
case cancel = 0x04
case getAuthToken = 0xF5
}
enum RequestType {
case BLE(code:RequestCode, provider:BLEProvider, characteristic: CBCharacteristic, service: CBService)
case HTTP(code:RequestCode, provider:NetworkProvider, data: Data, accessToken:String, method:HTTPMethod, params:[String:Any]?)
}
class Request {
var type: RequestType
init(type: RequestType) {
self.type = type
}
func execute() {
switch type {
case .BLE(let code, let provider, let characteristic, let service):
provider.writeValue(data: code.rawValue, characteristic: characteristic, service:service)
case .HTTP(let code, let provider, let data, let accessToken, let method, let params):
provider.performRequest(data: data, token: accessToken, method: method, params:params)
}
}
}
</code></pre>
<p><strong>Questions</strong></p>
<ol>
<li><p>What is a better way to structure my requests, to handle both BLE and HTTP? </p></li>
<li><p>How can I handle transitions from one state/event to the next? Does it make sense to try to use promises, where I can call <code>execute</code> on each request, and chain them all together? If not, should I think of adding each request to a queue, if and how could a state machine be designed around <code>RequestCode</code> which are the events in the sequence? </p></li>
</ol>
|
[] |
[
{
"body": "<p>You should separate concerns whenever possible. Since BLE & HTTP requests are quite different, you could write the following protocols:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>protocol Request {\n associatedtype Provider\n var provider: Provider { get }\n\n func execute() \n}\n\nprotocol BLERequest: Request {\n typealias Provider = BLEProvider\n\n var code: UInt { get }\n var characteristic: CBCharacteristic { get }\n var service: CBService { get }\n}\n\nprotocol HTTPRequest: Request {\n typealias Provider = NetworkProvider\n\n var data: Data { get }\n var accessToken: String { get }\n var method: HTTPMethod { get }\n var params: [String:Any]? { get }\n}\n</code></pre>\n\n<p>Then comes the magic; you can write generic extensions on your <code>Request</code> protocol, for each specific <code>Request</code> type.</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>extension Request where Self: BLERequest {\n func execute() {\n // provider is available since it is a get-able requirement, \n // and we know it is a BLEProvider instance\n // same goes for all the other get-able vars\n provider.writeValue(data: code, characteristic: characteristic, service: service)\n }\n}\n\nextension Request where Self: HTTPRequest {\n func execute() {\n // Again, same thing, we have all vars we need\n provider.performRequest(data: data, token: accessToken, method: method, params: params)\n }\n}\n</code></pre>\n\n<p>Then, when you are implementing a new <code>Request</code>, all you need to do is implement the requirements for your chosen protocol, and everything else will be handled for you :)</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>enum MyBLERequest: BLERequest {\n case getStatus\n case download\n\n // MARK: BLE Request conformance\n var provider: Provider {\n return BLEProvider(... whatever init is needed)\n }\n\n var code: UInt {\n switch self {\n case .getStatus: return 0x01\n case .download: return 0x02\n // Any further new case will require you to implement the code here, so you have compile-time safety :)\n }\n }\n\n var characteristic: CBCharacteristic {\n return CBCharacteristic(.. init)\n }\n\n var service: CBService {\n return CBService(... more init)\n }\n}\n</code></pre>\n\n<p>Then you can simply do <code>MyBLERequest.getStatus.execute()</code>, and it's all done through the protocol extension code.</p>\n\n<p>And since Swift Enums allow associated values, you can always pass in additional parameters, whenever needed (you could have another case <code>case getAuthToken(byUserID: String)</code>, which are then available to you in your implementation)</p>\n\n<p>Now, since you have this all neatly separated, I would go further and pass your <code>Request</code> instances to each specific <code>Provider</code> directly. In effect, you are not the one <code>executing</code> a request, a <code>provider</code> is. That means your requests are agnostic to whatever <code>Provider</code> executes them, which will allow you to set up unit testing easier (because then you can write Mock Providers, and still pass them your requests like usual).</p>\n\n<p>So you should probably extend each provider like such:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>extend BLEProvider {\n func execute(request: BLERequest) {\n writeValue(code: request.code, \n characteristic: request.characteristic,\n service: request.service)\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T01:05:57.853",
"Id": "469380",
"Score": "1",
"body": "thanks, exactly the detailed answer i was looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-16T17:22:05.607",
"Id": "239009",
"ParentId": "238599",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T02:00:32.263",
"Id": "238599",
"Score": "3",
"Tags": [
"object-oriented",
"swift",
"http",
"ios",
"bluetooth"
],
"Title": "Handle HTTP and BLE requests"
}
|
238599
|
<p>For the full code, please go to <a href="https://github.com/emadboctorx/labelpix" rel="nofollow noreferrer">https://github.com/emadboctorx/labelpix</a></p>
<p>This is an object detection tool for drawing bounding boxes over images and save output to csv/hdf or yolo (<a href="https://pjreddie.com/darknet/yolo/" rel="nofollow noreferrer">You Only Look Once</a>) format. Suggestions for improvement / features to add / general feedback are more than welcome.</p>
<h1>Features</h1>
<ul>
<li>Preview and edit interfaces.</li>
<li>Save bounding box relative coordinates to csv / hdf formats.</li>
<li>Save relative coordinates to yolo format</li>
</ul>
<h1>Instructions</h1>
<ul>
<li>Upload photos.</li>
<li>Add labels to session labels.</li>
<li>Click on a photo from the photo list.</li>
<li>Click on the desired label from the labels you added.</li>
<li>Activate edit mode.</li>
<li>Draw bounding boxes.</li>
<li>Switch photos by scrolling/clicking on images in the list.</li>
<li>Save data by entering filename_example.csv or filename_example.h5</li>
<li>You can also save to yolo formatted txt outputs.</li>
<li>For deleting any of the 3 right lists (session labels / Labels of the current image / Photo list) items, check item and press the delete button</li>
</ul>
<h1>Image</h1>
<p><a href="https://i.stack.imgur.com/3vDCJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3vDCJ.jpg" alt="ui" /></a></p>
<h1>Code</h1>
<p><code>labelpix.py</code>:</p>
<pre><code>from PyQt5.QtGui import QIcon, QPixmap, QPainter, QPen
from PyQt5.QtWidgets import (QMainWindow, QApplication, QDesktopWidget, QAction, QStatusBar, QHBoxLayout,
QVBoxLayout, QWidget, QLabel, QListWidget, QFileDialog, QFrame,
QLineEdit, QListWidgetItem, QDockWidget, QMessageBox)
from PyQt5.QtCore import Qt, QPoint, QRect
from settings import *
import pandas as pd
import cv2
import sys
import os
class RegularImageArea(QLabel):
"""
Display only area within the main interface.
"""
def __init__(self, current_image, main_window):
"""
Initialize current image for display.
Args:
current_image: Path to target image.
main_window: ImageLabeler instance.
"""
super().__init__()
self.setFrameStyle(QFrame.StyledPanel)
self.current_image = current_image
self.main_window = main_window
def get_image_names(self):
"""
Return:
Directory of the current image and the image name.
"""
full_name = self.current_image.split('/')
return '/'.join(full_name[:-1]), full_name[-1].replace('temp-', '')
def paintEvent(self, event):
"""
Adjust image size to current window.
Args:
event: QPaintEvent object.
Return:
None
"""
painter = QPainter(self)
current_size = self.size()
origin = QPoint(0, 0)
if self.current_image:
scaled_image = QPixmap(self.current_image).scaled(
current_size, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
painter.drawPixmap(origin, scaled_image)
def switch_image(self, img):
"""
Switch the current image displayed in the main window with the new one.
Args:
img: Path to new image to display.
Return:
None
"""
self.current_image = img
self.repaint()
@staticmethod
def calculate_ratios(x1, y1, x2, y2, width, height):
"""
Calculate relative object ratios in the labeled image.
Args:
x1: Start x coordinate.
y1: Start y coordinate.
x2: End x coordinate.
y2: End y coordinate.
width: Bounding box width.
height: Bounding box height.
Return:
bx: Relative center x coordinate.
by: Relative center y coordinate.
bw: Relative box width.
bh: Relative box height.
"""
box_width = abs(x2 - x1)
box_height = abs(y2 - y1)
bx = 1 - ((width - min(x1, x2) + (box_width / 2)) / width)
by = 1 - ((height - min(y1, y2) + (box_height / 2)) / height)
bw = box_width / width
bh = box_height / height
return bx, by, bw, bh
@staticmethod
def ratios_to_coordinates(bx, by, bw, bh, width, height):
"""
Convert relative coordinates to actual coordinates.
Args:
bx: Relative center x coordinate.
by: Relative center y coordinate.
bw: Relative box width.
bh: Relative box height.
width: Current image display space width.
height: Current image display space height.
Return:
x: x coordinate.
y: y coordinate.
w: Bounding box width.
h: Bounding box height.
"""
w, h = bw * width, bh * height
x, y = bx * width + (w / 2), by * height + (h / 2)
return x, y, w, h
def draw_boxes(self, ratios):
"""
Draw boxes over the current image using given ratios.
Args:
ratios: A list of [[bx, by, bw, bh], ...]
Return:
None
"""
img_dir, img_name = self.get_image_names()
to_label = cv2.imread(self.current_image)
to_label = cv2.resize(to_label, (self.width(), self.height()))
for bx, by, bw, bh in ratios:
x, y, w, h = self.ratios_to_coordinates(bx, by, bw, bh, self.width(), self.height())
to_label = cv2.rectangle(to_label, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 1)
temp = f'{img_dir}/temp-{img_name}'
cv2.imwrite(f'{img_dir}/temp-{img_name}', to_label)
self.switch_image(temp)
class ImageEditorArea(RegularImageArea):
"""
Edit and display area within the main interface.
"""
def __init__(self, current_image, main_window):
"""
Initialize current image for display.
Args:
current_image: Path to target image.
main_window: ImageLabeler instance.
"""
super().__init__(current_image, main_window)
self.main_window = main_window
self.start_point = QPoint()
self.end_point = QPoint()
self.begin = QPoint()
self.end = QPoint()
def paintEvent(self, event):
"""
Adjust image size to current window and draw bounding box.
Args:
event: QPaintEvent object.
Return:
None
"""
super().paintEvent(event)
qp = QPainter(self)
pen = QPen(Qt.red)
qp.setPen(pen)
qp.drawRect(QRect(self.begin, self.end))
def mousePressEvent(self, event):
"""
Start drawing the box.
Args:
event: QMouseEvent object.
Return:
None
"""
self.start_point = event.pos()
self.begin = event.pos()
self.end = event.pos()
self.update()
def mouseMoveEvent(self, event):
"""
Update size with mouse move.
Args:
event: QMouseEvent object.
Return:
None
"""
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
"""
Calculate coordinates of the bounding box, display a message, update session data.
Args:
event: QMouseEvent object.
Return:
None
"""
self.begin = event.pos()
self.end = event.pos()
self.end_point = event.pos()
x1, y1, x2, y2 = (self.start_point.x(), self.start_point.y(),
self.end_point.x(), self.end_point.y())
self.main_window.statusBar().showMessage(f'Start: {x1}, {y1}, End: {x2}, {y2}')
self.update()
if self.current_image:
bx, by, bw, bh = self.calculate_ratios(x1, y1, x2, y2, self.width(), self.height())
self.update_session_data(x1, y1, x2, y2)
current_label_index = self.main_window.get_current_selection('slabels')
if current_label_index is None or current_label_index < 0:
return
self.draw_boxes([[bx, by, bw, bh]])
def update_session_data(self, x1, y1, x2, y2):
"""
Add a row to session_data containing calculated ratios.
Args:
x1: Start x coordinate.
y1: Start y coordinate.
x2: End x coordinate.
y2: End y coordinate.
Return:
None
"""
current_label_index = self.main_window.get_current_selection('slabels')
if current_label_index is None or current_label_index < 0:
return
window_width, window_height = self.width(), self.height()
object_name = self.main_window.right_widgets['Session Labels'].item(current_label_index).text()
bx, by, bw, bh = self.calculate_ratios(x1, y1, x2, y2, window_width, window_height)
data = [[self.get_image_names()[1], object_name, current_label_index, bx, by, bw, bh]]
to_add = pd.DataFrame(data, columns=self.main_window.session_data.columns)
self.main_window.session_data = pd.concat([self.main_window.session_data, to_add], ignore_index=True)
self.main_window.add_to_list(f'{data}', self.main_window.right_widgets['Image Label List'])
class ImageLabeler(QMainWindow):
"""
Image labeling main interface.
"""
def __init__(self, window_title='Image Labeler', current_image_area=RegularImageArea):
"""
Initialize main interface and display.
Args:
window_title: Title of the window.
current_image_area: RegularImageArea or ImageEditorArea object.
"""
super().__init__()
self.current_image = None
self.label_file = None
self.current_image_area = current_image_area
self.images = []
self.image_paths = {}
self.session_data = pd.DataFrame(
columns=['Image', 'Object Name', 'Object Index', 'bx', 'by', 'bw', 'bh'])
self.window_title = window_title
self.setWindowTitle(self.window_title)
win_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
win_rectangle.moveCenter(center_point)
self.move(win_rectangle.topLeft())
self.setStyleSheet('QPushButton:!hover {color: orange} QLineEdit:!hover {color: orange}')
self.tools = self.addToolBar('Tools')
self.tool_items = setup_toolbar(self)
self.top_right_widgets = {'Add Label': (QLineEdit(), self.add_session_label)}
self.right_widgets = {'Session Labels': QListWidget(),
'Image Label List': QListWidget(),
'Photo List': QListWidget()}
self.left_widgets = {'Image': self.current_image_area('', self)}
self.setStatusBar(QStatusBar(self))
self.adjust_tool_bar()
self.central_widget = QWidget(self)
self.main_layout = QHBoxLayout()
self.left_layout = QVBoxLayout()
self.adjust_widgets()
self.adjust_layouts()
self.show()
def adjust_tool_bar(self):
"""
Adjust the top tool bar and setup buttons/icons.
Return:
None
"""
self.tools.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
if sys.platform == 'darwin':
self.setUnifiedTitleAndToolBarOnMac(True)
for label, icon_file, widget_method, status_tip, key, check in self.tool_items.values():
action = QAction(QIcon(f'../Icons/{icon_file}'), label, self)
action.setStatusTip(status_tip)
action.setShortcut(key)
if check:
action.setCheckable(True)
if label == 'Delete':
action.setShortcut('Backspace')
action.triggered.connect(widget_method)
self.tools.addAction(action)
self.tools.addSeparator()
def adjust_layouts(self):
"""
Adjust window layouts.
Return:
None
"""
self.main_layout.addLayout(self.left_layout)
self.central_widget.setLayout(self.main_layout)
self.setCentralWidget(self.central_widget)
def adjust_widgets(self):
"""
Adjust window widgets.
Return:
None
"""
self.left_layout.addWidget(self.left_widgets['Image'])
for text, (widget, widget_method) in self.top_right_widgets.items():
dock_widget = QDockWidget(text)
dock_widget.setFeatures(QDockWidget.NoDockWidgetFeatures)
dock_widget.setWidget(widget)
self.addDockWidget(Qt.RightDockWidgetArea, dock_widget)
if widget_method:
widget.editingFinished.connect(widget_method)
self.top_right_widgets['Add Label'][0].setPlaceholderText('Add Label')
self.right_widgets['Photo List'].selectionModel().currentChanged.connect(
self.display_selection)
for text, widget in self.right_widgets.items():
dock_widget = QDockWidget(text)
dock_widget.setFeatures(QDockWidget.NoDockWidgetFeatures)
dock_widget.setWidget(widget)
self.addDockWidget(Qt.RightDockWidgetArea, dock_widget)
def get_current_selection(self, display_list):
"""
Get current selected item data.
Args:
display_list: One of the right QWidgetList(s).
Return:
Image path or current row.
"""
if display_list == 'photo':
current_selection = self.right_widgets['Photo List'].currentRow()
if current_selection >= 0:
return self.images[current_selection]
self.right_widgets['Photo List'].selectionModel().clear()
if display_list == 'slabels':
current_selection = self.right_widgets['Session Labels'].currentRow()
if current_selection >= 0:
return current_selection
@staticmethod
def add_to_list(item, widget_list):
"""
Add item to one of the right QWidgetList(s).
Args:
item: str : Item to add.
widget_list: One of the right QWidgetList(s).
Return:
None
"""
item = QListWidgetItem(item)
item.setFlags(item.flags() | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
item.setCheckState(Qt.Unchecked)
widget_list.addItem(item)
widget_list.selectionModel().clear()
def display_selection(self):
"""
Display image that is selected in the right Photo list.
Return:
None
"""
ratios = []
self.right_widgets['Image Label List'].clear()
self.current_image = self.get_current_selection('photo')
if not self.current_image:
return
self.left_widgets['Image'].switch_image(self.current_image)
image_dir, img_name = self.left_widgets['Image'].get_image_names()
for item in self.session_data.loc[self.session_data['Image'] == img_name].values:
self.add_to_list(f'{[[x for x in item]]}', self.right_widgets['Image Label List'])
ratios.append([x for x in item][3:])
self.left_widgets['Image'].draw_boxes(ratios)
def upload_photos(self):
"""
Add image(s) to the right photo list.
Return:
None
"""
file_dialog = QFileDialog()
file_names, _ = file_dialog.getOpenFileNames(self, 'Upload Photos')
for file_name in file_names:
image_dir, photo_name = '/'.join(file_name.split('/')[:-1]), file_name.split('/')[-1]
self.add_to_list(photo_name, self.right_widgets['Photo List'])
self.images.append(file_name)
self.image_paths[photo_name] = image_dir
def upload_vid(self):
pass
def upload_folder(self):
"""
Add images of a folder to the right photo list.
Return:
None
"""
file_dialog = QFileDialog()
folder_name = file_dialog.getExistingDirectory()
if folder_name:
for file_name in os.listdir(folder_name):
if not file_name.startswith('.'):
photo_name = file_name.split('/')[-1]
self.add_to_list(photo_name, self.right_widgets['Photo List'])
self.images.append(f'{folder_name}/{file_name}')
self.image_paths[file_name] = folder_name
def switch_editor(self, image_area):
"""
Switch between the display/edit interfaces.
Args:
image_area: RegularImageArea or ImageEditorArea object.
Return:
None
"""
self.left_layout.removeWidget(self.left_widgets['Image'])
self.left_widgets['Image'] = image_area(self.current_image, self)
self.left_layout.addWidget(self.left_widgets['Image'])
def edit_mode(self):
"""
Switch between the display/edit interfaces.
Return:
None
"""
if self.windowTitle() == 'Image Labeler':
self.setWindowTitle('Image Labeler(Editor Mode)')
self.switch_editor(ImageEditorArea)
else:
self.setWindowTitle('Image Labeler')
self.switch_editor(RegularImageArea)
self.display_selection()
def save_session_data(self, location):
"""
Save session data to csv/hdf.
Args:
location: Path to save session data file.
Return:
None
"""
if location.endswith('.csv'):
self.session_data.to_csv(location, index=False)
if location.endswith('h5'):
self.session_data.to_hdf(location, key='session_data', index=False)
def read_session_data(self, location):
"""
Read session data from csv/hdf
Args:
location: Path to session data file.
Return:
data.
"""
data = self.session_data
if location.endswith('.csv'):
data = pd.read_csv(location)
if location.endswith('.h5'):
data = pd.read_hdf(location, 'session_data')
return data
def save_changes_table(self):
"""
Save the data in self.session_data to new/existing csv/hdf format.
Return:
None
"""
if self.label_file:
location = self.label_file
old_session_data = self.read_session_data(location)
self.session_data = pd.concat([old_session_data, self.session_data], ignore_index=True)
self.session_data.drop_duplicates(inplace=True)
self.save_session_data(location)
else:
dialog = QFileDialog()
location, _ = dialog.getSaveFileName(self, 'Save as')
self.label_file = location
self.save_session_data(location)
self.statusBar().showMessage(f'Labels Saved to {location}')
def clear_yolo_txt(self):
"""
Delete txt files in working directories.
Return:
None
"""
working_directories = set(['/'.join(item.split('/')[:-1]) for item in self.images])
for working_directory in working_directories:
for file_name in os.listdir(working_directory):
if file_name.endswith('.txt'):
os.remove(f'{working_directory}/{file_name}')
def save_changes_yolo(self):
"""
Save session data to txt files in yolo format.
Return:
None
"""
if self.session_data.empty:
return
self.clear_yolo_txt()
txt_file_names = set()
for index, data in self.session_data.iterrows():
image_name, object_name, object_index, bx, by, bw, bh = data
image_path = self.image_paths[image_name]
txt_file_name = f'{image_path}/{image_name.split(".")[0]}.txt'
txt_file_names.add(txt_file_name)
with open(txt_file_name, 'a') as txt:
txt.write(f'{object_index!s} {bx!s} {by!s} {bw!s} {bh!s}\n')
self.statusBar().showMessage(f'Saved {len(txt_file_names)} txt files')
@staticmethod
def get_list_selections(widget_list):
"""
Get in-list index of checked items in the given QWidgetList.
Args:
widget_list: One of the right QWidgetList(s).
Return:
A list of checked indexes.
"""
items = [widget_list.item(i) for i in range(widget_list.count())]
checked_indexes = [checked_index for checked_index, item in enumerate(items)
if item.checkState() == Qt.Checked]
return checked_indexes
def delete_list_selections(self, checked_indexes, widget_list):
"""
Delete checked indexes in the given QWidgetList.
Args:
checked_indexes: A list of checked indexes.
widget_list: One of the right QWidgetList(s).
Return:
None
"""
if checked_indexes:
for q_list_index in reversed(checked_indexes):
if widget_list is self.right_widgets['Photo List']:
image_name = self.images[q_list_index].split('/')[-1]
del self.images[q_list_index]
del self.image_paths[image_name]
if widget_list is self.right_widgets['Image Label List']:
current_row = eval(f'{self.right_widgets["Image Label List"].item(q_list_index).text()}')[0]
row_items = dict(zip(self.session_data.columns, current_row))
current_boxes = self.session_data.loc[self.session_data['Image'] == current_row[0]]
for index, box in current_boxes[['bx', 'by', 'bw', 'bh']].iterrows():
if box['bx'] == row_items['bx'] and box['by'] == row_items['by']:
self.session_data = self.session_data.drop(index)
break
widget_list.takeItem(q_list_index)
def delete_selections(self):
"""
Delete all checked items in all 3 right QWidgetList(s).
Return:
None
"""
checked_session_labels = self.get_list_selections(self.right_widgets['Session Labels'])
checked_image_labels = self.get_list_selections(self.right_widgets['Image Label List'])
checked_photos = self.get_list_selections(self.right_widgets['Photo List'])
self.delete_list_selections(checked_session_labels, self.right_widgets['Session Labels'])
self.delete_list_selections(checked_image_labels, self.right_widgets['Image Label List'])
self.delete_list_selections(checked_photos, self.right_widgets['Photo List'])
def upload_labels(self):
"""
Upload labels from csv or hdf.
Return:
None
"""
dialog = QFileDialog()
file_name, _ = dialog.getOpenFileName(self, 'Load labels')
self.label_file = file_name
new_data = self.read_session_data(file_name)
labels_to_add = new_data[['Object Name', 'Object Index']].drop_duplicates().sort_values(
by='Object Index').values
self.right_widgets['Session Labels'].clear()
for label, index in labels_to_add:
self.add_session_label(label)
self.session_data = pd.concat([self.session_data, new_data], ignore_index=True).drop_duplicates()
if file_name:
self.statusBar().showMessage(f'Labels loaded from {file_name}')
def reset_labels(self):
"""
Delete all labels in the current session_data.
Return:
None
"""
message = QMessageBox()
answer = message.question(
self, 'Question', 'Are you sure, do you want to delete all current session labels?')
if answer == message.Yes:
self.session_data.drop(self.session_data.index, inplace=True)
self.statusBar().showMessage(f'Session labels deleted successfully')
def display_settings(self):
pass
def display_help(self):
pass
def add_session_label(self, label=None):
"""
Add label entered to the session labels list.
Return:
None
"""
labels = self.right_widgets['Session Labels']
new_label = label or self.top_right_widgets['Add Label'][0].text()
session_labels = [str(labels.item(i).text()) for i in range(labels.count())]
if new_label and new_label not in session_labels:
self.add_to_list(new_label, labels)
self.top_right_widgets['Add Label'][0].clear()
def remove_temps(self):
"""
Remove temporary image files from working directories.
Return:
None
"""
working_dirs = set(['/'.join(item.split('/')[:-1]) for item in self.images])
for working_dir in working_dirs:
for file_name in os.listdir(working_dir):
if 'temp-' in file_name:
os.remove(f'{working_dir}/{file_name}')
def closeEvent(self, event):
"""
Save session data, clear cache, and close with or without saving.
Args:
event: QCloseEvent object.
Return:
None
"""
if not self.label_file and not self.session_data.empty:
message = QMessageBox()
answer = message.question(self, 'Question', 'Quit without saving?')
if answer == message.No:
self.save_changes_table()
if self.label_file and not self.session_data.empty:
self.save_changes_table()
self.remove_temps()
event.accept()
if __name__ == '__main__':
test = QApplication(sys.argv)
test_window = ImageLabeler()
sys.exit(test.exec_())
</code></pre>
<p><code>settings.py</code></p>
<pre><code>def setup_toolbar(qt_obj):
tools = {}
names = ['Upload photos', 'Upload Labels', 'Save', 'Save Yolo', 'Upload Photo Folder',
'Upload video', 'Edit Mode', 'Delete Selection(s)', 'Reset', 'Settings', 'Help']
icons = ['upload_photo6.png', 'labels.png', 'save3.png', 'yolo.png', 'upload_folder5.png', 'upload_vid3.png',
'draw_rectangle3.png', 'delete.png', 'reset4.png', 'settings.png', 'help.png']
methods = [qt_obj.upload_photos, qt_obj.upload_labels, qt_obj.save_changes_table, qt_obj.save_changes_yolo,
qt_obj.upload_folder, qt_obj.upload_vid, qt_obj.edit_mode, qt_obj.delete_selections,
qt_obj.reset_labels, qt_obj.display_settings, qt_obj.display_help]
keys = 'OLSYFVRDJAH'
tips = ['Select photos from a folder and add them to the photo list',
'Upload labels from csv, hdf',
'Save changes to csv or hdf',
'Save changes to txt files with Yolo format',
'Open a folder from the last saved point or open a new one containing '
'photos and add them to the photo list',
'Add a video and convert it to .png frames and add them to the photo list',
'Activate editor mode',
'Delete all selections(checked items)', 'Delete all labels in the current working folder',
'Display settings', 'Display help']
tips = [f'Press ⌘⇧{key}: ' + tip for key, tip in zip(keys, tips)]
key_shorts = [f'Ctrl+Shift+{key}' for key in keys]
check_status = [False, False, False, False, False, False, False, True, False, False, False, False]
assert len(names) == len(icons) == len(methods) == len(tips) == len(key_shorts)
for name, icon, method, tip, key, check in zip(names, icons, methods, tips, key_shorts, check_status):
tools[name] = [name, icon, method, tip, key, check]
return tools
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:52:52.237",
"Id": "467929",
"Score": "0",
"body": "@AlexV it doesn't really matter anyway, if you have any suggestions for improvement / questions / problems running the code, feel free to ask or maybe provide some feedback"
}
] |
[
{
"body": "<h1><code>setup_toolbar</code> from <code>settings.py</code></h1>\n\n<p>Maintaining a several lists in parallel is tedious. <code>setup_toolbar</code> has a minimal check with <code>assert len(names) == len(icons) == len(methods) == len(tips) == len(key_shorts)</code> to help here, but even if all the <code>list</code>s have the same length, there is no way to make sure that those values are really consistent.</p>\n\n<p>I'd propose to use something like the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def setup_toolbar(qt_obj):\n tools = {\n 'Upload photos': {\n 'icon': 'upload_photo6.png', \n 'callback': qt_obj.upload_photos, 'key': 'O',\n 'hint': 'Select photos from a folder and add them to the photo list',\n 'checkable': False\n },\n # and so on ...\n }\n\n # auto-generate shortcuts and rich hints\n for name, properties in tools.items():\n shortcut = f'Ctrl+Shift+{properties['key']}'\n properties['shortcut'] = shortcut\n # Mac symbols omitted out of lazyness ;-)\n properties['hint'] = f'Press {shortcut}: {properties[\"hint\"]}'\n # this /is redundant, but is in line with the original code\n properties['name'] = name\n\n return tools\n</code></pre>\n\n<p>This should be more robust, since all the relevant parts are closer together. Using a dict here is also more robust than a list because the properties can now be accessed using their names instead of having to remember to order in the list. Of course, <code>ImageLabeler.adjust_tool_bar</code> would have to be adapted to this change.</p>\n\n<p>More on a semantic note, maybe also replace <code>Upload</code> with <code>Load</code> or <code>Open</code>, since, at least in my opinion, \"upload\" is usually used when pushing some content onto a remote system or device. I guess that's not your intention.</p>\n\n<h1><code>labelpix.py</code></h1>\n\n<h2>Imports</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Imports should be sorted and grouped.</a> Also, avoid wildcard <code>*</code> <code>import</code>s, especially if you only need a single function like <code>setup_toolbar</code>. With these changes the code looks as follows:</p>\n\n<pre><code># built-in libraries\nimport os\nimport sys\n\n# third-party libraries\nimport cv2\nimport pandas as pd\nfrom PyQt5.QtCore import QPoint, QRect, Qt\nfrom PyQt5.QtGui import QIcon, QPainter, QPen, QPixmap\nfrom PyQt5.QtWidgets import (QAction, QApplication, QDesktopWidget,\n QDockWidget, QFileDialog, QFrame, QHBoxLayout,\n QLabel, QLineEdit, QListWidget, QListWidgetItem,\n QMainWindow, QMessageBox, QStatusBar, QVBoxLayout,\n QWidget)\n\n# libraries from this module\nfrom settings import setup_toolbar\n</code></pre>\n\n<p>The comments between the groups are only for educational purposes.</p>\n\n<h2>Path handling</h2>\n\n<p>The code handles paths at several points. Doing it \"manually\" like here in <code>foo</code></p>\n\n<blockquote>\n<pre><code>def get_image_names(self):\n \"\"\"\n Return:\n Directory of the current image and the image name.\n \"\"\"\n full_name = self.current_image.split('/')\n return '/'.join(full_name[:-1]), full_name[-1].replace('temp-', '')\n</code></pre>\n</blockquote>\n\n<p>is error-prone and won't work on Windows (and possibly other operating systems) where <code>/</code> is not used as path separator.</p>\n\n<p>Fortunately, Python can help here. The could should use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.split\" rel=\"nofollow noreferrer\"><code>os.path.split</code></a> or <a href=\"https://docs.python.org/3/library/os.path.html#os.path.dirname\" rel=\"nofollow noreferrer\"><code>os.path.dirname</code></a>/<a href=\"https://docs.python.org/3/library/os.path.html#os.path.basename\" rel=\"nofollow noreferrer\"><code>os.path.basename</code></a> from the built-in <code>os</code> module, or the <a href=\"https://docs.python.org/3/library/pathlib.html#module-pathlib\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> module, which provides a higher level, more OOP-like abstraction to the whole problem. Similarly building paths should use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\"><code>os.path.join</code></a> or the corresponding functionality from <code>pathlib</code>.</p>\n\n<h1>General feedback</h1>\n\n<p>I tried to use the program on some more or less random example images. Since the aspect ratio of the image display area is fixed to that of the window, images become squished once you resize the window or simply if they don't have the correct aspect ratio. There also seems to be a bug where the original image seems to persist in the background (see screenshot below).</p>\n\n<p><a href=\"https://i.stack.imgur.com/66wmO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/66wmO.png\" alt=\"screenshot of a demo image\"></a></p>\n\n<p>The image is similar to the one in a <a href=\"https://codereview.stackexchange.com/q/220863/\">question of mine</a> here on Code Review, so the circle on the left should really be a circle, not an ellipse.</p>\n\n<p>Sometimes also freshly drawn bounding boxes vanished immediately and where also not listed in the Image Label List on the right. I admit that I did not really try to look into this, so it might be a simple user error on my side.</p>\n\n<p>I'd also prefer to have a little bit more control over where the label files are stored, or at least have some indication where they were put.</p>\n\n<hr>\n\n<p>There is likely more to say about the code, but that's all for now. Maybe I will have another go at it later. Till then: Happy Coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T21:47:04.180",
"Id": "468006",
"Score": "0",
"body": "Thanks for the feedback, boxes usually vanish without adding coordinates to the image label list if no labels are selected in the upper list(session labels) which specifies the type of object. Regarding the bug, I'm aware of its presence but it only occurs if you delete all photos, I'll be working on fixing it. I'll take your mentioned points in consideration in my next follow up. Thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T14:58:21.517",
"Id": "468063",
"Score": "0",
"body": "Regarding the aspect ratio: if I set it to keep the ratio during resizes this would create dead zones that would count as valid coordinates even if the box is drawn over blank, which will lead to false results and i'm not sure how to handle it while keeping the aspect ratio."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:01:34.740",
"Id": "468064",
"Score": "0",
"body": "Try replacing all `Qt.IgnoreAspectRatio` with to `Qt.KeepAspectRatio` and draw boxes in blank space, they will count as valid boxes"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:43:58.630",
"Id": "238629",
"ParentId": "238604",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238629",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T04:50:06.390",
"Id": "238604",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"gui",
"pyqt"
],
"Title": "labelpix, image annotation tool for object detection GUI python"
}
|
238604
|
<p>It's an exercise, which I found on <a href="https://www.codewars.com/" rel="noreferrer">Codewars</a>.</p>
<p><strong>Instructions:</strong></p>
<p>Write a function which returns the count of distinct case-insensitive alphabetic characters and numeric digits which occur more then once in a given string. The given string can be assumed to contain only alphabets (lower-, uppercase) and numerics.</p>
<p>Examples: </p>
<ul>
<li><p>"abcde" results in 0, because no characters repeats more than once.</p></li>
<li><p>"aabbcde" results in 2, because of 'a' and 'b'.</p></li>
<li><p>"aabBcde" => 2, because 'a' occurs twice and 'b' occurs twice (b and B).</p></li>
<li><p>"indivisibility" => 1, because 'i' occurs six times.</p></li>
<li><p>"Indivisibilities" => 2, because 'i' seven times & 's' twice.</p></li>
<li><p>"aA11" => 2, because 'a' and '1'.</p></li>
<li><p>"ABBA" -> 2, because 'A' and 'B' each twice.</p></li>
</ul>
<p><strong>My (valid*) solution:</strong></p>
<pre><code>fun duplicateCount(text: String): Int {
var count = 0
var invalid = ArrayList<Char>()
var i = 0
while (i < text.length) {
if (invalid.contains(text[i].toLowerCase())) {
i++
continue
}
var j = i + 1
while (j < text.length) {
if (text[i].toLowerCase() == text[j].toLowerCase()) {
invalid.add(text[i].toLowerCase())
count++
break
}
j++
}
i++
}
return count
}
</code></pre>
<p>*It has passed the unit-tests.</p>
<p><strong>What are your thoughts about my implementation?</strong></p>
<p><strong>How could it be improved? What would you have done differently and why?</strong></p>
<p>Looking forward to reading your comments and answers.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:54:52.830",
"Id": "468055",
"Score": "1",
"body": "Use a HashSet, add every incoming character to the set but before you do, increment a counter if it's already there. No need to loop the string many times, just once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:33:50.960",
"Id": "468163",
"Score": "0",
"body": "@Gábor yup, that's roughly my answer."
}
] |
[
{
"body": "<p>Some little things. The count is already counted by ArrayList(), with the for() loop you can't miss/forget a i++ and with the <code>c</code> there is no need for another toLowerCase().</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n var invalid = ArrayList<Char>()\n\n for (i in 0 until text.length) {\n var c = text[i].toLowerCase()\n if (invalid.contains(c))\n continue\n\n for (j in i+1 until text.length) {\n if (c == text[j].toLowerCase()) {\n invalid.add(c)\n break\n }\n }\n }\n\n return invalid.size;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:19:15.617",
"Id": "467933",
"Score": "2",
"body": "I think you are confusing your languages. Those aren't valid Kotlin `for` loops and `size` isn't a method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T10:47:28.087",
"Id": "467945",
"Score": "2",
"body": "The for-loop can be easily fixed by using `for (i in 0 until text.size)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T10:50:08.573",
"Id": "467947",
"Score": "2",
"body": "And instead of calling ArrayList constructor, use `var invalid = mutableListOf<Char>()`. And it should be a `Set` instead, so `mutableSetOf` would be even better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T14:29:35.293",
"Id": "468057",
"Score": "1",
"body": "@Holger, `ArrayList` is only available on Kotlin-Java and Kotlin-js, while `mutableListOf` is available in common-Kotlin (every Kotlin version). Also, you don't change the reference of your variables. Therefor, you should use `val` instead of `var`. Also, you could use `c in invalid` instead of `invalid.contains(c)`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T08:12:13.590",
"Id": "238608",
"ParentId": "238607",
"Score": "7"
}
},
{
"body": "<p>A more straight forward solution would be to count each character and then to count the characters that have a count larger than 1. This can easily be done using the functional methods available in Kotlin's standard library:</p>\n\n<pre><code>fun duplicateCount(text: String): Int =\n text.toLowerCase()\n .groupingBy { it }.eachCount()\n .count { it.value > 1 }\n</code></pre>\n\n<p><code>.groupingBy { it }.eachCount()</code> creates a map (<code>Map<Char, Int></code>) that assigns each character in the string to its count.</p>\n\n<p><code>.count { it.value > 1 }</code> then counts all entries in the map where the count is more than one.</p>\n\n<hr>\n\n<p>EDIT: Inspired by @SimonForsberg here in comparision a procedural implementation of the same algorithm. I also modified the version above to use the better <code>count(predicate)</code> method, which I originally forgot about.</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n val lcText = text.toLowerCase()\n val characterCount = mutableMapOf<Char, Int>()\n\n for (i in 0 until lcText.length) {\n val char = lcText[i]\n characterCount.put(char, 1 + characterCount.getOrDefault(char, 0))\n }\n\n var count = 0\n\n for (entry in characterCount) {\n if (entry.value > 1) {\n count++\n }\n }\n\n return count\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T10:48:47.120",
"Id": "467946",
"Score": "2",
"body": "While it's true that Kotlin's standard library provides a bunch of methods for this, I assume that the code is written as a learning exercise and probably avoids these on purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:05:52.783",
"Id": "467949",
"Score": "2",
"body": "@SimonForsberg I do agree, but its sometimes difficult to say what exactly should be avoided. I considered also showing my algorithm in a procedural style, but I thought is was also worth showing a more Kotlin-like style"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:56:36.863",
"Id": "238614",
"ParentId": "238607",
"Score": "12"
}
},
{
"body": "<ol>\n<li><p>lowerCase and uppercase should be treated te same? Let's make them the same:</p>\n\n<pre><code>val lowerText = text.toLowerCase()\n</code></pre></li>\n<li><p>Check for duplicates? A set doesn't allow duplicates.<br>\nAlso, <code>add</code> returns a <code>Boolean</code> which tells if the value is added.<br>\nThis means we can get a list off all the unique values by checking if we can add it to a set:</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n val lowerText = text.toLowerCase()\n val invalid = mutableSetOf<Char>()\n\n val chars = lowerText.filter{ invalid.add(it) }\n return chars.length\n}\n</code></pre></li>\n<li><p>But we needed the duplicates...<br>\nWell, this means that we need to get the items that already were in our set.<br>\nAs we can only add items to our set once, the duplicates are the items where we cannot add it (because they are already added):</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n val lowerText = text.toLowerCase()\n val invalid = mutableSetOf<Char>()\n\n val chars = lowerText.filterNot{ invalid.add(it) }\n return chars.length\n}\n</code></pre></li>\n<li><p>What happens if we come come across a character three times: </p>\n\n<ol>\n<li>it can be added -> add returns true -> we ignore it</li>\n<li>it can't be added -> add returns false -> we add it to <code>chars</code>.</li>\n<li>it can't be added -> add returns false -> we add it to <code>chars</code> again.</li>\n</ol>\n\n<p>but, I guess we can change the list into a collections that doesn't allow duplicates :-)</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n val lowerText = text.toLowerCase()\n val invalid = mutableSetOf<Char>()\n\n val chars = lowerText\n .filterNot{ invalid.add(it) }\n .toSet()\n return chars.length\n}\n</code></pre></li>\n</ol>\n\n<p>or without redundant params:</p>\n\n<pre><code> fun duplicateCount(text: String): Int {\n val invalid = mutableSetOf<Char>()\n\n return text\n .toLowerCase()\n .filterNot{ invalid.add(it) }\n .toSet()\n .length\n }\n</code></pre>\n\n<p>5*. We can optimize it a bit by adding it immediately to a Set.<br>\n We can do this by calling <code>filterNotTo</code> instead of <code>filterNot</code>.<br>\n We need to get the <code>filterNotTo</code> for classes with an <a href=\"https://kotlinlang.org/docs/reference/iterators.html\" rel=\"noreferrer\">iterator</a> (which implements Iterable), but String doesn't have this.<br>\nFortunately, <code>String</code> has a function <code>asIterable</code> which returns an <code>Iterable</code> for the <code>String</code>.</p>\n\n<p>When we combine this we get:</p>\n\n<pre><code>fun duplicateCount(text: String): Int {\n val invalid = mutableSetOf<Char>()\n return text\n .toLowerCase()\n .asIterable()\n .filterNotTo(mutableSetOf()){\n invalid.add(it.toLowerCase())\n }.size\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T11:12:46.540",
"Id": "238617",
"ParentId": "238607",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "238608",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T07:52:50.463",
"Id": "238607",
"Score": "7",
"Tags": [
"beginner",
"kotlin"
],
"Title": "Count the number of duplicated chars in a string"
}
|
238607
|
<p>I'm working on a project the scenario: teacher model then is the teacher has not a profile the institute which working at will upload the courses does this is written the way I have tried in the course model?</p>
<pre><code>class Course(models.Model):
course_name = models.CharField(max_length=20)
student = models.ManyToMany(Student)
institute_name = models.ForeignKey(Institute,on_delete=models.CASCADE , null=True,blank=True)
teacher_name = models.ForeignKey(Teacher ,on_delete=models.CASCADE,blank=True,null=True)
tags = models.ManyToManyField(Category,on_delete=models.CASCADE)
time = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
</code></pre>
<p>Then define:</p>
<pre><code>if user loggedin in user.is_institute
</code></pre>
<p>So querying in an institute like this:</p>
<pre><code>if loggedin in user.is_teacher
</code></pre>
<p>And then will work on the teacher model. Does this structure fine?</p>
<p>I've heard <code>generic foreign keys</code> but I'm not sure if it working with API!?</p>
<pre><code>from django.contrib.contenttypes.models import ContentType
Teacher, Institute have different fields name
</code></pre>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T12:59:38.973",
"Id": "468048",
"Score": "3",
"body": "Hi. I'm familiar with Django and would love to help here, but I don't quite understand the question. Could you make the following changes? Anything in code blocks should be valid Python Code, so we're sure what your code is and what is part of your question. (For example, ``if user loggedin in user.is_institute`` is not valid code, both the syntax is broken and ``is_institute`` is never defined.) Also, if possible, please make the English clearer or get a friend to help you edit this question, I'm having a hard time understanding what you're trying to do and where you are struggling. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T09:14:45.260",
"Id": "238612",
"Score": "1",
"Tags": [
"python",
"api",
"django"
],
"Title": "two foreign keys in one django model"
}
|
238612
|
<p>The goal is to upload the columns from the csv into the SQL Pro database. I am able to select the column names that have been uploaded from the csv file, the columns from the csv file are then uploaded into the option dropdown. In return I need to submit the selections that have been selected from the options dropdown, into the database. I am writing this in PHP. What I have is definitely not correct.</p>
<p><strong>PHP</strong> </p>
<pre><code>public function csvProcess(Request $request)
{
$contact = newContact();
$contact->first_name = $rowProperties[$mapping['column_first_name']];
$contact->last_name = $rowProperties[$mapping['column_last_name']];
//$contact->newContact()->attach($first_name[$mapping['column_first_name']]);
store(newContact()->where->$columnNames=$firstrow());
$result = create($this(newContact()));
$contact->save();
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><h1 class="mb-7 m-5 ml-6 font-bold text-2xl"> Contact Fields</h1>
<div v-for="field in requiredContactFields" class="p-8 -mr-6 -mb-8 flex flex-wrap" style="width:150px">
<label :for="field" type="select" name="field">{{field}}</label>
<select :id="field" :name="field" v-model="mapping[field]"required>
<option value="">Please Select</option>
<option v-for="columnName in columnNames" :name="columnName" :value="columnName" value="">{{columnName}}</option>
</select>
</div>
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code> submitFiles()
{
//Form validation that will not allow a user to submit the form by upon the @click event
if(!this.$refs.csvFile.checkValidity())
{
return null;
}
let formData = new FormData();
formData.append('file', this.file);
axios.post('http://localhost:8080/api/contacts/upload-csv',
formData,
{
headers:
{
'Content-Type': 'multipart/form-data'
}
}
)
.then(function(response){
console.log('SUCCESS!!');
console.log(response);
})
.catch(function(response){
console.log('FAILURE!!');
console.log(response);
})
}
}
}
</script>
</code></pre>
|
[] |
[
{
"body": "<p><strong>I defined the fields that I wanted to be required first. Then, I defined a One-to-Many relationship between an account table and a contacts table where the <em>contact id</em> is the account's name in the account's table in the SQL database</strong></p>\n\n<pre><code> $account = new Account();\n $mapping = $request->$mapping;\n $account->name = $rowProperties[$mapping['account_name']];\n\n //One-To-Many Eloquent Relationship that links a table of Account Names in the Account's \n //table to contact Account_ID's in the Contact tables \n //$contact->id = $account->id;\n\n $account->save();\n\n $contact = new Contact();\n $contact->id = $account->id;\n $contact->contact_id = $rowProperties[$mapping['contact_account_name']];\n $contact->first_name = $rowProperties[$mapping['contact_first_name']];\n $contact->last_name = $rowProperties[$mapping['contact_last_name']]; \n</code></pre>\n\n<pre><code> account = new Account();\n $account->name = $rowProperties[$mapping['account_name']];\n $this->account->hasMany('contact_account_names');\n //$accountid->contact_account_name\n $account->save();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T21:00:00.120",
"Id": "468095",
"Score": "4",
"body": "Welcome to Code Review! Please use the _edit_ link below your question to add more information. You [can answer your own question but bear in mind that it needs to be reviewing the code](https://codereview.stackexchange.com/help/self-answer), not adding more information."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T20:15:14.293",
"Id": "238688",
"ParentId": "238626",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:21:06.117",
"Id": "238626",
"Score": "0",
"Tags": [
"sql",
"csv",
"database",
"php5",
"laravel"
],
"Title": "PHP - Importing columns from uploaded CSV file to SQL database (Laravel 5.7)"
}
|
238626
|
<p>I have the following method that only checks if a Sqlite database has data, but I don't like how the code looks</p>
<pre><code> private void comprobarColorActual() {
try {
if (cantidadRegistrosBodega() > 1) {
colorBodega.setBackgroundColor(Color.parseColor("#D5F5E3"));
}
if (cantidaRegistrosMaestro() > 1) {
colorMaestro.setBackgroundColor(Color.parseColor("#D5F5E3"));
}
if (cantidaRegistrosProductos() > 1) {
colorProducto.setBackgroundColor(Color.parseColor("#D5F5E3"));
}
} catch (NumberFormatException e) {
Log.i("NumberFormatException", e.toString());
} catch (RuntimeException e) {
Log.i("RuntimeException", e.toString());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T16:43:43.023",
"Id": "467992",
"Score": "2",
"body": "Hello, in my opinion, you should add more details of what the code does, and since the code is not compiling, it's really hard to do a proper code review."
}
] |
[
{
"body": "<p>Use <code>else if</code>, whenever applicable. I don't understand the names can't say for certain if these conditions are exclusive.</p>\n\n<p>Ensure you method name is meaningful. <code>colorActual</code> in english is not really meaningful.</p>\n\n<p>Use a wrapper for all your Logging, it will help if you move environments and need to change how you make your LOG statements.</p>\n\n<p><code>Log.i</code> usually means 'info', <code>Log.e</code> would be for errors. If you don't want to handle these errors (and it looks like they shouldn't occur), add a <code>throws</code> statement instead.</p>\n\n<p>Avoid magic numbers & magic strings, instead declare static final variables at the top of the class, or use a properties file.</p>\n\n<p>Example refactored code:</p>\n\n<pre><code>private static final String BACKGROUND_COLOR = \"#D5F5E3\";\n\nprivate void comprobarColorActual() throws NumberFormatException {\n private String backgroundColor;\n\n if (cantidadRegistrosBodega() > 1) {\n colorBodega.setBackgroundColor(Color.parseColor(BACKGROUND_COLOR));\n } else if (cantidaRegistrosMaestro() > 1) {\n colorMaestro.setBackgroundColor(Color.parseColor(BACKGROUND_COLOR));\n } else if (cantidaRegistrosProductos() > 1) {\n colorProducto.setBackgroundColor(Color.parseColor(BACKGROUND_COLOR));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T16:13:42.653",
"Id": "238633",
"ParentId": "238627",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238633",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:23:38.037",
"Id": "238627",
"Score": "-2",
"Tags": [
"java",
"android"
],
"Title": "Set backgroud color based around database call"
}
|
238627
|
<p>Recently discovered <a href="https://pypi.org/project/PyQt5/" rel="nofollow noreferrer">PyQt5</a> and decided to make this as a 'hello world' for GUIs</p>
<p>Would like input on the design, best practices, as well as idiomatic nature of the application and its structure.</p>
<p><strong>Game.py</strong></p>
<pre><code>import collections
from PyQt5.QtWidgets import QMainWindow, QGridLayout, QPushButton, QDialog, QLabel, QLineEdit, QWidget, QAction, QDesktopWidget
# TODO-P: Maybe add color for symbol. Alt: Use stylesheets.
Player = collections.namedtuple('Player', ['name', 'symbol'])
class TicTacToe(QMainWindow):
def __init__(self):
super().__init__()
self.xPlayer = Player('X Player', 'X')
self.oPlayer = Player('O Player', 'O')
self.currentPlayer = self.xPlayer
self.turnIndicator = f"{self.currentPlayer.name}'s Turn"
self.initUI()
def initUI(self):
self.board = TicTacToeBoard(self)
self.setCentralWidget(self.board)
self.initElements()
self.setWindowTitle('Tic Tac Toe')
self.resize(1200, 1200)
self.center()
self.show()
def initElements(self):
self.initStatusBar()
self.initMenu()
def initStatusBar(self):
self.statusBar = self.statusBar()
self.statusBar.showMessage(self.turnIndicator)
def initMenu(self):
gameMenu = self.menuBar().addMenu('Game')
gameMenu.addAction(self.resetAction())
settingsMenu = self.menuBar().addMenu('Settings')
settingsMenu.addAction(self.setNameAction())
settingsMenu.addAction(self.turnIndicatorToggle())
def resetAction(self):
action = QAction('Reset', self)
action.setShortcut('Ctrl+R')
action.setToolTip('Reset Game')
action.triggered.connect(self.reset)
return action
def reset(self):
self.board.reset()
self.currentPlayer = self.xPlayer
self.updateIndicator()
def updateIndicator(self):
# TODO-Q: Does PyQt have parameter binding? Can I also use signals / slots to 'auto-update' variables / displayed text?
self.turnIndicator = f"{self.currentPlayer.name}'s Turn"
self.statusBar.showMessage(self.turnIndicator)
def setNameAction(self):
action = QAction('Set Name(s)', self)
action.setShortcut('Ctrl+A')
action.setStatusTip('Set Player Name(s)')
action.triggered.connect(self.setNameDialog)
return action
def setNameDialog(self):
dialog = QDialog(self)
dialog.setWindowTitle('Set Player Name(s)')
dialog.resize(600, 200)
layout = QGridLayout()
xText = QLineEdit()
oText = QLineEdit()
layout.addWidget(QLabel(f'<b>{self.xPlayer.name}:</b>'), 0, 0)
layout.addWidget(xText, 0, 1)
layout.addWidget(QLabel(f'<b>{self.oPlayer.name}:</b>'), 1, 0)
layout.addWidget(oText, 1, 1)
dialog.setLayout(layout)
enterButton = QPushButton('Enter')
enterButton.clicked.connect(lambda: self.setName(xText.text(), oText.text()))
enterButton.clicked.connect(dialog.accept)
layout.addWidget(enterButton, 2, 0)
dialog.exec_()
def setName(self, xName, oName):
if xName:
self.xPlayer = self.xPlayer._replace(name=xName)
if oName:
self.oPlayer = self.oPlayer._replace(name=oName)
self.currentPlayer = self.xPlayer if self.currentPlayer is self.xPlayer else self.oPlayer
self.updateIndicator()
def buttonClicked(self):
button = self.sender()
button.capture(self.currentPlayer.symbol)
self.togglePlayer()
def togglePlayer(self):
self.currentPlayer = self.oPlayer if self.currentPlayer is self.xPlayer else self.xPlayer
self.updateIndicator()
def turnIndicatorToggle(self):
action = QAction('Turn Indicator', self, checkable=True)
action.setShortcut('Ctrl+T')
action.setChecked(True)
action.setStatusTip('Toggle Status Indicator')
action.triggered.connect(self.toggleTurnIndicator)
return action
def toggleTurnIndicator(self, state):
if state:
self.statusBar.show()
self.statusBar.showMessage(self.turnIndicator)
else:
self.statusBar.hide()
def showVictory(self):
winner = self.oPlayer if self.currentPlayer is self.xPlayer else self.xPlayer
self.statusBar.showMessage(f'{winner.name} wins!')
def center(self):
qr = self.frameGeometry()
qr.moveCenter(QDesktopWidget().availableGeometry().center())
self.move(qr.topLeft())
class TicTacToeBoard(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.game = parent
layout = QGridLayout()
self.setLayout(layout)
# TODO-Q: How to implement __mul__ so this works -> [TicTacToeCell(self) * 3] * 3
self.grid = [[TicTacToeCell(self), TicTacToeCell(self), TicTacToeCell(self)], [TicTacToeCell(self), TicTacToeCell(self), TicTacToeCell(self)], [TicTacToeCell(self), TicTacToeCell(self), TicTacToeCell(self)]]
positions = [(i, j) for i in range(3) for j in range(3)]
for position in positions:
x, y = position
button = self.grid[x][y]
button.clicked.connect(parent.buttonClicked)
button.clicked.connect(self.evaluateBoard)
layout.addWidget(button, *position)
def reset(self):
for row in self.grid:
for cell in row:
cell.reset()
def disable(self):
for row in self.grid:
for cell in row:
cell.setEnabled(False)
def evaluateBoard(self):
self.evaluateCells(self.grid[0][0], self.grid[1][1], self.grid[2][2])
self.evaluateCells(self.grid[0][2], self.grid[1][1], self.grid[2][0])
for i in range(3):
self.evaluateCells(self.grid[i][0], self.grid[i][1], self.grid[i][2])
self.evaluateCells(self.grid[0][i], self.grid[1][i], self.grid[2][i])
def evaluateCells(self, a, b, c):
if a.captured() and a.text is b.text is c.text:
self.disable()
self.game.showVictory()
class TicTacToeCell(QPushButton):
def __init__(self, parent):
super().__init__(parent)
self.setMinimumSize(400, 400)
self.text = ''
def captured(self):
return self.text
def capture(self, symbol):
self.text = symbol
self.setText(symbol)
self.setEnabled(False)
def reset(self):
self.text = ''
self.setText(self.text)
self.setEnabled(True)
def __repr__(self):
return f'[{self.text}]'
</code></pre>
<p><strong>App.py</strong></p>
<pre><code>import sys
from PyQt5.QtWidgets import QApplication
from Game import TicTacToe
if __name__ == '__main__':
app = QApplication(sys.argv)
tictactoe = TicTacToe()
sys.exit(app.exec_())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T09:20:15.690",
"Id": "468034",
"Score": "2",
"body": "Looks good. You don't need to construct `TicTacToeCell` widgets with a parent because adding them to the layout sets the parent automatically. Doing so actually places them on the parent widget at coordinates (0, 0), until the layout repositions them. The `TicTacToeCell` constructor can be changed to `def __init__(self, parent=None)` and you can do this `self.grid = [[TicTacToeCell() for i in range(3)] for j in range(3)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:39:49.750",
"Id": "468054",
"Score": "1",
"body": "@alec The \"add an answer\" button is just a little lower than the \"add comment\" button. Comments should be used to ask clarifying questions, not to give review feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T21:22:40.080",
"Id": "468101",
"Score": "0",
"body": "Oh ok, but it wasn't a complete answer addressing all the questions so I thought I should comment it."
}
] |
[
{
"body": "<p>The code generally looks good, but is a little rough to read (in part due to length but also with method names like <code>turnIndicatorToggle(self)</code> and <code>toggleTurnIndicator(self)</code>). But when I try to run your program I run into a few issues; your main window is fairly huge (bigger than my screen!) and can't be resized, and your indicators for tics and tacs (x and o) don't appear after the first. I think there's also supposed to be text somewhere but I can't see it (which may be because the window is too big).</p>\n\n<p>Since you're asking for Qt advice, I think that you should look at decorators for your slots; it increases both readability and performance. And since you ask for best practices, you should get used to snake_case instead of camelCase for your variables and functions, and lower case names for your files, and it would also be nice with type hinting and some docstrings as well as some additional whitespace in your functions. You may also want to consider separating the \"back-end\" of the game and putting that functionality in its own class.</p>\n\n<p>Finally, I'll add some minor practical tips:</p>\n\n<ul>\n<li>you could simplify lines 136–137 to <code>for x, y in positions</code> (and you could have a tuple of tuples instead of a list of tuples) <em>(don't use memory you don't need to use.)</em></li>\n<li>You can simplify it even more with <code>for x, y in itertools.product(range(3), range(3)):</code> <em>(if there's a function that can do what you want to do, use it.)</em></li>\n<li>your <code>capture</code> and <code>reset</code> functions in <code>TicTacToeCell</code> can merged with a default argument: <code>def capture(self, symbol=''):</code> <em>(look for repetition)</em></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T18:49:32.950",
"Id": "239153",
"ParentId": "238631",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239153",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T15:50:40.457",
"Id": "238631",
"Score": "7",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe",
"pyqt"
],
"Title": "Pyqt Tic Tac Toe"
}
|
238631
|
<p>I am a young computer science student programming mainly in Java.</p>
<p>I wrote a simple RESTful web service using Spring Boot Framework and the DDD architecture pattern. The project is a library management system that allows users to browse, book and borrow books.</p>
<p>I was wondering if I could get feedback from more experienced programmers about my code in general.</p>
<p>Here is the entire project repository: <a href="https://github.com/eziomou/library-backend" rel="nofollow noreferrer">Project repository</a></p>
<pre><code>@NamedEntityGraph(
name = "book-entity-graph",
attributeNodes = {
@NamedAttributeNode(value = "author"),
@NamedAttributeNode(value = "genre"),
@NamedAttributeNode(value = "publisher")
}
)
@AggregateRoot
@Entity
public class Book extends BaseEntity {
@Column(nullable = false)
private String title;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Author author;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Genre genre;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Publisher publisher;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private LocalDate publicationDate;
private boolean loaned;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "book")
@OrderColumn(name = "index")
private List<Reservation> reservations;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "book")
private List<Loan> loans;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "book")
private List<Rating> ratings;
private double averageRating = 0.; // Additional field to increase performance
protected Book() {
reservations = new ArrayList<>();
loans = new ArrayList<>();
ratings = new ArrayList<>();
}
public Book(String title, Author author, Genre genre, Publisher publisher, String description,
LocalDate publicationDate) {
this();
setTitle(title);
setAuthor(author);
setGenre(genre);
setPublisher(publisher);
setDescription(description);
setPublicationDate(publicationDate);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = Objects.requireNonNull(title);
}
public Author getAuthor() {
return author;
}
private void setAuthor(Author author) {
this.author = Objects.requireNonNull(author);
if (!author.getBooks().contains(this)) {
author.addBook(this);
}
}
public void changeAuthor(Author author) {
Objects.requireNonNull(author);
this.author.removeBook(this);
setAuthor(author);
}
public Genre getGenre() {
return genre;
}
private void setGenre(Genre genre) {
this.genre = Objects.requireNonNull(genre);
if (!genre.getBooks().contains(this)) {
genre.addBook(this);
}
}
public void changeGenre(Genre genre) {
Objects.requireNonNull(genre);
this.genre.removeBook(this);
setGenre(genre);
}
public Publisher getPublisher() {
return publisher;
}
private void setPublisher(Publisher publisher) {
this.publisher = Objects.requireNonNull(publisher);
if (!publisher.getBooks().contains(this)) {
publisher.addBook(this);
}
}
public void changePublisher(Publisher publisher) {
Objects.requireNonNull(publisher);
this.publisher.removeBook(this);
setPublisher(publisher);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = Objects.requireNonNull(description);
}
public LocalDate getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(LocalDate publicationDate) {
this.publicationDate = Objects.requireNonNull(publicationDate);
}
public boolean isLoaned() {
return loaned;
}
public void setLoaned(boolean loaned) {
this.loaned = loaned;
}
public List<Reservation> getReservations() {
return Collections.unmodifiableList(reservations);
}
public List<Reservation> getReservations(Reservation.Status status) {
return reservations.stream()
.filter(r -> r.getStatus() == status)
.collect(Collectors.toUnmodifiableList());
}
public void addReservation(Reservation reservation) {
Objects.requireNonNull(reservation);
if (!reservation.getBook().equals(this)) {
throw new IllegalStateException("The reservation has a different book");
}
reservations.add(reservation);
}
public List<Loan> getLoans() {
return Collections.unmodifiableList(loans);
}
public void addLoan(Loan loan) {
Objects.requireNonNull(loan);
if (!loan.getBook().equals(this)) {
throw new IllegalArgumentException("The loan has a different book");
}
loans.add(loan);
}
public List<Rating> getRatings() {
return Collections.unmodifiableList(ratings);
}
public void addRating(Rating rating) {
Objects.requireNonNull(rating);
if (!rating.getBook().equals(this)) {
throw new IllegalArgumentException("The rating has a different book");
}
averageRating = (averageRating * ratings.size() + rating.getValue()) / (ratings.size() + 1);
ratings.add(rating);
}
public void removeRating(Rating rating) {
if (!ratings.contains(rating)) {
throw new IllegalArgumentException("The book doesn't contain this rating");
}
if (ratings.size() > 1) {
averageRating = (averageRating * ratings.size() - rating.getValue()) / (ratings.size() - 1);
} else {
averageRating = 0.;
}
ratings.remove(rating);
}
public double getAverageRating() {
return averageRating;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T13:33:05.070",
"Id": "468052",
"Score": "0",
"body": "Welcome to Code Review. I have a question: a `Book` instance is a physical copy of one book present in the library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:48:43.273",
"Id": "468069",
"Score": "0",
"body": "@dariosicily Yes. To simplify the model, each book has only one copy."
}
] |
[
{
"body": "<p>I checked your code from project repository and one feedback from my end -</p>\n\n<p>Use proper HTTP response codes as mentioned <a href=\"https://restfulapi.net/http-methods/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You have used <code>200</code> for POST which can be <code>201 (CREATED)</code></p>\n\n<p>and <code>201</code> for DELETE requests which can be <code>200 (OK)</code> or <code>202 (Not Accepted)</code> or <code>204 (No Content)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T00:45:14.540",
"Id": "473550",
"Score": "0",
"body": "Only code included in the question should be reviewed. Links to more code can sometimes be useful but the code in them should not be reviewed (one reason is that the link can break or the code there can change)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T00:46:25.033",
"Id": "473551",
"Score": "0",
"body": "Oh.. Thanks for head up "
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T23:47:18.667",
"Id": "241329",
"ParentId": "238634",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T17:05:20.160",
"Id": "238634",
"Score": "2",
"Tags": [
"java",
"rest",
"spring",
"ddd"
],
"Title": "Simple REST web service"
}
|
238634
|
<p>Below is an implementation of <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshtein Distance</a> algorithm.</p>
<p>I am trying to use modern C++ features as much as I can, i.e. auto, no pointer / raw memory but I feel like it is a constant struggle.</p>
<p>Code:</p>
<pre><code>#include <string_view>
#include <memory>
#include <vector>
namespace utils
{
auto getLevenshteinDistance(std::string_view string_1, std::string_view string_2)
{
const auto size_1{ string_1.size() };
const auto size_2{ string_2.size() };
if (size_1 == 0) return size_2;
if (size_2 == 0) return size_1;
std::vector<std::size_t> costs(size_2);
for (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;
std::size_t i{ 0 };
for (const auto& itr_1 : string_1)
{
++i;
costs[0] = i + 1;
auto corner{ i };
std::size_t j{ 0 };
for (const auto& itr_2 : string_2)
{
++j;
auto upper{ costs[j + 1] };
if (itr_1 == itr_2)
{
costs[j + 1] = corner;
}
else
{
auto t{ upper < corner ? upper : corner };
costs[j + 1] = (costs[j] < t ? costs[j] : t) + 1;
}
corner = upper;
}
}
return costs[size_2];
}
}
</code></pre>
<p>For instance, I can't use <code>auto</code> when declaring my vector, because there is no <code>std::make_vector</code> (like <code>make_tuple</code> for instance).</p>
<p>Also I'm developing anxiety for implicit conversions; for instance I could have written</p>
<pre><code>auto i{ 0 };
</code></pre>
<p>instead of </p>
<pre><code>std::size_t i{ 0 };
</code></pre>
<p>But given that the value will be put into an array containing type <code>std::size_t</code>, I'd rather just have it be of the right type immediately. Lots of stuff like that is bothering me.</p>
<p>Even looping through the array by <code>const auto&</code> seems weird when I'm still having a count variable.. Doesn't advantage disappear, and I might as well just <code>for (int i = 0; ..)</code></p>
<p>Any suggestions for improvements in the way of modern, good practice, and performance is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T22:57:23.543",
"Id": "468009",
"Score": "4",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T01:12:28.953",
"Id": "468013",
"Score": "1",
"body": "Are you somehow obsessed with the “almost always auto” style? I mean, auto is handy when you want the type to be deduced, but I don’t think you need to change `std::size_t i = 0;` to `auto i = std::size_t{0};`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T01:27:48.303",
"Id": "468015",
"Score": "1",
"body": "You're accessing out of bounds for several of your array references: `costs[k] = k;`, `costs[j + 1]`."
}
] |
[
{
"body": "<h1>Invalid access</h1>\n\n<p>There are several occurrences of out-of-range access as <a href=\"https://codereview.stackexchange.com/questions/238641/an-implementation-of-levenshtein-distance-algorithm-in-modern-c#comment468015_238641\">1201ProgramAlarm's comment</a> pointed out:</p>\n\n<blockquote>\n<pre><code>for (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;\n</code></pre>\n \n \n\n<pre><code>costs[j + 1]\n</code></pre>\n \n \n\n<pre><code>return costs[size_2];\n</code></pre>\n</blockquote>\n\n<p>This problem can be fixed by increasing the size of <code>costs</code> by one.</p>\n\n<h1>Usage of the standard library</h1>\n\n<blockquote>\n<pre><code>std::vector<std::size_t> costs(size_2);\nfor (std::size_t k{ 0 }; k <= size_2; ++k) costs[k] = k;\n</code></pre>\n</blockquote>\n\n<p>Use <code>std::iota</code>:</p>\n\n<pre><code>std::vector<std::size_t> costs(size_2 + 1);\nstd::iota(costs.begin(), costs.end(), std::size_t{0}); // or 0_zu; see below\n</code></pre>\n\n<blockquote>\n<pre><code>auto t{ upper < corner ? upper : corner };\ncosts[j + 1] = (costs[j] < t ? costs[j] : t) + 1;\n</code></pre>\n</blockquote>\n\n<p>Use <code>std::min</code>:</p>\n\n<pre><code>costs[j + 1] = std::min({upper, corner, costs[j]}) + 1;\n</code></pre>\n\n<h1><code>auto</code></h1>\n\n<p>When you want the type of a variable to be deduced, <code>auto</code> is handy, because you don't have to write the type or expression twice. When you want the type of a variable to be fixed, however, <code>auto</code> becomes cumbersome — so feel free to write</p>\n\n<pre><code>std::size_t i = 0;\n</code></pre>\n\n<p>An alternative is to use a user-defined literal: (there's a proposal <a href=\"https://wg21.link/p0330\" rel=\"nofollow noreferrer\">P0330 Literal Suffix for (signed) <code>size_t</code></a> to add builtin literals for <code>std::size_t</code>)</p>\n\n<pre><code>namespace util_literals {\n constexpr std::size_t operator\"\"_zu(unsigned long long number)\n {\n return static_cast<std::size_t>(number);\n }\n}\n</code></pre>\n\n<p>So you can write:</p>\n\n<pre><code>using namespace util_literals;\nauto i = 0_zu;\n</code></pre>\n\n<p>Also, instead of</p>\n\n<blockquote>\n<pre><code>for (const auto& itr_1 : string_1)\n</code></pre>\n</blockquote>\n\n<p>it is more common to access characters by value. Also, <code>itr</code> is a misleading name for characters:</p>\n\n<pre><code>for (char c_1 : string_1)\n</code></pre>\n\n<h1>Simplification</h1>\n\n<p>This check is redundant:</p>\n\n<blockquote>\n<pre><code>if (size_1 == 0) return size_2;\nif (size_2 == 0) return size_1;\n</code></pre>\n</blockquote>\n\n<p>because the algorithm works well with empty strings.</p>\n\n<hr>\n\n<p>Here's my version:</p>\n\n<pre><code>#include <algorithm>\n#include <cstddef>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <string_view>\n#include <vector>\n\nstd::size_t Levenshtein_distance(std::string_view string_a, std::string_view string_b)\n{\n const auto size_a = string_a.size();\n const auto size_b = string_b.size();\n\n std::vector<std::size_t> distances(size_b + 1);\n std::iota(distances.begin(), distances.end(), std::size_t{0});\n\n for (std::size_t i = 0; i < size_a; ++i) {\n std::size_t previous_distance = 0;\n for (std::size_t j = 0; j < size_b; ++j) {\n distances[j + 1] = std::min({\n std::exchange(previous_distance, distances[j + 1]) + (string_a[i] == string_b[j] ? 0 : 1),\n distances[j] + 1,\n distances[j + 1] + 1\n });\n }\n }\n return distances[size_b];\n}\n\nint main()\n{\n std::string string_a;\n std::string string_b;\n while (std::cin >> std::quoted(string_a) >> std::quoted(string_b)) {\n std::cout << Levenshtein_distance(string_a, string_b) << '\\n';\n }\n}\n</code></pre>\n\n<p>Input:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>kitten sitting\ncorporate cooperation\n123 \"\"\n\"\" \"\"\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>3\n5\n0\n0\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/0ZValXTB8RPkFAYS\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T02:58:33.473",
"Id": "238646",
"ParentId": "238641",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238646",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T22:53:11.600",
"Id": "238641",
"Score": "2",
"Tags": [
"c++",
"performance",
"algorithm",
"edit-distance"
],
"Title": "An implementation of Levenshtein Distance algorithm in modern C++"
}
|
238641
|
<p>I am developing (for fun) a Utilities & Logging library </p>
<p>Can someone please help me to improve:
<a href="https://github.com/quano1/util" rel="nofollow noreferrer">Github link</a></p>
<p><strong>Pros</strong></p>
<ul>
<li>Thread-safe, no mutex. Use lock-free ring buffer (the idea is inherited from FreeBSD lock-free queue: extremely reliable and fast)</li>
<li>Support multiple file descriptors</li>
<li>Only 2 or 1 header files</li>
<li><em>printf</em> style (user-defined log format)</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>Please help to figure-out</li>
</ul>
<p>logger.h</p>
<pre><code>#pragma once
#include <fstream>
#include <vector>
#include <mutex>
#include <chrono>
#include <thread>
#include <sstream>
#include <string>
#include <unordered_set>
#include <cstdarg>
#include <iomanip>
#include <netinet/in.h>
#include <unistd.h> // close
#include <sys/socket.h>
#include <sys/un.h>
#include <functional>
#include "utils.h"
#include <omp.h>
#ifndef STATIC_LIB
#define TLL_INLINE
#else
#define TLL_INLINE inline
#endif
namespace tll {
typedef uint32_t LogType;
namespace logtype { /// logtype
static const LogType kDebug=(1U << 0);
static const LogType kTrace=(1U << 1);
static const LogType kInfo=(1U << 2);
static const LogType kFatal=(1U << 3);
}
typedef std::pair<LogType, std::string> LogInfo;
typedef std::pair<LogType, int> LogFd;
template <size_t const kLogSize, uint32_t max_log_in_queue, uint32_t const kDelayMicro>
class Logger
{
public:
template < typename ... LFds>
Logger(LFds ...lfds) : ring_queue_(max_log_in_queue), is_running_(false)
{
addFd__(lfds...);
}
~Logger()
{
is_running_.store(false, std::memory_order_relaxed);
if(broadcast_.joinable()) broadcast_.join();
for(auto lfd : lfds_)
{
close(lfd.second);
}
}
template <LogType type, typename... Args>
void log(const char *format, Args &&...args)
{
ring_queue_.push([](LogInfo &elem, uint32_t size, LogInfo &&log_msg)
{
elem = std::move(log_msg);
}, LogInfo{type, utils::Format(kLogSize, format, std::forward<Args>(args)...)});
if(!is_running_.load(std::memory_order_relaxed)) start();
}
TLL_INLINE void start()
{
bool val = false;
if(!is_running_.compare_exchange_strong(val, true, std::memory_order_relaxed)) return;
broadcast_ = std::thread([this]()
{
while(is_running_.load(std::memory_order_relaxed))
{
if(ring_queue_.empty())
{
std::this_thread::sleep_for(std::chrono::microseconds(kDelayMicro));
continue;
}
LogInfo log_message;
ring_queue_.pop([&log_message](LogInfo &elem, uint32_t)
{
log_message = std::move(elem);
});
// FIXME: parallel is 10 times slower???
// #pragma omp parallel for
for(int i=0; i<lfds_.size(); i++)
{
LogFd &lfd = lfds_[i];
if(lfd.first & log_message.first)
{
auto size = write(lfd.second, log_message.second.data(), log_message.second.size());
}
}
}
});
}
TLL_INLINE void join()
{
while(is_running_.load(std::memory_order_relaxed) && !ring_queue_.empty())
std::this_thread::sleep_for(std::chrono::microseconds(kDelayMicro));
}
template < typename ... LFds>
void addFd(LFds ...lfds)
{
if(is_running_.load(std::memory_order_relaxed)) return;
addFd__(lfds...);
}
private:
template <typename ... LFds>
void addFd__(LogFd lfd, LFds ...lfds)
{
lfds_.push_back(lfd);
addFd__(lfds...);
}
TLL_INLINE void addFd__(LogFd lfd)
{
lfds_.push_back(lfd);
}
utils::BSDLFQ<LogInfo> ring_queue_;
std::atomic<bool> is_running_;
std::thread broadcast_;
std::vector<LogFd> lfds_;
};
} // llt
#define LOG_HEADER__ utils::Format("(%.6f)%s:%s:%d[%s]", utils::timestamp<double>(), __FILE__, __FUNCTION__, __LINE__, utils::tid())
#define TLL_LOGD(logger, format, ...) (logger).log<tll::logtype::kDebug>("[D]%s(" format ")\n", LOG_HEADER__ , ##__VA_ARGS__)
#define TLL_LOGTF(logger) (logger).log<tll::logtype::kTrace>("[T]%s", LOG_HEADER__); utils::Timer timer__([&logger](std::string const &str){logger.log<tll::logtype::kTrace>("%s", str.data());}, __FUNCTION__)
#define TLL_LOGT(logger, ID) (logger).log<tll::logtype::kTrace>("[T]%s", LOG_HEADER__); utils::Timer timer_##ID__([&logger](std::string const &str){logger.log<tll::logtype::kTrace>("%s", str.data());}, #ID)
#define TLL_LOGI(logger, format, ...) (logger).log<tll::logtype::kInfo>("[I]%s(" format ")\n", LOG_HEADER__ , ##__VA_ARGS__)
#define TLL_LOGF(logger, format, ...) (logger).log<tll::logtype::kFatal>("[F]%s(" format ")\n", LOG_HEADER__ , ##__VA_ARGS__)
</code></pre>
<p>utils.h</p>
<pre><code>#pragma once
#include <vector>
#include <chrono>
#include <thread>
#include <unordered_map>
#include <string>
#include <sstream>
#include <atomic>
#include <cstring>
#include "SimpleSignal.hpp"
#define LOGPD(format, ...) printf("[D](%.6f)%s:%s:%d[%s]:" format "\n", utils::timestamp<double>(), __FILE__, __PRETTY_FUNCTION__, __LINE__, utils::tid().data(), ##__VA_ARGS__)
#define LOGD(format, ...) printf("[D](%.6f)%s:%s:%d[%s]:" format "\n", utils::timestamp<double>(), __FILE__, __FUNCTION__, __LINE__, utils::tid().data(), ##__VA_ARGS__)
#define LOGE(format, ...) printf("[E](%.6f)%s:%s:%d[%s]:" format "%s\n", utils::timestamp<double>(), __FILE__, __FUNCTION__, __LINE__, utils::tid().data(), ##__VA_ARGS__, strerror(errno))
#define TIMER(ID) utils::Timer __timer_##ID(#ID)
#define TRACE() utils::Timer __tracer(std::string(__FUNCTION__) + ":" + std::to_string(__LINE__) + "(" + utils::tid() + ")")
namespace utils {
/// format
template <typename T>
T Argument(T value) noexcept
{
return value;
}
template <typename T>
T const * Argument(std::basic_string<T> const & value) noexcept
{
return value.data();
}
template <typename ... Args>
int StringPrint(char * const buffer,
size_t const bufferCount,
char const * const format,
Args const & ... args) noexcept
{
int const result = snprintf(buffer,
bufferCount,
format,
Argument(args) ...);
// assert(-1 != result);
return result;
}
template <typename ... Args>
int StringPrint(wchar_t * const buffer,
size_t const bufferCount,
wchar_t const * const format,
Args const & ... args) noexcept
{
int const result = swprintf(buffer,
bufferCount,
format,
Argument(args) ...);
// assert(-1 != result);
return result;
}
template <typename T, typename ... Args>
std::basic_string<T> Format(
size_t size,
T const * const format,
Args const & ... args)
{
std::basic_string<T> buffer;
buffer.resize(size);
int len = StringPrint(&buffer[0], buffer.size(), format, args ...);
buffer.resize(len);
return buffer;
}
template <typename T, typename ... Args>
std::basic_string<T> Format(
T const * const format,
Args const & ... args)
{
std::basic_string<T> buffer;
// size_t const size = 0x100;
size_t const size = StringPrint(&buffer[0], 0, format, args ...);
if (size > 0)
{
buffer.resize(size + 1); /// extra for null
StringPrint(&buffer[0], buffer.size(), format, args ...);
}
return buffer;
}
inline uint32_t nextPowerOf2(uint32_t val)
{
val--;
val |= val >> 1;
val |= val >> 2;
val |= val >> 4;
val |= val >> 8;
val |= val >> 16;
val++;
return val;
}
inline bool powerOf2(uint32_t val)
{
return (val & (val - 1)) == 0;
}
template <typename T, size_t const kELemSize=sizeof(T)>
class BSDLFQ
{
public:
BSDLFQ(uint32_t num_of_elem) : prod_tail_(0), prod_head_(0), cons_tail_(0), cons_head_(0)
{
capacity_ = powerOf2(num_of_elem) ? num_of_elem : nextPowerOf2(num_of_elem);
buffer_.resize(capacity_ * kELemSize);
}
template <typename F, typename ...Args>
void pop(F &&doPop, Args &&...elems)
{
uint32_t cons_head = cons_head_.load(std::memory_order_relaxed);
for(;;)
{
if (cons_head == prod_tail_.load(std::memory_order_relaxed))
continue;
if(cons_head_.compare_exchange_weak(cons_head, cons_head + 1, std::memory_order_acquire, std::memory_order_relaxed))
break;
}
std::forward<F>(doPop)(elemAt(cons_head), kELemSize, std::forward<Args>(elems)...);
while (cons_tail_.load(std::memory_order_relaxed) != cons_head);
cons_tail_.fetch_add(1, std::memory_order_release);
}
template <typename F, typename ...Args>
void push(F &&doPush, Args&&...elems)
{
uint32_t prod_head = prod_head_.load(std::memory_order_relaxed);
for(;;)
{
if (prod_head == (cons_tail_.load(std::memory_order_relaxed) + capacity_))
continue;
if(prod_head_.compare_exchange_weak(prod_head, prod_head + 1, std::memory_order_acquire, std::memory_order_relaxed))
break;
}
std::forward<F>(doPush)(elemAt(prod_head), kELemSize, std::forward<Args>(elems)...);
while (prod_tail_.load(std::memory_order_relaxed) != prod_head);
prod_tail_.fetch_add(1, std::memory_order_release);
}
inline bool tryPop(uint32_t &cons_head)
{
cons_head = cons_head_.load(std::memory_order_relaxed);
for(;;)
{
if (cons_head == prod_tail_.load(std::memory_order_relaxed))
return false;
if(cons_head_.compare_exchange_weak(cons_head, cons_head + 1, std::memory_order_acquire, std::memory_order_relaxed))
return true;
}
return false;
}
inline bool completePop(uint32_t cons_head)
{
while (cons_tail_.load(std::memory_order_relaxed) != cons_head);
cons_tail_.fetch_add(1, std::memory_order_release);
return true;
}
inline bool tryPush(uint32_t &prod_head)
{
prod_head = prod_head_.load(std::memory_order_relaxed);
for(;;)
{
if (prod_head == (cons_tail_.load(std::memory_order_relaxed) + capacity_))
return false;
if(prod_head_.compare_exchange_weak(prod_head, prod_head + 1, std::memory_order_acquire, std::memory_order_relaxed))
return true;
}
return false;
}
inline bool completePush(uint32_t prod_head)
{
while (prod_tail_.load(std::memory_order_relaxed) != prod_head);
prod_tail_.fetch_add(1, std::memory_order_release);
return true;
}
inline bool empty() const { return size() == 0; }
inline uint32_t size() const
{
return prod_tail_.load(std::memory_order_relaxed) - cons_tail_.load(std::memory_order_relaxed);
}
inline uint32_t wrap(uint32_t index) const
{
return index & (capacity_ - 1);
}
inline uint32_t capacity() const { return capacity_; }
inline T &elemAt(uint32_t index)
{
return buffer_[kELemSize * wrap(index)];
}
inline T const &elemAt(uint32_t index) const
{
return buffer_[kELemSize * wrap(index)];
}
inline size_t elemSize() const
{
return kELemSize;
}
private:
std::atomic<uint32_t> prod_tail_, prod_head_, cons_tail_, cons_head_;
uint32_t capacity_;
std::vector<T> buffer_;
};
inline std::string tid()
{
std::stringstream ss;
ss << std::this_thread::get_id();
return ss.str();
}
template <typename T=size_t, typename D=std::ratio<1,1>, typename C=std::chrono::high_resolution_clock>
T timestamp(typename C::time_point &&t = C::now())
{
return std::chrono::duration_cast<std::chrono::duration<T,D>>(std::forward<typename C::time_point>(t).time_since_epoch()).count();
}
struct Timer
{
using clock__= std::chrono::high_resolution_clock;
Timer() : name_(""), begin_(clock__::now()) {}
Timer(std::string id) : name_(std::move(id)), begin_(clock__::now())
{
printf(" (%.6f)%s\n", utils::timestamp<double>(), name_.data());
}
Timer(std::function<void(std::string const&)> logf, std::string id="") : name_(std::move(id)), begin_(clock__::now())
{
sig_log_.connect(logf);
sig_log_.emit(Format("(%s)\n", utils::timestamp<double>(), name_.data()));
}
~Timer()
{
if(sig_log_)
sig_log_.emit(Format(" (%.6f)[%s](~%s) %.3f (ms)\n", utils::timestamp<double>(), utils::tid(), name_.data(), elapse<double,std::milli>()));
else if(!name_.empty())
printf(" (%.6f)~%s: %.3f (ms)\n", utils::timestamp<double>(), name_.data(), elapse<double,std::milli>());
}
template <typename T=double, typename D=std::milli>
T reset()
{
T ret = elapse<T,D>();
begin_ = clock__::now();
return ret;
}
template <typename T=double, typename D=std::milli>
T elapse() const
{
using namespace std::chrono;
return duration_cast<std::chrono::duration<T,D>>(clock__::now() - begin_).count();
}
template <typename T=double, typename D=std::milli>
std::chrono::duration<T,D> duration() const
{
using namespace std::chrono;
auto ret = duration_cast<std::chrono::duration<T,D>>(clock__::now() - begin_);
return ret;
}
clock__::time_point begin_;
std::string name_;
Simple::Signal<void(std::string const&)> sig_log_;
};
} /// utils
</code></pre>
<p>logtest.cc</p>
<pre><code>#include <fstream>
#include <iostream>
#include <fcntl.h> /* For O_RDWR */
#include <unistd.h> /* For open(), creat() */
#include "../libs/SimpleSignal.hpp"
#include "../libs/utils.h"
#include "../libs/logger.h"
// #include "../libs/exporterudp.h"
namespace {
int const fd_terminal = 0;
}
int main(int argc, char const *argv[])
{
tll::Logger<0x400, 0x1000, 5> lg
(
tll::LogFd{tll::logtype::kDebug | tll::logtype::kInfo | tll::logtype::kFatal, fd_terminal},
tll::LogFd{tll::logtype::kTrace | tll::logtype::kDebug, open("fd_t.log", O_WRONLY | O_TRUNC | O_CREAT , 0644)},
tll::LogFd{tll::logtype::kInfo, open("fd_i.log", O_WRONLY | O_TRUNC | O_CREAT , 0644)},
tll::LogFd{tll::logtype::kFatal, open("fd_f.log", O_WRONLY | O_TRUNC | O_CREAT , 0644)}
);
TLL_LOGTF(lg);
if(argc == 2)
{
TIMER(logger);
for(int i=0; i<std::stoi(argv[1]); i++)
{
TLL_LOGD(lg, "%d %s", 10, "oi troi oi");
TLL_LOGT(lg, loop);
TLL_LOGI(lg, "%d %s", 10, "oi troi oi");
TLL_LOGF(lg, "%d %s", 10, "oi troi oi");
}
lg.join();
}
else
{
TIMER(rawlog);
for(int i=0; i<std::stoi(argv[1]); i++)
printf("[%d]%ld:%s:%s:%d[%s](%d %s)\n", (int)tll::logtype::kInfo, utils::timestamp(), __FILE__, __FUNCTION__, __LINE__, utils::tid().data(), 10, "oi troi oi");
}
return 0;
}
</code></pre>
<p>Command-line to compile</p>
<p><code>cd util/tests; g++ logtest.cc -std=c++11 -lpthread -fopenmp -O3 && ./a.out 100</code></p>
<p>Any advice would be valuable for me</p>
<p>Thanks in advance</p>
|
[] |
[
{
"body": "<p>The following are only a few quick notes on the C++ language usage from a first reading. I didn't have enough time to fully get through the whole code (might revisit later) and make suggestions on the overall design. I hope this is still considered an ok answer:</p>\n\n<hr>\n\n<p><code>TTL_INLINE</code> is pointless. It is used only on declarations of member functions which are defined in the class itself. Member functions defined in a class are <code>inline</code> automatically. Especially in a (class) template definition there is no point to <code>inline</code> at all, because being a template already imparts the same semantics as <code>inline</code> does.</p>\n\n<hr>\n\n<pre><code>static const LogType kDebug=(1U << 0);\n</code></pre>\n\n<p>It doesn't matter so much for variables of integral type, but if you want to declare a compile-time constant it is advisable to always declare it <code>constexpr</code>. This guarantees that the variable is indeed a compile-time constant (and you will get an error message if it isn't.</p>\n\n<p><code>static</code> is pointless for global <code>const</code> (or <code>constexpr</code>) variables, because they have internal linkage in C++ anyway (but not in C!).</p>\n\n<p>So, better:</p>\n\n<pre><code>constexpr LogType kDebug=(1U << 0);\n</code></pre>\n\n<p>Similarly there is no point in having the unnamed namespace in</p>\n\n<pre><code>namespace {\n int const fd_terminal = 0;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>template <size_t const kLogSize, uint32_t max_log_in_queue, uint32_t const kDelayMicro>\n</code></pre>\n\n<p><code>const</code>-qualifying a template parameter is pointless. They cannot be modified anyway.</p>\n\n<hr>\n\n<p><code>addFd__</code>, <code>LOG_HEADER__</code>, <code>clock__</code>, <code>timer__</code>: Identifiers containing a double underscore <em>in any place</em> are reserved for the C++ compiler/standard library in all contexts.</p>\n\n<p>You are not allowed to define them as macro or declare them in any way. Doing so causes the program to technically have undefined behavior and will definitively get you in trouble if the compiler/standard library actually uses one of the reserved names.</p>\n\n<p>Note that the same is true for identifiers starting with a single underscore followed by an upper case letter. Identifiers starting with a single underscore are always reserved in the global scope.</p>\n\n<p>Use a different naming scheme instead.</p>\n\n<hr>\n\n<p>Your <code>Logger</code> class has a custom destructor, but you are not defining a copy constructor and copy assignment operator. This is by itself is a violation of the <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">rule of 0/3/5</a>. Violating this rule in most cases causes undefined behavior when the copies of objects of the class are made.</p>\n\n<p>However, in your particular case the class is non-copyable because it contains a non-copyable type (<code>std::thread</code>) and is also non-movable because of the user-declared destructor. Therefore you won't be able to copy class objects anyway.</p>\n\n<p>You might still want to be explicit about it though and delete the copy operations:</p>\n\n<pre><code>Logger(const Logger&) = delete;\nLogger& operator=(const Logger&) = delete;\nLogger(Logger&&) = delete;\nLogger& operator=(Logger&&) = delete;\n</code></pre>\n\n<p>The <code>Timer</code> class has a similar issue.</p>\n\n<hr>\n\n<pre><code>template <typename T>\nT Argument(T value) noexcept\n{\n return value;\n}\n</code></pre>\n\n<p>This seems dangerous, because there is no guarantee that the copy constructors involved in this are actually <code>noexcept</code>. Instead you can simply pass-on the a reference:</p>\n\n<pre><code>template <typename T>\nconst T& Argument(const T& value) noexcept\n{\n return value;\n}\n</code></pre>\n\n<p>which is guaranteed to not throw and also never requires copy constructor calls.</p>\n\n<p>However <code>StringPrint</code> itself also has the same problem. It is however only a symptom of the much larger issue that you are not checking the types passed to your logger functions at all. In reality you should only accept types matching the format specification. Everything else will, silently, lead to undefined behavior.</p>\n\n<p>In general, I'd suggest not using the C IO library which fundamentally has this type-safety problem. Instead have a look at e.g. the <code>fmt</code> library, which also inspires the upcoming C++20 <code>std::format</code>.</p>\n\n<hr>\n\n<p>(This one might be a bit pedantic, I think it is not a problem in practice.)</p>\n\n<p><code>uint32_t</code>, <code>size_t</code>, <code>snprintf</code> and all the other C type aliases and functions are not guaranteed to be introduced into the global namespace when you include the <code><c...></code> header versions.</p>\n\n<p>From what I can tell the POSIX header <code>unistd.h</code> guarantees that <code>size_t</code> and all the symbols from <code>stdio.h</code> are introduced in the global namespace and the POSIX header <code>netinet/in.h</code> guarantees that <code>uint32_t</code> is introduced, but you might want to just always prefix <code>std::</code> (or add a using declaration), just to be sure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T15:30:46.170",
"Id": "468279",
"Score": "0",
"body": "Thank you to pointed out, all your comments are correct. They are caused by copy-pasted mistake. I will clean them in later commits. But how about the design architecture, any points to make it easier to be used or re-used? How about performance, any idea to make it faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T15:36:57.613",
"Id": "468280",
"Score": "0",
"body": "BTW, I am very interested in (proud of) my BSDLFQ (lol!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T20:08:14.643",
"Id": "468312",
"Score": "0",
"body": "Thanks about _\"Identifiers containing a double underscore in any place are reserved for the C++ compiler/standard library in all contexts.\"_ I saw stdlib usually uses **___<previx>**, so I decided to use **<posfix>___** instead. Seems better to avoid __ in any situation"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T04:04:37.300",
"Id": "238748",
"ParentId": "238645",
"Score": "2"
}
},
{
"body": "<p>Not that it is important, but <code>pop</code> and <code>push</code> both use unbounded loops to wait for other operations to finish. So strictly speaking your queue implementation is not lock-free. This <em>can</em> be a performance problem in case of oversubscription (i.e., when you use more threads than you have cores).</p>\n\n<p>However, with regards to performance improvements you should first run some profiling tests. If you come back with some results where most of the time is spent, we might be able to give a few pointers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T16:23:04.543",
"Id": "238889",
"ParentId": "238645",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T02:49:34.043",
"Id": "238645",
"Score": "2",
"Tags": [
"c++",
"c++11",
"template",
"logging",
"lock-free"
],
"Title": "Lock-free multi producer logging/profiling, multi file descriptors"
}
|
238645
|
<p>I have here some methods which reverse string characters. Example if given string is "HELLO", it will returns "OLLEH". Are my big o notation for these approaches correct? And which approach is the most efficient (both time and space complexity)?</p>
<pre><code> /// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_TwoArrays(string str)
{
char[] arr2 = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
arr2[i] = str[str.Length - 1 - i];
}
return string.Join("",arr2);
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ClassicForLoop_ArrayIndex(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
{
sb.Append(str[i]);
}
return sb.ToString();
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ForEachConcat(string str)
{
string newStr = "";
foreach (var item in str)
{
newStr = item.ToString() + newStr;
}
return newStr;
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_Stack(string str)
{
var stack = new Stack();
foreach (var item in str) // Time Complexity: o(n)
{
stack.Push(item); // Time Complexity: o(1)
}
return string.Join("", stack.ToArray());
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(n)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_ArrayReverse(string str)
{
char[] arrChar = str.ToCharArray();
Array.Reverse(arrChar);
return string.Join("", arrChar);
}
/// <summary>
/// Time Complexity: o(n)
/// Space Complexity: o(1)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReverseString_LINQ(string str)
=> string.Join("", str.Reverse());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T19:59:51.033",
"Id": "468088",
"Score": "1",
"body": "Strings in C# are immutable, so in order to reverse a string you will always have to create a new string in the end which takes `O(n)` space. In order to get `O(1)` space you would need to reverse the string *in place* which is not possible."
}
] |
[
{
"body": "<p>There are a couple of constructs in there that can be improved.</p>\n\n<ul>\n<li><code>string.Join(\"\", charArray)</code>, repeated a lot. <code>string</code> has a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.-ctor?view=netframework-4.8#System_String__ctor_System_Char___\" rel=\"nofollow noreferrer\">constructor that takes a <code>char[]</code></a>, which is a lot faster. They are both linear time, which your question seems to focus on, but in terms of actual efficiency the difference is nearly two orders of magnitude in some tests (actual impact of course varies).</li>\n<li><code>new Stack()</code>, so.. the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=netframework-4.8\" rel=\"nofollow noreferrer\">old stack</a>, from the .NET 1.1 days? Don't use that one, use <code>Stack<T></code>. Especially if the things you're putting in them are value types, which would have to be boxed in the old non-generic <code>Stack</code>.</li>\n</ul>\n\n<p>For <code>ReverseString_ForEachConcat</code>, I don't agree that the time complexity is O(n). At every step, the old string is copied over into the new string, with something concatenated in front of it. So in the second iteration there is 1 copied character, in the third iteration there are 2 copied characters etc. That's a classic O(n²) pattern.</p>\n\n<p>I think we could also argue about whether or not it takes constant space. The many old versions of the string can disappear quickly, but while the concatenation is happening, both the old string and the result of the concatenation need to exist. In the last iteration, that means that while the final result is being made (the size of which doesn't count), there is an other string in play of nearly the same size, so O(n) worth of auxiliary space.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T03:52:31.303",
"Id": "238649",
"ParentId": "238647",
"Score": "4"
}
},
{
"body": "<p>I was going to write this as a comment, but I have too much to talk about. When I first read the question, what was screaming at me is \"<strong><em>WHY?!</em></strong>\" Why go through such gymnastics? Are you intentionally trying to <strong>reinvent-the-wheel</strong>? If you are, then please tag the question with that tag.</p>\n\n<p>If you are wanting to learn C#, and equally important, .NET, then I would suggest your focus should be on relying upon the framework.</p>\n\n<p>For a simple Americanized string, where each character in the string is its own entity, you could try something like:</p>\n\n<pre><code>public static string ReverseString(string str)\n{\n char[] arr2 = str.ToCharArray();\n Array.Reverse(arr2);\n return new string(arr2);\n}\n</code></pre>\n\n<p>There are also examples here on CR where the reversing is done by only going halfway through the char array. The endpoints are swapped, and then indices are moved inward.</p>\n\n<p>Note the above only works for some strings. If your input string contains certain characters from different cultures, these characters are known as surrogate pairs. You may loosely think of the pair as a composite. For such things, you do not want to reverse the individual characters because it breaks the surrogate relationship. Instead, you would use .NET and look into the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.globalization.stringinfo?view=netframework-4.8\" rel=\"nofollow noreferrer\">StringInfo</a> class (part of System.Globalization). The link provided shows how to honor surrogates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:42:42.330",
"Id": "238674",
"ParentId": "238647",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238649",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T03:12:22.970",
"Id": "238647",
"Score": "4",
"Tags": [
"c#",
"linq"
],
"Title": "Big O notation for Reverse String"
}
|
238647
|
<p>I am trying to extract all the elements from a webpage which contains given set of words. E.g. Given I have an array of random words </p>
<pre><code>words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"]
</code></pre>
<p>and suppose all of them present in the DOM. It means I need to check each possible tag for their presence. Below are the tags which I am searching for.</p>
<pre><code>// 14 essential tags
items = ["p", "li", "h2", "h3", "h4", "h5", "h6", "b",
"small", "td", "span", "strong", "blockquote", "div"]
</code></pre>
<p>also I need to ensure the whitespace boundary of word. So for each word I need to define three checks in jQuery <code>contains()</code> selector like below.</p>
<pre><code>tagName:contains('sky '), tagName:contains(' sky'), tagName:contains(' sky ')`
</code></pre>
<p>So in total the final query for above scenario makes <code>words.length * items.length * 3</code> 14*11*3 = 462 selectors. Which is itself a large query and as the words array start growing my query looks like below. </p>
<p><code>$(p:icontains('ACCESSIBLE '), p:icontains(' ACCESSIBLE'), p:icontains(' ACCESSIBLE '), li:icontains('ACCESSIBLE '), li:icontains(' ACCESSIBLE'), li:icontains(' ACCESSIBLE '), h3:icontains('ACCESSIBLE '), h3:icontains(' ACCESSIBLE'), h3:icontains(' ACCESSIBLE '), h4:icontains('ACCESSIBLE '), h4:icontains(' ACCESSIBLE'), h4:icontains(' ACCESSIBLE '), h5:icontains('ACCESSIBLE '), h5:icontains(' ACCESSIBLE'), h5:icontains(' ACCESSIBLE '), b:icontains('ACCESSIBLE '), b:icontains(' ACCESSIBLE'), b:icontains(' ACCESSIBLE '), td:icontains('ACCESSIBLE '), td:icontains(' ACCESSIBLE'), td:icontains(' ACCESSIBLE '), span:icontains('ACCESSIBLE '), span:icontains(' ACCESSIBLE'), span:icontains(' ACCESSIBLE '), strong:icontains('ACCESSIBLE '), strong:icontains(' ACCESSIBLE'), strong:icontains(' ACCESSIBLE '), div:icontains('ACCESSIBLE '), div:icontains(' ACCESSIBLE'), div:icontains(' ACCESSIBLE ')p:icontains('ADDRESS '), p:icontains(' ADDRESS'), p:icontains(' ADDRESS '), li:icontains('ADDRESS '), li:icontains(' ADDRESS'), li:icontains(' ADDRESS '), h3:icontains('ADDRESS '), h3:icontains(' ADDRESS'), h3:icontains(' ADDRESS '), h4:icontains('ADDRESS '), h4:icontains(' ADDRESS'), h4:icontains(' ADDRESS '), h5:icontains('ADDRESS '), h5:icontains(' ADDRESS'), h5:icontains(' ADDRESS '), b:icontains('ADDRESS '), b:icontains(' ADDRESS'), b:icontains(' ADDRESS '), td:icontains('ADDRESS '), td:icontains(' ADDRESS'), td:icontains(' ADDRESS '), span:icontains('ADDRESS '), span:icontains(' ADDRESS'), span:icontains(' ADDRESS '), strong:icontains('ADDRESS '), strong:icontains(' ADDRESS'), strong:icontains(' ADDRESS '), div:icontains('ADDRESS '), div:icontains(' ADDRESS'), div:icontains(' ADDRESS ')p:icontains('ANTIEMETICS '), p:icontains(' ANTIEMETICS'), p:icontains(' ANTIEMETICS '), li:icontains('ANTIEMETICS '), li:icontains(' ANTIEMETICS'), li:icontains(' ANTIEMETICS '), h3:icontains('ANTIEMETICS '), h3:icontains(' ANTIEMETICS'), h3:icontains(' ANTIEMETICS '), h4:icontains('ANTIEMETICS '), h4:icontains(' ANTIEMETICS'), h4:icontains(' ANTIEMETICS '), h5:icontains('ANTIEMETICS '), h5:icontains(' ANTIEMETICS'), h5:icontains(' ANTIEMETICS '), b:icontains('ANTIEMETICS '), b:icontains(' ANTIEMETICS'), b:icontains(' ANTIEMETICS '), td:icontains('ANTIEMETICS '), td:icontains(' ANTIEMETICS'), td:icontains(' ANTIEMETICS '), span:icontains('ANTIEMETICS '), span:icontains(' ANTIEMETICS'), span:icontains(' ANTIEMETICS '), strong:icontains('ANTIEMETICS '), strong:icontains(' ANTIEMETICS'), strong:icontains(' ANTIEMETICS '), div:icontains('ANTIEMETICS '), div:icontains(' ANTIEMETICS'), div:icontains(' ANTIEMETICS ')p:icontains('BRAND '), p:icontains(' BRAND'), p:icontains(' BRAND '), li:icontains('BRAND '), li:icontains(' BRAND'), li:icontains(' BRAND '), h3:icontains('BRAND '), h3:icontains(' BRAND'), h3:icontains(' BRAND '), h4:icontains('BRAND '), h4:icontains(' BRAND'), h4:icontains(' BRAND '), h5:icontains('BRAND '), h5:icontains(' BRAND'), h5:icontains(' BRAND '), b:icontains('BRAND '), b:icontains(' BRAND'), b:icontains(' BRAND '), td:icontains('BRAND '), td:icontains(' BRAND'), td:icontains(' BRAND '), span:icontains('BRAND '), span:icontains(' BRAND'), span:icontains(' BRAND '), strong:icontains('BRAND '), strong:icontains(' BRAND'), strong:icontains(' BRAND '), div:icontains('BRAND '), div:icontains(' BRAND'), div:icontains(' BRAND ')p:icontains('CAPABLE '), p:icontains(' CAPABLE'), p:icontains(' CAPABLE '), li:icontains('CAPABLE '), li:icontains(' CAPABLE'), li:icontains(' CAPABLE '), h3:icontains('CAPABLE '), h3:icontains(' CAPABLE'), h3:icontains(' CAPABLE '), h4:icontains('CAPABLE '), h4:icontains(' CAPABLE'), h4:icontains(' CAPABLE '), h5:icontains('CAPABLE '), h5:icontains(' CAPABLE'), h5:icontains(' CAPABLE '), b:icontains('CAPABLE '), b:icontains(' CAPABLE'), b:icontains(' CAPABLE '), td:icontains('CAPABLE '), td:icontains(' CAPABLE'), td:icontains(' CAPABLE '), span:icontains('CAPABLE '), span:icontains(' CAPABLE'), span:icontains(' CAPABLE '), strong:icontains('CAPABLE '), strong:icontains(' CAPABLE'), strong:icontains(' CAPABLE '), div:icontains('CAPABLE '), div:icontains(' CAPABLE'), div:icontains(' CAPABLE ')p:icontains('COMMAND '), p:icontains(' COMMAND'), p:icontains(' COMMAND '), li:icontains('COMMAND '), li:icontains(' COMMAND'), li:icontains(' COMMAND '), h3:icontains('COMMAND '), h3:icontains(' COMMAND'), h3:icontains(' COMMAND '), h4:icontains('COMMAND '), h4:icontains(' COMMAND'), h4:icontains(' COMMAND '), h5:icontains('COMMAND '), h5:icontains(' COMMAND'), h5:icontains(' COMMAND '), b:icontains('COMMAND '), b:icontains(' COMMAND'), b:icontains(' COMMAND '), td:icontains('COMMAND '), td:icontains(' COMMAND'), td:icontains(' COMMAND '), span:icontains('COMMAND '), span:icontains(' COMMAND'), span:icontains(' COMMAND '), strong:icontains('COMMAND '), strong:icontains(' COMMAND'), strong:icontains(' COMMAND '), div:icontains('COMMAND '), div:icontains(' COMMAND'), div:icontains(' COMMAND ')p:icontains('CONFLUENCE ') ....</code>
<a href="https://i.stack.imgur.com/vQljp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vQljp.png" alt="enter image description here"></a></p>
<p>A query with 87Kb of selectors and it takes nearly 30-40 seconds to execute on a page. Is there any way to optimize it. I am already eliminating the tags which are not present in the page before making the query.</p>
<p>EDIT: The reason I can't do whole page text parsing with regex is that I need to replace those matched words with some HTML after parsing, it's similar to highlighting those words on page by injecting some HTML in their place. If I do regex I'll lose control over HTML element and their position. Also regex replacement does not guarantee the text nodes. It also replaces the words written inside title attributes and other attributes if present. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T07:35:37.790",
"Id": "468019",
"Score": "1",
"body": "Welcome to CodeReview@SE. Please try and use a more suitable title for your question, see [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) for guidance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T21:34:26.110",
"Id": "476964",
"Score": "0",
"body": "Thanks for updating your title but it still doesn't really describe what the code does. Please take a (-nother) look at that [_How do I ask_](https://codereview.stackexchange.com/help/how-to-ask) page - especially the section including \"_State what your code does in your title, not your main concerns about it._\" If we ask you what the code does then I doubt you would respond \"_Is it possible to optimise jQuery tag:contains() selector?_\""
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T03:57:15.847",
"Id": "238650",
"Score": "0",
"Tags": [
"javascript",
"performance",
"jquery",
"dom"
],
"Title": "Is it possible to optimise jQuery tag:contains() selector?"
}
|
238650
|
<p>I'm still new to C++ and tried one of the harder challenges on a coding practice/challenge website.
The challenge was the following:</p>
<p><em>Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.</em></p>
<p>I was able to solve it in ~ 50 minutes, but I feel like my code is really sloppy. Can anyone give me tips on how to simplify this? I find myself falling into very complex ways of solving things often.</p>
<pre><code>std::string longestSubstring(std::string digits) {
std::string strOddEven{};
std::vector<std::string> vecOddEven{};
bool next{};
int maxSize{};
for (int i = 0; i < digits.size() - 1; ++i)
{
if ((digits.at(i) % 2 == 0 && digits.at(i + 1) % 2 != 0) ||
(digits.at(i) % 2 != 0 && digits.at(i + 1) % 2 == 0))
{
strOddEven += digits.at(i);
next = true;
if (i == digits.size() - 2) // add to strOddEven and push_back
{ // in case of longest string being at end
strOddEven += digits.at(i + 1);
vecOddEven.push_back(strOddEven);
}
}
else if (next)
{
strOddEven += digits.at(i);
vecOddEven.push_back(strOddEven);
strOddEven = "";
next = false;
}
}
for (auto& i : vecOddEven)
if (i.size() > maxSize)
maxSize = i.size();
for (auto& i : vecOddEven)
if (i.size() == maxSize)
return i;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Include the headers we need</h1>\n\n<pre><code>#include <string>\n#include <vector>\n</code></pre>\n\n<h1>Don't make unnecessary copies</h1>\n\n<pre><code>std::string longestSubstring(const std::string& digits) {\n</code></pre>\n\n<p>Also, consider storing <code>std::string_view</code> objects internally, as these are much lighter than owning strings.</p>\n\n<h1>Fix the bug</h1>\n\n<p>I get a SIGABRT when I call with empty string as argument:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>==1629582== by 0x4914B54: __cxa_throw (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)\n==1629582== by 0x490C090: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)\n==1629582== by 0x10AC0B: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::at(unsigned long) const (basic_string.h:1087)\n==1629582== by 0x10A30F: longestSubstring(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (238652.cpp:12)\n==1629582== by 0x10A725: main (238652.cpp:46)\n</code></pre>\n\n<h1>Use the algorithm library</h1>\n\n<p>The standard <code><algorithm></code> library has the tools you need, that will save you writing much tedious and error-prone code for yourself.</p>\n\n<p>The most useful function here is <code>std::adjacent_find()</code>, which you can use with a simple predicate such as</p>\n\n<pre><code>auto const both_even_or_both_odd\n = [](auto a, auto b){ return a % 2 == b % 2; };\n</code></pre>\n\n<h1>No need to store all the substrings</h1>\n\n<p>We only need to remember the longest substring seen so far, so there's no need for the two vectors. Just have a single <code>std::string_view</code> variable that you update when you find a longer run than the existing one.</p>\n\n<hr>\n\n<h1>Modified version</h1>\n\n<p>Here's a version using <code>std::adjacent_find()</code> as suggested:</p>\n\n<pre><code>#include <algorithm>\n#include <string>\n#include <utility>\n#include <vector>\n\nstd::string longestSubstring(const std::string& digits)\n{\n std::string longest = \"\";\n\n auto const same_mod2 = [](auto a, auto b){ return a % 2 == b % 2; };\n\n auto start = digits.begin();\n while (start < digits.end()) {\n auto finish = std::adjacent_find(start, digits.end(), same_mod2);\n if (finish != digits.end()) {\n ++finish;\n }\n auto const candidate = std::string{start, finish};\n if (candidate.size() > longest.size()) {\n longest = std::move(candidate);\n }\n start = finish;\n }\n\n return std::string{longest};\n}\n</code></pre>\n\n<p>And a simple test:</p>\n\n<pre><code>#include <iostream>\n\nint main()\n{\n for (auto const& s: { \"\", \"0\", \"11\", \"01\", \"112\",\n \"0112\", \"01224\", \"01223\", \"01123\" }) {\n std::cout << s << \"-->\" << longestSubstring(s) << '\\n';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T08:29:01.503",
"Id": "238660",
"ParentId": "238652",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T04:25:13.670",
"Id": "238652",
"Score": "2",
"Tags": [
"c++",
"beginner",
"programming-challenge"
],
"Title": "Longest Alternating Substring Code Challenge"
}
|
238652
|
<p>I have this method which reverses a list of numbers. For example, if the given input is <code>{ 1232, 3455, 6071 }</code>, it will return <code>{2321, 5543, 1706}</code></p>
<pre><code>public static List<int> ReverseIntegerList_Array(List<int> intList)
{
var newIntList = new List<int>();
foreach (var numbers in intList)
{
var charNums = numbers.ToString();
char[] arrNums = new char[charNums.Length];
for (int x = 0; x < charNums.Length;x++)
{
arrNums[x] = charNums[charNums.Length-1-x];
}
newIntList.Add(Convert.ToInt32(string.Join("",arrNums)));
}
return newIntList;
}
</code></pre>
<p>Can I reduce the space complexity further by not using an extra list object to store the result and return the result by overwriting the existing list object (defined in the method parameter)?</p>
<p>Found the way already.</p>
<pre><code> public static List<int> ReverseIntegerList_Array3(List<int> intList)
{
// var newIntList = new List<int>();
for (int i = 0; i < intList.Count; i++)
{
var charNums = intList[i].ToString();
intList[i] = 0; // Clear it.
char[] arrNums = new char[charNums.Length];
for (int x = 0; x < charNums.Length; x++)
{
arrNums[x] = charNums[charNums.Length - 1 - x];
}
intList[i] = Convert.ToInt32(string.Join("", arrNums));
}
return intList;
}
</code></pre>
<p>Is this solution okay in regards to space complexity?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:42:30.957",
"Id": "468082",
"Score": "5",
"body": "Title should really be \"Reverse numbers in a list\" :)"
}
] |
[
{
"body": "<p>You can improve the efficiency by reversing the numbers as integers instead of converting to strings and back.</p>\n\n<p>Modifying the list and returning it is redundant since the list is passed by reference and your changes will persist to the original list.</p>\n\n<p>Simplified your code could look like this:</p>\n\n<pre><code>public static void ReverseIntegerList_Array(List<int> intList)\n{\n if(intList == null)\n {\n return;\n }\n int limit = intList.Count;\n for(int i = 0; i < limit;++i)\n {\n intList[i] = ReverseNum(intList[i]);\n }\n}\n\npublic static int ReverseNum(int num)\n{\n int retVal = 0;\n while(num > 0)\n {\n retVal = (retVal * 10) + num % 10;\n num /= 10;\n }\n return retVal;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T09:01:18.633",
"Id": "468032",
"Score": "0",
"body": "Thanks for the solution. For this solution, the time complexity is o(n2)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:27:52.890",
"Id": "468080",
"Score": "1",
"body": "What do you think the old time and space complexity was and what the name one is? (Also how do you think conversion from int to characters is actually accomplished? Hint: It looks pretty much identical to your loop)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T20:21:14.973",
"Id": "468089",
"Score": "0",
"body": "@Voo - Converting to and from a string requires extra time and space"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T20:23:11.793",
"Id": "468091",
"Score": "1",
"body": "@tinstaafl That's not what's meant with space and time *complexity*. You should read the [wikipedia article](https://en.wikipedia.org/wiki/Time_complexity) on the topic since this is a much too large topic to explain in a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T20:24:16.020",
"Id": "468092",
"Score": "0",
"body": "@tinstaafl You don't need the `ReverseNum`, just move it inside the for loop, this would make it nicer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T20:25:31.807",
"Id": "468093",
"Score": "0",
"body": "@tinstaafl forgot null check on the main method. just a reminding. ;)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T05:00:42.060",
"Id": "238654",
"ParentId": "238653",
"Score": "14"
}
},
{
"body": "<p>You can convert <code>int</code> to <code>string</code>, then reverse, back to <code>string</code> and to <code>int</code>. This is two lines solution:</p>\n\n<pre><code>public static void ReverseIntegerList_Array(List<int> integers)\n{\n for (int i = 0; i < integers.Count; i++)\n integers[i] = int.Parse(new string(integers[i].ToString().Reverse().ToArray()));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T07:12:26.683",
"Id": "238659",
"ParentId": "238653",
"Score": "5"
}
},
{
"body": "<p>As we are working in C#, below is an example of an object-oriented approach, in contrast to the static/procedural approach.</p>\n\n<p>UPDATE: In the original answer I neglected to create a Number class to handle the reversing of the value. I have added it.</p>\n\n<p>And here's the output:<br>\n<a href=\"https://i.stack.imgur.com/4jjA7.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4jjA7.jpg\" alt=\"output\"></a></p>\n\n<pre><code>public class App_ReverseNumbers\n{\n public void Run()\n {\n var list = new List<int> { 123, 456, 789 };\n\n var numbers = new Numbers(list);\n Console.WriteLine(numbers.ToString());\n\n var reversed = numbers.AsReversed();\n Console.WriteLine(reversed.ToString());\n } \n}\n\npublic class Numbers\n{\n public List<int> List;\n\n public Numbers(List<int> list) => List = list;\n\n public Numbers AsReversed() => \n new Numbers(List.Select(i => new Number(i).Reverse()).ToList());\n\n public override string ToString() => string.Join(\", \", List);\n}\n\npublic class Number\n{\n public int Value { get; private set; }\n\n public Number(int value) => Value = value;\n\n public int Reverse() => int.Parse(new string(Value.ToString().Reverse().ToArray()));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T20:03:44.607",
"Id": "239075",
"ParentId": "238653",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238654",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T04:39:02.780",
"Id": "238653",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Reverse each number in a list"
}
|
238653
|
<p>I'm building a page in <a href="https://developer.salesforce.com/docs/component-library/documentation/en/48.0/lwc" rel="nofollow noreferrer">LWC</a> this page consist of a table, you can search, sort and paginate with this table.</p>
<p><a href="https://i.stack.imgur.com/0QyGr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0QyGr.png" alt="enter image description here"></a></p>
<p>When the first element is selected:
<a href="https://i.stack.imgur.com/dkf2q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dkf2q.png" alt="enter image description here"></a></p>
<p>when the last element is selected:
<a href="https://i.stack.imgur.com/1pk3U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1pk3U.png" alt="enter image description here"></a></p>
<p>When the middle element is selected:
<a href="https://i.stack.imgur.com/wmLGS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wmLGS.png" alt="enter image description here"></a></p>
<p>Here's pagination HTML code:</p>
<pre><code><div class="pageButtons">
<template if:true={buttons} for:each={buttons} for:item="button" for:index="index">
<template if:true={button.isVisible}>
<lightning-button key={button.value} variant="Neutral" if:true={button.isVisible} disabled={button.isDisabled} label={button.value} class="pageButton" onclick={paginate}></lightning-button>
</template>
<template if:true={button.isPlaceHolder}>
<lightning-formatted-rich-text key={button.value} value="..."></lightning-formatted-rich-text>
</template>
</template>
</div>
</code></pre>
<p>Here's the JS code:</p>
<pre><code>//For initial load
const getButtonData = (pageSize) => {
pageSize = pageSize + 1;
let buttons = [];
buttons.push(add('First', true, true, false));
buttons.push(add('Previous', true, true, false));
for (let i = 1; i <= pageSize; i++) {
if (pageSize > 10) {
if (i < 6) {
buttons.push(add(i, i == 1 ? true : false, true, false));
}
else if (pageSize >= 6 && i == 6) {
buttons.push(add(i, i == 1 ? true : false, pageSize > 6 ? false : true, pageSize > 6 ? true : false));
}
else if (i == pageSize) {
buttons.push(add(i, false, true, false));
}
}
else {
buttons.push(add(i, i == 1 ? true : false, true, false));
}
}
buttons.push(add('Next', false, true, false));
buttons.push(add('Last', false, true, false));
return buttons;
}
//For onclick of buttons
const getButtonDataByPage = (pageSize, currentPage) => {
pageSize = pageSize + 1;
let buttons = [];
let isFirstPrev = currentPage == 1 ? true : false;
buttons.push(add('First', isFirstPrev, true, false));
buttons.push(add('Previous', isFirstPrev, true, false));
if (pageSize > 10) {
for (const i of getNextElements(currentPage, pageSize)) {
buttons.push(
add(
i.value,
i.value == currentPage,
i.isEllipses ? false : true,
i.isEllipses
)
);
}
}
else {
for (let i = 1; i <= pageSize; i++) {
buttons.push(add(i, i == currentPage ? true : false, true, false));
}
}
let isNextLast = currentPage == pageSize ? true : false;
buttons.push(add('Next', isNextLast, true, false));
buttons.push(add('Last', isNextLast, true, false));
return buttons;
}
function add(value, isDisabled, isVisible, isPlaceHolder) {
return {
value : value,
isDisabled: isDisabled,
isVisible : isVisible,
isPlaceHolder : isPlaceHolder
};
}
//To get the index array along with ellipses
function getNextElements(currentPage, pageSize) {
let index = [];
// Is first element
if (currentPage == 1) {
for (let j = 1; j <= pageSize; j++) {
if (j < 6) {
index.push({value : j, isEllipses: false});
}
else if (pageSize >= 6 && j == 6) {
index.push({value : j, isEllipses: true});
}
else if (j == pageSize) {
index.push({value : j, isEllipses: false});
}
}
}
// Is last element
else if (currentPage == pageSize) {
let lastColumn = (pageSize) - 5;
for (let j = 1; j <= pageSize ; j++) {
if (j > lastColumn) {
index.push({value : j, isEllipses: false});
}
else if (j == lastColumn) {
index.push({value : j, isEllipses: true});
}
else if (j == 1) {
index.push({value : j, isEllipses: false});
}
}
}
// Is middle element
else if (currentPage !== 1 || currentPage !== pageSize) {
let lastColumn = (pageSize) - 5;
let isCloseToFirstElement = (1 + currentPage <= 6) ? true : false;
let isCloseToLastElement = ((pageSize - currentPage) < 5) ? true : false;
if (isCloseToFirstElement) {
for (let j = 1; j <= pageSize; j++) {
if (j < 6) {
index.push({value : j, isEllipses: false});
}
else if (pageSize >= 6 && j == 6) {
index.push({value : j, isEllipses: true});
}
else if (j == pageSize) {
index.push({value : j, isEllipses: false});
}
}
}
if (isCloseToLastElement) {
for (let j = 1; j <= pageSize ; j++) {
if (j > lastColumn) {
index.push({value : j, isEllipses: false});
}
else if (j == lastColumn) {
index.push({value : j, isEllipses: true});
}
else if (j == 1) {
index.push({value : j, isEllipses: false});
}
}
}
if (!isCloseToLastElement && !isCloseToFirstElement) {
for (let i = 1; i <= pageSize; i++) {
if (i == 1) {
index.push({value : 1, isEllipses: false});
}
else if ((i !== 1 && i !== pageSize) && i == currentPage) {
index.push({value : currentPage - 2, isEllipses: true});
index.push({value : currentPage - 1, isEllipses: false});
index.push({value : currentPage, isEllipses: false});
index.push({value : currentPage + 1, isEllipses: false});
index.push({value : currentPage + 2, isEllipses: true});
}
else if (i == pageSize) {
index.push({value : i, isEllipses: false});
}
}
}
}
return index;
}
export {getButtonData, getButtonDataByPage};
</code></pre>
<p>I know the JS can be optimized a bit better I'm just not sure how.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T08:27:07.347",
"Id": "468026",
"Score": "1",
"body": "Welcome to CodeReview@SE. As is, the title of your question is too generic to be helpful. Heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[
{
"body": "<h1>Method Names</h1>\n\n<p>The most method names do not describe what the method really does and what the method name implies.</p>\n\n<ul>\n<li><code>getButtonData</code> let me imply that it returns information about one button</li>\n<li><code>getButtonDataByPage</code> the same like <code>getButtonData</code></li>\n<li><code>add</code> implies that something gets added to a collection</li>\n</ul>\n\n<p>In generell method names that start with <code>get</code> are known as <a href=\"https://guide.freecodecamp.org/java/getters-and-setters/\" rel=\"nofollow noreferrer\"><em>getter</em></a> and that they return values of an object that has no or less computation. The methods you provide starts with <code>get</code> but relay heavily on computation and do not return just a value.</p>\n\n<p>Names that would better fit are: <code>buildInitialButtonList</code>, <code>buildNavigatedButtonList</code> and <code>createButton</code>.</p>\n\n<h1>Hard to Read</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (pageSize > 10) {\n if (i < 6) {\n buttons.push(add(i, i == 1 ? true : false, true, false));\n }\n else if (pageSize >= 6 && i == 6) {\n buttons.push(add(i, i == 1 ? true : false, pageSize > 6 ? false : true, >pageSize > 6 ? true : false));\n }\n else if (i == pageSize) {\n buttons.push(add(i, false, true, false));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The code smells <a href=\"https://www.informit.com/articles/article.aspx?p=1392524\" rel=\"nofollow noreferrer\"><em>boolean flags</em></a> and <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\"><em>magic numbers</em></a> make your code hard to read an to maintain. </p>\n\n<p>Imagine you want to show only 3 instead 6 buttons: Alone in this small snipped you have to touch the code 5 times and in the whole code you provide 12 times.</p>\n\n<h1>Many Conditions</h1>\n\n<p>Beside the code smells you have many conditions. The 3 lines below contain 4 conditions:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>else if (pageSize >= 6 && i == 6) {\n buttons.push(add(i, i == 1 ? true : false, pageSize > 6 ? false : true, pageSize > 6 ? true : false));\n}\n</code></pre>\n</blockquote>\n\n<h1>Simplify Conditions</h1>\n\n<p>Some conditions follow the semantic of <code>condition ? true : false</code> which is the same as <code>condition</code>. For instance:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>buttons.push(add(i, i == 1 ? true : false, pageSize > 6 ? false : true, pageSize > 6 ? true : false))\n</code></pre>\n</blockquote>\n\n<p>Is the same as</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>buttons.push(add(i, i == 1, pageSize > 6, pageSize > 6))\n</code></pre>\n\n<h1>Useless Conditions</h1>\n\n<p>Let's analyze <code>getButtonData</code> and the same will be apply to <code>getButtonDataByPage</code>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>else if (... && i == 6) {\n buttons.push(add(i, i == 1 ? true : false, ..., ...));\n}\n</code></pre>\n</blockquote>\n\n<p>We first check if <code>(i == 6)</code> and if this is true we check if <code>i == 1</code> which will always be false:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>else if (... && i == 6) {\n buttons.push(add(i, false, ..., ...));\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (pageSize > 10) {\n if (...) {/* ... */}\n else if (pageSize >= 6 && i == 6) {\n buttons.push(add(..., ..., pageSize <= 6, pageSize > 6));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>First we make sure that <code>pageSize > 10</code> and than we check if <code>pageSize >= 6</code>, <code>pageSize <= 6</code> and <code>pageSize > 6</code>. Since we already know that <code>pageSize</code> is greater than 10 we can simplify to:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (pageSize > 10) {\n if (...) {/* ... */}\n else if (i == 6) {\n buttons.push(add(..., ..., true, true));\n }\n}\n</code></pre>\n\n<hr>\n\n<p>After the simplification:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (let i = 1; i <= pageSize; i++) {\n if (pageSize > 10) {\n if (i < 6) {\n buttons.push(add(i, i == 1, true, false));\n }\n else if (i == 6) {\n buttons.push(add(i, false, true, true));\n }\n else if (i == pageSize) {\n buttons.push(add(i, false, true, false));\n }\n }\n else {\n buttons.push(add(i, i == 1, true, false));\n }\n}\n</code></pre>\n\n<p>where <code>i == 1</code> can have its own branch:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (i === 1) {\n buttons.push(add(i, true, true, false))\n} else if (pageSize > 10) {\n if (i < 6) {\n buttons.push(add(i, false, true, false));\n } else if (i === 6) {\n buttons.push(add(i, false, true, true));\n } else if (i === pageSize) {\n buttons.push(add(i, false, true, false));\n }\n} else {\n buttons.push(add(i, false, true, false));\n}\n</code></pre>\n\n<p>Since only the first 6 button gets rendered we do not need to check for <code>pageSize > 10</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (i === 1) {\n buttons.push(add(i, true, true, false))\n} else if (i < 6) {\n buttons.push(add(i, false, true, false));\n} else if (i === 6) {\n buttons.push(add(i, false, true, true));\n} else if (i === pageSize) {\n buttons.push(add(i, false, true, false));\n}\n</code></pre>\n\n<p>and since the branch body of <code>i < 6</code> and <code>i === pageSize</code> are the same:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (i === 1) {\n buttons.push(add(i, true, true, false))\n} else if (i < 6 || i === pageSize) {\n buttons.push(add(i, false, true, false));\n} else if (i === 6) {\n buttons.push(add(i, false, true, true));\n}\n</code></pre>\n\n<h1>Builder Pattern</h1>\n\n<p>To go away from all the boolean flags you could create a <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder</a> and refactor the simplified version from above to something like: </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>const firstButton = new ButtonBuilder().withValue(1).disabled().visible().noPlaceholder();\nconst placeholder = new ButtonBuilder().enabled().visible().placeholder();\nconst button = new ButtonBuilder().enabled().visible().noPlaceholder();\nfor (let i = 1; i <= pageSize; i++) {\n if (i === 1) {\n buttons.push(firstButton);\n } else if (i < 6 || i === pageSize) {\n buttons.push(button.withValue(i).build());\n } else if (i === 6) {\n buttons.push(placeholder.withValue(i).build());\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>The Algorithm</h1>\n\n<p>In your example, you can page through 50 buttons, of which only 6 are required to render. For each button click you have to loop 50 times to render 6 buttons again.</p>\n\n<p>But actually you know directly which buttons are required to render without to loop 50 times. There are 3 cases:</p>\n\n<ul>\n<li>on the first to 5. button : <code>1, 2, 3, 4, 5 ... 50</code></li>\n<li>on button between 6. to 50.: <code>1, ... 6, [7], 8, ..., 50</code></li>\n<li>on button 47. to 50.: <code>1, ... 47, 48, [49], 50</code></li>\n</ul>\n\n<p>some pseudo code:</p>\n\n<pre><code>function buildPagination(current) {\n if (current < 6) {\n const pagination = [\n button(1),\n button(2),\n button(3),\n button(4),\n button(5),\n placeholder(),\n button(last),\n ];\n pagination[current].disable();\n return pagination;\n }\n\n if (current > (last - 4)) {\n const pagination = [\n button(1),\n placeholder(),\n button(last - 4),\n button(last - 3),\n button(last - 2),\n button(last - 1),\n button(last),\n ];\n pagination[current].disable();\n return pagination;\n }\n\n return [\n button(1),\n placeholder(),\n button(current - 1),\n button(current).disable(),\n button(current + 1),\n placeholder(),\n button(last),\n ];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T19:34:42.993",
"Id": "238687",
"ParentId": "238655",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238687",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T05:33:24.157",
"Id": "238655",
"Score": "1",
"Tags": [
"javascript",
"pagination"
],
"Title": "How can I optimize my pagination code?"
}
|
238655
|
<p>I have some files such as <code>.\image_1_01.bmp</code> that will be created elsewhere. I am then moving these files to an output directory. If any are missing I inform the user that it's missing and instruct them to check the logs.</p>
<p>Given how similar all the code is, can I make this code shorter?</p>
<pre><code>if not os.path.exists(".\image_1_01.bmp"):
print('image_1_01.bmp not generated\n' 'for more info check the log file' )
return 1
else:
shutil.move(".\image_1_01.bmp", output_directory)
if not os.path.exists(".\image_1_01.raw"):
print('image_1_01.raw not generated\n' 'for mor info check the log file' )
return 1
else:
shutil.move(".\image_1_01.raw", output_directory)
if not os.path.exists(".\image_1_01_hist.csv"):
print('image_1_01_hist.csv not generated\n' 'for mor info check the log file' )
return 1
else:
shutil.move(".\image_1_01_hist.csv", output_directory)
if not os.path.exists(".\image_1_02.bmp"):
print('image_1_02.bmp not generated\n' 'for more info check the log file' )
return 1
else:
shutil.move(".\image_1_02.bmp", output_directory)
if not os.path.exists(".\image_1_02.raw"):
print('image_1_02.raw not generated\n' 'for mor info check the log file' )
return 1
else:
shutil.move(".\image_1_02.raw", output_directory)
if not os.path.exists(".\image_1_02_hist.csv"):
print('image_1_02_hist.csv not generated\n' 'for mor info check the log file' )
return 1
else:
shutil.move(".\image_1_02_hist.csv", output_directory)
if not os.path.exists(".\scan_stats.csv"):
print('scan_stats.csv not generated\n' 'for mor info check the log file' )
return 1
else:
shutil.move(".\scan_stats.csv", output_directory)
if retcode != 0:
sys.exit(1)
else:
print("Test case is not suitable for your configuration")
sys.exit(2)
if __name__ == '__main__':
exit( generic() )<span class="math-container">`</span>
</code></pre>
|
[] |
[
{
"body": "<p>You are right in that most of your code is very similar, except for the file that you are checking. Since only a small part of the code changes, and the same actions are made at every step, this asks for a loop that iterates over the different files that you want to check:</p>\n\n<pre><code>paths_to_check = [\".\\image_1_01.bmp\", \".\\image_1_01.raw\", \".\\image_1_01_hist.csv\", \".\\image_1_02.bmp\", \".\\image_1_02.raw\", \".\\image_1_02_hist.csv\", \".\\scan_stats.csv\"]\n\nfor p in paths_to_check:\n if not os.path.exists(p):\n print(p + 'not generated\\n' 'for mor info check the log file' )\n return 1\n else:\n shutil.move(p, output_directory)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:49:51.063",
"Id": "468070",
"Score": "0",
"body": "Welcome to Code Review. Please note, questions that don't have enough context about how the code/output is used are off-topic on this site (and hence why the post was closed). If the OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T16:17:13.373",
"Id": "468074",
"Score": "0",
"body": "Allright, thanks. Should I delete this answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:17:39.850",
"Id": "468077",
"Score": "2",
"body": "I'd say leave it for now. The question isn't \"crap\" like the meta post describes and thus there likely wouldn't be a push for it to be deleted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T10:00:35.280",
"Id": "238664",
"ParentId": "238658",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T06:58:40.990",
"Id": "238658",
"Score": "2",
"Tags": [
"python"
],
"Title": "Moving files to an output directory, with instructions on missing files"
}
|
238658
|
<p>I have solved the 3rd day puzzle of Advent of Code but wanted some feedback on my solution. The puzzle <a href="https://adventofcode.com/2019/day/3" rel="nofollow noreferrer">here</a> wants to find where two jumbled wires intersect closest to the origin. </p>
<p>Puzzle input is provided like so: <code>R8,U5,L5,D3</code> representing the path of each string. Part A of the puzzle asks you to find the closest intersection to the origin calculated by Manhattan distance, and part B looks for the intersection that is the fastest path for both strings. </p>
<p>My solution was to store every point visited by each wire and use that path to then locate the closest or fastest intersection: </p>
<pre><code># frozen_string_literal: true
data = File.read('day3.txt').split("\n")
direction_code_arrays = data.map { |string_path| string_path.split(',') }
def calculate_path(direction_code_array)
path = [[0, 0]]
direction_code_array.each do |direction_code|
direction = direction_code.slice(0, 1)
number = direction_code.slice(1..-1).to_i
while number.positive?
prev_position = path.last
new_position = Array.new(2, 0)
new_position[0] = prev_position[0]
new_position[1] = prev_position[1]
case direction
when 'R'
new_position[0] += 1
when 'L'
new_position[0] -= 1
when 'U'
new_position[1] += 1
when 'D'
new_position[1] -= 1
end
number -= 1
path << new_position
end
end
path
end
def intersection_points(path1, path2)
intersections = path1 & path2
# origin at (0,0) should be excluded
intersections.slice(1..-1)
end
def manhattan_distance(point)
point[0].abs + point[1].abs
end
def number_steps_to_point(point, path1, path2)
path1.find_index(point) + path2.find_index(point)
end
def shortest_manhattan_distance(path1, path2)
shortest_distance = nil
intersection_points = intersection_points(path1, path2)
intersection_points.each do |intersection|
if shortest_distance.nil? || manhattan_distance(intersection) < shortest_distance
shortest_distance = manhattan_distance(intersection)
end
end
shortest_distance
end
def fastest_intersection_point(path1, path2)
fastest_point = nil
intersection_points = intersection_points(path1, path2)
intersection_points.each do |intersection|
if fastest_point.nil? || number_steps_to_point(intersection, path1, path2) < fastest_point
fastest_point = number_steps_to_point(intersection, path1, path2)
end
end
fastest_point
end
string_1_path = calculate_path(direction_code_arrays[0])
string_2_path = calculate_path(direction_code_arrays[1])
print shortest_manhattan_distance(string_1_path, string_2_path)
print fastest_intersection_point(string_1_path, string_2_path)
</code></pre>
<p>To my understanding the time complexity of this solution is <span class="math-container">\$\mathcal{O}(n)\$</span>, as each direction code in the array is iterated over once, while the space complexity is really poor as each code can generate hundreds of points in the path array. If anyone can explain the time and space complexity of my solution more clearly or offer any advice in optimizing I would very much appreciate it!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T07:18:26.767",
"Id": "468123",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please give 1) a definition of $n$ 2) a reference about the resource consumption of Ruby's *array &* operator."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T10:14:33.373",
"Id": "238665",
"Score": "1",
"Tags": [
"performance",
"ruby"
],
"Title": "Advent of Code Day 3, how to optimize my ruby solution?"
}
|
238665
|
<p>I am trying to create a custom hash from a table. <code>User</code> has many <code>transactions</code>. A transaction has a <code>member_id</code>, <code>company_id</code>, <code>contribution</code>s. I am trying to create a custom hash which contains transactions(contributions) happened through a member_id to a company.</p>
<pre><code> {
member_id: {
company: {
id: "",
name: ""
},
transactions: [
{
particulars: "",
contribution: {
contribution1: "",
contribution2: ""
}
}
]
}
}
</code></pre>
<p>I can simply use </p>
<pre><code>transactions.group(:member_id, :company_id).count
</code></pre>
<p>to get the count, but unable to list the transactions grouped to them(Are there any ways?). So i am grouping transaction using group_by(&:member_id) and looping through the hash to generate a hash to my requirement.</p>
<p>Can any one review the bellow code and suggest better way to do this?</p>
<pre><code>user = User.find_by(id: 123)
return {} unless user
transactions = user.transactions
return {} unless transactions.present?
data = {}
transactions.group_by(&:member_id).each do |key, value|
transactions = []
company = {}
value.each do |record|
company['id'] = record.company_id
company['name'] = record.company_name
particulars = record.particulars
contribution = {}
contribution['contribution1'] = record.contribution1
contribution['contribution2'] = record.contribution2
details = { "particulars": particulars, "contribution": contribution }
transactions << details
end
data[key] = { "company": company, "transactions": transactions }
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:10:10.537",
"Id": "468066",
"Score": "0",
"body": "@BCdotWEB updated. Thanks."
}
] |
[
{
"body": "<p>It sounds like you're trying to group transactions by <code>member_id</code> and <code>company_id</code>, though in the code you posted you are only grouping by <code>member_id</code> and then overwriting the <code>company</code> with each new transactions' company.</p>\n\n<p>If you pass a block to <code>group_by</code>, though, you can group by more than a simple method on the object, for instance you can group by an array of attributes that match, such as:</p>\n\n<pre><code>transactions.group_by { |transaction| [transaction.member_id, transaction.company_id] }\n</code></pre>\n\n<p>and then you still have to loop through and format the transactions how you want, but you can clean that up as well, by using <code>map</code> and <code>each_with_object</code>:</p>\n\n<pre><code>transactions.\n group_by { |transaction| [transaction.member_id, transaction.company_id] }.\n each_with_object({}) do |((member_id, _), transactions), data|\n data[member_id] = {\n # no need to keep rebuilding the company hash, all transactions belong to\n # the same company\n company: { id: transactions.first.company_id,\n name: transactions.first.company_name },\n transactions: transactions.map do |transaction|\n { \n particulars: transaction.particulars,\n contribution: { contribution1: transaction.contribution1,\n contribution2: transaction.contribution2 }\n }\n end\n }\n end\n</code></pre>\n\n<p>This can be cleaned up even more, by moving the generation of these hashes to presenters but that's just moving the code around at this point, regardless you still need to go through all the transactions and present them as the hash, so the loop is unavoidable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T02:03:02.753",
"Id": "239299",
"ParentId": "238668",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T12:31:00.840",
"Id": "238668",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "custom hash from group_by hash"
}
|
238668
|
<p>I have two dictionaries and a merged dictionary:</p>
<pre><code>dict1 = {-3: 0.3, -2: 0.1, 1: 0.8}
dict2 = {0: 0.3, 1: 0.5, -1: 0.7}
dict_merged = {}
</code></pre>
<p>I have code that basically merges the two together by adding keys together and multiplying values:
e.g.</p>
<pre><code>for k1, v1 in dict1.items():
for k2, v2 in dict2.items():
new_key = k1 + k2
if new_key in dict_merged:
dict_merged[new_key] += v1 * v2
else:
dict_merged[new_key] = v1 * v2
</code></pre>
<p>Is there a faster way to do this, it feels like there should but dict comprehension doesn't seem helpful here. In the above example, we are going to get several contributes to the key "-3" for example.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T01:59:19.210",
"Id": "468113",
"Score": "1",
"body": "Be advised that in Python<3.7 the order of the keys are not guaranteed. Your code might work in your PC, but in someone else's might break horribly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T11:46:17.623",
"Id": "468143",
"Score": "2",
"body": "@pepoluan strange advice, since the code here doesn't require the dictionaries to be sorted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:28:59.540",
"Id": "468153",
"Score": "0",
"body": "@sanyash What do you mean either 0.09 or 0.07, the code clearly outputs 0.16."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T11:34:19.197",
"Id": "469470",
"Score": "0",
"body": "@Peilonrayz ahh okay I misread the code somehow. My bad."
}
] |
[
{
"body": "<p>It's standard to indent Python with 4 spaces. Not following this standard only makes your life and the life of people that have to interact with you harder.</p>\n\n<p>You can just use the optional default argument to <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>dict.get</code></a> to remove the need for the <code>if</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for k1, v1 in dict1.items():\n for k2, v2 in dict2.items():\n key = k1 + k2\n dict_merged[key] = v1 * v2 + dict_merged.get(key, 0)\n</code></pre>\n\n<p>Alternately you can change <code>dict_merged</code> to a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>, rather than a <code>dict</code>. This removes the need to use <code>dict.get</code>, and allows you to just us <code>+=</code>.\n<code>defaultdict</code> takes a function that provides the default value to use. Since <a href=\"https://docs.python.org/3/library/functions.html#int\" rel=\"nofollow noreferrer\"><code>int()</code> returns <code>0</code></a>, we can just pass <code>int</code> as the function. As noted by <a href=\"https://codereview.stackexchange.com/users/9012/ilmari-karonen\">Ilmari Karonen</a> you can also use <code>float</code> as that returns <code>0.0</code> without any arguments.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\ndict_merged = collections.defaultdict(int)\nfor k1, v1 in dict1.items():\n for k2, v2 in dict2.items():\n dict_merged[k1 + k2] += v1 * v2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T16:58:36.553",
"Id": "468076",
"Score": "1",
"body": "Thank you very much! I didn't know you could default a get value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:35:03.220",
"Id": "468179",
"Score": "0",
"body": "[`float` with no arguments also returns 0.0](https://docs.python.org/3/library/functions.html#float) and would probably be a more appropriate default factory for the OP, since their actual values all seem to be floats."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:57:39.590",
"Id": "468184",
"Score": "2",
"body": "I really wouldn't recommend defaultdict (at least without changing it back into a normal dict), since later on when you actually use it, you'll get 0 instead of a key error when you try to get something that's not there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:07:54.150",
"Id": "468185",
"Score": "0",
"body": "@Noctiphobia I've used `defaultdict` plenty of times, and haven't experienced that issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:06:28.970",
"Id": "468197",
"Score": "0",
"body": "I agree with @Noctiphobia. defaultdict seem overkill for that problem and can lead to many problems down the line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T18:03:13.557",
"Id": "468206",
"Score": "0",
"body": "@Peilonrayz You won't necessarily run into this issue, and sometimes it's really the desired behavior (which is the main use case for `defaultdict`), but in this case I see no indication that this is the desired behavior. And while you might not run into this issue (for example you'd never get a key error to begin with), it also may happen. In my experience, that's been a source of bugs in multiple cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T18:10:28.437",
"Id": "468208",
"Score": "1",
"body": "@Cal And that's why I provided two alternates..."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T16:30:29.647",
"Id": "238678",
"ParentId": "238677",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "238678",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T16:02:34.077",
"Id": "238677",
"Score": "7",
"Tags": [
"python",
"performance",
"python-3.x",
"hash-map"
],
"Title": "Merging two dictionaries together whilst adding keys but multiplying values"
}
|
238677
|
<p>Can I do it with a lower Big O / better code? How can I improve this solution?</p>
<p><strong>Task:</strong></p>
<p>Let's assume we have a array like this:</p>
<blockquote>
<p>1 0 0 1 0</p>
<p>0 0 0 0 0</p>
<p>0 0 0 1 0</p>
<p>0 0 0 0 0</p>
<p>1 0 0 0 0</p>
</blockquote>
<p>In each turn, '1's are propagated to the neighbors(left, top, right, bottom). Return number of turns after which the whole grid will be filled with '1's.</p>
<p>Example of the above:</p>
<p><strong>After turn 1</strong>(bold - a new '1' in the last turn):</p>
<blockquote>
<p>1 <strong>1</strong> <strong>1</strong> 1 <strong>1</strong></p>
<p><strong>1</strong> 0 0 <strong>1</strong> 0</p>
<p>0 0 <strong>1</strong> 1 <strong>1</strong></p>
<p><strong>1</strong> 0 0 <strong>1</strong> 0</p>
<p>1 <strong>1</strong> 0 0 0</p>
</blockquote>
<p><strong>After turn 2</strong>:</p>
<blockquote>
<p>1 1 1 1 1 </p>
<p>1 <strong>1 1</strong> 1 <strong>1</strong></p>
<p><strong>1 1</strong> 1 1 1</p>
<p>1 1 <strong>1 1</strong> 1</p>
<p>1 <strong>1 1</strong> 1 0</p>
</blockquote>
<p><strong>After turn 3</strong>:</p>
<blockquote>
<p>1 1 1 1 1</p>
<p>1 1 1 1 1</p>
<p>1 1 1 1 1</p>
<p>1 1 1 1 1</p>
<p>1 1 1 1 <strong>1</strong></p>
</blockquote>
<p><strong>Result: 3</strong></p>
<p><strong>My approach:</strong></p>
<ol>
<li>Collect all '1'</li>
<li>For each saved '1' propagate to all neighbors that are '0' and save newly propagated</li>
<li>Repeat 2 till nothing new appear</li>
<li>Return number of turns/generations</li>
</ol>
<p><strong>What is the Big O?</strong></p>
<p>R - rows</p>
<p>C - columns</p>
<p>I would assume. R*C(initial discover of '1') + 4*R*C(because each number will check ones all the neighbors) = 5*R<em>C = R</em>C</p>
<p>I think it is R*C and it is linear. Am I correct?</p>
<p>My code(the main method contains 4 additional examples):</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Console.WriteLine(MinimumGenerations(2, 2, new int[2,2] { { 1, 0 }, { 0, 0 } }));//result 2
Console.WriteLine(MinimumGenerations(3, 3, new int[3,3] { { 1, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }));//result 4
Console.WriteLine(MinimumGenerations(1, 1, new int[1, 1] { { 0 } }));//result -1
Console.WriteLine(MinimumGenerations(1, 1, new int[1, 1] { { 1 } }));//result 0
Console.ReadKey();
}
public static int MinimumGenerations(int rows, int columns, int[,] grid)
{
var toPropagate = InitialPointsToPropagate(rows, columns, grid);
if(toPropagate.Count == 0)//whole grid was filled with '0'
{
return -1;
}
if(toPropagate.Count == rows * columns)//whole grid was filled with '1'
{
return 0;
}
var generation = 0;
do
{
var toPropagateInNextGeneration = PropagateAllPoints(rows, columns, grid, toPropagate);
if (toPropagateInNextGeneration.Any())
{
generation++;
toPropagate = toPropagateInNextGeneration;
}
} while (toPropagate.Count > 0);
return generation;
}
private static Queue<CustomPoint> PropagateAllPoints(int rows, int columns, int[,] grid, Queue<CustomPoint> toPropagate)
{
var toPropagateInNextGeneration = new Queue<CustomPoint>();
while(toPropagate.Count > 0)
{
var pointToProcess = toPropagate.Dequeue();
if(EmptyBottom(rows, grid, pointToProcess))
{
var newPoint = new CustomPoint(pointToProcess.Column, pointToProcess.Row + 1);
grid[newPoint.Row, newPoint.Column] = 1;
toPropagateInNextGeneration.Enqueue(newPoint);
}
if(EmptyLeft(grid, pointToProcess))
{
var newPoint = new CustomPoint(pointToProcess.Column - 1, pointToProcess.Row);
grid[newPoint.Row, newPoint.Column] = 1;
toPropagateInNextGeneration.Enqueue(newPoint);
}
if(EmptyRight(columns, grid, pointToProcess))
{
var newPoint = new CustomPoint(pointToProcess.Column + 1, pointToProcess.Row);
grid[newPoint.Row, newPoint.Column] = 1;
toPropagateInNextGeneration.Enqueue(newPoint);
}
if(EmptyTop(grid, pointToProcess))
{
var newPoint = new CustomPoint(pointToProcess.Column, pointToProcess.Row - 1);
grid[newPoint.Row, newPoint.Column] = 1;
toPropagateInNextGeneration.Enqueue(newPoint);
}
}
return toPropagateInNextGeneration;
}
private static Queue<CustomPoint> InitialPointsToPropagate(int rows, int columns, int[,] grid)
{
var toPropagate = new Queue<CustomPoint>();
for (var row = 0; row < rows; row++)
{
for(var column = 0; column < columns; column++)
{
if(grid[row, column] == 1)
{
toPropagate.Enqueue(new CustomPoint(column, row));
}
}
}
return toPropagate;
}
private static bool EmptyRight(int columns, int[,] grid, CustomPoint point)
{
return point.Column<columns - 1 && grid[point.Row, point.Column + 1] == 0;
}
private static bool EmptyLeft(int[,] grid, CustomPoint point)
{
return point.Column > 0 && grid[point.Row, point.Column - 1] == 0;
}
private static bool EmptyBottom(int rows, int[,] grid, CustomPoint point)
{
return point.Row < rows - 1 && grid[point.Row + 1, point.Column] == 0;
}
private static bool EmptyTop(int[,] grid, CustomPoint point)
{
return point.Row > 0 && grid[point.Row - 1, point.Column] == 0;
}
}
internal struct CustomPoint
{
public int Row { get; }
public int Column { get; }
public CustomPoint(int column, int row)
{
Row = row;
Column = column;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just one remark: do not copy-paste code and then change one tiny bit of it. This indicates that you should create a method. What I mean is this:</p>\n\n<pre><code>var newPoint = new CustomPoint(pointToProcess.Column, pointToProcess.Row + 1);\ngrid[newPoint.Row, newPoint.Column] = 1;\ntoPropagateInNextGeneration.Enqueue(newPoint);\n</code></pre>\n\n<p>Those three lines are always the same, except the values of the parameters used in the <code>CustomPoint</code> constructor.</p>\n\n<p>I'd create a <code>AllPointsPropagator</code> like this:</p>\n\n<pre><code>internal class AllPointsPropagator\n{\n private static readonly Queue<CustomPoint> ToPropagateInNextGeneration = new Queue<CustomPoint>();\n\n public static Queue<CustomPoint> Execute(int rows, int columns, int[,] grid, Queue<CustomPoint> toPropagate)\n {\n while (toPropagate.Count > 0)\n {\n var pointToProcess = toPropagate.Dequeue();\n if (EmptyBottom(rows, grid, pointToProcess))\n {\n AddNewPoint(grid, pointToProcess.Column, pointToProcess.Row + 1);\n }\n\n if (EmptyLeft(grid, pointToProcess))\n {\n AddNewPoint(grid, pointToProcess.Column - 1, pointToProcess.Row);\n }\n\n if (EmptyRight(columns, grid, pointToProcess))\n {\n AddNewPoint(grid, pointToProcess.Column + 1, pointToProcess.Row);\n }\n\n if (EmptyTop(grid, pointToProcess))\n {\n AddNewPoint(grid, pointToProcess.Column, pointToProcess.Row - 1);\n }\n }\n\n return ToPropagateInNextGeneration;\n }\n\n private static void AddNewPoint(int[,] grid, int column, int row)\n {\n var newPoint = new CustomPoint(column, row);\n grid[newPoint.Row, newPoint.Column] = 1;\n ToPropagateInNextGeneration.Enqueue(newPoint);\n }\n</code></pre>\n\n<p>The four <code>Empty*</code> methods should also move to this class. Now <code>PropagateAllPoints()</code> can be replaced by <code>AllPointsPropagator.Execute(rows, columns, grid, toPropagate);</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:17:46.867",
"Id": "468178",
"Score": "0",
"body": "Good point with separate AddNewPoint(). I did that before but when I was running a performance test the average time for some reason was slower. I assumed it was correlated with stack calls. Here I don't see the difference. \nI like the idea of a separate class. I didn't think about it for a task like this. I will next time. \n\nThere is one small mistake in the code you provided. After 1st turn ToPropagateInNextGeneration and toPropagate are the same stack.\n1st line in Execute() method should be:\nToPropagateInNextGeneration = new Queue<CustomPoint>();\nand that field should not be readonly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:51:42.083",
"Id": "468182",
"Score": "0",
"body": "@Egnever Yeah, the code is more like proof of concept than actual production code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:03:51.887",
"Id": "238708",
"ParentId": "238680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T16:51:49.603",
"Id": "238680",
"Score": "2",
"Tags": [
"c#",
"performance",
"programming-challenge",
"array",
"interview-questions"
],
"Title": "Propagation in grid"
}
|
238680
|
<p>Use cases Messaging app between two users.</p>
<p>GameMain is for multithreading application refers to SendMessageWrokers.java</p>
<p>Only 2 user need to be defined and message app needs to finalize after a restriced amount of message count.</p>
<p>GameMain.java</p>
<pre><code>package org.nb;
import java.util.List;
import java.util.concurrent.*;
public class GameMain{
public final static int MESSAGE_LIMIT = 10;
Player initiator = new Player(0,"Initiator",true);
Player player = new Player(1,"Receiver");
SendMessageWorker messageWorker;
public GameMain(){
Player[] players =new Player[2];
players[0] = initiator;
players[1] = player;
}
public static void main(String[] args) {
GameMain gameMain = new GameMain();
gameMain.startGame();
}
public void startGame(){
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Shutdown Hook is running, Application Terminating")));
Integer counter = 0;
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(10);
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue);
while (true) {
counter++;
messageWorker = new SendMessageWorker(counter.toString(),"Sending a new message ",initiator,player);
executorService.submit(messageWorker);
if (counter >= MESSAGE_LIMIT) {
break;
}
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
}
Conversation conversation = initiator.getConversationHashMap(player.getId());
List<Message> messageList = conversation.getConversation();
for(Message message : messageList){
System.out.println("Message : " + message.getContent() + " - Date :" + message.getDate() +
"- Sender " + message.getSender().getName() + "- Receiver " + message.getReceiver().getName() );
}
System.out.println("Application Terminating ...");
}
}
</code></pre>
<p>Conversation.java</p>
<pre><code>package org.nb;
import java.util.ArrayList;
public class Conversation {
private Player participants[];
private ArrayList<Message> conversation = new ArrayList<>();
public Conversation(Player player1 , Player player2){
participants = new Player[2];
this.participants[0] = player1;
this.participants[1] = player2;
}
void addMessage(Message message){
conversation.add(message);
}
public ArrayList<Message> getConversation() {
return conversation;
}
}
</code></pre>
<p>Message.java</p>
<pre><code>package org.nb;
import java.util.Date;
public class Message {
private String content;
private Player sender;
private Player receiver;
private Date date;
private Boolean ack = false;
public Message(String content, Player player, Player toPlayer) {
this.content = content;
this.sender = player;
this.receiver = toPlayer;
this.date = new Date();
}
public Message(String content, Player player, Player toPlayer,Boolean ack) {
this.content = content;
this.sender = player;
this.receiver = toPlayer;
this.date = new Date();
this.ack = ack;
}
public String getContent() {
return content;
}
public Player getSender() {
return sender;
}
public Player getReceiver() {
return receiver;
}
public Date getDate() {
return date;
}
}
</code></pre>
<p>Player.java</p>
<pre><code>package org.nb;
import java.util.HashMap;
public class Player {
private int id;
private String name;
private boolean initiator = false;
private HashMap<Integer,Conversation> conversationHashMap = new HashMap<>();
public Player(int id,String name, boolean initiator){
this.id=id;
this.name=name;
this.initiator=initiator;
}
public Player(int id, String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public boolean isInitiator() {
return initiator;
}
public Conversation getConversationHashMap(int id) {
return conversationHashMap.get(id);
}
public void setConversationHashMap(Integer playerId, Conversation conversation) {
this.conversationHashMap.put(playerId, conversation);
}
}
</code></pre>
<p>SendWorkerMessage.java</p>
<pre><code>package org.nb;
public class SendMessageWorker implements Runnable {
private String name = "SendMessageTask";
String content;
Player initiator;
Player receiver;
private String counter;
public SendMessageWorker (String counter,String content,Player initiator, Player receiver) {
this.counter = counter;
this.content = content;
this.initiator = initiator;
this.receiver = receiver;
}
@Override
public void run() {
if (initiator.isInitiator() == false) {
System.out.println("Only initiator can send message");
return;
}
Conversation conversation = initiator.getConversationHashMap(receiver.getId());
if (conversation == null) {
conversation = new Conversation(initiator, receiver);
}
Message message = new Message(content, initiator, receiver);
conversation.addMessage(message);
Message messageAck = new Message(content.concat(String.valueOf("_" + counter)), receiver, initiator, true);
conversation.addMessage(messageAck);
initiator.setConversationHashMap(receiver.getId(), conversation);
receiver.setConversationHashMap(initiator.getId(), conversation);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T01:27:07.487",
"Id": "468112",
"Score": "1",
"body": "Note that this is one of these assignments where I'm missing information. The message number seems to appear out of nothing, and there is no indication on how the system needs to shutdown (which is kinda important if you have two *processes* specifically). Basically you need some kind of message that indicates the shutdown to happen. Over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:03:40.827",
"Id": "468114",
"Score": "0",
"body": "I was looking for a better method manage gracefully shutdown. I have added shutDownHook and counter limit. Do you recommend to changing message context itself ?"
}
] |
[
{
"body": "<h2>Design</h2>\n\n<p>The design is OK; it seems to use data classes and some classes that perform operations.</p>\n\n<p>In true OO fashion, I would expect the player to send the message. For instance, you could do <code>Player.sendMessageTo(int otherPlayerID, String message)</code>. You could initialize the player with a <code>MessageHandler</code> that does the actual sending of the message. The player then can keep a list of conversations with other player(s). That way you can hide much of the technical details from the \"game\". Similarly, you can have a <code>Player.receiveAcknowledgement</code> that is triggered by the same <code>MessageHandler</code>.</p>\n\n<h2>Code review</h2>\n\n<p><strong>GameMain</strong></p>\n\n<pre><code>public final static int MESSAGE_LIMIT = 10;\nPlayer initiator...\n</code></pre>\n\n<p>I'd always separate the constant values and the fields using an empty line.</p>\n\n<pre><code>Player initiator = new Player(0,\"Initiator\",true);\n</code></pre>\n\n<p>This is why you don't use boolean parameters: it is completely unclear what <code>true</code> does here when browsing through the code. Instead, use an enum <code>PlayerType</code> with values <code>INITIATOR</code> and <code>RECEIVER</code>. Note that you could now do away with the name - unless you want to have multiple receivers.</p>\n\n<p>A less intrusive refactor would be to use a constant <code>INITIATOR = true</code> to be used. This has the disadvantage that other developers overlook the constant though (for <code>Cipher.getInstance</code> in Java I keep seeing <code>Cipher.getInstance(1, ...)</code> instead of <code>Cipher.getInstance(Cipher.ENCRYPT_MODE)</code>).</p>\n\n<p>Consider maybe not numbering players, but using the name itself as ID (using a <code>HashMap<String, Player> nameToPlayer</code>, for instance). Generally you want to avoid having fields that have a similar function.</p>\n\n<pre><code>Integer counter = 0;\n</code></pre>\n\n<p>Always prefer basic types: <code>int counter = 0</code>. Auto-boxing will take care of the rest.</p>\n\n<pre><code>BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(10);\n\nExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue);\n</code></pre>\n\n<p>Why 10, 1, 1 and 0L? You need to use well named constant values here.</p>\n\n<pre><code>messageWorker = new SendMessageWorker(counter.toString(),\"Sending a new message \",initiator,player);\n</code></pre>\n\n<p>I'd try and not stringify before it is necessary. Just use the <code>counter</code> as parameter. Don't forget your code style, and add spaces after the commas. Note that you can use <code>Integer.toString(int)</code> to convert; no need to box it.</p>\n\n<pre><code>if (counter >= MESSAGE_LIMIT) {\n break;\n}\n</code></pre>\n\n<p>I've got nothing against <code>while (true) { ... if (condition) break ...}</code> <em>in principle</em> but why not just a <code>for</code> loop here?</p>\n\n<pre><code>Conversation conversation = initiator.getConversationHashMap(player.getId());\n</code></pre>\n\n<p>As reader I would expect to get a <code>HashMap</code> here, not a specific object. Furthermore, it is not clear to me what a \"conversation hash map\" <strong>is</strong>.</p>\n\n<pre><code>List<Message> messageList = conversation.getConversation();\n</code></pre>\n\n<p>Hmm, that's slightly weird, get a conversation from a conversation. <code>getMessages</code> maybe?</p>\n\n<p><strong>Conversation</strong></p>\n\n<p>I would expect a <em>list</em> of players. Try and avoid arrays, the are not very OO.</p>\n\n<p>Then you would get:</p>\n\n<pre><code>public Conversation(Player ... players){\n participants = List.of(players);\n}\n</code></pre>\n\n<p>and note that the actual constructor call is <em>not even changed</em>.</p>\n\n<pre><code>public ArrayList<Message> getConversation() {\n return conversation;\n}\n</code></pre>\n\n<p>Try and avoid to expose the state of an object instance, you're failing to encapsulate the field. Return either an iterator or return <code>Collections.unmodifiableList(conversation)</code>.</p>\n\n<p><strong>Message</strong></p>\n\n<pre><code>private Boolean ack = false;\n</code></pre>\n\n<p><code>ack</code> will automatically be assigned <code>false</code>. <code>ack</code> is never read, and it is again an object instance rather than <code>boolean</code>.</p>\n\n<p><code>Date</code> should preferably not be used; try and use <code>Instant.now()</code> instead (and possibly also include a clock as parameter, for testing purposes).</p>\n\n<pre><code>public Conversation getConversationHashMap(int id) {\n return conversationHashMap.get(id);\n}\n</code></pre>\n\n<p>You probably refactored this, but forgot to change the name of the method. <code>getConversationFromHashMap</code> would be better, but it would expose the inner workings of the class. <code>getConversationWithPlayer(int id)</code> is probably best.</p>\n\n<p>Note that because <code>Conversation</code> is not immutable, the returned value again exposes state.</p>\n\n<p><strong>SendMessageWorker</strong></p>\n\n<pre><code>if (initiator.isInitiator() == false) {\n System.out.println(\"Only initiator can send message\");\n return;\n}\n</code></pre>\n\n<p><strong>Never</strong> keep running with invalid state. <em>Bad programmer</em>. Down (the application)! </p>\n\n<p>If you should not get into such a state: <code>throw new IllegalStateException(\"Only initiator can send message\")</code>.</p>\n\n<pre><code>if (conversation == null) {\n conversation = new Conversation(initiator, receiver);\n}\n</code></pre>\n\n<p>Ugh, don't do this. Either use an empty conversation and intialize in the object, or - if that's too expensive - lazily instantiate a conversation.</p>\n\n<p>Note that this is resolved if you let the user keep track of their own conversation(s). A good design will lead you into fewer traps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T00:53:16.357",
"Id": "468110",
"Score": "1",
"body": "As a first question. Do you recommend to \"MessageHandler\" as a Runnable Thread still? And initialize the Player ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T01:02:08.490",
"Id": "468111",
"Score": "1",
"body": "In my scheme I guess it makes more sense to control the players using a thread. The message handler can simply sync on the blocking queue. Hopefully, that will also make it easier to do something using two processes. I would introduce a different class for that though. What about \"Puppeteer\" ? ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T22:03:23.853",
"Id": "238691",
"ParentId": "238681",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T17:30:05.017",
"Id": "238681",
"Score": "5",
"Tags": [
"java",
"multithreading"
],
"Title": "Multithreaded Message Game"
}
|
238681
|
<p>I have an input hook that is reusable in other input fields. These input fields have onChange functions that are dispatched by redux.</p>
<p>My question is, is the following code considered a react hook?</p>
<p><strong>handleHook.tsx</strong></p>
<pre><code>import React, { useState } from "react";
export const InputHook = (props) => {
const handleInputChange = (event) => {
if (event.target.name === "title") {
props.addTitle(event.target.value);
}
if (event.target.name === "postContent") {
props.addContent(event.target.value);
}
if (event.target.name === "username") {
props.addUsername(event.target.value);
}
if (event.target.name === "email") {
props.addEmail(event.target.value);
}
if (event.target.name === "password") {
props.addPassword(event.target.value);
}
if (event.target.name === "passwordConf") {
props.addPasswordConf(event.target.value);
} else {
return null;
}
};
return {
handleInputChange,
};
};
</code></pre>
<p>And it is being used here, for example:</p>
<p><strong>register.tsx</strong></p>
<pre><code>import Typography from "@material-ui/core/Typography";
import React, { Component, Fragment } from "react";
import SignUpForm from "../forms/signUp/signUp";
import GridHoc from "../hoc/grid";
import IsAuth from "../hoc/isAuthenticated";
import { InputHook } from "./../common/handleHook";
export interface registerProps {
onChange: (event: any) => void;
signUpInit: (event: object, history: object) => void;
addUsername: (event: object) => void;
addEmail: (event: object) => void;
addPassword: (event: object) => void;
addPasswordConf: (event: object) => void;
user?: any;
history?: any;
}
export interface registerState {
passwordConf: string;
passErr: string;
}
function Register(registerProps: any) {
const { handleInputChange } = InputHook(registerProps);
const handleSubmit = (e: any) => {
e.preventDefault();
const { username, email, password, passwordConf } = registerProps.user;
const creds = {
username,
email,
password,
};
console.log(creds);
registerProps.signUpInit(creds, registerProps.history);
};
const { username, email, password, passwordConf, passwordConfError, usernameError, passwordError, emailError } = registerProps.user;
const isEnabled = passwordConfError === true && emailError === true && passwordError === true && usernameError === true ? false : true;
return (
<Fragment>
<Typography variant="h4" style={{ letterSpacing: "2px" }}>
Register
</Typography>
{registerProps.user.error && <div>{registerProps.user.error}</div>}
<SignUpForm
submit={handleSubmit}
usernameChange={handleInputChange}
emailChange={handleInputChange}
passwordChange={handleInputChange}
passwordConfChange={handleInputChange}
username={username}
password={password}
passwordConf={passwordConf}
email={email}
usernameError={usernameError}
passwordError={passwordError}
passwordConfError={passwordConfError}
emailError={emailError}
disButton={isEnabled}
/>
</Fragment>
);
}
export default GridHoc(IsAuth(Register));
</code></pre>
|
[] |
[
{
"body": "<p>It's a good idea to abstract this away. Otherwise you would end up with a lot of different callbacks. But I think your approach might be improved.</p>\n\n<p>First: why do you use different actions instead of simply handling the different events and input names inside a reducer? Now you have conditionals inside the hook and probably inside the reducer for the different actions as well, right? Moving everything to the reducer might simplify things.</p>\n\n<p>Having form state in the global redux state is btw not so great. It means that all your connected components might re-render on every input change. There are great solutions for handling forms in React like formik or react-form-hook. Latter gets a lot of traction currently</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:04:42.403",
"Id": "468283",
"Score": "0",
"body": "will look into your recommendations, but will leave this unanswered as this doesn't provide a code refactor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T12:35:16.567",
"Id": "238763",
"ParentId": "238684",
"Score": "2"
}
},
{
"body": "<p>I agree with the other answer from <a href=\"https://codereview.stackexchange.com/users/220135/jkettmann\"><em>@jkettmann</em></a> that you should abstract this. Generally speaking having a long list of if-else conditions usually has a better alternative.</p>\n\n<p>That could be a reducer like mentioned, or could just be an object map like:</p>\n\n<pre><code>const handlers = {\n title: addTitle,\n content: addContent,\n username: addUsername,\n email: addEmail,\n password: addPassword,\n passwordConf: addPasswordConf\n}\nconst { name } = event.target;\nif (!handlers.hasOwnProperty(name)) {\n return null;\n}\nreturn handlers[name](event.target.value);\n</code></pre>\n\n<p>I find it strange to be using the same handler to be calling different update methods (eg: <code>addTitle</code>). Forms are the ideal use case for a managing the state together in a reducer.</p>\n\n<p>You're not even using it properly inside <code>register.tsx</code> anyway:</p>\n\n<pre><code>usernameChange={handleInputChange}\nemailChange={handleInputChange}\npasswordChange={handleInputChange}\npasswordConfChange={handleInputChange}\n</code></pre>\n\n<p>You could use a form management hook/reducer library, but using custom reducers is extremely easy with React hooks:</p>\n\n<pre><code>const reducer = (state, event) => {\n return {\n ...state,\n [event.target.name]: event.target.value,\n }\n};\nconst [state, dispatch] = React.useReducer(reducer, {\n title: '',\n content: '',\n username: '',\n email: '',\n password: '',\n passwordConf: ''\n});\n...\n<Register\n handleInputChange={dispatch}\n user={state}\n...\n...\n<SignUpForm\n submit={handleSubmit}\n usernameChange={handleInputChange}\n</code></pre>\n\n<p>I'll try and answer your actual question as well:</p>\n\n<blockquote>\n <p><em>is the following code considered a react hook ?</em></p>\n</blockquote>\n\n<p>Your <code>InputHook</code> is structured like a hook but there's a few details that make it not 100% so.</p>\n\n<p>The React docs say hooks are defined by this definition:</p>\n\n<blockquote>\n <p>A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.\n <a href=\"https://reactjs.org/docs/hooks-custom.html#extracting-a-custom-hook\" rel=\"nofollow noreferrer\">Source</a></p>\n</blockquote>\n\n<p>Your hook both does not have <code>use</code> in front and doesn't call any other hooks. So really it's just a function imitating a hook.</p>\n\n<p>For example, this would become a hook if you used the <code>useCallback</code> hook inside your custom hook: (and made sure to name it with <code>use</code>)</p>\n\n<pre><code>export default function useInputChange(props) {\n const {\n addTitle,\n addContent,\n addUsername,\n addEmail,\n addPassword,\n addPasswordConf\n } = props;\n return React.useCallback((event) => {\n if (event.target.name === \"title\") {\n addTitle(event.target.value);\n }\n if (event.target.name === \"postContent\") {\n addContent(event.target.value);\n }\n if (event.target.name === \"username\") {\n addUsername(event.target.value);\n }\n if (event.target.name === \"email\") {\n addEmail(event.target.value);\n }\n if (event.target.name === \"password\") {\n addPassword(event.target.value);\n }\n if (event.target.name === \"passwordConf\") {\n addPasswordConf(event.target.value);\n } else {\n return null;\n }\n }, [addTitle, addContent, addUsername, addEmail, addPassword, addPasswordConf]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-05T04:00:44.017",
"Id": "470665",
"Score": "0",
"body": "thank you for this, appreciate the explanation, and refactor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:42:00.380",
"Id": "239686",
"ParentId": "238684",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239686",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T17:55:55.363",
"Id": "238684",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "React custom hook"
}
|
238684
|
<p><a href="https://leetcode.com/problems/network-delay-time/" rel="nofollow noreferrer">https://leetcode.com/problems/network-delay-time/</a></p>
<blockquote>
<p>There are N network nodes, labelled 1 to N.</p>
<p>Given times, a list of travel times as directed edges times[i] = (u,
v, w), where u is the source node, v is the target node, and w is the
time it takes for a signal to travel from source to target.</p>
<p>Now, we send a signal from a certain node K. How long will it take for
all nodes to receive the signal? If it is impossible, return -1.</p>
</blockquote>
<pre><code>Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2
</code></pre>
<p><a href="https://i.stack.imgur.com/9ylAr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ylAr.png" alt="enter image description here"></a></p>
<p>Please review for performance, I know I can solve this with Dijkstra's algorithm and Bellman ford.
I am still working on those. and will upload them for review.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Timers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://leetcode.com/problems/network-delay-time/
/// </summary>
[TestClass]
public class NetworkDelayTimeTest
{
[TestMethod]
public void ExampleTest()
{
int N = 4;
int K = 2;
int[][] times = { new[] { 2, 1, 1 }, new[] { 2, 3, 1 }, new[] { 3, 4, 1 } };
NetWorkDelayTimeDfs dfs = new NetWorkDelayTimeDfs();
Assert.AreEqual(2, dfs.NetworkDelayTime(times, N, K));
}
}
public class NetWorkDelayTimeDfs
{
private Dictionary<int, int> dist;
public int NetworkDelayTime(int[][] times, int N, int K)
{
var graph = new Dictionary<int, List<List<int>>>();
//we build a dictionary
// key = from vertex
// values - weight and destination
foreach (var edge in times)
{
if (!graph.TryGetValue(edge[0], out var temp))
{
temp = graph[edge[0]] = new List<List<int>>();
}
temp.Add(new List<int> {edge[2], edge[1]});
}
// we sort by the weight
foreach (var node in graph)
{
node.Value.Sort((a, b) => a[0] - b[0]);
}
// all the edges get max value
dist = new Dictionary<int, int>();
for (int i = 1; i <= N; i++)
{
dist.Add(i, int.MaxValue);
}
DFS(graph, K, 0);
// we compute the max distance.
// if one of the edges equals int.max
// we can't reach it so we return -1;
int ans = 0;
foreach (var cand in dist.Values)
{
if (cand == int.MaxValue)
{
return -1;
}
ans = Math.Max(ans, cand);
}
return ans;
}
private void DFS(Dictionary<int, List<List<int>>> graph, int node, int elapsed)
{
//if the distance bigger then what we already have for this node.
// return there is nothing to update
if (elapsed >= dist[node])
{
return;
}
dist[node] = elapsed;
if (graph.ContainsKey(node))
{
//we run DFS to all the other nodes
//we update the total distance to elapsed + weight
foreach (var info in graph[node])
{
DFS(graph, info[1], elapsed + info[0]);
}
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T18:51:55.093",
"Id": "238685",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"depth-first-search"
],
"Title": "LeetCode: Network Delay Time DFS solution C#"
}
|
238685
|
<p>I have based this code on <a href="https://realpython.com/intro-to-python-threading/#producer-consumer-threading" rel="nofollow noreferrer">Producer-Consumer Threading</a> on Real Python.</p>
<p>The idea is that I have 2 producers:</p>
<ul>
<li>One producer will give result every 0.4 to 0.7 seconds, depending on REST call.</li>
<li>The second producer will be a web socket that will forward filtered information to consumer.</li>
</ul>
<p>And one consumer that needs to act on results from producers.</p>
<p>This code is working fine, but I'd like a second opinion on what I can improve from design/architecture side.</p>
<pre><code>import concurrent.futures
import logging
import queue
import random
import threading
import time
def producer_1(queue_1, event_1):
"""Pretend we're getting a number from the network."""
while True:
time.sleep(1)
message = random.randint(1, 101)
logging.info("Producer_1 got message: %s", message)
queue_1.put(message)
event_1.set()
logging.info("Producer_1 Exiting")
def producer_2(queue_2, event_2):
"""Pretend we're getting a number from the network."""
while True:
time.sleep(0.5)
message = random.randint(1, 101)
logging.info("Producer_2 got message: %s", message)
queue_2.put(message)
event_2.set()
logging.info("Producer_2 Exiting")
def consumer(queue_1, queue_2, event_1):
"""Pretend we're saving a number in the database."""
while True:
event_1.wait()
logging.info("Consumer START")
if not queue_1.empty():
message = queue_1.get()
logging.info("Consumer storing message_1: %s (size=%d)", message, queue_1.qsize())
if queue_1.empty():
event_1.clear()
logging.info("Queue_1 EMPTY")
if not queue_2.empty():
message = queue_2.get()
logging.info("Consumer storing message_2: %s (size=%d)", message, queue_2.qsize())
if queue_2.empty():
event_1.clear()
logging.info("Queue_2 EMPTY")
logging.info("Consumer END")
logging.info("Consumer Exiting")
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
pipeline_1 = queue.Queue(maxsize=10)
event_1 = threading.Event()
pipeline_2 = queue.Queue(maxsize=10)
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
#executor.submit(consumer, pipeline_1, event_1, pipeline_2, event_2)
executor.submit(consumer, pipeline_1, pipeline_2, event_1)
executor.submit(producer_1, pipeline_1, event_1)
executor.submit(producer_2, pipeline_2, event_1)
logging.info("Main: about to set event")
</code></pre>
|
[] |
[
{
"body": "<h2>Logging after an infinite loop</h2>\n\n<p>The only way that this:</p>\n\n<pre><code>while True:\n time.sleep(1)\n message = random.randint(1, 101)\n logging.info(\"Producer_1 got message: %s\", message)\n queue_1.put(message)\n event_1.set()\n</code></pre>\n\n<p>is going to terminate is on an exception. That in itself isn't a bad thing - stop iteration exceptions are a common pattern in Python. However, it means that this line:</p>\n\n<pre><code>logging.info(\"Producer_1 Exiting\")\n</code></pre>\n\n<p>can by definition never execute. You might want to try:</p>\n\n<pre><code>try:\n while True:\n time.sleep(1)\n message = random.randint(1, 101)\n logging.info(\"Producer_1 got message: %s\", message)\n queue_1.put(message)\n event_1.set()\nfinally:\n logging.info(\"Producer_1 Exiting\")\n</code></pre>\n\n<h2><code>main</code> method</h2>\n\n<p>Putting code in this block:</p>\n\n<pre><code>if __name__ == \"__main__\":\n</code></pre>\n\n<p>doesn't remove it from global scope. For that, you need to add a <code>main</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T13:57:02.077",
"Id": "238944",
"ParentId": "238689",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T21:04:17.960",
"Id": "238689",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"multithreading",
"concurrency",
"producer-consumer"
],
"Title": "One consumer and two producers using threads"
}
|
238689
|
<p>I created a simple Bank application to make multiple transactions between multiple accounts. It is working as expected. But I want to know can I make the code more optimized.</p>
<pre><code>public class BankingApplication {
public static void main(String[] args) throws Exception{
ExecutorService service = Executors.newFixedThreadPool(100);
Bank bankObj = new Bank();
for(int i =0; i <= 10000; i++){
service.submit(bankObj);
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
bankObj.getTotalBalanceWithStats();
}
}
class Account{
String accountName;
int balance;
Object lock1 = new Object();
Object lock2 = new Object();
Object lock3 = new Object();
Account(String name, int balance){
this.accountName = name;
this.balance = balance;
}
void deposit(int amount){
synchronized (lock1) {
this.balance = getBalance() + amount;
}
}
void withdraw(int amount) throws Exception {
synchronized (lock2) {
int balance = getBalance() - amount;
if(balance <= 0){
throw new Exception("Invalid Transaction");
}
this.balance = getBalance() - amount;
}
}
int getBalance(){
synchronized (lock3){
return this.balance;
}
}
}
class Bank implements Runnable{
List<Account> accountList = new ArrayList<>();
Bank(){
for(int i=0; i <= 30; i++){
accountList.add(new Account("A"+i, 1000));
}
getTotalBalanceWithStats();
}
public void run() {
Random random = new Random();
Account from = null;
Account to = null;
while(true) {
int a1 = random.nextInt(30);
int a2 = random.nextInt(30);
if(a1 == a2) continue;
from = accountList.get(a1);
to = accountList.get(a2);
break;
}
doTransaction(from, to, random.nextInt(400));
}
private void doTransaction(Account from, Account to, int nextInt) {
System.out.println("Transaction from " + from.accountName + " to " + to.accountName);
try {
from.withdraw(nextInt);
to.deposit(nextInt);
} catch (Exception e){
System.out.println(e.getMessage());
}
}
void getTotalBalanceWithStats(){
int total = 0;
for(Account acc : accountList){
System.out.println("Account " + acc.accountName + " balance " + acc.getBalance());
total += acc.getBalance();
}
System.out.println("Total Balance " + total);
}
}
</code></pre>
<p>As per my knowledge I feel deposit(), withdrawal() and getBalanace() API are independent of each other so creating different mutex for each process.</p>
<p>Some scenarios which I am trying to test</p>
<p>What I am trying to achieve is when Account1 is trying to send money to Account2 at the same time Account3 can also send money to Account2 or vice versa.</p>
<p>When Account1 is sending money to Account2 at same time Account2 can also send money to Account1.</p>
<p>When Account1 is sending money to Account2 and at same time Account3 is sending money to Account1. withdraw() method of Account1 should not block deposit().</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T06:01:15.157",
"Id": "468120",
"Score": "0",
"body": "Welcome to CodeReview@SE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T06:02:20.820",
"Id": "468121",
"Score": "0",
"body": "(Out of curiosity: what have been the `getTotalBalanceWithStats()` outputs in your test runs?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T08:41:20.217",
"Id": "468127",
"Score": "0",
"body": "@greybeard I am getting the proper output everytime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:51:30.067",
"Id": "470061",
"Score": "0",
"body": "Banking is one application where accuracy and auditability are way more important than speed."
}
] |
[
{
"body": "<p>This code is broken.</p>\n\n<p>Imagine an <code>Account</code> with $100, two threads, one depositing $1, the other withdrawing $50.</p>\n\n<p>Thread one acquired <code>lock1</code>, and begins executing:</p>\n\n<pre><code>this.balance = getBalance() + amount;\n</code></pre>\n\n<p>and reads $100 ...</p>\n\n<p>Thread two acquired <code>lock2</code>, reads the balance (still $100), subtracts $50, stores the new balance ($50) and releases <code>lock2</code>.</p>\n\n<p>... (back to thread one) ... adds $1, for a total of $101, which it stores in <code>balance</code>.</p>\n\n<p>Free money! The withdrawal of $50 was forgotten. </p>\n\n<p>You must lock all read-modify-write operations of an object's member with the same lock. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T08:47:43.223",
"Id": "468128",
"Score": "0",
"body": "I got your point. But what should be the ideal way in which different threads acquire lock on different processes to make transaction faster. If Thread1 is sending money from A1 to A2 at same time A3 can send money to A1. I am unable to get irrespective of having different lock why I am getting correct output everytime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T08:52:33.017",
"Id": "468130",
"Score": "0",
"body": "For reason creating different mutex is when Thread1 is depositing amount for Account1 at same time Thread2 can withdraw amount if not less than 0. I am here handling the failover scenario. But at same time no two thread can deposit amount for Account1. I hope you got my point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T11:31:17.433",
"Id": "468141",
"Score": "1",
"body": "It is almost impossible to create unit tests for concurrency issues. You would have to be able to insert a delay between calling getBalance() and assigning the result of the addition/subtraction to balance. Your unit tests returning correct results are meaningless here. With a debugger you probably would be able to do it by manually stepping through statements in each thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T11:33:02.813",
"Id": "468142",
"Score": "1",
"body": "And I don't think you are getting the point, because the point is that you can not perform a withdrawal and a deposit to the same Account in parallel. It is not the place where you can optimize for performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:39:19.000",
"Id": "468164",
"Score": "0",
"body": "@TorbenPutkonen I understand by putting Thread to sleep giving me incorrect result. I just started learning multithreading. What I am simply trying to achieve is when I am trying to make transaction between A1 and A2 it should not make transaction between A3 and A1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:59:40.337",
"Id": "468170",
"Score": "1",
"body": "\"_You must lock all read-modify-write operations of an object's member with the same lock._\" As in, remove `lock2` and `lock3`, changing usages to `lock1`. Or, maintain 2 members: `balance` and `credits`, with 1 lock for credits, and one for balance. Deposits lock & add to credits. Withdraws lock & subtract from balance, but if balance is about to go negative, then also lock credits, transfer credits into balance, zeroing credits, & unlock credits. Then attempt to subtract from balance again. Finally unlock balance. I doubt that gains you anything, however."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T22:04:59.537",
"Id": "238692",
"ParentId": "238690",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "238692",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T21:22:48.703",
"Id": "238690",
"Score": "1",
"Tags": [
"java",
"multithreading",
"thread-safety",
"concurrency"
],
"Title": "Banking application - Optimizing java multi-threading code"
}
|
238690
|
<p>I have a Class that:</p>
<ol>
<li>goes to a url </li>
<li>grabs a link from that page, <em>and</em> a date (<code>filing_date</code>) </li>
<li>navigates to the link, and </li>
<li>writes the table from <em>that</em> page to a dataframe. </li>
</ol>
<p>I am trying to add the respective <code>filing_date</code> from step 2 to the dataframe from step 4, but rather than pass the multiple <code>filing_dates</code>, like so:</p>
<pre><code> nameOfIssuer cik Filing Date
0 Agilent Technologies, Inc. (A) ... 0000846222 2020-01-10
1 Adient PLC (ADNT) ... 0000846222 2020-01-10
.. ... ... ... ...
662 Whirlpool Corp (WHR) ... 0000846222 2010-07-08
</code></pre>
<p>it only passes the <em>last</em> scraped date from the prior page to all rows:</p>
<pre><code> nameOfIssuer cik Filing Date
0 Agilent Technologies, Inc. (A) ... 0000846222 2010-07-08
1 Adient PLC (ADNT) ... 0000846222 2010-07-08
.. ... ... ... ...
662 Whirlpool Corp (WHR) ... 0000846222 2010-07-08
</code></pre>
<p>I've tried storing the dates to an empty list and then appending to the output data frame, but because the length of the list doesn't match the list of the dataframe, I get <code>ValueError: Length of values does not match length of index</code>. </p>
<p>Can someone advise on what the best approach would be (e.g., making another function to solely handle <code>filing_date</code> or perhaps returning a data frame instead)? </p>
<pre><code>import pandas as pd
from urllib.parse import urljoin
from bs4 import BeautifulSoup, SoupStrainer
import requests
class Scraper:
BASE_URL = "https://www.sec.gov"
FORMS_URL_TEMPLATE = "/cgi-bin/browse-edgar?action=getcompany&CIK={cik}&type=13F"
def __init__(self):
self.session = requests.Session()
def get_holdings(self, cik):
"""
Main function that first finds the most recent 13F form and then passes
it to scrapeForm to get the holdings for a particular institutional investor.
"""
# get the form urls
forms_url = urljoin(self.BASE_URL, self.FORMS_URL_TEMPLATE.format(cik=cik))
parse_only = SoupStrainer('a', {"id": "documentsbutton"})
soup = BeautifulSoup(self.session.get(forms_url).content, 'lxml', parse_only=parse_only)
urls = soup.find_all('a', href=True)
# get form document URLs
form_urls = []
for url in urls:
url = url.get("href")
url = urljoin(self.BASE_URL, str(url))
headers = {'User-Agent': 'Mozilla/5.0'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
# Get filing date and "period date"
dates = soup.find("div", {"class": "formContent"})
filing_date = dates.find_all("div", {"class": "formGrouping"})[0]
filing_date = filing_date.find_all("div", {"class": "info"})[0]
filing_date = filing_date.text
# get form table URLs
parse_only = SoupStrainer('tr', {"class": 'blueRow'})
soup = BeautifulSoup(self.session.get(url).content,'lxml', parse_only=parse_only)
form_url = soup.find_all('tr', {"class": 'blueRow'})[-1].find('a')['href']
if ".txt" in form_url:
pass
else:
form_url = urljoin(self.BASE_URL, form_url)
# print(form_url)
form_urls.append(form_url)
return self.scrape_document(form_urls, cik, filing_date)
def scrape_document(self, urls, cik, filing_date):
"""This function scrapes holdings from particular document URL"""
cols = ['nameOfIssuer', 'titleOfClass', 'cusip', 'value', 'sshPrnamt',
'sshPrnamtType', 'putCall', 'investmentDiscretion',
'otherManager', 'Sole', 'Shared', 'None']
data = []
for url in urls:
soup = BeautifulSoup(self.session.get(url).content, 'lxml')
for info_table in soup.find_all(['ns1:infotable', 'infotable']):
row = []
for col in cols:
d = info_table.find([col.lower(), 'ns1:' + col.lower()])
row.append(d.text.strip() if d else 'NaN')
data.append(row)
df = pd.DataFrame(data, columns=cols)
df['cik'] = cik
df['Filing Date'] = filing_date
return df
holdings = Scraper()
holdings = holdings.get_holdings("0000846222")
print(holdings)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:16:34.173",
"Id": "468116",
"Score": "2",
"body": "What version of python is this written in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T02:44:18.520",
"Id": "468117",
"Score": "1",
"body": "Sorry, it's Python 3.7"
}
] |
[
{
"body": "<p>Seems like you have as many filing_dates as you have URLs, so you should have those together and handle them similarly.</p>\n\n<p>Your problem seems to come from the fact that you're losing the intel of which row comes from which URL, and so your only option becomes to set one date for the full dataframe.</p>\n\n<p>Here's an updated version saving the dates at the same time as the URLs and using and using a new <code>res_df</code> dataframe in <code>scrape_document</code> to aggregate the dataframes retrieved from each URL.</p>\n\n<pre><code>import pandas as pd\nfrom urllib.parse import urljoin\nfrom bs4 import BeautifulSoup, SoupStrainer\nimport requests\n\nclass Scraper:\n BASE_URL = \"https://www.sec.gov\"\n FORMS_URL_TEMPLATE = \"/cgi-bin/browse-edgar?action=getcompany&CIK={cik}&type=13F\"\n\n def __init__(self):\n self.session = requests.Session()\n\n def get_holdings(self, cik):\n \"\"\"\n Main function that first finds the most recent 13F form and then passes\n it to scrapeForm to get the holdings for a particular institutional investor.\n \"\"\"\n # get the form urls\n forms_url = urljoin(self.BASE_URL, self.FORMS_URL_TEMPLATE.format(cik=cik))\n parse_only = SoupStrainer('a', {\"id\": \"documentsbutton\"})\n soup = BeautifulSoup(self.session.get(forms_url).content, 'lxml', parse_only=parse_only)\n urls = soup.find_all('a', href=True)\n\n # get form document URLs\n form_urls = []\n filing_dates = []\n for url in urls:\n url = url.get(\"href\")\n url = urljoin(self.BASE_URL, str(url))\n\n headers = {'User-Agent': 'Mozilla/5.0'}\n page = requests.get(url, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n # Get filing date and \"period date\"\n dates = soup.find(\"div\", {\"class\": \"formContent\"})\n filing_date = dates.find_all(\"div\", {\"class\": \"formGrouping\"})[0]\n filing_date = filing_date.find_all(\"div\", {\"class\": \"info\"})[0]\n filing_date = filing_date.text\n\n # get form table URLs\n parse_only = SoupStrainer('tr', {\"class\": 'blueRow'})\n soup = BeautifulSoup(self.session.get(url).content,'lxml', parse_only=parse_only)\n form_url = soup.find_all('tr', {\"class\": 'blueRow'})[-1].find('a')['href']\n if \".txt\" in form_url:\n pass\n else:\n form_url = urljoin(self.BASE_URL, form_url)\n # print(form_url)\n form_urls.append(form_url)\n # Save the filing date too\n filing_dates.append(filing_date)\n\n # Pass the dates list rather than the last one\n return self.scrape_document(form_urls, cik, filing_dates)\n\n def scrape_document(self, urls, cik, filing_dates):\n \"\"\"This function scrapes holdings from particular document URL\"\"\"\n\n cols = ['nameOfIssuer', 'titleOfClass', 'cusip', 'value', 'sshPrnamt',\n 'sshPrnamtType', 'putCall', 'investmentDiscretion',\n 'otherManager', 'Sole', 'Shared', 'None']\n\n res_df = pd.DataFrame(columns=cols+[\"Filing Date\"])\n\n # Iterate over both list at the same time\n for url, date in zip(urls, filing_dates):\n data = []\n soup = BeautifulSoup(self.session.get(url).content, 'lxml')\n\n for info_table in soup.find_all(['ns1:infotable', 'infotable']):\n row = []\n for col in cols:\n d = info_table.find([col.lower(), 'ns1:' + col.lower()])\n row.append(d.text.strip() if d else 'NaN')\n data.append(row)\n url_df = pd.DataFrame(data, columns=cols)\n url_df[\"Filing Date\"] = date\n res_df = res_df.append(url_df, ignore_index=True)\n\n # CIK seems common to the whole DF, if not follow the example of dates\n res_df['cik'] = cik\n\n return res_df\n\nholdings = Scraper()\nholdings = holdings.get_holdings(\"0000846222\")\nprint(holdings)\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T18:06:31.947",
"Id": "468207",
"Score": "1",
"body": "Thanks I appreciate this. Made a couple edits on some minor typos but I think this will work. Out of curiosity, is there a better way I could have organized/structured this from the beginning?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T17:05:12.040",
"Id": "468302",
"Score": "1",
"body": "It's pretty clean already. Separating the data processing from the data fetching (get requests) might prove useful if you plan to write unit tests. It'll make mocking easier."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:28:22.297",
"Id": "238724",
"ParentId": "238693",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238724",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T23:15:34.707",
"Id": "238693",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"pandas",
"beautifulsoup"
],
"Title": "Scraping Data From Multiple URLs into Single Dataframe"
}
|
238693
|
<p>So, I've a code that is below which works just fine:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
<title> Javascript Practice </title>
</head>
<body>
<div id="myDiv">
</div>
<script>
var a = 0;
var b = 255;
var c = 0;
var color2 = 'RGB(' + a + ',' + b + ',' + c + ')';
document.getElementById("myDiv").style.backgroundColor = color2;
document.getElementById("myDiv").style.width = 50;
document.getElementById("myDiv").style.height = 300;
</script>
</body>
</html>
</code></pre>
<p>I've got a lot of feedback saying that when accessing DOM style property, I need to set value as strings such as setting DOM.style.width not to a number like I've done here but appending <code>w + "px"</code> </p>
<p>I'm puzzled because I'm using Brackets as a code editor and deploying this on chrome. My code runs just fine and every time I load the HTML page, it initializes a div of the required dimensions. Everyone tells me it won't work which is what's confusing me. </p>
<p>TIA. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T09:56:12.927",
"Id": "468136",
"Score": "2",
"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": "2020-03-11T11:58:06.577",
"Id": "468147",
"Score": "0",
"body": "@Mr.Polywhirl no better way to demonstrate what results I'm getting. Look at the video that I've made - https://drive.google.com/open?id=1_p_-Tn0OlEpC_L_a2ov81VENzsbY_qWn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:02:07.590",
"Id": "468148",
"Score": "0",
"body": "@TobySpeight Thanks for the feedback. Have tried to edit the title to reflect what I'm trying to achieve with the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:53:15.563",
"Id": "468169",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>Inline style lengths require units. In <a href=\"https://developer.mozilla.org/en-US/docs/Mozilla/Mozilla_quirks_mode_behavior\" rel=\"nofollow noreferrer\">quirks mode</a>, browsers will assume pixels as the unit, if provided with an integer instead of a length. If you are not sure how the browser will handle the value, specify the units.</p>\n\n<blockquote>\n <p><em>The CSS parser interprets unitless numbers as px (except for <code>line-height</code> and any other properties where they have distinct meaning, and except in shorthands).</em></p>\n</blockquote>\n\n<p><strong>Bonus:</strong> Here is an extensible version of your script.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const state = {\n color : { r : 0, g : 255, b : 0 },\n dimensions : { width : 50, height : 300 }\n}\n\nconst applyState = (el, state) => {\n Object.assign(el.style, {\n backgroundColor: `rgb(${state.color.r}, ${state.color.g}, ${state.color.b})`,\n width: `${state.dimensions.width}px`,\n height: `${state.dimensions.height}px`\n })\n}\n\napplyState(document.getElementById('my-div'), state)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"my-div\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:11:16.753",
"Id": "238704",
"ParentId": "238695",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "238704",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T03:49:27.307",
"Id": "238695",
"Score": "0",
"Tags": [
"javascript",
"dom"
],
"Title": "Code to modify DOM element using DOM.style property"
}
|
238695
|
<p>I have a PHP page I used to download YouTube videos, hosted on my Pi 4.</p>
<p>The site is only going to be used on my home network (so a dot local address), but it allows me to download videos on my phone or computer without downloading any executables or special apps.</p>
<p>The user can submit a request on an HTML page with four options:</p>
<pre><code>Form ID : Description to user
----------------------------------------
bestquality : MP4 (video with sound)
worstquality : MP4 (video without sound)
bestaudio : M4A
worstaudio : WEBM
</code></pre>
<p>This is a majority of the code used to make this:</p>
<pre><code><?php
//the file extension
$formatExt = "";
switch($_GET['format']) {
case 'bestvideo': case 'worstvideo': $formatExt = "MP4"; break;
case 'bestaudio': $formatExt = "m4a"; break;
case 'worstaudio': $formatExt = "webm";
break;
default:
echo("Illegal video format '".$_GET['format']."'!");
exit(1);
}
$url = $_GET['url'];
$format = $_GET['format'];
$ytcmd = 'youtube-dl';
$directoriesInUse = array_filter(glob("./workers/*"), 'is_dir');
$integerIDs = array(sizeof($directoriesInUse));
//if the working directory changes, make sure to change the 2 at the end of the
//expression in the for loop to match the amount of '/' characters.
for($i = 0; $i < sizeof($directoriesInUse); $i++)
$integerIDs[$i] = (int)explode("/", $directoriesInUse[$i])[2];
//If these are not sorted, it will see a list of 1 thru 14 and pick 9 as the largest number (because that's how the directory would be listed)
sort($integerIDs);
$numberToUse = $integerIDs[sizeof($integerIDs) - 1] + 1;
//prevent exploiting and issuing server commands
$url = str_replace(" ", "", $url);
$url = str_replace("|", "", $url);
//url may contain & for a playlist, so it will be removed here to prevent other issues.
$url = substr($url, 0, strpos($url, "&"));
//Download the video, the "--format" option will not download audio for a video (worstvideo is video w/o audio)
if($format === "bestaudio" or $format === "worstaudio" or $format === "worstvideo")
$response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist --format '.$format.' -o \'%(title)s.%(ext)s\' '.$url);
else
$response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist -o \'%(title)s.%(ext)s\' '.$url);
//Get the first file in a directory, this SHOULD be the video that was downloaded. It is not possible (AFAIK) to get the file name of a video from the youtube-dl binary
function magicWorkers($path) {
return array_diff(scandir($path), array('.', '..'))[2];
}
//change file date so the crontab doesn't delete the file too early (youtube-dl may save the file with the date it was uploaded)
echo exec("touch ./workers/".$numberToUse."/".magicWorkers("./workers/".$numberToUse));
//sleep 2 seconds for good measure (in case things haven't updated for whatever reason, this has happened!)
sleep(2);
//This works, but I would like to find an alternative soon (prompt download vs direct)
header("Location: ./workers/".$numberToUse.'/'.magicWorkers("./workers/".$numberToUse));
exit(0);
</code></pre>
<p>The server is being hosted on an Apache2 web server in the <code>/var/www/html/</code> directory, and Apache2 has rw- access in the <code>/var/www/html/workers/</code> directory.</p>
<p>I have seen some security problems with this before, for instance, inputting <code>example.com/video && cowsay MOO</code> will execute the cowsay command, so I made a small patch by disabling the characters " " (space), "&", and "|".</p>
<p>My other concern is that I am linking the user directly to the file to download, whereas it would be better (and probably more secure) if they were prompted for the download.</p>
<p>One last thing: I have a crontab that runs every minute to delete files in the <code>workers</code> directory (older than two hours) to make sure that the space on the Pi doesn't fill up (directories do not get deleted).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:11:19.953",
"Id": "468172",
"Score": "1",
"body": "Rather than removing specific characters you should use [escapeshellarg](https://php.net/escapeshellarg) to escape it ensuring that any special characters are handled appropriately, otherwise someone could still pass through unclosed quotes causing you errors or even run their own commands with `$(command-here)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T21:57:14.263",
"Id": "468234",
"Score": "0",
"body": "Which version of PHP is it running? I tried running it locally and see a *syntax error, unexpected '1' (T_LNUMBER)* due to the `exit 0;` I tried it on http://sandbox.onlinephpfunctions.com/ with various versions of 4,5 and 7 and all of them show that syntax error..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:46:25.163",
"Id": "468242",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ it was that the exit command did not have parentheses. It ran fine on my machine when I tested for syntax errors. I have updated the question by the way. EDIT: I am running PHP 7.2.24."
}
] |
[
{
"body": "<h1>Initial thoughts</h1>\n\n<p>I must admit I hadn't heard of the <a href=\"https://ytdl-org.github.io/youtube-dl/index.html\" rel=\"nofollow noreferrer\">youtube-dl</a> program but it seems quite nifty. Perhaps it was what many of the websites I have seen for downloading YT videos use behind the scenes.</p>\n\n<p>I tried using the script locally and found that the URL <strong>must contain an ampersand</strong> (i.e. have 2+ query string variables), otherwise the logic to look for a playlist parameter and remove it would lead to an empty string passed to the youtube-dl program. But some URLs I see from Youtube only have zero or one parameters (e.g. <a href=\"https://www.youtube.com/watch?v=DuB6UjEsY_Y\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=DuB6UjEsY_Y</a> and the equivalent sharing link: <a href=\"https://youtu.be/DuB6UjEsY_Y\" rel=\"nofollow noreferrer\">https://youtu.be/DuB6UjEsY_Y</a>). </p>\n\n<p>Initially I was wondering why <code>$numberToUse</code> couldn't be set to <code>count($directoriesInUse) + 1</code> but then I realized that some of those directories could be deleted and that might lead to issues. Then I considered that if you could parse out a video id (which <a href=\"https://webapps.stackexchange.com/a/54448\">seems to have remained the same since 2014</a>) from the URL then that could be used instead of an integer for the sub-directory name.</p>\n\n<h1>Suggestions</h1>\n\n<h2>Use a mapping instead of a <code>switch</code></h2>\n\n<p>The <code>switch</code> could be simplified:</p>\n\n<blockquote>\n<pre><code>switch($_GET['format']) {\n case 'bestvideo': case 'worstvideo': $formatExt = \"MP4\"; break;\n case 'bestaudio': $formatExt = \"m4a\"; break;\n case 'worstaudio': $formatExt = \"webm\";\n break;\n default:\n echo(\"Illegal video format '\".$_GET['format'].\"'!\");\n exit(1);\n}\n</code></pre>\n</blockquote>\n\n<p>A mapping could be defined of formats to extensions:</p>\n\n<pre><code>const FORMAT_MAPPING = [\n 'bestvideo' => \"MP4\",\n 'worstvideo' => \"MP4\",\n 'bestaudio' => \"m4a\",\n 'worstaudio' => \"webm\"\n];\n</code></pre>\n\n<p>Then if the query string is missing that key or that key does not exist in the mapping, show the error and exit early.</p>\n\n<pre><code>if (!isset($_GET['format']) || !array_key_exists($_GET['format'], FORMAT_MAPPING)) {\n echo(\"Illegal video format '\".$_GET['format'].\"'!\");\n exit(1);\n}\n</code></pre>\n\n<p>Otherwise just assign the value to <code>$formatExt</code>:</p>\n\n<pre><code>$formatExt = FORMAT_MAPPING[$_GET['format']];\n</code></pre>\n\n<h2>Control structures not using statement groups</h2>\n\n<p>While it may seem unlikely that there would be a need for multiple lines following <code>if</code>, <code>else</code> or <code>for</code> statements, it is best to put the statements to execute in a group (i.e. with curly braces/brackets). Then when you determine that you need to add a line to one of those statement groups, it eliminates any chance of logic error.</p>\n\n<blockquote>\n<pre><code>if($format === \"bestaudio\" or $format === \"worstaudio\" or $format === \"worstvideo\") {\n $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist --format '.$format.' -o \\'%(title)s.%(ext)s\\' '.$url);\n}\nelse {\n $response = exec('mkdir ./workers/'.$numberToUse.' && cd ./workers/'.$numberToUse.'/ && '.$ytcmd.' --no-playlist -o \\'%(title)s.%(ext)s\\' '.$url);\n}\n</code></pre>\n</blockquote>\n\n<h2><code>or</code> has lower precedence than <code>||</code> and others like assignment</h2>\n\n<p>Note the <a href=\"https://www.php.net/manual/en/language.operators.precedence.php\" rel=\"nofollow noreferrer\">operator precedence</a> list and how <code>or</code> is at the end of the list, while logical or i.e. <code>||</code>, is above assignment and others:</p>\n\n<p><a href=\"https://i.stack.imgur.com/pjFGX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pjFGX.png\" alt=\"operator precedence\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/tiCyx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tiCyx.png\" alt=\"operator precedence end\"></a></p>\n\n<p>There is a <a href=\"https://www.php.net/manual/en/language.operators.precedence.php#117390\" rel=\"nofollow noreferrer\">good illustration of the difference in the user contributed notes by fabmlk</a>:</p>\n\n<blockquote>\n <p>Watch out for the difference of priority between 'and vs &&' or '|| vs or':</p>\n\n<pre><code><?php\n$bool = true && false;\nvar_dump($bool); // false, that's expected\n\n$bool = true and false;\nvar_dump($bool); // true, ouch!\n?>\n</code></pre>\n \n <p>Because 'and/or' have lower priority than '=' but '||/&&' have higher.</p>\n</blockquote>\n\n<p>So it is wise to get in the practice of using <code>||</code> unless you know you need <code>or</code> </p>\n\n<h2>use <code>foreach</code> instead of <code>for</code></h2>\n\n<p>Instead of this <code>for</code> loop:</p>\n\n<blockquote>\n<pre><code>for($i = 0; $i < sizeof($directoriesInUse); $i++)\n $integerIDs[$i] = (int)explode(\"/\", $directoriesInUse[$i])[2];\n</code></pre>\n</blockquote>\n\n<p>A <a href=\"https://php.net/foreach\" rel=\"nofollow noreferrer\"><code>foreach</code></a> could be used </p>\n\n<pre><code>foreach ($directoriesInUse as $i => $directory) {\n $integerIDs[$i] = (int)explode(\"/\", $directory)[2];\n}\n</code></pre>\n\n<p>One could also use <code>array_map()</code>. Instead of storing an array of integers, you could just keep track of the maximum number seen - using <a href=\"https://www.php.net/max\" rel=\"nofollow noreferrer\"><code>max()</code></a>. That would avoid the need to sort the array. This likely wouldn’t be a major optimization unless there were a large number of directories. </p>\n\n<h2>Logical flaw when no ampersand exists in URL</h2>\n\n<p>As was mentioned above, this line doesn't work well when there is no ampersand in <code>$url</code></p>\n\n<blockquote>\n<pre><code>//url may contain & for a playlist, so it will be removed here to prevent other issues.\n$url = substr($url, 0, strpos($url, \"&\"));\n</code></pre>\n</blockquote>\n\n<p>This is because <a href=\"http://php.net/strpos\" rel=\"nofollow noreferrer\"><code>strpos()</code></a> \"Returns <strong><code>FALSE</code></strong> if the needle was not found.\"<sup><a href=\"http://php.net/strpos\" rel=\"nofollow noreferrer\">1</a></sup>. I would update the code to only perform that alteration if the string actually contains an ampersand.</p>\n\n<p><sup>1</sup><sub><a href=\"http://php.net/strpos\" rel=\"nofollow noreferrer\">http://php.net/strpos</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T15:46:17.770",
"Id": "468368",
"Score": "0",
"body": "Thank you for answering. I’ve stated in my question that I did not want an ampersand because I did not want to allow playlists to be downloaded. The only other character besides an ampersand would be `?`, used in `youtube.com/watch?v=...`, which isn’t deleted. Also, I added an ampersand at the end of the URL, though it isn’t in this question, to prevent issues; however, I did not even consider that `strpos()` would return *false* if it was provided no ampersand, which explains why there were issues. Thank you again for answering."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T05:05:21.833",
"Id": "238807",
"ParentId": "238696",
"Score": "1"
}
},
{
"body": "<h1>Security</h1>\n\n<h2>Command injection</h2>\n\n<blockquote>\n <p>I made a small patch by disabling the characters \" \" (space), \"&\", and \"|\".</p>\n</blockquote>\n\n<p>This can easily be bypassed. Example:</p>\n\n<pre><code>url=http://example.com/;id;?%26x=y;\n</code></pre>\n\n<p>Other relevant characters include - but are not limited to - <code>$</code>, ```, etc.</p>\n\n<p>As mentioned in the comments, you should use <code>escapeshellarg</code> instead (input filtering is quite difficult).</p>\n\n<h2>XSS</h2>\n\n<p>This is vulnerable to XSS:</p>\n\n<pre><code>echo(\"Illegal video format '\".$_GET['format'].\"'!\");\n</code></pre>\n\n<p>An attacker can exploit this to run arbitrary JavaScript on the domain the script is hosted on. If there are other applications hosted there, this might have a significant impact. XSS also allows bypass of CSRF protection (see next point).</p>\n\n<p>You should apply <code>htmlentities</code> to any user-supplied value you output.</p>\n\n<h2>CSRF / Missing authentication</h2>\n\n<p>As-is, anyone could get you to download a video by including an <code>img</code> tag to the PHP script in a website, an email, etc.</p>\n\n<p>This also allows remote attackers who are not in your home network to execute arbitrary code on your computer via the command injection issue.</p>\n\n<p>I would suggest to add <em>some</em> form of authentication here, and if it's only a hardcoded key you pass in the URL.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T06:37:25.233",
"Id": "239091",
"ParentId": "238696",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238807",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T04:58:39.283",
"Id": "238696",
"Score": "4",
"Tags": [
"php",
"linux",
"shell",
"server",
"raspberry-pi"
],
"Title": "A PHP script used on my home server to download YouTube videos"
}
|
238696
|
<p>I have a working function achieving what I want to do, but, I feel that there is a better, concise, and appropriate way to achieve this but I can't quite put my finger on how.</p>
<p>Given an object with (n) recipients, duplicate the message so that there is only ever one recipient and every recipient receives a unique message-id.</p>
<p>here is how I achieved it:</p>
<pre><code>const uuidGenerator = () => Math.random();
const message = {
message: 'hello',
recipients: ['John', 'Susie', 'Christian'],
}
function split(obj) {
const messages = [];
const recipients = obj.recipients;
let copy = obj;
for (let i = 0; i < recipients.length; i++) {
copy.id = uuidGenerator(),
copy.recipient = recipients[i];
copy.message = obj.message
messages.push(copy);
copy = {}
}
return messages;
}
const arrOfMessages = split(message)
console.log(arrOfMessages)
</code></pre>
<p>precisely I am not a fan of how at the end of each loop I am reassigning an obj. I feel... dirty, and it feels like the bigger an object could be the more expensive it could be... what if the message had Base64 video file within it? copying and reassigning feels like this could become more expensive (n2) in big O notation?</p>
<p>any help and clarification would be well appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T09:55:52.277",
"Id": "468135",
"Score": "0",
"body": "Welcome to Code Review! 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": "2020-03-12T09:00:24.123",
"Id": "468250",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to ask a new question with the improved code linking back to this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T13:16:00.197",
"Id": "468352",
"Score": "0",
"body": "If you don't like the reassigning part, just declare it within the loop. That would become something like for(looping constructs) { const copy = obj; // ... everything else }.\nThis way at the end of loop it gets auto destroyed"
}
] |
[
{
"body": "<p>I think this is what you're looking for</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const uuidGenerator = () => Math.random();\n\nconst message = {\n message: 'hello',\n recipients: ['John', 'Susie', 'Christian'],\n};\n\nfunction split(obj) {\n const { message, recipients, ...remaining } = obj;\n return recipients.map((recipient) => {\n return { id: uuidGenerator(), message, ...remaining, recipient: recipient };\n });\n}\n\nconst arrOfMessages = split(message);\nconsole.log(arrOfMessages);\n</code></pre>\n\n<p>if there are too many values that you want to copy from the actual <code>obj</code>, then you can use the spread operator i.e., <code>remaining</code> in this case. </p>\n\n<p>However, I am not sure about how efficient this is. These are possible approaches: \n- <code>Object.assign</code>\n- <code>Spread Operator</code>\n- manually adding keys to base Object\nBecause, I have seen instances where each of these perform differently based on the sample size.</p>\n\n<p>I remember that last approach is faster if your sample size is huge.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T08:38:37.793",
"Id": "468249",
"Score": "0",
"body": "thanks for the input, I was able to modify it a little differently, I am not sure how efficient it is either. but maybe you can weigh in on it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T10:44:24.373",
"Id": "238701",
"ParentId": "238699",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T09:30:40.413",
"Id": "238699",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Javascript obj assignment/mutation in for-loops"
}
|
238699
|
<p>I'm writing a bash script to search C source files and find the lines where I missed the void keyword (unlike in C++, in C, empty parameter lists have to be indicated with the void keyword).</p>
<p>I read that I shouldn't use <code>for</code> but <code>while</code>: <a href="https://mywiki.wooledge.org/DontReadLinesWithFor" rel="nofollow noreferrer">https://mywiki.wooledge.org/DontReadLinesWithFor</a></p>
<p>I find that <code>for</code> has an easier to follow, top-down structure (first I write the command that produces the items to be iterated, then I write what to do with each).</p>
<p>I understand that if a filename contained a newline it would cause trouble in case of <code>for</code>; however, with <code>IFS=$'\n'; set -f</code> I would think all other problems are solved.</p>
<p>My code using for:</p>
<pre><code>#!/bin/bash
returnTypeOpt_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}[* ]\{1,\}\)\{0,1\}'
spaceOpt_BRE=$'[ \t\r]\\{0,\\}'
functionName_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}\)'
declarationMissingVoid_BRE="^$returnTypeOpt_BRE$spaceOpt_BRE$functionName_BRE$spaceOpt_BRE($spaceOpt_BRE)$spaceOpt_BRE;$spaceOpt_BRE\$"
targetFolder_Path="$1"
if [ $# -eq 0 ]; then
targetFolder_Path="."
fi
IFS=$'\n'; set -f; for file in $( find "$targetFolder_Path" -name '*.c' -or -name '*.h' ); do
printf "%s\n" "$file"
for line in $( grep --basic-regex --regexp=$declarationMissingVoid_BRE $file ); do
printf "\t>%s\n" "$line"
done
done; unset IFS; set +f
</code></pre>
<p>My code using while:</p>
<pre><code>#!/bin/bash
returnTypeOpt_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}[* ]\{1,\}\)\{0,1\}'
spaceOpt_BRE=$'[ \t\r]\\{0,\\}'
functionName_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}\)'
declarationMissingVoid_BRE="^$returnTypeOpt_BRE$spaceOpt_BRE$functionName_BRE$spaceOpt_BRE($spaceOpt_BRE)$spaceOpt_BRE;$spaceOpt_BRE\$"
targetFolder_Path="$1"
if [ $# -eq 0 ]; then
targetFolder_Path="."
fi
while IFS=; read -u 3 -r -d $'\0' file; do
printf "%s\n" "$file"
while IFS=; read -u 4 -r line; do
printf "\t>%s\n" "$line"
done 4< <( grep --basic-regex --regexp=$declarationMissingVoid_BRE $file )
done 3< <( find "$targetFolder_Path" -name '*.c' -print0 -or -name '*.h' -print0 )
</code></pre>
<p>So, for me both scripts work correctly, and produce the same result.</p>
<p>Beyond the "filenames with newlines" issue is there anything else that would make <code>while</code> better? Can you show me a test case?</p>
<p>If I had to solve similar but different (possibly more complex) tasks would I have problems with <code>for</code>?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>I'm writing a bash script to search C source files and find the lines where I missed the void keyword</p>\n</blockquote>\n\n<p>This alone suggests that your approach is very problematic. To do this properly you'd effectively need to write most of a C parser, and that isn't a good use of your time. There are other approaches that would get you more mileage and accuracy:</p>\n\n<ul>\n<li>Double-check that your compiler (gcc?) for sure doesn't have <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\" rel=\"nofollow noreferrer\">warnings</a> that cover your use-case; if it does, then simply compile and look at the output.</li>\n<li>Failing that, reuse a parser. I recommend the <a href=\"https://clang.llvm.org/docs/IntroductionToTheClangAST.html\" rel=\"nofollow noreferrer\">Clang AST</a>.</li>\n</ul>\n\n<p>Bash is just the hideously wrong tool for this. Save yourself the pain of writing regexes that are both complex and likely missing many edge cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T17:25:35.770",
"Id": "468596",
"Score": "0",
"body": "GCC doesn't have warnings for this. If it did, that would be great, but it doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T18:35:31.637",
"Id": "468597",
"Score": "0",
"body": "My C source files are quite simple, and I'm not afraid of missing some edge cases. On the other hand, I would like to know how to search regex patterns in multiple files with bash scripts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T13:50:36.357",
"Id": "238943",
"ParentId": "238702",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T11:17:21.883",
"Id": "238702",
"Score": "4",
"Tags": [
"comparative-review",
"bash"
],
"Title": "Finding missing void keywords in C source code"
}
|
238702
|
<p>I needed to create a custom <code>trim()</code> function instead of using existing <a href="https://www.php.net/manual/en/function.ltrim.php" rel="nofollow noreferrer">ltrim</a> or <a href="https://www.php.net/manual/en/function.rtrim.php" rel="nofollow noreferrer">rtrim</a> due to below problems.</p>
<p><strong>Here are problem with existing functions.</strong></p>
<pre><code>$string = '<ul><li>This</li></ul>';
var_dump(ltrim($string, '<br>'));
// Output :: string(21) "ul><li>This</li></ul>"
</code></pre>
<p><a href="https://tio.run/##K8go@P/fxr4go4CLS6W4pCgzL13BVkHdpjTHziYn0y4kI7PYRh/IsNEHiqhbc3GVJRbFp5TmFmjkABXnakD16AC1JBXZqWtqWv//DwA" rel="nofollow noreferrer">Fiddle</a>.</p>
<p>As you can see <em>ltrim</em> trimming <strong><</strong> brace because <strong><br></strong> not found I think (Not sure 100%).</p>
<p><strong>Here created function,</strong></p>
<pre><code>function trimString($string, $replaceWith = ' ', $type = 'ltrim')
{
$type = (!empty($type) && in_array($type, ['ltrim', 'rtrim'])) ? $type : 'ltrim';
if (!empty($string) && !empty($replaceWith)) {
// Like ltrim
if ($type == 'ltrim') {
if (strpos($string, $replaceWith) === 0) {
$string = substr_replace($string, '', 0, strlen($replaceWith));
}
} elseif ($type == 'rtrim') {
// Like rtrim
$reverceString = strrev($string);
$replaceWithCount = strlen($replaceWith);
$count = 1;
for ($i = 0; $i < strlen($string); $i++){
if ($count <= $replaceWithCount) {
$newString .= $reverceString[$i];
}
$count++;
if ($count == $replaceWith) {
break;
}
}
if (!empty($newString)) {
if (strrev($newString) == $replaceWith) {
$string = strrev(strReplaceFirst($reverceString, strrev($replaceWith), ''));
}
}
}
}
return $string;
}
function strReplaceFirst($content, $from, $to)
{
if (!empty($content) && !empty($from)) {
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
return $content;
}
</code></pre>
<p><a href="https://tio.run/##lVVNb6MwEL3nV0ylqICCQnotkB5W6mlPu5X2UFURYZ3GKjGuMV1VFb89OzbGfDnarA8GDzPPb57HAz/y8zl54Ee@WACOQ81ySUsGUtDTT5zYq7@s9DOEpSC8yHLyi8ojpOCBhzb5yYlaFCrCCzTKl57V6D77N@TE5aev1wHc3gJlu0yIzJhCeDYIIXhCv7wEATwYgPsOP7bI9NCDtgQ1bGcaUEWcnpAaUQTf6RsBDTn6okAN5T6lSXTnh5vysnKrE2B8ChtXqFaljUFdqnqP7zsT2oN5qMMmBFwWhE2yiWeYzcjSACkqMk5FXEylE0PMxNBMBfkgIidtKShLqkih1aoeu4Is3W9lzWQbNMvEEZlr98FI4W7udigFJkfx4yYGfCYWvuOE1tUqcKuvlWk3StI52UuHpvkx8sdIsU4n4jwv6UvsjGzcRaAprFbx4l8s03RSXJcJ7gXJ3q5l0TjrurtBNtXg0obmFuhi6L3/h@7gIrQ4@PjRhj5SUUl/LHFoa2@Ir26L61Zck3S/avpjEETWgnXkWuBm0h9nRPOSScIk9oGDKE@qMZbTZjhU17iPepYKnImtrarBRt6aC/K6e69LSXyzC1qDNU6TIjIZaH/bWyyvEHq2dwPhHBIYP6vBYnxqXlIX26Sg26cjrZIIX5IILaZN6@kjE7vf9Yn7rj@Kl@zFVh/etb7294BB5/Nf" rel="nofollow noreferrer">Fiddle</a>.</p>
<p>So, it is working properly for me! But I still don't know if it's the proper way to do that or not? Or it's side effect and time consumption.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:31:07.530",
"Id": "468154",
"Score": "0",
"body": "The proper way to trim a string depends on its use. This is similar to case-folding on a case-insensitive filesystem and \"newline trimming\" in some Perl input loops. What's your use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:38:47.850",
"Id": "468155",
"Score": "0",
"body": "The stock trimming functions trim *bytes*, not strings. Is your goal to remove particular substring(s) at the beginning or the end of the input to your trim functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:49:18.923",
"Id": "468167",
"Score": "0",
"body": "@DannyNiu yes my goal is to remove particular needle from string fron beginning or from the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T14:03:09.717",
"Id": "468270",
"Score": "1",
"body": "If you read carefully documentation of `ltrim`, you will understand why does it do what you saw. Second parameter is \"character mask\" it trims any of characters in that string. That means your call will trim any `b`, `r`, `<` and `>`."
}
] |
[
{
"body": "<p>PHP is hell of a language to see other people working (abusing) with. </p>\n\n<p>I'll assume the initial goal is to remove line-break elements at the beginning and the end of strings intended for output. </p>\n\n<p>I'd suggest a single-purpose function like: </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function trimbr($s)\n{\n return preg_replace('{^(<br\\s*/*>)*|(<br\\s*/*>)*$}i', \"\", $s);\n}\n</code></pre>\n\n<p>The reason is as follow: </p>\n\n<ol>\n<li><p>Regex-based string modification runs much much faster than character iterating methods. </p></li>\n<li><p>Over-generalizing our trim function may not be as useful as it initially seems to be. </p></li>\n<li><p>Since we're restraining ourselves from generalizing, we now aim for a minimal functionality and implementation. </p></li>\n</ol>\n\n<p>Point 1 and 3 are easy to understand I suppose.</p>\n\n<p>As for 2, we can put some stock regex substrings in the function - these substrings should be commonly-needed, and regex-safe. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:52:12.397",
"Id": "238707",
"ParentId": "238705",
"Score": "3"
}
},
{
"body": "<p>I wonder if you did a quick Google search before rolling your own solution. Despite being implemented via different languages, they all give the same general regex solution.</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/q/32225635/2943403\">Regex to remove all <code><br /></code> tags from beginning and end of a string in javascript</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/q/28128929/2943403\">Remove <code><br></code> tags from the beginning and end of a string</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/q/18717206/2943403\">Remove BR tag from the beginning and end of a string</a></p></li>\n</ul>\n\n<p>As you have discovered, <code>trim()</code> functions treat the 2nd parameter as a \"character mask\", this means that it will greedily remove any consecutive characters from the beginning/end of the string from that \"list of characters\" (<code><br></code> is the same as <code>rb><</code>).</p>\n\n<p>If you need a utility function and require the same passed-in parameters:</p>\n\n<pre><code>function trimString($input, $find, $replacement = ' ', $type = 'ltrim') {\n $patterns = [\n 'ltrim' => '^(?:' . preg_quote($find, '/') . ')+',\n 'rtrim' => '(?:' . preg_quote($find, '/') . ')+$'\n ];\n $pattern = $patterns[$type] ?? implode('|', $patterns);\n return preg_replace('/' . $pattern . '/i', $replacement, $input);\n}\n</code></pre>\n\n<p>If you want to be able to pass replacement strings which contain regex to the custom function like <code><br\\s*/?></code>, then you can remove the <code>preg_quote()</code> calls entirely or set a flag/argument in the custim function which determines whether the quoting call should be implemented. This means that the responsiblity of quoting any special characters is transferred from the custom function to whatever layer is calling the custom function.</p>\n\n<p>If you want to use <code>trim()</code> before or after the execution of this custom function, that makes perfect sense too -- removing whitespace characters is exactly what it is mean to do.</p>\n\n<p>If your requirements keep extending and you have the intention of removing HTML tags from a valid HTML document, then regex is probably not the right path to go down. Regex is DOM-unaware and will be vulnerable to breakage in fringe case scenarios -- a legitimate DOM parser would be my strong recommendation in that case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:34:28.660",
"Id": "238739",
"ParentId": "238705",
"Score": "4"
}
},
{
"body": "<p>Sticking to what you state as your goal in the comment</p>\n\n<blockquote>\n <p>my goal is to remove particular needle from string fron beginning or\n from the end</p>\n</blockquote>\n\n<p>rather than use any assumptions about manipulating html tags (which should be done in DOMDocument or a similar DOM parser), then I will stick to this.</p>\n\n<p>The problem in your case is that any of the <code>trim()</code> functions take a list of characters to trim, so they are considered individually rather than as a string in itself (which is what the search functions use).</p>\n\n<p>This code just considers the first (or last) set of characters equivalent to the length of the needle and compares this with the needle itself. If it matches, then just <code>substr()</code> the haystack to remove this many characters off the string...</p>\n\n<pre><code>function ltrimString( string $haystack, string $needle ) {\n if ( substr($haystack, 0, strlen($needle)) === $needle ) {\n $haystack = substr($haystack, strlen($needle));\n }\n return $haystack;\n}\n\nfunction rtrimString( string $haystack, string $needle ) {\n if ( substr($haystack, -strlen($needle)) === $needle ) {\n $haystack = substr($haystack, 0, -strlen($needle));\n }\n return $haystack;\n}\n</code></pre>\n\n<p>some examples...</p>\n\n<pre><code>echo '<ul><li>This</li></ul>=' .\n ltrimString('<ul><li>This</li></ul>', '<br>') . PHP_EOL;\n\n// <ul><li>This</li></ul>=<ul><li>This</li></ul>\n\necho '<br><ul><li>This</li></ul><br>=' .\n ltrimString('<br><ul><li>This</li></ul><br>', '<br>') . PHP_EOL;\n\n// <br><ul><li>This</li></ul><br>=<ul><li>This</li></ul><br>\n\necho '<ul><li>This</li></ul>=' .\n rtrimString('<ul><li>This</li></ul>', '<br>') . PHP_EOL;\n\n// <ul><li>This</li></ul>=<ul><li>This</li></ul>\n\necho '<br><ul><li>This</li></ul><br>=' .\n rtrimString('<br><ul><li>This</li></ul><br>', '<br>') . PHP_EOL;\n\n// <br><ul><li>This</li></ul><br>=<br><ul><li>This</li></ul>\n</code></pre>\n\n<p>The one thing I have not coded for is repeating chunks, this could be achieved by changing the <code>if()</code> to a <code>while()</code>. For example</p>\n\n<pre><code>function ltrimString( string $haystack, string $needle ) {\n while ( substr($haystack, 0, strlen($needle)) === $needle ) {\n $haystack = substr($haystack, strlen($needle));\n }\n return $haystack;\n}\n</code></pre>\n\n<p>would produce...</p>\n\n<pre><code><br><br><br><br><ul><li>This</li></ul><br>=<ul><li>This</li></ul><br>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T08:17:32.873",
"Id": "239173",
"ParentId": "238705",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T12:24:48.153",
"Id": "238705",
"Score": "2",
"Tags": [
"php"
],
"Title": "PHP : Custom trim function instead existing ltrim() or rtrim()"
}
|
238705
|
<p>I have created a timer with GUI in Java.</p>
<p>Here's the code:</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.text.NumberFormatter;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
public class Counter {
private JButton button;
private JFormattedTextField hours;
private JFormattedTextField minutes;
private JFormattedTextField seconds;
private Timer timer;
private int delay = 1000;
private ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(sec >= 1) {
sec = sec - 1;
seconds.setText(String.valueOf(sec));
}
else if(sec == 0 && min > 0) {
sec = 59;
min = min - 1;
seconds.setText(String.valueOf(sec));
minutes.setText(String.valueOf(min));
}
else if(min == 0 && hrs > 0) {
sec = 59;
min = 59;
hrs = hrs - 1;
seconds.setText(String.valueOf(sec));
minutes.setText(String.valueOf(min));
hours.setText(String.valueOf(hrs));
}
if(hrs == 0 && min == 0 && sec == 0) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null,"Countdown ended!","Ende", JOptionPane.CANCEL_OPTION);
timer.stop();
}
}
};
private int hrs;
private int min;
private int sec;
public static void main(String[] args) throws InterruptedException {
SwingUtilities.invokeLater(Counter::new);
}
Counter() {
JFrame frame = new JFrame();
frame.setSize(300, 200);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JPanel subpanel1 = new JPanel(new GridLayout(2, 3));
/*
* The following lines ensure that the user can
* only enter numbers.
*/
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
//"labeling"
JTextField text1 = new JTextField();
text1.setText("hours:");
text1.setEditable(false);
JTextField text2 = new JTextField();
text2.setText("minutes:");
text2.setEditable(false);
JTextField text3 = new JTextField();
text3.setText("seconds:");
text3.setEditable(false);
//fields for minutes and seconds
hours = new JFormattedTextField(formatter);
minutes = new JFormattedTextField(formatter);
seconds = new JFormattedTextField(formatter);
hours.setText("0");
minutes.setText("0");
seconds.setText("0");
JPanel subpanel2 = new JPanel();
/*
* When the user presses the OK-button, the program will
* start to count down.
*/
button = new JButton("OK");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
hrs = Integer.valueOf(hours.getText());
min = Integer.valueOf(minutes.getText());
sec = Integer.valueOf(seconds.getText());
button.setEnabled(false);
//Timer for one second delay
Timer timer = new Timer(delay, taskPerformer);
timer.start();
}
});
//Reset-button
JButton button2 = new JButton("Reset");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
hours.setText("0");
minutes.setText("0");
seconds.setText("0");
button.setEnabled(true);
hrs = 0;
min = 0;
sec = 0;
}
});
subpanel1.add(text1);
subpanel1.add(text2);
subpanel1.add(text3);
subpanel1.add(hours);
subpanel1.add(minutes);
subpanel1.add(seconds);
subpanel2.add(button);
subpanel2.add(button2);
panel.add(subpanel1, BorderLayout.CENTER);
panel.add(subpanel2, BorderLayout.PAGE_END);
frame.add(panel);
frame.setVisible(true);
}
}
</code></pre>
<p>I would appreciate any suggestions on improving the code!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:49:09.567",
"Id": "468166",
"Score": "0",
"body": "Please tell us more about the purpose of the code. It's a timer, ok, timing what? What is it supposed to do? What prompted you to write this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:09:31.620",
"Id": "468171",
"Score": "0",
"body": "It doesn't have any special purpose. It was just for fun. I know that this answer doesn't really help, but I can't give a better one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:31:00.683",
"Id": "468189",
"Score": "0",
"body": "I don't like global imports: `javax.swing.*` I can't tell what sort of Timer you have. There's java.util.Timer and java.swing.Timer, and it isn't obvious which one you're using. Please don't use global imports like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T21:12:29.803",
"Id": "468233",
"Score": "0",
"body": "@markspace - I would say the difference between `java.util` and `javax.swing` is pretty easy to see, especially when only one of them is being imported. Also, as in this case, it seems to me that using a global is better than adding a lot of extra lines to the imports"
}
] |
[
{
"body": "<p>A few things I noticed:</p>\n\n<p>Quite a few of your variables can be marked <code>final</code>. From my understanding pretty much any variable where the underlying object doesn't get reassigned to a new object.</p>\n\n<p>Instead of 3 separate variable for the time parts, you could use <code>java.time.LocalTime</code> to hold the time parts. Not only does this reduce your code, but it simplifies the count down portion in that subtracting 1 second will adjust the other fields automatically.</p>\n\n<p>Since <code>Integer.valueOf</code> uses <code>Integer.parseInt</code> anyway, I think it would be better, in this case, to use <code>Integer.parseInt</code></p>\n\n<p>You misspelled the title of the message dialog when the countdown is done.</p>\n\n<p>I think <code>INFORMATION_MESSAGE</code> is a better icon, for the message dialog, than <code>CANCEL_OPTION</code>, in this case.</p>\n\n<p>The <code>throws</code> clause in the <code>main</code> declaration is redundant.</p>\n\n<p>With these adjustments your code could look like this:</p>\n\n<pre><code>import javax.swing.*;\nimport javax.swing.text.NumberFormatter;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.text.NumberFormat;\nimport java.time.LocalTime;\n\nimport static javax.swing.WindowConstants.EXIT_ON_CLOSE;\n\npublic class Counter {\n private final JButton button;\n private final JFormattedTextField hours;\n private final JFormattedTextField minutes;\n private final JFormattedTextField seconds;\n\n private final Timer timer;\n private final int delay = 1000;\n private final ActionListener taskPerformer = new ActionListener() {\n public void actionPerformed(ActionEvent evt) {\n time = time.minusSeconds(1);\n if (time.equals(LocalTime.MIN)) {\n Toolkit.getDefaultToolkit().beep();\n JOptionPane.showMessageDialog(null, \"Countdown ended!\", \"Ended\", JOptionPane.INFORMATION_MESSAGE);\n timer.stop(); \n }\n seconds.setText(String.valueOf(time.getSecond()));\n minutes.setText(String.valueOf(time.getMinute()));\n hours.setText(String.valueOf(time.getHour()));\n }\n };\n\n private LocalTime time = LocalTime.of(0, 0, 0);\n\n public static void main(String[] args) {\n\n SwingUtilities.invokeLater(Counter::new);\n }\n\n Counter() {\n timer = new Timer(delay,taskPerformer);\n JFrame frame = new JFrame();\n frame.setSize(300, 200);\n frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n JPanel panel = new JPanel(new BorderLayout());\n JPanel subPanel1 = new JPanel(new GridLayout(2, 3));\n\n /*\n * The following lines ensure that the user can\n * only enter numbers.\n */\n\n NumberFormat format = NumberFormat.getInstance();\n NumberFormatter formatter = new NumberFormatter(format);\n formatter.setValueClass(Integer.class);\n formatter.setMinimum(0);\n formatter.setMaximum(Integer.MAX_VALUE);\n formatter.setAllowsInvalid(false);\n formatter.setCommitsOnValidEdit(true);\n\n //\"labeling\"\n\n JTextField text1 = new JTextField();\n text1.setText(\"hours:\");\n text1.setEditable(false);\n\n JTextField text2 = new JTextField();\n text2.setText(\"minutes:\");\n text2.setEditable(false);\n\n\n JTextField text3 = new JTextField();\n text3.setText(\"seconds:\");\n text3.setEditable(false);\n\n //fields for minutes and seconds\n hours = new JFormattedTextField(formatter);\n minutes = new JFormattedTextField(formatter);\n seconds = new JFormattedTextField(formatter);\n hours.setText(\"0\");\n minutes.setText(\"0\");\n seconds.setText(\"0\");\n\n JPanel subPanel2 = new JPanel();\n\n /*\n * When the user presses the OK-button, the program will\n * start to count down.\n */\n\n button = new JButton(\"OK\");\n button.addActionListener(actionEvent -> {\n time = LocalTime.of(Integer.parseInt(hours.getText()), Integer.parseInt(minutes.getText()), Integer.parseInt(seconds.getText()));\n button.setEnabled(false);\n //Timer for one second delay\n timer.start();\n });\n\n //Reset-button\n JButton button2 = new JButton(\"Reset\");\n button2.addActionListener(actionEvent -> {\n hours.setText(\"0\");\n minutes.setText(\"0\");\n seconds.setText(\"0\");\n button.setEnabled(true);\n time = LocalTime.of(0, 0, 0);\n timer.stop();\n });\n\n subPanel1.add(text1);\n subPanel1.add(text2);\n subPanel1.add(text3);\n subPanel1.add(hours);\n subPanel1.add(minutes);\n subPanel1.add(seconds);\n subPanel2.add(button);\n subPanel2.add(button2);\n panel.add(subPanel1, BorderLayout.CENTER);\n panel.add(subPanel2, BorderLayout.PAGE_END);\n frame.add(panel);\n frame.setVisible(true);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T06:43:15.830",
"Id": "468327",
"Score": "0",
"body": "would you please rename the **magic number** `delay = 1000`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T21:03:59.700",
"Id": "238736",
"ParentId": "238709",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238736",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T13:45:39.420",
"Id": "238709",
"Score": "2",
"Tags": [
"java",
"swing",
"timer",
"gui"
],
"Title": "Timer in Java with GUI"
}
|
238709
|
<p><strong>Background:</strong> </p>
<p>Equation 1: 2x-y=6 </p>
<p>Equation 2: 4x+3y=22</p>
<p>Because 1 is ax-by=c and 2 is dx-ey=f</p>
<p>y=(a * f - c * d) / (a * e - b * d) and x is simply (c - (b * y)) / a)</p>
<p><strong>What I am trying to do:</strong></p>
<p>Ultimately, generate linear equations that can be solved simultaneously for practice (which the code I wrote below can do). So I am creating variations of Equations 1 and 2 above that have whole number solutions for x and y. I do this by:</p>
<p>1.Creating random numbers.</p>
<p>2.Use the above calculation to find x and y from these numbers.</p>
<p>3.Ensure that x and y are whole numbers and if not, create new numbers for a-f until they are.</p>
<p><strong>Working code:</strong></p>
<p>The function <code>NumberGeneration()</code> is called with a button click.</p>
<pre><code>double a;
double b;
double c;
double d;
double e;
double f;
double x;
double y;
System.Random rnd = new System.Random();
string question;
string answer;
public void NumberGeneration()//1.Generates the variables, calculates x and y.
{
a = rnd.Next(1, 10);
b = rnd.Next(1, 10);
c = rnd.Next(1, 10);
d = rnd.Next(1, 10);
e = rnd.Next(1, 10);
f = rnd.Next(1, 10);
y = ((a * f - c * d) / (a * e - b * d));
x = ((c - (b * y)) / a);
CheckForZeros();
}
void CheckForZeros() //2.Checking for zeros
{
if ((a * e - b * d) == 0) //To avoid dividing by 0, if this is 0 generate new numbers.
{
NumberGeneration();
}
else if((a * e - b * d) != 0) // otherwise proceed to make sure x and y are whole numbers
{
EnsureWhole();
}
}
void EnsureWhole()
{
decimal dy = Convert.ToDecimal(y);
decimal dx = Convert.ToDecimal(x);
if ((dy % 1) == 0 && (dx % 1) == 0) //3.If both x and y are whole numbers, setup the question with these numbers
{
question = string.Format($"{a}x+{b}y={c}, \n {d}x+{e}y={f}", a, b, c, d, e, f);
answer = string.Format($"x={x} and y={y}");
}
else if((dy % 1) != 0 || (dx % 1) != 0)//Otherwise start again, generate a new set of numbers and attempt for a new answer where x and y are ints
{
NumberGeneration();
};
}
</code></pre>
<p><strong>Questions:</strong></p>
<ul>
<li>What is the proper way to do this? </li>
<li>How to optimize the code?</li>
<li>Is this the optimal way to generate random numbers?</li>
</ul>
<p><strong><em>Bonus follow-up:</strong>
Do you have any personal resource suggestions for learning C#? I get that instinctive feeling that my methods have holes in them, I know I am not good at coding, I just don't have the education to know better and I want to educate myself. Even better within the context of maths.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T10:30:41.660",
"Id": "468255",
"Score": "0",
"body": "It will help reviewers if you show the full class and how you intent to use it through af simple use case."
}
] |
[
{
"body": "<p>The good thing is, that you have made some meaningful methods with descriptive names.</p>\n\n<p>But you have a quite peculiar workflow:</p>\n\n<blockquote>\n<pre><code>public void NumberGeneration()//1.Generates the variables, calculates x and y.\n{\n a = rnd.Next(1, 10);\n b = rnd.Next(1, 10);\n c = rnd.Next(1, 10);\n d = rnd.Next(1, 10);\n e = rnd.Next(1, 10);\n f = rnd.Next(1, 10);\n y = ((a * f - c * d) / (a * e - b * d));\n x = ((c - (b * y)) / a);\n CheckForZeros();\n}\n</code></pre>\n</blockquote>\n\n<p>Here you check for dividing by zero after you do the calculation that is supposed to be guarded by the check.</p>\n\n<p>And calling <code>NumberGeneration()</code> recursively from <code>CheckForZeros()</code> and <code>EnsureWhole()</code> if something goes wrong has the potential to end in a stack overflow, if all the generated sets of values fail in the two tests. This is not a good use of recursion, instead you should use an iterative approach and provide a value for max retries before the generator returns unsuccessfully. </p>\n\n<hr>\n\n<p>Have you considered this condition properly:</p>\n\n<blockquote>\n<pre><code> else if ((dy % 1) != 0 || (dx % 1) != 0)//Otherwise start again, generate a new set of numbers and attempt for a new answer where x and y are ints\n {\n NumberGeneration();\n };\n</code></pre>\n</blockquote>\n\n<p>Why must at least one of the result values in the current failed calculation be a decimal number in order to allow a new calculation with an entire new set of data? It makes no sense to me.</p>\n\n<hr>\n\n<p>If everything go well you end the calculations by formatting a pair of private strings and then nothing happens:</p>\n\n<blockquote>\n<pre><code> question = string.Format($\"{a}x+{b}y={c}, \\n {d}x+{e}y={f}\", a, b, c, d, e, f);\n answer = string.Format($\"x={x} and y={y}\");\n</code></pre>\n</blockquote>\n\n<p>I imagine that you provide these results to the client in some way or else all the efforts seem useless :-)</p>\n\n<hr>\n\n<p>In</p>\n\n<blockquote>\n <p><code>(dy % 1) != 0</code></p>\n \n <p><code>(a * e - b * d) == 0</code></p>\n</blockquote>\n\n<p>The parenteses are unnecessary.</p>\n\n<p>And so are the outmost parenteses in this expression:</p>\n\n<blockquote>\n <p><code>y = ((a * f - c * d) / (a * e - b * d))</code></p>\n</blockquote>\n\n<hr>\n\n<p>I think you normally will solve the system with <code>+</code> between the parts:</p>\n\n<pre><code> ax + by = c\n dx + ey = f\n\n <=>\n\n y = (cd - af) / (bd - ae)\n x = (c - by) / a\n</code></pre>\n\n<hr>\n\n<p>The randomly generated input values (<code>a..f</code>) are all integers, so you could do all calculations as integer calculations, because you only want solutions with integral x and y. That will make the calculations a lot easier and more reliable. Checking if two double values are equal is often not reliable.</p>\n\n<hr>\n\n<p>There are a lot of ways to structure this kind of exercise. Below I have posted one version. I'm not claiming it to be <em>the</em> way to do it, but you may find some inspiration. </p>\n\n<p>The approach is rather traditional, and I have focused on an easy-to-follow workflow, naming and testability - at least to a some level. It's only using integer values and calculations.</p>\n\n<p><strong>The solver itself controlling the workflow and doing the calculations:</strong></p>\n\n<pre><code>/// <summary>\n/// Creates a random linear system of two equations with two variables of first degree and find a\n/// possible solution with integral values for the variables x and y. This is the same as\n/// finding the intersection between two lines in the plane.\n/// </summary>\npublic class LinearSystemSolver\n{\n private readonly int maxRetries;\n private readonly ICoefficientProvider coefficientProvider;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"maxRetries\">The number of times to try to find a valid solution before returning false from TrySovle().</param>\n /// <param name=\"coefficientProvider\">An object that provides the coefficients in a linear system to solve.</param>\n public LinearSystemSolver(int maxRetries, ICoefficientProvider coefficientProvider)\n {\n this.maxRetries = maxRetries;\n this.coefficientProvider = coefficientProvider\n ?? throw new ArgumentNullException(nameof(coefficientProvider));\n }\n\n public bool TrySolve(out IntegralLinearSystem result)\n {\n result = IntegralLinearSystem.Empty;\n\n for (int i = 0; i < maxRetries; i++)\n {\n Coefficients coefficients = GenerateCoefficients();\n if (HasSolution(coefficients) && GetIntegralSolution(coefficients, out int x, out int y))\n {\n result = new IntegralLinearSystem(coefficients, x, y);\n return true;\n }\n }\n\n return false;\n }\n\n private Coefficients GenerateCoefficients()\n {\n return coefficientProvider.GetCoefficients();\n }\n\n private bool HasSolution(Coefficients coefficients)\n {\n // This is a test of bd - ae != 0\n return coefficients.B * coefficients.D != coefficients.A * coefficients.E;\n }\n\n private bool GetIntegralSolution(Coefficients coefficients, out int x, out int y)\n {\n int numY = coefficients.C * coefficients.D - coefficients.A * coefficients.F;\n int denomY = coefficients.B * coefficients.D - coefficients.A * coefficients.E;\n y = numY / denomY;\n\n int numX;\n int denomX;\n if (coefficients.A != 0)\n {\n numX = coefficients.C - coefficients.B * y;\n denomX = coefficients.A;\n }\n else\n {\n // A and D can not both be 0 because the system then doesn't have a solution (the two lines are parallel with the x-axis)\n // A = D = 0 would have been caught by HasSolution() before ending here\n numX = coefficients.F - coefficients.E * y;\n denomX = coefficients.D;\n }\n x = numX / denomX;\n\n return numY % denomY == 0 && numX % denomX == 0;\n }\n}\n</code></pre>\n\n<p><strong>An object representing the integral solution - if found:</strong></p>\n\n<pre><code>/// <summary>\n/// Object representing a linear system of first degree with two variables with integral solutions for x and y.\n/// </summary>\npublic struct IntegralLinearSystem\n{\n public static readonly IntegralLinearSystem Empty = new IntegralLinearSystem(Coefficients.Empty, 0, 0);\n\n public IntegralLinearSystem(Coefficients coefficients, int x, int y)\n {\n Coefficients = coefficients;\n X = x;\n Y = y;\n\n if (!IsValid)\n throw new InvalidOperationException(\"Inconsistent integral linear system\");\n }\n\n public readonly Coefficients Coefficients;\n public readonly int X;\n public readonly int Y;\n\n public bool IsValid\n {\n get\n {\n return\n Coefficients.A * X + Coefficients.B * Y == Coefficients.C &&\n Coefficients.D * X + Coefficients.E * Y == Coefficients.F;\n }\n }\n\n public override string ToString()\n {\n StringBuilder builder = new StringBuilder();\n builder.Append(Coefficients);\n builder.AppendLine();\n builder.AppendLine(\"<=>\");\n builder.AppendFormat(\"x = {0}, y = {1}\", X, Y);\n\n return builder.ToString();\n }\n}\n</code></pre>\n\n<p><strong>An object representing the constant values (coefficients) for the system</strong></p>\n\n<pre><code>/// <summary>\n/// Object holding the coefficients to x and y and values on the right side \n/// of the equal sign in a linear system with two variables of first degree\n/// on the form <code>ax + by = c</code> and <code>dx + ey = f</code>\n/// </summary>\npublic struct Coefficients\n{\n public static readonly Coefficients Empty = new Coefficients();\n\n public readonly int A;\n public readonly int B;\n public readonly int C;\n public readonly int D;\n public readonly int E;\n public readonly int F;\n\n public Coefficients(int a, int b, int c, int d, int e, int f)\n {\n A = a;\n B = b;\n C = c;\n D = d;\n E = e;\n F = f;\n }\n\n public override string ToString()\n {\n return $\"{A}x + {B}y = {C}{Environment.NewLine}{D}x + {E}y = {F}\";\n }\n}\n</code></pre>\n\n<p><strong>The contract between the solver and the generator of the constant values:</strong></p>\n\n<pre><code>public interface ICoefficientProvider\n{\n Coefficients GetCoefficients();\n}\n</code></pre>\n\n<p><strong>An object providing randomly generated coefficients to the system:</strong></p>\n\n<pre><code>/// <summary>\n/// Creates randomly generated coefficients to a linear system of two variables.\n/// </summary>\npublic class RandomCoefficientProvider : ICoefficientProvider\n{\n private readonly int min;\n private readonly int max;\n private readonly Random random;\n\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"min\">The inclusive lower boundary of the random numbers returned.</param>\n /// <param name=\"max\">The exclusive upper boundary of the random numbers returned.</param>\n /// <param name=\"randomSeed\"></param>\n public RandomCoefficientProvider(int min, int max, int? randomSeed = null)\n {\n this.min = Math.Min(min, max);\n this.max = Math.Max(min, max);\n random = randomSeed == null ? new Random() : new Random(randomSeed.Value);\n }\n\n public Coefficients GetCoefficients()\n {\n return new Coefficients\n (\n random.Next(min, max),\n random.Next(min, max),\n random.Next(min, max),\n random.Next(min, max),\n random.Next(min, max),\n random.Next(min, max)\n );\n }\n}\n</code></pre>\n\n<p><strong>Use Case:</strong></p>\n\n<pre><code> LinearSystemSolver solver = new LinearSystemSolver(10, new RandomCoefficientProvider(1, 10));\n if (solver.TrySolve(out IntegralLinearSystem result))\n {\n Console.WriteLine($\"Result:{Environment.NewLine}{result}\");\n }\n else\n {\n Console.WriteLine(\"No integral solution found\");\n }\n</code></pre>\n\n<p>As seen, I have created the interface <code>ICoefficientProvider</code> in order to separate the (random) creation of the constant values of the system from the workflow and calculations. \nIt gives me the possibility to implement another coefficient provider like the below - for testing purposes - without changing anything in the solver:</p>\n\n<pre><code>/// <summary>\n/// A Coefficient Provider that can be used for testing purposes\n/// </summary>\npublic class ConstantCoefficientProvider : ICoefficientProvider\n{\n private readonly Coefficients coefficients;\n\n public ConstantCoefficientProvider(int a, int b, int c, int d, int e, int f)\n {\n coefficients = new Coefficients(a, b, c, d, e, f);\n }\n\n public Coefficients GetCoefficients()\n {\n return coefficients;\n }\n}\n</code></pre>\n\n<p>You could easily extend this pattern of <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> to handle other parts of the program, for instance the calculations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T06:49:47.113",
"Id": "238928",
"ParentId": "238711",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:27:00.277",
"Id": "238711",
"Score": "5",
"Tags": [
"c#",
"performance",
"beginner",
"mathematics"
],
"Title": "Solving a linear system with two variables"
}
|
238711
|
<p>I've got a very very basic demo here that uses the <code>.stopPropagation</code> method. I want to just make it so that clicking on the <strong>parent element only</strong> runs the function, so I assumed I could use <code>e.stopPropagation()</code> as in the commented out line in the example below. However, that fails, which meant I had to apply the <code>stopPropagation()</code> method to the child element to prevent clicking on the child activating the initial click function.</p>
<p>Is this really the right way of doing this, or is there a better way? Something doesn't feel right here. Thanks for any help - the code is below</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var test = document.getElementById('test'),
child = document.getElementById('child');
test.addEventListener('click', function (e) {
//e.stopPropagation();
console.log('click');
});
child.addEventListener('click', function (e) {
e.stopPropagation();
console.log('clicked child - is there a better way of using e.stopPropagation() ?');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test {
background: red;
display: flex;
position: relative;
height: 30px;
width: 100%;
}
#child {
background: pink;
margin-top: 5em;
position: absolute;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='test'>
<div id='child'>child</div>
</div></code></pre>
</div>
</div>
</p>
<p>CodePen: <a href="https://codepen.io/ns91/pen/wvayqaE" rel="nofollow noreferrer">https://codepen.io/ns91/pen/wvayqaE</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T00:52:44.343",
"Id": "468247",
"Score": "0",
"body": "I don't think this is question for codereview. Here you ask for working code. What you are looking for is `useCapture`, which defines order in which events will be captured in your code. Try playing around with passing `true` or `false` as 3rd parameter. See more at:\nhttps://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-16T17:11:10.353",
"Id": "468730",
"Score": "0",
"body": "I thought stackoverflow was asking for working code and stack exchange code reviews was for optimising already working code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T18:17:49.633",
"Id": "502137",
"Score": "0",
"body": "Do you need an event triggered when the child is clicked, or just trying to have an event triggered **only** when the parent is clicked and nothing should happen when a child element is clicked?"
}
] |
[
{
"body": "<h2>Your Question</h2>\n<blockquote>\n<p>Is this really the right way of doing this, or is there a better way? Something doesn't feel right here.</p>\n</blockquote>\n<p>The term "<em>better</em>" is subjective so you can judge for yourself. Presuming there is not a need to have clicks on the child elements trigger any event handlers, one alternative is to use the CSS property <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events\" rel=\"nofollow noreferrer\"><code>pointer-events</code></a> style. One could use the value <code>none</code>:</p>\n<blockquote>\n<p><strong>none</strong><br>\nThe element is never the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/target\" rel=\"nofollow noreferrer\">target</a> of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles\" rel=\"nofollow noreferrer\">bubble</a> phases.</p>\n</blockquote>\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>var test = document.getElementById('test'),\n child = document.getElementById('child');\n\ntest.addEventListener('click', function (e) {\n console.log('click on parent without stopping propagation');\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#test {\n background: red;\n display: flex;\n position: relative;\n height: 30px;\n width: 100%;\n}\n#child {\n background: pink;\n margin-top: 5em;\n position: absolute;\n pointer-events: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id='test'>\n <div id='child'>child</div>\n</div></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-20T08:49:32.180",
"Id": "254985",
"ParentId": "238712",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254985",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:28:50.857",
"Id": "238712",
"Score": "3",
"Tags": [
"javascript",
"event-handling"
],
"Title": "Basic event stopPropagation() example - a better way of doing so?"
}
|
238712
|
<p>I wrote this code which has the ability to download images and videos from a specific Instagram profile.</p>
<p>Using multiprocessing and threading I managed to speed up the extraction of data.</p>
<p>My goal is to achieve: </p>
<ol>
<li>Make it faster (if it is possible)</li>
<li>Writing less code (if it is possible)</li>
<li>Using better methods (if it is possible)</li>
</ol>
<pre><code>import string
import requests
import os
import time
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import sys
from multiprocessing.dummy import Pool
import random
import urllib.parse
import argparse
import threading
LINKS = []
PICTURES = []
VIDEO = []
class Errors:
"""Checking Instagram Profiles"""
def __init__(self, link, cookies=None):
self.link = urllib.parse.urljoin(link, "?__a=1")
self.cookies = cookies
if self.cookies is not None:
self.cookies = cookies
def availability(self):
"""
Check The Profile Availability
From status_code and from graphql json that provides the link https://www.instagram.com/{username}/?__a=1
:return: True, If it's not private or its available
"""
search = requests.get(self.link, self.cookies)
if search.status_code == 404:
return "Sorry, this page isn't available."
elif search.json()["graphql"]["user"]["is_private"] is True:
return "This Account is Private"
else:
return True
class fetch_urls(threading.Thread):
def __init__(self, url, cookies=None):
threading.Thread.__init__(self)
self.cookies = cookies
if self.cookies is not None:
self.cookies = cookies
self.url = url
def run(self):
"""Extract Images or Videos From Every Url Using json and graphql"""
logging_page_id = requests.get(self.url.split()[0], cookies=COOKIES).json()
try:
"""Taking Url from Gallery Photos or Videos"""
for i in range(len(logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'])):
video = \
logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i]['node'][
"is_video"]
if video is True:
video_url = \
logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i][
'node'][
"video_url"]
if video_url not in VIDEO:
VIDEO.append(video_url)
else:
image = \
logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][i][
'node'][
'display_url']
if image not in PICTURES:
PICTURES.append(image)
except KeyError:
"""Unique url from photo or Video"""
image = logging_page_id['graphql']['shortcode_media']['display_url']
if image not in PICTURES:
PICTURES.append(image)
if logging_page_id['graphql']['shortcode_media']["is_video"] is True:
videos = logging_page_id['graphql']['shortcode_media']["video_url"]
if videos not in VIDEO:
VIDEO.append(videos)
class Instagram_pv:
def close(self):
self.driver.close()
def __init__(self, username, password, folder, name):
"""
:param username: The username
:param password: The password
:param folder: The folder name that images and videos will be saved
:param name: The instagram name that will search
"""
self.username = username
self.password = password
self.name = name
self.folder = folder
try:
self.driver = webdriver.Chrome()
except WebDriverException as e:
print(str(e))
sys.exit(1)
def control(self):
"""
Create the folder name and raises an error if already exists
"""
if not os.path.exists(self.folder):
os.mkdir(self.folder)
else:
self.close()
raise FileExistsError("[*] Alredy Exists This Folder")
def login(self):
"""Login To Instagram"""
self.driver.get("https://www.instagram.com/accounts/login")
time.sleep(3)
self.driver.find_element_by_name('username').send_keys(self.username)
self.driver.find_element_by_name('password').send_keys(self.password)
submit = self.driver.find_element_by_tag_name('form')
submit.submit()
time.sleep(3)
try:
"""Check For Invalid Credentials"""
var_error = self.driver.find_element_by_class_name("eiCW-").text
if len(var_error) > 0:
print(var_error)
sys.exit(1)
except WebDriverException:
pass
try:
self.driver.find_element_by_xpath('//button[text()="Not Now"]').click()
except WebDriverException:
pass
time.sleep(2)
"""Taking Cookies To pass it in requests If the Profile is Private and you are following,
otherwise the data from graphql will be incomplete"""
cookies = self.driver.get_cookies()
needed_cookies = ['csrftoken', 'ds_user_id', 'ig_did', 'mid', 'sessionid']
global COOKIES
COOKIES = {cookies[i]['name']: cookies[i]['value'] for i in range(len(cookies)) if
cookies[i]['name'] in needed_cookies}
self.driver.get("https://www.instagram.com/{name}/".format(name=self.name))
"""From The Class <Errors> Checking the Profile Availability"""
error = Errors("https://www.instagram.com/{name}/".format(name=self.name), COOKIES).availability()
if error is not True:
print(error)
self.close()
sys.exit(1)
else:
self._scroll_down()
def _get_href(self):
elements = self.driver.find_elements_by_xpath("//a[@href]")
for elem in elements:
urls = elem.get_attribute("href")
if "p" in urls.split("/"):
LINKS.append(urls)
def _scroll_down(self):
"""Taking hrefs while scrolling down"""
end_scroll = []
while True:
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
self._get_href()
time.sleep(2)
new_height = self.driver.execute_script("return document.body.scrollHeight")
end_scroll.append(new_height)
if end_scroll.count(end_scroll[-1]) > 4:
self.close()
self.extraction_url()
break
def extraction_url(self):
"""Gathering Images and Videos Using Threads From Class <fetch_urls>"""
links = list(set(LINKS))
print("[!] Ready for video - images".title())
print("[*] extracting {links} posts , please wait...".format(links=len(links)).title())
for url in LINKS:
new_link = urllib.parse.urljoin(url, '?__a=1')
fetch_urls(new_link).start()
for thread in threading.enumerate():
if thread is not threading.currentThread():
thread.join()
def content_of_url(self, url):
re = requests.get(url)
return re.content
def _download_video(self, new_videos):
"""
Saving the content of video in the file
"""
with open(
os.path.join(self.folder, "Video{}.mp4").format(
"".join([random.choice(string.digits) for i in range(20)])),
"wb") as f:
content_of_video = self.content_of_url(new_videos)
f.write(content_of_video)
def _images_download(self, new_pictures):
"""Saving the content of picture in the file"""
with open(
os.path.join(self.folder, "Image{}.jpg").format(
"".join([random.choice(string.digits) for i in range(20)])),
"wb") as f:
content_of_picture = self.content_of_url(new_pictures)
f.write(content_of_picture)
def downloading_video_images(self):
"""Using multiprocessing for Saving Images and Videos"""
print("[*] ready for saving images and videos!".title())
new_pictures = list(set(PICTURES))
new_videos = list(set(VIDEO))
pool = Pool(8)
pool.map(self._images_download, new_pictures)
pool.map(self._download_video, new_videos)
print("[+] done".title())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username", help='Username or your email of your account', action="store",
required=True)
parser.add_argument("-p", "--password", help='Password of your account', action="store", required=True)
parser.add_argument("-f", "--filename", help='Filename for storing data', action="store", required=True)
parser.add_argument("-n", "--name", help='Name to search', action="store", required=True)
args = parser.parse_args()
ipv = Instagram_pv(args.username, args.password, args.filename, args.name)
ipv.control()
ipv.login()
ipv.downloading_video_images()
</code></pre>
<p>Usage of code:</p>
<pre><code>myfile.py -u example@hotmail.com -p mypassword -f myfile -n stackoverjoke
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T23:10:08.883",
"Id": "468415",
"Score": "0",
"body": "Can you explain what the code is doing? I see no documentation, so having to reverse engineer the code is going to be annoying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T01:50:16.673",
"Id": "468425",
"Score": "0",
"body": "@AMC You are right. I already updated! I tried to write how it works, i hope will not need more. Thanks for the observation!"
}
] |
[
{
"body": "<h2>Error management</h2>\n\n<p>This:</p>\n\n<pre><code> if search.status_code == 404:\n return \"Sorry, this page isn't available.\"\n elif search.json()[\"graphql\"][\"user\"][\"is_private\"] is True:\n return \"This Account is Private\"\n else:\n return True\n</code></pre>\n\n<p>is problematic. First of all, you're mixing return types (boolean and string). More importantly: returning \"string if error or true-boolean otherwise\" is a nasty mix of in-band error signalling, mixing of user display vs. business logic concerns, and tight coupling.</p>\n\n<p>Instead of this <code>Errors</code> class, you could consider writing a method <code>check_availability</code>, which</p>\n\n<ul>\n<li>accepts the same parameters as your <code>__init__</code></li>\n<li>fires off the same request</li>\n<li>calls <code>search.raise_for_status()</code>, potentially catching and wrapping any exception that arises - this will cover your 404 and dozens of other HTTP errors</li>\n<li>does the JSON load-and-check, and if there are any issues, raise an exception. It's important to note that your <code>[\"graphql\"][\"user\"][\"is_private\"]</code> is fragile, so any key errors will currently be thrown with no additional information. Either catch and wrap that key error, or be more careful and use <code>get</code> on those nested dictionaries.</li>\n<li>If nothing is wrong, do not throw an exception and simply return.</li>\n</ul>\n\n<p>The above, combined with custom exception types, will make your program much more programmer-friendly and will improve the structure of your code.</p>\n\n<h2>Case conventions</h2>\n\n<p><code>fetch_urls</code> should be <code>FetchURLs</code>. That said, its name makes it sound like a function when it's currently a class. So either:</p>\n\n<ul>\n<li>Just make it a function; it's not really useful as a class anyway; or</li>\n<li>Name it something like <code>URLFetcher</code>.</li>\n</ul>\n\n<h2>Puzzling <code>None</code> logic</h2>\n\n<pre><code> self.cookies = cookies\n if self.cookies is not None:\n self.cookies = cookies\n</code></pre>\n\n<p>Not sure what you were going for here. The <code>if</code> can be dropped altogether, as it doesn't affect what will land in <code>self.cookies</code>.</p>\n\n<h2>Cookie management</h2>\n\n<p>This:</p>\n\n<pre><code> global COOKIES\n COOKIES = {cookies[i]['name']: cookies[i]['value'] for i in range(len(cookies)) if\n cookies[i]['name'] in needed_cookies}\n</code></pre>\n\n<p>is also problematic. First of all, globals are a code smell, particularly when they're set from outside of global scope like this. Second of all, rather than manipulating these cookies yourself, you may want to set up a Requests session object and pass it around to those who need to use requests with that cookie jar. Advantages are that any additional cookies modified in the following web traffic will be obeyed. Disadvantages are that you may end up carrying around state that (a) you don't care about, or (b) actively harms your workflow; but these are unlikely.</p>\n\n<h2>Method order</h2>\n\n<pre><code> def close(self):\n self.driver.close()\n</code></pre>\n\n<p>should appear after <code>__init__</code>, which should almost always appear first. Also: since you have a driver that needs closing, you should make <code>InstagramPV</code> a context manager and refer to it using a <code>with</code> block so that the driver gets closed regardless of any exceptions that take place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T03:44:02.780",
"Id": "468431",
"Score": "0",
"body": "Perfect explanation!!! I have only one question. What do you mean by \"Just make it a function; it's not really useful as a class anyway;\" Also, can i update my post using your advises ? Thank you so much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T03:53:00.030",
"Id": "468432",
"Score": "0",
"body": "_can i update my post using your advises_ - Please don't; CR policy is that you open a new question after each round of review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T03:58:06.207",
"Id": "468434",
"Score": "1",
"body": "_What do you mean by \"Just make it a function\"_ - You haven't really gained anything by making `fetch_urls` a class. It's a fairly reasonable implementation of `threading.Thread`, but it could just as well be spawned as a function passed to `thread.start_new_thread`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T04:00:11.070",
"Id": "468435",
"Score": "1",
"body": "n.b. rather than `start_new_thread`, if you're in Python 3, you can pass a function to the `target` parameter of `Thread`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T19:08:26.923",
"Id": "468502",
"Score": "0",
"body": "I appreciate your advises that you gave to me and the time that you spend explaining me my mistakes. Thank you very much for the knowledge!! I already fixed my code and i would like to show you, if its possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T19:09:41.700",
"Id": "468503",
"Score": "1",
"body": "The best place to show me is in a new question :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T00:21:29.713",
"Id": "468525",
"Score": "0",
"body": "[new question](https://codereview.stackexchange.com/questions/238902/scraping-instagram-with-selenium-extract-urls-download-posts)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T02:24:56.670",
"Id": "238862",
"ParentId": "238713",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238862",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:38:02.193",
"Id": "238713",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"selenium",
"instagram"
],
"Title": "Instagram scraper Posts (Videos and Photos)"
}
|
238713
|
<p>I am working on a <a href="https://www.kaggle.com/kimjihoo/coronavirusdataset" rel="noreferrer">dataset</a> which contains a column with common country names.</p>
<p>Task: To convert country name into standard ISO names</p>
<p>I have written a basic function which converts country names into country codes using <code>pycountry</code> library.</p>
<pre><code>import pandas as pd
import pycountry
df = pd.DataFrame({"Country":["China","US","Iceland"])
def do_fuzzy_search(country):
try:
result = pycountry.countries.search_fuzzy(country)
return result[0].alpha_3
except:
return np.nan
df["country_code"] = df["Country"].apply(lambda country: do_fuzzy_search(country))
</code></pre>
<p>But I am facing issues.Its taking too long. My dataset has 17003 rows,which is not even that large a number.</p>
<p>Firstly, suggestions on the code to improve its performance would be welcome.</p>
<p>Secondly, I would like to know if there is completely different way to do this faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:41:25.910",
"Id": "468181",
"Score": "0",
"body": "It would help if you could add some more context. The speed of this will (partially) depend on how you are calling this code and what *large* means in your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T15:56:48.537",
"Id": "468183",
"Score": "1",
"body": "I have edited the question as per your suggestion.If there is any thing more I can do to improve my question I would welcome the it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:11:23.033",
"Id": "468186",
"Score": "0",
"body": "Aren't your firstly and secondly the same question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:18:52.197",
"Id": "468188",
"Score": "0",
"body": "Actually,i my second question is if I can do this completely differently using some other way by ignoring this code if need be.Any reference material in that case for that would be welcome."
}
] |
[
{
"body": "<p>I always get my code to be as clean as possible before starting work on performance. Here you have a bare <code>except</code>, which can hide errors. Change it to something better, for now I'll change it to <code>Exception</code>. You are also hiding a potential <code>IndexError</code> and <code>AttributeError</code> if the data ever changes shape as they are in the <code>try</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def do_fuzzy_search(country):\n try:\n result = pycountry.countries.search_fuzzy(country)\n except Exception:\n return np.nan\n else:\n return result[0].alpha_3\n</code></pre>\n\n<p>Since there are roughly <a href=\"https://en.wikipedia.org/wiki/List_of_sovereign_states\" rel=\"noreferrer\">200 sovereign states</a> and you're working with 17003 rows you likely have a lot of the same values hitting a costly function. To resolve this issue you can use <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"noreferrer\"><code>functools.lru_cache</code></a>. Running in amortized <span class=\"math-container\">\\$O(n)\\$</span> time and <span class=\"math-container\">\\$O(n)\\$</span> space.</p>\n\n<pre><code>@functools.lru_cache(None)\ndef do_fuzzy_search(country):\n ...\n</code></pre>\n\n<p>Alternately you can sort the data by the provided countries name and then get each country once. Running in <span class=\"math-container\">\\$O(n\\log n)\\$</span> time and <span class=\"math-container\">\\$O(1)\\$</span> space.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:39:30.933",
"Id": "468191",
"Score": "0",
"body": "Both the codes look so similar.I would like to learn how your code improves upon my defects of try except."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T10:51:12.297",
"Id": "468259",
"Score": "3",
"body": "@AkhilSharma The first change is to only catch `Exception`s. By default, `except` catches `BaseException`, which also includes `GeneratorExit`, `SystemExit`, and `KeyboardInterrupt`. The second change is to use `try...else` so that any exception raised in `result[0].alpha_3` is not caught with `except`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:20:28.613",
"Id": "238717",
"ParentId": "238714",
"Score": "12"
}
},
{
"body": "<p>The question I have is why do you have 17K rows when there are only 200+ countries. Are the country names translated in many languages perhaps ? Isn't it conceivable to use a simplified dataset ? What does the current dataset look like ?</p>\n\n<p>When you're saying \"Its taking too long\", do you mean the function is too slow (how long does it take on average ?), or it is because you have a lot of data to process ?\nIf some of the data is repetitive, perhaps you could regroup the identical records so as to call the function only once instead of repeating the process for each row.\nBasically, reorder the data a bit before processing by your script.</p>\n\n<p>Maybe the task could be performed equally fine in SQL, for example from a <strong>SQLite</strong> DB with an appropriate <code>LIKE</code> or a <code>MATCH</code> clause (or even <code>soundex</code> - <em>not available by default, requires recompilation</em>), possibly using <a href=\"https://www.sqlite.org/fts5.html\" rel=\"nofollow noreferrer\">FTS</a> or <a href=\"https://www.sqlite.org/partialindex.html\" rel=\"nofollow noreferrer\">(partial) indexes</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:30:04.497",
"Id": "468200",
"Score": "0",
"body": "Actually,each of the row is a Covid patient belonging to some certain country."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:07:16.637",
"Id": "238721",
"ParentId": "238714",
"Score": "3"
}
},
{
"body": "<p>Here is a way to do this differently. You will have to test it to see if it is actually faster (since I don't have an example of 17k different almost matching ways to write countries).</p>\n\n<p>First note that you can extract the underlying data used by <code>pycountry</code>. On my machine the file containing the data on all existing countries can be found at <code>/usr/local/lib/python3.6/dist-packages/pycountry/databases/iso3166-1.json</code>. Depending on your OS this will be in a different place, but the actual filename should be the same.</p>\n\n<p>Next, there exists a tool that can directly merge dataframes on certain columns, using fuzzy search, called <a href=\"https://pypi.org/project/fuzzy-pandas/\" rel=\"nofollow noreferrer\"><code>fuzzy_pandas</code></a>. With it you can do something like this:</p>\n\n<pre><code>import json\nimport pandas as pd\nimport fuzzy_pandas as fpd\n\nwith open(\"/tmp/iso3166-1.json\") as f:\n countries = pd.DataFrame.from_dict(json.load(f)[\"3166-1\"])\ncountries = countries.drop(columns=[\"alpha_2\", \"numeric\"])\ncountries = countries.fillna(method=\"ffill\", axis=1)\n\ndata = pd.DataFrame({\"country\": [\"Samos\", \"Germanz\"]})\n\n\nfpd.fuzzy_merge(data, countries, left_on=[\"country\"], right_on=[\"name\"], method=\"levenshtein\")\n# country alpha_3 name official_name common_name\n# 0 Samos WSM Samoa Independent State of Samoa Independent State of Samoa\n# 1 Germanz DEU Germany Federal Republic of Germany Federal Republic of Germany\n</code></pre>\n\n<p>You might have to try which column to use for <code>right_on</code>. You might have to use all of them in separate calls to <code>pfd.fuzzy_merge</code> and then decide what to do with the ones that give different results. In the implementation of <code>pycountry</code> the name and official name are used and given a certain weighting factor:</p>\n\n<pre><code> # Prio 3: partial matches on country names\n for candidate in countries:\n # Higher priority for a match on the common name\n for v in [candidate._fields.get('name'),\n candidate._fields.get('official_name')]:\n if v is None:\n continue\n v = remove_accents(v.lower())\n if query in v:\n # This prefers countries with a match early in their name\n # and also balances against countries with a number of\n # partial matches and their name containing 'new' in the\n # middle\n add_result(candidate, max([5, 30-(2*v.find(query))]))\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T07:36:04.557",
"Id": "238751",
"ParentId": "238714",
"Score": "4"
}
},
{
"body": "<p>Apart from speeding up your code, there are some other improvements possible that I don't see mentioned yet.</p>\n\n<h1>The speedup</h1>\n\n<p>As other users have already picked up, you only need to transform around 200 countries instead of 17k rows. You can do this efficiently by storing the mapping in a <strong>dictionary</strong>:</p>\n\n<pre><code>iso_map = {country: do_fuzzy_search(country) for country in df[\"Country\"].unique()}\ndf[\"country_code\"] = df[\"Country\"].map(iso_map)\n</code></pre>\n\n<p>This is in essence very similar to using the <code>lru_cache</code> proposed by Peilonrayz, but it's a bit more explicit.</p>\n\n<hr>\n\n<h1>Consistent naming</h1>\n\n<p>As a side note, I would advise you to use a consistent naming scheme in your DataFrame. This doesn't have to follow the python convention, but it should be easy to remember.</p>\n\n<p>For example, turn all columns to lowercase by using something like:</p>\n\n<pre><code>df = df.rename(columns = {name: name.lower() for name in df.columns}\n</code></pre>\n\n<hr>\n\n<h1>Using categoricals</h1>\n\n<p>Since the number of countries (and isocodes) is limited, you might want to consider using <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html\" rel=\"noreferrer\">categorical columns</a>. These have the advantage of requiring less memory and being faster on some operations. </p>\n\n<p>It might not be worth the extra lines of code in your situation, but it's something useful to keep in the back of your mind.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T07:48:01.540",
"Id": "238752",
"ParentId": "238714",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "238717",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:53:17.733",
"Id": "238714",
"Score": "8",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Basic function to convert Country name to ISO code using Pycountry"
}
|
238714
|
<p>I made a sequence and series solver just for helping me solve homework, and I'm in dire need of ways to make it further compact and efficient, since I used brute force.</p>
<p>If you want to see what this is supposed to do, please see my <a href="https://github.com/MahdeenSky/MicroPythonCalculator/tree/master/MY%20PROJECTS/Sequence%20%26%20Series%20Solver" rel="nofollow noreferrer">github</a>.</p>
<p>This Python code is meant for the fx-cg50 calculator's <strong>micropython</strong>, where there are a lot of functions that don't work including fractions, some mathematical functions such as <code>math.gcd</code> and <code>math.isclose</code>. So I really require some advice or coding tricks to simplify my program.</p>
<p>Disclaimer: I'm only an A-Level student of 16 years; consider me a beginner. I know <code>eval</code> is insecure, but I'm not planning on uploading this online; it's only for my personal use.</p>
<pre class="lang-py prettyprint-override"><code># just to make the input_checker function smaller and to eliminate repeated code, responsible for iterating through a list of inputs
def three_variables_looper_arithmetic():
count_list = [input("enter a1: "), input("enter n: "), input("enter d: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
# just to make the input_checker function smaller and to eliminate repeated code, responsible for iterating through a list of inputs
def three_variables_looper_geometric():
count_list = [input("enter a1: "), input("enter r: "), input("enter n: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
# loops through all the inputs of a given situation based on whether its arithmetic
# or not, and checks whether the input is string like "6/2" so it could evaluate it, allows input of fractions
def input_checker(choice_main, choice_sub, L):
if choice_main == 'arithmetic':
if choice_sub == 'a_nth':
return three_variables_looper_arithmetic()
elif choice_sub == 'sum_to_nth_without_L':
return three_variables_looper_arithmetic()
elif choice_sub == 'sum_to_nth_with_L':
count_list = [input("enter a1: "), input("enter n: "), L]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_sub == "a_nth_exceed":
count_list = [input("enter a1: "), input("enter r/d: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_sub == "sum_to_nth_without_L_exceed":
count_list = [input("enter a1: "), input("enter r/d: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_sub == "sum_to_nth_with_L_exceed":
count_list = [input("enter a1: "), L]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_main == 'geometric':
if choice_sub == 'a_nth':
return three_variables_looper_geometric()
elif choice_sub == 'sum_to_nth':
return three_variables_looper_geometric()
elif choice_sub == 'sum_to_infinity':
count_list = [input("enter a1: "), input("enter r: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_sub == "a_nth_exceed":
count_list = [input("enter a1: "), input("enter r/d: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
elif choice_sub == "sum_to_nth_without_L_exceed":
count_list = [input("enter a1: "), input("enter r/d: ")]
count_list = [float(eval(count)) for count in count_list if isinstance(count, str)]
return count_list
# checks if L is an x or not, also based on whether its on the exceed or normal path, and
# an x means L is not present, while a value of L represents it is present and used in calculation
def L_evaluator(L, option, choice_n, value):
if option == "normal":
if L == "x":
a1, n, d = input_checker(choice_main, choice_n, L)
result = (n/2)*(2*a1+(n-1)*d)
return result
else:
choice_n = choice_map_sub['x']
a1, n, L = input_checker(choice_main, choice_n, L)
result = (n/2)*(a1+L)
return result
if option == "exceed":
if L == "x":
a1, d = input_checker(choice_main, choice_n, 0)
a1, d = float(a1), float(d)
n = 1
while True:
result = (n/2)*(2*a1+(n-1)*d)
if (result >= float(value)):
break
n += 1
return n
else:
choice_n = choice_map_exceed['c']
a1, L = input_checker(choice_main, choice_n, L)
n = 1
while True:
result = (n/2)*(a1+L)
if (result >= float(value)):
break
n += 1
return n
# finds the first n to exceed a certain value, by using brute force method
def minimum_n_finder(choice_main, choice_map_exceed):
choice_n_input = None
if choice_main == "arithmetic":
while choice_n_input not in ['a', 'b']:
choice_n_input = input("Enter a for nth\nEnter b for sum\n>> ")
choice_n = choice_map_exceed[choice_n_input]
print("enter x in n")
if choice_n == "a_nth_exceed":
print("a1+(n-1)d > Value")
a1, d = input_checker(choice_main, choice_n, 0)
n = 1
value = input("Enter the value to exceed: ")
while True:
result = a1+(n-1)*d
if (result >= float(value)):
break
n += 1
print("The minimum n to exceed is " + str(n))
if choice_n == "sum_to_nth_without_L_exceed":
n = 1
print("Sn=(n/2)(2a1+(n-1)d)>Value\nSn=(n/2)(a1+L)>Value\nEnter x if L is unknown")
L = input("Enter L: ")
value = input("Enter the value to exceed: ")
result = L_evaluator(L, "exceed", choice_n, value)
print("The minimum n to exceed is " + str(result))
elif choice_main == 'geometric':
while choice_n_input not in ['a', 'b']:
choice_n_input = input("Enter a for nth\nEnter b for sum_to_nth\n>> ")
choice_n = choice_map_exceed[choice_n_input]
if choice_n == "a_nth_exceed":
print("a1(r)^(n-1)>Value")
a1, r = input_checker(choice_main, choice_n, 0)
if a1 == 0:
print("a cannot be 0")
raise SystemExit
n = 1
value = input("Enter the value to exceed: ")
while True:
result = a1*(r)**(n-1)
if (result >= float(value)):
break
n += 1
print("The minimum n to exceed is " + str(n))
elif choice_n == "sum_to_nth_without_L_exceed":
print("Sn=(a1(1-(r)^n))/(1-r)")
a1, r = input_checker(choice_main, choice_n, 0)
if a1 == 0:
print("a cannot be 0")
raise SystemExit
n = 1
value = input("Enter the value to exceed: ")
while True:
result = (a1*(1-(r)**n))/(1-r)
if (result >= float(value)):
break
n += 1
print("The minimum n to exceed is " + str(n))
# as this code is for a calculator the x button is very easily accessible to shut the whole program.
def stopper():
stop_or_continue = input("Stop?: enter x then\n>>> ")
if stop_or_continue == "x":
raise SystemExit
print("Sequence & Series Solver")
# asks whether you want to solve arithmetically or geometrically, depends on the sequence/series
while True:
choice_main , choice_input_main = None, None
choices_main_options = ['a','b']
choice_map_main ={"a": 'arithmetic', "b": 'geometric'}
while choice_input_main not in choices_main_options:
choice_input_main = input("a for arithmetic\nb for geometric\n>> ")
choice_main = choice_map_main[choice_input_main]
if choice_main == "arithmetic":
print("Arithmetic: ")
choice_sub, choice_input_sub = None, None
choices_sub_options = ['a', 'b', 'c']
choice_map_sub = {'a': 'a_nth', 'b': 'sum_to_nth_without_L', 'x': 'sum_to_nth_with_L', 'c':'minimum_number_of_terms_to_exceed'}
while choice_input_sub not in choices_sub_options:
choice_input_sub = input("a for a_nth term\nb for sum\nc for min_term_to_exceed\n>> ")
choice_sub = choice_map_sub[choice_input_sub]
# the variable choice_main refers to whether the choice is arithmetic or geometric
# choice_sub refers to the types of formulas you'll use in sequences/series
if choice_sub == "a_nth":
print("a_nth=a1+(n-1)d")
a1, n, d = input_checker(choice_main, choice_sub, 0)
result = a1+(n-1)*d
print(round(result,4))
elif choice_sub == "sum_to_nth_without_L":
print("Sn=(n/2)(2a1+(n-1)d)\nSn=(n/2)(a1+L)\nEnter x if L is unknown")
L = input("Enter L: ")
print(round(L_evaluator(L, "normal", choice_sub, 0), 4))
elif choice_sub == "minimum_number_of_terms_to_exceed":
choice_map_exceed = {'a': 'a_nth_exceed', 'b': 'sum_to_nth_without_L_exceed', 'c': 'sum_to_nth_with_L_exceed'}
minimum_n_finder("arithmetic", choice_map_exceed)
elif choice_main == "geometric":
print("Geometric: ")
choice_sub, choice_input_sub = None, None
choices_sub_options = ['a', 'b', 'c', 'd']
choice_map_sub = {'a': 'a_nth', 'b': 'sum_to_nth', 'c': 'sum_to_infinity', 'd': 'minimum_number_of_terms_to_exceed'}
while choice_input_sub not in choices_sub_options:
choice_input_sub = input("a for a_nth term\nb for sum\nc for sum to infinity\nd for min_terms_exceed\n>> ")
choice_sub = choice_map_sub[choice_input_sub]
if choice_sub == "a_nth":
print("a_nth=a1(r)^(n-1)")
a1, r, n = input_checker(choice_main, choice_sub, 0)
result = a1*(r)**(n-1)
print(round(result,4))
elif choice_sub == "sum_to_nth":
print("Sn=(a1(1-(r)^n))/(1-r)")
a1, r, n = input_checker(choice_main, choice_sub, 0)
try:
result = (a1*(1-(r)**n))/(1-r)
print(round(result,4))
except (ZeroDivisionError, NameError):
print("r cannot be 1!")
elif choice_sub == "sum_to_infinity":
print("S_inf=a1/(1-r)")
a1, r = input_checker(choice_main, choice_sub, 0)
if (r > 1):
print("r cannot be greater than 1")
raise SystemExit
try:
result = a1/(1-r)
print(round(result,4))
except (ZeroDivisionError, NameError):
print("r cannot be 1!")
elif choice_sub == "minimum_number_of_terms_to_exceed":
choice_map_exceed = {'a': 'a_nth_exceed', 'b': 'sum_to_nth_without_L_exceed', 'c': 'sum_to_nth_with_L_exceed'}
minimum_n_finder("geometric", choice_map_exceed)
stopper()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:13:02.240",
"Id": "468198",
"Score": "0",
"body": "What would the user enter when asked for `enter a1:`? A mathematical expression?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:14:08.587",
"Id": "468224",
"Score": "0",
"body": "yeah i set the prints before the input to show the formula so youd know what you are entering to calculate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:14:57.080",
"Id": "468226",
"Score": "0",
"body": "and each input like a1, r/d, is one value not an expression, tho the expression could be 1/2 for example or generally something that isnt whole and could be expressed using only fractions"
}
] |
[
{
"body": "<p>First, you can just return the list comprehension instead of first overwriting <code>count_list</code>. That should save you a few lines without affecting readability.</p>\n\n<p>For all of your if-cases, you could use a dictionary instead. So that if <code>choice_sub in dict.keys(): dict[choice_sub]</code>.</p>\n\n<p>Generally, when functions are getting as long as yours are, it's a good idea to start thinking about OOP and classes. And you could separate the \"front-end\" (all of your prints and inputs) from your \"back-end\" (the functions/methods performing the calculations). This would also make it easier on yourself if you want to migrate away from a CLI app to something with a graphical interface (which could help make the formatting of the formulas more readable).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T14:52:17.177",
"Id": "238885",
"ParentId": "238716",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238885",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:02:30.800",
"Id": "238716",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator",
"math-expression-eval"
],
"Title": "Sequence and Series Solver"
}
|
238716
|
<p>I'm creating an option checkbox for an Organization data only if they have Organization data to submit from their CSV. I am creating a <code><div></code> and my <code><select></code> and <code><option></code> are wrapped inside of the <code><div></code>.</p>
<p>Do I need to create an input ? I'm in Vue.js and don't see any current methods or <code>v-if</code> nested in the right way. I want this selection of this checkbox to be done upon upload of the CSV and prior to submit. </p>
<h3>HTML</h3>
<pre><code><div class="large-12 medium-12 small-12 cell">
<input type="checkbox" id="organization" ref="Organization" v-model="checkbox" :v-if="field in requiredOrganizationFields"
<h1 class="mb-7 mt-5 ml-6 font-bold text-2xl"> Organization Fields</h1>
<div v-for="field in requiredOrganizationFields" class="p-8 -mr-6 -mb-6 flex flex-wrap" style="width:150px">
<label :for="field" type="select" name="field">{{field}}</label>
<select :id="field" :name="field" v-model="mapping[field]" required>
<option value="">Please Select</option>
<option v-for="columnName in columnNames" :name="columnName" :value="columnName" value="">{{columnName}}</option>
</select>
</div>
</div>
</code></pre>
<h3>JavaScript</h3>
<pre><code> data: null,
columnNames: [],
file: null,
requiredContactFields: [
'contact_account_name',
'contact_first_name',
'contact_last_name'
],
optionalContactFields: [
'contact_email',
'contact_phone',
'contact_address',
'contact_city',
'contact_region',
'contact_postal_code'
],
requiredOrganizationFields: [
'organization_account_name',
'organization_name'
],
optionalOrganizationFields: [
'organization_email',
'organization_phone',
'organization_address',
'organization_city',
'organization_region',
'organization_postal_code'
]
}
getColumnNames() {
let formData = new FormData();
formData.append('file', this.file);
let self = this;
axios
.post('http://localhost:8080/api/contacts/csv-column-names',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function(response){
console.log('SUCCESS!!');
console.log(response);
//Need array of column names you get from the back-end
self.columnNames = response.data.column_names;
})
.catch(function(response){
console.log('FAILURE!!');
console.log(response);
})
},
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T17:04:57.433",
"Id": "468196",
"Score": "1",
"body": "@tieskedh That open tag in my Javascript is meant to be empty to allow user data to be passed through prior to submission. It is a problem that can be improved through nesting the v-if in the correct tag. Also the way someone simulates a shouting experience is by ALL-CAPS, not bolded letters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T10:45:12.053",
"Id": "468257",
"Score": "2",
"body": "Do you want a review of the code provided or are you more interested in the addition of a specific feature? Please clarify after looking at [our help center](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T18:13:19.880",
"Id": "468308",
"Score": "0",
"body": "Addition on specific features. There are no clear examples a single checkbox for this use case"
}
] |
[
{
"body": "<p>If you want to allow a user to be able to input an optional field after checking that check box it will go like this</p>\n\n<p>You bind the field you want to make optional in your v-model. Upon the click event that optional field should dropdown </p>\n\n<p><strong>HTML</strong> </p>\n\n<pre><code><label></label>\n <input type=\"checkbox\" name=\"show_organization_fields\" v-model=\"showOrganizationFields\">\n <div v-if=\"showOrganizationFields\">\n <h1 class=\"mb-7 mt-5 ml-6 font-bold text-2xl\">Organization Fields</h1> \n <div v-for=\"field in requiredOrganizationFields\" class=\"p-8 -mr-6 -mb-6 flex flex-wrap\" style=\"width:150px\">\n <label :for=\"field\" type=\"select\" name=\"field\">{{field}}</label>\n <select :id=\"field\" :name=\"field\" v-model=\"mapping[field]\" required>\n <option value=\"\">Please Select</option>\n <option v-for=\"columnName in columnNames\" :name=\"columnName\" :value=\"columnName\" value=\"\">{{columnName}}</option>\n </select>\n </div>\n</code></pre>\n\n<p><strong>Javascript</strong></p>\n\n<pre><code>data: null,\n columnNames: [],\n\n\n\n showOrganizationFields: false,\n\n\n file: null,\n requiredContactFields: [ \n 'contact_account_name',\n 'contact_first_name',\n 'contact_last_name'\n ],\n optionalContactFields: [\n 'contact_email',\n 'contact_phone',\n 'contact_address',\n 'contact_city',\n 'contact_region',\n 'contact_postal_code'\n ],\n requiredOrganizationFields: [\n 'organization_account_name',\n 'organization_name'\n ],\n optionalOrganizationFields: [\n 'organization_email',\n 'organization_phone',\n 'organization_address',\n 'organization_city',\n 'organization_region',\n 'organization_postal_code'\n\n ] \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T18:39:10.767",
"Id": "238788",
"ParentId": "238719",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238788",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T16:44:52.970",
"Id": "238719",
"Score": "0",
"Tags": [
"vue.js"
],
"Title": "Vue.js v-if for a checkbox selection of data from a csv"
}
|
238719
|
<p>I've created a Tic Tac Toe game in JS/HTML/CSS. Is there anyway this can be improved? Thanks</p>
<p>Codepen: <a href="https://codepen.io/KhushrajRathod/pen/wvaeOaZ" rel="nofollow noreferrer">https://codepen.io/KhushrajRathod/pen/wvaeOaZ</a></p>
<p>Github: <a href="https://github.com/KhushrajRathod/TicTacToe" rel="nofollow noreferrer">https://github.com/KhushrajRathod/TicTacToe</a></p>
<p>Demo: <a href="https://www.khushrajrathod.me/TicTacToe" rel="nofollow noreferrer">https://www.khushrajrathod.me/TicTacToe</a></p>
<p>Javascript:</p>
<pre><code>"use strict";
const grid = document.getElementById("grid").children
const x =
`<svg viewBox="0 0 40 40">
<path style="stroke: #506ded; stroke-width: 2;" d="M 10,10 L 30,30 M 30,10 L 10,30"></path>
</svg>`
const o =
`<svg viewBox="0 0 40 40">
<circle cx="20" cy="20" r="12" fill="#fff" style="stroke: #ea4335; stroke-width: 1.7;"></circle>
</svg>`
const winningPatterns = [
// Horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
// Vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
// Diagonal
[0, 4, 8],
[2, 4, 6]
]
let turn = x // Player 1 = X, Player 2 = Y
let turnsPlayed = 0
for (const item of grid) {
item.addEventListener("click", () => {
if (!item.innerHTML) { // Because "" is falsy
item.innerHTML = turn
turnsPlayed++
checkWin()
turn === x ? turn = o : turn = x // Reverse the value of "current"
}
})
}
function checkWin() {
for (const pattern of winningPatterns) {
if (grid[pattern[0]].innerHTML.toUpperCase() === turn.toUpperCase() && grid[pattern[1]].innerHTML.toUpperCase() === turn.toUpperCase() && grid[pattern[2]].innerHTML.toUpperCase() === turn.toUpperCase()) {
if (turn === x) {
win("X")
} else {
win("O")
}
return
}
}
if (turnsPlayed === 9) {
draw()
}
}
function win(player) {
swal({
title: player + " wins!",
text: "Would you like to play again?",
icon: "success",
buttons: ["No", "Yes"]
}).then ((choice) => {
if (!choice) { // NO
// noinspection SillyAssignmentJS
document.body.outerHTML = document.body.outerHTML // Disallow further moves by removing EventListeners
} else {
for (const item of grid) {
item.innerHTML = ""
}
turnsPlayed = 0
}
})
}
function draw() {
swal({
title: "Draw!",
text: "Would you like to play again?",
icon: "info",
buttons: ["No", "Yes"]
}).then ((choice) => {
if (!choice) { // NO
// noinspection SillyAssignmentJS
document.body.outerHTML = document.body.outerHTML // Disallow further moves by removing EventListeners
} else {
for (const item of grid) {
item.innerHTML = ""
}
turnsPlayed = 0
}
})
}
</code></pre>
<p>HTML (excluding HTML5 Boilerplate):</p>
<pre><code><div id="container">
<div id="grid">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
</div>
</div>
</code></pre>
<p>CSS (excluding normalize and HTML5 Boilerplate):</p>
<pre class="lang-css prettyprint-override"><code>body,
html {
height: 100%;
width: 100%;
overflow: hidden;
}
#container {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
#grid {
border: 2px solid #808080;
max-width: 400px;
max-height: 400px;
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
}
#grid > * {
border: 1px solid #808080;
}
* {
box-sizing: border-box;
}
/* X or O */
#grid > * > * {
width: 100%;
height: 100%;
}
/*! HTML5 Boilerplate v7.3.0 | MIT License | https://html5boilerplate.com/ */
/* main.css 2.0.0 | MIT License | https://github.com/h5bp/main.css#readme */
/*
* What follows is the result of much research on cross-browser styling.
* Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
* Kroc Camen, and the H5BP dev community and team.
*/
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><code>if (!item.innerHTML) { // Because \"\" is falsy</code>.</p>\n\n<p>If you need to add a comment then maybe the code isn't clear enough. I suggest either comparing it implicitly to an empty string, or using a data attribute to mark it as filled.</p></li>\n<li><p>In checkWin and the onClick listener, instead of relying on the innerHTML value, you should either use a virtual grid state, or save the state in a data attribute.</p></li>\n<li><p>The callback function of the would you like to play again is repeated for both the win and the draw functions. Thus, it should be extracted to be it's own function.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T23:36:06.590",
"Id": "238741",
"ParentId": "238725",
"Score": "2"
}
},
{
"body": "<ol>\n<li>I really don't like this svg code in javascript string. Why don't you put in html instead? It's presentation detail of your <code>X</code> and <code>O</code> has no meaning in your code. Edit: or even separate .svg file</li>\n<li>Extract your data from HTML. Your \"data\" are in html elements and <code>innerHTML</code>. That's just too tight.</li>\n<li>Your code is mix of different responsibilities (game itself, UI). Try to make tic tac toe game, which is completely independent of HTML. Good practice is to get it working using developer console. For example by adding function <code>move(x,y)</code>. Then you add another piece of code, that will handle only your game HTML interface - for example <code>move</code> function will be called from event fired by click on element. That way your code doesn't mix too many things at once and is a lot more clear. Make more functions, make them return value, use that value (ex: <code>checkWin</code> should return maybe boolean or maybe player who won or undefined, some other function should update UI based on the result). You can also very simply unit test that kind of code.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T00:38:00.003",
"Id": "238742",
"ParentId": "238725",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238741",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T18:28:22.343",
"Id": "238725",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"tic-tac-toe"
],
"Title": "Javascript Tic Tac Toe"
}
|
238725
|
<p>I have built a timer program in JavaScript. It decrements one counter every second, and if that counter is at zero, it decrements another counter, and sets the first counter to 59. If the second counter now is below zero, then it stops the timer. Would it be more efficient to store the total seconds left, and calculate the minutes on the fly? Is there other stuff I can improve on?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var timerRun; // Variable for holding the interval
var timeLeft; //Array; index 0 keeps track of the minutes, and index 1 keeps track of the seconds
var timerRunning = false; //Boolean to keep track of whether the timer is running
function tick() {
// Subtract 1 second
timeLeft[1] -= 1;
if (timeLeft[1] < 0) { // Decrement the minute if neccessary
timeLeft[0] -= 1;
timeLeft[1] = 59;
}
if (timeLeft[0] < 0) { // Check if the timer is done
clearInterval(timerRun);
alert("Timer is done!");
timerRunning = false;
document.getElementById("timer").innerHTML = "Simple Timer";
}
if (timeLeft[1] < 10) { // Display the seconds as a two-digit number
timeLeft[1] = "0" + timeLeft[1];
}
document.getElementById("timer").innerHTML = timeLeft.join(":");
if (timerRunning == false) {
document.getElementById("timer").innerHTML = "Simple Timer";
}
}
function time() { // Restart timer
clearInterval(timerRun)
timerRun = setInterval(tick, 1000);
// Create array
timeLeft = document.getElementById("time").value.split(":");
timerRunning = true;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="timer">Simple Timer</h1>
<input type="text" id="time" value="15:00">
<button type="button" onclick="time();" id="start">Start</button>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<ul>\n<li>You are basically trying to show timer, which can be up to hours. Best way to calculate and represent that for your usecase is definitely by just one variable, which holds all the seconds. That way your code handling current state is a lot simpler - you have just one variable, you decrease it every second until it's done.\nYou will have more work displaying that value as you will have to calculate minutes and seconds, but that's fine.</li>\n<li>Definitely extract that to function - you pass number of seconds and you get string representing it. You may even consider using library for that or a number formatter. There are plenty ways how to do that:\n<a href=\"https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds\">https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds</a></li>\n<li>Your variable <code>timerRunning</code> is redundant. In your code same meaning has expression <code>timeLeft[1] < 0 && timeLeft[0] < 0</code>. You really don't want redundancy, that leads to bugs. Again you can extract to function <code>isTimerRunning</code> if you need it. But again if you end up with only one <code>timeLeft</code> variable with representing all in seconds, you just need <code>!timeLeft</code> to check, if timer is over.</li>\n<li>Probably not a problem in your case, but keep in mind, that <code>setInterval</code> is not very reliable time-wise. It pings \"around\" every second, but it jumps a lot. More on this here:\n<a href=\"https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript\">https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript</a></li>\n</ul>\n\n<p>Edit:</p>\n\n<ul>\n<li>In this line <code>function time() { // Restart timer</code> you poorly name your function and then you have to comment it to describe what it does. Why not just name function <code>restartTimer</code> and you can delete comment?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T00:48:18.460",
"Id": "238743",
"ParentId": "238726",
"Score": "3"
}
},
{
"body": "<p>In large part I agree with K.H. so functions will be a much shorter:</p>\n\n<pre><code>function tick() {\n timeLeft -= 1;\n if (timeLeft < 0) { // Check if the timer is done\n clearInterval(timerRun);\n alert(\"Timer is done!\");\n document.getElementById(\"timer\").innerHTML = \"Simple Timer\";\n } else {\n timeDisplay = Math.round( timeLeft / 60 ) + \":\" + ( \"0\" + timeLeft % 60 ).slice(-2);\n document.getElementById(\"timer\").innerHTML = timeDisplay;\n }\n}\n\nfunction time() { // Restart timer\n clearInterval(timerRun)\n timerRun = setInterval(tick, 1000);\n // Create array\n timeLeft = document.getElementById(\"time\").value.split(\":\");\n timeLeft = timeLeft[0]*60 + parseInt(timeLeft[1]); // change array to seconds\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T07:57:59.790",
"Id": "468448",
"Score": "0",
"body": "Nice, that also shows poor naming of `time` function in original question. I updated my answer :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T19:28:57.647",
"Id": "238845",
"ParentId": "238726",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T18:40:09.527",
"Id": "238726",
"Score": "3",
"Tags": [
"javascript",
"performance",
"html",
"timer"
],
"Title": "Simple Timer Program"
}
|
238726
|
<p>In my programming class I am learning how to make graphical user interfaces, and so I decided to make one.</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as t
from random import choice
COLORS = ["white", "black", "red", "green", "blue", "cyan", "yellow", "magenta"]
def button_clicked():
display_area.config(text = "You clicked the button!")
screen.itemconfig(epilepsy_man, fill = choice(COLORS))
def epilepsy_man_movment(event):
key = event.keysym
if key == "Right":
screen.move(epilepsy_man, 10, 0)
screen.itemconfig(epilepsy_man, fill = choice(COLORS))
elif key == "Left":
screen.move(epilepsy_man, -10, 0)
screen.itemconfig(epilepsy_man, fill = choice(COLORS))
elif key == "Up":
screen.move(epilepsy_man, 0, -10)
screen.itemconfig(epilepsy_man, fill = choice(COLORS))
elif key == "Down":
screen.move(epilepsy_man, 0, 10)
screen.itemconfig(epilepsy_man, fill = choice(COLORS))
window = t.Tk()
window.title("Your reading this right now. Please stop.")
button = t.Button(window, text = "Can you click me?", command = button_clicked)
button.pack()
display_area = t.Label(window, text = "Go on! Click the button!")
display_area.pack()
screen = t.Canvas(window, width = 500, height = 500)
screen.pack()
epilepsy_man = screen.create_oval(200, 200, 300, 300, fill = choice(COLORS))
screen.bind_all("<Key>", epilepsy_man_movment)
window.mainloop()
</code></pre>
<p><strong>Please note</strong> "epilepsy". If you run this there will be flashing images.</p>
<p>I want to know if I properly followed any conventions, as well as if there is any better way of doing what I have done.</p>
<p>What this program does is make a button that changes the color of the circle and the text on a textbox, as well as creating said textbox and said circle which moves with the arrow keys and changes with each key press.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:50:59.380",
"Id": "468215",
"Score": "2",
"body": "Can I have a better explanation of the close vote and the downvotes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:06:02.480",
"Id": "468222",
"Score": "3",
"body": "Most likely due to lack of details about this program. What is its purpose? What specific improvements are you looking for? The more detail about your program, the better."
}
] |
[
{
"body": "<p>You misspelled \"movement\" as \"movment\".</p>\n\n<p>Typically (as per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>), indentations are specified by one hard tab or four spaces, so you're good in that respect.</p>\n\n<p>To be sure about formatting you can read up on PEP-8.</p>\n\n<p>I am also wondering about <code>_man</code>. This doesn't seem to be displaying a man (but I haven't run it) so why name it that way? Also, <code>epilepsy</code> doesn't seem like a suitable name. Perhaps <code>colored_box</code> would be more formal?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:58:45.630",
"Id": "468221",
"Score": "0",
"body": "Why the downvote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:16:18.000",
"Id": "468227",
"Score": "0",
"body": "I downvoted because I felt that it did not add anything as it seemed to me the only feedback you gave for me is that I misspelled a word."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:23:42.583",
"Id": "468228",
"Score": "1",
"body": "@K00lman Thanks for the feedback. I wouldn't have pointed it out if I didn't feel it was important. Typos might make you look bad to the professor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:27:51.747",
"Id": "468230",
"Score": "1",
"body": "Thanks for that, but this is just something I made in my free time to make sure I get what is being taught. It is not going to be used in my class at all. As such, it's not the most formal."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:47:43.790",
"Id": "238732",
"ParentId": "238728",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:29:29.293",
"Id": "238728",
"Score": "0",
"Tags": [
"python",
"beginner",
"python-3.x",
"gui"
],
"Title": "Python graphical user interface test"
}
|
238728
|
<h1>Background</h1>
<p>At contract bridge, each player gets a hand of 13 cards from a deck of 52 cards. To evaluate the potential of a hand, we need to calculate what we called the High Card Points (HCP) of it. To do so, we give to each card a value:</p>
<ul>
<li>Ace: 4 points</li>
<li>King: 3 points</li>
<li>Queen: 2 points</li>
<li>Jack: 1 point</li>
<li>Any other card: 0 points</li>
</ul>
<p>For instance, if I have a hand with one ace, two kings and one jack, the value of my hand is 11 HCP.</p>
<h1>Challenge</h1>
<p>What I want to know is what is the probability to have a hand of <em>n</em> HCP. To do so, I need to count the number of possible hands with <em>n</em> HCP and divide it by the number of the total possible hands at bridge which is <span class="math-container">\$\binom{52}{13}\$</span> or 635 013 559 600.</p>
<p>Therefore, the goal of my code below is to give the number of possible hands for each HCP value. Running it gives me this results:</p>
<pre><code>635013559600:
0: 2310789600
1: 5006710800
2: 8611542576
3: 15636342960
4: 24419055136
5: 32933031040
6: 41619399184
7: 50979441968
8: 56466608128
9: 59413313872
10: 59723754816
11: 56799933520
12: 50971682080
13: 43906944752
14: 36153374224
15: 28090962724
16: 21024781756
17: 14997082848
18: 10192504020
19: 6579838440
20: 4086538404
21: 2399507844
22: 1333800036
23: 710603628
24: 354993864
25: 167819892
26: 74095248
27: 31157940
28: 11790760
29: 4236588
30: 1396068
31: 388196
32: 109156
33: 22360
34: 4484
35: 624
36: 60
37: 4
</code></pre>
<p>It means, for instance, there is 4 different hands of 37 HCP.</p>
<h1>Issues with my code</h1>
<p>There are a lot of possible combinations of hands (as I said before, more than 635 billions). Therefore, my code took more than 29 hours to give me the results above.
My main concern about it is: how can I improve the performance of my program?</p>
<p>However, I'm open to every suggestions that not concern performance. For instance, I would like to know if I could use different library from the standard library. Also, I compile my code with C++17, maybe I could use some new features of it.</p>
<p>About the algorithm I used, my work is based on <a href="https://www.geeksforgeeks.org/print-subsets-given-size-set/" rel="nofollow noreferrer">this article</a>. I modify it to implement the multi-threading in my program but it produces duplicate code and I didn't find a way to refactor it.</p>
<h1>Code</h1>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <vector>
#include <array>
#include <atomic>
#include <thread>
#define DECK_SIZE 52
#define HAND_SIZE 13
// Array which will contain my results
// The key corresponds to the number of HCP
// The value corresponds to the number of hands with this HCP
// The maximum HCP of a hand is 37, so an array of 38 cells is enough
std::array<std::atomic<long long>, 38> results;
// A loop counter just to verify all the combination of hands are taken into account
std::atomic<long long> loop(0);
// Print the results
void print(std::array<std::atomic<long long>, 38>& vec)
{
std::string content;
content = std::to_string(loop) + ":\n";
for(int i = 0; i < vec.size(); i++)
content += std::to_string(i) + ": " + std::to_string(vec[i]) + "\n";
std::cout << content << std::endl;
}
// Compute and store into results the number of HCP of the hand given in parameter
void compute(std::vector<int>& hand)
{
loop++;
int value = 0;
for(auto it = hand.begin(); it != hand.end(); it++)
{
// A card is a value between 0 and 51
// To get the number of the card, we use its value % 13
// It gives a number between 0 and 12:
// - Ace: 12
// - King: 11
// - Queen: 10
// - Jack: 9
// - Every other cards: value-2
// Only cards with a value above 9 are useful
// We substract 8 to get the HCP of the cards
value += (*it) % 13 >= 9 ? (*it) % 13 - 8 : 0;
}
results[value]++;
}
// Deal a hand in the same thread
// The parameters are in reference and modified by the function
void deal(std::vector<int>& deck, std::vector<int>& hand, int idxDeck, int idxHand)
{
if(idxHand == HAND_SIZE)
{
// The hand vector contains the maximum number of cards
// We can now compute its value
compute(hand);
return;
}
// There are no more cards in the deck
if(idxDeck >= DECK_SIZE)
return;
// Deal the current card of the deck into the hand
hand[idxHand] = deck[idxDeck];
// Continue to deal the cards
deal(deck, hand, idxDeck+1, idxHand+1);
deal(deck, hand, idxDeck+1, idxHand);
}
// Deal a hand in a new thread if currentDepth <= threadMinDepth
// The parameters are in copy to let each thread working with its own copy
void deal_copy(std::vector<int> deck, std::vector<int> hand, int idxDeck, int idxHand, int currentDepth, int threadMinDepth)
{
if(idxHand == HAND_SIZE)
{
// The hand vector contains the maximum number of cards
// We can now compute its value
compute(hand);
return;
}
// There are no more cards in the deck
if(idxDeck >= DECK_SIZE)
return;
// Deal the current card of the deck into the hand
hand[idxHand] = deck[idxDeck];
// If we want to continue to create new thread for each new cards
if(currentDepth <= threadMinDepth)
{
// Creation of two new threads with their own copy of the deck and the hands
std::thread t1 = std::thread(deal_copy, deck, hand, idxDeck+1, idxHand+1, currentDepth+1, threadMinDepth);
std::thread t2 = std::thread(deal_copy, deck, hand, idxDeck+1, idxHand, currentDepth+1, threadMinDepth);
t1.join();
t2.join();
}
else
{
// No more thread, we continue with this version of the deal function
// The parameters are provided by reference to increase speed
deal(deck, hand, idxDeck+1, idxHand+1);
deal(deck, hand, idxDeck+1, idxHand);
}
}
int main() {
// This vector will contains all the possible cards
std::vector<int> deck;
// A card is represented by an integer with a value from 0 to 51
// To get the suit of a card, suit = value / 4:
// 0: clubs, 1: diamonds, 2: hearts, 3: spades (however, not relevant here)
// To get the number of a card, number = (value % 13) + 2
// Ace = 14, King = 13, Queen = 12, Jack = 11
for(int i = 0; i < DECK_SIZE; i++)
{
deck.push_back(i);
}
// The hand is empty at the beginning...
std::vector<int> hand(HAND_SIZE, 0);
// and it will be filled by recursive call to deal function
deal_copy(deck, hand, 0, 0, 0, 3);
print(results);
return 0;
}
</code></pre>
<p>To compile it: <code>g++ -std=c++17 -pthread count.cpp -o count</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:44:32.927",
"Id": "468212",
"Score": "0",
"body": "How many tasks do you perform per thread?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:53:31.373",
"Id": "468218",
"Score": "1",
"body": "@S.S.Anne I'm not sure to exactly understand what you mean by _task_. However, the computational work is not correctly divided between the threads. Indeed, I used an arbitrary value for `threadMinDepth`(3 will create 8 threads) and each thread calls the `deal` function. But the recursion can be more or less longer depending of the arguments which are different for all the different threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T00:03:29.283",
"Id": "468246",
"Score": "0",
"body": "I assume that you treat hands as if they are rearranged as any bridge player would (regardless of the order of the deal to the hand): (e.g. for four cards) `Dj,Sk,Hq,Sa` is reordered to `Sa,Sk,Hq,Dj` and they are counted as one unique hand [_not_ two]. Is that correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T09:18:33.387",
"Id": "468251",
"Score": "0",
"body": "@CraigEstey Yes, the algorithm I used to create all the combinations of hand always create ordered hands and doesn't create the same one twice."
}
] |
[
{
"body": "<h1>Redundant summing</h1>\n\n<blockquote>\n<pre><code> // The hand vector contains the maximum number of cards\n // We can now compute its value\n</code></pre>\n</blockquote>\n\n<p>That is not completely true, the value could have been built up incrementally each time a card was added to the hand, which would remove some duplicated work: hands that share a common prefix would not each recompute the sum of the values of that prefix, as they do now. So it's not just redistributing the work that is done in that loop, duplicate work goes away by reusing the results.</p>\n\n<h1>Contention</h1>\n\n<p>A performance trap here is that all threads are slamming the same <code>results</code> array, and even in the same places. Of course, the counters are atomic, so <em>the result</em> should come out fine. But there is heavy contention, and even <a href=\"https://fgiesen.wordpress.com/2014/08/18/atomics-and-contention/\" rel=\"noreferrer\">atomic operations don't make contention fast</a>. The contention can be solved by giving each thread its own array of local counts (sufficiently aligned and padded to also avoid <em>false</em> sharing), and summing them into the total at the end. As a bonus, only the additions at the end need to be atomic, not the individual increments - they can be the faster non-atomic increments now.</p>\n\n<p>On my PC (4770K Haswell), compiled with MSVC and using <code>DECK_SIZE 31</code> (to save time), and commenting out <code>loop++</code> (which has a significant cost), the effect of that was:</p>\n\n<pre><code>original: 3.0 seconds\nincremental: 2.6 seconds\nlocal count: 0.6 seconds\n</code></pre>\n\n<p>Since the deck was smaller, the access pattern to <code>results</code> was different, so esspecially the result for using local counts is not necessarily representative of how much speedup the \"full deck\" version would have.</p>\n\n<h1>Missing include</h1>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"noreferrer\"><code>std::to_string</code></a> is in <code><string></code> which was not included.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:54:21.803",
"Id": "238735",
"ParentId": "238731",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>how can I improve the performance of my program?</p>\n</blockquote>\n\n<p>A standard answer is use a better algorithm.</p>\n\n<p>Trying to improve performance by shaving cycles while enumerating a 635 013 559 600 strong set is futile.</p>\n\n<p>Consider instead enumerating subsets of valuable cards. There are merely <span class=\"math-container\">\\$2^{16} = 65536\\$</span> of them; a trillion time acceleration. Given a <code>popcount</code> function, you may do something along the lines of</p>\n\n<pre><code>for (int value_cards = 0; value_cards < (1 << 16); value_cards++) {\n if (popcount(value_cards) <= 13) {\n hand_value = compute_hand_value(value_cards);\n hands[hand_value] += choose((52 - 16), 13 - popcount(value_cards));\n }\n}\n</code></pre>\n\n<p><code>52 - 16</code> above is a number of a non-value cards in the deck. <code>13 - popcount(value_cards)</code> is a number of non-value cards which could be dealt to the hand with a given number of value cards.</p>\n\n<p>And of course, the <code>choose</code> shall be a precomputed array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T08:32:55.683",
"Id": "469972",
"Score": "0",
"body": "This is indeed the simplest solution. Also, I didn't create a `popcount` nor a `compute_hand_value` function and put all the instructions into the for loop because it avoids redundant computation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T21:13:38.403",
"Id": "238905",
"ParentId": "238731",
"Score": "4"
}
},
{
"body": "<p>Here's a better algorithm:</p>\n\n<p>It has been benchmarked and reduces the time from 29 hours to <strong>1.1 seconds</strong></p>\n\n<p>This is approximately 95,000 times faster.</p>\n\n<p><strong>Edit:</strong> Faster version, described below, reduces the execution time to <strong>0.68 seconds</strong>, which is 153,500 times faster.</p>\n\n<hr>\n\n<p>We only need to consider the number of each type of honor and then combinations of remaining spot cards.</p>\n\n<p>Using a state vector for the honors, we calculate all possible honor distributions [based on count]. The state vector is similar to a 4 digit base 5 number: <code>nA|nK|nQ|nJ</code> where each digit represents the number of the given card we are \"dealing\"</p>\n\n<p>We reject any state that has more than 13 honors.</p>\n\n<p>We reject any state that has a different HCP than we want (we loop on all desired HCP in the range 0-37).</p>\n\n<p><strong>Edit:</strong> Added an output vector, indexed by HCP, that accumulates all intermediate hand deal results, so that the honors state vector only needs to be cycled once, instead of a full pass for each given/desired HCP. (i.e. looping on the \"desired\" HCP is no longer required). The original behavior can be seen by adding a command line option of <code>-v</code></p>\n\n<p>We get the total number of combinations of honors:</p>\n\n<pre><code>honornCk = nCk(4,nJ) * nCk(4,nQ) * nCk(4,nK) * nCk(4,nA)\n</code></pre>\n\n<p>We calculate the number of slots left for spot cards:</p>\n\n<pre><code>nslot = 36 - (nJ + nQ + nK + nA)\n</code></pre>\n\n<p>We calculate the number of combinations of spots:</p>\n\n<pre><code>spotnCk = nCk(36,nslot)\n</code></pre>\n\n<p>We get the total number of combinations of cards for this hand:</p>\n\n<pre><code>curhand = spotnCk * honornCk\n</code></pre>\n\n<p>We accumulate the total number of hand combinations:</p>\n\n<pre><code>tothand += curhand\n</code></pre>\n\n<p>This is the final result</p>\n\n<hr>\n\n<p>Here is the [working] code</p>\n\n<p>It is written in C. Many combinations of caching/memoization and other [failed] attempts before coming up with this final version were tried. <em>Side note:</em> The primary criterion was on the algorithm vs. use of STL or style, so go easy on the niceties.</p>\n\n<p>It used <code>gmp</code> for large integers, so it must be linked with <code>-lgmp</code></p>\n\n<p>The algorithm is primarily in the <code>handinc</code> and <code>handhcp</code> functions.</p>\n\n<pre><code>// bridgehcp/bridgehcp.c -- calculate HCP of bridge hand\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gmp.h>\n\n#define NHONOR 4 // number of different honor types\n#define NSUIT 4 // number of suits\n#define DECKSIZE 52\n#define MAXHONOR (NHONOR * NSUIT)\n#define MAXSPOT (DECKSIZE - MAXHONOR)\n#define CARDS_PER_HAND 13\n#define HCPMAX 38\n\n#define SPT 0\n\ntypedef unsigned long long u64;\ntypedef unsigned long ui_t;\ntypedef unsigned char byte;\ntypedef int inum_t;\ntypedef inum_t *inum_p;\n\ntypedef mpz_t qnum_t;\ntypedef mpz_t qnum_p;\n\nint opt_d = 0;\nint opt_b = 0;\nint opt_t = 0;\nint opt_v = 0;\nint opt_commatst = 0;\n\n#define OPTCMP(_str) \\\n if (optcmp(cp,#_str,&opt_##_str)) \\\n continue\n\n// honor state/slot control\ntypedef struct {\n int slot_ctype; // card type 0=J, 1=Q, 2=Q, 3=A\n int slot_count; // number of cards of given type (0-4)\n inum_t slot_nCk; // multiplier for slot_count\n} slot_t;\ntypedef slot_t *slot_p;\n\nslot_t honors[NHONOR]; // honor counts in given dealt hand\n\ntypedef struct {\n qnum_t hand_tot; // total for hand\n} handvec_t;\ntypedef handvec_t *handvec_p;\n\nhandvec_t handvec[HCPMAX]; // vector of final values\n\n#define HANDVEC(_hcp) \\\n handvec_p hand = &handvec[_hcp]\n\nconst char *hcpstr[HCPMAX] = {\n [0] = \"2,310,789,600\",\n [1] = \"5,006,710,800\",\n [2] = \"8,611,542,576\",\n [3] = \"15,636,342,960\",\n [4] = \"24,419,055,136\",\n [5] = \"32,933,031,040\",\n [6] = \"41,619,399,184\",\n [7] = \"50,979,441,968\",\n [8] = \"56,466,608,128\",\n [9] = \"59,413,313,872\",\n [10] = \"59,723,754,816\",\n [11] = \"56,799,933,520\",\n [12] = \"50,971,682,080\",\n [13] = \"43,906,944,752\",\n [14] = \"36,153,374,224\",\n [15] = \"28,090,962,724\",\n [16] = \"21,024,781,756\",\n [17] = \"14,997,082,848\",\n [18] = \"10,192,504,020\",\n [19] = \"6,579,838,440\",\n [20] = \"4,086,538,404\",\n [21] = \"2,399,507,844\",\n [22] = \"1,333,800,036\",\n [23] = \"710,603,628\",\n [24] = \"354,993,864\",\n [25] = \"167,819,892\",\n [26] = \"74,095,248\",\n [27] = \"31,157,940\",\n [28] = \"11,790,760\",\n [29] = \"4,236,588\",\n [30] = \"1,396,068\",\n [31] = \"388,196\",\n [32] = \"109,156\",\n [33] = \"22,360\",\n [34] = \"4,484\",\n [35] = \"624\",\n [36] = \"60\",\n [37] = \"4\",\n};\n\n#define FOR_ALL_HONORS(_hon) \\\n _hon = &honors[0]; _hon < &honors[NHONOR]; ++_hon\n\n#define MPZALL(_cmd) \\\n _cmd(qtmp,\"temp variable\") \\\n _cmd(kfac,\"k!\") \\\n _cmd(nkfac,\"(n - k)!\") \\\n _cmd(abstot,\"absolute total number of hands (e.g. ~650G)\") \\\n _cmd(spotnCk,\"current number of combinations of spot cards\") \\\n _cmd(curhand,\"spotnCk * honornCk\") \\\n _cmd(totspot,\"total number of spot cards\") \\\n _cmd(tothand,\"totspot * honornCk\") \\\n _cmd(expres,\"expected result\") \\\n _cmd(exptot,\"expected total\")\n\n#define _MPXDEF(_sym,_reason) \\\n qnum_t _sym;\nMPZALL(_MPXDEF)\n\n#define _MPXINIT(_sym,_reason) \\\n mpz_init(_sym);\n#define _MPXCLEAR(_sym,_reason) \\\n mpz_clear(_sym);\n\n#define outf(_fmt...) \\\n do { \\\n if (! opt_t) \\\n printf(_fmt); \\\n } while (0)\n\n#ifdef DEBUG\n#define dbgprt(_lvl,_fmt...) \\\n do { \\\n if (opt_d >= _lvl) \\\n outf(_fmt); \\\n } while (0)\n#else\n#define dbgprt(_lvl,_fmt...) \\\n do { \\\n } while (0)\n#endif\n\n#define TLSMAX 10\n\nchar *\nstrtls(void)\n{\n static char bufpool[TLSMAX][1024];\n static int bufidx = 0;\n char *buf;\n\n buf = bufpool[bufidx];\n bufidx += 1;\n bufidx %= TLSMAX;\n\n *buf = 0;\n\n return buf;\n}\n\nint\noptcmp(char *cp,const char *str,int *opt)\n{\n int len;\n int matchflg;\n\n len = strlen(str);\n\n do {\n matchflg = (strncmp(cp,str,len) == 0);\n if (! matchflg)\n break;\n\n cp += len;\n\n if (*cp == 0) {\n *opt = ! *opt;\n break;\n }\n\n if (*cp == '=')\n ++cp;\n\n *opt = atoi(cp);\n } while (0);\n\n return matchflg;\n}\n\nvoid\ncommaprt(char *dst,const char *src,int len)\n{\n const char *dot;\n char *bp;\n int sep;\n int off;\n\n if (len < 0)\n len = strlen(src);\n\n dot = strchr(src,'.');\n if (dot == NULL)\n dot = &src[len];\n\n len = dot - src;\n\n bp = dst;\n off = 0;\n sep = 0;\n\n for (; src < dot; ++src, ++off) {\n int chr = *src;\n\n if (((len - off) % 3) == 0) {\n if (sep)\n *bp++ = ',';\n }\n sep = 1;\n\n *bp++ = chr;\n }\n\n for (int chr = *src++; chr != 0; chr = *src++)\n *bp++ = chr;\n\n *bp = 0;\n}\n\nstatic inline void\nqnum_init(qnum_p num)\n{\n\n mpz_init(num);\n}\n\nstatic inline void\nqnum_set_ui(qnum_p num,ui_t val)\n{\n\n mpz_set_ui(num,val);\n}\n\nstatic inline void\nqnum_mul_ui(qnum_p dst,qnum_p src,ui_t val)\n{\n\n mpz_mul_ui(dst,src,val);\n}\n\nstatic inline void\nqnum_set(qnum_p num,qnum_p val)\n{\n\n mpz_set(num,val);\n}\n\nstatic inline void\nqnum_add(qnum_p dst,qnum_p src,qnum_p val)\n{\n\n mpz_add(dst,src,val);\n}\n\nstatic inline void\nqnum_mul(qnum_p dst,qnum_p src,qnum_p val)\n{\n\n mpz_mul(dst,src,val);\n}\n\nstatic inline void\nqnum_div(qnum_p dst,qnum_p src,qnum_p val)\n{\n\n mpz_div(dst,src,val);\n}\n\nvoid\n_qnumprt(char *buf,qnum_p num)\n{\n char tmp[1000];\n int len;\n\n len = gmp_sprintf(tmp,\"%Zd\",num);\n\n commaprt(buf,tmp,len);\n}\n\nchar *\nqnumprt(qnum_p num)\n{\n char *buf;\n\n buf = strtls();\n _qnumprt(buf,num);\n\n return buf;\n}\n\nvoid\nqnumset(qnum_p num,const char *str)\n{\n char *dst;\n char tmp[1000];\n\n dst = tmp;\n\n for (int chr = *str++; chr != 0; chr = *str++) {\n switch (chr) {\n case ',':\n break;\n default:\n *dst++ = chr;\n break;\n }\n }\n\n *dst = 0;\n\n mpz_set_str(num,tmp,10);\n}\n\nvoid\ncommatst(const char *src)\n{\n char buf[1000];\n\n if (opt_commatst) {\n commaprt(buf,src,-1);\n outf(\"\\n\");\n outf(\"commatst: SRC '%s'\\n\",src);\n outf(\"commatst: DST '%s'\\n\",buf);\n }\n}\n\n// qnumfac -- get n!\nvoid\nqnumfac(qnum_p num,int n)\n{\n\n qnum_set_ui(num,1);\n for (int idx = 2; idx <= n; ++idx)\n qnum_mul_ui(num,num,idx);\n}\n\n// qnumnCk -- get nCk (combinations of n things taken k at a time)\nvoid\nqnumnCk(qnum_p rtn,int n,int k)\n{\n\n // rtn = n! / (k! (n - k)!)\n\n // get n!\n qnumfac(rtn,n);\n\n // get k!\n qnumfac(kfac,k);\n\n // get (n - k)!\n qnumfac(nkfac,n - k);\n\n // get k! * (n - k)!\n qnum_mul(kfac,kfac,nkfac);\n\n // get n! / (k! * (n - k)!)\n qnum_div(rtn,rtn,kfac);\n}\n\n// qnumnPk -- get nPk (permutations of n things taken k at a time)\nvoid\nqnumnPk(qnum_p rtn,int n,int k)\n{\n\n // rtn = n! / (n - k)!\n\n // get n!\n qnumfac(rtn,n);\n\n // get (n - k)!\n qnumfac(nkfac,n - k);\n\n // get n! / (n - k)!\n qnum_div(rtn,rtn,nkfac);\n}\n\ninum_t\ninumfac(int n)\n{\n inum_t rtn;\n\n rtn = 1;\n for (int idx = 2; idx <= n; ++idx)\n rtn *= idx;\n\n return rtn;\n}\n\ninum_t\ninumnCk(int n,int k)\n{\n inum_t kfac;\n inum_t nkfac;\n inum_t rtn;\n\n // rtn = n! / (k! (n - k)!)\n\n // get n!\n rtn = inumfac(n);\n\n // get k!\n kfac = inumfac(k);\n\n // get (n - k)!\n nkfac = inumfac(n - k);\n\n // get k! * (n - k)!\n kfac *= nkfac;\n\n // get n! / (k! * (n - k)!)\n rtn /= kfac;\n\n return rtn;\n}\n\ninum_t\ninumnPk(int n,int k)\n{\n inum_t nkfac;\n inum_t rtn;\n\n // rtn = n! / (n - k)!\n\n // get n!\n rtn = inumfac(n);\n\n // get (n - k)!\n nkfac = inumfac(n - k);\n\n // get n! / (n - k)!\n rtn /= nkfac;\n\n return rtn;\n}\n\nint\nhonortag(slot_p hon)\n{\n static char *tag = \"JQKA\";\n\n return tag[hon->slot_ctype];\n}\n\nchar *\nhonorshow(void)\n{\n slot_p hon;\n static char buf[100];\n char *bp = buf;\n char *sep = \"\";\n\n bp += sprintf(bp,\"(\");\n\n for (FOR_ALL_HONORS(hon)) {\n bp += sprintf(bp,\"%s%c%d/%d\",\n sep,honortag(hon),\n hon->slot_count,hon->slot_nCk);\n sep = \" \";\n }\n\n bp += sprintf(bp,\")\");\n\n return buf;\n}\n\n// handhcp -- get HCP and number of hands for a given deal of honor cards\nint\nhandhcp(int hcpneed)\n{\n slot_p hon;\n int hcptot = 0;\n int nslot = CARDS_PER_HAND;\n int hontot = 0;\n int slotnCk;\n int honornCk = 1;\n\n dbgprt(2,\"handhcp: ENTER hcpneed=%d\\n\",hcpneed);\n\n do {\n // get number of honors in this hand\n for (FOR_ALL_HONORS(hon)) {\n // get number of slots that this honor needs\n int honcnt = hon->slot_count;\n\n // accumulate number of honors for this dealt hand\n hontot += honcnt;\n }\n\n // impossible hand -- there are more honors dealt than the number of\n // cards in a hand (e.g. 14 honors dealt)\n if (hontot > CARDS_PER_HAND) {\n hcptot = -1;\n break;\n }\n\n // get HCP for this hand\n for (FOR_ALL_HONORS(hon)) {\n int honcnt = hon->slot_count;\n\n // get number of HCP for this honor\n int hcpcur = honcnt * (hon->slot_ctype + 1);\n\n // accumulate total number of HCP for all honors in this hand\n hcptot += hcpcur;\n }\n\n // insufficient/incorrect HCP -- doesn't match the _desired_ HCP\n if (hcpneed >= 0) {\n if (hcptot != hcpneed)\n break;\n }\n\n // get number of combinations of honor cards\n for (FOR_ALL_HONORS(hon)) {\n int honcnt = hon->slot_count;\n\n // number of combinations of honors of the given type\n slotnCk = inumnCk(NSUIT,honcnt);\n\n // accumulate number of combinations of all honors\n honornCk *= slotnCk;\n }\n\n // reduce number of available slots for spot cards in this hand by\n // number of honors in this hand\n nslot -= hontot;\n\n // get number of combinations of remaining spot cards\n qnumnCk(spotnCk,MAXSPOT,nslot);\n\n // accumlate total for this\n // FIXME -- really not needed anymore\n qnum_add(totspot,totspot,spotnCk);\n\n // get number of hands that have the given distribution of honors and\n // spots [for the desired HCP]\n qnum_mul_ui(curhand,spotnCk,honornCk);\n\n // accumulate total for all hands for the given HCP\n qnum_add(tothand,tothand,curhand);\n\n // save in vector\n HANDVEC(hcptot);\n qnum_add(hand->hand_tot,hand->hand_tot,curhand);\n\n // brief output\n if (opt_b)\n break;\n\n outf(\"handhcp: STATE honors=%s\",honorshow());\n\n outf(\" hcptot=%d\",hcptot);\n outf(\" hontot=%d\",hontot);\n outf(\" honornCk=%d\",honornCk);\n\n outf(\" nspot=%d\",MAXSPOT);\n outf(\" nslot=%d\",nslot);\n outf(\" spotnCk=%s\",qnumprt(spotnCk));\n\n#if SPT\n outf(\" totspot=%s\",qnumprt(totspot));\n#endif\n outf(\" curhand=%s\",qnumprt(curhand));\n outf(\" tothand=%s\",qnumprt(tothand));\n\n outf(\"\\n\");\n } while (0);\n\n dbgprt(2,\"handhcp: EXIT hcptot=%d\\n\",hcptot);\n\n return hcptot;\n}\n\n// handinit -- initialize honors state vector\nvoid\nhandinit(void)\n{\n slot_p hon;\n int idx;\n\n // set initial state of all honors (e.g. all honor counts are zero\n // J=0, Q=0, K=0, A=0)\n idx = 0;\n for (FOR_ALL_HONORS(hon), ++idx) {\n hon->slot_ctype = idx;\n hon->slot_count = 0;\n }\n\n qnum_set_ui(totspot,0);\n qnum_set_ui(tothand,0);\n\n qnum_set_ui(exptot,0);\n}\n\n// _handinc -- increment single digit in honors state vector\nint\n_handinc(slot_p hon)\n{\n int cout;\n\n // NOTE: we only care about the _number_ of honors of a given type\n int val = hon->slot_count;\n\n dbgprt(3,\"_handinc: ctype=%d val=%d\",hon->slot_ctype,val);\n\n val += 1;\n\n cout = (val > NSUIT);\n if (cout)\n val = 0;\n\n hon->slot_count = val;\n\n dbgprt(3,\" val=%d cout=%d\\n\",val,cout);\n\n return cout;\n}\n\n// handinc -- increment honors state vector\nint\nhandinc(void)\n{\n slot_p hon;\n int cout = 0;\n\n for (FOR_ALL_HONORS(hon)) {\n cout = _handinc(hon);\n if (! cout)\n break;\n }\n\n return cout;\n}\n\n// prettyprt -- define result output\nvoid\nprettyprt(const char *tag,qnum_p num)\n{\n\n outf(\"%s: %s\\n\",tag,qnumprt(num));\n}\n\n// dotest -- perform algorithm for given HCP\nvoid\ndotest(int hcpneed,const char *str)\n// hcpneed -- desired HCP\n// str -- expected result\n{\n\n handinit();\n\n int handgud = 0;\n int handtot = 0;\n\n outf(\"\\n\");\n outf(\"HCP: %d\\n\",hcpneed);\n\n while (1) {\n int hcpcur = handhcp(hcpneed);\n\n if (hcpcur == hcpneed)\n handgud += 1;\n\n handtot += 1;\n\n // increment to next state for number of honors of each type\n int cout = handinc();\n\n // stop after the _last_ state (i.e. we just did: J=4, Q=4, K=4, A=4\n // and we incremented back to the start (J=0, Q=0, K=0, A=0)\n if (cout)\n break;\n }\n\n outf(\"HANDS: %d of %d\\n\",handgud,handtot);\n\n // pretty print the numbers\n prettyprt(\"EXP\",expres);\n#if SPT\n prettyprt(\"SPT\",totspot);\n#endif\n prettyprt(\"ACT\",tothand);\n}\n\nvoid\ndoall(void)\n{\n\n handinit();\n\n while (1) {\n handhcp(-1);\n\n // increment to next state for number of honors of each type\n int cout = handinc();\n\n // stop after the _last_ state (i.e. we just did: J=4, Q=4, K=4, A=4\n // and we incremented back to the start (J=0, Q=0, K=0, A=0)\n if (cout)\n break;\n }\n}\n\nvoid\ndoany(int hcpneed,const char *str)\n{\n\n do {\n qnumset(expres,str);\n\n // accumulate expected results -- check OP's result, when done,\n // this should be 52C13\n qnum_add(exptot,exptot,expres);\n\n if (opt_v) {\n dotest(hcpneed,str);\n break;\n }\n\n outf(\"\\n\");\n outf(\"HCP: %d\\n\",hcpneed);\n\n // pretty print the numbers\n prettyprt(\"EXP\",expres);\n#if SPT\n prettyprt(\"SPT\",totspot);\n#endif\n HANDVEC(hcpneed);\n prettyprt(\"ACT\",hand->hand_tot);\n } while (0);\n}\n\nint\nmain(int argc,char **argv)\n{\n char *cp;\n\n --argc;\n ++argv;\n\n for (; argc > 0; --argc, ++argv) {\n cp = *argv;\n if (*cp != '-')\n break;\n\n ++cp;\n\n OPTCMP(commatst);\n OPTCMP(d);\n OPTCMP(b);\n OPTCMP(t);\n OPTCMP(v);\n\n printf(\"bridgehcp: unknown option -- '%s'\\n\",cp);\n exit(1);\n }\n\n // test the commaprt routine\n const char *digits = \"1234567890\";\n for (const char *lhs = digits; *lhs != 0; ++lhs)\n commatst(lhs);\n for (const char *lhs = digits; *lhs != 0; ++lhs) {\n for (const char *rhs = digits; *rhs != 0; ++rhs) {\n char buf[100];\n sprintf(buf,\"%s.%s\",lhs,rhs);\n commatst(buf);\n }\n }\n\n MPZALL(_MPXINIT)\n\n // show all factorials\n for (int n = 1; n <= 52; ++n) {\n qnumfac(qtmp,n);\n dbgprt(1,\"qnumfac: n=%d %s\\n\",n,qnumprt(qtmp));\n }\n\n // total number of possible hands\n qnumnCk(abstot,DECKSIZE,CARDS_PER_HAND);\n outf(\"qnumnCk: %s\\n\",qnumprt(abstot));\n\n // show nCk 4C0-4C4\n for (int n = 1; n <= 4; ++n) {\n for (int k = 0; k <= 4; ++k) {\n qnumnCk(qtmp,n,k);\n dbgprt(1,\"%dC%d: %s\\n\",n,k,qnumprt(qtmp));\n }\n }\n\n // when we're done this will match the number of possible hands\n qnum_set_ui(exptot,0);\n\n // initialize hand total vector\n for (int hcpneed = 0; hcpneed < HCPMAX; ++hcpneed) {\n HANDVEC(hcpneed);\n memset(hand,0,sizeof(handvec_t));\n qnum_init(hand->hand_tot);\n qnum_set_ui(hand->hand_tot,0);\n }\n\n // precalc all\n if (! opt_v)\n doall();\n\n for (int hcpneed = 0; hcpneed < HCPMAX; ++hcpneed)\n doany(hcpneed,hcpstr[hcpneed]);\n\n // NOTE: these should match\n outf(\"\\n\");\n outf(\"abstot: %s\\n\",qnumprt(abstot));\n outf(\"exptot: %s\\n\",qnumprt(exptot));\n\n MPZALL(_MPXCLEAR)\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T20:21:28.600",
"Id": "238957",
"ParentId": "238731",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238905",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T19:38:44.650",
"Id": "238731",
"Score": "6",
"Tags": [
"c++",
"performance",
"multithreading",
"playing-cards"
],
"Title": "Compute the value of a hand at contract bridge for every possible hand"
}
|
238731
|
<p><a href="https://i.stack.imgur.com/l1VgJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l1VgJ.png" alt="enter image description here"></a></p>
<p>I need my h1 to show below my for my checkbox. It is inside of the div. Should I maybe put it outside of the . </p>
<p>The missing is below the Organization Fields header. It is suppose to display below the checkbox input but it is not showing at all. What may cause it to disappear</p>
<p><strong>HTML</strong> </p>
<pre><code><label name="Organization">Show Organization Data</label>
<input type="checkbox" :v-model="showOrganizationFields" :true-value="true" :false-value="false">
<div v-if="showOrganizationFields">
<h1 class="mb-7 mt-5 ml-6 font-bold text-2xl"> Organization Fields</h1>
<div v-for="field in requiredOrganizationFields" class="p-8 -mr-6 -mb-6 flex flex-wrap" style="width:150px">
<label :for="field" type="select" name="field">{{field}}</label>
<select :id="field" :name="field" v-model="mapping[field]" required>
<option value="">Please Select</option>
<option v-for="columnName in columnNames" :name="columnName" :value="columnName" value="">{{columnName}}</option>
</select>
</div>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:14:13.597",
"Id": "468225",
"Score": "2",
"body": "Welcome to Code Review. Asking for advice on code yet to be written or implemented is off-topic for this site. See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference. Once you have written working code, you're welcome to ask a new question here and we can then help you improve it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:23:52.627",
"Id": "468229",
"Score": "0",
"body": "It works if I remove the label. Doesn't work If I add a label for the checkbox. I need the label for the input. Can't have an opening and closing input tag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:39:23.383",
"Id": "468232",
"Score": "1",
"body": "Well, regardless, this is not the right place to ask about fixing code. You might check Stack Overflow instead, they specialize in that."
}
] |
[
{
"body": "<p>You have to add the tag above the & tags</p>\n\n<pre><code><h1 class=\"mb-7 mt-5 ml-6 font-bold text-2xl\">Organization Fields</h1>\n <label class=\"ml-6 mt-6 mb-6 text-medium\" name=\"Organization\">Show Organization Data</label>\n <input type=\"checkbox\" :v-model=\"showOrganizationFields\" :true-value=\"true\" :false-value=\"false\">\n <div v-if=\"showOrganizationFields\">\n <div v-for=\"field in requiredOrganizationFields\" class=\"p-8 -mr-6 -mb-6 flex flex-wrap\" style=\"width:150px\">\n <label :for=\"field\" type=\"select\" name=\"field\">{{field}}</label>\n <select :id=\"field\" :name=\"field\" v-model=\"mapping[field]\" required>\n <option value=\"\">Please Select</option>\n <option v-for=\"columnName in columnNames\" :name=\"columnName\" :value=\"columnName\" value=\"\">{{columnName}}</option>\n </select>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T11:00:37.633",
"Id": "468262",
"Score": "0",
"body": "Please do not answer off-topic questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:44:31.260",
"Id": "238734",
"ParentId": "238733",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238734",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T20:08:07.630",
"Id": "238733",
"Score": "-2",
"Tags": [
"vue.js"
],
"Title": "Missing header in the UI - Vue.js"
}
|
238733
|
<p>I'm learning recursion and I think that I can finally wrap my head around it.</p>
<p>I had to write a program that given an integer would print out its number of digits and I wanted to know if it is correctly implemented and if there's anything I can do to make it better.</p>
<p>Here's my code:</p>
<pre><code>#include<stdio.h>
int countDigits(int n);
int main(void){
int n,result;
printf("What is the number?\n");
scanf("%d", &n);
result=countDigits(n);
printf("%d\n", result);
return 0;
}
int countDigits(int n){
if(n>=0&&n<10){
return 1;
}
else{
return 1+countDigits(n/10);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:37:14.390",
"Id": "468238",
"Score": "1",
"body": "What about negative numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:37:43.643",
"Id": "468239",
"Score": "0",
"body": "Didn't make it to work for them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:43:03.330",
"Id": "468240",
"Score": "1",
"body": "Then you should check for a negative number before you call `countDigits()` with a negative number. Also, `unsigned int` may be a more appropriate argument and return type if `countDigits()` is not intended to count the number of digits of a negative number. It's not difficult to make it work with negative numbers, though..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T07:52:57.520",
"Id": "468248",
"Score": "1",
"body": "I can understand that you decided to implement it recursively as you said to be learning recursion. But if you should take a lesson from this, it should be that recursion is often not the best solution. The way you implemented it can produce up to 10 stack frames (for 32bit integers) where you only realy need one frame, two local variables and a while loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T02:14:11.980",
"Id": "468426",
"Score": "0",
"body": "... and at other times, recursion is the best solution. Use the right tool for the job. Typical iterations are not a good recursion solution but do allow learners to \"wrap their heads around it\""
}
] |
[
{
"body": "<p>As mentioned in comments, you should be careful about which integer type you use. <code>int</code> is negative and if your function takes <code>int</code> as parameter, it will therefore be assumed that it can handle negative numbers. So <code>unsigned int</code> might have been a better choice.</p>\n\n<p>More importantly, you should be aware that recursion is dangerous, ineffective and often hard to read. The compiler may not always be able to optimize away the recursive call - so-called <em>tail-call optimization</em> - and if it doesn't the function turns very slow and gives a peak in stack memory use.</p>\n\n<p>In this specific case, the compiler should be able to recognize that the <code>else</code> is redundant and the recursive call ends up at the return statement where it should be in order to enable optimization.</p>\n\n<p>Still, gcc gives me less efficient code for your recursive function than for a loop alternative, even though it could optimize away the recursive call. Disassembling your code and comparing it with this one:</p>\n\n<pre><code>int countDigitsSane (int n){\n int digits=1;\n for(int i=n; i>9; i/=10)\n {\n digits++;\n }\n return digits;\n}\n</code></pre>\n\n<p>Then it gives me slightly worse code for the recursive alternative, <a href=\"https://godbolt.org/z/Ddzv9u\" rel=\"nofollow noreferrer\">https://godbolt.org/z/Ddzv9u</a>. The assembler generated is pretty unreadable with lots of compiler tricks, but writing the code as a plain readable loop is what makes such tricks possible. Usually, code that is easily read by humans is code that is easily optimized by the compiler.</p>\n\n<p>So what was gained from recursion? The code turned slower and harder to read. The uncomfortable truth here is that recursion is mostly used for posing, when the programmer writes needlessly complicated code on purpose to show off.</p>\n\n<p>In the real world where professionals write code with the purpose of making it safe, rugged and maintainable, recursion should be avoided in general. There are very few actual uses for it outside artificial academic exercises - it should pretty much only be used in various specialized search/sort algorithms and never in ordinary application logic. High level language programmers may tell you otherwise, but that's because they don't have a clue about how actual machine code is generated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T09:42:17.187",
"Id": "468254",
"Score": "0",
"body": "And to recursion-hugging people who will start to whine in comments and down-vote: _talk to the disassembly_."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T09:41:38.547",
"Id": "238755",
"ParentId": "238738",
"Score": "2"
}
},
{
"body": "<p>I unfortunately cannot comment (not enough reputation), but in terms of performance and generated assembly code both variants are exactly same:</p>\n\n<pre><code>int countDigitsSane (int n){\n int digits=1;\n for(int i=n; i>9; i/=10)\n {\n digits++;\n }\n return digits;\n}\n\nint countDigits(int n){\n if(n<10){\n return 1;\n }\n else{\n return 1+countDigits(n/10);\n }\n}\n</code></pre>\n\n<p>Pay attention, I have removed the redundant check in the recursive snippet.With that correction, the code generated by the compiler is almost 100% same, save for different choice of registers.</p>\n\n<p>Having said that, it is indeed, better to avoid recursion in imperative languages (such as C++), however in functional languages (Haskell, OCaml etc.) , recursion is a normal thing, and the compiler guarantees it can optimise tail-recursive calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T08:45:13.887",
"Id": "468331",
"Score": "0",
"body": "On gcc specifically, yeah nearly identical machine code. On icc -O3... fine machine code for my version, complete trash code for the recursive version, since it fails to tail-call optimize. Sitting in some ivory tower and saying that the compiler should take care of everything does us no good - in the real world that is not often the case. The programmer who made the call to use recursion is to blame for the mess, not the compiler. We shouldn't write needlessly inefficient code when there are faster and more readable alternatives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T10:09:50.033",
"Id": "468340",
"Score": "1",
"body": "Not only GCC but Clang produces exactly same code in both cases. Not only that, I have explicitly mentioned that is not appropriate technique to use in C and C++, as they are imperative languages. One more thing to mention - it is not tail recursive code at all, and clang and g++ do us a favor, when reorganize it to be such. Properly written tail recursive I am sure code will be optimal on Intel C++ too. Speaking of readability - for someone coming from say Haskell background, recursive version could be, in fact more readable, than the one with a loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T22:11:18.617",
"Id": "468403",
"Score": "0",
"body": "Both incorrectly report 1 when `n <= -10`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T14:31:58.100",
"Id": "238773",
"ParentId": "238738",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>it is correctly implemented (?)</p>\n</blockquote>\n\n<p>No. Incorrect result when <code>n <= 10</code>.</p>\n\n<p>Goal: Counting the number of digits with a recursion algorithm in c</p>\n\n<p>Simply change the condition to handle all <code>int</code>.</p>\n\n<pre><code>int countDigits(int n){\n // if(n>=0&&n<10){\n if(n > -10 && n < 10) {\n return 1;\n }\n else {\n return 1 + countDigits(n/10);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T22:15:57.293",
"Id": "238853",
"ParentId": "238738",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238773",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:05:04.913",
"Id": "238738",
"Score": "2",
"Tags": [
"c",
"recursion"
],
"Title": "Counting the number of digits with a recursion algorithm in c"
}
|
238738
|
<p>I am trying to find all the SE answers which contain "<strong>on context</strong>" in a single sentence, in the meanwhile the "<strong>on</strong>" is not a part of common collocations in any form, such as "depending on context", "depend on context", "Based on context", "rely on context", "Counting on Context", "Count on Context" ...</p>
<p>Here is the code</p>
<pre><code>SELECT Id, CreationDate, Score, Body
INTO #tb_postcount
FROM Posts
WHERE Body LIKE '% on context%'
AND PostTypeId=2
SELECT Id AS [Post Link] from #tb_postcount
WHERE Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%depend%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%base%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%rely%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%count%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%lean%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%take%on context%'
</code></pre>
<p>It works well, at least to me:) Could someone please take a look at it?</p>
<p>Is there a more efficient way to do the job?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T13:35:16.640",
"Id": "468268",
"Score": "0",
"body": "Could you expand upon what you want to be improved and looked at?"
}
] |
[
{
"body": "<p>The following are a few suggestions on how I'd write the SQL statement.</p>\n\n<p><strong>Source Control</strong> </p>\n\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>I would download the following tool for SSMS and Visual Studio, <a href=\"https://www.apexsql.com/sql-tools-refactor.aspx\" rel=\"nofollow noreferrer\">SQL formatter from ApexSQL</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n\n<p><strong>Copy & Paste</strong></p>\n\n<p>If you find yourself copying and pasting the same string or number over and over in your query, then you should define it as a variable or create a table. <a href=\"https://en.wikipedia.org/wiki/David_Parnas\" rel=\"nofollow noreferrer\"><em>Copy and paste is a design error ~ David Parnas</em></a></p>\n\n<p><strong>Commas</strong></p>\n\n<p>I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier. </p>\n\n<p><strong>Where Clause</strong></p>\n\n<p>If you put <code>1=1</code> at the top of a <code>WHERE</code> condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact. <a href=\"https://stackoverflow.com/q/242822/9059424\">Reference</a></p>\n\n<p><strong>Common Table Expressions (CTE)</strong></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">CTE's</a> in your SQL, help with documentation. The expression name can then let other developers know why you used that expression e.g. <code>post_body_filter</code>.</p>\n\n<p><strong>Schema Names</strong></p>\n\n<p>Always reference the schema when selecting an object e.g. <code>[dbo].[Posts]</code>.</p>\n\n<p><strong>Keywords</strong></p>\n\n<p>Avoid using keywords as object names. <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">Microsoft Reference</a></p>\n\n<ul>\n<li>Also check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow noreferrer\"><em>Clean Code</em></a>. It will change the way you think about naming conventions.</li>\n</ul>\n\n<hr>\n\n<p><strong>Revised SQL</strong></p>\n\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start.</p>\n\n<pre><code>WITH\nPosts\nAS\n(\n SELECT tbl.* FROM (VALUES\n ( 1, '01-Jan-2020', 85, 'depend on context', 2)\n , ( 2, '02-Jan-2020', 86, 'base on Context', 2)\n , ( 3, '03-Jan-2020', 87, 'rely on context', 2)\n , ( 4, '04-Jan-2020', 88, 'Count on Context', 2)\n , ( 5, '05-Jan-2020', 89, 'lean on context', 2)\n , ( 6, '06-Jan-2020', 90, 'Take on Context', 2)\n , ( 7, '07-Jan-2020', 91, '... on context', 2)\n , ( 8, '08-Jan-2020', 92, ' on context ...', 2)\n , ( 9, '09-Jan-2020', 93, '... on context ...', 2)\n , ( 10, '10-Jan-2020', 94, '... on ... context ...', 2)\n , ( 11, '11-Jan-2020', 95, '...', 2)\n , ( 12, '12-Jan-2020', 96, '... on context ...', 1)\n ) tbl ([Id], [CreationDate], [Score], [Body], [PostTypeId]) \n)\n,\npost_body_filter --here it would be good to name the table expression so others will know why you're filtering them out.\nAS\n(\n SELECT tbl.* FROM (VALUES\n ( '%depend%')\n , ( '%base%')\n , ( '%rely%')\n , ( '%count%')\n , ( '%lean%')\n , ( '%take%')\n ) tbl ([Body]) \n)\nSELECT \n [po].[Id]\n , [po].[CreationDate]\n , [po].[Score]\n , [po].[Body]\nFROM\n [Posts] AS [po]\n LEFT JOIN [post_body_filter] AS [pf] ON [po].[Body] LIKE [pf].[Body] COLLATE SQL_Latin1_General_CP1_CI_AS\nWHERE\n 1 = 1\n AND [pf].[Body] IS NULL\n AND [po].[Body] LIKE '% on context%'\n AND [po].[PostTypeId] = 2\n ;\n</code></pre>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/hGuXM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hGuXM.png\" alt=\"screenshot\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T05:48:34.607",
"Id": "242118",
"ParentId": "238740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T22:40:45.387",
"Id": "238740",
"Score": "1",
"Tags": [
"sql"
],
"Title": "filter SE posts with specific keywords"
}
|
238740
|
<pre><code>def tictactoe():
Board = [1,2,3,4,5,6,7,8,9]
w = True
PlayerX = []
PlayerO = []
while len(PlayerO) < 9:
while True:
z = int(input("Player X: Select a place (1-9)\n"))
if z in Board:
Board[z-1] = []
PlayerX.append(z)
break
else:
print("Place not available! Choose another X")
while True:
y = int(input("Player O: Select a place (1-9)\n"))
if y in Board:
Board[y-1] = []
PlayerO.append(y)
break
else:
print("Place not available! Choose another O")
if len(PlayerX) > 2:
if set([1,2,3]).issubset(set(PlayerX)) or set([4,5,6]).issubset(set(PlayerX)) or set([7,8,9]).issubset(set(PlayerX)) or set([1,4,7]).issubset(set(PlayerX)) or set([2,5,8]).issubset(set(PlayerX)) or set([3,6,9]).issubset(set(PlayerX)) or set([1,5,9]).issubset(set(PlayerX)) or set([3,5,7]).issubset(set(PlayerX)):
print("Player X won!")
w = False
break
elif set([1,2,3]).issubset(set(PlayerO)) or set([4,5,6]).issubset(set(PlayerO)) or set([7,8,9]).issubset(set(PlayerO)) or set([1,4,7]).issubset(set(PlayerO)) or set([2,5,8]).issubset(set(PlayerO)) or set([3,6,9]).issubset(set(PlayerO)) or set([1,5,9]).issubset(set(PlayerO)) or set([3,5,7]).issubset(set(PlayerO)):
print("Player O won!")
w = False
break
if w is True:
print("Tie")
if input("Play Again (y/n)?\n") == "y":
tictactoe()
tictactoe()
</code></pre>
<p>I'm trying to make this code as efficient as possible. I'm new to Python and kinda limited with the knowledge I have. How can I simplify the code and especially the line shown below?</p>
<p><a href="https://i.stack.imgur.com/SBl3K.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SBl3K.jpg" alt="Numbered spots (1-9)"></a></p>
<pre><code>if set([1,2,3]).issubset(set(PlayerX)) or set([4,5,6]).issubset(set(PlayerX)) or set([7,8,9]).issubset(set(PlayerX)) or set([1,4,7]).issubset(set(PlayerX)) or set([2,5,8]).issubset(set(PlayerX)) or set([3,6,9]).issubset(set(PlayerX)) or set([1,5,9]).issubset(set(PlayerX)) or set([3,5,7]).issubset(set(PlayerX)):
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T12:11:29.557",
"Id": "468267",
"Score": "2",
"body": "Define \"efficient\". Do you mean in regards to runtime performance, development time, maintenance complexity, ...?"
}
] |
[
{
"body": "<p>I guess from efficiency point of view this is fine, even that last line. Efficiency points:</p>\n\n<ul>\n<li>You create player variable as <code>list</code> and then keep converting to set over and over again, why not have it as set from beginning?</li>\n</ul>\n\n<p>From readability and maintenance point of view, you are having lots of duplicities.</p>\n\n<ul>\n<li>Player moves are exactly same except for message and variable, you can extract that to function.</li>\n<li>Same goes for checking if a player won.</li>\n<li>I don't like variable <code>w</code>. Why not make variable <code>winner</code> instead and save name of winner into it? Related to extracting if player won to separate function.</li>\n</ul>\n\n<p>And for your last line - you can put all possible winning combinations into array or tupple and then check that in cycle (you get the idea):</p>\n\n<pre><code>winning_combinations = [\n[1, 2, 3],\n[4, 5, 6],\n...\n]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T01:14:34.307",
"Id": "238746",
"ParentId": "238744",
"Score": "5"
}
},
{
"body": "<p>In addition to what @K.H. already mentioned:</p>\n\n<h2>Comments to the code</h2>\n\n<ul>\n<li>Things will get simplified if you represent the <code>Board</code> as a set of numbers</li>\n</ul>\n\n<pre><code>Board = set([1,2,3,4,5,6,7,8,9])\n</code></pre>\n\n<p>Then <code>Board.remove(z)</code> would look better than doing manipulations with indices and assigning an empty list (<code>Board[z-1] = []</code>)</p>\n\n<ul>\n<li>The condition below is not really used:</li>\n</ul>\n\n<pre><code>while len(PlayerO) < 9:\n</code></pre>\n\n<p>Can the length of <code>Player0</code> ever be more or equal to 9?</p>\n\n<ul>\n<li>You can simplify <code>if w is True:</code> -> <code>if w:</code></li>\n</ul>\n\n<h2>General comment about variable naming</h2>\n\n<p>I would like also to pay your attention to variable naming. It might seem insignificant for a small program like yours, but it is important. After some time you are going to forget which information variables like <code>w</code> or <code>Board</code> actually hold, and those who read your program won't be able to understand it right away either. So it will take more time to understand your code.</p>\n\n<p>For example, you could rename your variables as follows:</p>\n\n<p><code>Board</code> -> <code>free_places_on_board</code></p>\n\n<p><code>Player0</code> -> <code>player_0_selected_places</code></p>\n\n<p><code>w</code> -> <code>tie</code></p>\n\n<p><code>z</code> -> <code>selected_place</code></p>\n\n<p>Although these names are longer (shouldn't be a problem since all modern IDEs provide code completion), but they give much more information, and the code reads much easier, just like the English language:</p>\n\n<pre><code>selected_place = int(input(\"Player O: Select a place (1-9)\\n\"))\nif selected_place in free_places_on_board:\n player_0_selected_places.append(selected_place)\n</code></pre>\n\n<p>A big advantage of this is that if there's a bug somewhere in your code, it will become obvious:</p>\n\n<pre><code>if not w: # not obvious\n print(\"Tie\")\n</code></pre>\n\n<pre><code>if not tie: # now the statement does not make sense -> the bug becomes obvious \n print(\"Tie\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T13:16:33.553",
"Id": "238940",
"ParentId": "238744",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238746",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T00:51:41.130",
"Id": "238744",
"Score": "2",
"Tags": [
"python",
"beginner",
"tic-tac-toe"
],
"Title": "TicTacToe with Python"
}
|
238744
|
<p>So basically my input stacks have change event that handle its state by changing it. I don't think this is the right way to handle it.</p>
<p>What I'm trying to say, if it react render bunch of heavy components does it always re render it per state setting? If that'ss true does this result in a heavy load on the JavaScript?</p>
<p>Example of my code:</p>
<pre><code>testfunctionPack = {
onChange: (e)=>{
let property = e.target.getAttribute("name");
let state = this.state;
state.user.info[property] = e.target.value;
this.setState(state);
},
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T10:48:23.717",
"Id": "468258",
"Score": "1",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>Yes, this is common practice. If you have heavy components you can, for example, separate the form and the heavy components. The form takes care of its state. This way you don't need to re-render everything on every state change. You could alternatively use <code>React.memo</code> for functional components, <code>PureComponent</code> or <code>shouldComponentUpdate</code> for class. You shouldn't use the latter too often though since you can easily introduce bugs.</p>\n\n<p>Btw you're accidentally mutating state. This is not good since you should only use setState to change the state. You need to copy the old state into a new variable:</p>\n\n<pre><code>let property = e.target.getAttribute(\"name\");\nlet user = { ...this.state.user };\nuser.info = {\n ...user.info,\n [property]: e.target.value,\n};\nthis.setState({ user });\n</code></pre>\n\n<p>Here you create a new user object and inside of that a new info object. Nested objects inside state are always annoying for this reason. You can also use a library like lodash for deep cloning. Or you use an immutibilaty library like immer, which is probably the best way</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T09:49:10.073",
"Id": "238756",
"ParentId": "238745",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T01:07:50.007",
"Id": "238745",
"Score": "-1",
"Tags": [
"react.js"
],
"Title": "Should I update react state on every input change?"
}
|
238745
|
<p>This is an exercise on the website <a href="https://exercism.io" rel="nofollow noreferrer">Exercism</a>. I am self taught trying to learn C# and C++. This is the information from the readme.</p>
<blockquote>
<p>Convert a number, represented as a sequence of digits in one base, to
any other base.</p>
<p>Implement general base conversion. Given a number in base <strong>a</strong>,
represented as a sequence of digits, convert it to base <strong>b</strong>.</p>
<h2>Note</h2>
<ul>
<li>Try to implement the conversion yourself. Do not use something else to perform the conversion for you.</li>
</ul>
<h2>About <a href="https://en.wikipedia.org/wiki/Positional_notation" rel="nofollow noreferrer">Positional Notation</a></h2>
<p>In positional notation, a number in base <strong>b</strong> can be understood as a
linear combination of powers of <strong>b</strong>.</p>
<p>The number 42, <em>in base 10</em>, means:</p>
<p>(4 <em>10^1) + (2</em> 10^0)</p>
<p>The number 101010, <em>in base 2</em>, means:</p>
<p>(1 *2^5) + (0 *2^4) + (1 <em>2^3) + (0</em> 2^2) + (1* 2^1) + (0* 2^0)</p>
<p>The number 1120, <em>in base 3</em>, means:</p>
<p>(1 *3^3) + (1 <em>3^2) + (2</em> 3^1) + (0* 3^0)</p>
<p>I think you got the idea!</p>
<p>Yes. Those three numbers above are exactly the same. Congratulations!</p>
</blockquote>
<p>Following script is my solution to the exercise.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
public static class AllYourBase
{
private static void RebaseIsException(int inputBase, int[] digits, int outputBase)
{
if (digits is null)
throw new ArgumentNullException(nameof(digits));
if (inputBase <= 1)
throw new ArgumentException(nameof(inputBase));
if (digits.Any(e => e < 0))
throw new ArgumentException(nameof(digits));
if (digits.Any(e => e >= inputBase))
throw new ArgumentException(nameof(inputBase), nameof(digits));
if (outputBase <= 1)
throw new ArgumentException(nameof(outputBase));
if (inputBase <= 0 && outputBase <= 0)
throw new ArgumentException(nameof(inputBase), nameof(outputBase));
}
public static bool RebaseIsDigitsEmptyOrZero(int[] digits) => digits.Sum() == 0;
public static int[] RebaseSolution(int inputBase, int[] digits, int outputBase)
{
int number = 0;
List<int> list = new List<int>();
foreach (int i in digits)
number = number * inputBase + i;
do
{
list.Add(number % outputBase);
} while ((number /= outputBase) != 0);
list.Reverse();
return list.ToArray();
}
public static int[] Rebase(int inputBase, int[] digits, int outputBase)
{
RebaseIsException(inputBase, digits, outputBase);
return RebaseIsDigitsEmptyOrZero(digits) ? new int[] { 0 } : RebaseSolution(inputBase, digits, outputBase);
}
}
</code></pre>
<p>Next, is the test case for this exercise.</p>
<pre><code>// This file was auto-generated based on version 2.3.0 of the canonical data.
using System;
using Xunit;
public class AllYourBaseTest
{
[Fact]
public void Single_bit_one_to_decimal()
{
var inputBase = 2;
var digits = new[] { 1 };
var outputBase = 10;
var expected = new[] { 1 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Binary_to_single_decimal()
{
var inputBase = 2;
var digits = new[] { 1, 0, 1 };
var outputBase = 10;
var expected = new[] { 5 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Single_decimal_to_binary()
{
var inputBase = 10;
var digits = new[] { 5 };
var outputBase = 2;
var expected = new[] { 1, 0, 1 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Binary_to_multiple_decimal()
{
var inputBase = 2;
var digits = new[] { 1, 0, 1, 0, 1, 0 };
var outputBase = 10;
var expected = new[] { 4, 2 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Decimal_to_binary()
{
var inputBase = 10;
var digits = new[] { 4, 2 };
var outputBase = 2;
var expected = new[] { 1, 0, 1, 0, 1, 0 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Trinary_to_hexadecimal()
{
var inputBase = 3;
var digits = new[] { 1, 1, 2, 0 };
var outputBase = 16;
var expected = new[] { 2, 10 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Hexadecimal_to_trinary()
{
var inputBase = 16;
var digits = new[] { 2, 10 };
var outputBase = 3;
var expected = new[] { 1, 1, 2, 0 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Number_15_bit_integer()
{
var inputBase = 97;
var digits = new[] { 3, 46, 60 };
var outputBase = 73;
var expected = new[] { 6, 10, 45 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Empty_list()
{
var inputBase = 2;
var digits = Array.Empty<int>();
var outputBase = 10;
var expected = new[] { 0 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Single_zero()
{
var inputBase = 10;
var digits = new[] { 0 };
var outputBase = 2;
var expected = new[] { 0 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Multiple_zeros()
{
var inputBase = 10;
var digits = new[] { 0, 0, 0 };
var outputBase = 2;
var expected = new[] { 0 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Leading_zeros()
{
var inputBase = 7;
var digits = new[] { 0, 6, 0 };
var outputBase = 10;
var expected = new[] { 4, 2 };
Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Input_base_is_one()
{
var inputBase = 1;
var digits = new[] { 0 };
var outputBase = 10;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Input_base_is_zero()
{
var inputBase = 0;
var digits = Array.Empty<int>();
var outputBase = 10;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Input_base_is_negative()
{
var inputBase = -2;
var digits = new[] { 1 };
var outputBase = 10;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Negative_digit()
{
var inputBase = 2;
var digits = new[] { 1, -1, 1, 0, 1, 0 };
var outputBase = 10;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Invalid_positive_digit()
{
var inputBase = 2;
var digits = new[] { 1, 2, 1, 0, 1, 0 };
var outputBase = 10;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Output_base_is_one()
{
var inputBase = 2;
var digits = new[] { 1, 0, 1, 0, 1, 0 };
var outputBase = 1;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Output_base_is_zero()
{
var inputBase = 10;
var digits = new[] { 7 };
var outputBase = 0;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Output_base_is_negative()
{
var inputBase = 2;
var digits = new[] { 1 };
var outputBase = -7;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
[Fact]
public void Both_bases_are_negative()
{
var inputBase = -2;
var digits = new[] { 1 };
var outputBase = -7;
Assert.Throws<ArgumentException>(() => AllYourBase.Rebase(inputBase, digits, outputBase));
}
}
</code></pre>
<p>I was able to without effort come up with <strong>RebaseIsException</strong> to pass the test that wants you to throw new ArgumentException. Few other test where passed using <strong>RebaseIsDigitsEmptyOrZero</strong>. I had to borrow from a few sites to come up with what you see in <strong>RebaseSolution</strong>. In particular the foreach loop and the do/while loop to get the solution. I kind of stumbled into passing this after a few days of spending a few minutes on it each night, with most the time just in this one function.</p>
<p>Anyhow, I would be grateful and appreciate whatever feedback to help me continue to learn. Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T10:35:05.893",
"Id": "468256",
"Score": "0",
"body": "`if (inputBase <= 0 && outputBase <= 0)` Just FYI this can never happen. If the input base is negative it'll already have thrown an `ArgumentException`, same for the output base."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T17:01:58.927",
"Id": "468299",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T21:17:56.883",
"Id": "468315",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ read and understood. Thanks for pointing that out."
}
] |
[
{
"body": "<p>I like it. Coding is easy to read. In particular, here are the positives:</p>\n\n<ul>\n<li>Nice style and indentation</li>\n<li>Nice variable naming</li>\n<li>I like <code>public</code> and <code>private</code> declarations to each method.</li>\n</ul>\n\n<p>The biggest area of contention is a matter of personal style, and that would be whether to always use braces after an <code>if</code> or <code>foreach</code>. The general consensus here at CR is that you should use them, but there is a significant number of developers who do not.</p>\n\n<p>Getting pickier, <code>RebaseIsDigitsEmptyOrZero</code> and <code>RebaseSolution</code> should maybe be marked <code>private</code>. When you call them in <code>Rebase</code>, you have already validated all arguments. If it is <code>public</code>, I could call <code>RebaseIsDigitsEmptyOrZero</code> directly and either pass in a null <code>digits</code> or <code>{ -1, 1 }</code>. The former would throw an exception but the latter would return <code>true</code>.</p>\n\n<p>For a future challenge, if you dare, I was thinking of a class or struct that contains <code>Digits</code> and <code>Base</code> as properties that are co-joined in that class/struct. Then you could have a <code>ConvertBase</code> method accepting the new base as the argument, and it would return a new instance of that class/struct with the appropriate <code>Digits</code> and <code>Base</code>. Dunno. Still thinking about that one, but it might be worth exploring.</p>\n\n<p>Nice job. I look forward to your future CR questions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:36:53.420",
"Id": "468288",
"Score": "0",
"body": "Thank you for your feedback. I have since changed all functions except **Rebase** to private. I float back and forth with brackets. I like not using them, but understand that if the argument is maintainability, some might argue that is a reason to throw them in in case of future refactor. As for a **ConvertBase** method, I have seen others that have done something like that. That's above my ability at math. It's some of the reason why I do math problems. Trying to get better at it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T12:51:17.377",
"Id": "238764",
"ParentId": "238747",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p><code>RebaseIsException()</code></p>\n</blockquote>\n\n<p>This is a little strange name for a method. It doesn't tell anything about what happens inside it. A better name would be <code>VerifyInput()</code> or <code>ValidateInput()</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (inputBase <= 0 && outputBase <= 0)\n throw new ArgumentException(nameof(inputBase), nameof(outputBase));\n</code></pre>\n</blockquote>\n\n<p>This will never happen, because <code><= 0</code> is caught by the previous <code><= 1</code></p>\n\n<hr>\n\n<blockquote>\n <p><code>public static bool RebaseIsDigitsEmptyOrZero(int[] digits) => digits.Sum() == 0;</code></p>\n</blockquote>\n\n<p>Again a little strange name.</p>\n\n<p>Besides that I think your general algorithm should be able to handle the zero-value of any base.</p>\n\n<p>Further: You test against each digit not being negative. Therefore the only way this can return <code>true</code> is if <code>digits</code> only contains zeros or is empty and that is handled by <code>RebaseSolution()</code>.</p>\n\n<p><code>RebaseIsDigitsEmptyOrZero(int[] digits)</code> is all in all an optimization for zero-values, but in fact a bottleneck for all other values, because it iterate through the list one extra time.</p>\n\n<hr>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code> if (digits.Any(e => e < 0))\n throw new ArgumentException(nameof(digits));\n\n if (digits.Any(e => e >= inputBase))\n throw new ArgumentException(nameof(inputBase), nameof(digits));\n</code></pre>\n</blockquote>\n\n<p>can be combinded to:</p>\n\n<pre><code> if (digits.Any(e => e < 0 || e >= inputBase))\n throw new ArgumentOutOfRangeException(nameof(digits));\n</code></pre>\n\n<p>saving one iteration of the data set (in worst case).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:41:07.897",
"Id": "468290",
"Score": "0",
"body": "` if (inputBase <= 0 && outputBase <= 0)\n throw new ArgumentException(nameof(inputBase), nameof(outputBase));`\n\nI have removed that. Thank you for spotting that. I was working my way through all the test one at a time on the exceptions. \n\n`public static bool RebaseIsDigitsEmptyOrZero(int[] digits) => digits.Sum() == 0;`\nSame as above, therefore omitted. Thank you again for spotting this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:41:29.700",
"Id": "468291",
"Score": "0",
"body": "` if (digits.Any(e => e < 0 || e >= inputBase))\n throw new ArgumentOutOfRangeException(nameof(digits));\n`\nThis refactor fails two test. **AllYourBaseTest.Negative_digit** and **AllYourBaseTest.Invalid_positive_digit**\nOtherwise great job on your recommendations!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T17:03:17.183",
"Id": "468301",
"Score": "0",
"body": "@Milliorn: but they maybe fail because, you haven't changed the type argument in `Assert.Throws<ArgumentException>` to `ArgumentOutOfRangeException`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T21:21:14.853",
"Id": "468316",
"Score": "0",
"body": "That might very well be the reason, but the site that issued the exercise expected those test cases and its results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T06:09:26.073",
"Id": "468325",
"Score": "0",
"body": "@Milliorn: Ah, then change the exception in the code back to `ArgumentException`, and it should work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T16:08:30.960",
"Id": "468372",
"Score": "0",
"body": "I overlooked that. That suggestion worked. Good catch!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T13:40:29.837",
"Id": "238767",
"ParentId": "238747",
"Score": "4"
}
},
{
"body": "<p>Try to avoid doing sneaky value changes in what is otherwise a logical evaluation. Not that it doesn't work, but condensing these steps into one another detracts from readability.</p>\n\n<pre><code>// Yours\n\ndo\n{\n list.Add(number % outputBase);\n} while ((number /= outputBase) != 0);\n\n// My suggestion\n\ndo\n{\n list.Add(number % outputBase);\n number /= outputBase;\n} while (number != 0);\n</code></pre>\n\n<hr>\n\n<p>Avoid defaulting to publically accessible methods. In <code>AllYourBase</code>, only <code>Rebase</code> should be public, the others can be made private.</p>\n\n<p>This helps consumers of your static class know which method to call as they can't use the methods they shouldn't call directly.</p>\n\n<hr>\n\n<p>The validation logic can do with some descriptive error messages. You test very specific circumstances but then don't actually report back <em>which</em> part of the validation failed.</p>\n\n<p>Try to provide a meaningful message in your exception, such as <code>base cannot be zero or negative</code> or <code>digit values exceed input base</code>.</p>\n\n<hr>\n\n<p>There also seems to be a disconnect in your validation itself:</p>\n\n<pre><code>if (inputBase <= 1)\n throw new ArgumentException(nameof(inputBase));\n\nif (outputBase <= 1)\n throw new ArgumentException(nameof(outputBase));\n\nif (inputBase <= 0 && outputBase <= 0)\n throw new ArgumentException(nameof(inputBase), nameof(outputBase));\n</code></pre>\n\n<p>It's unclear as to why you first check for <code><= 1</code> and then <code><= 0</code>. It makes sense to not allow any base below 2, so the first two tests make sense.</p>\n\n<p>There is no additional case that the third test will catch. If the third validation fails, then either the first or second validation has already failed and thus the third validation will never be run.</p>\n\n<p>I think you need to revisit your test logic as the third test doesn't add anything of value. Additionally, I suggest commenting your validation logic to explain the intention, <em>especially</em> when you are using magic values like <code>1</code> or <code>0</code> and where the intention is not trivially readable.</p>\n\n<hr>\n\n<p>The method names in <code>AllYourBase</code> can be improved.</p>\n\n<ul>\n<li>None of the private methods (see previous point) should have <code>Rebase</code> prepended to them. Their name should stand on its own.</li>\n<li><code>RebaseIsException</code> implies a boolean return value, but it's <code>void</code></li>\n<li><code>RebaseSolution</code> is a confusing name. Methods take an imperative form (= command), and \"to rebase a solution\" isn't understandable. You presumably mean \"the actual solution for the <code>Rebase</code> method\", but that's not a good name.</li>\n</ul>\n\n<p>My suggested renames are:</p>\n\n<ul>\n<li><code>RebaseIsException</code> => <code>ValidateInput</code></li>\n<li><code>RebaseIsDigitsEmptyOrZero</code> => <code>IsEmptyOrZero</code></li>\n<li><code>RebaseSolution</code> => <code>CalculateRebasedDigits</code></li>\n</ul>\n\n<p>These methods are being using in <code>Rebase</code>, and their names were chosen to specifically highlight their responsibility as part of the <code>Rebase</code> superlogic.</p>\n\n<pre><code>// My suggestion\n\npublic static int[] Rebase(int inputBase, int[] digits, int outputBase)\n{\n ValidateInput(inputBase, digits, outputBase);\n\n return IsEmptyOrZero(digits) \n ? new int[] { 0 } \n : CalculateRebasedDigits(inputBase, digits, outputBase);\n}\n</code></pre>\n\n<hr>\n\n<p>Your unit tests are overall clear and readable. </p>\n\n<p>What I'd change, though, is the naming. Currently, your test name describes the values you're arranging, but it's generally more meaningful to describe the expected behavior.</p>\n\n<p>If I see a test called <code>Both_bases_are_negative</code> pass, that suggests to me that both bases being negative is a happy path. It obviously shouldn't be, so the test name should reflect that e.g. <code>ThrowsException_WhenBothBasesAreNegative</code>.</p>\n\n<p>Similarly, <code>Leading_zeros</code> can be renamed to <code>IgnoresLeadingZeroes</code>. These are just two random examples of how you should introduce a description of the desired behavior.<br>\nAs you may notice, I prefer to cut down on the amount of underscores in a test name, but that's personal preference.</p>\n\n<hr>\n\n<p>You have a lot of unit tests that test the same thing with different values. xUnit has a better approach for this: <strong>theories</strong>. Very simply put, a theory is a fact with parameters; so you can run the same test for different values.</p>\n\n<p>As an example, you can reduce these three facts:</p>\n\n<pre><code>[Fact]\npublic void Binary_to_multiple_decimal()\n{\n var inputBase = 2;\n var digits = new[] { 1, 0, 1, 0, 1, 0 };\n var outputBase = 10;\n var expected = new[] { 4, 2 };\n Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));\n}\n\n[Fact]\npublic void Decimal_to_binary()\n{\n var inputBase = 10;\n var digits = new[] { 4, 2 };\n var outputBase = 2;\n var expected = new[] { 1, 0, 1, 0, 1, 0 };\n Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));\n}\n\n[Fact]\npublic void Trinary_to_hexadecimal()\n{\n var inputBase = 3;\n var digits = new[] { 1, 1, 2, 0 };\n var outputBase = 16;\n var expected = new[] { 2, 10 };\n Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase));\n}\n</code></pre>\n\n<p>to a single theory:</p>\n\n<pre><code>[Theory]\n[InlineData(2, new[] { 1, 0, 1, 0, 1, 0 }, 10, new[] { 4, 2 })\n[InlineData(3, new[] { 1, 1, 2, 0 }, 16, new[] { 2, 10 })\n[InlineData(10, new[] { 4, 2 }, 2, new[] { 1, 0, 1, 0, 1, 0 })\npublic void Rebases_toOutputBase(int inputBase, int[] inputDigits, int outputBase, int[] expectedResult)\n{\n var actual = AllYourBase.Rebase(inputBase, inputDigits, outputBase);\n\n Assert.Equal(expectedResult, actual);\n}\n</code></pre>\n\n<p>There are ways to further improve this by using <code>MemberData</code> or <code>ClassData</code> attributes, which allows you to further abstract your test cases, but the general outset is the same: it prevents copy/pasting of structurally identical tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:54:30.860",
"Id": "468296",
"Score": "0",
"body": "Your refactor of the do/while loop was successful. I changed it in my code thinking the while condition makes more sense on readability. I change all my functions to private except **Rebase**. Common mistake I make when I initially write C#. Thank you for pointing out some tips on unit testing. It's really new to me and I haven't grasped what is the best way to handle exception messages. Same with naming conventions with my methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T16:55:30.653",
"Id": "468297",
"Score": "0",
"body": "As for your comments and suggestions with the unit testing, that was provided by the site and is immutable beyond reformatting the code. Lot of great advice, thank you for your time and input."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T14:11:20.773",
"Id": "238770",
"ParentId": "238747",
"Score": "4"
}
},
{
"body": "<p>Thank you everyone for your help. This is what I refactored based on all the feedback.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class AllYourBase\n{\n private static void ValidateInput(int inputBase, int[] digits, int outputBase)\n {\n if (inputBase <= 1)\n throw new ArgumentException(nameof(inputBase));\n\n if (digits.Any(e => e < 0 || e >= inputBase || digits is null))\n throw new ArgumentException(nameof(digits));\n\n if (outputBase <= 1)\n throw new ArgumentException(nameof(outputBase));\n }\n\n private static int[] CalculateRebasedDigits(int inputBase, int[] digits, int outputBase)\n {\n int number = 0;\n List<int> list = new List<int>();\n\n foreach (int i in digits)\n number = number * inputBase + i;\n\n do\n {\n list.Add(number % outputBase);\n number /= outputBase;\n } while (number != 0);\n\n list.Reverse();\n return list.ToArray();\n }\n\n public static int[] Rebase(int inputBase, int[] digits, int outputBase)\n {\n ValidateInput(inputBase, digits, outputBase);\n\n return CalculateRebasedDigits(inputBase, digits, outputBase);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T00:17:14.293",
"Id": "238913",
"ParentId": "238747",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T01:18:15.630",
"Id": "238747",
"Score": "6",
"Tags": [
"c#",
"performance",
".net",
"unit-testing",
"mathematics"
],
"Title": "All your Base - Exercism.io"
}
|
238747
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.