body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I need some advice for this task.</p> <p>We've got this structure:</p> <pre><code>const scenes = { 'Node1': { 'scene1': [ { nodeKey: 'cccc', category: 'user', }, { nodeKey: 'eeee', category: 'interface', }, ] }, } </code></pre> <p>I need to make this:</p> <pre><code>let result = { 'Node1': { 'scene1': { 'cccc': { nodeKey: 'cccc', category: 'user', } } } } </code></pre> <p>I use the reduce function to make it work. But I think it can be done more efficiently and maybe more readable?</p> <pre><code>function makeNewStructure(scenes) { return Object.keys(scenes).reduce((prevNode, currentNode) =&gt; { return { ...prevNode, [currentNode]: Object.keys(scenes[currentNode]).reduce((prevScene, currentScene) =&gt; { return { ...prevScene, [currentScene]: scenes[currentNode][currentScene].reduce((previous, current) =&gt; { return { ...previous, [current.nodeKey]: current } },{}) } }, {}) } }, {}) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-28T23:18:06.123", "Id": "390583", "Score": "1", "body": "Welcome to Code Review. Please provide a better specification of what the transformation is, because the example is unclear. What happens to `'eeee'`, and why? See [ask]." } ]
[ { "body": "<p>I am not sure you can get it much \"smarter\" but I believe this is clearer:</p>\n\n<pre><code>function forEach(target, fn) {\n var keys = Object.keys(target);\n var key;\n var i = -1;\n while (++i &lt; keys.length) {\n key = keys[i];\n fn(target[key], key);\n }\n}\nfu...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-28T23:15:13.503", "Id": "202702", "Score": "-2", "Tags": [ "javascript" ], "Title": "Function that changes structure" }
202702
<p>I have a Raspberry Pi 3B with a USB microphone. I have used a combination of Bash and Python scripts to detect noise levels above a certain threshold that trigger a notification on my phone. The actual sound is not streamed. </p> <p>The scripts are called using a command line alias for the following:</p> <pre class="lang-sh prettyprint-override"><code>bash /home/pi/babymonitor.sh | /home/pi/monitor.py </code></pre> <h2>Bash script - <em>babymonitor.sh</em></h2> <p>This uses <code>arecord</code> to repeatedly record 2-second snippets via a temporary file, <code>sox</code> and <code>grep</code> to get the RMS (root mean square) amplitude (see this <a href="//stackoverflow.com/q/43415353">example</a> for sox stat output) and then <code>tail</code> to get only the numerical data at the end of the line. This is then piped to the Python script.</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash trap break INT while true; do arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 /dev/shm/tmp_rec.wav ; sox -t .wav /dev/shm/tmp_rec.wav -n stat 2&gt;&amp;1 | grep "RMS amplitude" | tail -c 9 done </code></pre> <h2>Python processing script - <em>monitor.py</em></h2> <p>This receives the volume data and compares it to an arbitrarily defined threshold that I chose based on testing. If a noise is detected in one of the 2-second snippets, a push notification is sent and it suppresses further notifications for 10 seconds (5 cycles of 2-second snippets).</p> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python import sys import push THRESHOLD = 0.01 count = 0 suppress = False while True: try: line = sys.stdin.readline().strip() # e.g. "0.006543" number = float(line) if number &gt; THRESHOLD and not suppress: p = push.PushoverSender("user_key", "api_token") p.send_notification("There's a noise in the nursery!") count = 0 suppress = True elif suppress: print("Suppressing output") else: print("All quiet") # Count 5 cycles after a trigger if suppress: count += 1 if count &gt;= 5: count = 0 suppress = False except ValueError: # Cannot coerce to float or error in stdin print("Value error: " + line) break except KeyboardInterrupt: # Cancelled by user print("Baby monitor script ending") break sys.exit() </code></pre> <h2>Script for push notification service - <em>push.py</em></h2> <p>This sends an <code>http</code> request to the <a href="https://pushover.net" rel="nofollow noreferrer">Pushover</a> service, which results in a push notification on my phone.</p> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python import httplib import urllib class PushoverSender: def __init__(self, user_key, api_key): self.user_key = user_key self.api_key = api_key def send_notification(self, text): conn = httplib.HTTPSConnection("api.pushover.net:443") post_data = {'user': self.user_key, 'token': self.api_key, 'message': text} conn.request("POST", "/1/messages.json", urllib.urlencode(post_data), {"Content-type": "application/x-www-form-urlencoded"}) print(conn.getresponse().read()) </code></pre> <hr> <p>I would be grateful for any feedback on how I can improve my code or the conceptual aspects of this project. I am not very familiar with Bash scripting so feedback is particularly welcome on this.</p> <ol> <li><p>Is it acceptable to have the Bash script and Python script called together with a pipe between them and both running <code>while True</code> loops? It certainly seems to work.</p></li> <li><p>Is there a better way to exit? Current pressing <kbd>ctrl</kbd>+<kbd>c</kbd> will terminate both the Bash script (due to <code>trap break INT</code>) and the Python script (due to <code>except KeyboardInterrupt</code>).</p></li> </ol>
[]
[ { "body": "<p>One thing you might do to the shell script is to swap the commands in your <code>while</code>:</p>\n\n\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\nwhile arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 \\\n /dev/shm/tmp_rec.wav \\\n &amp;&amp; sox -t .wa...
{ "AcceptedAnswerId": "202722", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-28T23:31:31.643", "Id": "202704", "Score": "7", "Tags": [ "python", "bash", "audio", "raspberry-pi" ], "Title": "A baby monitor using a Raspberry Pi to send push notifications when triggered by noise" }
202704
<p>I am developing a very basic CLI flag utility library in C. The following code is a part of the main translation unit containing all the relevant functions, and is located in the global scope.</p> <pre><code>struct pair { char name[100]; char defaultValue[100]; }; static struct pair *defaults = NULL; void setDefault(const char *flagName, const char *defaultValue) { if (defaults == NULL) { defaults = malloc(10 * sizeof(struct pair)); } static short pos = 0; if(pos % 10 == 0) { defaults = realloc(defaults, (pos + 10) * sizeof(struct pair)); } strncpy((defaults + pos)-&gt;name, flagName, 100); strncpy((defaults + pos)-&gt;defaultValue, defaultValue, 100); pos++; } static void clearDefaults(void) { free(defaults); } </code></pre> <p>To clue you in, the idea is that the user calls <code>setDefault</code> with 2 strings, the first of which represents a flag name, and the second which represents the default value of that (should it not have been passed to the program). The pair is stored in memory and is later used by other library functions.</p> <hr> <p>My question is centered around the storage of <code>flagName:defaultValue</code> pairs, which are represented using the <code>pair</code> struct. Right now I'm using a global static variable <code>defaults</code> which stores a pointer to a dynamically allocated array of said <code>struct</code>s. It's static, therefore I had to initially set it to NULL, and "initialize" it only after the first call of <code>setDefaults</code>. I feel that this creates unnecessary clutter as other library functions have to test <code>defaults</code> for <code>NULL</code> before trying to search it for a specific pair.</p> <p>That is my first concern, is there a better way to initialize a global static variable?</p> <hr> <p>The second is my implementation of dynamic reallocation in <code>setDefault</code>. It initially allocates space for 10 pairs, and once the limit is reached it allocated space for 10 more and so on. I've tested the implementation with Valgrind and a bunch of calls to <code>setDefault</code> and there were no memory leaks or other errors.</p> <hr> <p>Is this a good way to do it? Can anything be improved? I'm very much a beginner at C so any feedback is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T00:30:24.737", "Id": "390586", "Score": "1", "body": "Are you deliberately reinventing [POSIX `getopt`](https://en.wikipedia.org/wiki/Getopt) and [its clones](https://stackoverflow.com/q/10404448/1157100)?" }, { "ContentLice...
[ { "body": "<p>Yes, there are things to improve:</p>\n\n<pre><code>if (defaults == NULL) {\n defaults = malloc(10 * sizeof(struct pair));\n}\n\nstatic short pos = 0;\nif(pos % 10 == 0) {\n defaults = realloc(defaults, (pos + 10) * sizeof(struct pair));\n}\n</code></pre>\n\n<p>That allocates space for 10 el...
{ "AcceptedAnswerId": "202706", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T00:15:42.023", "Id": "202705", "Score": "0", "Tags": [ "c", "library" ], "Title": "Handler for default values in a CLI flag utility library in C" }
202705
<p>I wanted to try convert <a href="https://norvig.com/lispy.html" rel="noreferrer">Peter Norvigs' Python Scheme interpreter</a> to C++. I had tried this a few years before and failed abysmally but I saw that the latest C++ standard includes several features which might make things easier so I tried again. The tokenizing and parsing bits were easy but I struggled for a while with eval() until I had an epiphany and then that was straightforward to implement too.</p> <p>I have several more features to add before the program is equivalent to the python version (e.g. a REPL, if, quote, set! and lambda, the rest of the standard environment) but I have enough to run the example program Norvig gives so I thought it would be an appropriate juncture to ask for a critique. Apart from the standard issues of style etc. there are some specific questions I'd like to ask.</p> <ul> <li><p>Is std::list the best choice for the List datatype? There are a couple of places where using operator[] would make the code a little easier to read but std::list doesn't provide that. On the other hand it seems that e.g std::deque or std::vector use more memory/have other features I don't need.</p></li> <li><p>Am I using std::any correctly? All that typeid-ing and casting seems a bit clunky to me. At least I wish there was some way to add a "tag" more comprehensible than the gibberish the compile provides as a type name. Would I be better off in the long run providing my own class to hold Scheme data types (perhaps a wrapper around std::any?) instead of using raw std:any?</p></li> <li><p>builtin functions in the Python version are very elegant thanks to that languages lambda operator. "Well C++ has lambdas now" I thought but I ran into some difficulty. It is easy to stuff a lambda into a std::any but getting it back out is another matter entirely. I think it is because each lambda gets a unique and essentially random type name so we won't know what to std::any_cast it to. Is this correct? My workaround was to wrap lambdas in a std::function which does have an identifiable type name. Is this the right way to do it?</p></li> <li><p>This one is minor but is M_PI standard C++ or not? It seems not to be but if you include cmath, g++ defines it without giving a warning. </p></li> </ul> <pre><code>#include &lt;any&gt; #include &lt;cmath&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;list&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;typeinfo&gt; #include &lt;unordered_map&gt; using Symbol = std::string; using Expression = std::any; using List = std::list&lt;Expression&gt;; using Environment = std::unordered_map&lt;Symbol, Expression&gt;; using Function = std::function&lt;Expression(List&amp;, Environment&amp;)&gt;; Expression atom(const std::string&amp; token) { try { auto result = stol(token); return result; } catch (std::invalid_argument) { try { auto result = stod(token); return result; } catch (std::invalid_argument) { return token; } catch (std::out_of_range&amp; e) { throw e; } } catch (std::out_of_range) { throw std::runtime_error(token + " is out of range"); } } Expression read_from_tokens(std::list&lt;std::string&gt;&amp; tokens) { if (tokens.size() == 0) { throw std::runtime_error("unexpected EOF"); } auto token = tokens.front(); tokens.pop_front(); if (token == "(") { List L; while (tokens.front() != ")") { L.push_back(read_from_tokens(tokens)); } tokens.pop_front(); // pop off ')' return L; } else if (token == ")") { throw std::runtime_error("unexpected )"); } else { return atom(token); } } const std::list&lt;std::string&gt; tokenize(const std::string&amp; str) { std::string replaced; for (auto&amp; c: str) { switch(c) { case '(': replaced.append(" ( "); break; case ')': replaced.append(" ) "); break; default: replaced.append(1, c); } } std::istringstream stream(replaced); std::list&lt;std::string&gt; tokens; std::string token; while (stream &gt;&gt; token) { tokens.push_back(token); } return tokens; } Expression parse(const std::string&amp; str) { auto tokens = tokenize(str); return read_from_tokens(tokens); } Expression eval(Expression exp, Environment&amp; env) { auto&amp; type = exp.type(); try { if (type == typeid(Symbol)) { auto symbol = std::any_cast&lt;Symbol&gt;(exp); try { return env.at(symbol); } catch (std::out_of_range&amp;) { throw std::runtime_error(symbol + " is undefined"); } } else if (type == typeid(double)) { return std::any_cast&lt;double&gt;(exp); } else if (type == typeid(long)) { return std::any_cast&lt;long&gt;(exp); } else if (type == typeid(List)) { auto list = std::any_cast&lt;List&gt;(exp); auto proc = std::any_cast&lt;Symbol&gt;(list.front()); list.pop_front(); if (proc == "define") { auto var = std::any_cast&lt;Symbol&gt;(list.front()); list.pop_front(); env[var] = eval(list.front(), env); return {}; } else { List args; for (auto&amp; arg: list) { args.push_back(eval(arg, env)); } return std::invoke(std::any_cast&lt;Function&gt;(env[proc]), args, env); } } else { std::string error{exp.type().name()}; error += " is an unknown type"; throw std::runtime_error(error); } } catch(std::bad_any_cast&amp; e) { std::string error{exp.type().name()}; error += " is the wrong type"; throw std::runtime_error(error); } return exp; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Expression&amp; exp) { auto&amp; type = exp.type(); try { if (type == typeid(Symbol)) { out &lt;&lt; std::any_cast&lt;Symbol&gt;(exp) &lt;&lt; ' '; } else if (type == typeid(double)) { out &lt;&lt; std::any_cast&lt;double&gt;(exp); } else if (type == typeid(long)) { out &lt;&lt; std::any_cast&lt;long&gt;(exp); } else if (type == typeid(List)) { out &lt;&lt; "[ "; auto list = std::any_cast&lt;List&gt;(exp); for (auto&amp; item : list) { out &lt;&lt; item; } out &lt;&lt; "] "; } else { std::string error{exp.type().name()}; error += " is an unknown type"; throw std::runtime_error(error); } } catch(std::bad_any_cast&amp; e) { std::string error{exp.type().name()}; error += " is the wrong type"; throw std::runtime_error(error); } return out; } auto number(Expression&amp; exp) { return exp.type() == typeid(double) ? std::any_cast&lt;double&gt;(exp) : exp.type() == typeid(long) ? std::any_cast&lt;long&gt;(exp) : throw std::runtime_error("not a number"); } int main () { std::string program{"(begin (define r 10) (* pi (* r r)))"}; Environment standard_env; standard_env["begin"] = Function([](List&amp; args, Environment&amp;) -&gt; Expression{ return args.back(); }); standard_env["*"] = Function([](List&amp; args, Environment&amp;) -&gt; Expression { auto a = number(args.front()); args.pop_front(); auto b = number(args.front()); return a * b; }); standard_env["pi"] = M_PI; try { std::cout &lt;&lt; eval(parse(program), standard_env) &lt;&lt; '\n'; } catch (std::runtime_error&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre>
[]
[ { "body": "<blockquote>\n <p>Is std::list the best choice for the List datatype? There are a couple of places where using operator[] would make the code a little easier to read but std::list doesn't provide that. On the other hand it seems that e.g std::deque or std::vector use more memory/have other features ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T04:02:22.213", "Id": "202714", "Score": "8", "Tags": [ "c++", "scheme", "c++17", "interpreter" ], "Title": "Peter Norvigs' lis.py in c++17" }
202714
<p>This code allows <strong>Add, Edit and Delete</strong> a database record for the <code>Category</code> table. Separate Service classes are implemented to handle these operations which are called via the Web API Endpoint <code>CategoriesController</code>.</p> <ul> <li><p>I want to improve the current code pattern because I am not sure calling <code>BaseBusinessService.Execute()</code> on <code>CategoriesController</code> is good practise? </p></li> <li><p><code>Execute()</code> is declared as <strong>Public</strong> in the <strong>Abstract Class</strong> <code>BaseBusinessService</code>. I am not sure whether this is a good idea?</p></li> </ul> <p>The following code with basic explanation.</p> <p><strong>BaseController.cs</strong> - to abstract the common tasks, such as store the connection string.</p> <pre><code>public class BaseController { protected string DbConnectionString { get; } protected BaseController(IConfiguration configuration) { DbConnectionString = configuration.GetSection("connectionStrings:databaseConnectionString").Value; } } </code></pre> <p><strong>CategoriesController.cs</strong> - called via the api endpoint.</p> <pre><code>[Route("api/v1/categories")] public class CategoriesController : BaseController { public CategoriesController(IConfiguration configuration) : base(configuration) { } [HttpPost] public IActionResult Post([FromBody]CategoryModel model) { new CategoryAddService(DbConnectionString, model).Execute(); return new OkResult(); } [HttpPut("{id}")] public IActionResult Put(int id, [FromBody]CategoryModel model) { new CategoryEditService(DbConnectionString, id, model).Execute(); return new OkResult(); } [HttpDelete("{id}")] public IActionResult Delete(int id) { new CategoryDeleteService(DbConnectionString, id).Execute(); return new OkResult(); } } </code></pre> <p><strong>BaseBusinessService.cs</strong> - to abstract common methods, the implemented service classes must inherit from this class.</p> <pre><code>public abstract class BaseBusinessService { protected string DbConnectionString { get; } protected BaseBusinessService(string dbConnectionString) { DbConnectionString = dbConnectionString; } protected abstract void OnValidate(); protected abstract void OnExecute(); // This method is called from the Controller, that's why this is Public. Not a good idea? public void Execute() { OnValidate(); OnExecute(); } } </code></pre> <p><strong>CategoryAddService.cs</strong> - Gets called from the Api Endpoint and adds a single record into the database.</p> <pre><code>public class CategoryAddService : BaseBusinessService { CategoryModel _categoryModel; public CategoryAddService(string dbConnectionString, CategoryModel categoryModel) : base(dbConnectionString) { _categoryModel = categoryModel; } protected override void OnValidate() { } protected override void OnExecute() { var poco = PreparePoco(_categoryModel.CategoryName); AddCategoryRecord(poco); } CategoryPoco PreparePoco(string categoryName) { return new CategoryPoco() { CategoryName = categoryName }; } void AddCategoryRecord(CategoryPoco poco) { using (var connection = new SqlConnection(DbConnectionString)) { connection.Insert(poco); } } } </code></pre> <p><strong>CategoryEditService.cs</strong> - Gets called from the api endoint, validates the existing record and updates the row in the database.</p> <pre><code>public class CategoryEditService : BaseBusinessService { readonly string _categoryName; readonly int _id; public CategoryEditService(string dbConnectionString, int id, CategoryModel categoryModel) : base(dbConnectionString) { _categoryName = categoryModel.CategoryName; _id = id; } protected override void OnValidate() { // Validate and throw the error if the doesn't exists. } protected override void OnExecute() { var poco = PreparePoco(_categoryName); UpdateCategoryRecord(poco); } CategoryPoco PreparePoco(string categoryName) { return new CategoryPoco() { CategoryId = _id, CategoryName = categoryName }; } void UpdateCategoryRecord(CategoryPoco poco) { using (var connection = new SqlConnection(DbConnectionString)) { connection.Update(poco); } } } </code></pre> <p><strong>CategoryDeleteService.cs</strong> - Gets called via the api endoing, validates the existing row and deletes a record from the database.</p> <pre><code>public class CategoryDeleteService : BaseBusinessService { readonly int _id; public CategoryDeleteService(string dbConnectionString, int id) : base(dbConnectionString) { _id = id; } protected override void OnValidate() { // Validate and throw the error if the doesn't exists. } protected override void OnExecute() { DeleteCategoryRecord(); } void DeleteCategoryRecord() { using (var connection = new SqlConnection(DbConnectionString)) { connection.Delete&lt;CategoryPoco&gt;(_id); } } } </code></pre> <p><strong>CategoryPoco.cs</strong> - This is used for the Dapper and SimpleCRUD ORM.</p> <pre><code>using Dapper; namespace AppPattern.Categories.Services { [Table("Category")] public sealed class CategoryPoco { [Key] public int CategoryId { get; set; } public string CategoryName { get; set; } } } </code></pre> <p><strong>CategoryModel.cs</strong> - A model which does the <em>validation</em> using FluentValidation library.</p> <pre><code>using FluentValidation; namespace AppPattern.Categories.Models { public class CategoryModel { string _categoryName; public string CategoryName { get { return _categoryName; } set { _categoryName = value.Trim(); } } } class CategoryAddModelValidator : AbstractValidator&lt;CategoryModel&gt; { public CategoryAddModelValidator() { RuleFor(x =&gt; x.CategoryName).NotEmpty(); RuleFor(x =&gt; x.CategoryName).Length(1, 128) .When(x =&gt; !string.IsNullOrEmpty(x.CategoryName)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T11:29:10.893", "Id": "390649", "Score": "1", "body": "Have you considered [using MediatR](https://github.com/jbogard/MediatR/wiki)? You can [add validation](https://stackoverflow.com/questions/42283011/add-validation-to-a-mediatr-be...
[ { "body": "<p><strong>Dependency inversion principle violation</strong></p>\n<p><code>CategoriesController</code> depend on <code>Category[operation]Services</code> (concrete implementations) rather depending on abstractions.</p>\n<p>How to prevent this rule violation? <em>Write unit tests</em>.</p>\n<p><strong...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T04:24:17.540", "Id": "202715", "Score": "1", "Tags": [ "c#", "design-patterns", "asp.net-web-api", "crud" ], "Title": "Design Pattern to Add, Edit and Delete Records" }
202715
<p>I would greatly appreciate feedback on the enclosed script, which auto-generates a Markdown table of contents for Github-flavoured Markdown, with respect to:</p> <ul> <li>Consistency with Ruby idiom &amp; style</li> <li>Any use of bad practices</li> </ul> <pre class="lang-rb prettyprint-override"><code>#!/usr/bin/env ruby def usage puts "Usage: #{$0} FILE.md" exit 1 end class ToCWriter def initialize(source_file, top=2, max=4) @source_file = source_file @top = top @max = max @c = 1 @level = "" @header = "" @start = "" write end def write puts "#### Table of contents\n\n" File.open(@source_file).each_line do |line| next unless line.match(/^#/) @level, @header = line.match(/^(#+) (.*)/).captures next if @header == "Table of contents" next if skip? ref = header_to_ref set_start puts "#{@start} [#{@header}](##{ref})" end end private def skip? len = @level.length len &lt; @top || len &gt; @max end def header_to_ref @header .gsub(/ /, "-") .gsub(/[\.\/,&amp;\()&lt;&gt;-]+/, "-") .gsub(/-$/, "") .downcase end def set_start len = @level.length if len == @top @start = "#{@c}." @c += 1 else bullet = len % 2 == 0 ? "*" : "-" @start = " " * (len - 2) + bullet end end end usage unless ARGV.length == 1 source_file = ARGV[0] ToCWriter.new(source_file) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T12:44:11.353", "Id": "391690", "Score": "0", "body": "use ' instead of \" when you can\nIn fact I suggest you to use rubocop, it will help you with all thoose little things" }, { "ContentLicense": "CC BY-SA 4.0", "Creati...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T04:32:16.263", "Id": "202716", "Score": "4", "Tags": [ "ruby", "file", "formatting", "markdown" ], "Title": "Script to auto-generate Markdown tables of contents" }
202716
<p>What do you think of my markdown previewer, which uses the <a href="https://github.com/markedjs/marked/tree/fadec132b600475a9d60fc66734cc83cb9fc16ef" rel="nofollow noreferrer">marked library</a>? I'm asking because I'm new to React. And also what do you think of app itself? Did I use React correctly and properly?</p> <p>HTML:</p> <pre><code>&lt;div id="root"&gt;&lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>$position: absolute; $percentage: 100%; $color: whitesmoke; $car: auto; @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css"); @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"); .btn1 { position: $position; bottom: -30px; left: 51.3%; z-index: 999; background-color: $color; border: 1px solid gray; color: aqua; } #root { width: $percentage; //font-size: 1.5em; } body, html { height: $percentage; } body { background-color: $color; background-image: url("../images/react1.png"); background-repeat: no-repeat; background-size: $car; background-position: center bottom; overflow: hidden; } .grid-container { display: grid; grid-template-columns: 50% 50%; background-color: $color; padding: 10px; grid-gap: 15px; width: $percentage; grid-template-rows: 30px 25px 98%; } .grid-item { text-align: center; margin-top: 10px !important; padding-top: 10px !important; } #inner2 { padding-left: 20px; padding-right: 25px; border-bottom: 15px solid #d6e9c6; padding-bottom: 55px; background-color: #fcf8e3; width: $percentage; margin-left: $car; margin-right: $car; position: $position; top: 0px; left: 0px; height: $percentage; min-height: 20%; max-height: $percentage; } #editor { width: $percentage; background-color: white; resize: none; color: #495057; border: 1px solid #ced4da; border-radius: 0.25rem; overflow-y: $car; max-height: $percentage; min-height: 40px; margin-bottom: 40px; } #preview { width: 98.9%; background-color: white; border-radius: 0.25rem; border: 1px solid #ced4da; overflow-y: $car; max-height: $percentage; min-height: 40px; margin-bottom: 40px; } #item1, #item2 { font-family: "Russo One" !important; font-style: oblique !important; font-weight: 700 !important; font-size: 2em !important; margin-bottom: 10px; padding-bottom: 0px; width: $percentage; background-color: #fcf8e3; min-height: 50px; border-bottom: none; margin-top: 10px !important; padding-top: 10px !important; } .insignia { letter-spacing: 5px; -webkit-transition: letter-spacing 1s; transition: letter-spacing 1s; } .insignia:hover { letter-spacing: 13px; cursor: pointer; } .ui-resizable-s { cursor: row-resize; } textarea:focus, input:focus { outline: none; } #arrow { background-color: #dff0d8; width: $percentage; height: 15px; position: $position; bottom: -12px; padding-left: 0px; padding-right: 0px; font-size: 1.5em; border-bottom: 1px solid #d6e9c6; text-align: center; } .glyphicon { top: -4px; left: 4px; color: gray; -ms-transform: scale(1, 0.6); /* IE 9 */ -webkit-transform: scale(1, 0.6); /* Safari */ transform: scale(1, 0.6); } #eraser { text-align: center; grid-column: 1 / 3; z-index: 2; line-height: 10px; margin-left: $car; margin-right: $car; } /*Additional styling*/ td, th { border: 2px solid #224b4b; padding-left: 5px; padding-right: 5px; } .label { position: $position; top: -10px; left: 0px; min-width: $percentage; z-index: 999; } .preview-editor { position: fixed; top: 55px; left: 0px; min-width: $percentage; height: $percentage; z-index: 999; } h1 { margin-top: 10px !important; padding-top: 10px !important; border-bottom: 2px solid #224b4b; } h2 { border-bottom: 1px solid #224b4b; } code { background-color: #d6e9c6; color: #e83e8c !important; } blockquote { border-left: 2px solid black; padding-left: 5px; margin-left: 25px; } @media only screen and (max-width: 768px) { img { width: 100%; } #ggED { text-align: left; } #ggPrev { text-align: right; } .insignia, .insignia:hover { letter-spacing: 0px !important; font-size: 1em !important; } #root { //font-size: 1.25em; } } </code></pre> <p>JS part: </p> <pre><code>/*const Inner2 = (props) =&gt; { return ( &lt;div id={this.props.id} className={this.props.className} style={this.props.style} onDoubleClick={this.props.onDoubleClick}&gt;Editor:&lt;/div&gt; ); };*/ var renderer = new marked.Renderer(); renderer.link = function(href, title, text) { return ( '&lt;a target="_blank" href="' + href + '" title="' + title + '"&gt;' + text + "&lt;/a&gt;" ); }; marked.setOptions({ breaks: true, renderer: renderer, sanitize: true }); class DisplayMessages extends React.Component { constructor(props) { super(props); this.state = { markdown: defaultMarkdown, erase: false, goFull: false, headViewKlasa: "grid-item", headEdKlasa: "grid-item", editorKlasa: "", previewKlasa: "", stilPreview: {}, stilEditor: {}, attr: "Click on me for fullscreen", inner2H: "", h2Inner: false }; this.handleChange = this.handleChange.bind(this); this.eraseFields = this.eraseFields.bind(this); this.inner2Height = this.inner2Height.bind(this); } eraseFields() { this.setState({ erase: true }); if (this.state.erase === false) { this.setState({ markdown: "" }); } if (this.state.erase === true) { this.setState({ markdown: defaultMarkdown, erase: !this.state.erase }); } } /*componentDidMount() { this.node = ReactDOM.findDOMNode(this); $(this.node).resizable({ handles: "s", minHeight: 170 }); document .querySelector(".ui-resizable-handle.ui-resizable-s") .setAttribute( "title", "Double click on me or pull me down to full height" ); }*/ inner2Height() { if (this.state.h2Inner === false) { this.setState({ inner2H: "100%", h2Inner: true }); } if (this.state.h2Inner === true) { this.setState({ inner2H: "", h2Inner: false }); } } fullScreen(clicked_id) { if (clicked_id === "ggEd" &amp;&amp; this.state.goFull === false) { this.setState({ headEdKlasa: this.state.headEdKlasa + " label", attr: "Click again to go back!", editorKlasa: "preview-editor", stilPreview: { display: "none" }, stilEditor: { paddingTop: "0px" }, goFull: true }); } if (clicked_id === "ggEd" &amp;&amp; this.state.goFull === true) { this.setState({ headEdKlasa: this.state.headEdKlasa.substr(0, 9), attr: "Click on me for fullscreen", editorKlasa: "", stilPreview: { display: "block" }, stilEditor: { paddingTop: "10px" }, goFull: !this.state.goFull }); } if (clicked_id === "ggPrev" &amp;&amp; this.state.goFull === false) { this.setState({ headViewKlasa: this.state.headViewKlasa + " label", attr: "Click again to go back!", previewKlasa: "preview-editor", stilEditor: { display: "none" }, stilPreview: { paddingTop: "0px" }, goFull: true }); } if (clicked_id === "ggPrev" &amp;&amp; this.state.goFull === true) { this.setState({ headViewKlasa: this.state.headViewKlasa.substr(0, 9), attr: "Click on me for fullscreen", previewKlasa: "", stilEditor: { display: "block" }, stilPreview: { paddingTop: "10px" }, goFull: !this.state.goFull }); } } handleChange(event) { this.setState({ markdown: event.target.value }); } render() { const btnText = this.state.erase ? "Populate" : "Erase"; const handleClick = e =&gt; this.fullScreen(e.target.id); return ( &lt;div id="inner2" className="grid-container animated zoomIn" style={{ height: this.state.inner2H }} onDoubleClick={this.inner2Height} &gt; &lt;EditorHead id={"item1"} style={this.state.stilEditor} className={this.state.headEdKlasa} onClick={handleClick} title={this.state.attr} /&gt; &lt;PreviewHead id={"item2"} style={this.state.stilPreview} className={this.state.headViewKlasa} onClick={handleClick} title={this.state.attr} /&gt; &lt;BtnEraser id={"eraser"} onClick={this.eraseFields} type={"button"} className={"btn btn-danger btn-lg"} title={"Erase &amp; populate both fields"} value={btnText} /&gt; &lt;Editor id={"editor"} onChange={this.handleChange} className={this.state.editorKlasa} value={this.state.markdown} placeholder={"Enter ... some kind a text!? ..."} title={ "This is rather obvious isn't it? It's editor window Sherlock :D" } /&gt; &lt;Preview id={"preview"} className={this.state.previewKlasa} dangerouslySetInnerHTML={{ __html: marked(this.state.markdown, { renderer: renderer }) }} title={"It's a preview window, Sherlock ;)"} /&gt; &lt;Arrow id={"arrow"} /&gt; &lt;/div&gt; ); } } /*class Inner2 extends React.Component{ render(){ return ( &lt;div id={this.props.id} className={this.props.className} style={this.props.style} onDoubleClick={this.props.onDoubleClick}&gt;Editor:&lt;/div&gt; ); } }*/ class EditorHead extends React.Component { render() { return ( &lt;h1 id={this.props.id} style={this.props.style} className={this.props.className} onClick={this.props.onClick} &gt; &lt;span className="insignia" title={this.props.title} id="ggEd"&gt; Editor: &lt;/span&gt; &lt;/h1&gt; ); } } class PreviewHead extends React.Component { render() { return ( &lt;h1 id={this.props.id} style={this.props.style} className={this.props.className} onClick={this.props.onClick} &gt; &lt;span className="insignia" title={this.props.title} id="ggPrev"&gt; Previewer: &lt;/span&gt; &lt;/h1&gt; ); } } class BtnEraser extends React.Component { render() { return ( &lt;button id={this.props.id} onClick={this.props.onClick} type={this.props.type} className={this.props.className} title={this.props.title} &gt; {this.props.value} &lt;/button&gt; ); } } class Editor extends React.Component { render() { return ( &lt;textarea id={this.props.id} onChange={this.props.onChange} className={this.props.className} value={this.props.value} placeholder={this.props.placeholder} title={this.props.title} /&gt; ); } } class Preview extends React.Component { render() { return ( &lt;div id={this.props.id} className={this.props.className} dangerouslySetInnerHTML={this.props.dangerouslySetInnerHTML} title={this.props.title} /&gt; ); } } class Arrow extends React.Component { render() { return ( &lt;div id={this.props.id}&gt; &lt;Glyph className={"glyphicon glyphicon-align-justify"} /&gt; &lt;/div&gt; ); } } class Glyph extends React.Component { render() { return &lt;span className={this.props.className} /&gt;; } } ReactDOM.render(&lt;DisplayMessages /&gt;, document.getElementById("root")); </code></pre> <p><a href="https://codepen.io/codename11/full/vaqMwE/" rel="nofollow noreferrer">Codepen</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T04:57:13.133", "Id": "202717", "Score": "2", "Tags": [ "react.js", "jsx", "markdown", "text-editor" ], "Title": "Markdown Previewer app done in ReactJS" }
202717
<p>I'd like to read lines from a file and process them concurrently. I came up with the following code to do this:</p> <pre><code>var wg sync.WaitGroup func main(){ file := "data/input.txt" reader, _ := os.Open(file) scanner := bufio.NewScanner(reader) for scanner.Scan() { wg.Add(1) go processLine(scanner.Text()) } wg.Wait() } func processLine(line string) { time.Sleep(time.Duration(rand.Intn(5)) * time.Second) fmt.Println("line:", line) wg.Done() } </code></pre> <p>I added the random sleep time in there to simulate potential differences in processing times. </p> <p>Is there any potential drawbacks that I should be aware of with this method of concurrent processing? Are there any better ways that I should consider concurrently processing lines in a file?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T06:28:32.367", "Id": "390600", "Score": "1", "body": "Did you try it? Does it work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:41:07.453", "Id": "390670", "Score": "1", ...
[ { "body": "<p>The general approach seems fine. You may want to benchmark your application based on the type of inputs you'll receive and the type of computation that's done. If the computation is CPU intensive, it may not make sense to have too many goroutines running in parallel since they can't all use the CP...
{ "AcceptedAnswerId": "202794", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T06:07:46.853", "Id": "202718", "Score": "1", "Tags": [ "file", "go", "concurrency" ], "Title": "Reading lines from a file and processing them concurrently" }
202718
<p>Okay here is my <em>maiden attempt</em> at programming using <strong>Python 2.7.</strong> I need help or feedback on this code:</p> <ol> <li>How do I know about the <em>processing cycles</em> this program consumes?</li> <li>How do I implement this idea using <em>recursion</em>?</li> <li><p>What's the best way of removing duplicate items fom a list. I am not happy with this</p> <pre><code>#remove the duplicate elements in the list set_of_factors = set(list_of_all_quotients) list_of_all_quotients = list(set_of_factors) return list_of_all_quotients </code></pre></li> </ol> <p>The <strong>design constraints</strong> are the following:</p> <ol> <li>The <em>prime numbers</em> are to be generated at the run time.</li> <li>All <em>composite</em> (non-prime) factors are to be <em>derived</em> from prime factors only.</li> </ol> <p>Here goes the code:</p> <pre><code>#-------------------This Function would find all the prime factors of a given number------------- def find_prime_factors(number): list_of_prime_factors = [] quotient = number while (quotient &gt; 1): if(quotient % 2 == 0): #check whether the quotient is even? list_of_prime_factors.append(2) quotient = quotient / 2 else: #if the quotient is odd for index in xrange (3, 1 + (number/2),2): #start the for loop at 3 and end at a number around one-half of the quotient, and test with odd numbers only if (quotient % index == 0 ): list_of_prime_factors.append(index) quotient = quotient / index else: #The number isn't even and there are no odd numbered factors for it, that is it's a prime. break #------------------------------------- return list_of_prime_factors #-------------------This Function would find quotients that would result by dividing the number by it's prime factors------------------ def find_all_quotients(number, list_of_prime_factors = []): list_of_all_quotients = [] dividend = number for index in list_of_prime_factors: dividend = dividend / index list_of_all_quotients.append(index) list_of_all_quotients.append(dividend) if (len(list_of_all_quotients) == 0): return list_of_all_quotients else: #if the last item in the list is 1, then remove it: if(list_of_all_quotients[-1] == 1 ):list_of_all_quotients.pop() #remove the duplicate elements in the list set_of_factors = set(list_of_all_quotients) list_of_all_quotients = list(set_of_factors) return list_of_all_quotients #This Function would find all the factors of a number #--by using it's prime factors and quotients (derived by dividing it by it's prime factors) def find_all_factors(number, list_of_prime_factors = [] ,list_of_all_quotients = []): list_of_all_factors = list_of_all_quotients for otr_index in range(0, len(list_of_prime_factors) ): for inr_index in range(0, len(list_of_all_factors)): product = list_of_prime_factors[otr_index] * list_of_all_factors[inr_index] if (number % product == 0 and number != product): list_of_all_factors.append(product) if (len(list_of_all_factors) == 0): return list_of_all_factors else: #if the last item in the list is 1, then remove it: if(list_of_all_factors[-1]==1): list_of_all_factors.pop() #remove the duplicate elements in the list set_of_factors = set(list_of_all_factors) list_of_all_factors = list(set_of_factors) return list_of_all_factors #-------------------This Function would print all the prime factors of a given number------------ def print_factors(number, list_to_be_printed=[], separator=''): if (len(list_to_be_printed) == 0) : #No roots - means a prime number: if (separator == ''): print"\n\nTry again", else: print"\n\nOops {} is a prime number! So, it doesn't have any prime factors except for 1 and iself. ".format(number) #Composite Number: else: factors = list_to_be_printed factors.sort() if separator == '': #The separator isn't specified or empty, means print all factors separated by space: print "\n\nAll the Factors for {} would be = ".format(number), for index in xrange (0, len(factors)): print "{}".format(factors[index]), if (index + 1 == len(factors)): pass else: print separator, else: #Some separator is specified, use that, and print prime numbers: print "\n\nThe Prime Factorization for {} would be = ".format(number), for index in xrange (0, len(factors)): print "{}".format(factors[index]), if (index + 1 == len(factors)): pass else: print separator, #-------------------The Main Function Block------------------------------------------------------- def main(): str_product = raw_input("Please enter a number to get its factors ") int_product = int(str_product) #------------------------------------------------------------------ prime_factors = find_prime_factors(int_product) print_factors(int_product, prime_factors,'X') quotients = find_all_quotients(int_product, prime_factors) all_factors = find_all_factors(int_product, prime_factors,quotients) print_factors(int_product, all_factors,'') #----------------------------------------------------------------- if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>A couple of stylistic comments and python gotchas:</p>\n\n<p>If you are just starting out in Python I would look to use Py3 and if you can't use Py3, use some of the <code>__future__</code> imports to ensure you are writing code that is compatible and behaves the same, e.g.:</p>\n\n<pre><code>from...
{ "AcceptedAnswerId": "202768", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T08:30:52.230", "Id": "202727", "Score": "0", "Tags": [ "python", "performance", "beginner", "primes", "python-2.x" ], "Title": "Printing all the factors as well as the prime factors of a given number using Python 2.7.x" }
202727
<p>We have pages that contain 1-3 forms. Each form does have a submit button which is styled as inactive<sup>*</sup> as long as the user didn't change the form.</p> <p>Now I need to:</p> <ul> <li>remove the class from the button as soon as the form changes</li> <li>remove the event listener from the form</li> </ul> <p>I came up with this:</p> <pre><code>for (const form of Array.from(document.getElementsByClassName('form'))) { const formHandlerChange = event =&gt; { const submit = form.getElementsByClassName('disabled')[0]; submit.classList.remove('disabled'); form.removeEventListener('change', formHandlerChange); }; form.addEventListener('change', formHandlerChange); } </code></pre> <p>Is this a good solution? Is it a bad thing to create <code>formHandlerChange</code> for each form? Would it be better to get the form each time <code>formHandlerChange</code> is entered manually and have this function defined only once outside the loop?</p> <p><sub><sup>*</sup> It's also <code>disabled</code> but I removed it for simplicity of this review.</sub></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T15:20:18.790", "Id": "390722", "Score": "0", "body": "Is it really necessary to remove the event handler after it triggers? In your case it would seem that you would just remove the `disabled` class more than once.\nWhat I prefer to...
[ { "body": "<p>If you use <code>event.currentTarget</code> instead of <code>form</code>, you can declare the event handler function once and reuse it:</p>\n\n<pre><code>function formHandlerChange(event) {\n const form = event.currentTarget;\n const submit = form.querySelector('.disabled');\n submit.clas...
{ "AcceptedAnswerId": "202741", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T09:09:21.950", "Id": "202730", "Score": "0", "Tags": [ "javascript", "event-handling" ], "Title": "Activate submit button on form change and detach event listener" }
202730
<p>I would appreciate some criticsm on my code so that I could improve it. I tried making the Snake game in OOP but don't think I did it right. Any suggestions would be appreciated.</p> <p>The code is is commented in my language which isn't english hope that won't be a problem :)</p> <p>Here is the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;vector&gt; #include &lt;conio.h&gt; #include &lt;windows.h&gt; using namespace std; //Mihael Petricevic enum objects {EMPTY, WALL, SNAKE_HEAD, SNAKE_TAIL, FRUIT}; objects** Map; //KONSTANTE const int m_x = 40; const int m_y = 10; class GameObject { public: //INHERITED BY CHILD CLASSES virtual void update() = 0; }; class Snake : public GameObject { public: void update(); private: int _x = 19; int _y = 4; int _x_old, _y_old; int _direction = 3; int _tsize = 0; //PRIVATE STRUCT struct Tail { int x; int y; }; //ARRAY OR TAILS vector&lt;Tail&gt;tails; //HELPER METHODS void _KeyBoard(); void _MoveSnake(); void _AddTail(); bool _Ate(); void _MoveTail(); void _Collision(); }; /* UZIMA INPUT OD IGRACA I MJENJA SMJER ZMIJE */ void Snake::_KeyBoard() { /* 1 up 2 3 left right 4 down */ if (kbhit()) { char input = getch(); if (input == 'w') { _direction = 1; } else if (input == 'a') { _direction = 2; } else if (input == 'd') { _direction = 3; } else if (input == 's') { _direction = 4; } } } /* */ void Snake::_MoveSnake() { //SPREMA ZADNJE KORDINATE PRIJE PROMJENE ZA PRVI REP _x_old = _x; _y_old = _y; switch(_direction) { case 1: { _y--; break; } case 2: { _x--; break; } case 3: { _x++; break; } case 4: { _y++; break; } } //STAVLJA MJESTO GLAVE ZMIJE U IGRACE POLJE Map[_y_old][_x_old] = EMPTY; Map[_y][_x] = SNAKE_HEAD; } /* FUNKCIJA DODAVA NOVI REP - NA POCETKU DODAVA 2 REPA JER TOLIKO IMA ZMIJA POCETNO - KASNIJE AKO JE POJELA VOCE SE DODAVA JOS JEDAN IZA ZADNJEG BAZIRAN O DIREKCIJU U KOJOJ SE MICE ZMIJA */ void Snake::_AddTail() { //NA POCETKU IGRE ZMIJA IMA 2 REPA if (_tsize == 0) { for (int i=0;i&lt;2;i++) { tails.push_back(Tail()); tails[i].x = 19 - i; //OVO SAMO STAVLJA REPA 1 IZA GLAVE PA ONDA 2 IZA GLAVE (NIJE 18 JER SE POMAKNE ZA 1 ODMA CIM SE STVORI OBJEKT SNAKE) tails[i].y = 4; //STAVLJANJE REPA U IGRACE POLJE Map[tails[i].y][tails[i].x] = SNAKE_TAIL; //POVECANJE BROJA REPA KOJI JE NA POCETKU 0 _tsize++; } } if (_Ate()) { //DODAVA NOVI REP tails.push_back(Tail()); //ODREDIVANJA KORDINATA NOVOG REPA switch(_direction) { case 1: { tails[_tsize].x = tails[_tsize - 1].x; tails[_tsize].y = tails[_tsize - 1].y - 1; break; } case 2: { tails[_tsize].x = tails[_tsize - 1].x + 1; tails[_tsize].y = tails[_tsize - 1].y; break; } case 3: { tails[_tsize].x = tails[_tsize - 1].x - 1; tails[_tsize].y = tails[_tsize - 1].y; break; } case 4: { tails[_tsize].x = tails[_tsize - 1].x; tails[_tsize].y = tails[_tsize - 1].y + 1; break; } } //POVECAVA SE KOLIKI JE BROJ REPA _tsize++; } } /* GLEDA AKO JE ZMIJA POJELA VOCE */ bool Snake::_Ate() { //AKO ZMIJA IDE U SMJERU VOCA I AKO JE VOCE JEDNO POLJE ISPRED ONDA ZNACI DA GA JE IGRAC POJEO if (_direction == 1 &amp;&amp; Map[_y - 1][_x] == FRUIT) { return true; } else if (_direction == 2 &amp;&amp; Map[_y][_x - 1] == FRUIT) { return true; } else if (_direction == 3 &amp;&amp; Map[_y][_x + 1] == FRUIT) { return true; } else if (_direction == 4 &amp;&amp; Map[_y + 1][_x] == FRUIT) { return true; } return false; } /* POMICE ZMIJIN REP TAKO DA UZIMA KORDINATE ZADNJEG REPA I PREBACUJE GA NE SLJEDECI */ void Snake::_MoveTail() { //ZADNJI REP SE BRISE Map[tails[_tsize - 1].y][tails[_tsize - 1].x] = EMPTY; //UZIMA KORDINATE ZADNJEG REPA BRISE SVOJE MJESTO I UZIMA KORDINATE SLJEDECOG REPA for (int i=_tsize - 1;i!=0;i--) { tails[i].x = tails[i-1].x; tails[i].y = tails[i-1].y; } //STAVLJAM DA JE PRVI REP SADA NA STAROM MJESTU GLAVE ZMIJE tails[0].x = _x_old; tails[0].y = _y_old; //STAVLJA DA JE PRVI REP NA POZICIJ Map[_y_old][_x_old] = SNAKE_TAIL; } /* PROVJERAVA DA LI JE IGRAC IZGUBIO */ void Snake::_Collision() { //JE LI IGRAC UDARIO ZID if (_x == 0 || _x == 39) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } if (_direction == 1 &amp;&amp; Map[_y - 1][_x] == WALL || _direction == 4 &amp;&amp; Map[_y + 1][_x] == WALL) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } //PROVJERA AKO JE IGRAC SE ZALETIO U SVOJ REP if (_direction == 1 &amp;&amp; Map[_y - 1][_x] == SNAKE_TAIL) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } else if (_direction == 2 &amp;&amp; Map[_y][_x - 1] == SNAKE_TAIL) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } else if (_direction == 3 &amp;&amp; Map[_y][_x + 1] == SNAKE_TAIL) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } else if (_direction == 4 &amp;&amp; Map[_y + 1][_x] == SNAKE_TAIL) { cout &lt;&lt; "YOU LOST, GET GUD SCRUB!"; system("pause"); exit(0); } } /* ZOVE SVE HELPER METHODS ZA ZMIJU STVARA LOOP UPDATA SVE PODATKE O ZMIJI I NJEZINOM REPU */ void Snake::update() { _KeyBoard(); _AddTail(); _Collision(); _MoveSnake(); _MoveTail(); } class Fruit : public GameObject { public: void update(); private: int _x; int _y; //HELPER METHODS void _spawnFruit(); bool _check_for_fruit(); }; /* STVARA VOCE NA RANDOM LOKACIJI NA MAPI */ void Fruit::_spawnFruit() { int x,y; x = 1 + rand() % 38; y = 1 + rand() % 8; Map[y][x] = FRUIT; } /* PROVJERAVA AKO JE KORISNIK POJEL VOCE TJ. AKO IMA VOCA NA MAPI */ bool Fruit::_check_for_fruit() { for (int i=1;i&lt;m_y - 1;i++) { for (int j=1;j&lt;m_x - 1;j++) { if (Map[i][j] == FRUIT) { return true; } } } return false; } /* ZOVE SVE HELPER METHODS ZA VOCE I STVARA GA AKO GA NEMA NA IGRACEM POLJU */ void Fruit::update() { if (!_check_for_fruit()) { _spawnFruit(); } } /* STVARA LISTU KOJA UPDATA SVAKI OBJEKT IGRE */ void Scene(vector&lt;GameObject*&gt;&amp;updates) { //AKO NEMA OVOGA SE BUDE SVAKI PUT SPREMILA NOVA INSTANCA OBJEKTA SNAKE I FRUIT TE BUDU IMALI DEFAULT VRIJEDNOST I NEBUDU SE UOPCE MJENJALI //GLEDAM AKO JE VEKTOR PRAZAN I AKO JE GA POPUNJAVAM SA NOVIM INSTANCAMA OBJEKTI //ISTO KAO DA NAPRAVIM Snake a.update(); I ONDA NAKON OPET STVARAM TAJ OBJEKT PA SE ON RESETIRA PA ZA TO SLUZI IF //MOGLO SE SAMO I NAPISATI TU Snake a.update(); ISTO BI DOSLO ALI MORA BITI OVAJ IF if (updates.size() == 0) { //SPREAMNJE SUBKLASI U VEKTOR TAKO DA SLAZEMO NOVI POINTER PREMA TOJ SUBKLASI updates.push_back(new Snake()); updates.push_back(new Fruit()); } //ZOVE SE UPDATE SVAKE SUBKLASSE for (vector&lt;GameObject*&gt;::iterator itr = updates.begin(), end = updates.end();itr != end; itr++) { (*itr)-&gt;update(); } } /* CRTA IGRACE POLJE I OBJEKTE IGRE */ void draw() { //REFRESH SCREEN COORD cur = {0,0}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur); //CRATNJE IGRACEG POLJA for (int i=0;i&lt;m_y;i++) { for (int j=0;j&lt;m_x;j++) { if (Map[i][j] == WALL) { cout &lt;&lt; "*"; } else if (Map[i][j] == EMPTY) { cout &lt;&lt; " "; } else if (Map[i][j] == SNAKE_HEAD) { cout &lt;&lt; "O"; } else if (Map[i][j] == SNAKE_TAIL) { cout &lt;&lt; "o"; } else if (Map[i][j] == FRUIT) { cout &lt;&lt; "+"; } } cout &lt;&lt; endl; } } /* FUNKCIJA MAIN() */ int main() { //srand(time(0)); //KREACIJA MAPE Map = new objects*[m_y]; for (int i=0;i&lt;m_y;i++) { Map[i] = new objects[m_x]; } //ISPUNJAVANJE MAPE for (int i=0;i&lt;m_y;i++) { for (int j=0;j&lt;m_x;j++) { if (i == 0 || i == m_y-1 || j == 0 || j == m_x-1) { Map[i][j] = WALL; } else { Map[i][j] = EMPTY; } } } //KREIRANJE LISTE KOJA UPDATA SVE OBJEKTE CLASSE GAMEOBJECT vector&lt;GameObject*&gt;updates; //MAIN GAME LOOP while (1) { draw(); Scene(updates); Sleep(200); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T10:07:45.227", "Id": "390632", "Score": "0", "body": "Which version of C++ is this targeting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T10:33:24.650", "Id": "390641", "Score": "0", "...
[ { "body": "<p>Welcome to Code Review. I hope my criticism will be constructive and you take it as opportunity to improve yourself.\nWe all are here to learn something, including myself.</p>\n\n<h1>using namespace std</h1>\n\n<p>This may be the <em>easy</em> way, but not so good, it can cause a lot of trouble an...
{ "AcceptedAnswerId": "202823", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T09:49:49.677", "Id": "202731", "Score": "3", "Tags": [ "c++", "object-oriented", "snake-game" ], "Title": "Console Snake Game in C++ with Classes" }
202731
<p>In order to practice some Haskell, I tried <a href="http://osherove.com/tdd-kata-1/" rel="nofollow noreferrer">this kata</a>, where the task is to add some numeric inputs that are delimited by commas or newlines.</p> <p>I have the below solution in Haskell which passes my tests, but could anyone offer any improvements? It feels a bit messy to me so feedback on how to make it more functional (my experience is pretty much all OO until now) would be great!</p> <p><strong>Known failings:</strong></p> <p>This does not try to be smart about invalid syntax so the pattern matching is not exhaustive - would the best solution here be to use a try/either type? This seemed like it would add quite a bit of noise at this stage so for now I have left this. It also does not fail on negative numbers for the same reason.</p> <p><strong>Code:</strong></p> <pre><code>module Calculator where import Data.List.Split defaultDelimiters = [",", "\n"] readInt :: String -&gt; Int readInt = read splitAtDelims :: ([String], String) -&gt; [String] splitAtDelims (delims, body) = foldr splitEachOnSubStr [body] delims where splitOnSubStr = split . dropBlanks . dropDelims . onSublist splitEachOnSubStr = concatMap . splitOnSubStr parseDelim :: String -&gt; String -&gt; (String, String) parseDelim (']':xs) delim = (delim, xs) parseDelim (x:xs) delim = parseDelim xs (delim++[x]) parseCustomDelimiters :: [String] -&gt; String -&gt; ([String], String) parseCustomDelimiters [] (delim:'\n':body) = ([[delim]], body) parseCustomDelimiters delims ('\n':rest) = (delims, rest) parseCustomDelimiters delims ('[':rest) = parseCustomDelimiters newDelims remainingText where parsed = parseDelim rest "" newDelims = delims ++ [fst parsed] remainingText = snd parsed parse :: String -&gt; ([String], String) parse ('/':'/':text) = parseCustomDelimiters [] text parse body = (defaultDelimiters, body) add :: String -&gt; Int add = sum . filter (&lt; 1000) . map readInt . splitAtDelims . parse </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T14:34:03.837", "Id": "390715", "Score": "3", "body": "You seem to be ignoring the TDD aspect of the kata." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T20:19:34.203", "Id": "390778", "Score"...
[ { "body": "<p>I'd suggest to accompany the code with comments. Not just for the purpose of review, but also for your own. After a few weeks it's hard to remember all the details, and what seems to be clear now will be hard to read later. Especially in this case when all arguments are of <code>String</code> or <...
{ "AcceptedAnswerId": "202924", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T11:15:58.270", "Id": "202737", "Score": "2", "Tags": [ "haskell" ], "Title": "String Calculator kata in Haskell" }
202737
<p>There are many files [ <strong>file1.php</strong>, <strong>file2.php</strong> ] in our project &amp; i wrote database connection code in many files instead of single file [ <strong>database.php</strong> ] , is there any problem with that ?</p> <p>if it is wrong than please help me what code i need to change in file1.php to connect to database.php</p> <p>Below 2 lines i used in <strong>file1.php</strong></p> <pre><code>$con=mysqli_connect('localhost', 'root', 'gfgf', 'g'); if ($result=mysqli_query($con,$sql)) </code></pre> <p>Instead of above 2 lines, is it correct to use below 2 lines ?</p> <pre><code>require_once("database.php"); $db_handle = new DBController(); </code></pre> <p><strong>file1.php</strong></p> <pre><code>&lt;?php require_once("database.php"); $db_handle = new DBController(); $con=mysqli_connect('localhost', 'root', 'gfgf', 'g'); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $todaydate=date('Y-m-d'); $sql="SELECT * FROM orders WHERE importdate &gt;= NOW() - INTERVAL 1 DAY"; if ($result=mysqli_query($con,$sql)) { $rowcount=mysqli_num_rows($result); printf("Uploaded - %d rows.\n",$rowcount); // Free result set mysqli_free_result($result); } mysqli_close($con); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:21:49.527", "Id": "390661", "Score": "0", "body": "please tell me why downvotes, so that i will correct it....." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:46:03.263", "Id": "390675", ...
[ { "body": "<blockquote>\n <p>database connection code in many files instead of single file, is there any problem with that?</p>\n</blockquote>\n\n<p>Nothing critical, but what if your database credentials would change? Are you going to edit all these files?</p>\n\n<blockquote>\n <p>is it correct to use below ...
{ "AcceptedAnswerId": "202740", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T11:17:07.520", "Id": "202738", "Score": "-3", "Tags": [ "php" ], "Title": "write database connection code in many files" }
202738
<p>I put together a log4net wrapper that more closely resembles F#-idiomatic logging functions. The basic idea is that there's a <code>Log</code> module that defines a set of 8 functions for each log level, as in the following example for the <code>Error</code> log level:</p> <p><code>Log.error</code> - Log a message (<code>string</code>) with the <code>Error</code> log level</p> <p><code>Log.errorf</code> - Log a formatted message (like <code>printf</code>) with the <code>Error</code> log level</p> <p><code>Log.errorx</code> - Log an <code>Exception</code> and a message with the <code>Error</code> log level</p> <p><code>Log.errorxf</code> - Log an <code>Exception</code> and a formatted message (like <code>printf</code>) with the <code>Error</code> log level</p> <p><code>Log.errorr</code> - Log a message (<code>string</code>) with the <code>Error</code> log level, then return the message</p> <p><code>Log.errorfr</code> - Format and log a message with the <code>Error</code> log level, then return the formatted message</p> <p><code>Log.errorxr</code> - Log an <code>Exception</code> and message with the <code>Error</code> log level, then return the message</p> <p><code>Log.errorxfr</code> - Log an <code>Exception</code> and a formatted message with the <code>Error</code> log level, then return the formatted message</p> <p>The biggest issue I had when implementing this wrapper was with getting the proper Stack Trace to show up in the log4net output. To match the behavior of using the standard log4net client in a C# application, I had to <code>inline</code> all the logging functions, as well as as reflectively mutate the <code>m_stackFrames</code> member of the log4net <code>LocationInfo</code> object. </p> <blockquote> <pre><code>let private writeLog level message maybeEx logDate (stackTrace: StackTrace) = let user = Threading.Thread.CurrentPrincipal.Identity let topFrame = stackTrace.GetFrame(0) let callingMethod = topFrame.GetMethod() let location = LocationInfo(callingMethod.DeclaringType.FullName, callingMethod.Name, callingMethod.DeclaringType.Name, String.Empty) typeof&lt;LocationInfo&gt; .GetField("m_stackFrames", BindingFlags.Instance ||| BindingFlags.NonPublic) .SetValue(location, stackTrace.GetFrames() |&gt; Array.map StackFrameItem) // ...etc (complete code below) </code></pre> </blockquote> <p>I really don't like this solution, as it is tightly coupled to the private member name in the log4net code, which could change with any new release. However, I could not see a better way to do it, since the <code>LocationInfo</code> object does not have a constructor overload that accepts the stack trace as a parameter, and the field is <code>private readonly</code> in the C# code. </p> <p>I'd be happy to hear any suggestions on how to improve this part of the code, as well as any general improvements for the logging functions or ways to make them more idiomatic. The complete wrapper code is as follows:</p> <pre><code>open log4net open log4net.Core open System open System.Diagnostics open System.Reflection [&lt;RequireQualifiedAccess&gt;] module Logger = let private log = lazy( log4net.Config.XmlConfigurator.Configure() |&gt; ignore LogManager.GetLogger("Logger")) let GetLogger () = log.Value.Logger [&lt;RequireQualifiedAccess&gt;] module Log = type LoggedException (message, ex: Exception) = inherit Exception(message, ex) let private logger = Logger.GetLogger() [&lt;Struct&gt;] type LogInfo = { Message: string Error: exn option Date: DateTime StackTrace: StackTrace } type LogMessage = | Debug of LogInfo | Info of LogInfo | Warning of LogInfo | Error of LogInfo | Fatal of LogInfo member this.Message = match this with | Debug info -&gt; info.Message | Info info -&gt; info.Message | Warning info -&gt; info.Message | Error info -&gt; info.Message | Fatal info -&gt; info.Message member this.Exception = match this with | Debug info -&gt; info.Error | Info info -&gt; info.Error | Warning info -&gt; info.Error | Error info -&gt; info.Error | Fatal info -&gt; info.Error let private writeLog level message maybeEx logDate (stackTrace: StackTrace) = let user = Threading.Thread.CurrentPrincipal.Identity let topFrame = stackTrace.GetFrame(0) let callingMethod = topFrame.GetMethod() let location = LocationInfo(callingMethod.DeclaringType.FullName, callingMethod.Name, callingMethod.DeclaringType.Name, String.Empty) // Correctly populate the read-only Location.StackFrames property by reflectively assigning the underlying m_stackFrames member. // In .NET, private readonly fields can still be mutated at run-time. This is not the ideal solution and may be implementaiton-specific, // but for now, this should work, and it's the only way to get the Stack Trace information into the log message when constructing // the LoggingEvent manually from F# (since F# does not fully support the CallerMemberName attribute that log4net uses in C#). typeof&lt;LocationInfo&gt; .GetField("m_stackFrames", BindingFlags.Instance ||| BindingFlags.NonPublic) .SetValue(location, stackTrace.GetFrames() |&gt; Array.map StackFrameItem) match maybeEx with | Some ex -&gt; let logData = new LoggingEventData(Domain = AppDomain.CurrentDomain.FriendlyName, Level = level, LocationInfo = location, Message = message, TimeStamp = logDate, LoggerName = "Logger", Identity = user.Name, UserName = user.Name, ExceptionString = ex.ToString()) let logEvent = new LoggingEvent(logData) logger.Log(logEvent) | None -&gt; let logData = new LoggingEventData(Domain = AppDomain.CurrentDomain.FriendlyName, Level = level, LocationInfo = location, Message = message, TimeStamp = logDate, LoggerName = "Logger", Identity = user.Name, UserName = user.Name) let logEvent = new LoggingEvent(logData) logger.Log(logEvent) let logAgent = MailboxProcessor.Start &lt;| fun inbox -&gt; let rec logLoop () = async { let! message = inbox.Receive() match message with | Debug info -&gt; writeLog Level.Debug info.Message info.Error info.Date info.StackTrace | Info info -&gt; writeLog Level.Info info.Message info.Error info.Date info.StackTrace | Warning info -&gt; writeLog Level.Warn info.Message info.Error info.Date info.StackTrace | Error info -&gt; writeLog Level.Error info.Message info.Error info.Date info.StackTrace | Fatal info -&gt; writeLog Level.Fatal info.Message info.Error info.Date info.StackTrace return! logLoop() } logLoop () let inline postAndReturn logMessage = logAgent.Post logMessage logMessage.Message let inline postAndRaise logMessage = logAgent.Post logMessage match logMessage.Exception with | Some ex -&gt; LoggedException(logMessage.Message, ex) | None -&gt; LoggedException(logMessage.Message, null) let inline log messageType = (messageType &gt;&gt; logAgent.Post) let inline logr messageType = (messageType &gt;&gt; postAndReturn) let inline logf messageType = Printf.kprintf (messageType &gt;&gt; logAgent.Post) let inline logfr messageType = Printf.kprintf (messageType &gt;&gt; postAndReturn) let inline logxr messageType = (messageType &gt;&gt; postAndRaise) let inline logxfr messageType = Printf.kprintf (messageType &gt;&gt; postAndRaise) let inline debug message = let stackTrace = StackTrace() Debug {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; logAgent.Post let inline debugf format args = let stackTrace = StackTrace() logf (fun message -&gt; Debug {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline debugx ex = let stackTrace = StackTrace() log &lt;| fun message -&gt; Debug {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline debugxf ex format args = let stackTrace = StackTrace() logf (fun message -&gt; Debug {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline debugr message = let stackTrace = StackTrace() Debug {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; postAndReturn let inline debugfr format args = let stackTrace = StackTrace() logfr (fun message -&gt; Debug {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline debugxr ex = let stackTrace = StackTrace() logxr &lt;| fun message -&gt; Debug {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline debugxfr ex format args = let stackTrace = StackTrace() logxfr (fun message -&gt; Debug {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline info message = let stackTrace = StackTrace() Info {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; logAgent.Post let inline infof format args = let stackTrace = StackTrace() logf (fun message -&gt; Info {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline infox ex = let stackTrace = StackTrace() log &lt;| fun message -&gt; Info {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline infoxf ex format args = let stackTrace = StackTrace() logf (fun message -&gt; Info {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline infor message = let stackTrace = StackTrace() Info {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; postAndReturn let inline infofr format args = let stackTrace = StackTrace() logfr (fun message -&gt; Info {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline infoxr ex = let stackTrace = StackTrace() logxr &lt;| fun message -&gt; Info {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline infoxfr ex format args = let stackTrace = StackTrace() logxfr (fun message -&gt; Info {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline warn message = let stackTrace = StackTrace() Warning {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; logAgent.Post let inline warnf format args = let stackTrace = StackTrace() logf (fun message -&gt; Warning {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline warnx ex = let stackTrace = StackTrace() log &lt;| fun message -&gt; Warning {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline warnxf ex format args = let stackTrace = StackTrace() logf (fun message -&gt; Warning {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline warnr message = let stackTrace = StackTrace() Warning {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; postAndReturn let inline warnfr format args = let stackTrace = StackTrace() logfr (fun message -&gt; Warning {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline warnxr ex = let stackTrace = StackTrace() logxr &lt;| fun message -&gt; Warning {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline warnxfr ex format args = let stackTrace = StackTrace() logxfr (fun message -&gt; Warning {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline error message = let stackTrace = StackTrace() Error {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; logAgent.Post let inline errorf format args = let stackTrace = StackTrace() logf (fun message -&gt; Error {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline errorx ex = let stackTrace = StackTrace() log &lt;| fun message -&gt; Error {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline errorxf ex format args = let stackTrace = StackTrace() logf (fun message -&gt; Error {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline errorr message = let stackTrace = StackTrace() Error {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; postAndReturn let inline errorfr format args = let stackTrace = StackTrace() logfr (fun message -&gt; Error {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline errorxr ex = let stackTrace = StackTrace() logxr &lt;| fun message -&gt; Error {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline errorxfr ex format args = let stackTrace = StackTrace() logxfr (fun message -&gt; Error {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline fatal message = let stackTrace = StackTrace() Fatal {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; logAgent.Post let inline fatalf format args = let stackTrace = StackTrace() logf (fun message -&gt; Fatal {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline fatalx ex = let stackTrace = StackTrace() log &lt;| fun message -&gt; Fatal {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline fatalxf ex format args = let stackTrace = StackTrace() logf (fun message -&gt; Fatal {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline fatalr message = let stackTrace = StackTrace() Fatal {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace} |&gt; postAndReturn let inline fatalfr format args = let stackTrace = StackTrace() logfr (fun message -&gt; Fatal {Message = message; Error = None; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args let inline fatalxr ex = let stackTrace = StackTrace() logxr &lt;| fun message -&gt; Fatal {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace} let inline fatalxfr ex format args = let stackTrace = StackTrace() logxfr (fun message -&gt; Fatal {Message = message; Error = Some ex; Date = DateTime.UtcNow; StackTrace = stackTrace}) format args </code></pre>
[]
[ { "body": "<p>Your design doesn't make sense, to me.</p>\n\n<blockquote>\n<pre><code>[&lt;Struct&gt;]\ntype LogInfo =\n {\n Message: string\n Error: exn option\n Date: DateTime\n StackTrace: StackTrace\n }\n\ntype LogMessage = \n| Debug of LogInfo\n| Info of LogInfo\n| Warning ...
{ "AcceptedAnswerId": "202756", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:39:57.303", "Id": "202745", "Score": "5", "Tags": [ "functional-programming", "f#", "logging", "log4net" ], "Title": "F# Idiomatic Log4Net Wrapper" }
202745
<p>I wrote this php class to generate one time random and unique coupon codes.</p> <p>The Class generates coupon codes, storing it in a json file.</p> <p>My question is regarding the write and get methods of this class.</p> <p>In the write method, I use file_put_contents with LOCK_EX flag. I assume if the function fails to get a lock, it returns false.</p> <p>When the Get method is called, </p> <ul> <li>it pop a coupon code from the data array property</li> <li>call the write method to update the file</li> <li>if write returns true, it returns the coupon to the user and updates the database</li> <li>if write returns false, it sleeps 10ms and makes a recursive call to itself.</li> </ul> <p>Is this a correct way to prevent concurrent file access issues? For example, 2 users getting the same coupon code.</p> <p>Any other suggestions or improvements would be much appreciated.</p> <pre><code>&lt;?php namespace Cart; /** * Generates random and unique coupon codes */ class CouponGenerator { private $query; private $data; private $file; private $prefix; private $noOfCodesToGenerate = 10000; public function __construct(\QueryBuilder $query, $prefix = '') { switch ($prefix) { case 'FB': $this-&gt;file = 'fb.json'; break; default: $this-&gt;file = 'coupons.json'; break; } $this-&gt;query = $query; // if file doesn't exist or empty if (! file_exists($this-&gt;file) || empty($this-&gt;data = $this-&gt;read())) { // generate code and write to file $this-&gt;generateCodes(); $this-&gt;write(); } } // returns the coupon code public function get() { // Pop the last coupon $code = array_pop($this-&gt;data); // try updating the file if ($this-&gt;write()) { // if successful update the database and return code $this-&gt;updateTable($code); $data = []; return $code; } // else sleep 10ms and attempt again usleep(100000); $this-&gt;get(); } private function updateTable($code) { // update database and return result } private function read() { return json_decode(file_get_contents($this-&gt;file)); } private function write() { return false !== file_put_contents($this-&gt;file, json_encode($this-&gt;data), LOCK_EX); } private function generateCodes() { $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; $charsLen = strlen($chars) - 1; $code = $this-&gt;prefix; $maxLen = 8 - strlen($this-&gt;prefix); $result = []; while (count($result) &lt; $this-&gt;noOfCodesToGenerate) { for ($i=0; $i &lt; $maxLen; $i++) { $code .= $chars[mt_rand(0, $charsLen)]; } if (! in_array($code, $result)) { $result[] = $code; } $code = $this-&gt;prefix; } $this-&gt;data = $result; } } </code></pre> <p><strong>EDIT</strong> I took @freezePhoenix advice and rewrote the below function. Its not as random and unique as a UUID but i ran a test for 100000 codes and got just 3 collisions.</p> <p>To eliminate duplicate codes, i implemented a try catch block to catch the PDOException and regenerate the code. </p> <pre><code>private function generateCode() { $randomCode = $this-&gt;prefix . bin2hex(openssl_random_pseudo_bytes(16)); $ambigousChars = [0, 'o', 1, 'i', 'l']; $cleanString = str_replace($ambigousChars, '', $randomCode); return strtoupper(substr($cleanString, 0, 8)); } public function get() { try { $code = $this-&gt;generateCode(); $this-&gt;updateTable($code); return $code; } catch (PDOException $e) { $this-&gt;get(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:58:21.723", "Id": "390688", "Score": "1", "body": "Why don't you use UUID? Or the general barcode?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T13:17:25.903", "Id": "390695", "Score": "1...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T12:52:04.763", "Id": "202746", "Score": "1", "Tags": [ "php" ], "Title": "PHP CouponGenerator class - preventing concurrent file access" }
202746
<p>I'm working on a python module to randomly choose a wallpaper for my desktop background among thousands of pictures in my photo library.</p> <p>I though I'd make a general function:</p> <pre><code>get_random_file(ext, top) </code></pre> <blockquote> <p>Return the name of a random file in a directory tree with top as root.</p> </blockquote> <p>Since I'm dealing with a very large directory tree, listing all possible files would be very time consuming (edit: see comments on C. Harley answer). So I went for heuristic method, making sure all files are covered and adding an upper bound in case there are no files with given extension. There are occasionally false negatives, which is not a too big deal, but most importantly, it runs nearly instantly.</p> <p>Algorithm is simple:</p> <ol> <li>Get a list of directories, including <code>.</code></li> <li>Pick a random directory from that list.</li> <li>If the picked directory is <code>.</code> (either randomly, or only available option), then retrieve a list of files in that directory.</li> <li>If the list of files is empty, go back to 1.</li> <li>Return a random file from that list.</li> </ol> <p>Note that this algorithm can go many levels deep into sub-directories.</p> <p>So far I'm happy with performance and returned values. It is able to quickly pick up a file in a very large tree.</p> <p>However, I'm after general comments in terms of performance and also code style.</p> <p>What I'm not particularly proud of in my code is the use of <code>next(os.walk(top))[1]</code> to get the list of sub-directories in the current directory.</p> <p>There are also false negatives, when asking for a file extension with not many occurrences in a tree with many directories. However, I don't want to increase the limit too much to avoid waiting when really there are not such files in the tree.</p> <p>The code:</p> <pre><code># -*- coding: utf-8 -*- """ Created on Wed Aug 29 14:05:27 2018 @author: raf """ import os import sys import glob import random def get_random_files(ext, top): '''Return the name of a random file within a top path. Works recursivelly in subdirectories. Note that a full list of files could be got with glob(top + '/**/*.' + ext, recursive=True) However that would be extremely slow for large directories. ''' _top = top ct, limit = 0, 50000 while True: if ct &gt; limit: return 'No file found after %d iterations.' % limit ct += 1 try: dirs = next(os.walk(top))[1] except StopIteration: # access denied and other exceptions top = _top continue i = random.randint(0, len(dirs)) if i == 0: # use . files = glob.glob(top + '/*.' + ext) if not files: top = _top continue i = random.randint(0, len(files)-1) return files[i] top += '/' + dirs[i-1] if __name__ == '__main__': if len(sys.argv) &gt; 1: print(get_random_files(sys.argv[1], os.getcwd())) else: print(get_random_files('*', os.getcwd())) </code></pre>
[]
[ { "body": "<p>There are many problems with your approach.</p>\n\n<ul>\n<li><p>It can be extremely unfair depending on your tree structure. do a depth first complete walk and list probabilities. root is probability <code>1</code>, in each level divide by number of dirs (including <code>.</code>), finally divide ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T13:43:26.200", "Id": "202749", "Score": "7", "Tags": [ "python", "random", "file-system" ], "Title": "Pick a random file from a directory tree" }
202749
<p>I am seeking a review of my <a href="https://www.codility.com/" rel="nofollow noreferrer">codility</a> solution.</p> <p>Whilst the problem is fairly simple, my approach differs to many solutions already on this site. My submission passes 100% of the automated correctness tests. </p> <p>I am looking for feedback regarding the design of my solution, and any comments in relation to how this submission might be graded by a human.</p> <p><strong>Problem description:</strong></p> <blockquote> <p>A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.</p> <p>For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.</p> <p>Write a function:</p> <p>def solution(N)</p> <p>that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.</p> <p>For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.</p> <p>Write an efficient algorithm for the following assumptions:</p> <p>N is an integer within the range [1..2,147,483,647].</p> </blockquote> <p><strong>Solution:</strong></p> <pre><code>def solution(N): bit_array = [int(bit) for bit in '{0:08b}'.format(N)] indices = [bit for bit, x in enumerate(bit_array) if x == 1] if len(indices) &lt; 2: return 0 lengths = [end - beg for beg, end in zip(indices, indices[1:])] return max(lengths) - 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T17:55:38.570", "Id": "525504", "Score": "0", "body": "This question has also been [asked at Stack Overflow](https://stackoverflow.com/q/48951591)." } ]
[ { "body": "<ol>\n<li>Converting from string to int in your first comprehension isn't needed as you're comparing to a literal anyway.</li>\n<li>You can merge the first two comprehensions.</li>\n<li>you don't need to return early, as you can default <code>max</code> to 1.</li>\n<li>You shouldn't need the <code>8<...
{ "AcceptedAnswerId": "202755", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T14:09:02.853", "Id": "202750", "Score": "4", "Tags": [ "python", "performance", "algorithm", "programming-challenge" ], "Title": "Codility binary gap solution using indices" }
202750
<p>I have the following function that checks a data record to see if it has met certain criteria specified separately in configuration settings. The configurations are set up as a list of dictionaries with certain trigger keywords that are used by the condition check function ('in','not in', etc).</p> <p>The condition checker has a lot of duplicated code, but it's just different enough that a better setup is not obvious to me. I would appreciate any feedback.</p> <p>Here is a minimal working example to illustrate:</p> <pre><code>def check_if_condition_was_met( row, condition ): condition_met = True for key, val in condition.iteritems(): if key == 'in': for condition_key, condition_val in val.iteritems(): if row[condition_key] in condition_val: # IN continue else: condition_met = False break elif key == 'not in': for condition_key, condition_val in val.iteritems(): if row[condition_key] not in condition_val: # NOT IN continue else: condition_met = False break elif key == 'max': for condition_key, condition_val in val.iteritems(): if not row[condition_key]: condition_met = False break if int(row[condition_key]) &lt;= int(condition_val): # MAX (&lt;=) continue else: condition_met = False break elif key == 'min': for condition_key, condition_val in val.iteritems(): if int(row[condition_key]) &gt;= int(condition_val): # MIN (&gt;=) continue else: condition_met = False break return condition_met if __name__ == '__main__': # data test_data = [ {'Flag1':'Y', 'Flag2':'Canada','Number':35} ,{'Flag1':'Y', 'Flag2':'United States','Number':35} ,{'Flag1':'N', 'Flag2':'United States','Number':35} ,{'Flag1':'N', 'Flag2':'England','Number':35} ,{'Flag1':'N', 'Flag2':'Canada','Number':35} ,{'Flag1':'N', 'Flag2':'Canada','Number':5} ] # configuration test_conditions = [ { 'in':{'Flag1':['N'], 'Flag2':['United States']} } ,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'max':{'Number':7} } ,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'min':{'Number':7} } ,{ 'not in':{'Flag1':['Y']}, 'min':{'Number':7} } ] for condition_id, condition in enumerate(test_conditions): print print 'now testing for condition %i' % condition_id for data_id, data in enumerate(test_data): print '%s | %s' % ( data_id, check_if_condition_was_met(data,condition) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T15:35:17.117", "Id": "390728", "Score": "0", "body": "It's still very vague - lots of my functions test for different conditions of their input data. Can you make it any more specific? I can see that it's difficult, because the fu...
[ { "body": "<ol>\n<li>Use <code>return</code> to also return early. It's easier to understand and read then assigning to <code>condition_met</code> and <code>break</code>.</li>\n<li>I'm ignoring the extra code that <code>key = 'max'</code> has.</li>\n<li>Your code would be smaller and easier to read if you inver...
{ "AcceptedAnswerId": "202774", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T14:32:57.707", "Id": "202753", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Function to test for different conditions in input data" }
202753
<p>I have an Angular 6 app with the following requirements:</p> <ol> <li>Get data from a web service.</li> <li>Load the data when the page is displayed.</li> <li>Reload the data when the user requests a reload by through some UI, like a button.</li> <li>Show a spinner while loading data in the header of the page. That is, not in the same place where the data is going to be displayed. Which means I cannot use <code>ngIf</code> with <code>; else #loading</code>.</li> </ol> <p>I have the following (simplified) code that is actually working. I also have <a href="https://stackblitz.com/edit/angular-async-reload-with-spinner" rel="noreferrer">a live code sample</a>. However I wonder if this is the canonical way to do it. Especially as I a am new to RxJS. Other improvements or suggestions are also welcome.</p> <p>Some things I am not sure of:</p> <ul> <li>Using the <code>refresh</code> Subject to do load/reload.</li> <li>Setting the <code>loading</code> member within RxJS operators (side effects).</li> </ul> <p>The component:</p> <pre><code>@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { refresh: Subject&lt;string&gt;; // For load/reload items$: Observable&lt;any&gt;; // Some items loading: boolean = true; // Turn spinner on and off constructor (private http: HttpClient) { } ngOnInit() { this.refresh = new Subject(); this.items$ = this.refresh.asObservable() .pipe( startWith('onInit'), // Emit value to force load on page load; actual value does not matter flatMap(_ =&gt; this.http.get&lt;any&gt;('https://swapi.co/api/people/')), // Get some items delay(1000), // Delay to let our spinner shine map(data =&gt; data.results), // Map data tap(_ =&gt; this.loading = false) // Turn off the spinner ); } onRefresh() { this.loading = true; // Turn on the spinner. this.refresh.next('onRefresh'); // Emit value to force reload; actual value does not matter } } </code></pre> <p>The template:</p> <pre><code>&lt;div class="header"&gt; &lt;h1&gt;Items &lt;a href="#"&gt;&lt;i class="fas fa-sync" (click)="onRefresh()"&gt;&lt;/i&gt;&lt;/a&gt; &lt;i class="fas fa-spinner fa-spin" *ngIf="loading"&gt;&lt;/i&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div class="content"&gt; &lt;div *ngIf="items$ | async as items"&gt; &lt;ul&gt; &lt;li *ngFor="let item of items"&gt; {{item.name}} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T13:34:50.343", "Id": "452688", "Score": "0", "body": "In this context, it is better to use `switchMap` than `flatMap`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T13:35:57.113", "Id": "452689"...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T14:35:46.160", "Id": "202754", "Score": "5", "Tags": [ "typescript", "angular-2+", "rxjs" ], "Title": "Angular async pipe with loading spinner and manual refresh" }
202754
<p>Below is a sample implementation for getting the expired credit cards in the credit card list.I wrote a property and initialized it in the constructor. Need an opinion on if this is a proper way to implement it.</p> <pre><code> public class User { private readonly List&lt;CreditCard&gt; creditCards; public int CountOfCreditCards { get { return counter; } } private static int counter; private User() { creditCards = new List&lt;CreditCard&gt;(); counter = GetCountOfExpiredCreditCards(); } public int GetCountOfExpiredCreditCards() { return creditCards.Count(x =&gt; x.ExpirationMonth &lt;= DateTime.Now.Month); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T16:00:03.453", "Id": "390736", "Score": "1", "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 y...
[ { "body": "<blockquote>\n <p>If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.</p>\n</blockquote>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-c...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T15:25:24.217", "Id": "202760", "Score": "0", "Tags": [ "c#", "object-oriented" ], "Title": "Get count of credit cards that are expired" }
202760
<p>This code defines a <code>MessageBus</code> used to handle messages from many producers to a single consumer. The bus allows multiple publishers to send messages asynchronously to a single message handler. This is not a <code>Pub-Sub</code> model, instead, it's a many publisher and single consumer with the ability to send a result back to the publisher. The publisher can <code>await</code> for the message to be sent using the <code>PostAsync</code> methods. Or <code>await</code> for the completion or optional result of the handler by using the <code>SendAsync</code> methods. All messages and handlers are treated asynchronously regardless of their implementation, however, a synchronous implementation will not block the publisher. This setup centralizes who actually handles messages instead of keeping track of many subscriptions. </p> <p>Underneath the hood this is using TPL-Dataflow to flow messages and SimpleInjector for IoC and wiring up handlers to messages.</p> <p>First, the interface definition of the example message bus:</p> <pre><code>public interface IMessageBus { /// &lt;summary&gt; /// Posts a message to the bus and returns a Task representing the acceptance of the message. /// &lt;/summary&gt; /// &lt;typeparam name="TMessage"&gt;&lt;/typeparam&gt; /// &lt;param name="message"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; Task PostAsync&lt;TMessage&gt;(TMessage message) where TMessage : IMessage; /// &lt;summary&gt; /// Posts a message to the bus and returns a Task representing the acceptance of the message with an error handling delegate. /// &lt;/summary&gt; /// &lt;typeparam name="TMessage"&gt;&lt;/typeparam&gt; /// &lt;param name="message"&gt;&lt;/param&gt; /// &lt;param name="OnError"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; Task PostAsync&lt;TMessage&gt;(TMessage message, Action&lt;Exception&gt; OnError) where TMessage : IMessage; /// &lt;summary&gt; /// Sends a message to the bus and returns a Task representing completion of handling the message. /// &lt;/summary&gt; /// &lt;typeparam name="TMessage"&gt;&lt;/typeparam&gt; /// &lt;param name="message"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; Task SendAsync&lt;TMessage&gt;(TMessage message) where TMessage : IMessage; /// &lt;summary&gt; /// Sends a message to the bus and returns a Task representing completion of handling the message and yields the result of the handling. /// &lt;/summary&gt; /// &lt;typeparam name="TMessage"&gt;&lt;/typeparam&gt; /// &lt;typeparam name="TReply"&gt;&lt;/typeparam&gt; /// &lt;param name="message"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; Task&lt;TReply&gt; SendAsync&lt;TMessage, TReply&gt;(TMessage message) where TMessage : IMessage&lt;TReply&gt;; } </code></pre> <p>And the implementation:</p> <pre><code>public class MessageBus : IMessageBus { private IContainer Container { get; } public MessageBus(IContainer container) =&gt; Container = container ?? throw new ArgumentNullException(nameof(container)); public Task PostAsync&lt;TMessage&gt;(TMessage message) where TMessage : IMessage =&gt; PostAsync(message, null); public Task PostAsync&lt;TMessage&gt;(TMessage message, Action&lt;Exception&gt; OnError) where TMessage : IMessage { var block = GetHandlerBlock&lt;TMessage&gt;(async msg =&gt; { try { var handler = Container.GetInstance&lt;IMessageHandler&lt;TMessage&gt;&gt;(); await handler.HandleAsync(msg); } catch (Exception ex) { if (OnError == null) return; OnError(ex); } }); return block.SendAsync(message); } public Task SendAsync&lt;TMessage&gt;(TMessage message) where TMessage : IMessage { var tcs = new TaskCompletionSource&lt;bool&gt;(); var block = GetHandlerBlock&lt;TMessage&gt;(async msg =&gt; { try { var handler = Container.GetInstance&lt;IMessageHandler&lt;TMessage&gt;&gt;(); await handler.HandleAsync(msg); tcs.TrySetResult(true); } catch (Exception ex) { tcs.TrySetException(ex); } }); block.Post(message); return tcs.Task; } public Task&lt;TReply&gt; SendAsync&lt;TMessage, TReply&gt;(TMessage message) where TMessage : IMessage&lt;TReply&gt; { var tcs = new TaskCompletionSource&lt;TReply&gt;(); var block = GetHandlerBlock&lt;TMessage&gt;(async msg =&gt; { try { var handler = Container.GetInstance&lt;IMessageHandler&lt;TMessage, TReply&gt;&gt;(); var reply = await handler.HandleAsync(msg); tcs.TrySetResult(reply); } catch (Exception ex) { tcs.TrySetException(ex); } }); block.Post(message); return tcs.Task; } private ITargetBlock&lt;TMessage&gt; GetHandlerBlock&lt;TMessage&gt;(Func&lt;TMessage, Task&gt; action) =&gt; new ActionBlock&lt;TMessage&gt;(action); } </code></pre> <p>The publisher has a few options: </p> <ol> <li>Post a message, awaiting only for the message to be accepted.</li> <li>Post a message with an error handling delegate, awaiting only for the message to be accepted.</li> <li>Send a message awaiting completion of processing.</li> <li>Send a message awaiting a reply from the handler.</li> </ol> <p>And the supporting interfaces:</p> <pre><code>public interface IMessage { } public interface IMessage&lt;TReply&gt; : IMessage { } public interface IMessageHandler&lt;TMessage&gt; where TMessage : IMessage { Task HandleAsync(TMessage message); } public interface IMessageHandler&lt;TMessage, TReply&gt; where TMessage : IMessage&lt;TReply&gt; { Task&lt;TReply&gt; HandleAsync(TMessage message); } public interface IContainer { TInstance GetInstance&lt;TInstance&gt;() where TInstance : class; } </code></pre>
[]
[ { "body": "<p>A few comments:</p>\n\n<p><code>var handler = Container.GetInstance&lt;IMessageHandler&lt;TMessage, TReply&gt;&gt;();</code></p>\n\n<p>You're looking up the <code>IMessageHandler</code> inside the handler block, which means you're looking it up for every message. I'm not that familiar with Simple...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T16:53:37.000", "Id": "202769", "Score": "1", "Tags": [ "c#", "task-parallel-library", "tpl-dataflow", "simple-injector" ], "Title": "Dispatch multiple publishers to single handler with result" }
202769
<p>I want to visualize all unlabeled trees with \$n\$ or fewer nodes, not just <a href="https://oeis.org/A000055" rel="nofollow noreferrer">count them</a>.</p> <p>First idea/attempt: Take a list of all \$n-1\$ node trees, then append a new <a href="http://mathworld.wolfram.com/TreeLeaf.html" rel="nofollow noreferrer">leaf</a> to every tree in every way to get a new list of \$n\$ node trees. Clearly, this new list will contain <strong>a lot</strong> of isomorphic duplicates. To fix this, we start adding the \$n\$ trees to a new list, and doing so only if they are not isomorphic to any of the trees in the new list. Since <a href="https://en.wikipedia.org/wiki/Graph_isomorphism_problem" rel="nofollow noreferrer">graph isomorphism problem</a> is not known to be solvable in polynomial time, this makes the entire process even more horrible performance wise, because this process will do <strong>a lot</strong> of such checks.</p> <p>My question is if this can be done more efficiently, or in a better way?</p> <p>The python code implementing this idea/attempt using networkX and pyplot:</p> <pre><code>""" trees of order N or less will be generated """ N = 9 import networkx as nx """ return copy of graph with newNode node appended to toNode node """ def leaf_copy(graph, newNode, toNode): g = nx.Graph.copy(graph) g.add_node(newNode) g.add_edge(newNode,toNode) return g from networkx.algorithms import isomorphism """ get all n+1 node cases out of all n node cases in prevTreeList """ def genNextTreeList(prevTreeList): """ one node case """ if prevTreeList == None or prevTreeList == []: g = nx.Graph() g.add_node(1) return [g] """ new loads of n+1 graphs by all possible list appendations """ """ this will include loads of isomprhic duplicates... """ nextTreeList = [] for g in prevTreeList: v = len(g.nodes())+1 for node in g.nodes(): nextTreeList.append(leaf_copy(g,v,node)) """ remove isomorphic duplicates """ """ it will check every graph to be added with all added graphs for isomorphism... """ nextTreeListClean = [] for g in nextTreeList: isomorphic = False for clean_g in nextTreeListClean: i = isomorphism.GraphMatcher(g,clean_g) if i.is_isomorphic(): isomorphic = True break if not isomorphic: nextTreeListClean.append(g) return nextTreeListClean import matplotlib.pyplot as plt if __name__ == "__main__": print(0, "\t", 1) G = [] figure = 0 for n in range(N): G = genNextTreeList(G) """ print the number of examples to check if the code is working properly """ print(n+1, "\t", len(G)) """ draw and save the plots """ for g in G: figure += 1 fig = plt.figure(figure) plt.title(str(n+1)+'.'+str(G.index(g)+1)) nx.draw(g, with_labels=False) plt.figure(figure).savefig('plot'+str(figure)+'.png',bbox_inches='tight',dpi=100) plt.close(fig) </code></pre> <p><a href="https://i.stack.imgur.com/ltwUq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ltwUq.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T18:42:08.833", "Id": "390767", "Score": "1", "body": "Tree isomorphism is polinomial. Maybe [this](https://math.stackexchange.com/questions/407562/gallery-of-unlabelled-trees-with-n-vertices) helps or [this](https://blogs.msdn.micro...
[ { "body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>In Python, a docstring goes <em>after</em> the function or class introduction. So instead of:</p>\n\n<pre><code>\"\"\" return copy of graph with newNode node appended to toNode node \"\"\"\ndef leaf_copy(graph, newNode, toNode):\n</code></pre>\n\n<p>write something ...
{ "AcceptedAnswerId": "204631", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T18:04:07.310", "Id": "202773", "Score": "5", "Tags": [ "python", "performance", "tree", "mathematics", "data-visualization" ], "Title": "Generating all unlabeled trees with up to n nodes" }
202773
<p>I cannot use add ins here so I set out to create an excel application that could get the job done. I suppose that I could easily transport this into outlook?</p> <p>Basically I want to click one of the icons and have the img inside that icons insert into the email that I am working on. </p> <p>Question re unit testing: Here it seems like I have to unit test by hand in a sense. I suppose I could write code that simulates the object application environments, ie opens outlook application and then creates multiple popped out emails, no emails, a mix of popped out and inline etc? Then I pass this to each individual function and see that it works?</p> <p><strong>This Workbook:</strong></p> <pre><code>Private Sub Workbook_Open() Me.Windows(1).WindowState = xlMinimized EmjoiControlPanel.Show vbModal End Sub </code></pre> <p><strong>EmojiControlPanel:</strong></p> <pre><code>Option Explicit Sub Image1_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image1 End Sub Sub Image2_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image2 End Sub Sub Image3_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image3 End Sub Sub Image4_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image4 End Sub Sub Image5_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image5 End Sub Sub Image6_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image6 End Sub Sub Image7_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image7 End Sub Sub Image8_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image8 End Sub Sub Image9_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image9 End Sub Sub Image10_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image10 End Sub Sub Image11_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image11 End Sub Sub Image12_Click() TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image12 End Sub </code></pre> <p><strong>TransferIMG:</strong></p> <pre><code>Option Explicit Public Sub EmojiEmailTransfer(ByRef picControl As Image) On Error GoTo Delete Dim olApp As Outlook.Application Dim pictureFilePath As String Set olApp = GetObject(, "Outlook.Application") pictureFilePath = "Z:\tempPic" SavePicture picControl.picture, pictureFilePath If TypeName(olApp.ActiveWindow) = "Inspector" Then PoppedOutEmailLoadPicture olApp, pictureFilePath ElseIf TypeName(olApp.ActiveWindow) = "Explorer" Then NotPoppedOutEmailLoadPicture olApp, pictureFilePath End If Delete: DeleteFile pictureFilePath End Sub Private Sub PoppedOutEmailLoadPicture(ByRef olApp As Outlook.Application, ByRef pictureFilePath As String) On Error GoTo CouldNotLoad Dim objDoc As Word.Document Dim objSelect As Word.Selection Set objDoc = olApp.ActiveInspector.WordEditor Set objSelect = objDoc.Windows(1).Selection objSelect.InlineShapes.AddPicture pictureFilePath Exit Sub CouldNotLoad: End Sub Private Sub NotPoppedOutEmailLoadPicture(ByRef olApp As Outlook.Application, ByRef pictureFilePath As String) On Error GoTo CouldNotLoad Dim objDoc As Word.Document Dim objSelect As Word.Selection Set objDoc = olApp.ActiveExplorer.ActiveInlineResponseWordEditor Set objSelect = objDoc.Windows(1).Selection objSelect.InlineShapes.AddPicture pictureFilePath Exit Sub CouldNotLoad: End Sub Private Sub DeleteFile(ByRef pictureFilePath As String) Dim fso As Object Set fso = CreateObject("scripting.filesystemobject") If fso.fileexists(pictureFilePath) Then fso.DeleteFile ("" &amp; pictureFilePath &amp; "") End Sub </code></pre> <p><strong>RunApp (Assigned to a button in worksheet):</strong></p> <pre><code>Sub RunApp() ActiveWorkbook.Windows(1).WindowState = xlMinimized EmjoiControlPanel.Show vbModal End Sub </code></pre> <p><a href="https://i.stack.imgur.com/mxjmK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxjmK.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T00:01:51.243", "Id": "390787", "Score": "0", "body": "Without having read your question yet - [rubberduck](https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing) can help with unit testing VBA." }, { "ContentLicense...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T19:43:14.517", "Id": "202778", "Score": "1", "Tags": [ "vba", "unit-testing", "excel", "error-handling", "outlook" ], "Title": "Insert Emojis Into Outlook Email With VBA Application (For those of us who cant use add-ins)" }
202778
<p>I took a code test for acme transport company and was rejected. That's ok. I'm still learning how to code. I didn't get much feedback so that's a bit frustrating. Can anyone here provide tips on how to optimize this python code? I thought that I had done a pretty good job with it, had the correct answers, etc. But apparently there are some fatal flaws, at least according to acme transport co!</p> <p>Here's the challenge:</p> <p>Parse a <a href="https://gist.githubusercontent.com/pepebutter/f840e635d0d063ce7e1b744023b09ce8/raw/50e388ae1164598299b9700c1eff22be049ee19f/events.txt" rel="nofollow noreferrer">text file</a> so that we know the following:</p> <ul> <li>how many cars were dropped in total?</li> <li>which car had the longest single trip? How long was the trip?</li> <li>what car had the longest cumulative distance? How long was that.</li> </ul> <p>The text file is formatted like this:</p> <ul> <li><p>timestamp, Integer, The time in seconds since the start of the simulation</p></li> <li><p>id, String, The id of the associated vehicle, e.g. JK5T</p></li> <li><p>event_type, String The type of the event is one of START_RIDE, END_RIDE, DROP</p></li> <li><p>x, Double, The x coordinate of the location of where the event happened in the simulation</p></li> <li><p>y, Double, The y coordinate of the location of where the event happened in the simulation</p></li> <li><p>user_id, Integer, The id of the associated user or NULL if the event does not have an associated user</p></li> </ul> <p>The first few lines of the file look like this:</p> <pre><code>302,OPN1,DROP,33.28280226855614,-87.88162047789511,NULL 305,OPN1,START_RIDE,33.28280226855614,-87.88162047789511,4204 419,G2I0,DROP,-28.367411419413685,23.567421582328606,NULL 426,OPN1,END_RIDE,7.563016232237587,91.97004351346015,4204 428,LQBF,DROP,-50.50579634246066,-54.53980771216895,NULL 441,5HQH,DROP,-70.05156581770649,36.8358644984674,NULL </code></pre> <p>For my code I import a library called shapely that helps determine distances:</p> <pre><code>import csv from shapely.geometry import Point from collections import defaultdict def main(): myDict = defaultdict(dict) aDict = {} totalDrops = 0 maxCar = None with open('events.txt') as f: reader = csv.reader(f) for row in reader: if row[2] == 'DROP': totalDrops += 1 myDict[row[1]]['drop'] = Point(float(row[3]), float(row[4])) if row[2] == 'START_RIDE': myDict[row[1]]['start_ride'] = Point(float(row[3]), float(row[4])) if row[2] == 'END_RIDE': singleTripDistance = myDict[row[1]]['drop'].distance(Point(float(row[3]), float(row[4]))) distanceTraveled = myDict[row[1]]['start_ride'].distance(Point(float(row[3]), float(row[4]))) aDict[row[1]] = singleTripDistance if not maxCar: maxCar = row[1] if 'allDistances' not in myDict[row[1]]: myDict[row[1]]['allDistances'] = distanceTraveled else: myDict[row[1]]['allDistances'] += distanceTraveled if myDict[row[1]]['allDistances'] &gt; myDict[maxCar]['allDistances']: maxCar = row[1] maxSingleTrip = max(zip(aDict.values(), aDict.keys())) print('There are ' + '' + str(totalDrops) + ' ' + 'total Drops.' + '\n' + 'The Car that ends up furthest away from its drop is:' + ' ' + str(maxSingleTrip[1]) + ' ' + 'and the distance is:' + ' ' + str(maxSingleTrip[0]) + '\n' + 'The Car with the highest total distance traveled is:' + ' ' + maxCar + ', ' + 'and the total distance is:' + ' ' + str(myDict[maxCar]['allDistances'])) main() </code></pre>
[]
[ { "body": "<p><strong>Making the code easier to read with variables</strong></p>\n\n<p>Having all the accesses to <code>row[something]</code> everywhere makes the code hard to read and to update.\nA good idea could be to introduce variables with meaningful names. You'd get for instance <code>x = row[3]</code>.<...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T21:29:02.393", "Id": "202780", "Score": "4", "Tags": [ "python", "beginner", "interview-questions", "csv" ], "Title": "Calculating travel statistics based on CSV data" }
202780
<blockquote> <p>Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.</p> <p>For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.</p> <p>Evaluate the sum of all the amicable numbers under 10000.</p> </blockquote> <p>My solution to the 21 problem on project Euler is very slow (with pure brute force it took 30 mins to find the solution). Any ways that I can improve my code or should I scrap it and think about something else ?</p> <p>Here's my code :</p> <pre><code>import time, math start = time.time() amicable_nums = set() def sum_div(n): divisors = [] for x in range(1, int(math.sqrt(n) + 1)): if n % x == 0: divisors.append(x) if x * x != n and x != 1: divisors.append(int(n / x)) return sum(divisors) for i in range(1, 10000): for j in range(1, 10000): if sum_div(i) == j and sum_div(j) == i and i != j: amicable_nums.update([i, j]) print(sum(amicable_nums)) print("It took " + str(time.time() - start) + " seconds") </code></pre>
[]
[ { "body": "<p>In your <code>sum_div</code> method, 1 is always a divisor, and n/1 is never a “proper” divisor of n. So you can remove the “1” case from your loop, and get rid of the <code>x != 1</code> test, for a slight speed increase. </p>\n\n<p>Also, if <code>n % x == 0</code>, then the other divisor is <co...
{ "AcceptedAnswerId": "202788", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-29T23:21:47.867", "Id": "202783", "Score": "4", "Tags": [ "python", "beginner", "time-limit-exceeded", "mathematics" ], "Title": "Project Euler Problem 21 in Python: Summing amicable numbers" }
202783
<p>I am a beginner in the programming world. This is the first big project I tackle which is the battleships game. I implemented the game to run in the console. I was hoping if you guys can check my code and help realize if I can have shortcuts or make it more efficient.</p> <p>The game goes as follows:</p> <ol> <li>deploy map.</li> <li>user enters coordinates of his ships.</li> <li>random coordinates are generated for pc ships.</li> <li>the user ships should be on top of each other and the same goes for the pc ships.</li> <li>the pc and the user ships cannot be on top of each other as well.</li> <li>now the game starts, the user enter coords if he misses the "O" appears, if he hits the "!" appears, if he hits his ship the "X" appears.</li> <li>if he hits pc/his ships the user can't enter the same coords again. he cant enter the coords of the ones he missed too.</li> <li>random coords are generated for the pc, but need to make sure that the numbers were not already used and missed and it can't generate the same coords when it hits its-own/user ships.</li> </ol> <p>I had to use an array list to store where the pc has missed whereas for the user I am visually comparing the "O". I am not sure how I can test the part where the pc can't enter the missed coords again. Finally, can I get some tips or help with improving the pieces of my code and make it more efficient?</p> <p>UPDATE : I rethought the layout of my code, so i could use fewer functions that can be used by both the user and the pc but at the price of complicating things a bit. This is the final version, do you think something can be fixed to make it more efficient?</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class BattleShips { // INITIALIZE MAIN VARIABLES AND CALL FUNCTIONS IN ORDER public static void main(String[] args) { // VARIABLES // Scanner input = new Scanner(System.in); String[][] battleMap = new String[10][10]; Integer[][] userShips = new Integer[5][2]; Integer[][] pcShips = new Integer[5][2]; Integer[] dummyCoords = new Integer[2]; ArrayList&lt;ArrayList&lt;Integer&gt;&gt; pcMissedShips = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(); // FUNCTION CALLS // intro(); fillBattleMap(battleMap); userShips = getUserShips(input, userShips, 0); manipulateBattleMapShips(userShips, battleMap, dummyCoords, "@", true); updateBattleMap(battleMap); System.out.println(" Computer is deploying ships"); pcShips = getPcShips(pcShips, userShips, 0); manipulateBattleMapShips(pcShips, battleMap, dummyCoords, " ", true); updateBattleMap(battleMap); while (!isGameOver(battleMap)) { userCoordsEntry(input, battleMap, pcMissedShips, userShips, pcShips); pcCoordsEntry(battleMap, pcMissedShips, userShips, pcShips); updateBattleMap(battleMap); } } // INTRODUCTION public static void intro() { System.out.println(); System.out.println("***** Let's play a game of Battle Ships *****"); System.out.println(); } // FILL BATTLEMAP ARRAY AND PRINT public static void fillBattleMap(String[][] battleMap) { System.out.println(" 0 1 2 3 4 5 6 7 8 9"); System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); for (int i = 0; i &lt; battleMap.length; i++) { System.out.print(" " + i + " | "); for (int j = 0; j &lt; battleMap[i].length; j++) { battleMap[i][j] = " "; System.out.print(battleMap[i][j] + " "); } System.out.print("| " + i); System.out.println(); } System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(" 0 1 2 3 4 5 6 7 8 9"); System.out.println(); } // PRINT BATTLEMAP public static void updateBattleMap (String[][] battleMap) { System.out.println(); System.out.println(" 0 1 2 3 4 5 6 7 8 9"); System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); for (int i = 0; i &lt; battleMap.length; i++) { System.out.print(" " + i + " | "); for (int j = 0; j &lt; battleMap[i].length; j++) { System.out.print(battleMap[i][j] + " "); } System.out.print("| " + i); System.out.println(); } System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(" 0 1 2 3 4 5 6 7 8 9"); System.out.println(); } // USER INPUTS SHIPS LOCATION AND RETURNS 2D ARRAY CONTAINING COORDINATES public static Integer[][] getUserShips (Scanner input, Integer[][] userShips, int loop) { boolean checkIfOutOfBounds = false; boolean checkIfThereIsShipForUser = false; Integer[] userShipsCoords = new Integer[2]; for (int i = loop; i &lt; 5; i++) { System.out.print("Enter X coordinate for your " + (i + 1) + ". ship:"); userShipsCoords[0] = input.nextInt(); System.out.print("Enter Y coordinate for your " + (i + 1) + ". ship:"); userShipsCoords[1] = input.nextInt(); checkIfOutOfBounds = checkIfOutOfBounds(userShipsCoords); checkIfThereIsShipForUser = checkIfThereIsShip(userShipsCoords, userShips); if (checkIfOutOfBounds) { return getUserShips(input, userShips, i); } else if (checkIfThereIsShipForUser) { return getUserShips(input, userShips, i); } userShips[i][0] = userShipsCoords[0]; userShips[i][1] = userShipsCoords[1]; } return userShips; } // RANDOMS SHIPS LOCATIONS AND MAKES SURE THEY DO NOT COLLIDE WITH THE USER'S OR PC'S SHIPS public static Integer[][] getPcShips (Integer[][] pcShips, Integer[][] userShips, int loop) { Integer[] pcCoords = new Integer[2]; boolean checkIfThereIsShipForPc = false; boolean checkIfThereIsShipForUser = false; for (int i = loop; i &lt; pcShips.length; i++) { pcCoords[0] = (int) Math.floor(Math.random()*10); pcCoords[1] = (int) Math.floor(Math.random()*10); checkIfThereIsShipForUser = checkIfThereIsShip(pcCoords, userShips); checkIfThereIsShipForPc = checkIfThereIsShip(pcCoords, pcShips); if (checkIfThereIsShipForPc) { return getPcShips(pcShips, userShips, i); } else if (checkIfThereIsShipForUser) { return getPcShips(pcShips, userShips, i); } pcShips[i][0] = pcCoords[0]; pcShips[i][1] = pcCoords[1]; System.out.println(" " + (i+1) + ". Ship DEPLOYED "); } System.out.println(" ----------------"); return pcShips; } // TAKE USER COORDINATES INPUT AND CHECKS IF ITS VALID THEN UPDATES BATTLEMAP ARRAY, IF NOT THE USER HAS TO ENTER AGAIN NEW COORDS public static Integer[] userCoordsEntry (Scanner input, String[][] battleMap, ArrayList&lt;ArrayList&lt;Integer&gt;&gt; pcMissedShips, Integer[][] userShips, Integer[][] pcShips) { Integer[] userCoords = new Integer[2]; System.out.println(); System.out.println("Your Turn."); System.out.print("Enter X coordinate:"); userCoords[0] = input.nextInt(); System.out.print("Enter Y coordinate:"); userCoords[1] = input.nextInt(); if (checkIfOutOfBounds(userCoords)) { System.out.println("Choose again"); return userCoordsEntry (input, battleMap, pcMissedShips, userShips, pcShips); } else if (checkIfUserShipIsHitAtCoords(battleMap, userCoords)) { System.out.println("Choose again"); return userCoordsEntry (input, battleMap, pcMissedShips, userShips, pcShips); } else if (checkIfPcShipIsHitAtCoords(battleMap, userCoords)) { System.out.println("Choose again"); return userCoordsEntry (input, battleMap, pcMissedShips, userShips, pcShips); } else if (checkIfShipIsMissed(battleMap, userCoords, true, pcMissedShips)) { System.out.println("Choose again"); return userCoordsEntry (input, battleMap, pcMissedShips, userShips, pcShips); } else { if (checkIfThereIsShip (userCoords, userShips)) { System.out.println("You hit your own ship..."); manipulateBattleMapShips (userShips, battleMap, userCoords, "X", false); } else if (checkIfThereIsShip (userCoords, pcShips)) { System.out.println("BOOM! You got your opponent!"); manipulateBattleMapShips (pcShips, battleMap, userCoords, "!", false); } else { System.out.println("OH no! You missed:("); manipulateBattleMapShips (userShips, battleMap, userCoords, "O", false); } } return userCoords; } // RANDOMS COMPUTERS COORDS INPUT AND CHECKS IF ITS VALID THEN UPDATES BATTLEMAP ARRAY, IF NOT THE USER HAS TO ENTER AGAIN NEW COORDS public static Integer[] pcCoordsEntry (String[][] battleMap, ArrayList&lt;ArrayList&lt;Integer&gt;&gt; pcMissedShips, Integer[][] userShips, Integer[][] pcShips) { Integer[] pcCoords = new Integer[2]; System.out.println(); System.out.println("Computer's Turn."); pcCoords[0] = (int) Math.floor(Math.random()*10); pcCoords[1] = (int) Math.floor(Math.random()*10); System.out.println("The Computer chose it\'s X coordinate to be: " + pcCoords[0]); System.out.println("The Computer chose it\'s Y coordinate to be: " + pcCoords[1]); if (checkIfUserShipIsHitAtCoords(battleMap, pcCoords)) { return pcCoordsEntry (battleMap, pcMissedShips, userShips, pcShips); } else if (checkIfPcShipIsHitAtCoords(battleMap, pcCoords)) { return pcCoordsEntry (battleMap, pcMissedShips, userShips, pcShips); } else if (checkIfShipIsMissed(battleMap, pcCoords, false, pcMissedShips)) { return pcCoordsEntry (battleMap, pcMissedShips, userShips, pcShips); } else { if (checkIfThereIsShip (pcCoords, userShips)) { System.out.println("NO! Computer hit your ship."); manipulateBattleMapShips (userShips, battleMap, pcCoords, "|", false); } else if (checkIfThereIsShip (pcCoords, pcShips)) { System.out.println("YES! Computer hit his own ship"); manipulateBattleMapShips (pcShips, battleMap, pcCoords, "#", false); } else { System.out.println("Computer missed:)"); pcMissedShips.add(new ArrayList&lt;Integer&gt;(Arrays.asList(pcCoords))); } } return pcCoords; } // END GAME CONDITION public static boolean isGameOver (String[][] battleMap) { int pcShipCount = 5; int userShipCount = 5; for (int i = 0; i &lt; battleMap.length; i++) { for (int j = 0; j &lt; battleMap[i].length; j++) { if (battleMap[i][j].equals("X")) { userShipCount--; } if (battleMap[i][j].equals("|")) { userShipCount--; } if (battleMap[i][j].equals("#")) { pcShipCount--; } if (battleMap[i][j].equals("!")) { pcShipCount--; } } } if (userShipCount == 0) { System.out.println("GAME OVER! Computer Wins"); System.out.println("Your ships: " + userShipCount + " | Comuter ships " + pcShipCount); return true; } else if (pcShipCount == 0) { System.out.println("GAME OVER! You win"); System.out.println("Your ships: " + userShipCount + " | Comuter ships " + pcShipCount); return true; } return false; } // MANIPULATE BATTLEMAP BY "CHARACTER" WITH ANOTHER "CHARACTER" public static void manipulateBattleMapShips (Integer[][] ships, String[][] battleMap, Integer[] coords, String character, boolean addShipOrAddCharacter) { if (addShipOrAddCharacter) { for (int i = 0; i &lt; ships.length; i++) { battleMap[ships[i][1]][ships[i][0]] = character; } } else { battleMap[coords[1]][coords[0]] = character; } } // CHECK IF THE COORDINATES OF SHIP ARE INSIDE THE MAP public static boolean checkIfOutOfBounds (Integer[] coords) { if (coords[1] &lt; 0 || coords[1] &gt; 9 || coords[0] &lt; 0 || coords[0] &gt; 9) { return true; } else { return false; } } // CHECK IF THE SHIPS LOCATIONS ARE NOT DUPLICATED public static boolean checkIfThereIsShip (Integer[] coords, Integer[][] ships) { for (int i = 0; i &lt; ships.length; i++) { if (coords[0] == ships[i][0] &amp;&amp; coords[1] == ships[i][1]) { return true; } } return false; } // CHECK IF USER SHIP IS HIT WHEN COORDINATES ARE ENTERED public static boolean checkIfUserShipIsHitAtCoords (String[][] battleMap, Integer[] coords) { if (battleMap[coords[1]][coords[0]].equals("|") || battleMap[coords[1]][coords[0]].equals("X")) { return true; } else { return false; } } // CHECK IF PC SHIP IS HIT WHEN C public static boolean checkIfPcShipIsHitAtCoords (String[][] battleMap, Integer[] coords){ if (battleMap[coords[1]][coords[0]].equals("#") || battleMap[coords[1]][coords[0]].equals("!")) { return true; } else { return false; } } // CHECK IS USER OR PC SHIPS ARE MISSED AT COORDINATES ENTERED/GUESSED public static boolean checkIfShipIsMissed (String[][] battleMap, Integer[] coords, boolean userOrPc, ArrayList&lt;ArrayList&lt;Integer&gt;&gt; pcMissedShips) { if (userOrPc) { if (battleMap[coords[1]][coords[0]].equals("O")) { return true; } else { return false; } } else { if (pcMissedShips.size() == 0) { return false; } for (int i = 0; i &lt; pcMissedShips.size(); i++) { if (coords[0] == pcMissedShips.get(i).get(0) &amp;&amp; coords[1] == pcMissedShips.get(i).get(1)) { return true; } } return false; } } </code></pre> <p>}</p>
[]
[ { "body": "<p>Welcome to the world of programming! Congrats on undertaking your first project as well! I will have to spend more time looking at your code to figure out how to do things more efficiently, but in terms of adding functionality to prevent a user from entering duplicate coordinates I think you can e...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T03:01:32.417", "Id": "202790", "Score": "5", "Tags": [ "java", "performance", "beginner", "battleship" ], "Title": "Java battle ship game" }
202790
<p>For many years, I have waited for function aliases in C++. They still aren't here. I've been using macros to generate wrapper functions. This is my best attempt at the perfect function alias:</p> <pre><code>#define FUN_ALIAS(NEW_NAME, ...) \ template &lt;typename... Args&gt; \ inline decltype(auto) NEW_NAME(Args &amp;&amp;... args) \ noexcept(noexcept(__VA_ARGS__(std::forward&lt;Args&gt;(args)...))) { \ return __VA_ARGS__(std::forward&lt;Args&gt;(args)...); \ } </code></pre> <p>I'm using <code>std::forward</code> to forward the arguments and I'm using <code>decltype(auto)</code> to get the right return type. In the future, we might have <code>noexcept(auto)</code> which will be perfect for this situation but I'm not getting my hopes up.</p> <p>Here's an example from my OpenGL wrapper:</p> <pre><code>template &lt;GLenum TYPE&gt; Shader&lt;TYPE&gt; makeShader(); template &lt;GLenum TYPE&gt; Shader&lt;TYPE&gt; makeShader(const GLchar *, size_t); template &lt;GLenum TYPE, size_t... SIZES&gt; Shader&lt;TYPE&gt; makeShader(const GLchar (&amp;... sources)[SIZES]); FUN_ALIAS(makeVertShader, makeShader&lt;GL_VERTEX_SHADER&gt;) FUN_ALIAS(makeFragShader, makeShader&lt;GL_FRAGMENT_SHADER&gt;) </code></pre> <p>What I want to know: </p> <ul> <li>Is there a situation where the compiler will not optimize away the wrapper because the wrapper and the original function have different semantics?</li> <li>Does this fail to compile for some functions?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T06:20:08.097", "Id": "390811", "Score": "0", "body": "I don't like macros, however this looks really nice! I think this will work unless your alias needs to be a template as well. Why do you need FUN_ALIAS_PTR? Doesn't the other cov...
[ { "body": "<blockquote>\n <p>Is there a situation where the compiler will not optimize away the wrapper because the wrapper and the original function have different semantics?</p>\n</blockquote>\n\n<p>Yes to the first part and no to the second. Any optimizing compiler will inline your wrapper, as it consists o...
{ "AcceptedAnswerId": "203322", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T03:29:22.153", "Id": "202791", "Score": "8", "Tags": [ "c++", "template-meta-programming", "c++17", "macros", "variadic" ], "Title": "The perfect function alias" }
202791
<p>I am currently using Django (2.1) to build an API, and I have added djangorestframework-jwt to manage JWT.</p> <p>Here is the configuration:</p> <pre><code>JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', } </code></pre> <p>and the endpoints:</p> <pre><code>urlpatterns = [ path('auth/get-token/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), ] </code></pre> <p>The client is built with ReactJS. I use an axios instance as a client to communicate with the API. This instance is created that way :</p> <pre><code>import axios from 'axios' import jwt_decode from 'jwt-decode' // eslint-disable-line import { signOut } from '../actions/authActions' const signOutOn401 = (statusCode) =&gt; { if (statusCode === 401) { signOut() window.location = '/signin' } } const client = axios.create({ baseURL: process.env.API_URL, headers: {'Authorization': ''} }) /* * This interceptor is used for: * - adding Authorization header if JWT available * - refreshing JWT to keep user authenticated */ client.interceptors.request.use((config) =&gt; { if (window.localStorage.getItem('token')) { let token = window.localStorage.getItem('token') // Calculate time difference in days // between now and token expiration date const t = ((jwt_decode(token).exp * 1000) - Date.now()) / 1000 / 60 / 60 / 24 // Refresh the token if the time difference is // smaller than 13 days (original token is valid 14 days) if (t &lt; 13) { axios.post(`${process.env.API_URL}/auth/refresh-token/`, { token: token }) .then(({data}) =&gt; { token = data.token }) .catch((error) =&gt; { signOutOn401(error.response.status) return error }) } config.headers['Authorization'] = `Bearer ${token}` } return config }) /* * This interceptor is used for: * - disconnect user if JWT is expired or revoked */ client.interceptors.response.use( (response) =&gt; { return response }, (error) =&gt; { signOutOn401(error.response.status) return error } ) export default client </code></pre> <p>The signout action only clear the session and clean the store :</p> <pre><code>export const signOut = () =&gt; { window.localStorage.clear() return ({ type: SIGN_OUT, payload: { authenticated: false, user: {}, errorMessage: '' } }) } </code></pre> <p>Everything looks working fine, I would just like to know if that implementation is correct, and if there is no security flaw :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T09:26:32.873", "Id": "390836", "Score": "0", "body": "\"and if there is no security flaw\" What's your threat model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T19:30:08.040", "Id": "390919", ...
[ { "body": "<h1>UX concern: refresh period</h1>\n<p>I wonder if you are confusing the access token expiration setting (<code>JWT_EXPIRATION_DELTA</code>) with the refresh token expiration (<code>JWT_REFRESH_EXPIRATION_DELTA</code>). In either case, your <code>t &lt; 13</code> check should be related to the refre...
{ "AcceptedAnswerId": "202893", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T08:43:50.833", "Id": "202800", "Score": "3", "Tags": [ "javascript", "authentication", "react.js", "django", "jwt" ], "Title": "JWT authentication between Django and ReactJS" }
202800
<p>I'm trying to learn some multithreading and this seems like a good example, want to apply this to frustum culling later. The goal is to find prime numbers in randomly generated vector of numbers. Single threaded solution is simple, multithreaded way is to divide vector of random numbers in two parts, solve each one in the same time and merge results.</p> <p>Here is the time it took to solve:</p> <p>mt:</p> <p>solved in: 17185.4 ms</p> <p>solved in: 15832.2 ms</p> <p>solved in: 16012.5 ms</p> <p>solved in: 16354.9 ms</p> <p>st:</p> <p>solved in: 26942 ms</p> <p>solved in: 30577.9 ms</p> <p>solved in: 26403.4 ms</p> <p>solved in: 29625.7 ms</p> <p>It obviously works, but is the code correct?</p> <p>This is from main.cpp:</p> <pre><code> #include "primeNumbers.h" int main(){ PrimeNumbers numbers(100000, 0, 5000000); PrimeNumberSolver* solver = new PrimeNumberSingleThread; //PrimeNumberSolver* solver = new PrimeNumberMultiThread; numbers.Solve(solver); delete solver; } </code></pre> <p>This is the rest of the code:</p> <pre><code>//primeNumbers.h #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &lt;iostream&gt; class PrimeNumberSolver abstract { public: bool isPrime(int n) { for (int i = 2; i &lt; n/2; ++i) { if (n % i == 0) return false; } return true; } virtual void solve(const std::vector&lt;int&gt;&amp; source, std::vector&lt;int&gt;&amp; result) = 0; }; class PrimeNumberSingleThread final : public PrimeNumberSolver { friend class PrimeNumbers; private: virtual void solve(const std::vector&lt;int&gt;&amp; source, std::vector&lt;int&gt;&amp; result) override{ for (unsigned i = 0; i &lt; source.size(); ++i) { if (isPrime(source[i])) result.push_back(source[i]); } } }; class PrimeNumberMultiThread final : public PrimeNumberSolver { friend class PrimeNumbers; private: virtual void solve(const std::vector&lt;int&gt;&amp; source, std::vector&lt;int&gt;&amp; result) override { std::vector&lt;int&gt; r1; std::vector&lt;int&gt; r2; //split source int half = source.size() / 2; int end = source.size(); std::mutex m; //run two threads std::thread t1([&amp;]() { for (int i = 0; i &lt; half; ++i) { //std::lock_guard&lt;std::mutex&gt; lock(m); //do i need to lock mutex before accessing source if (isPrime(source[i])) r1.push_back(source[i]); } }); std::thread t2([&amp;]() { for (int i = half; i &lt; end; ++i) { //std::lock_guard&lt;std::mutex&gt; lock(m); //do i need to lock mutex before accessing source if (isPrime(source[i])) r2.push_back(source[i]); } }); //join threads if(t1.joinable()) t1.join(); if(t2.joinable()) t2.join(); //merge results result.insert(result.end(), r1.begin(), r1.end()); result.insert(result.end(), r2.begin(), r2.end()); } }; class PrimeNumbers { public: PrimeNumbers(int size, unsigned min, unsigned max) { std::mt19937 rng; for (int i = 0; i &lt; size; ++i) { rng.seed(std::random_device()()); std::uniform_int_distribution&lt;std::mt19937::result_type&gt; dist6(min, max); randoms.push_back(dist6(rng)); } std::cout &lt;&lt; "Numbers are generated" &lt;&lt; std::endl; } void Solve(PrimeNumberSolver* solver) { double time = glfwGetTime(); solver-&gt;solve(randoms, primes); std::cout &lt;&lt; "solved in: " &lt;&lt; (glfwGetTime() - time) * 1000.0 &lt;&lt; " ms" &lt;&lt; std::endl; } void printPrimes() { for (unsigned i = 0; i &lt; primes.size(); ++i) std::cout &lt;&lt; primes[i] &lt;&lt; std::endl; } std::vector&lt;int&gt; randoms; std::vector&lt;int&gt; primes; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T09:25:38.203", "Id": "390835", "Score": "1", "body": "\"It obviously works, but is the code correct?\" Have you tested the output? Does it work the way you expected it to?" }, { "ContentLicense": "CC BY-SA 4.0", "Creatio...
[ { "body": "<p>This is a poor way to test primality:</p>\n\n<pre><code>bool isPrime(int n) {\n for (int i = 2; i &lt; n/2; ++i) {\n if (n % i == 0)\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Even sticking with trial division, we can stop at √n, which is generally much l...
{ "AcceptedAnswerId": "202815", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T08:46:51.150", "Id": "202802", "Score": "2", "Tags": [ "c++", "multithreading", "primes" ], "Title": "Are numbers prime multithreading" }
202802
<p>I am working on code to generate a screw made up of different elements and animating it by rotatation. The elements are so called conveying elements (denoted by <code>GFA</code>) which are helical shaped screw elements and kneading blocks (denoted by <code>KB</code>) which are smaller sequential sections offset by a staggering angle.</p> <p>The algorithm is as follows:</p> <ol> <li>Typical initialization (in <code>init</code>) of Three.js objects such as renderer, scene, camera and controls</li> <li>An instance of a custom object <code>Screw</code> is initialized and elements are added using a identifier string, e.g. 'GFA 2-40-90' or 'KB 5-2-30-90'.</li> <li>The <code>add</code> method of <code>Screw</code> checks what type the element is (i.e. <code>GFA</code> or <code>KB</code>) and creates an instances of the relevant element object (i.e. <code>GFAElement</code> or <code>KBElement</code> using the parameters of the element and moves it to the end of the screw.</li> <li>As an element object is instantiated, the profile shape is determined from the screw parameters and used to extrude to the required geometry using the element parameters stored in <code>userData</code>. For <code>GFAElements</code>, the geometry is subsequently twisted to generate the helical shape of the screw. For <code>KBElements</code>, the mesh of a block is extruded to the required thickness and then cloned while rotating in discrete steps to generate a <code>Three.Group</code> of smaller sections offset by an angle.</li> <li>After the adding of elements to the screw has finished, the screw is cloned to a mirror screw which is offset by a certain distance and angle from the original screw. During <code>animate</code>, the screw and its mirrored clone are rotated by a certain angle.</li> </ol> <p>What I would like to improve:</p> <ol> <li><strong><em>memory usage and performance</em></strong> - for GFAElements 'twisting' the vertices seems to be a big performance hit at initialization specifically for a large number of elements and high resolutions (defined by the <code>steps</code> property in <code>extrudeSettings</code>).</li> <li><strong><em>Improve feathering of GFAElements</em></strong> - at low resolutions the edges of the element are feathered; this is reduced by increasing the <code>step</code> resolution but also decreases performance at initialization and increases memory usage.</li> <li><strong><em>Class structuring</em></strong> - I am unsure if I have structured my classes logically. Particularly, I am not sure about the way I decide on which type of element is added in <code>Screw</code> method <code>add</code>. Perhaps it is better to have a abstract base class for an element and inherit from it for <code>GFAElement</code> and <code>KBElement</code>.</li> </ol> <p>Using JavaScript with <a href="https://threejs.org/" rel="nofollow noreferrer">three.js</a>.</p> <p>Code (<a href="http://jsfiddle.net/nlooije/pamv8krb/" rel="nofollow noreferrer">fiddle</a>):</p> <pre><code>'use strict'; var container; var camera, scene, renderer, controls; var screw, mirror; // Screw parameters var P = 2; // number of flights var D = 50, // outer diameter Dr = D/1.66, // root diameter Cl = (Dr+D)/2, // centerline distance αi = 2*Math.acos(Cl/D), Ih = D*Math.sin(αi/2)/2, H = D-Cl; var αf = αi, αt = Math.PI/P - αf, αr = αt; //console.log(D, Dr, Cl, Ih, H); //console.log(αi, αf, αt, αr); function getFlankParams(α1, D1, α2, D2, ctr){ // flanks are arcs with origin (xc, yc) of radius Cl passing through (x1, y1) and (x2, y2): // (x1-xc)^2 + (y1-yc)^2 = Cl^2 // (x2-xc)^2 + (y2-yc)^2 = Cl^2 var x1 = D1*Math.cos(α1), y1 = D1*Math.sin(α1), x2 = D2*Math.cos(α2), y2 = D2*Math.sin(α2); // Solving system of equations yields linear eq: // y1-yc = beta - alpha*(x1-xc) var alpha = (x1-x2)/(y1-y2), beta = (y1-y2)*(1+Math.pow(alpha,2))/2; // Substitution and applying quadratic equation: var xc = x1 - alpha*beta/(1+Math.pow(alpha,2))*(1+Math.pow(-1,ctr)*Math.sqrt(1-(1-Math.pow(Cl/beta,2))*(1+1/Math.pow(alpha,2)))), yc = y1 + alpha*(x1-xc) - beta; // Following from law of consines, the angle the flank extends wrt its own origin: var asq = Math.pow(Dr/2,2)+Math.pow(D/2,2)-2*(Dr/2)*(D/2)*Math.cos(αf), af = Math.acos(1-asq/Math.pow(Cl, 2)/2); return {xc, yc, af}; } function getProfile() { var shape = new THREE.Shape(); var angle = 0, ctr = 0; // loop over number of flights for (var p=0; p&lt;P; p++){ // tip shape.absarc(0, 0, D/2, angle, angle+αt); angle += αt; // flank var params = getFlankParams(angle, D/2, angle+αf, Dr/2, ctr++); shape.absarc(params.xc, params.yc, Cl, angle+αf-params.af, angle+αf, false); angle += αf; // root shape.absarc(0, 0, Dr/2, angle, angle+αr); angle += αr; // flank params = getFlankParams(angle, Dr/2, angle+αf, D/2, ctr++); shape.absarc(params.xc, params.yc, Cl, angle, angle+αf-params.af, false); angle += αf; } return shape; } class GFAElement extends THREE.Mesh { constructor(params){ // var p = params.split("-"); var userData = { type: "GFA", flights: parseInt(p[0]), pitch: parseInt(p[1]), length: parseInt(p[2]), }; var shape = getProfile(); var extrudeSettings = { steps: userData.length/2, depth: userData.length, bevelEnabled: false }; var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings ); var material = new THREE.MeshStandardMaterial( { color: 0xffffff, metalness: 0.5, roughness: 0.5, } ); super( geometry, material ); this.geometry.vertices.forEach( vertex =&gt; { var angle = -2*Math.PI/userData.flights*vertex.z/userData.pitch; var updateX = vertex.x * Math.cos(angle) - vertex.y * Math.sin(angle); var updateY = vertex.y * Math.cos(angle) + vertex.x * Math.sin(angle); vertex.x = updateX; vertex.y = updateY; }); this.geometry.computeFaceNormals(); this.geometry.computeVertexNormals(); this.type = 'GFAElement'; this.userData = userData; this._params = params; this._name = 'GFA ' + params; } clone(){ return new this.constructor( this._params ).copy( this ); } } class KBElement extends THREE.Group { // constructor(params){ super(); var p = params.split("-"); var userData = { type: "KB", thickness: parseInt(p[0]), flights: parseInt(p[1]), length: parseInt(p[2]), stagAngle: parseInt(p[3]), }; var shape = getProfile(); var extrudeSettings = { depth: userData.thickness, bevelEnabled: false }; var geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings ); var material = new THREE.MeshStandardMaterial( { color: 0xffffff, metalness: 0.5, roughness: 0.5, } ); var mesh = new THREE.Mesh( geometry, material ); super.add( mesh ); for (var n=1, nt = userData.length/userData.thickness; n&lt;nt; n++){ mesh = mesh.clone(); mesh.position.z += userData.thickness; mesh.rotation.z += userData.stagAngle; super.add( mesh ); } this.type = 'KBElement'; this.userData = userData; this._params = params; this._name = 'KB ' + params; } clone(){ return new this.constructor( this._params ).copy( this ); } } class Screw extends THREE.Group { // constructor(){ super(); this.userData.length = 0; //length of screw starting at origin } add(desc){ var elem, params = desc.split(" "); if (params[0] == "GFA") { elem = new GFAElement(params[1]); } else if (params[0] == "KB") { elem = new KBElement(params[1]); } elem.position.z = this.userData.length; this.userData.length += elem.userData.length; super.add(elem); } clone(){ var clone = super.clone(false); clone.userData.length = 0; this.children.forEach(function(elem){ var e = elem.clone(); clone.add(e._name); }); clone.position.x += -Cl; clone.rotation.z += Math.PI/2; return clone } } function init() { renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); //renderer.gammaInput = true; //renderer.gammaOutput = true; document.body.appendChild( renderer.domElement ); scene = new THREE.Scene(); scene.background = new THREE.Color( 0x222222 ); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.set( -200, 200, -200 ); scene.add( camera ); var light = new THREE.PointLight( 0xffffff ); camera.add( light ); controls = new THREE.TrackballControls( camera, renderer.domElement ); controls.minDistance = 100; controls.maxDistance = 500; screw = new Screw(); screw.add('GFA 2-40-90'); screw.add('KB 5-2-30-90'); screw.add('GFA 2-40-90'); screw.add('KB 10-2-120-15'); mirror = screw.clone(); scene.add(screw, mirror); } function animate() { screw.rotation.z += 2*Math.PI/100; mirror.rotation.z += 2*Math.PI/100; requestAnimationFrame( animate ); controls.update(); renderer.render( scene, camera ); } init(); animate(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-09T18:10:43.377", "Id": "392065", "Score": "0", "body": "hey Did you attempt to make any changes based on my suggestions? If so, did it help at all?" } ]
[ { "body": "<blockquote>\n <p><strong><em>memory usage and performance</em></strong></p>\n</blockquote>\n\n<p>I see that the constructor for <code>GFAElement</code> uses a <code>forEach</code> iterator. While functional programming is great, one drawback is that it is typically slower because function calls are...
{ "AcceptedAnswerId": "203125", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T09:01:36.827", "Id": "202804", "Score": "5", "Tags": [ "javascript", "performance", "ecmascript-6", "animation", "graphics" ], "Title": "Animating a screw made up of elements" }
202804
<p>I've written a simple script that calculates the distance between two points in time and returns the duration.</p> <p>Example: Start - 11:00, End - 11:45, Duration - 0.75</p> <p>I wanted to make use of ES6 classes and I'd like feedback on the <code>Duration</code> class in particular. For example, should the validation of the <code>start</code> and <code>end</code> arguments go in the constructor? Or should that be done later?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Duration { constructor(start, end) { const reg = RegExp('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$'); this.start = reg.test(start) ? start : '00:00'; this.end = reg.test(end) ? end : '00:00'; } _seconds(time = "00:00") { const split = time.split(':'); return Number(split[0]) * 60 + Number(split[1]); } // See: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary _round(float) { return Math.round((float + 0.0001) * 100) / 100; } get difference() { const { _round: round, _seconds: seconds, start, end } = this; return round((seconds(end) - seconds(start)) / 60); } } function calcDuration(e) { e.preventDefault(); const start = document.getElementById('time-start'); const end = document.getElementById('time-end'); const target = document.getElementById('target'); const duration = new Duration(start.value, end.value); target.innerHTML += `&lt;tr&gt;&lt;td&gt;${duration.start}&lt;/td&gt;&lt;td&gt;${duration.end}&lt;/td&gt;&lt;td&gt;${duration.difference}&lt;/td&gt;&lt;/tr&gt;`; start.focus(); } document.getElementById('time-submit').addEventListener('click', calcDuration);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col pt-5"&gt; &lt;h1&gt;Duration Calculator&lt;/h1&gt; &lt;p&gt;Enter a start time and an end time and a conversion to a decimal will be given!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col pt-4 pb-4"&gt; &lt;form class="time mx-auto"&gt; &lt;div class="form-row"&gt; &lt;div class="col-auto"&gt; &lt;label for="time-start"&gt;Start time:&lt;/label&gt; &lt;/div&gt; &lt;div class="col-auto"&gt; &lt;input type="time" id="time-start" class="form-control" name="time-start" required autofocus/&gt; &lt;/div&gt; &lt;div class="col-auto"&gt; &lt;label for="time-end"&gt;End time:&lt;/label&gt; &lt;/div&gt; &lt;div class="col-auto"&gt; &lt;input type="time" id="time-end" name="time-end" class="form-control" required/&gt; &lt;/div&gt; &lt;div class="col-auto"&gt; &lt;button id="time-submit" class="btn btn-primary" type="submit" value="Calculate"&gt;Calculate&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col pt-2 pb-5"&gt; &lt;table id="target" class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Start&lt;/th&gt; &lt;th&gt;End&lt;/th&gt; &lt;th&gt;Duration&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><sub><sup><strong>NOTE</strong> &nbsp; &nbsp; I'll only be taking a look at your <code>Duration</code> class, not the UI-specific code.</sup></sub></p>\n\n<hr>\n\n<h1>Regex as a constant</h1>\n\n<p>You don't need to re-instantiate a new <code>RegExp</code> instance every time a <code>Duration</cod...
{ "AcceptedAnswerId": "202839", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T09:23:08.087", "Id": "202806", "Score": "2", "Tags": [ "javascript", "object-oriented", "datetime", "ecmascript-6" ], "Title": "Simple Duration calculator using es6 class syntax" }
202806
<p>I have found myself referencing controls on a form (think Windows forms but more proprietary) by hard-typing their names in over and over again. Often I'll have a number of similar controls which could be named <code>coolControl1department</code>, <code>coolControl2department</code>, <code>coolControl1jobTitle</code>, <code>coolControl2jobTitle</code>, etc. This becomes tedious and a nightmare to maintain. Renaming the controls is definitely an option but I would still need some way of generating their names to assign values and whatnot.</p> <p>To make this less reliant on me typing in the names I've created a dictionary method to concatenate the various parts of the control names, including unique reference numbers, and then call the final values elsewhere. </p> <p>While it's more centralised than it was previously, there is still room for improvement and I'd appreciate any suggestions to streamline this.</p> <p>Note that I'm only able to use C# version 4.0 in this application. Code below.</p> <pre><code> public void DoStuffWithControls() { Dictionary&lt;string, string&gt; myControls1 = GeneratedControlNames(1); Dictionary&lt;string, string&gt; myControls2 = GeneratedControlNames(2); string genericControl1; string genericControl2; string departmentControl1; string departmentControl2; myControls1.TryGetValue("generic", out genericControl1); myControls1.TryGetValue("department", out departmentControl1); myControls2.TryGetValue("generic", out genericControl2); myControls2.TryGetValue("department", out departmentControl2); EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).Value = "some value"; EnquiryForm.GetEnquiryControl(departmentControl1, EnquiryControlMissing.Exception).Value = "some value"; EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).AnotherProperty = "some other value"; EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).Value = "some value"; EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).AnotherProperty = "some other value"; EnquiryForm.GetEnquiryControl(departmentControl2, EnquiryControlMissing.Exception).Value = "some value"; } private static Dictionary&lt;string, string&gt; GeneratedControlNames(int refNumber) { var genericPrefix = "coolControl"; var departmentControlSuffix = "Department"; var jobTitleControlSuffix = "Title"; var directDialControlSuffix = "DDI"; var emailDialControlSuffix = "Email"; var dict = new Dictionary&lt;string, string&gt;(); dict.Add("generic", string.Concat(genericPrefix, refNumber)); dict.Add("department", string.Concat(genericPrefix, refNumber, departmentControlSuffix)); dict.Add("jobTitle", string.Concat(genericPrefix, refNumber, jobTitleControlSuffix)); dict.Add("directDial", string.Concat(genericPrefix, refNumber, directDialControlSuffix)); dict.Add("email", string.Concat(genericPrefix, refNumber, emailDialControlSuffix)); return dict; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T16:49:10.090", "Id": "391074", "Score": "1", "body": "How much work has this really saved? You still need to do what amounts to typing out the identifier by typing out which dictionary it's in as well as the generalized label _while...
[ { "body": "<p>I think the dictionary is overkill. Plus adds a lot more code with the TryGet. I would make a class to help and hide the magic strings. </p>\n\n<p>As a side note magic strings should be made into constants so they are maintained in one place and if a typo you just need to fix it in one place. ...
{ "AcceptedAnswerId": "202884", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T10:12:02.203", "Id": "202808", "Score": "1", "Tags": [ "c#", "hash-map", "winforms" ], "Title": "Dictionary to generate control names" }
202808
<p>I made a simple Mastermind clone and I'd just like some tips on what I could do better/different solutions for what I have already coded. If you're wondering what mastermind is, there are, for the original, 6 different colors and 4 different holes. I decided to make this since I had made mastermind in other things so I thought it would be a good starter project in C#.</p> <pre><code>static void Main(string[] args) { Random GenRandom = new Random(); int t = 0, r, c1 = GenRandom.Next(1, 6), c2 = GenRandom.Next(1, 6), c3 = GenRandom.Next(1, 6), c4 = GenRandom.Next(1, 6); bool w = false; string Input, Code = Convert.ToString(c1); Code += c2; Code += c3; Code += c4; while (t != 8) { t++; Unepic: Console.Clear(); Console.WriteLine("You have {0} turn(s) left.",9-t); Console.WriteLine("Guess the code E.g 1561: "); Input = Console.ReadLine(); if (Input.Length != 4) goto Unepic; // Checks if input is 4 characters long try { Convert.ToInt16(Input); Convert.ToString(Input); } catch (FormatException) { goto Unepic; } // Checks if input is only numbers if (Input == Code) { w = true; goto End; }; // Checks if you've won if (Input.Contains("0") || Input.Contains("7") || Input.Contains("8") || Input.Contains("9")) { goto Unepic; } // Checks if it has any digits that are 0 or above 7 r = -1; while (r != 3) { r++; if (Input[r] == Code[r]) Console.Write(1); else Console.Write(0); // Checks if a digit of the input is equal to a digit of the code } Console.WriteLine(); Console.Write("Press any key to continue."); Console.ReadKey(true); } End:; Console.Clear(); if (w == true) { Console.WriteLine("You won! The code you guessed was {0}.", Code); } else { Console.WriteLine("You lost! The code you couldnt guess was {0}.",Code); }; Console.ReadKey(true); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T15:05:03.470", "Id": "390876", "Score": "2", "body": "What does \"unepic\" mean? Is that French?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T23:36:28.963", "Id": "390936", "Score": "19", ...
[ { "body": "<p>Don't use meaningless names. <code>GenRandom</code>, <code>t</code>, <code>r</code>, <code>c1</code>,... These don't tell me anything and make your code needlessly obscure.</p>\n\n<hr>\n\n<p>This is not a traditional C# coding style:</p>\n\n<pre><code>string Input, Code = Convert.ToString(c1); Cod...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T10:51:50.903", "Id": "202809", "Score": "24", "Tags": [ "c#", "beginner", "game" ], "Title": "A simple mastermind clone" }
202809
<p>I implemented a doubly linked list in Python. Please tell me what I can do to improve performance, what methods I should add, etc. I gave it the best Big O time perfomance/complexity I could. So, here it is:</p> <pre><code>class DoublyLinkedList(): """ A basic class implementing a doubly linked list. DoublyLinkedList() - new empty linked list DoublyLinkedList(iterable) - new linked list with the items of the iterable: head - iterable[0] tail - iterable[-1] """ class _Node(): """A doubly linked list node class.""" def __init__(self, value): """Initialize default values.""" self._value = value self._next = None self._prev = None def __init__(self, seq=()): """Initialize default values.""" self._head = None self._tail = None self._size = 0 # set default values self.extend(seq) # copy iterables values def __iter__(self): """Implement iter(self).""" node = self._head while node: yield node._value node = node._next def __len__(self): """Implement len(self). Return the number of items in list.""" return self._size def __str__(self): """Define string casting for the list.""" return 'None &lt;= ' + ' &lt;=&gt; '.join(map(str, self)) + ' =&gt; None' def __repr__(self): """Return repr(self).""" return self.__str__() def __contains__(self, item): """Implement 'in' access: if item in.""" for i in self: if i == item: return True return False def __eq__(self, other): """Implement comparison: a == b.""" if type(other) is not type(self): # check if other is dll return False if len(self) != len(other): return False for i, j in zip(self, other): if i != j: return False return True def __getitem__(self, index): """Implement indexing access: a[b].""" # change index if negative index = self._size + index if index &lt; 0 else index if 0 &lt;= index &lt; self._size: for i, item in enumerate(self): if i == index: return item else: raise IndexError('list index out of range') def __setitem__(self, index, item): """Implement indexed assignment.""" # change index if negative index = self._size + index if index &lt; 0 else index if 0 &lt;= index &lt; self._size: i = 0 node = self._head while i &lt; index: node = node._next i += 1 node._value = item else: raise IndexError('list assignment index out of range') def __delitem__(self, index): """Implement indexed deletion.""" # change index if negative if type(index) is not int: raise TypeError('list index must be an integer') index = self._size + index if index &lt; 0 else index if 0 &lt; index &lt; self._size - 1: i = 0 node = self._head while i &lt; index: node = node._next i += 1 node._prev._next = node._next node._next._prev = node._prev self._size -= 1 elif index == 0 and self._head is not None: # case for head self._head = self._head._next self._head._prev = None self._size -= 1 elif index == self._size - 1 and self._head is not None: self._tail = self._tail._prev self._tail._next = None self._size -= 1 else: raise IndexError('list index out of range') def insertStart(self, item): """Insert an item to the _head of the list.""" new_node = self._Node(item) if not self._head: # or if not self._tail self._head = new_node self._tail = new_node else: new_node._next = self._head self._head._prev = new_node self._head = new_node self._size += 1 def insertEnd(self, item): """Insert an item at the _tail of the list.""" new_node = self._Node(item) if not self._tail: # or if not self._head self._tail = new_node self._head = new_node else: new_node._prev = self._tail self._tail._next = new_node self._tail = new_node self._size += 1 def insert(self, index, item): """Insert an item before the specified index.""" t = type(index) if t is not int: raise TypeError('{} cannot be interpreted as an integer'.format(t)) else: # change index if negative index = self._size + index if index &lt; 0 else index if index &gt; self._size - 1: # check for special cases self.insertEnd(item) elif index &lt;= 0: self.insertStart(item) else: # iterate through and insert item i = 0 node = self._head while i &lt; index - 1: node = node._next i += 1 new_node = self._Node(item) new_node._next = node._next new_node._prev = node node._next = new_node new_node._next._prev = new_node self._size += 1 def extend(self, seq=()): """Extend list by appending elements from the iterable.""" for i in seq: self.insertEnd(i) def remove(self, item): """ Remove the first occurence of the value(default _tail). Raises a ValueError if the is not present. Raises an IndexError if the list is empty. """ if not self._head: raise IndexError("remove from an empty list") else: if self._head._value == item: # case for head self._head = self._head._next self._head._prev = None elif self._tail._value == item: # case for tail self._tail = self._tail._prev self._tail._next = None else: node = self._head try: while node._value != item: node = node._next node._prev._next = node._next node._next._prev = node._prev except AttributeError: # mute the original error raise ValueError('value not present in list') from None self._size -= 1 def pop(self, index=-1): """ Remove and return item at specified index (default last). Raises IndexError if list is empty or index is out of range. """ if self._size == 0: # check if list is empty raise IndexError("pop from an empty list") t = type(index) if t is not int: # check if index is integer raise TypeError('{} cannot be interpreted as an integer'.format(t)) item = self[index] # save the item to return del self[index] return item def index(self, item): """Return index of first occurence of specified item. -1 if absent.""" for index, el in enumerate(self): if el == item: return index return -1 def count(self, item): """Return number of occurrences of item.""" count = 0 for i in self: if i == item: count += 1 return count def clear(self): """Remove all the items from the list.""" self._head = None self._tail = None self._size = 0 def reverse(self): """Reverse list in place.""" tmp = None curr = self._head while curr: tmp = curr._prev curr._prev = curr._next curr._next = tmp curr = curr._prev if tmp: self._head = tmp._prev def sort(self): """Sort list in place.""" self._head = self._merge_sort(self._head) def _merge(self, left, right): # merge two lists t_head = self._Node(None) curr = t_head while left and right: if left._value &lt; right._value: curr._next = left left = left._next else: curr._next = right right = right._next curr = curr._next if left is None: curr._next = right if right is None: curr._next = left return t_head._next def _split(self, lst): # split a list if lst is None or lst._next is None: left = lst right = None return left, right else: mid = lst fast = lst._next while fast is not None: fast = fast._next if fast is not None: fast = fast._next mid = mid._next left = lst right = mid._next mid._next = None return left, right def _merge_sort(self, t_head): # merge sort if t_head is None: return t_head if t_head._next is None: return t_head left, right = self._split(t_head) left = self._merge_sort(left) right = self._merge_sort(right) return self._merge(left, right) if __name__ == '__main__': dll = DoublyLinkedList([2, 4, 1, 8, 5, 3]) print(dll) dll.insertEnd(4) dll.insertStart(0) dll.sort() dll.insert(-11, 'start') print(dll) print(dll.pop()) print(dll.pop(2)) dll.remove(4) dll.extend('someiterable') dll.index(8) print(dll.count(4)) print(dll) </code></pre>
[]
[ { "body": "<p>Instead of passing an iterable to the constructor, you could use <code>*values</code> as the argument:</p>\n\n<pre><code> def __init__(self, *values):\n # ... \n self.extend(values)\n</code></pre>\n\n<p>This will allow you to use:</p>\n\n<pre><code>dll = DoublyLinkedList(2, 4, 1, ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T12:53:08.987", "Id": "202813", "Score": "7", "Tags": [ "python", "beginner", "python-3.x", "linked-list" ], "Title": "Doubly Linked List in Python" }
202813
<p>A server sends JSON to my webpage via a socket and the webpage creates or updates a "card" which displays the information from the JSON data. It's a one-way/read-only system.</p> <p>Flow is:</p> <ol> <li>Thing sends data to Server</li> <li>Server receives data and does some things/logic</li> <li>Server sends data via websocket to webpage</li> <li>User opens webpage and connects to server via websocket</li> <li>Webpage receives the message and converts the Json to an object</li> <li><strong>Webpage now passes the data object to some functions to display the data</strong></li> </ol> <p>Here's the general flow for the data: a global array of elements is maintained with all the objects being displays if the object exists, it's updated with new data, if it doesn't, it's created and added to the array. The array it then sorted and then appened to the DOM.</p> <p>Here's the javascript for step 6</p> <pre><code>// JavaScript source code var properties = ["AlarmNumber", "ActiveProgram", "prop1", "prop2", "prop3", "prop4"]; var currentWidget; var widgets = []; //this is the function called when data is received from socket. function CreateBlock(widgetData) { var widgetID = widgetData.MachineID.replace(/ /g,"_"); var myWidget = document.getElementById('widget-' + widgetID); if (myWidget == null) { myWidget = CreateCard(widgetID); UpdateCard(myWidget,widgetData); } else { UpdateCard(myWidget,widgetData);//no card to updatre becuase it doesn't exist yet } widgets.push(myWidget); DrawWidgets(); } function DrawWidgets() { var parent = document.getElementById("Cards"); var currentCard; widgets.sort(compare) for (i = 0; i&lt;=widgets.length;i++) { currentCard = widgets[i]; var oldWidget = document.getElementById(currentCard.id); if (oldWidget !=null) { oldWidget.remove(); //document.removeChild(oldWidget); } parent.appendChild(currentCard); } } function compare(a,b) { var aValue = a.children.cardbody.children.title.innerText var bValue = b.children.cardbody.children.title.innerText; if (aValue &lt; bValue) return -1; if (aValue &gt; bValue) return 1; return 0; } //create the card function CreateCard(cardID) //as object { var parent var newdiv var cardElement = document.createElement("div"); cardElement.className = "card"; cardElement.id = "widget-" + cardID; cardElement.style = "height:500px;"; parent=cardElement; newdiv = document.createElement("div"); newdiv.className = "card-header"; parent.appendChild(newdiv); newdiv = document.createElement("div"); newdiv.className = "card-body"; newdiv.id = "cardbody"; parent.appendChild(newdiv); parent=newdiv; newdiv = document.createElement("div"); newdiv.className = "card-title"; newdiv.id = "title"; newdiv.textContent = "title"; parent.appendChild(newdiv); newdiv = document.createElement("div"); newdiv.className = "card-sub-title"; newdiv.id = "subtitle"; newdiv.textContent = "subtitle"; parent.appendChild(newdiv); newdiv = document.createElement("div"); parent.appendChild(newdiv); return cardElement; } //Add a data element function AddDataElement(myWidget, title, value, showTitle = true) { var cardElement = myWidget; var cardElementBody = cardElement.children.cardbody; var dataElement = cardElementBody.children[title]; if (dataElement == null) { dataElement = document.createElement("div"); dataElement.id = title; dataElement.className = "card-item"; } var output = showTitle == true ? title + ": " + value : value; dataElement.innerText = output; cardElementBody.appendChild(dataElement); } //update the card and set the formatting function UpdateCard(myWidget, widgetData) //myWidget is by reference { var card = myWidget; //some logic with inputs if (widgetData.AlarmNumber != 0) { card.style.backgroundColor = "red"; //".color-primary-0"; //how to apply CSS reference? card.className += " " + "blink-me"; //card.style += ";background-color:.color-primary-0"; } else if (widgetData.ExecutionMode !="Running"){ card.className = "card"; card.style.backgroundColor = "Orange"; } else { card.style.backgroundColor = null; card.className = "card"; } //now populate the data var currentDate = new Date(); var day = currentDate.getDay(); var month = currentDate.getMonth(); //Be careful! January is 0 not 1 var year = currentDate.getFullYear(); var hour = currentDate.getHours(); var min = currentDate.getMinutes(); var sec = currentDate.getSeconds(); var dateString = year + "-" + ZeroPad(month + 1, 2) + "-" + ZeroPad(day,2) + " " + ZeroPad(hour, 2) + ":" + ZeroPad(min, 2) + ":" + ZeroPad(sec, 2); //"MachineID", "RunningMode", AddDataElement(card, "title", widgetData.MachineID,false); AddDataElement(card, "subtitle", widgetData.ExecutionMode,false); var data; for (let i = 0; i &lt; properties.length; i++) { data = widgetData[properties[i]]; AddDataElement(card, properties[i], data); } AddDataElement(card, "Timestamp", dateString); } function ZeroPad(num, places) { var zero = places - num.toString().length + 1; return Array(+(zero &gt; 0 &amp;&amp; zero)).join("0") + num; } </code></pre> <p>note: the webpage uses some CSS from grapeJS.</p> <p>The code is working, but looking for some feedback regarding flow/process or any issues. Does this code follow some best practices? </p>
[]
[ { "body": "<h1>JavaScript conventions.</h1>\n\n<h3>Block delimiting</h3>\n\n<p>Javascript has the opening <code>{</code> on the same line as the statement</p>\n\n<pre><code>// Conventional JS\nif (foo === bar) {\n\n// Un-conventional JS\nif (foo === bar) \n{\n</code></pre>\n\n<h3>Capitalizing</h3>\n\n<p>Unlike ...
{ "AcceptedAnswerId": "202824", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T14:16:33.273", "Id": "202817", "Score": "2", "Tags": [ "javascript", "html", "css", "dom" ], "Title": "IOT Javascript GUI/Hub - Displaying Incoming Data" }
202817
<p>I am getting timeout for test cases having very large input. </p> <p>-= <a href="https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&amp;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=strings" rel="nofollow noreferrer">Challenge Link</a> =-</p> <p>-= <a href="https://hr-testcases-us-east-1.s3.amazonaws.com/71637/input02.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&amp;Expires=1535648224&amp;Signature=5SOqMgWSZSFHFbJWvS0gKLfI9JM%3D&amp;response-content-type=text%2Fplain" rel="nofollow noreferrer">Test case example</a> =-</p> <p>Code is working fine as can be checked on <a href="https://ideone.com/hkfRcY" rel="nofollow noreferrer">ideone</a>. (Note: Here <code>fout</code> has been replaced with <code>cout</code>.)</p> <blockquote> <p><strong>Problem Statement :</strong></p> <p>A string is said to be a special palindromic string if either of two conditions is met:</p> <ul> <li>All of the characters are the same, e.g. aaa.</li> <li>All characters except the middle one are the same, e.g. aadaa.</li> </ul> <p>A special palindromic substring is any substring of a string which meets one of those criteria. Given a string, determine how many special palindromic substrings can be formed from it.</p> <p>For example, given the string s = mnonopoo , we have the following special palindromic substrings: {m, n, o, n, o, p, o, o, non, ono, opo, oo}.</p> <p><strong>Function Description</strong></p> <p>Complete the substrCount function in the editor below. It should return an integer representing the number of special palindromic substrings that can be formed from the given string.</p> <p>substrCount has the following parameter(s):</p> <ul> <li>n: an integer, the length of string s</li> <li>s: a string</li> </ul> <p><strong>Input Format</strong></p> <p>The first line contains an integer, n , the length of s. The second line contains the string .</p> <p><strong>Constraints</strong></p> <p>1 ≤ n ≤ 10^6</p> <p>Each character of the string is a lowercase alphabet, ascii[a-z].</p> <p><strong>Output Format</strong></p> <p>Print a single line containing the count of total special palindromic substrings.</p> <p><strong>Sample Input 0</strong></p> <pre><code>5 asasd </code></pre> <p><strong>Sample Output 0</strong></p> <pre><code>7 </code></pre> <p><strong>Explanation 0</strong></p> <p>The special palindromic substrings of s = asasd are {a, s, a, s, d, asa, sas}. </p> <p><strong>Sample Input 1</strong></p> <pre><code>7 abcbaba </code></pre> <p><strong>Sample Output 1</strong></p> <pre><code>10 </code></pre> <p><strong>Explanation 1</strong></p> <p>The special palindromic substrings of s = abcbaba are {a, b, c, b, a, b, a, bcb, bab, aba}.</p> <p><strong>Sample Input 2</strong></p> <pre><code>4 aaaa </code></pre> <p><strong>Sample Output 2</strong></p> <pre><code>10 </code></pre> <p><strong>Explanation 2</strong></p> <p>The special palindromic substrings of s = aaaa are {a, a, a, a, aa, aa, aa, aaa, aaa, aaaa}.</p> </blockquote> <p><strong>Code:</strong></p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; // Complete the substrCount function below. long substrCount(int n, string s) { long int length_sub = 2; long int count = n; while(length_sub &lt;= n){ for(long int i = 0; i &lt;= n - length_sub ; i++){ string sub = s.substr(i, length_sub); //cout &lt;&lt; sub &lt;&lt; " "; string rev_sub(sub); reverse(rev_sub.begin(), rev_sub.end()); //cout &lt;&lt; rev_sub;; char c = sub[0]; int flag = 0; for(long int j = 0; j &lt; sub.length() / 2; j++){ if(sub[j] != c || rev_sub[j] != c){ flag = 1; break; } } if(flag == 0){ //cout &lt;&lt; " - Special\n"; count++; } // else{ // cout &lt;&lt; "\n"; // } } length_sub++; } return count; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin &gt;&gt; n; cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); string s; getline(cin, s); long result = substrCount(n, s); fout &lt;&lt; result &lt;&lt; "\n"; fout.close(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T15:26:49.670", "Id": "390883", "Score": "1", "body": "Not sure it belongs here... codereview isn't about improving algorithms as far as I know. That said, a hint: don't create an endless stream of substrings when you can use iterato...
[ { "body": "<p>This</p>\n\n<pre><code>#include &lt;bits/stdc++.h&gt;\nusing namespace std;\n</code></pre>\n\n<p>is given by the submission template from HackerRank (so it is not your fault),\nbut note that both lines are generally considered as bad practice.\nSee for example</p>\n\n<ul>\n<li><a href=\"https://st...
{ "AcceptedAnswerId": "202840", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T15:04:49.357", "Id": "202820", "Score": "7", "Tags": [ "c++", "algorithm", "programming-challenge", "time-limit-exceeded", "c++14" ], "Title": "Hacker Rank Challenge : Find count of substrings which are special palindrome" }
202820
<p>I am working on a Master List, where I am copying data from various sources for each month into the columns Z, AC, AF, AI etc. (always separated by 2 columns). Then I copy that cell all the way down to update the values for each row. As you can see in the code below, the only difference from one section of the code to the next is:</p> <ul> <li>Change column (here Z to AC)</li> <li>Change paths which are stored in different cells (e.g. <code>fromPath</code> changed to <code>fromPath2</code>.</li> </ul> <p>How can I make it more efficient?</p> <pre><code>' Update Jan 2018 fromPath = Sheets("Filepaths for P25 2017").Range("G2") vbaPath = Sheets("Filepaths for P25 2017").Range("F2") vbaFile = Sheets("Filepaths for P25 2017").Range("H2") Orderlist2017 = Sheets("Filepaths for P25 2017").Range("I2") With ThisWorkbook.Sheets("Orderlist P25 2017") Range("Z10").Formula = "=VLookup(C10, '" &amp; vbaPath &amp; vbaFile &amp; Orderlist2017 &amp; "'!C14:Z90, 8, False)" Range("Z10").Select Selection.Copy Range("Y10").Select Selection.End(xlDown).Select Range("Z85").Select Range(Selection, Selection.End(xlUp)).Select ActiveSheet.Paste Application.CutCopyMode = False End With ' Update Feb 2018 fromPath2 = Sheets("Filepaths for P25 2017").Range("G3") vbaPath2 = Sheets("Filepaths for P25 2017").Range("F3") vbaFile2 = Sheets("Filepaths for P25 2017").Range("H3") Orderlist2017 = Sheets("Filepaths for P25 2017").Range("I3") With ThisWorkbook.Sheets("Orderlist P25 2017") Range("AC10").Formula = "=VLookup(C10, '" &amp; vbaPath2 &amp; vbaFile2 &amp; Orderlist2017 &amp; "'!C14:Z90, 8, False)" Range("AC10").Select Selection.Copy Range("Y10").Select Selection.End(xlDown).Select Range("AC85").Select Range(Selection, Selection.End(xlUp)).Select ActiveSheet.Paste Application.CutCopyMode = False End With </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T16:10:18.120", "Id": "390889", "Score": "1", "body": "[How to avoid using .Select](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) would be a great start." }, { "ContentLicense": "CC BY-S...
[ { "body": "<p>This: </p>\n\n<pre><code>With ThisWorkbook.Sheets(\"Orderlist P25 2017\")\nRange(\"Z10\").Formula = \"=VLookup(C10, '\" &amp; vbaPath &amp; vbaFile &amp; Orderlist2017 &amp; \"'!C14:Z90, 8, False)\"\nRange(\"Z10\").Select\n Selection.Copy\n Range(\"Y10\").Select\n Selection.End(xlDown).S...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T16:03:09.117", "Id": "202822", "Score": "2", "Tags": [ "performance", "vba", "excel" ], "Title": "Copying data from various sources into a master list" }
202822
<p>I've created a simple API wrapper that I intend a few developers to utilize. I decided to follow an Fluent Interface methodology, similar to <a href="https://scottlilly.com/how-to-create-a-fluent-interface-in-c/" rel="nofollow noreferrer">this</a>.</p> <pre><code>public class SalesAPI { private HttpClient _client; private string _url; private List&lt;string&gt; CompanyNums; private List&lt;string&gt; CustBillToCodes; private List&lt;string&gt; CustShipToCodes; private List&lt;string&gt; CustPONum; private List&lt;string&gt; Warehouse; private List&lt;string&gt; ProdNum; private string StartDeliveryDate; private string EndDeliveryDate; private string StartShipDate; private string EndShipDate; private string StartPickDate; private string EndPickDate; private string Status; private JObject _request; public SalesAPI(string url) { _request = new JObject(); _client = new HttpClient(); _url = url; _request["appId"] = "APISALES"; _request["command"] = "getSalesOrderDetails"; _request["username"] = HttpContext.Current.User.Identity.GetShortADName(); } public SalesAPI SetProdNum(List&lt;string&gt; prodNums) { ProdNum = prodNums; return this; } public SalesAPI SetProdNum(string prodNum) { ProdNum = new List&lt;string&gt;(new string[] { prodNum }); return this; } public SalesAPI SetCompany(List&lt;string&gt; companies) { CompanyNums = companies; return this; } public SalesAPI SetCompany(string company) { CompanyNums = new List&lt;string&gt;(new string[] { company }); return this; } public SalesAPI SetBillToCustCode(List&lt;string&gt; custCodes) { CustBillToCodes = custCodes; return this; } public SalesAPI SetBillToCustCode(string custCode) { CustBillToCodes = new List&lt;string&gt;(new string[] { custCode }); return this; } public SalesAPI SetCustPONum(List&lt;string&gt; custPONums) { CustPONum = custPONums; return this; } public SalesAPI SetCustPONum(string custPONum) { CustPONum = new List&lt;string&gt;(new string[] { custPONum }); return this; } public SalesAPI SetWarehouse(List&lt;string&gt; warehouses) { Warehouse = warehouses; return this; } public SalesAPI SetWarehouse(string warehouse) { Warehouse = new List&lt;string&gt;(new string[] { warehouse }); return this; } public SalesAPI SetShipToCustCode(List&lt;string&gt; custCodes) { CustShipToCodes = custCodes; return this; } public SalesAPI SetShipToCustCode(string custCode) { CustShipToCodes = new List&lt;string&gt;() { custCode }; return this; } public SalesAPI SetDeliveryDateRange(DateTime start, DateTime end) { StartDeliveryDate = start.ToPPROFormattedDate(); EndDeliveryDate = end.ToPPROFormattedDate(); return this; } public SalesAPI SetShipDateRange(DateTime start, DateTime end) { StartShipDate = start.ToPPROFormattedDate(); EndShipDate = end.ToPPROFormattedDate(); return this; } public SalesAPI SetPickDateRange(DateTime start, DateTime end) { StartPickDate = start.ToPPROFormattedDate(); EndPickDate = end.ToPPROFormattedDate(); return this; } public SalesAPI SetStatus(string status) { Status = status; return this; } private SalesAPI SetParameters() { JArray companyNumArray = new JArray(CompanyNums); JArray custBillToArray = new JArray(CustBillToCodes); JArray custShipToArray = new JArray(CustShipToCodes); JArray custPOArray = new JArray(CustPONum); JArray warehouseArray = new JArray(Warehouse); JArray prodNumArray = new JArray(ProdNum); if (CompanyNums != null) { _request["company"] = companyNumArray; } if (CustBillToCodes != null) { _request["custPOBillToID"] = custBillToArray; } if (CustShipToCodes != null) { _request["custShipToID"] = custShipToArray; } if (CustPONum != null) { _request["custPONum"] = custPOArray; } if (Warehouse != null) { _request["warehouse"] = warehouseArray; } if (StartDeliveryDate != null) { _request["startDeliveryDate"] = StartDeliveryDate; } if (EndDeliveryDate != null) { _request["endDeliveryDate"] = EndDeliveryDate; } if (StartShipDate != null) { _request["startShipDate"] = StartShipDate; } if (EndShipDate != null) { _request["endShipDate"] = EndShipDate; } if (StartPickDate != null) { _request["startPickDate"] = StartPickDate; } if (EndPickDate != null) { _request["endPickDate"] = EndPickDate; } if (Status != null) { _request["status"] = Status; } if (ProdNum != null) { _request["productNum"] = prodNumArray; } return this; } public async Task&lt;RootSalesOrderObject&gt; GetSalesOrderDetailsAsync() { SetParameters(); var content = new StringContent(_request.ToString(Formatting.None), Encoding.UTF8, "application/json"); var response = await _client.PostAsync(_url, content); var contents = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject&lt;RootSalesOrderObject&gt;(contents); } } </code></pre> <p>Here is how the api is consumed:</p> <pre><code> var salesAPI = new SalesAPI("https://xxxxx.xxxxx.com/yyyyy/services"); var companies = new List&lt;string&gt;() { "0002", "0007", "0009" }; return await salesAPI .SetCompany(companies) .SetDeliveryDateRange(DateTime.Now.AddDays(-3), DateTime.Now.AddDays(3)) .SetProdNum("17876") .GetSalesOrderDetailsAsync(); </code></pre> <p>Let me know what improvement you think could be made or if you think it is sufficient as is. Do you think this follows best practices and is relatively easy to understand for other developers who may need to use it?</p>
[]
[ { "body": "<p>That <code>SalesAPI</code> is doing way too much. Which violates Single Responsibility Principle (SRP). The fluent interface also feels like over engineering but it can still be workable with some modifications to the current design.</p>\n\n<p>My first suggestion would be to simplify the main cla...
{ "AcceptedAnswerId": "202865", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T17:22:54.347", "Id": "202825", "Score": "1", "Tags": [ "c#", "api", "asp.net-mvc", "wrapper", "fluent-interface" ], "Title": "Wrapper for a sales API, with a fluent interface" }
202825
<p>I did not like that <code>get</code> synchronizes every time I call it - because I may be calling it more than once. So I wrote the wrapper for the future interface which keeps not synchronized local variable for completion state and caches the result. I am very sure it is thread safe. Please have a look:</p> <pre><code>package i; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.RunnableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class FutureTaskWrapper&lt;V&gt; implements RunnableFuture&lt;V&gt; { private FutureTask&lt;V&gt; localFuture; private V result; //this one is not synchronized on purpose. It does not have to be. //It will either use wrapped class' done mechanism or eventually will update and it will use cached result. private boolean done = false; public FutureTaskWrapper(FutureTask&lt;V&gt; instance) { localFuture = instance; } @Override public void run() { localFuture.run(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return localFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return localFuture.isCancelled(); } @Override public boolean isDone() { if (done) { return true; } else { return localFuture.isDone(); } } @Override public V get() throws InterruptedException, ExecutionException { if (done) { System.out.println("using cached version."); return result; } else { System.out.println("using version version from future."); result = localFuture.get(); done = true; return result; } } @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (done) { System.out.println("using cached version."); return result; } else { System.out.println("using version version from future."); result = localFuture.get(timeout, unit); //could clean up localFuture here. done = true; return result; } } //main method for testing. public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); FutureTask&lt;String&gt; future = new FutureTask&lt;&gt;(() -&gt; { Thread.sleep(1000L); return "future"; }); FutureTaskWrapper&lt;String&gt; wrapper = new FutureTaskWrapper(future); executor.submit(future); wrapper.get(); wrapper.get(); wrapper.get(); wrapper.get(); executor.shutdownNow(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T15:54:28.377", "Id": "396598", "Score": "0", "body": "there is a new improved version of this class here: https://codereview.stackexchange.com/questions/205610/futuretaskwrapper-for-java-v2 please have a look." } ]
[ { "body": "<blockquote>\n <p>I am very sure it is thread safe. </p>\n</blockquote>\n\n<p>Actually, it's not because the <code>done</code> is not in happens-before relations with the <code>result</code>.</p>\n\n<p>But you can reach the desired behavior without extending anything: just check <code>isDone()</code...
{ "AcceptedAnswerId": "205419", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T17:32:55.170", "Id": "202826", "Score": "3", "Tags": [ "java", "concurrency", "wrapper" ], "Title": "FutureTaskWrapper for Java" }
202826
<p>I have a small JS application that allows a user, after clicking on a canvas, to draw a picture.</p> <p>Once the user clicks the mouse, the user is allowed to drag the mouse wherever they want within the canvas and a line will be drawn from where they started moving the mouse to where the mouse stopped.</p> <p>Only by clicking again will the drawing cease.</p> <p>The code I have for this is below, and one concern of mine is how I'm storing the coordinates of the mouse's position each time it moves.</p> <pre><code>var draw = false; var coords = []; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.addEventListener('click', function (event) { coords = []; draw = !draw; }); canvas.addEventListener('mousemove', function (event) { if (draw) { context = canvas.getContext("2d"); var coord = { 'x': event.x - this.offsetLeft, 'y': event.y - thisoffsetTop }; coords.push(coord); var max = coords.length - 1; if (typeof coords[max - 1] !== "undefined") { var curr = coords[max], prev = coords[max - 1]; context.beginPath(); context.moveTo(prev.x, prev.y); context.lineTo(curr.x, curr.y); context.stroke(); } } }); </code></pre> <p>I have a feeling that I could be storing the coordinates more efficiently, rather than just add them to an ever-increasing <code>Array</code>. Is this the right approach, or is there a more efficient way of handling this sort of storage?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T18:14:33.390", "Id": "390906", "Score": "0", "body": "Do you need the coordinates later for something, like storing them on a server? With the code as-is, you do not need to store all coordinates at all: only the previous one in ord...
[ { "body": "<p>Inside the <code>if (typeof coords[max - 1] !== \"undefined\")</code> loop, adding the following two lines will ensure that only two pairs of coordinates are kept inside <code>coords</code> when drawing</p>\n\n<pre><code>if (typeof coords[max - 1] !== \"undefined\") {\n var curr = coords[max], ...
{ "AcceptedAnswerId": "202836", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T18:10:23.413", "Id": "202830", "Score": "2", "Tags": [ "javascript", "array", "canvas" ], "Title": "Javascript: Canvas drawing - storing mouse coordinates" }
202830
<p>I have decided to rewrite what I did <a href="https://codereview.stackexchange.com/questions/197387/generic-stack-data-structure-using-linked-lists-follow-up">here</a>, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate.</p> <p>I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community in their effort in evaluating my code, I really appreciate it and I believe it is slowly but surely taking my coding skills to the next level.</p> <p>Here is my header file:</p> <pre><code>#ifndef Stack_h #define Stack_h #include &lt;iterator&gt; #include &lt;memory&gt; template &lt;class T&gt; class Stack { struct Node { T data; std::unique_ptr&lt;Node&gt; next = nullptr; template&lt;typename... Args, typename = std::enable_if_t&lt;std::is_constructible&lt;T, Args&amp;&amp;...&gt;::value&gt;&gt; explicit Node(std::unique_ptr&lt;Node&gt;&amp;&amp; next, Args&amp;&amp;... args) noexcept(std::is_nothrow_constructible&lt;T, Args&amp;&amp;...&gt;::value) : data{ std::forward&lt;Args&gt;(args)... }, next{ std::move(next) } {} // disable if noncopyable&lt;T&gt; for cleaner error msgs explicit Node(const T&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(x) , next(std::move(p)) {} // disable if nonmovable&lt;T&gt; for cleaner error msgs explicit Node(T&amp;&amp; x, std::unique_ptr&lt;Node&gt;&amp;&amp; p = nullptr) : data(std::move(x)) , next(std::move(p)) {} }; std::unique_ptr&lt;Node&gt; front = nullptr; void do_unchecked_pop() { front = std::move(front-&gt;next); } public: // Constructors Stack() = default; // empty constructor Stack(Stack const &amp;source); // copy constructor // Rule of 5 Stack(Stack &amp;&amp;move) noexcept; // move constructor Stack&amp; operator=(Stack &amp;&amp;move) noexcept; // move assignment operator ~Stack(); // Overload operators Stack&amp; operator=(Stack const &amp;rhs); // Create an iterator class class iterator; iterator begin(); iterator end(); iterator before_begin(); // Create const iterator class class const_iterator; const_iterator cbegin() const; const_iterator cend() const; const_iterator begin() const; const_iterator end() const; const_iterator before_begin() const; const_iterator cbefore_begin() const; // Member functions template&lt;typename... Args&gt; iterator emplace(const_iterator pos, Args&amp;&amp;... args); void swap(Stack&amp; other) noexcept; bool empty() const {return front == nullptr;} int size() const; void push(const T&amp; theData); void push(T&amp;&amp; theData); T&amp; top(); const T&amp; top() const; void pop(); }; template &lt;class T&gt; class Stack&lt;T&gt;::iterator { Node* node = nullptr; bool before_begin = false; public: friend class Stack&lt;T&gt;; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T * ; using reference = T &amp; ; operator const_iterator() const noexcept { return const_iterator{ node }; } iterator(Node* node = nullptr, bool before = false) : node{ node }, before_begin{ before } {} bool operator!=(iterator other) const noexcept; bool operator==(iterator other) const noexcept; T&amp; operator*() const { return node-&gt;data; } T&amp; operator-&gt;() const { return &amp;node-&gt;data; } iterator&amp; operator++(); iterator operator++(int); }; template &lt;class T&gt; class Stack&lt;T&gt;::const_iterator { Node* node = nullptr; bool before_begin = false; public: friend class Stack&lt;T&gt;; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = const T * ; using reference = const T &amp; ; const_iterator() = default; const_iterator(Node* node, bool before = false) : node{ node }, before_begin{ before } {} bool operator!=(const_iterator other) const noexcept; bool operator==(const_iterator other) const noexcept; const T&amp; operator*() const { return node-&gt;data; } const T&amp; operator-&gt;() const { return &amp;node-&gt;data; } const_iterator&amp; operator++(); const_iterator operator++(int); }; template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack&lt;T&gt; const&amp; source) { try { for(auto loop = source.front.get(); loop != nullptr; loop = loop-&gt;next.get()) push(loop-&gt;data); } catch (...) { while(front != nullptr) do_unchecked_pop(); throw; } } template &lt;class T&gt; Stack&lt;T&gt;::Stack(Stack&amp;&amp; move) noexcept { move.swap(*this); } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack&amp;&amp; move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; Stack&lt;T&gt;::~Stack() { while(front != nullptr) { do_unchecked_pop(); } } template &lt;class T&gt; Stack&lt;T&gt;&amp; Stack&lt;T&gt;::operator=(Stack const&amp; rhs) { Stack copy(rhs); swap(copy); return *this; } template &lt;class T&gt; void Stack&lt;T&gt;::swap(Stack&amp; other) noexcept { using std::swap; swap(front,other.front); } template &lt;class T&gt; template &lt;typename... Args&gt; typename Stack&lt;T&gt;::iterator Stack&lt;T&gt;::emplace(const_iterator pos, Args&amp;&amp;... args) { if (pos.before_begin) { emplace_front(std::forward&lt;Args&gt;(args)...); return begin(); } if (pos.node-&gt;next) { pos.node-&gt;next = std::make_unique&lt;Node&gt;(std::move(pos.node-&gt;next), std::forward&lt;Args&gt;(args)...); // Creating a new node that has the old next pointer with the new value and assign it to the next pointer of the current node return { pos.node-&gt;next.get() }; } } // Free function template &lt;typename T&gt; void swap(Stack&lt;T&gt;&amp; a, Stack&lt;T&gt;&amp; b) noexcept { a.swap(b); } template &lt;class T&gt; int Stack&lt;T&gt;::size() const { int size = 0; for (auto current = front.get(); current != nullptr; current = current-&gt;next.get()) size++; return size; } template &lt;class T&gt; void Stack&lt;T&gt;::push(const T&amp; theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(theData); if(front) { newNode-&gt;next = std::move(front); } front = std::move(newNode); } template &lt;class T&gt; void Stack&lt;T&gt;::push(T&amp;&amp; theData) { std::unique_ptr&lt;Node&gt; newNode = std::make_unique&lt;Node&gt;(std::move(theData)); if(front) { newNode-&gt;next = std::move(front); } front = std::move(newNode); } template &lt;class T&gt; T&amp; Stack&lt;T&gt;::top() { if(!empty()) { return front-&gt;data; } else { throw std::out_of_range("The stack is empty!"); } } template &lt;class T&gt; const T&amp; Stack&lt;T&gt;::top() const { if(!empty()) { return front-&gt;data; } else { throw std::out_of_range("The stack is empty!"); } } template &lt;class T&gt; void Stack&lt;T&gt;::pop() { if(empty()) { throw std::out_of_range("The stack is empty!"); } do_unchecked_pop(); } // Iterator Implementaion//////////////////////////////////////////////// template &lt;class T&gt; typename Stack&lt;T&gt;::iterator&amp; Stack&lt;T&gt;::iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename Stack&lt;T&gt;::iterator Stack&lt;T&gt;::iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; bool Stack&lt;T&gt;::iterator::operator==(iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool Stack&lt;T&gt;::iterator::operator!=(iterator other) const noexcept { return !(*this == other); } template&lt;class T&gt; typename Stack&lt;T&gt;::iterator Stack&lt;T&gt;::begin() { return front.get(); } template&lt;class T&gt; typename Stack&lt;T&gt;::iterator Stack&lt;T&gt;::end() { return {}; } template &lt;class T&gt; typename Stack&lt;T&gt;::iterator Stack&lt;T&gt;::before_begin() { return { front.get(), true }; } // Const Iterator Implementaion//////////////////////////////////////////////// template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator&amp; Stack&lt;T&gt;::const_iterator::operator++() { if (before_begin) before_begin = false; else node = node-&gt;next.get(); return *this; } template&lt;typename T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::const_iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template&lt;typename T&gt; bool Stack&lt;T&gt;::const_iterator::operator==(const_iterator other) const noexcept { return node == other.node &amp;&amp; before_begin == other.before_begin; } template&lt;typename T&gt; bool Stack&lt;T&gt;::const_iterator::operator!=(const_iterator other) const noexcept { return !(*this == other); } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::begin() const { return front.get(); } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::end() const { return {}; } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::cbegin() const { return begin(); } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::cend() const { return end(); } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::before_begin() const { return { front.get(), true }; } template &lt;class T&gt; typename Stack&lt;T&gt;::const_iterator Stack&lt;T&gt;::cbefore_begin() const { return before_begin(); } #endif /* Stack_h */ </code></pre> <p>Here is the test cpp file I used:</p> <pre><code>#define CATCH_CONFIG_MAIN #include "catch.h" #include "Stack.h" TEST_CASE("An empty stack", "[Stack]") { Stack&lt;int&gt; stack; REQUIRE(stack.empty()); REQUIRE(stack.size() == 0u); SECTION("inserting an element makes the map not empty") { stack.push(2); REQUIRE(!stack.empty()); } SECTION("inserting an element increases the size") { stack.push(4); REQUIRE(stack.size() == 1u); } SECTION("pop on empty stack does nothing") { stack.push(6); stack.pop(); REQUIRE(stack.size() == 0); REQUIRE(stack.empty()); } } TEST_CASE("Create a stack list with multiple elements", "[Stack]") { Stack&lt;int&gt; stack; stack.push(2); stack.push(4); stack.push(6); stack.push(8); stack.push(10); static auto init_values = std::vector&lt;int&gt;{2, 4, 6, 8, 10}; REQUIRE(stack.size() == init_values.size()); REQUIRE(!stack.empty()); REQUIRE(std::distance(stack.begin(), stack.end()) == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); SECTION("Can find elements with std::find") { auto found = std::find(std::begin(stack), std::end(stack), 4); REQUIRE(found != std::end(stack)); REQUIRE(*found == 4); } SECTION("pop removes last element") { stack.pop(); REQUIRE(stack.top() == 8); REQUIRE(stack.size() == 4); } SECTION("copy construction") { auto second_list = stack; REQUIRE(stack.size() == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); REQUIRE(second_list.size() == stack.size()); //REQUIRE(std::equal(second_list.begin(), second_list.end(), stack.begin())); } SECTION("copy assignment") { auto second_list = Stack&lt;int&gt;{}; second_list = stack; REQUIRE(stack.size() == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); REQUIRE(second_list.size() == stack.size()); //REQUIRE(std::equal(second_list.begin(), second_list.end(), stack.begin())); } SECTION("move construction leaves original list in empty state") { auto second_list = Stack&lt;int&gt;{ std::move(stack) }; REQUIRE(stack.empty()); REQUIRE(second_list.size() == init_values.size()); // REQUIRE(std::equal(second_list.begin(), second_list.end(), init_values.begin())); } } </code></pre> <p>For tests, I used the <a href="https://github.com/catchorg/Catch2" rel="nofollow noreferrer">Catch2 testing framework</a>. I guess the only problem I had was the std::equal() but other than that I am satisfied with the tests it passed.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T18:14:22.387", "Id": "202831", "Score": "3", "Tags": [ "c++", "stack", "pointers" ], "Title": "Generic stack data structure using linked list and smart pointers" }
202831
<p>I had been working on the implementation of closest pair algorithm in a 2-D plane.</p> <p>My approach has been that of divide and conquer O(nlogn) : </p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;cmath&gt; using namespace std; int getval(int size) { if (size &lt; 15) return size; else return 15; } struct point { int x, y; }; struct point_pair { point a, b; }; bool compare_x(point &amp;a, point &amp;b) { if (a.x &lt; b.x) return true; else return false; } bool compare_y(point &amp;a, point &amp;b) { if (a.y &lt; b.y) return true; else return false; } //calculates distance between a pair of points double calc_distance(point_pair pair) { int k1 = abs(pair.a.x - pair.b.x); int k2 = abs(pair.a.y - pair.b.y); size_t k3 = k1 * k1; size_t k4 = k2 * k2; size_t k5 = k3 + k4; return sqrt(k5); } point_pair minimal_distance_naive(vector&lt;point&gt; points) { point_pair min; min.a = points[0]; min.b = points[1]; for (int i = 0; i &lt; points.size(); i++) { point_pair temp; temp.a = points[i]; for (int j = i + 1; j &lt; points.size(); j++) { temp.b = points[j]; if (calc_distance(temp) &lt; calc_distance(min)) { min = temp; } } } return min; } point_pair minimal_distance_rec(vector&lt;point&gt; points_x, vector&lt;point&gt; points_y) { if (points_x.size() &lt;= 3) { return minimal_distance_naive(points_x); } else { int mid = points_x.size() / 2; vector&lt;point&gt; left_x, left_y; vector&lt;point&gt; right_x, right_y; for (int i = 0; i &lt; mid; i++) { left_x.push_back(points_x[i]); } for (int i = mid; i &lt; points_x.size(); i++) { right_x.push_back(points_x[i]); } int middle = points_x[mid - 1].x; for (int i = 0; i &lt; points_y.size(); i++) { if (points_y[i].x &lt;= middle) { left_y.push_back(points_y[i]); } else { right_y.push_back(points_y[i]); } } point_pair left = minimal_distance_rec(left_x, left_y); point_pair right = minimal_distance_rec(right_x, right_y); double d_left = calc_distance(left); double d_right = calc_distance(right); point_pair min; double min_distance; if (d_left &lt;= d_right) { min_distance = d_left; min = left; } else { min_distance = d_right; min = right; } vector&lt;point&gt; middle_set; for (int i = 0; i &lt; points_y.size(); i++) { if (abs(points_y[i].x - middle) &lt;= min_distance) { middle_set.push_back(points_y[i]); } } if (middle_set.size() &lt; 2) { return min; } point_pair init; init.a = middle_set[0]; init.b = middle_set[1]; double k = 0, m = calc_distance(init); point_pair tmp, min_tmp = init; for (int i = 0; i &lt; middle_set.size(); i++) { tmp.a = middle_set[i]; for (int j = i + 1; j &lt;= getval(middle_set.size() - 1); j++) { tmp.b = middle_set[j]; k = calc_distance(tmp); if (k &lt; m) { m = k; min_tmp = tmp; } } } if (min_distance &lt; m) return min; else return min_tmp; } } double minimal_distance(vector&lt;int&gt; x, vector&lt;int&gt; y) { vector&lt;point&gt; points(x.size()); for (int i = 0; i &lt; x.size(); i++) { points[i].x = x[i]; points[i].y = y[i]; } sort(points.begin(), points.end(), compare_x); vector&lt;point&gt; points_x = points; sort(points.begin(), points.end(), compare_y); vector&lt;point&gt; points_y = points; point_pair p = minimal_distance_rec(points_x, points_y); return calc_distance(p); } int main() { size_t n; std::cin &gt;&gt; n; vector&lt;int&gt; x(n); vector&lt;int&gt; y(n); for (size_t i = 0; i &lt; n; i++) { cin &gt;&gt; x[i] &gt;&gt; y[i]; } cout &lt;&lt; fixed; cout &lt;&lt; setprecision(9) &lt;&lt; minimal_distance(x, y) &lt;&lt; "\n"; } </code></pre> <p><strong>Input:</strong> <em>n</em> number of points, followed by <em>n</em> lines of coordinates, <em>x</em> followed by <em>y</em> </p> <p><strong>Output:</strong> <em>k</em> minimum distance</p> <p>The code works fine for inputs in small range, like: <code>-100 &lt;= x, y &lt;= 100</code>. How can I make it work for large inputs, say in the range: <code>-1000000000 &lt;= x,y &lt;= 1000000000</code> ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T13:19:33.660", "Id": "391032", "Score": "1", "body": "In what sense does it not work for large inputs? Does it take forever or does it throw some error while compiling or running the code?" }, { "ContentLicense": "CC BY-SA 4...
[ { "body": "<p>Your code can be improved in regard to its efficiency and its readability. But first of all, <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">don't write that <code>using namespace std</code></a>.</p>\n\n<h2>Efficiency</h2>\n\n<p>You create...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T18:18:02.287", "Id": "202832", "Score": "6", "Tags": [ "c++", "algorithm", "clustering", "divide-and-conquer" ], "Title": "Closest Pair algorithm implementation in C++" }
202832
<p>A simple neural network I wrote in Python without libraries. I avoided implementing it in matrix form because I sought to get a basic understanding of the way NN's work first. For that reason I'm strongly favoring legibility over efficiency. I tried to keep my code readable and pyhonic, any style feedback would be particularly appreciated.</p> <p>A quirk about this design is it does back propagation on a per training example basis and uses momentum to try and avoid over fitting to specific examples. Also I realized I never added base values to the neurons, it seems to work alright with out them but if anyone has a more in depth understanding of why you'd want them I'd be curious to hear about that.</p> <pre><code>import math import random import data def sigmoid(x): return 1 / (1 + math.exp(-x)) def sigmoid_prime(x): return x * (1.0 - x) def loss(x,y): return sum([(a-b)**2 for (a,b) in zip(x,y)]) class Neuron(): learning_rate = 0.015 momentum_loss = 0.03 def __init__(self, input_neurons): self.weights = [random.uniform(-1,1) for _ in range(input_neurons)] self.momentum = [0 for _ in range(input_neurons)] def forward(self, inputs): dot = sum([x*y for (x,y) in zip(inputs, self.weights)]) self.output = sigmoid(dot) return self.output def backpropagate(self, inputs, error): error_values = list() gradient = error * sigmoid_prime(self.output) for i, inp in enumerate(inputs): self.nudge_weight(i, gradient * inp) error_values.append(self.weights[i] * gradient) return error_values def nudge_weight(self, weight, amount): change = amount * Neuron.learning_rate self.momentum[weight] += change self.momentum[weight] *= (1 - Neuron.momentum_loss) self.weights[weight] += change + self.momentum[weight] class Network(): def __init__(self, topology): self.layers = list() for i in range(1,len(topology)): self.layers.append([Neuron(topology[i-1]) for _ in range(topology[i])]) def forward(self, data): output = data for layer in self.layers: output = [neuron.forward(output) for neuron in layer] return output def backpropagate(self, data, output, target): error_values = [tval - output for (tval, output) in zip(target, output)] for i in range(len(self.layers)-1,0,-1): layer_output = [neuron.output for neuron in self.layers[i-1]] error_values = self.backpropagate_layer(i, error_values, layer_output) self.backpropagate_layer(0, error_values, data) def backpropagate_layer(self, layer, error_values, inputs): next_errors = list() for neuron, error in zip(self.layers[layer], error_values): bp_error = neuron.backpropagate(inputs,error) if not next_errors: next_errors = bp_error else: next_errors = [a+b for a,b in zip(next_errors,bp_error)] return next_errors </code></pre> <p>The full source code for project including the data base and some other testing code can be found here: <a href="https://github.com/RowanL3/Neural-Network/tree/d1e36d5e8277b44040aae6ffdad94fd4a21235c3" rel="noreferrer">https://github.com/RowanL3/Neural-Network</a></p>
[]
[ { "body": "<p>A more pythonic way of writing <code>self.momentum = [0 for _ in range(input_neurons)]</code> would be <code>self.momentum = [0]*input_neurons</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T18:58:19.877", "Id": "202837", "Score": "6", "Tags": [ "python", "ai", "machine-learning", "neural-network" ], "Title": "Simple neural network implementation in Python" }
202837
<p>I have been working on a small game lately and I was tired of looking up and copy-pasting game loops so I tried to make one as you can see. It works perfectly so if you want to feel free to use it, but for those who are good at making these I would like to ask if I can improve it, make it more efficient and overall is it a good solution to run two of these one to render, the other to tick.</p> <pre><code>package engine; public abstract class RapidExecutor extends Thread { Application app; /* the field app is here because the abstract tick method can only acces the stuff needed to render or to tick objects so if you want to use it for anything else you can just delete it */ private final int TPS; private boolean running; public RapidExecutor(Application app, int TPS) { this.app = app; this.TPS = TPS; if (TPS &gt; 1000 || TPS &lt; 1) try { throw new Exception("Invalid TPS count"); } catch (Exception e) { e.printStackTrace(); } } public abstract void tick(); public void run() { try { this.running = true; long now, startTime; int delta, TPSCount = 1000 / this.TPS; while (this.running) { startTime = System.currentTimeMillis(); tick(); now = System.currentTimeMillis(); delta = (int) (TPSCount - (now - startTime)); if (delta &lt; 0) this.stopThread(); sleep(delta); } } catch (Exception e) { e.printStackTrace(); } } public synchronized void stopThread() { try { this.running = false; this.join(); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>Feel free to use the code and if you have any thoughts I would be very glad to hear them.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T20:38:20.223", "Id": "390924", "Score": "1", "body": "I see that you wrote a comment that tries to explain what `Application app` is for, but I don't understand what you mean. Maybe an example subclass would help." }, { "Con...
[ { "body": "<p>Before reviewing the code, I want to point out that this kind of functionality already exists in the core Java libraries. A <code>ScheduledExecutorService</code> will run an arbitrary <code>Runnable</code> on a fixed time schedule. Instead of extending <code>RapidExecutor</code>, you just implemen...
{ "AcceptedAnswerId": "202881", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-30T19:08:38.407", "Id": "202838", "Score": "0", "Tags": [ "java", "game", "multithreading", "serialization" ], "Title": "Serializable game loop thread" }
202838
<p>Are there Rust features I could apply to optimize for simple test of a JPEG or PNG resized from 2000 x 2000 pixels to 150 x 150 pixels?</p> <pre><code>extern crate image; use std::env; fn main() { let mut args = env::args(); args.next(); let file_location = args.next().unwrap(); let width = args.next().unwrap().parse().unwrap(); let height = args.next().unwrap().parse().unwrap(); let img = image::open(file_location.as_str()).unwrap(); // img.resize(width, height, image::imageops::Lanczos3); img.thumbnail(width, height); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T05:55:51.760", "Id": "390965", "Score": "0", "body": "I'm not sure this is a suitable question for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T07:01:18.343", "Id": "390969", "...
[ { "body": "<p>I would slightly change this code:</p>\n\n<pre><code>use std::error::Error;\n\nfn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {\n // Args arrangement\n let mut args = std::env::args().skip(1);\n assert_eq!(args.len(), 3, \"Arguments must be: file_location width height\");\n\n /...
{ "AcceptedAnswerId": "203273", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T02:21:48.910", "Id": "202850", "Score": "3", "Tags": [ "performance", "comparative-review", "rust" ], "Title": "Image resizing in Rust" }
202850
<p>The entry point is the <code>Macros</code> module, which - for now - includes only a single procedure, at a very high abstraction level - I'm quite happy with this:</p> <pre><code>'@Folder("Macros") Option Explicit '@Ignore MoveFieldCloserToUsage; controller reference needs to be held at module level! Private controller As GameController Public Sub PlayWorksheetInterface() Dim view As WorksheetView Set view = New WorksheetView Set controller = New GameController controller.NewGame GridViewAdapter.Create(view) End Sub </code></pre> <h2>Model</h2> <p>The <em>Model</em> consists of <code>Ship</code> (<code>IShip</code>), <code>PlayerGrid</code>, <code>GridCoord</code>, <code>AIPlayer</code>, and <code>HumanPlayer</code> (<code>IPlayer</code>) classes, which I've posted <a href="https://codereview.stackexchange.com/q/202184">here</a>. The code changed a little since then, but this post isn't about the model.</p> <h2>View</h2> <p>The <em>View</em> consists essentially of two interfaces: <code>IViewEvents</code>, which sends messages from the view to the controller, and <code>IViewCommands</code>, which sends messages from the controller to the view.</p> <p><strong>IViewEvents</strong></p> <pre><code>'@Folder("Battleship.View") '@Description("Commands sent from the view to the GridViewAdapter.") Option Explicit Public Sub CreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) End Sub Public Sub PreviewRotateShip(ByVal gridId As Byte, ByVal position As IGridCoord) End Sub Public Sub PreviewShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) End Sub Public Sub ConfirmShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) End Sub Public Sub AttackPosition(ByVal gridId As Byte, ByVal position As IGridCoord) End Sub </code></pre> <p><strong>IViewCommands</strong></p> <pre><code>'@Folder("Battleship.View") '@Description("Commands sent from the GridViewAdapter to the view.") Option Explicit '@Description("Gets/sets a weak refererence to the GridViewAdapter.") Public Property Get Events() As IGridViewEvents End Property Public Property Set Events(ByVal value As IGridViewEvents) End Property '@Description("Instructs the view to react to a miss in the specified grid.") Public Sub OnMiss(ByVal gridId As Byte) End Sub '@Description("Instructs the view to report a hit in the specified grid.") Public Sub OnHit(ByVal gridId As Byte) End Sub '@Description("Instructs the view to report a sunken ship in the specified grid.") Public Sub OnSink(ByVal gridId As Byte) End Sub '@Description("Instructs the view to update the specified player's fleet status, for the specified ship.") Public Sub OnUpdateFleetStatus(ByVal player As IPlayer, ByVal hitShip As IShip, Optional ByVal showAIStatus As Boolean = False) End Sub '@Description("Instructs the view to select the specified position in the specified grid.") Public Sub OnSelectPosition(ByVal gridId As Byte, ByVal position As IGridCoord) End Sub '@Description("Instructs the view to lock the specified grid, preventing user interaction.") Public Sub OnLockGrid(ByVal gridId As Byte) End Sub '@Description("Instructs the view to begin a new game.") Public Sub OnNewGame() End Sub '@Description("Instructs the view to end the game.") Public Sub OnGameOver(ByVal winningGrid As Byte) End Sub '@Description("Instructs the view to begin positioning the specified ship.") Public Sub OnBeginShipPosition(ByVal currentShip As IShip, ByVal player As IPlayer) End Sub '@Description("Instructs the view to confirm the position of the specified ship.") Public Sub OnConfirmShipPosition(ByVal player As IPlayer, ByVal newShip As IShip, ByRef confirmed As Boolean) End Sub '@Description("Instructs the view to preview the position of the specified ship.") Public Sub OnPreviewShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) End Sub '@Description("Instructs the view to begin attack phase.") Public Sub OnBeginAttack() End Sub '@Description("Instructs the view to react to an attack attempt on a known-state position.") Public Sub OnKnownPositionAttack() End Sub '@Description("Instructs the view to redraw the specified grid.") Public Sub OnRefreshGrid(ByVal grid As PlayerGrid) End Sub </code></pre> <p>Then there's a <code>GridViewAdapter</code>, that implements both - this was adapted/inferred from <a href="https://stackoverflow.com/a/45825831/1188513">this SO answer</a>, which describes/outlines the pattern and roughly demonstrates how to use interfaces and events together (since VBA doesn't let you expose events on interfaces).</p> <pre><code>'@Folder("Battleship.View") Option Explicit Implements IGridViewCommands Implements IGridViewEvents Public Enum ViewMode NewGame MessageShown FleetPosition player1 player2 GameOver End Enum Public Event OnCreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) Public Event OnPreviewCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) Public Event OnConfirmCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) Public Event OnRotateCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) Public Event OnPlayerReady() Public Event OnAttackPosition(ByVal gridId As Byte, ByVal position As IGridCoord) Public Event OnHit(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal hitShip As IShip) Public Event OnMiss(ByVal gridId As Byte, ByVal position As IGridCoord) Public Event OnGameOver(ByVal winner As IPlayer) Public Event Play(ByVal enemyGrid As PlayerGrid, ByVal player As IPlayer, ByRef position As IGridCoord) Private Type TAdapter ShipsToPosition As Byte GridView As IGridViewCommands End Type Private this As TAdapter Public Function Create(ByVal view As IGridViewCommands) As GridViewAdapter With New GridViewAdapter Set .GridView = view Set view.Events = .Self Set Create = .Self End With End Function Public Property Get Self() As GridViewAdapter Set Self = Me End Property Public Property Get GridView() As IGridViewCommands Set GridView = this.GridView End Property Public Property Set GridView(ByVal value As IGridViewCommands) Set this.GridView = value End Property Private Sub Class_Initialize() this.ShipsToPosition = PlayerGrid.ShipsPerGrid End Sub '@Ignore ParameterNotUsed Private Property Set IGridViewCommands_Events(ByVal value As IGridViewEvents) Err.Raise 5, TypeName(Me) End Property Private Property Get IGridViewCommands_Events() As IGridViewEvents Set IGridViewCommands_Events = Me End Property Private Sub IGridViewCommands_OnBeginAttack() this.GridView.OnBeginAttack End Sub Private Sub IGridViewCommands_OnBeginShipPosition(ByVal currentShip As IShip, ByVal player As IPlayer) this.GridView.OnLockGrid IIf(player.PlayGrid.gridId = 1, 2, 1) this.GridView.OnBeginShipPosition currentShip, player End Sub Private Sub IGridViewCommands_OnConfirmShipPosition(ByVal player As IPlayer, ByVal newShip As IShip, ByRef confirmed As Boolean) If player.PlayerType = ComputerControlled Then Exit Sub this.GridView.OnConfirmShipPosition player, newShip, confirmed If confirmed Then this.ShipsToPosition = this.ShipsToPosition - 1 If this.ShipsToPosition = 0 Then RaiseEvent OnPlayerReady End If End If End Sub Private Sub IGridViewCommands_OnGameOver(ByVal winningGrid As Byte) this.GridView.OnGameOver winningGrid Set this.GridView.Events = Nothing End Sub Private Sub IGridViewCommands_OnHit(ByVal gridId As Byte) this.GridView.OnHit gridId End Sub Private Sub IGridViewCommands_OnKnownPositionAttack() this.GridView.OnKnownPositionAttack End Sub Private Sub IGridViewCommands_OnLockGrid(ByVal gridId As Byte) this.GridView.OnLockGrid gridId End Sub Private Sub IGridViewCommands_OnMiss(ByVal gridId As Byte) this.GridView.OnMiss gridId End Sub Private Sub IGridViewCommands_OnNewGame() this.GridView.OnNewGame End Sub Private Sub IGridViewCommands_OnPreviewShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) If player.PlayerType = ComputerControlled Then Exit Sub this.GridView.OnPreviewShipPosition player, newShip End Sub Private Sub IGridViewCommands_OnRefreshGrid(ByVal grid As PlayerGrid) this.GridView.OnRefreshGrid grid End Sub Private Sub IGridViewCommands_OnSelectPosition(ByVal gridId As Byte, ByVal position As IGridCoord) this.GridView.OnSelectPosition gridId, position End Sub Private Sub IGridViewCommands_OnSink(ByVal gridId As Byte) this.GridView.OnSink gridId End Sub Private Sub IGridViewCommands_OnUpdateFleetStatus(ByVal player As IPlayer, ByVal hitShip As IShip, Optional ByVal showAIStatus As Boolean = False) this.GridView.OnUpdateFleetStatus player, hitShip, showAIStatus End Sub Private Sub IGridViewEvents_AttackPosition(ByVal gridId As Byte, ByVal position As IGridCoord) RaiseEvent OnAttackPosition(gridId, position) End Sub Private Sub IGridViewEvents_ConfirmShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) RaiseEvent OnConfirmCurrentShipPosition(gridId, position) End Sub Private Sub IGridViewEvents_CreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) RaiseEvent OnCreatePlayer(gridId, pt, difficulty) End Sub Private Sub IGridViewEvents_PreviewRotateShip(ByVal gridId As Byte, ByVal position As IGridCoord) RaiseEvent OnRotateCurrentShipPosition(gridId, position) End Sub Private Sub IGridViewEvents_PreviewShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) RaiseEvent OnPreviewCurrentShipPosition(gridId, position) End Sub </code></pre> <p>I'm using an <em>adapter</em>, because I intend to make the game playable on a <code>UserFormView</code> just as well as on a <code>WorksheetView</code> - otherwise I guess wouldn't have minded coupling the controller with the view directly. Here's the <code>WorksheetView</code>:</p> <pre><code>'@Folder("Battleship.View.Worksheet") Option Explicit Implements IGridViewCommands Private adapter As IWeakReference Private WithEvents sheetUI As GameSheet Private Sub Class_Initialize() Set sheetUI = GameSheet End Sub Private Property Get ViewEvents() As IGridViewEvents Set ViewEvents = adapter.Object End Property Private Property Set IGridViewCommands_Events(ByVal value As IGridViewEvents) Set adapter = WeakReference.Create(value) End Property Private Property Get IGridViewCommands_Events() As IGridViewEvents Set IGridViewCommands_Events = adapter.Object End Property Private Sub IGridViewCommands_OnBeginAttack() sheetUI.ShowInfoBeginAttackPhase End Sub Private Sub IGridViewCommands_OnBeginShipPosition(ByVal currentShip As IShip, ByVal player As IPlayer) sheetUI.ShowInfoBeginDeployShip currentShip.Name End Sub Private Sub IGridViewCommands_OnConfirmShipPosition(ByVal player As IPlayer, ByVal newShip As IShip, confirmed As Boolean) sheetUI.ConfirmShipPosition player, newShip, confirmed End Sub Private Sub IGridViewCommands_OnGameOver(ByVal winningGridId As Byte) With sheetUI .ShowAnimationVictory winningGridId .ShowAnimationDefeat IIf(winningGridId = 1, 2, 1) .LockGrids End With End Sub Private Sub IGridViewCommands_OnHit(ByVal gridId As Byte) With sheetUI .ShowAnimationHit gridId .LockGrid gridId End With End Sub Private Sub IGridViewCommands_OnKnownPositionAttack() sheetUI.ShowErrorKnownPositionAttack End Sub Private Sub IGridViewCommands_OnLockGrid(ByVal gridId As Byte) sheetUI.LockGrid gridId End Sub Private Sub IGridViewCommands_OnMiss(ByVal gridId As Byte) With sheetUI .ShowAnimationMiss gridId .LockGrid gridId End With End Sub Private Sub IGridViewCommands_OnNewGame() With sheetUI .Visible = xlSheetVisible .OnNewGame End With End Sub Private Sub IGridViewCommands_OnPreviewShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) sheetUI.PreviewShipPosition player, newShip End Sub Private Sub IGridViewCommands_OnRefreshGrid(ByVal grid As PlayerGrid) sheetUI.RefreshGrid grid End Sub Private Sub IGridViewCommands_OnSelectPosition(ByVal gridId As Byte, ByVal position As IGridCoord) If sheetUI Is Application.ActiveSheet Then sheetUI.GridCoordToRange(gridId, position).Select End If End Sub Private Sub IGridViewCommands_OnSink(ByVal gridId As Byte) With sheetUI .ShowAnimationSunk gridId .LockGrid gridId End With End Sub Private Sub IGridViewCommands_OnUpdateFleetStatus(ByVal player As IPlayer, ByVal hitShip As IShip, Optional ByVal showAIStatus As Boolean = False) With sheetUI If player.PlayerType = ComputerControlled And showAIStatus Then .ShowAcquiredTarget IIf(player.PlayGrid.gridId = 1, 2, 1), hitShip.Name, hitShip.IsSunken Else .UpdateShipStatus player, hitShip End If End With End Sub Private Sub sheetUI_CreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) ViewEvents.CreatePlayer gridId, pt, difficulty End Sub Private Sub sheetUI_DoubleClick(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) Select Case Mode Case ViewMode.FleetPosition ViewEvents.ConfirmShipPosition gridId, position Case ViewMode.player1, ViewMode.player2 ViewEvents.AttackPosition gridId, position End Select End Sub Private Sub sheetUI_RightClick(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) If Mode = FleetPosition Then ViewEvents.PreviewRotateShip gridId, position End Sub Private Sub sheetUI_SelectionChange(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) If Mode = FleetPosition Then ViewEvents.PreviewShipPosition gridId, position End Sub </code></pre> <p>The <code>IWeakReference</code> is an updated version of <a href="https://codereview.stackexchange.com/q/202414">this code</a> that now includes precompiler directives (so that it works in both 32 and 64 bit hosts) and proper error handling.</p> <p>The <code>GameSheet</code> is an Excel worksheet exposing the methods invoked by the <code>WorksheetView</code>; the reason I didn't make the worksheet itself implement <code>IGridViewCommands</code>, is because making VBA host document modules implement interfaces is a very good way to crash the entire thing - i.e. you don't do that. So instead I made the worksheet expose methods that handle all the presentation concerns, and the <code>WorksheetView</code> simply invokes them.</p> <h2>Controller</h2> <p>The <code>GameController</code> class encapsulates the entire game logic - too much for my taste: I find it's responsible for way too many things, and that's making it rather hard to refactor and support custom game modes, like <em>salvo mode</em>. I tried extracting the <code>currentPlayer</code>/<code>currentTarget</code> and player turn logic into a <code>ClassicMode</code> class (implementing an <code>IGameMode</code> interface that an eventual <code>SalvoMode</code> class could also implement), but that broke everything so I rolled it back... and basically I'm asking Code Review to help me cleanly separate the too many concerns I've put into this controller.</p> <pre><code>'@Folder("Battleship") Option Explicit Private Const Delay As Long = 1200 Private player1 As IPlayer Private player2 As IPlayer Private currentPlayer As IPlayer Private currentTarget As IPlayer Private currentShip As IShip Private view As IGridViewCommands Private WithEvents viewAdapter As GridViewAdapter Public Sub NewGame(ByVal adapter As GridViewAdapter) Set viewAdapter = adapter Set view = adapter view.OnNewGame End Sub Private Sub viewAdapter_OnCreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) If gridId = 1 And Not player1 Is Nothing Then Exit Sub If gridId = 2 And Not player2 Is Nothing Then Exit Sub Dim player As IPlayer Select Case pt Case HumanControlled Set player = HumanPlayer.Create(gridId) Case ComputerControlled Select Case difficulty Case AIDifficulty.RandomAI Set player = AIPlayer.Create(gridId, RandomShotStrategy.Create(New GameRandomizer)) Case AIDifficulty.FairplayAI Set player = AIPlayer.Create(gridId, FairPlayStrategy.Create(New GameRandomizer)) Case AIDifficulty.MercilessAI Set player = AIPlayer.Create(gridId, MercilessStrategy.Create(New GameRandomizer)) End Select Case Else Err.Raise 5, TypeName(Me), "Invalid PlayerType" End Select If gridId = 1 Then Set player1 = player ElseIf gridId = 2 Then Set player2 = player End If If Not player1 Is Nothing And Not player2 Is Nothing Then OnShipPositionStart EndCurrentPlayerTurn End If End Sub Private Sub OnShipPositionStart() Dim kinds As Variant kinds = Ship.ShipKinds Set currentShip = Ship.Create(kinds(0), Horizontal, GridCoord.Create(1, 1)) If player1.PlayerType = HumanControlled Then view.OnBeginShipPosition currentShip, player1 ElseIf player2.PlayerType = HumanControlled Then view.OnBeginShipPosition currentShip, player2 Else 'AI vs AI Dim i As Long For i = LBound(kinds) To UBound(kinds) Set currentShip = Ship.Create(kinds(i), Horizontal, GridCoord.Create(1, 1)) player1.PlaceShip currentShip player2.PlaceShip currentShip Next Set currentPlayer = player1 Set currentTarget = player2 PlayAI End If End Sub Private Sub viewAdapter_OnNewGame() NewGame viewAdapter End Sub Private Sub viewAdapter_OnPreviewCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) On Error Resume Next Set currentShip = Ship.Create(currentShip.ShipKind, currentShip.Orientation, position) On Error GoTo 0 If gridId = 1 Then view.OnPreviewShipPosition player1, currentShip Else view.OnPreviewShipPosition player2, currentShip End If End Sub Private Sub viewAdapter_OnRotateCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) On Error Resume Next Set currentShip = Ship.Create(currentShip.ShipKind, IIf(currentShip.Orientation = Horizontal, Vertical, Horizontal), position) On Error GoTo 0 If gridId = 1 Then view.OnPreviewShipPosition player1, currentShip Else view.OnPreviewShipPosition player2, currentShip End If End Sub Private Sub viewAdapter_OnConfirmCurrentShipPosition(ByVal gridId As Byte, ByVal position As IGridCoord) If gridId &lt;&gt; currentPlayer.PlayGrid.gridId Then Exit Sub Dim confirmed As Boolean view.OnConfirmShipPosition currentPlayer, currentShip, confirmed ' no-op for human players player1.PlaceShip currentShip player2.PlaceShip currentShip Dim ships As Long ships = currentPlayer.PlayGrid.shipCount If confirmed And ships &lt; PlayerGrid.ShipsPerGrid Then Dim kind As ShipType kind = Ship.ShipKinds(ships) Set currentShip = Ship.Create(kind, Horizontal, GridCoord.Create(1, 1)) view.OnBeginShipPosition currentShip, currentPlayer End If End Sub Private Sub viewAdapter_OnPlayerReady() Set currentPlayer = player1 Set currentTarget = player2 If currentPlayer.PlayerType = HumanControlled Then view.OnBeginAttack Else currentPlayer.Play currentTarget.PlayGrid End If End Sub Private Sub viewAdapter_OnAttackPosition(ByVal gridId As Byte, ByVal position As IGridCoord) If gridId = currentPlayer.PlayGrid.gridId Then Exit Sub On Error GoTo CleanFail If currentPlayer.PlayerType = HumanControlled Then Play gridId, position Else PlayAI End If Exit Sub CleanFail: With Err If .Number = PlayerGridErrors.KnownGridStateError Then view.OnKnownPositionAttack End If End With End Sub Private Sub PlayAI() Debug.Assert currentPlayer.PlayerType &lt;&gt; HumanControlled Win32API.Sleep Delay Play currentTarget.PlayGrid.gridId, currentPlayer.Play(currentTarget.PlayGrid) End Sub Private Sub Play(ByVal gridId As Byte, ByVal position As IGridCoord) Dim result As AttackResult, hitShip As IShip result = currentTarget.PlayGrid.TryHit(position, hitShip) view.OnRefreshGrid currentTarget.PlayGrid view.OnSelectPosition gridId, position Select Case result Case AttackResult.Miss view.OnMiss gridId Case AttackResult.Hit view.OnUpdateFleetStatus currentTarget, hitShip, (player1.PlayerType = ComputerControlled And player2.PlayerType = ComputerControlled) view.OnHit gridId Case AttackResult.Sunk view.OnUpdateFleetStatus currentTarget, hitShip If currentTarget.PlayGrid.IsAllSunken Then view.OnGameOver currentPlayer.PlayGrid.gridId End Else view.OnSink gridId End If End Select EndCurrentPlayerTurn End Sub Private Sub EndCurrentPlayerTurn() If currentPlayer Is player1 Then Set currentPlayer = player2 Set currentTarget = player1 Else Set currentPlayer = player1 Set currentTarget = player2 End If If currentPlayer.PlayerType &lt;&gt; HumanControlled Then PlayAI End Sub </code></pre> <p>So, while I'm mostly interested in separating the too many concerns handled by the controller, as always I'm very open to feedback on every other aspect of this code. No feedback can be too picky - I want to eventually present this code as a demonstration of VBA+OOP capabilities, so I ultimately need it to be as close as possible to object-oriented perfection... as far as VBA allows anyway!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T04:15:56.650", "Id": "390955", "Score": "0", "body": "Gosh.. There's something about reading your own code in a CR post that mysteriously makes you see all the redundancies... there's much more to clean up in that controller than ju...
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T03:42:56.130", "Id": "202851", "Score": "7", "Tags": [ "object-oriented", "vba", "mvc", "battleship" ], "Title": "Battleship MVC Architecture" }
202851
<p>I wrote a task scheduler package with data persistence in Go.</p> <p>However, the logic seems super messy... even it seems passed all tests.</p> <p>Is there any better way to structure the code and finish few unsolved TODO in the code? PR welcome after a review, thank you in advance.</p> <pre><code>package goscheduler import ( "encoding/json" "reflect" "sync" "time" "github.com/changkun/goscheduler/internal/pool" "github.com/changkun/goscheduler/internal/pq" "github.com/changkun/goscheduler/internal/store" "github.com/changkun/goscheduler/task" ) var ( worker *Scheduler schedulerOnce sync.Once ) // Scheduler is the actual scheduler for task scheduling type Scheduler struct { mu *sync.Mutex timer *time.Timer queue *pq.TimerTaskQueue } // Init internal connection pool to data store func Init(url string) { pool.Init(url) } // New creates a temporary task scheduler func New() *Scheduler { schedulerOnce.Do(func() { worker = &amp;Scheduler{ mu: &amp;sync.Mutex{}, timer: nil, queue: pq.NewTimerTaskQueue(), } }) return worker } // RecoverAll given tasks func (s *Scheduler) RecoverAll(ts ...task.Interface) error { for _, t := range ts { if err := s.Recover(t); err != nil { return err } } return nil } // Recover given task type func (s *Scheduler) Recover(t task.Interface) error { ids, err := store.GetRecords() if err != nil { return err } for _, id := range ids { r := &amp;store.Record{} if err := r.Read(id); err != nil { return err } data, _ := json.Marshal(r.Data) // Note: The following comparasion provides a generic mechanism in golang, which // unmarshals an unknown type of data into acorss multiple into an arbitrary variable. // // temp1 holds for a unset value of t, and temp2 tries to be set by json.Unmarshal. // // In the end, if temp1 and temp2 are appropriate type of tasks, then temp2 should // not DeepEqual to temp1, because temp2 is setted by store data. // Otherwise, the determined task is inappropriate type to be scheduled, jump to // next record and see if it can be scheduled. temp1 := reflect.New(reflect.ValueOf(t).Elem().Type()).Interface().(task.Interface) temp2 := reflect.New(reflect.ValueOf(t).Elem().Type()).Interface().(task.Interface) if err := json.Unmarshal(data, &amp;temp2); err != nil { continue } if reflect.DeepEqual(temp1, temp2) { continue } temp2.SetID(id) temp2.SetExecution(r.Execution) s.queue.Push(temp2) } s.resume() return nil } // SetupAll given tasks func (s *Scheduler) SetupAll(ts ...task.Interface) error { for _, t := range ts { if err := s.Setup(t); err != nil { return err } } return nil } // Setup a task into runner queue func (s *Scheduler) Setup(t task.Interface) error { // save asap if err := store.Save(t); err != nil { return err } s.schedule(t) return nil } // LaunchAll given tasks func (s *Scheduler) LaunchAll(ts ...task.Interface) error { for _, t := range ts { if err := s.Launch(t); err != nil { return err } } return nil } // Launch a task immediately func (s *Scheduler) Launch(t task.Interface) error { t.SetExecution(time.Now().UTC()) return s.Setup(t) } func (s *Scheduler) schedule(t task.Interface) { s.pause() defer s.resume() // if priority is able to be update if s.queue.Update(t) { return } s.queue.Push(t) } func (s *Scheduler) pause() { s.mu.Lock() defer s.mu.Unlock() if s.timer != nil { s.timer.Stop() } } func (s *Scheduler) resume() { t := s.queue.Peek() if t == nil { return } s.mu.Lock() s.timer = time.NewTimer(t.GetExecution().Sub(time.Now().UTC())) timer := s.timer s.mu.Unlock() go func() { &lt;-timer.C t := s.queue.Pop() if t == nil { return } s.resume() s.arrival(t) }() } func (s *Scheduler) arrival(t task.Interface) { ok, err := store.Lock(t) if err != nil || !ok { return } defer func(t task.Interface) { if err := store.Unlock(t); err != nil { // no need to hadle unlock fail // since there is a timeout on redis return } }(t) s.execute(t) } func (s *Scheduler) verify(t task.Interface) (*time.Time, error) { r := &amp;store.Record{} if err := r.Read(t.GetID()); err != nil { return nil, err } taskTime := t.GetExecution() if taskTime.Before(r.Execution) { return &amp;r.Execution, nil } return &amp;taskTime, nil } func (s *Scheduler) execute(t task.Interface) { execution, err := s.verify(t) if err != nil { return } if execution.Before(time.Now().UTC()) { retry, err := t.Execute() if retry || err != nil { s.retry(t) return } if err := store.Delete(t); err != nil { // TODO: Generally, this is not able to be fail. // However it may caused by the lost of connection. // Though task will be recovered then app restarts, // but it may leads an inconsistency, we need other // means to solve this problem return } return } s.mu.Lock() s.queue.Push(t) s.mu.Unlock() } func (s *Scheduler) retry(t task.Interface) { t.SetExecution(t.GetExecution().Add(t.GetRetryDuration())) if err := s.Setup(t); err != nil { // TODO: If Setup() is fail because of redis failure, // directly schedule the task without any hesitate // In case it may leads a problem of unabiding task // scheduling s.schedule(t) } } </code></pre> <p><a href="https://github.com/changkun/sched" rel="nofollow noreferrer">https://github.com/changkun/sched</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T09:22:54.540", "Id": "390986", "Score": "2", "body": "@Graipher Hi, thanks for your suggestion, I attached the major part of my code. You can also find attached material in the link." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T09:05:19.977", "Id": "202857", "Score": "4", "Tags": [ "go", "scheduled-tasks" ], "Title": "A task scheduler with persistence" }
202857
<p>I have an array like this:</p> <pre><code>$array = [ ['id' =&gt; 1, 'content' =&gt; 'value 1'], ['id' =&gt; 2, 'content' =&gt; 'value 2'], ['id' =&gt; 3, 'content' =&gt; 'value 3'], ]; </code></pre> <p>I have another array containing the actual order of <code>id</code>s in which <code>$array</code> should be sorted :</p> <pre><code>$order = [3, 1, 2]; </code></pre> <p>Which means, the result should be this:</p> <pre><code>$sorted = [ 0 =&gt; ['id' =&gt; 3, 'content' =&gt; 'value 3'], 1 =&gt; ['id' =&gt; 1, 'content' =&gt; 'value 1'], 2 =&gt; ['id' =&gt; 2, 'content' =&gt; 'value 2'], ]; </code></pre> <p>The final requirement is, that the array should be printed using <code>foreach</code>:</p> <pre><code>foreach($sorted as $value) { print $value['content']; } </code></pre> <hr> <p>I came up with this solution:</p> <pre><code>function orderArray(array $array, array $order) { $sorted = []; foreach($array as $value) { $id = $value['id']; $index = array_search($id, $order); $sorted[$index] = $value; } ksort($sorted); return $sorted; } </code></pre> <hr> <p>This works fine. However, I wonder whether this is efficent, especially as I have to call <code>ksort</code> to make the array be printed correctly by <code>foreach</code>.</p> <p>Can this be optimized? Maybe there's also a more elegant solution to the problem.</p> <hr> <p><sup>It's a given, that all <code>id</code>s and only those are in <code>$order</code> - so no need to test for that.</sup></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T10:23:16.360", "Id": "391000", "Score": "0", "body": "Do the IDs in `$array` always correspond to the numbers in the `$order` array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T10:25:18.407", ...
[ { "body": "<p>I would say that array_search() is also a concern.</p>\n\n<p>So I would create an index array to make a correspondence between the id and the position and then just create a new array, like this</p>\n\n<pre><code>$sorted = [];\n$index = array_flip(array_column($array, 'id'));\nforeach ($order as $...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T09:53:35.460", "Id": "202861", "Score": "2", "Tags": [ "performance", "php", "array", "sorting" ], "Title": "Sort multidimensional array based on another one containing the desired order" }
202861
<p>I do a lot of PC swaps/replacements for my role. I've decided to write a script to assist with backing up the user's profile and network drives.</p> <p>I'd like to see how my script stands now. I'm still working to implement more features such as backing up saved wireless networks and printers. </p> <pre><code>#get current user's ID $userID=$env:UserName ##################################### ### Backup user's saved documents ### ##################################### $FoldersToCopy = @( 'Desktop' 'Downloads' 'Favorites' 'Documents' 'Pictures' 'Videos' 'AppData' ) $SourceRoot = "C:\Users\$User" $DestinationRoot = "$PSScriptRoot\fileBackup\$userID\" foreach( $Folder in $FoldersToCopy ){ $Source = Join-Path -Path $SourceRoot -ChildPath $Folder $Destination = Join-Path -Path $DestinationRoot -ChildPath $Folder Robocopy.exe $Source $Destination } ##################################### ### Backup user's mapped drives ### ##################################### $mappedDrives = @() $drives = Get-PSDrive -PSProvider FileSystem foreach ($drive in $drives) { if ($drive.DisplayRoot) { $mappedDrives += Select-Object Name,DisplayRoot -InputObject $drive } } New-Item -ItemType Directory -Force -Path $PSScriptRoot\fileBackup\$userID\mappedDrives $mappedDrives | Export-Csv $PSScriptRoot\fileBackup\$userID\mappedDrives\mappedDrives.csv </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T15:36:14.043", "Id": "391060", "Score": "0", "body": "Be careful to assume that desktop, documents, etc. will be located at `C:\\Users\\[Username]\\...`. They can be moved. https://www.codeproject.com/articles/878605/getting-all-spe...
[ { "body": "<p>Your code looks pretty good to me. A few notes:</p>\n\n<hr>\n\n<p>You have a bug here:</p>\n\n<pre><code>$userID=$env:UserName\n\n$SourceRoot = \"C:\\Users\\$User\"\n</code></pre>\n\n<p>You are referring to <code>$User</code>, which hasn't been set. I always put this at the top of my scripts ...
{ "AcceptedAnswerId": "203065", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T13:33:03.207", "Id": "202869", "Score": "3", "Tags": [ "powershell" ], "Title": "Backup Windows user's profile" }
202869
<p>Every Month I need to make an excel sheet with travel expenses, since this is a tedious task I decided to make a little python script to do this work for me.</p> <p>Everything works correctly, but any comments regarding style and functionality are welcome.</p> <pre><code>import datetime import calendar import re import argparse import openpyxl END_OF_WEEK = 5 def get_working_days(date, exclude_days): """ Gets the working days of that month args: date (str): The date in MM_YYYY format exclude (set): A set of excluded weekday(s) returns: a List of weekday dates in 'DD/MM/YYYY' format """ month, year = map(int, date.split('_')) num_days = calendar.monthrange(year, month)[1] for day in range(1, num_days+1): date = datetime.date(year, month, day) if date.weekday() &lt; END_OF_WEEK and date.weekday() not in exclude_days: yield date.strftime('%d/%m/%Y') def travel_expenses(date, home, work, company, distance, price, exclude_days): """ Creates Excel documents for travel expenses args: date (str): The month/year to create travel expenses for home (str): The home Address work (str): The work address company (str): The name of the company/customer currently traveling to distance (float): The distance in Km price (float): The price in $currency$ exclude (list): A list of excluded weekdays returns: None """ workbook = openpyxl.Workbook() worksheet = workbook.active worksheet.title = date optional = ['Prijs'] if price else ['Afstand (km)'] if distance else [] headers = ['Datum', 'Adres van vertrek', 'Adres van aankomst', 'Klant'] + optional for i, head in enumerate(headers, 1): worksheet.cell(row=1, column=i, value=head) exclude_days = set() if exclude_days is None else set(map(int, exclude_days)) days = list(get_working_days(date, exclude_days)) for i, day in enumerate(days, 2): for j, col in enumerate(filter(None, [day, home, work, company, distance, price]), 1): worksheet.cell(row=i, column=j, value=col) # Add sum of distance or price if exists total = None if not price is None: total = price * len(days) if not distance is None: total = distance * len(days) if not total is None: worksheet.cell(row=2 + len(days), column=4, value='Total:') worksheet.cell(row=2 + len(days), column=5, value=total) workbook.save("{}.xlsx".format(date)) def parse_arguments(): """Arguments parser.""" parser = argparse.ArgumentParser(usage='%(prog)s [options] &lt;date&gt; &lt;home&gt; &lt;work&gt; &lt;company&gt;', description='Declaring Travel expenses, by @Ludisposed', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' Examples: python reiskosten.py 06_2018 "111AA, 2" "2222BB, 1" "Company Name" python reiskosten.py 06_2018 "111AA, 2" "2222BB, 1" "Company Name" --distance 103.2 python reiskosten.py 06_2018 "111AA, 2" "2222BB, 1" "Company Name" --price 20.1 python reiskosten.py 06_2018 "111AA, 2" "2222BB, 1" "Company Name" --exclude 01 python reiskosten.py 06_2018 "111AA, 2" "2222BB, 1" "Company Name" --price 10.5 --exclude 23 ''') parser.add_argument('date', type=str, help='The date in MM_YYYY format') parser.add_argument('home', type=str, help='The Home address in "PostalCode, Number+Appendix" format') parser.add_argument('work', type=str, help='The Work address in "PostalCode, Number+Appendix" format') parser.add_argument('company', type=str, help='The company name') parser.add_argument('--distance', type=float, help='The distance of the travel (Useful for travels with Car)') parser.add_argument('--price', type=float, help='The price of the travel (Useful for travels with Train)') parser.add_argument('--exclude', type=list, help='Exclude some days in 02 format (Meaning excluding Monday and Wednesday)') args = parser.parse_args() if not args.price is None and not args.distance is None: parser.error("Specify Price or Distance not both") if not re.match(r"(\d{1,2}_\d{4})", args.date): parser.error("Date should be in {MM_YYYY} format") addres_regex = re.compile(r"(\d{4} [A-Z]{2}, \d+[A-Z]{0,1})") if not re.match(addres_regex, args.home): parser.error("Home address should be in {1111 AA, 2A} or {1111 AA, 2} format") if not re.match(addres_regex, args.work): parser.error("Work address should be in {1111 AA, 2A} or {1111 AA, 2} format") return args.date, args.home, args.work, args.company, args.distance, args.price, args.exclude if __name__ == '__main__': args = parse_arguments() travel_expenses(*args) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T13:36:04.217", "Id": "202870", "Score": "2", "Tags": [ "python", "python-3.x", "excel" ], "Title": "Excel for travel expenses" }
202870
<p>the following is an implementation of the standard Metropolis Hastings Monte Carlo sampler. You can read more about it <a href="https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm" rel="noreferrer">here</a>.</p> <p>At the end I am going to give you a link to the Rust playground, so you can test the code yourself!</p> <p>First I start with some traits, that define probability functions:</p> <pre><code>type Float=f64; /*Standard trait for distributions. Some applications only require the ability to sample from a distribution without the need for an explicit probability density function (pdf).*/ pub trait Distribution { type T; fn sample&lt;R:Rng+?Sized&gt;(&amp;self, rng:&amp;mut R)-&gt;Self::T; } /*Standard trait for distributions. Some applications only require the ability to sample from a distribution without the need for an explicit probability density function (pdf).*/ pub trait PDF: Distribution { fn pdf(&amp;self,x:&amp;Self::T)-&gt;Float; } /*When Rust offers optional function arguments, the conditional traits can be depraciated.*/ pub trait ConditionalDistribution { type T; fn csample&lt;R:Rng+?Sized&gt;(&amp;self, rng:&amp;mut R,x_prev:&amp;Self::T)-&gt;Self::T; } /*Conditional probability density function. This is especially useful, if the expression for the conditional pdf does only depend on the shape.*/ pub trait ConditionalPDF: ConditionalDistribution { fn cpdf(&amp;self,x:&amp;Self::T,x_prev:&amp;Self::T)-&gt;Float; } </code></pre> <p>The trait declarations are modelled after the ones in the <a href="https://github.com/rust-random/rand/blob/master/src/distributions/mod.rs" rel="noreferrer">rand</a> crate.</p> <p>Then comes the sampler itself:</p> <pre><code>#[doc = "Markov Chain Metropolis Hastings algorithm. Numerically evaluate the value of an integral, where the integrand is proportional to a probability distribution."] #[allow(non_snake_case)] #[allow(dead_code)] struct MetropolisHastings&lt;D,F&gt; where D:ConditionalDistribution+ConditionalPDF, D::T:AsRef&lt;[Float]&gt;+std::fmt::Debug+Clone, F:Fn(&amp;[Float])-&gt;Float { log_f:F, log_proposal:D, initial:D::T, burnIn:usize, isSymmetric:bool, } impl&lt;D,F&gt; MetropolisHastings&lt;D,F&gt; where D:ConditionalDistribution+ConditionalPDF, D::T:AsRef&lt;[Float]&gt;+std::fmt::Debug+Clone, F:Fn(&amp;[Float])-&gt;Float { fn new(log_f:F,log_proposal:D,x0:D::T)-&gt;MetropolisHastings&lt;D,F&gt; { MetropolisHastings{ log_f, log_proposal, initial:x0, burnIn:(250 as Float) as usize, isSymmetric:false, } } fn sample(&amp;self, n:usize)-&gt;Vec&lt;Float&gt; { let dim=1;//change! let mut samples=Vec::with_capacity(n*dim); let mut rng=rand::thread_rng(); let mut x=self.initial.clone(); for i in 0..self.burnIn+n as usize{ let x_p=self.log_proposal.csample(&amp;mut rng,&amp;x); let acc_rat=(self.log_f)(x_p.as_ref())+self.log_proposal.cpdf(&amp;x_p,&amp;x)-(self.log_f)(x.as_ref())-self.log_proposal.cpdf(&amp;x,&amp;x_p); let r=f64::min(0.0,acc_rat); let u=rng.gen::&lt;Float&gt;(); //the polynomial is a truncated Taylor series to u.ln(x) at x=0.5 if -0.7*2.0*(u-0.5)-2.0*(u-0.5)*(u-0.5) &lt;r { x=x_p.clone(); } if i&gt;=self.burnIn { samples.extend_from_slice(x_p.as_ref()); } } samples } } </code></pre> <p>It is required, that the user inputs the densities in log scale. Because Rust's f64::ln() function takes too long, I approximated this function in the intervall [0,1] with a truncated Taylor series at x=0.5. If the input is multidimensional, the output will be a flattened vector of size numSamples*dimension.</p> <p>Questions: With a burn-in of 250 and 100.000.000 million samples, it takes 2.3 seconds on my machine. Questions:</p> <ul> <li>Can I make the code any faster or better?</li> <li>Do you like my traits?</li> <li>Can I infer the dimension of the input automatically instead of fixing dim=1 in fn sample()?</li> </ul> <p>Here you can execute the bare code yourself:</p> <p><a href="https://play.rust-lang.org/?gist=9e9ac875d3b6071d9b873b5384bef8a8&amp;version=stable&amp;mode=debug&amp;edition=2015" rel="noreferrer">https://play.rust-lang.org/?gist=9e9ac875d3b6071d9b873b5384bef8a8&amp;version=stable&amp;mode=debug&amp;edition=2015</a></p> <p>Here you can execute the code with an added example: <a href="https://play.rust-lang.org/?gist=c37ee575716e37e1668b5a6f62f8e8cd&amp;version=stable&amp;mode=debug&amp;edition=2015" rel="noreferrer">https://play.rust-lang.org/?gist=c37ee575716e37e1668b5a6f62f8e8cd&amp;version=stable&amp;mode=debug&amp;edition=2015</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T13:59:33.187", "Id": "391039", "Score": "1", "body": "Don't take it personally, but your code formatting is ugly :( You should use the official Rust formatting if you want to share your code." }, { "ContentLicense": "CC BY-S...
[ { "body": "<p>Wow, this is old. I've gone through it and made some very small format\nchanges and changes to make it compile/build/run; See <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=3783b95aa4b7b9b4e73b91c8dff58b31\" rel=\"nofollow noreferrer\">playground</a>....
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T13:40:04.890", "Id": "202871", "Score": "8", "Tags": [ "algorithm", "random", "rust", "numerical-methods" ], "Title": "Metropolis Monte Carlo Sampler in Rust" }
202871
<p>I'm just starting to learn programming again after a long break and decided on Python. Here's my code:</p> <pre><code>#"Code Wars: Where my anagrams at?" A program that finds all anagrams of "word" in "wordList". import copy def anagrams(word, wordList): result = [] #List to store all the anagrams. for i in wordList: #Outer loop finds all anagrams of "word". source = copy.deepcopy(list(i)) #Creates a copy of the current word in the word list as a list. var = True #Boolean value that indicates whether "i" is an anagram of "word" or not. for j in word: #Inner loop. It checks if "i" is an anagram of "word". if(j in source): #Incrementally deletes the matching characters. source.remove(j) else: #Early exit if a single character in "word" is missing from "i". var = False break if(source != []): #If "i" is an anagram of "word", then "source" should be empty. var = False if(var): #Add the word to the result list iff "i" is an anagram of "word". result.append(i) return(result) </code></pre> <p>What am I doing wrong (re best practices/design/efficiency)?<br> What could I do better?</p>
[]
[ { "body": "<p>The most pythonic way (IMO) to check if two words are anagrams of each other is to check if the number of times each letter appears in each words is the same. For this you can use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>c...
{ "AcceptedAnswerId": "202882", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T14:38:02.883", "Id": "202873", "Score": "4", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Find anagrams of a word in a list" }
202873
<p>Today I had an interesting idea. I have been copy/pasting the following line for each kind of request method for every route.</p> <pre><code>http.Handle("/api/my/custom/route", mw.Chain(api.PostFunc, mw.Method("POST"), mw.Logging())) </code></pre> <p>It struck me that it looked very bad and unprofessional so I came up with a new idea.</p> <pre><code>type RouteInstructor struct { Instance struct { URL string Data struct { Method string Callback string } } } func Routes() { routes := &amp;RouteInstructor{ Instance: map[string]interface{}{ URL: "/api/my/custom/route", Data: map[string]interface{}{ Method: "POST", Callback: api.PostFunc, }, Data: map[string]interface{}{ Method: "GET", Callback: api.GetFunc, }, }, } mw.Routes(routes) } </code></pre> <p>Instead of calling the <code>mw.Chain</code> method and <code>http.Handle</code>, wouldn't it be better to make a struct, pass it to a middleware method where you apply <code>mw.Chain</code> and everything else? Although it does become more code, I feel like it becomes easier to understand and therefore more effective.</p> <p>What do you think of this new way of mine? What are pros and the cons?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T17:54:56.790", "Id": "391318", "Score": "0", "body": "You'll need to provide code that works before asking for a review (see https://codereview.stackexchange.com/help/dont-ask). From what I see, your code wouldn't compile and it's n...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T14:52:18.917", "Id": "202875", "Score": "2", "Tags": [ "go" ], "Title": "Dealing with API routes in form of interfaces" }
202875
<p><strong>EDIT BELOW</strong></p> <p>I am trying to create resusable classes for MSSQL and MySQL queries (later also Update and Delete queries). I tried it doing the OOP-way. Here is my result:</p> <p>Einstellungen.vb:</p> <pre><code>Public Class Einstellung Private _Server As String Public Property Server As String Get Return _Server End Get Set(value As String) _Server = value End Set End Property Private _Benutzer As String Public Property Benutzer As String Get Return _Benutzer End Get Set(value As String) _Benutzer = value End Set End Property Private _Passwort As String Public Property Passwort As String Get Return _Passwort End Get Set(value As String) _Passwort = value End Set End Property Private _Datenbank As String Public Property Datenbank As String Get Return _Datenbank End Get Set(value As String) _Datenbank = value End Set End Property Private _Art As String Public Property Art As String Get Return _Art End Get Set(value As String) _Art = value End Set End Property Private _Port As UShort = 3306 Public Property Port As UShort Get Return _Port End Get Set(value As UShort) _Port = value End Set End Property Private _IntegratedSecurity As Boolean Public Property IntegratedSecurity As Boolean Get Return _IntegratedSecurity End Get Set(value As Boolean) _IntegratedSecurity = value End Set End Property Public Sub New() End Sub Private _EinstellungenSchnittstelle As EinstellungenSchnittstelle Public Property EinstellungSchnittstelle As EinstellungenSchnittstelle Get Return _EinstellungenSchnittstelle End Get Set(value As EinstellungenSchnittstelle) _EinstellungenSchnittstelle = value End Set End Property Public Function BekommeVerbindung() As System.Data.Common.DbConnection If Art = "MySQL" Then Return New MySqlConnection() With { .Host = Server, .UserId = Benutzer, .Password = Passwort, .Database = Datenbank, .Port = Port, .Charset = "UTF8"} ElseIf Art = "MSSQL" Then Dim con As New SqlConnection If IntegratedSecurity = True Then con.ConnectionString = New SqlConnectionStringBuilder With { .DataSource = Server, .InitialCatalog = Datenbank, .IntegratedSecurity = True}.ConnectionString End If con.ConnectionString = New SqlConnectionStringBuilder With { .DataSource = Server, .UserID = Benutzer, .Password = Passwort, .InitialCatalog = Datenbank}.ConnectionString Return con Else Return Nothing End If End Function End Class </code></pre> <p>SqlMethoden.vb:</p> <pre><code>Public Class SqlMethoden Enum SqlDataType VarChar Text Int End Enum Private AbfragenMY As New Dictionary(Of String, String) From { {"Datenbanken", "SHOW DATABASES"} } Private AbfragenMS As New Dictionary(Of String, String) From { {"Datenbanken", "SELECT name FROM master.dbo.sysdatabases"} } Private _Verbindung As System.Data.Common.DbConnection Public Property Verbindung As System.Data.Common.DbConnection Get Return _Verbindung End Get Set(value As System.Data.Common.DbConnection) _Verbindung = value End Set End Property Sub New(ByVal Con As System.Data.Common.DbConnection) Me.Verbindung = Con End Sub Public Function SqlSelect(ByVal Name As String, Optional ByVal Parameter As DbParameter() = Nothing) As DataTable If Me.Verbindung.GetType Is GetType(MySqlConnection) Then Using con = Verbindung Using cmd As New MySqlCommand(AbfragenMY(Name), con) If Parameter IsNot Nothing Then cmd.Parameters.AddRange(Parameter) End If Using ada As New MySqlDataAdapter(cmd) Using dt As New DataTable ada.Fill(dt) Return dt End Using End Using End Using End Using Else Using con = Verbindung Using cmd As New SqlCommand(AbfragenMS(Name), con) If Parameter IsNot Nothing Then cmd.Parameters.AddRange(Parameter) End If Using ada As New SqlDataAdapter(cmd) Using dt As New DataTable ada.Fill(dt) Return dt End Using End Using End Using End Using End If End Function Public Function ErstelleParameter(ByVal Name As String, ByVal Value As Object, ByVal Typ As SqlDataType) As DbParameter If Me.Verbindung.GetType Is GetType(MySqlConnection) Then Dim parameter As New MySqlParameter() With parameter .ParameterName = Name .Value = Value Select Case Typ Case SqlDataType.Int .MySqlType = MySqlType.Int Case SqlDataType.Text .MySqlType = MySqlType.Text Case SqlDataType.VarChar .MySqlType = MySqlType.VarChar End Select End With Return parameter Else Dim parameter As New SqlParameter With parameter .ParameterName = Name .Value = Value Select Case Typ Case SqlDataType.Int .SqlDbType = SqlDbType.Int Case SqlDataType.Text .SqlDbType = SqlDbType.Text Case SqlDataType.VarChar .SqlDbType = SqlDbType.VarChar End Select End With Return parameter End If End Function End Class </code></pre> <p>This is how i call the SqlSelect-Method:</p> <pre><code>Dim Einstell As New Einstellung 'Properties will be filled with DataBinding Dim Sql As New SqlMethoden(Einstell.BekommeVerbindung) Dim result = Sql.SqlSelect("Datenbanken") Dim resultParameter = Sql.SqlSelect("Datenbanken", { Sql.ErstelleParameter("@Test", "Test", SqlMethoden.SqlDataType.Text), Sql.ErstelleParameter("@Test2", "Test2", SqlMethoden.SqlDataType.Text)}) </code></pre> <p>It works fine for me, but I think its not very good programmed (as i am still learning). Is there even something good about this code? How to do it better?</p> <p><strong>EDIT:</strong> So I created four new classes: SqlVerbindung (Base class), MsSqlVerbindung and MySqlVerbindung (implements the Base class) and SqlFactory (creates my My or Ms class)</p> <p>SqlVerbindung.vb:</p> <pre><code>Imports System.Data.Common &lt;Serializable&gt; Public MustInherit Class SqlVerbindung Enum SqlDataType VarChar Text Int End Enum Protected AbfragenMY As New Dictionary(Of String, String) From { {"Datenbanken", "SHOW DATABASES"} } Protected AbfragenMS As New Dictionary(Of String, String) From { {"Datenbanken", "SELECT name FROM master.dbo.sysdatabases"} } Private _Server As String Public Property Server As String Get Return _Server End Get Set(value As String) _Server = value End Set End Property Private _Benutzer As String Public Property Benutzer As String Get Return _Benutzer End Get Set(value As String) _Benutzer = value End Set End Property Private _Passwort As String Public Property Passwort As String Get Return _Passwort End Get Set(value As String) _Passwort = value End Set End Property Private _Datenbank As String Public Property Datenbank As String Get Return _Datenbank End Get Set(value As String) _Datenbank = value End Set End Property Private _Art As String Public Property Art As String Get Return _Art End Get Set(value As String) _Art = value End Set End Property Private _Port As UShort = 3306 Public Property Port As UShort Get Return _Port End Get Set(value As UShort) _Port = value End Set End Property Private _IntegratedSecurity As Boolean Public Property IntegratedSecurity As Boolean Get Return _IntegratedSecurity End Get Set(value As Boolean) _IntegratedSecurity = value End Set End Property Protected MustOverride Function BekommeVerbindung() As DbConnection Protected MustOverride Function SqlSelect(ByVal Name As String, Optional ByVal Parameter As DbParameter() = Nothing) As DataTable Protected MustOverride Function ErstelleParameter(ByVal Name As String, ByVal Value As Object, ByVal Typ As SqlDataType) As DbParameter Protected MustOverride Sub SqlUpdate() End Class </code></pre> <p>MySqlVerbindung.vb:</p> <pre><code>Imports System.Data.Common Imports Devart.Data.MySql &lt;Serializable&gt; Public Class MySqlVerbindung Inherits SqlVerbindung Protected Overrides Sub SqlUpdate() Throw New NotImplementedException() End Sub Protected Overrides Function SqlSelect(Name As String, Optional Parameter() As DbParameter = Nothing) As DataTable Using con = BekommeVerbindung() Using cmd As New MySqlCommand(AbfragenMY(Name), con) If Parameter IsNot Nothing Then cmd.Parameters.AddRange(Parameter) End If Using ada As New MySqlDataAdapter(cmd) Using dt As New DataTable ada.Fill(dt) Return dt End Using End Using End Using End Using End Function Protected Overrides Function ErstelleParameter(Name As String, Value As Object, Typ As SqlDataType) As DbParameter Dim parameter As New MySqlParameter() With parameter .ParameterName = Name .Value = Value Select Case Typ Case SqlDataType.Int .MySqlType = MySqlType.Int Case SqlDataType.Text .MySqlType = MySqlType.Text Case SqlDataType.VarChar .MySqlType = MySqlType.VarChar End Select End With Return parameter End Function Protected Overrides Function BekommeVerbindung() As DbConnection Return New MySqlConnection() With { .Host = Me.Server, .UserId = Me.Benutzer, .Password = Me.Passwort, .Database = Me.Datenbank, .Port = Me.Port, .Charset = "UTF8"} End Function End Class </code></pre> <p>MsSqlVerbindung.vb:</p> <pre><code>Imports System.Data.Common Imports System.Data.SqlClient &lt;Serializable&gt; Public Class MsSqlVerbindung Inherits SqlVerbindung Protected Overrides Sub SqlUpdate() Throw New NotImplementedException() End Sub Protected Overrides Function SqlSelect(Name As String, Optional Parameter() As DbParameter = Nothing) As DataTable Using con = BekommeVerbindung() Using cmd As New SqlCommand(AbfragenMS(Name), con) If Parameter IsNot Nothing Then cmd.Parameters.AddRange(Parameter) End If Using ada As New SqlDataAdapter(cmd) Using dt As New DataTable ada.Fill(dt) Return dt End Using End Using End Using End Using End Function Protected Overrides Function ErstelleParameter(Name As String, Value As Object, Typ As SqlDataType) As DbParameter Dim parameter As New SqlParameter With parameter .ParameterName = Name .Value = Value Select Case Typ Case SqlDataType.Int .SqlDbType = SqlDbType.Int Case SqlDataType.Text .SqlDbType = SqlDbType.Text Case SqlDataType.VarChar .SqlDbType = SqlDbType.VarChar End Select End With Return parameter End Function Protected Overrides Function BekommeVerbindung() As DbConnection Dim con As New SqlConnection If Me.IntegratedSecurity = True Then con.ConnectionString = New SqlConnectionStringBuilder With { .DataSource = Me.Server, .IntegratedSecurity = True, .InitialCatalog = Me.Datenbank}.ConnectionString Else con.ConnectionString = New SqlConnectionStringBuilder With { .DataSource = Me.Server, .UserID = Me.Benutzer, .Password = Me.Passwort, .InitialCatalog = Me.Datenbank}.ConnectionString End If Return con End Function End Class </code></pre> <p>SqlFactory.vb:</p> <pre><code>Public Class SqlFactory Public Shared Function Erstellen(ByVal Art As String) As SqlVerbindung Return If(Art = "MySQL", New MySqlVerbindung, New MsSqlVerbindung) End Function End Class </code></pre> <p>Now I have a problem: Using databinding with an BindingSource (Datasource = SqlVerbindung) and I want to call the function SqlSelect. Therefore I have to check if SqlVerbindung.Art = "MySQL" or "MSSQL" and then cast it to "MsSqlVerbindung" or "MySqlVerbindung" to call the method. I think thats not how it should work. Any tips or suggestions are welcome :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T15:16:10.727", "Id": "391054", "Score": "0", "body": "Everywhere you have an if statement, is code which applies to a specific type. Therefore, do this: `class Connection {} class MsSqlConnection : Connection {} class MySqlConnecti...
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T15:03:50.413", "Id": "202877", "Score": "2", "Tags": [ "object-oriented", "sql", "mysql", "sql-server", "vb.net" ], "Title": "One class for MySQL and MSSQL Queries" }
202877
<p>Is there any reason to not do this?<br> Putting the query directly inside a <code>foreach</code>-statment when the only time the result is going to be used is within that location.. </p> <pre><code>&lt;select&gt; &lt;?php foreach($dbh-&gt;query('SELECT id, name, so FROM Employees ORDER BY so') as $e): ?&gt; &lt;option value="&lt;?=$e['so']?&gt;"&gt;-- after "&lt;?=$e['name']?&gt;" --&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; </code></pre> <p>It seems like I don't have to provide the <code>fetchAll()</code> when doing so either.<br> In fact, if I just do the following, and not adding any <code>fetch()</code>-methods at all, I still get the result if I put <code>$employees</code> into a <code>foreach</code>-loop: </p> <pre><code>$employees = $dbh-&gt;query('SELECT id, name, so FROM Employees ORDER BY so'); foreach($employees as $e){ /* works same as above */ } </code></pre> <p>when I do <code>print_r($employees)</code>, I only get this string: </p> <pre><code>PDOStatement Object ( [queryString] =&gt; SELECT id, name, so FROM Employees ORDER BY so ) </code></pre> <p>Is that correct behaviour? </p> <p>These are my options for the connection: </p> <pre><code> $options = array( PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_EMULATE_PREPARES=&gt;false, PDO::ATTR_DEFAULT_FETCH_MODE=&gt;PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND=&gt;'SET NAMES utf8', PDO::ATTR_ERRMODE=&gt;PDO::ERRMODE_EXCEPTION, // _SILENT (pub) || _WARNING || _EXCEPTION (dev) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T16:19:40.780", "Id": "391066", "Score": "0", "body": "For an explanation of why you can use the `query()` call inside the `foreach` see [this answer](https://stackoverflow.com/a/41426713/1575353). @YourCommonSense kind of explains t...
[ { "body": "<p>The idea is very bad, for many reasons. </p>\n\n<ul>\n<li>your query could fail. It will result in a torn design, with only half the page rendered.</li>\n<li>sometimes you must display a different text if the query returned no rows</li>\n<li>sometimes you need to send your data in a different form...
{ "AcceptedAnswerId": "202886", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T15:14:21.597", "Id": "202880", "Score": "-1", "Tags": [ "php", "iterator", "pdo" ], "Title": "putting sql-query response directly to foreach-loop?" }
202880
<p>I'm working on a site running woocommerce and wp where the user will add/has added a dimension attribute. </p> <p>The dimension string will take the following format originally:</p> <p>Ht: 30 1⁄2" W: 22 1⁄2" D: 18"</p> <p>and should return the string with html to format the fraction e.g:</p> <p><code>Ht: 30 &lt;sup&gt;1&lt;/sup&gt;&amp;frasl;&lt;sub&gt;2&lt;/sub&gt;" W: 22 &lt;sup&gt;1&lt;/sup&gt;&amp;frasl;&lt;sub&gt;2&lt;/sub&gt;" D: 18"</code></p> <p>will the following to consider:</p> <ul> <li>The amount of fractions in the string will be unknown (0 - X)</li> <li>The string can be any valid fraction</li> <li>The user may/may not add a space in between the fraction and the quotation e.g Ht: 30 1/2 " W...</li> </ul> <p>Here's my solution:</p> <pre><code>add_filter( 'woocommerce_attribute', __NAMESPACE__ . '\\format_dimension_attr', 10, 2 ); /** * Format fractions in the Dimension attr string to include proper html * * e.g The 1/2 in 'Height: 5 1/2"' should be * * &lt;sup&gt;1&lt;/sup&gt;&amp;frasl;&lt;sub&gt;2&lt;/sub&gt; */ function format_dimension_attr( $value, $att ) { if ( 'Dimensions' === $att['name'] ) { // Use the raw value instead of $value (which includes html) $raw = $att-&gt;get_options()[0]; if ( strpos( $raw, '/' ) !== false ) { $raw = explode( ' ', $raw ); // Check for accidental space before quotation and remove it // e.g 'height: 5 1/2 "' will produce [5, 1/2, "] $raw = array_filter( $raw, function( $val ) { return '"' !== $val; } ); // Run through the array $raw = array_map( function( $val ) { // Format the current item if it contains a slash if ( strpos( $val, '/' ) !== false ) { // Remove any " before splitting $val = explode( '/', trim( $val, '"' ) ); $val = '&lt;sup&gt;' . $val[0] . '&lt;/sup&gt;&amp;frasl;&lt;sub&gt;' . $val[1] . '&lt;/sub&gt;"'; } return $val; }, $raw ); // Replace the p tag we removed by using the raw value $value = wpautop( join( ' ', $raw ) ); } } return $value; } </code></pre>
[]
[ { "body": "<p>Well, regex is often a bad idea, but it's one of the case I find it way better than the alternative :</p>\n\n<pre><code>$raw='30 1/2 et 22 3 / 4';\necho preg_replace('/([0-9]+)\\s*\\/\\s*([0-9]+)/', '&lt;sup&gt;$1&lt;/sup&gt;&amp;frasl;&lt;sub&gt;$2&lt;/sub&gt;',$raw);\n</code></pre>\n\n<p>Just te...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T15:31:43.713", "Id": "202883", "Score": "0", "Tags": [ "php", "strings", "wordpress" ], "Title": "Formatting fractions found in a given string to html fraction" }
202883
<p>I made a code that can find the <a href="https://projecteuler.net/problem=60" rel="noreferrer">prime sets</a>:</p> <blockquote> <p>The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.</p> <p>Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.</p> </blockquote> <p>First I made a set of 2 primes that satisfies two conditions.The first condition was the digit sum cannot be 3. The other condition was the concentrating test. After finding these all 2 prime sets, I tried to add the third prime to the set and again I checked these 2 conditions are satisfied. After that, I tried to add the fourth prime and so on.</p> <p>The problem is, it gives answer in 41 min so what should I do?</p> <pre><code>import itertools import time start = time.perf_counter() def prime(N): if N == 0 or N == 1 or N == 5: return False for i in range(2, int(N ** 0.5) + 1): if N % i == 0: return False return True def dig_sum(j, n): # j is the number, n is the element in the list as tuple d = 0 if j == 0: for k in n: d += sum(int(digit) for digit in str(k)) if d%3 == 0: return False return True else: s = sum(int(digit) for digit in str(j)) for k in n: w = s + sum(int(digit) for digit in str(k)) if w % 3 == 0: return False return True def con_test(j, n): # j is the number, n is the element in the list as tuple if j == 0: w = int(str(n[0]) + str(n[1])) w1 = int(str(n[1]) + str(n[0])) if prime(w) == False or prime(w1) == False: return False return True else: for i in n: w = int(str(j) + str(i)) w1 = int(str(i) + str(j)) if prime(w) == False or prime(w1) == False: return False return True def st(n): #to get rid of the repeated elements H = [tuple(sorted(i)) for i in n] G = set(H) return G Primes = [i for i in range(3,8000) if prime(i) == True] #Prime range Com_two = list(itertools.combinations(Primes,2)) G2 = [i for i in Com_two if dig_sum(0,i) == True and con_test(0,i) == True] G2r = st(G2) G3 = [(i,*j) for i in Primes for j in G2r if dig_sum(i,j) == True and con_test(i,j) == True ] G3r = st(G3) G4 = [(i,*j) for i in Primes for j in G3r if dig_sum(i,j) == True and con_test(i,j) == True ] G4r = st(G4) G5 = [(i,*j) for i in Primes for j in G4r if dig_sum(i,j) == True and con_test(i,j) == True ] F = [(sum(j),j) for j in G5] end = time.perf_counter() Time = end-start print(Time) print(F) </code></pre>
[]
[ { "body": "<p>This is not so much of a code review question as it is an algorithm review question. </p>\n\n<p>You are calling <code>dig_sum()</code> way too much. You want pairs of primes, which summed together are not a multiple of 3: <code>p1 + p2 != 3n</code>. If <code>p1 % 3 == 1</code> and <code>p2 % 3 ...
{ "AcceptedAnswerId": "202910", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T16:50:15.290", "Id": "202887", "Score": "5", "Tags": [ "python", "programming-challenge", "time-limit-exceeded", "primes" ], "Title": "Prime pair set finder (Project Euler problem 60)" }
202887
<p>I am writing an application which has lot of checks. Most of the logic is based on conditions. How can make such code comply with SOLID principles? I cannot give the code of my application here hence I will try to simulate problem with a simpler example.</p> <pre><code>class Person { public String gender; public int age; public int birthYear; public Benefits b; public Benefits getB() { return b; } public void setB(Benefits b) { this.b = b; } } class Student extends Person { public boolean isEngineerStudent; public boolean isMedicalStudent; } class Employed extends Person { public boolean privateSector; public boolean governmentSector; public int baseIncome; } class Benefits { public boolean isInsuraceAvailabe; public boolean isStipendAvailable; public boolean isPensionAvaiable; public boolean isHealthCheckupAvailable; public boolean isTransportAvaiable; public boolean isLabFacilityProvided; public boolean isComputerFacilityProvided; } public class EnableBenefits { public void enbableBenefits(Person p) { Benefits b = new Benefits(); p.setB(b); if (p instanceof Student) { Student s = (Student) p; if (s.isEngineerStudent &amp;&amp; s.age &gt; 22) { s.b.isStipendAvailable = true; s.b.isComputerFacilityProvided = true; } if (s.isMedicalStudent &amp;&amp; s.age &gt; 20) { s.b.isStipendAvailable = true; s.b.isLabFacilityProvided = true; } } if (p instanceof Employed) { Employed e = (Employed) p; if (e.governmentSector == true &amp;&amp; e.age &gt; 40 &amp;&amp; e.gender.equalsIgnoreCase("F") &amp;&amp; e.birthYear &lt;= 1960) { e.b.isPensionAvaiable = true; e.b.isInsuraceAvailabe = true; e.b.isTransportAvaiable = true; } if (e.governmentSector == true &amp;&amp; e.age &gt; 40 &amp;&amp; e.gender.equalsIgnoreCase("M") &amp;&amp; e.birthYear &lt;= 1960 &amp;&amp; e.baseIncome &lt; 20000) { e.b.isPensionAvaiable = true; e.b.isInsuraceAvailabe = true; } if (e.privateSector == true &amp; e.gender.equalsIgnoreCase("M") &amp;&amp; e.birthYear &lt;= 1960) { e.b.isInsuraceAvailabe = true; e.b.isTransportAvaiable = true; } } p.b.isHealthCheckupAvailable = true; } } </code></pre> <p>I have purposefully made the access modifiers of instance variables as public so that it does not have too much code.</p> <p>Though the code does not have too many conditions and logic, just imagine the code for student and employee logic are in hundreds of lines.</p> <p>Questions:</p> <ol> <li><p>How can I write huge <code>if</code> conditions in a better way? Can I use Lamba here? Of course the <code>if</code> condition is not too big but in my real application I can easily have 8 conditions.</p> <pre><code>if (e.governmentSector == true &amp;&amp; e.age &gt; 40 &amp;&amp; e.gender.equalsIgnoreCase("M") &amp;&amp; e.birthYear &lt;= 1960 &amp;&amp; e.baseIncome &lt; 20000) { e.b.isPensionAvaiable = true; e.b.isInsuraceAvailabe = true; } </code></pre></li> <li><p>Is it better to write this in the inner class?</p> <pre><code>if (p instanceof Student) { Student s = (Student) p; if (s.isEngineerStudent &amp;&amp; s.age &gt; 22) { s.b.isStipendAvailable = true; s.b.isComputerFacilityProvided = true; } if (s.isMedicalStudent &amp;&amp; s.age &gt; 20) { s.b.isStipendAvailable = true; s.b.isLabFacilityProvided = true; } } </code></pre></li> </ol>
[]
[ { "body": "<p>The simplest way would be to continue with inheritance here. That will give you MedicalStudent and EngineerStudent instead of using boolean fields on Student.</p>\n<p>Then you do the same for benefits to avoid a lot of duplication in your code.</p>\n<p>And lastly you can extract your conditions to...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T16:53:07.040", "Id": "202888", "Score": "-3", "Tags": [ "java", "object-oriented", "design-patterns" ], "Title": "Application for writing checks" }
202888
<p>I'm totally new to coding and tried myself on a short text based adventure game. I got the feeling that the functions are the same ones all the time and the whole game is a bit monotonous... I'd be very thankful if anybody has some improvements or additional ideas!</p> <pre><code>import random import time def nameFunction(): #hello what's your name? name = input("Hello! What's your name, adventurer?\n") time.sleep(2) print ("Hi " + name + "...!") time.sleep(3) def storyFunction(): #the story until hard part #half story is told print ("A few miles away,") time.sleep(3) print ("behind a huge wall out of undestroyable iron and concrete,") time.sleep(4) print ("is the most dangerous and frightening place you'll ever see.") time.sleep(5) print ("Once, many, many years ago the town had the euphonious name Therondia.") time.sleep(5) print ("The people living there where called 'the happy people', because of the prevailing satisfied and sunshiny atmosphere.") time.sleep(5) print ("Inhabitants of the sorrounding areas, envied people living in this town for the friendliness \nbetween the citizens and the completely safe neighborhoods, nothing bad had ever happened in Therondia.") time.sleep(6) print ("Everybody thought of it as the perfect place to spend their life.") time.sleep(5) print ("...") time.sleep(5) print ("But then it happened...") time.sleep(5) print ("... and everything changed.") def readyFunction(): # ready to join? ready = input("Are you brave enough to join us exploring this haunted town? Then say 'yes'! But if you are too scared, you can say no...\n") if ready == "yes" or ready == "Yes" or ready == "yes!": print ("You're coming with us? That is amazing, we need every help we can get! But let us tell you the whole story so that you know in what you engage.") time.sleep(4) storyFunction() if ready == "no" or ready == "No": print ("You're not coming with us? What a petty... See you next time!") else: print ("That's not what I asked for...") readyFunction() #Problem: wenn danach das richtige eingegeben wird geht er trotzdem wieder in die Loop zu are you ready # def missionFunctionAS(): #missionFunction after school print ("Well... Where should we search now?") time.sleep(3) schoolhomechurch = input ("What do you think? Should we search for her at school (1), at her families home (2) or at church (3)?\nJust answer '1', '2' or '3'!\n") time.sleep(3) if schoolhomechurch == "1": print("- you go to the school -") time.sleep(3) print("Hmmmmm... Let's split up, so if she's here, we can find her faster. But be careful that her friends do not see you!") schoolyesno = random.randint(1,2) if schoolyesno == 1: time.sleep(4) print ("HERE SHE IS!!!") time.sleep(3) print (".....") time.sleep(3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") if schoolyesno == 2: time.sleep(4) print ("I think there is nobody around... Let's search somewhere else...") missionFunctionAS() if schoolhomechurch == "2": print ("- you go to the families home -") time.sleep(3) print ("Hmmmmm... Let's split up, so if she's here, we can find her faster. But be careful that her parents do not see you!") homeyesno = random.randint(1,2) if homeyesno == 1: time.sleep(4) print ("HERE SHE IS!!!") time.sleep(3) print (".....") time.sleep(3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") if homeyesno == 2: time.sleep(4) print ("I think there is nobody around... Let's search somewhere else...") missionFunctionAS() if schoolhomechurch == "3": print ("- you go to the church -") time.sleep(3) print ("*whispering* Wow... this is an amazing building!... But pretty scary as well...") time.sleep(3) print ("LOOK! There she is... At the confessional...") time.sleep(3) print (" ......... ") time.sleep (3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") def rightpathFunction(): #which path to get into the town? -&gt; 1. stop to be kicked out of the game!! time.sleep(4) print ("The only way to get into the city is to climb the wall with our special equipment.") time.sleep(4) print ("There is still one problem we would have to deal with if we made it to the other side of it:") time.sleep(4) print ("If anyone sees us, they will fight us. We have to be prepared for a battle.") time.sleep(4) print ("We are five people, they will be max. 10. We can overcome them if we hit 5 of them quickly. Let's go!") time.sleep(4) seen = random.randint(1, 2) if seen == 1: print ("Puhhh... We did it without drawing any attention towards us. Good Job!") missionFunction() if seen == 2: print ("Ohhhh sh***!! Okay guys we have to fight!") time.sleep(4) print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print (" Fighting... ") print ("YOU MUST HIT ABOVE 5 OF YOUR ENEMIES TO WIN THIS FIGHT") print (" IF THE ZOMBIES HIT MORE OFTEN THAN YOU, YOU WILL DIE" ) print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") time.sleep(4) humans = int(random.randint(3, 10)) zombies = int(random.randint(1, 5)) print ("You hit ", humans, "times.") time.sleep(2) print ("The Zombies hit ", zombies, "times.") time.sleep(2) if zombies &gt; humans: print ("The Zombies have dealt more damage than you!") time.sleep(3) print ("You can't make it out alive... You die a heroic death....") time.sleep(3) playAgain = input ("Do you want to try to climb the wall again? God seems to give you another chance...") if playAgain == "yes" or playAgain == "Yes" or playAgain == "yes!": rightpathFunction() else: print ("Okay! See you next time!") else: print ("You won the fight!") time.sleep(3) print ("That was amazing! But we have no to time to rest on our success, let's go on.") missionFunction() #def schoolFunction(): #print ("Hmmmmm... Let's split up, so if she's here, we can find her faster.") #time.sleep(3) #print ("If somebody finds her, he contacts the rest of us via the walkie talkie!") #-&gt;choose random string from List #schoolyesno = ["shhhht....shtshht... (out of the walkie talkie) I found her! Come to room 143.", "shhhht....shtshht... (out of the walkie talkie) I think there is nobody around... Let's search somewhere else..."] #print (random.choice(schoolyesno)) #if schoolyesno == "shhhht....shtshht... (out of the walkie talkie) I found her! Come to room 143.": #room143Function() #if schoolyesno == "shhhht....shtshht... (out of the walkie talkie) I think there is nobody around... Let's search somewhere else...": #missionFunction() #schoolyesno = random.randint(1, 2) #if schoolyesno == 1: #print ("shhhht....shtshht... (out of the walkie talkie) I found her! Come to room 143.") #room143Function() #if schoolyesno == 2: #print ("shhhht....shtshht... (out of the walkie talkie) I think there is nobody around... Let's search somewhere else...") def missionFunction(): #where to go and if the girl is found print ("We need to find the girl. She is the key to everything that happended here. If we can find out what turned her to what ever she might be now,\nwe might find the cause and can save our families... ") time.sleep(4) print ("We assume the girl to be around either her school, her home or the church of the town. As you brang us good luck last time, you should decide again.") time.sleep(3) schoolhomechurch = input ("What do you think? Should we search for her at school (1), at her families home (2) or at church (3)?\nJust answer '1', '2' or '3'!\n") time.sleep(3) if schoolhomechurch == "1": print("- you go to the school -") time.sleep(3) print("Hmmmmm... Let's split up, so if she's here, we can find her faster. But be careful that her friends do not see you!") schoolyesno = random.randint(1,2) if schoolyesno == 1: time.sleep(4) print ("HERE SHE IS!!!") time.sleep(3) print (".....") time.sleep(3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") if schoolyesno == 2: time.sleep(4) print ("I think there is nobody around... Let's search somewhere else...") missionFunctionAS() if schoolhomechurch == "2": print ("- you go to the families home -") time.sleep(3) print ("Hmmmmm... Let's split up, so if she's here, we can find her faster. But be careful that her parents do not see you!") homeyesno = random.randint(1,2) if homeyesno == 1: time.sleep(4) print ("HERE SHE IS!!!") time.sleep(3) print (".....") time.sleep(3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") if homeyesno == 2: time.sleep(4) print ("I think there is nobody around... Let's search somewhere else...") missionFunctionAS() if schoolhomechurch == "3": print ("- you go to the church -") time.sleep(3) print ("*whispering* Wow... this is an amazing building!... But pretty scary as well...") time.sleep(3) print ("LOOK! There she is... At the confessional...") time.sleep(3) print (" ......... ") time.sleep (3) print ("Now that we know what happened to her, we can go home and carry on research for couring sickened people.") time.sleep(3) print ("And when we find a remedy, we'll come back and try to bring this town the peace it once held.") time.sleep(5) print ("... to be continued,extended and improved...") def rightpathFunction(): #which path to get into the town? -&gt; 1. stop to be kicked out of the game!! time.sleep(4) print ("There are two ways to get into the city: We could climb the wall (1) or take the secret tunnel (2).\nBoth have their risks.") time.sleep(4) print ("If we climb the wall and somebody sees us we will be dead by the time we arrive on the other side.\nIn the tunnel there are poisonous plants that randomly eject deadly gas that kills immediatly when inhaled.") time.sleep(4) chosenPath = input ("Which path should we try? 1 or 2 ? \n") time.sleep(3) print ("Okay... Let's take it! There's no wrong or right decision, it's just good or bad luck for us right now...") time.sleep(3) correctPath = random.randint(1,2) if str(chosenPath) == str(correctPath): print ("YES! You are amazing! We're inside! You will make all the decisions from now.") missionFunction() if str(chosenPath) != str(correctPath): print ("Oh....") time.sleep(3) print ("Ooooooooh NO !!!") time.sleep(3) print ("We...won't make it.") time.sleep(3) print ("----------------------------game over------------------------------") time.sleep(3) playAgain = input ("Do you want to choose again?") if playAgain == "yes" or playAgain == "Yes" or playAgain == "yes!": rightpathFunction() else: print ("Okay! See you next time!") def stillinFunction(): stillin = input ("Are you still willing to come with us?\n") if stillin == "yes" or stillin == "Yes" or stillin == "yes!": print ("Wow, I'm impressed. We can really need somebody brave like you. Which path shall we take?") rightpathFunction() if stillin == "no" or stillin == "No" or stillin == "no!": print ("Okay... We totally understand your choice. Goodbye!") if stillin != "yes" and stillin != "Yes" and stillin != "yes!" and stillin != "no" and stillin != "No": stillinFunction() #still in after hearing the whole story #still in after hearing the whole story? def wholestoryFunction(): #beeing told the whole story wholestory = input("Do you still want to hear the whole story? You might change your mind after hearing it...\n") if wholestory == "yes" or wholestory == "Yes" or wholestory == "yes!": print ("So you seem to be one of the fearless ones...") time.sleep(3) print ("Fine. Here's the end of the tragedy.") time.sleep(3) print ("One day the little daughter of the mayor got missing.") time.sleep(3) print ("Nobody could imagine what could've happened to her, the girl was a good kid who woul've never run away.") time.sleep(4) print ("Moreover there was no ransom demand or anything similar that could've indicated a kidnap.") time.sleep(4) print ("The whole town was searching for her for 3 whole months.") time.sleep(3) print ("But then one day, all of a sudden, she came home to the front door as if nothing had ever happened.") time.sleep(5) print ("She was completly unharmed and at first showed no signs of mental problems,\nexcept that she couldn't remember anyhting from the last quarter of the year.") time.sleep(6) print ("The little girl went back to school just one day after beeing back home and everything seemed normal until the some kids\nin the class of the little girl got sick.") time.sleep(6) print ("From one day to another, they lost their ability to speak.") time.sleep(4) print ("In addition, they had anxiety attacks and always their face was contorted with pain. No doctor knew what to do...") time.sleep(4) print ("At first many children fell ill, but when the first parent fell sick, everyone knew, that it was a matter of time when the whole town would be infected.") time.sleep(4) print ("Panic broke out. Parents needed to decide - stay with their infected children or leave before it was too late.") time.sleep(5) print ("Many people left. But some stayed...") time.sleep(3) print ("And they still 'live' there. But they became something similar to zombies.") time.sleep(4) print ("Until now, they couldn't leave because of the wall the fleeing inhabitants built around their hometown,\nbut it's getting ramsackle...") time.sleep(5) print ("We need to get in and find the cause for the virus or whatever it may be, before they break out and infect all the adjoining villages.") stillinFunction() if wholestory == "no" or wholestory == "No" or wholestory == "no!": print ("I understand, let's just get in there and try to get out alive. You can choose which path we take to go there.") rightpathFunction() if wholestory != "yes" and wholestory != "Yes" and wholestory != "yes!" and wholestory != "no" and wholestory != "No": wholestoryFunction() #else: #wholestoryFunction() def mainFunction():#mainFunction nameFunction() readyFunction() wholestoryFunction() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T21:15:07.637", "Id": "391242", "Score": "1", "body": "I noticed you commented out \"schoolFunction\" by using an octothorpe on each line. You can actually do this much easier by just turning it into a docstring by putting three quot...
[ { "body": "<p>A few remarks:</p>\n\n<ol>\n<li>Sleep duration is hard coded, it can be automatically calculated (depending on the text length).</li>\n<li>Display can be a function (including the sleep function).</li>\n<li>So you can just pass the string, it prints and waits.</li>\n<li>Instead of comparing the us...
{ "AcceptedAnswerId": "202923", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T17:22:10.243", "Id": "202889", "Score": "5", "Tags": [ "python", "beginner", "adventure-game" ], "Title": "Short text-based adventure game" }
202889
<blockquote> <p>Armstrong like numbers are those which are equal to the sum of the cubes of their 1/3rd parts. For example: </p> <ul> <li><p>\$165033 = 16^3 + 50^3 + 33^3\$</p></li> <li><p>\$166500333 = 166^3 + 500^3 + 333^3\$</p></li> </ul> </blockquote> <p>Here is my code, works fine, but I want to know how I can improve it: </p> <p>Method check() checks if the number is armstrong like and generate() generates 6 digit armstrong like numbers. </p> <pre><code>class Armstronglike { static boolean check(long n) { String s = Long.toString(n); int l = s.length(); if(l%3 !=0 ) { return false; } else { long sum =0; long num = n; long k = (long)Math.pow(10, s.length()/3); for(int i = 1; i&lt;= 3; i++) { sum = sum + (long)Math.pow((num%k), 3); num = num/k; } if(sum == n) { return true; } else return false; } } static void generate() //to generate 6 digit armstrong numbers { System.out.println("6 digit armstrong numbers are: "); for(long i = 100000; i&lt;1000000 ; i++) { if(check(i)== true) { System.out.println(i); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T20:10:23.393", "Id": "391085", "Score": "0", "body": "In your generator, instead of trying all the numbers, iterate on the three subparts. Keep in mind that the greatest of the three parts must be at least ((10^n)/3)^(1/3) where n i...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T18:43:39.823", "Id": "202892", "Score": "3", "Tags": [ "java" ], "Title": "Program to generate Armstrong like numbers (java)" }
202892
<p>My code works perfectly but it is redundant. How does one condense this? How do you use the =! operator? Any help would be greatly appreciated. </p> <pre><code>$("#about").click(function(){ $( ".home" ).hide(); $( ".headr" ).show(); $( ".about" ).show(); $( ".skills" ).hide(); $( ".experience" ).hide(); $( ".education" ).hide(); $( ".examples" ).hide(); console.log("about clicked"); }); $("#skills").click(function(){ $( ".home" ).hide(); $( ".headr" ).show(); $( ".about" ).hide(); $( ".skills" ).show(); $( ".experience" ).hide(); $( ".education" ).hide(); $( ".examples" ).hide(); console.log("skills clicked"); }); $("#experience").click(function(){ $( ".home" ).hide(); $( ".headr" ).show(); $( ".about" ).hide(); $( ".skills" ).hide(); $( ".experience" ).show(); $( ".education" ).hide(); $( ".examples" ).hide(); console.log("experience clicked"); }); $("#education").click(function(){ $( ".home" ).hide(); $( ".headr" ).show(); $( ".about" ).hide(); $( ".skills" ).hide(); $( ".experience" ).hide(); $( ".education" ).show(); $( ".examples" ).hide(); console.log("education clicked"); }); $("#examples").click(function(){ $( ".home" ).hide(); $( ".headr" ).show(); $( ".about" ).hide(); $( ".skills" ).hide(); $( ".experience" ).hide(); $( ".education" ).hide(); $( ".examples" ).show(); console.log("examples clicked"); }); </code></pre>
[]
[ { "body": "<p>1) Add another common class (using <code>toggle</code> in the example) to all of your tags</p>\n\n<pre><code>&lt;div class=\"toggle home\"&gt;data&lt;/div&gt;\n&lt;div class=\"toggle headr\"&gt;data&lt;/div&gt;\n&lt;div class=\"toggle about\"&gt;data&lt;/div&gt;\n&lt;div class=\"toggle skills\"&gt...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T21:20:13.493", "Id": "202897", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Basic jQuery hide/show code" }
202897
<blockquote> <p>We need the input number as the sum of consecutive natural numbers.</p> <p>Examples: </p> <p>For input 27, output should be: </p> <p>2 3 4 5 6 7 </p> <p>8 9 10 </p> <p>13 14</p> <p>For input 9, the output should be: </p> <p>4 5</p> <p>2 3 4</p> </blockquote> <p>Here is my code. It works as it is expected to: </p> <pre><code>import java.util.*; class Consecutives { static void print() { Scanner sc = new Scanner(System.in); System.out.println("Enter number: "); double n = sc.nextDouble(); /* * Needed: Different Arithmetic progressions (APs) with common difference 1; * i(2a + (i-1)) = 2n // from formula for sum of AP, a indicates first term of progression * #implies -&gt; a = n/i - (i-1)/2 // i indicates number of terms of AP possible * Now, a can't be negative so: * -&gt; n/i &gt; (i-1)/2 * -&gt; Range of i = [2, (int)(1+sqrt(1+8n))/2] */ int max_i = (int)((1+Math.sqrt(1+8*n))/2); System.out.println("Max i = "+ max_i); double a; for(double i=2; i &lt;= max_i ;i++) { a = n/i - (i-1)/2; if(a == Math.floor(a) &amp;&amp; a&gt;0)//i.e if a is an integer { if(i*(2*a+ (i-1))== 2*n) { for(int j= (int)a ; j&lt;=a + (i-1) ;j++) System.out.print(j+ " "); System.out.println(); } else break; } } } } </code></pre> <p>Are my comments too messy? Is there any way to change them and still make the logic clear to the reader? What other improvements can I make to my program? </p>
[]
[ { "body": "<p>Your algorithm, being \\$O(\\sqrt n)\\$, is pretty efficient. I just think that your code could just a bit of cleanup.</p>\n\n<p>Your <code>print()</code> function does all kinds of things, mostly unrelated to printing. You should separate the code for the user interaction from the calculation. ...
{ "AcceptedAnswerId": "202903", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-31T22:16:10.257", "Id": "202901", "Score": "3", "Tags": [ "java" ], "Title": "Program to print the number as a sum of consecutives" }
202901
<p>In the <a href="https://codereview.stackexchange.com/q/202851/23788">previous post</a> I presented the MVC architecture, but all we saw of the <em>View</em> was the pretty bits. From the outside everything looks innocently pretty:</p> <p><a href="https://i.stack.imgur.com/zeeTS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zeeTS.png" alt="Battleship game in progress"></a></p> <p>The guts of the worksheet's code-behind is a bit more... chaotic. Maybe not <em>chaotic-evil</em>, but chaotic nonetheless, despite the fact that it's really doing nothing more than exposing methods for the <code>GridViewAdapter</code> to interfact with, and handful of events for the <code>GridViewAdapter</code> to handle &amp; relay to the game controller... I find there's too much code in there.</p> <p>The UI involves a rather large number of named shapes (some clickable and thus attached to a sheet-local macro), so a lot of that code is just named (often indexed) properties that return a specific shape. The various shapes include the "player" buttons you click to pick your grid and opponent, the "fleet status" box, the ship pictures in it, and each individual "X" marker carefully positioned to cover each ship's peg holes; then there's a gigantic "HIT!", "MISS" and "SUNK" shape on each grid, and two "Game Over" shapes per grid (one winning, one losing), and in AI vs AI games there's an "acquired targets" box under each grid to show each player's enemy ships, with an "X" marker to mark sunken targets. Oh and then there's an "information" and "error" box with a clickable OK button to display various messages.</p> <p><a href="https://i.stack.imgur.com/pgyAM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pgyAM.png" alt="game screen with all shapes visible"></a></p> <p>The grid cells contain a hidden numeric value, and the white/red dots (and ships' preview/confirmed/illegal positions) are achieved using a custom conditional formatting:</p> <p><img src="https://i.stack.imgur.com/jxpfW.png" alt="custom conditional formatting configuration"></p> <p>These values correspond to the <code>GridState</code> enum values.</p> <p>All feedback &amp; cleanup ideas are welcome!</p> <pre><code>'@Folder("Battleship.View.Worksheet") Option Explicit Private Const InfoBoxMessage As String = _ "ENEMY FLEET DETECTED" &amp; vbNewLine &amp; _ "ALL SYSTEMS READY" &amp; vbNewLine &amp; vbNewLine &amp; _ "DOUBLE CLICK IN THE ENEMY GRID TO FIRE A MISSILE." &amp; vbNewLine &amp; vbNewLine &amp; _ "FIND AND DESTROY ALL ENEMY SHIPS BEFORE THEY DESTROY YOUR OWN FLEET!" Private Const InfoBoxPlaceShips As String = _ "FLEET DEPLOYMENT" &amp; vbNewLine &amp; _ "ACTION REQUIRED: DEPLOY %SHIP%" &amp; vbNewLine &amp; vbNewLine &amp; _ " -CLICK TO PREVIEW" &amp; vbNewLine &amp; _ " -RIGHT CLICK TO ROTATE" &amp; vbNewLine &amp; _ " -DOUBLE CLICK TO CONFIRM" &amp; vbNewLine &amp; vbNewLine Private Const ErrorBoxInvalidPosition As String = _ "FLEET DEPLOYMENT" &amp; vbNewLine &amp; _ "SYSTEM ERROR" &amp; vbNewLine &amp; vbNewLine &amp; _ " -SHIPS CANNOT OVERLAP." &amp; vbNewLine &amp; _ " -SHIPS MUST BE ENTIRELY WITHIN THE GRID." &amp; vbNewLine &amp; vbNewLine &amp; _ "DEPLOY SHIP TO ANOTHER POSITION." Private Const ErrorBoxInvalidKnownAttackPosition As String = _ "TARGETING SYSTEM" &amp; vbNewLine &amp; vbNewLine &amp; _ "SPECIFIED GRID LOCATION IS ALREADY IN A KNOWN STATE." &amp; vbNewLine &amp; vbNewLine &amp; _ "NEW VALID COORDINATES REQUIRED." Private previousMode As ViewMode Private Mode As ViewMode Private Random As IRandomizer Public Event CreatePlayer(ByVal gridId As Byte, ByVal pt As PlayerType, ByVal difficulty As AIDifficulty) Public Event SelectionChange(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) Public Event RightClick(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) Public Event DoubleClick(ByVal gridId As Byte, ByVal position As IGridCoord, ByVal Mode As ViewMode) Public Sub OnNewGame() Application.ScreenUpdating = False Mode = NewGame ClearGrid 1 ClearGrid 2 LockGrids HideAllShapes ShowShapes HumanPlayerButton(1), _ AIPlayerButton(1, RandomAI), _ AIPlayerButton(1, FairplayAI), _ AIPlayerButton(1, MercilessAI), _ HumanPlayerButton(2), _ AIPlayerButton(2, RandomAI), _ AIPlayerButton(2, FairplayAI), _ AIPlayerButton(2, MercilessAI) Me.Activate Application.ScreenUpdating = True End Sub Private Sub Worksheet_Activate() Set Random = New GameRandomizer End Sub Private Sub Worksheet_BeforeDoubleClick(ByVal target As Range, ByRef Cancel As Boolean) Cancel = True Dim gridId As Byte Dim position As IGridCoord Set position = RangeToGridCoord(target, gridId) RaiseEvent DoubleClick(gridId, position, Mode) End Sub Private Sub Worksheet_BeforeRightClick(ByVal target As Range, Cancel As Boolean) Cancel = True If Mode = FleetPosition Then Dim gridId As Byte Dim position As IGridCoord Set position = RangeToGridCoord(target, gridId) RaiseEvent RightClick(gridId, position, Mode) End If End Sub Private Sub Worksheet_SelectionChange(ByVal target As Range) Dim gridId As Byte Dim position As IGridCoord Set position = RangeToGridCoord(target, gridId) If Not position Is Nothing Then Me.Unprotect CurrentSelectionGrid(gridId).value = position.ToA1String CurrentSelectionGrid(IIf(gridId = 1, 2, 1)).value = Empty Me.Protect Me.EnableSelection = xlUnlockedCells RaiseEvent SelectionChange(gridId, position, Mode) End If End Sub Public Function RangeToGridCoord(ByVal target As Range, ByRef gridId As Byte) As IGridCoord If target.Count &gt; 1 Then Exit Function For gridId = 1 To 2 With PlayerGrid(gridId) If Not Intersect(.Cells, target) Is Nothing Then Set RangeToGridCoord = _ GridCoord.Create(xPosition:=target.Column - .Column + 1, _ yPosition:=target.Row - .Row + 1) Exit Function End If End With Next End Function Public Function GridCoordToRange(ByVal gridId As Byte, ByVal position As IGridCoord) As Range With PlayerGrid(gridId) Set GridCoordToRange = .Cells(position.Y, position.X) End With End Function Public Sub ClearGrid(ByVal gridId As Byte) Me.Unprotect PlayerGrid(gridId).value = Empty Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub LockGrids() Me.Unprotect PlayerGrid(1).Locked = True PlayerGrid(2).Locked = True Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub UnlockGrid(ByVal gridId As Byte) Me.Unprotect PlayerGrid(gridId).Locked = False PlayerGrid(IIf(gridId = 1, 2, 1)).Locked = True Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub LockGrid(ByVal gridId As Byte) Me.Unprotect PlayerGrid(gridId).Locked = True PlayerGrid(IIf(gridId = 1, 2, 1)).Locked = False Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Private Property Get PlayerGrid(ByVal gridId As Byte) As Range Set PlayerGrid = Me.Names("PlayerGrid" &amp; gridId).RefersToRange End Property Private Property Get CurrentSelectionGrid(ByVal gridId As Byte) As Range Set CurrentSelectionGrid = Me.Names("CurrentSelectionGrid" &amp; gridId).RefersToRange End Property Private Property Get TitleLabel() As Shape Set TitleLabel = Me.Shapes("Title") End Property Private Property Get MissLabel(ByVal gridId As Byte) As Shape Set MissLabel = Me.Shapes("MissLabelGrid" &amp; gridId) End Property Private Property Get HitLabel(ByVal gridId As Byte) As Shape Set HitLabel = Me.Shapes("HitGrid" &amp; gridId) End Property Private Property Get SunkLabel(ByVal gridId As Byte) As Shape Set SunkLabel = Me.Shapes("SunkGrid" &amp; gridId) End Property Private Property Get GameOverWinLabel(ByVal gridId As Byte) As Shape Set GameOverWinLabel = Me.Shapes("GameOverWinGrid" &amp; gridId) End Property Private Property Get GameOverLoseLabel(ByVal gridId As Byte) As Shape Set GameOverLoseLabel = Me.Shapes("GameOverLoseGrid" &amp; gridId) End Property Private Property Get InformationBox() As Shape Set InformationBox = Me.Shapes("InformationBox") End Property Private Property Get ErrorBox() As Shape Set ErrorBox = Me.Shapes("ErrorBox") End Property Private Property Get FleetStatusBox() As Shape Set FleetStatusBox = Me.Shapes("FleetStatusBox") End Property Private Property Get AcquiredTargetsBox(ByVal gridId As Byte) As Shape Set AcquiredTargetsBox = Me.Shapes("Grid" &amp; gridId &amp; "TargetsBox") End Property Private Property Get AcquiredTargetShip(ByVal gridId As Byte, ByVal shipName As String) As Shape Set AcquiredTargetShip = Me.Shapes("Grid" &amp; gridId &amp; "Target_" &amp; VBA.Strings.Replace(shipName, " ", vbNullString)) End Property Private Property Get ShipHitMarker(ByVal shipName As String, ByVal index As Byte) As Shape Set ShipHitMarker = Me.Shapes(VBA.Strings.Replace(shipName, " ", vbNullString) &amp; "_Hit" &amp; index) End Property Private Property Get SunkTargetMarker(ByVal gridId As Byte, ByVal shipName As String) As Shape Set SunkTargetMarker = Me.Shapes("Grid" &amp; gridId &amp; "TargetSunk_" &amp; VBA.Strings.Replace(shipName, " ", vbNullString)) End Property Private Property Get HumanPlayerButton(ByVal gridId As Byte) As Shape Set HumanPlayerButton = Me.Shapes("HumanPlayer" &amp; gridId) End Property Private Property Get AIPlayerButton(ByVal gridId As Byte, ByVal difficulty As AIDifficulty) As Shape Select Case difficulty Case AIDifficulty.RandomAI Set AIPlayerButton = Me.Shapes("RandomAIPlayer" &amp; gridId) Case AIDifficulty.FairplayAI Set AIPlayerButton = Me.Shapes("FairPlayAIPlayer" &amp; gridId) Case AIDifficulty.MercilessAI Set AIPlayerButton = Me.Shapes("MercilessAIPlayer" &amp; gridId) End Select End Property Private Sub HidePlayerButtons(Optional ByVal gridId As Byte) If gridId = 0 Then For gridId = 1 To 2 HideShapes HumanPlayerButton(gridId), _ AIPlayerButton(gridId, RandomAI), _ AIPlayerButton(gridId, FairplayAI), _ AIPlayerButton(gridId, MercilessAI) Next Else HideShapes HumanPlayerButton(gridId), _ AIPlayerButton(gridId, RandomAI), _ AIPlayerButton(gridId, FairplayAI), _ AIPlayerButton(gridId, MercilessAI) End If End Sub Public Sub OnHumanPlayer1() HidePlayerButtons 1 HideShapes HumanPlayerButton(2) RaiseEvent CreatePlayer(1, HumanControlled, Unspecified) End Sub Public Sub OnHumanPlayer2() HidePlayerButtons 2 HideShapes HumanPlayerButton(1) RaiseEvent CreatePlayer(2, HumanControlled, Unspecified) End Sub Public Sub OnRandomAIPlayer1() HidePlayerButtons 1 RaiseEvent CreatePlayer(1, ComputerControlled, RandomAI) End Sub Public Sub OnRandomAIPlayer2() HidePlayerButtons 2 RaiseEvent CreatePlayer(2, ComputerControlled, RandomAI) End Sub Public Sub OnFairPlayAIPlayer1() HidePlayerButtons 1 RaiseEvent CreatePlayer(1, ComputerControlled, FairplayAI) End Sub Public Sub OnFairPlayAIPlayer2() HidePlayerButtons 2 RaiseEvent CreatePlayer(2, ComputerControlled, FairplayAI) End Sub Public Sub OnMercilessAIPlayer1() HidePlayerButtons 1 RaiseEvent CreatePlayer(1, ComputerControlled, MercilessAI) End Sub Public Sub OnMercilessAIPlayer2() HidePlayerButtons 2 RaiseEvent CreatePlayer(2, ComputerControlled, MercilessAI) End Sub Public Sub HideInformationBox() InformationBox.Visible = msoFalse Mode = previousMode If Mode = player1 Then UnlockGrid 2 ElseIf Mode = player2 Then UnlockGrid 1 End If Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub HideErrorBox() ErrorBox.Visible = msoFalse Mode = previousMode Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub ShowInfoBeginDeployShip(ByVal shipName As String) Mode = FleetPosition ShowFleetStatus ShowInformation Replace(InfoBoxPlaceShips, "%SHIP%", UCase$(shipName)) End Sub Public Sub ShowInfoBeginAttackPhase() Mode = player1 ShowInformation InfoBoxMessage End Sub Public Sub ShowErrorKnownPositionAttack() ShowError ErrorBoxInvalidKnownAttackPosition End Sub Public Sub RefreshGrid(ByVal grid As PlayerGrid) Application.ScreenUpdating = False Me.Unprotect PlayerGrid(grid.gridId).value = Application.WorksheetFunction.Transpose(grid.StateArray) Me.Protect Me.EnableSelection = xlUnlockedCells Application.ScreenUpdating = True End Sub Private Sub ShowInformation(ByVal message As String) Me.Unprotect With InformationBox With .GroupItems("InformationBoxBackground") With .TextFrame .Characters.Delete .Characters.Text = vbNewLine &amp; message .VerticalAlignment = xlVAlignTop .VerticalOverflow = xlOartVerticalOverflowEllipsis .HorizontalAlignment = xlHAlignLeft End With End With .Visible = msoTrue End With previousMode = Mode Mode = MessageShown Me.Protect Me.EnableSelection = xlNoSelection End Sub Public Sub ShowError(ByVal message As String) Me.Unprotect With ErrorBox With .GroupItems("ErrorBoxBackground") With .TextFrame .Characters.Delete .Characters.Text = vbNewLine &amp; message .VerticalAlignment = xlVAlignTop .VerticalOverflow = xlOartVerticalOverflowEllipsis .HorizontalAlignment = xlHAlignLeft End With End With .Visible = msoTrue End With previousMode = Mode Mode = MessageShown Me.Protect Me.EnableSelection = xlNoSelection End Sub Public Sub HideAllShapes() Me.Unprotect Application.ScreenUpdating = False HideFleetStatus HideAcquiredTargetBoxes HideShapes InformationBox, ErrorBox Dim grid As Byte For grid = 1 To 2 HideShapes HitLabel(grid), _ SunkLabel(grid), _ MissLabel(grid), _ MissLabel(grid), _ HumanPlayerButton(grid), _ AIPlayerButton(grid, RandomAI), _ AIPlayerButton(grid, FairplayAI), _ AIPlayerButton(grid, MercilessAI), _ GameOverWinLabel(grid), _ GameOverLoseLabel(grid), _ AcquiredTargetsBox(grid) Next Application.ScreenUpdating = True Me.Protect End Sub Public Sub ShowAllShapes() 'for debugging Application.ScreenUpdating = False ShowFleetStatus ShowAcquiredTargetBoxes ShowShapes InformationBox, ErrorBox Dim grid As Byte For grid = 1 To 2 ShowShapes HitLabel(grid), _ SunkLabel(grid), _ MissLabel(grid), _ MissLabel(grid), _ HumanPlayerButton(grid), _ AIPlayerButton(grid, RandomAI), _ AIPlayerButton(grid, FairplayAI), _ AIPlayerButton(grid, MercilessAI), _ GameOverWinLabel(grid), _ GameOverLoseLabel(grid), _ AcquiredTargetsBox(grid) Next Application.ScreenUpdating = True End Sub Private Sub HideFleetStatus() HideShapes FleetStatusBox Dim shipFleet As Scripting.Dictionary Set shipFleet = Ship.Fleet Dim Names As Variant Names = shipFleet.Keys Dim sizes As Variant sizes = shipFleet.Items Dim currentName As Byte For currentName = LBound(Names) To UBound(Names) HideShipStatus Names(currentName) Dim position As Byte For position = 1 To sizes(currentName) HideShapes ShipHitMarker(Names(currentName), position) Next Next End Sub Private Sub HideAcquiredTargetBoxes() Dim shipFleet As Scripting.Dictionary Set shipFleet = Ship.Fleet Dim Names As Variant Names = shipFleet.Keys Dim gridId As Byte For gridId = 1 To 2 AcquiredTargetsBox(gridId).Visible = msoFalse Dim currentName As Byte For currentName = LBound(Names) To UBound(Names) AcquiredTargetShip(gridId, Names(currentName)).Visible = msoFalse SunkTargetMarker(gridId, Names(currentName)).Visible = msoFalse Next Next End Sub Private Sub ShowAcquiredTargetBoxes() Dim shipFleet As Scripting.Dictionary Set shipFleet = Ship.Fleet Dim Names As Variant Names = shipFleet.Keys Dim gridId As Byte For gridId = 1 To 2 AcquiredTargetsBox(gridId).Visible = msoTrue Dim currentName As Byte For currentName = LBound(Names) To UBound(Names) AcquiredTargetShip(gridId, Names(currentName)).Visible = msoTrue SunkTargetMarker(gridId, Names(currentName)).Visible = msoTrue Next Next End Sub Public Sub ShowAcquiredTarget(ByVal gridId As Byte, ByVal shipName As String, Optional ByVal sunken As Boolean = False) AcquiredTargetsBox(gridId).Visible = msoTrue AcquiredTargetShip(gridId, shipName).Visible = msoTrue SunkTargetMarker(gridId, shipName).Visible = IIf(sunken, msoTrue, msoFalse) End Sub Private Sub ShowFleetStatus() FleetStatusBox.Visible = msoTrue End Sub Private Sub HideShipStatus(ByVal shipName As String) Me.Shapes("FleetStatus_" &amp; VBA.Strings.Replace(shipName, " ", vbNullString)).Visible = msoFalse End Sub Private Sub ShowShipStatus(ByVal shipName As String) Me.Shapes("FleetStatus_" &amp; VBA.Strings.Replace(shipName, " ", vbNullString)).Visible = msoTrue End Sub Public Sub UpdateShipStatus(ByVal player As IPlayer, ByVal hitShip As IShip) Dim positions As Variant positions = hitShip.StateArray Dim currentPosition As Byte, currentMarker As Byte For currentPosition = LBound(positions) To UBound(positions) currentMarker = currentMarker + 1 If positions(currentPosition) Then If player.PlayerType = HumanControlled Then ShipHitMarker(hitShip.Name, currentMarker).Visible = msoTrue Else 'todo: update AI player targets End If End If Next End Sub Public Sub ShowAnimationMiss(ByVal gridId As Byte) FlashShape MissLabel(gridId), IIf(Random.NextSingle &lt; 0.75, 1, IIf(Random.NextSingle &lt; 0.75, 2, 3)), 10 End Sub Public Sub ShowAnimationHit(ByVal gridId As Byte) FlashShape HitLabel(gridId), IIf(Random.NextSingle &lt; 0.75, 1, IIf(Random.NextSingle &lt; 0.75, 2, 3)) End Sub Public Sub ShowAnimationSunk(ByVal gridId As Byte) FlashShape SunkLabel(gridId), IIf(Random.NextSingle &lt; 0.75, 2, 4), 12 End Sub Public Sub ShowAnimationVictory(ByVal gridId As Byte) GameOverWinLabel(gridId).Visible = msoTrue Mode = GameOver End Sub Public Sub ShowAnimationDefeat(ByVal gridId As Byte) FlashShape GameOverLoseLabel(gridId), 4 GameOverLoseLabel(gridId).Visible = msoTrue Mode = GameOver End Sub Public Sub PreviewShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) RefreshGrid player.PlayGrid Me.Unprotect With PlayerGrid(player.PlayGrid.gridId) _ .Cells(1, 1) _ .Offset(newShip.GridPosition.Y - 1, newShip.GridPosition.X - 1) _ .Resize(RowSize:=IIf(newShip.Orientation = Vertical, newShip.Size, 1), _ ColumnSize:=IIf(newShip.Orientation = Horizontal, newShip.Size, 1)) .value = GridState.PreviewShipPosition End With Dim intersecting As GridCoord Set intersecting = player.PlayGrid.IntersectsAny(newShip.GridPosition, newShip.Orientation, newShip.Size) If Not intersecting Is Nothing Then PlayerGrid(player.PlayGrid.gridId).Cells(intersecting.Y, intersecting.X).value = GridState.InvalidPosition End If Me.Protect Me.EnableSelection = xlUnlockedCells End Sub Public Sub ConfirmShipPosition(ByVal player As IPlayer, ByVal newShip As IShip, ByRef confirmed As Boolean) If player.PlayGrid.CanAddShip(newShip.GridPosition, newShip.Orientation, newShip.Size) Then player.PlayGrid.AddShip newShip RefreshGrid player.PlayGrid ShowShipStatus newShip.Name confirmed = True Else ShowError ErrorBoxInvalidPosition End If End Sub Public Sub ShowShapes(ParamArray objects() As Variant) Win32API.ScreenUpdate False Dim i As Long, current As Shape For i = LBound(objects) To UBound(objects) Set current = objects(i) current.Visible = msoTrue Next Win32API.ScreenUpdate True End Sub Public Sub HideShapes(ParamArray objects() As Variant) Win32API.ScreenUpdate False Dim i As Long, current As Shape For i = LBound(objects) To UBound(objects) Set current = objects(i) current.Visible = msoFalse Next Win32API.ScreenUpdate True End Sub Private Sub FlashShape(ByVal target As Shape, ByVal flashes As Long, Optional ByVal Delay As Long = 8) Me.Unprotect target.Rotation = -10 + (Random.NextSingle * 20) 'Target.Top = Target.Top - 10 + (random.NextSingle * 20) 'Target.Left = Target.Left - 10 + (random.NextSingle * 20) ShowShapes target Sleep Delay * 10 Dim i As Long For i = 0 To flashes - 1 ShowShapes target Sleep Delay * 1.5 HideShapes target Sleep Delay * 0.75 Next ShowShapes target Sleep Delay * 20 HideShapes target Me.Protect End Sub </code></pre> <hr> <p>Update: The full code is now <a href="https://github.com/rubberduck-vba/Battleship" rel="nofollow noreferrer">on GitHub</a>!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T07:13:02.153", "Id": "391114", "Score": "0", "body": "Again, don't have time to run a proper review answer. A quick thought for the `Public Sub On[]PlayerX` series could be collapsed into a single sub with two parameters (P1, P2 ta...
[ { "body": "<p>One thing I'm confused about while reading this, is <code>gridId as Byte</code> - I assume it can only be <code>1</code> or <code>2</code> - ID of the player, unless I'm mistaken.</p>\n\n<p>So in <code>RangeToGridCoord</code> you take the <code>gridID</code> <em>ByRef</em>, but <em>why?</em></p>\n...
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T05:55:49.020", "Id": "202911", "Score": "9", "Tags": [ "object-oriented", "vba", "excel" ], "Title": "Battleship UI: GameSheet" }
202911
<p>My program generates URLs. It takes in 3 variables and substitutes them in a URL to create different working URLs. It also has 3 options for language selection, which change the language of the page to which the URL points.</p> <p>However, the more options I add the more copy - pasted code there is. I know there is a way to simplify the code and only add the changes, however I'm still new to Python and I'm not too sure how.</p> <pre><code>#created by Kaloian Kozlev on 10.08.2018 import replit import time def welcome(): choice = 0 while choice &lt;= 5: print( "\nWelcome to URL Generator v3.0 VERSION UPDATE: 31/08/2018 \n-------------------------------- -------------------------- \n\n1.Direct/Combined 2.Indirect 1. Multiple offer link added \n3.Console 4.Facebook 2. Facebook link added \n 3. Multipe language support \n5.Exit \n-------------------------------- -------------------------- " ) try: print("\n1. English \n2. German\n3. French ") lang = int(input("\nSelect Language: ")) #English if lang == 1: choice = int(input("\nSelect URL generator: ")) if choice == 1: multiple = str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") if multiple =="n": print("\n\nSingle offer link\n-----------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = int(input("Please enter the PID: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") elif choice == 2: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") elif choice == 3: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=en-GB") elif choice == 4: rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=UK-RES-FACEBOOK:24747&amp;rid="+ str(rid)+ "&amp;pid=" + str(pid) + "&amp;lang=en-GB") #German if lang == 2: choice = int(input("\nSelect URL generator: ")) if choice == 1: multiple = str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") if multiple =="n": print("\n\nSingle offer link\n-----------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = int(input("Please enter the PID: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") elif choice == 2: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") elif choice == 3: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=de-DE") elif choice == 4: rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=UK-RES-FACEBOOK:24747&amp;rid="+ str(rid)+ "&amp;pid=" + str(pid) + "&amp;lang=de-DE") #French if lang == 3: choice = int(input("\nSelect URL generator: ")) if choice == 1: multiple = str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") if multiple =="n": print("\n\nSingle offer link\n-----------------") cid = str(input("\nPlease enter the CID: ")) rid = int(input("Please enter the RID: ")) pid = int(input("Please enter the PID: ")) print("\nhttps://bda.bookatable.com/?cid=" + cid + "&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") elif choice == 2: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=INTL-LBDIRECTORY_INDIRECT:10508&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") elif choice == 3: multiple =str(input("\nWould you like to create a multiple offer link? Y/N ")) if multiple == "y": print("\n\nMultiple offer link\n-------------------") rid = int(input("\nPlease enter the RID: ")) pid = str(input("Please enter multiple PIDs using ****,****: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") if multiple == "n": print("\n\nSingle offer link\n-----------------") rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=CONSOLEEMAILCAMPAIGNS:18663&amp;rid=" + str(rid) + "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") elif choice == 4: rid = int(input("\nPlease enter the RID: ")) pid = int(input("Please enter the PID: ")) print( "\nhttps://bda.bookatable.com/?cid=UK-RES-FACEBOOK:24747&amp;rid="+ str(rid)+ "&amp;pid=" + str(pid) + "&amp;lang=fr-FR") elif choice == 5: replit.clear() print("\n\nProgram terminated") return else: print("\nWrong selection, please choose options 1-5") time.sleep(2) replit.clear() welcome() end = input("\nWould you like to continue Y/N ") if end == "y": replit.clear() if end == "n": replit.clear() print("\n\nProgram terminated") return elif end == "": replit.clear() print("\n\nProgram terminated") return except ValueError: print("\nPlease enter a number!") time.sleep(1) replit.clear() welcome() </code></pre> <p>(This code is also in <a href="https://repl.it/@KaloianKozlev/URL-creator" rel="nofollow noreferrer">repl.it</a>.)</p>
[]
[ { "body": "<p>More functions. If you are copy and pasting code it should be in a fucntion call, not another repeat.</p>\n\n<p>Your call to welcome() should be underneath an <code>if __name__ == '__main__':</code> block as it is pythonic. </p>\n\n<p>You have three different languages but the execution is all the...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T09:24:26.713", "Id": "202915", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "url" ], "Title": "Generate URLs based on user's menu choices" }
202915
<p>I have written a <strong>simple download accelerator in java</strong> which <strong>downloads</strong> the same file <strong>in multiple threads</strong> and then combines them all.</p> <p>I would love some feedback on my design. How the same implementation can be better written. Idioms, conventions, anything that comes to your mind. I hope I have not included a lot of code here. I thought it would be hard to review my code without the basic classes.</p> <p>If you want to view the project in a more organized manner, the project is public in GitHub <a href="https://github.com/GnikDroy/DownloadManager" rel="nofollow noreferrer">here</a></p> <p>Thank you in advance. I have included a basic introduction to each of the classes along with the code. Hope that helps to review my code.</p> <h1>How the program looks</h1> <p><a href="https://i.stack.imgur.com/SeGqb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SeGqb.png" alt="Screenshot" /></a></p> <p><strong>DownloadManager.java</strong></p> <p>This class is the main starting point of the application. It starts up a GUI interface made in JavaFX, and creates a DownloadPool object. DownloadPool is the object that is responsible for managing the download of the files. This class is just the GUI interface for the actual program.</p> <pre><code>package downloadmanager; import java.io.IOException; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author gnik */ public class DownloadManager extends Application { DownloadPool downloadPool = new DownloadPool().load(); Stage window; TableView&lt;DownloadThread&gt; table; Label urlLabel = new Label(&quot;URL:&quot;); TextField urlInput = new TextField(); Button newDownload = new Button(&quot;Download&quot;); Button pauseButton = new Button(&quot;Pause&quot;); Button resumeButton = new Button(&quot;Resume&quot;); Button stopButton = new Button(&quot;Stop&quot;); Button removeButton = new Button(&quot;Remove&quot;); /** * @param args the command line arguments * @throws java.io.IOException * @throws java.lang.InterruptedException */ public static void main(String args[]) throws IOException, InterruptedException { launch(args); } @Override public void stop() { downloadPool.stopAll(); downloadPool.joinThreads(); downloadPool.save(); } public void setTable() { TableColumn&lt;DownloadThread, Integer&gt; idColumn = new TableColumn&lt;&gt;(&quot;ID&quot;); idColumn.setMinWidth(50); idColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, Integer&gt; download) -&gt; download.getValue().getDownloadMetadata().getDownloadIDProperty()); TableColumn&lt;DownloadThread, String&gt; urlColumn = new TableColumn&lt;&gt;(&quot;URL&quot;); urlColumn.setMinWidth(200); urlColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, String&gt; download) -&gt; download.getValue().getDownloadMetadata().getUrlProperty()); TableColumn&lt;DownloadThread, String&gt; statusColumn = new TableColumn&lt;&gt;(&quot;Status&quot;); statusColumn.setMinWidth(200); statusColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, String&gt; download) -&gt; download.getValue().getDownloadMetadata().getStatusProperty()); TableColumn&lt;DownloadThread, String&gt; filenameColumn = new TableColumn&lt;&gt;(&quot;Filename&quot;); filenameColumn.setMinWidth(150); filenameColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, String&gt; download) -&gt; download.getValue().getDownloadMetadata().getFilenameProperty()); TableColumn&lt;DownloadThread, String&gt; sizeColumn = new TableColumn&lt;&gt;(&quot;Size&quot;); sizeColumn.setMinWidth(100); sizeColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, String&gt; download) -&gt; download.getValue().getDownloadMetadata().getSizeProperty()); TableColumn&lt;DownloadThread, String&gt; acceleratedColumn = new TableColumn&lt;&gt;(&quot;Accelerated&quot;); acceleratedColumn.setMinWidth(50); acceleratedColumn.setCellValueFactory((TableColumn.CellDataFeatures&lt;DownloadThread, String&gt; download) -&gt; download.getValue().getDownloadMetadata().getAcceleratedProperty()); table = new TableView(); table.setItems(downloadPool.getDownloadThreads()); table.getColumns().addAll(idColumn, urlColumn, statusColumn, filenameColumn, sizeColumn, acceleratedColumn); } public void setButtons() { newDownload.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent eh) { downloadPool.newDownload(urlInput.getText()); urlInput.clear(); } }); pauseButton.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent eh) { downloadPool.pauseDownload(table.getSelectionModel().getSelectedItem()); } }); resumeButton.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent eh) { downloadPool.resumeDownload(table.getSelectionModel().getSelectedItem()); } }); stopButton.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent eh) { downloadPool.stopDownload(table.getSelectionModel().getSelectedItem()); } }); removeButton.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent eh) { downloadPool.removeDownload(table.getSelectionModel().getSelectedItem()); } }); } @Override public void start(Stage stage) throws Exception { window = stage; window.setTitle(&quot;Download Manager&quot;); setTable(); setButtons(); urlInput.setMinWidth(400); HBox hBox = new HBox(); hBox.getChildren().addAll(urlLabel, urlInput, newDownload); hBox.setSpacing(10); HBox buttonList = new HBox(); buttonList.getChildren().addAll(pauseButton, stopButton, resumeButton, removeButton); buttonList.setSpacing(10); VBox vBox = new VBox(); vBox.getChildren().addAll(hBox, buttonList, table); Scene scene = new Scene(vBox); scene.getStylesheets().add(&quot;/resources/modena_dark.css&quot;); window.setScene(scene); window.show(); } } </code></pre> <p><strong>DownloadPool.java</strong></p> <p>This class holds a bunch of DownloadThread objects. A DownloadThread object basically contains a thread that the download is running on, queues to communicate with the thread (for pausing/resuming downloads for example), and Download and DownloadMetadata objects that represent the downloads. This class is responsible for managing the state of all the Download objects.</p> <pre><code>package downloadmanager; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * * @author gnik */ public class DownloadPool { private final ObservableList&lt;DownloadThread&gt; downloadThreads = FXCollections.observableArrayList(); DownloadSaves downloadSaves=new DownloadSaves(); public DownloadPool() { downloadSaves.load(); } public void save(){ downloadSaves.clear(); for (DownloadThread downloadThread:downloadThreads){ DownloadState download; download=new DownloadState(downloadThread.getDownloadMetadata(),downloadThread.download.getValue().getPartMetadatas()); downloadSaves.addDownload(download); } downloadSaves.save(); } public DownloadPool load() { if(downloadSaves.getDownloads()==null){return this;} for (DownloadState downloadState : downloadSaves.getDownloads()) { DownloadMetadata downloadMetadata=downloadState.downloadMetadata; List&lt;DownloadPartMetadata&gt; downloadPartMetadata=downloadState.downloadPartMetadata; ConcurrentLinkedQueue queueCommand = new ConcurrentLinkedQueue(); ConcurrentLinkedQueue queueResponse = new ConcurrentLinkedQueue(); Download download = new Download(downloadMetadata, queueCommand, queueResponse); download.loadDownlaodPartMetadatas(downloadPartMetadata); Thread thread = new Thread(download); DownloadThread downloadThread = new DownloadThread(downloadMetadata, download, thread, queueCommand, queueResponse); downloadThreads.add(downloadThread); thread.start(); } return this; } public boolean isValidUrl(String url) { try { URL test=new URL(url); return true; } catch (MalformedURLException ex) { return false; } } public ObservableList&lt;DownloadThread&gt; getDownloadThreads() { return downloadThreads; } private void waitUntilCommand(DownloadThread downloadThread,DownloadAction.Response command){ while (true) { if(!downloadThread.queueResponse.isEmpty()){ if(downloadThread.queueResponse.peek().equals(command)){ downloadThread.queueResponse.poll(); break; } } } } public void stopDownload(DownloadThread downloadThread) { if (!downloadThread.thread.isAlive()) { return; } downloadThread.queueCommand.add(DownloadAction.Command.STOP); waitUntilCommand(downloadThread,DownloadAction.Response.STOPPED); joinThread(downloadThread); } public void pauseDownload(DownloadThread downloadThread) { if (!downloadThread.thread.isAlive()) { return; } downloadThread.queueCommand.add(DownloadAction.Command.PAUSE); waitUntilCommand(downloadThread,DownloadAction.Response.PAUSED); } public void resumeDownload(DownloadThread downloadThread) { if (!downloadThread.thread.isAlive()) { return; } downloadThread.queueCommand.add(DownloadAction.Command.RESUME); waitUntilCommand(downloadThread,DownloadAction.Response.RESUMED); } public void removeDownload(DownloadThread downloadThread){ if(downloadThread.thread.isAlive()){ stopDownload(downloadThread); try { downloadThread.thread.join(); } catch (InterruptedException ex) { Logger.getLogger(DownloadPool.class.getName()).log(Level.SEVERE, null, ex); } } downloadThreads.remove(downloadThread); } public void pauseAll() { for (DownloadThread downloadThread : downloadThreads) { pauseDownload(downloadThread); } } public void resumeAll() { for (DownloadThread downloadThread : downloadThreads) { resumeDownload(downloadThread); } } public void stopAll() { for (DownloadThread downloadThread : downloadThreads) { stopDownload(downloadThread); } } public void joinThread(DownloadThread downloadThread){ try { downloadThread.thread.join(); } catch (InterruptedException ex) { Logger.getLogger(DownloadPool.class.getName()).log(Level.SEVERE, null, ex); } } public void joinThreads() { for (DownloadThread downloadThread : downloadThreads) { joinThread(downloadThread); } } public void newDownload(String url) { DownloadMetadata downloadMetadata; try { downloadMetadata = new DownloadMetadata(url, downloadThreads.size()); } catch (MalformedURLException ex) { Logger.getLogger(DownloadManager.class.getName()).log(Level.SEVERE, null, ex); return; } ConcurrentLinkedQueue queueCommand = new ConcurrentLinkedQueue(); ConcurrentLinkedQueue queueResponse = new ConcurrentLinkedQueue(); Download download = new Download(downloadMetadata, queueCommand, queueResponse); Thread thread = new Thread(download); DownloadThread downloadThread = new DownloadThread(downloadMetadata, download, thread, queueCommand, queueResponse); downloadThreads.add(downloadThread); thread.start(); } } </code></pre> <p><strong>Download.java</strong></p> <p>This is the class that holds the download object. All the information about the download is stored in DownloadMetadata objects, and this class is responsible for handling all the actions such as pause/stop. The object also holds several DownloadPart objects, which as the name imply are the parts of the download. The download is separated into several DownloadPart objects and each part is simultaneously downloaded in several threads for accelerating download.</p> <pre><code>package downloadmanager; import java.net.HttpURLConnection; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; /** * * @author gnik */ public class Download implements Runnable { private final SimpleObjectProperty&lt;DownloadMetadata&gt; metadata; private final List&lt;DownloadPartThread&gt; downloadPartThreads = FXCollections.observableArrayList(); private final ConcurrentLinkedQueue queueCommand; private final ConcurrentLinkedQueue queueResponse; public Download(DownloadMetadata metadata, ConcurrentLinkedQueue queueCommand, ConcurrentLinkedQueue queueResponse) { this.metadata = new SimpleObjectProperty&lt;&gt;(metadata); this.queueCommand = queueCommand; this.queueResponse = queueResponse; } @Override public String toString() { return &quot;DownloadID:&quot; + metadata.getValue().getDownloadID(); } public DownloadMetadata getDownloadMetadata() { return metadata.getValue(); } public SimpleObjectProperty&lt;DownloadMetadata&gt; getDownloadMetadataProperty() { return metadata; } public List&lt;DownloadPartMetadata&gt; getPartMetadatas() { List&lt;DownloadPartMetadata&gt; metadatas = new ArrayList&lt;&gt;(); for (DownloadPartThread dthread : downloadPartThreads) { metadatas.add(dthread.getDownloadPartMetadata()); } return metadatas; } public void setHeaders() throws IOException { HttpURLConnection conn; conn = (HttpURLConnection) getDownloadMetadata().getUrl().openConnection(); conn.setRequestMethod(&quot;HEAD&quot;); getDownloadMetadata().setSize(conn.getContentLengthLong()); String ranges = conn.getHeaderField(&quot;Accept-Ranges&quot;); if (ranges != null &amp;&amp; !ranges.equals(&quot;none&quot;)) { getDownloadMetadata().setAccelerated(true); setStatus(DownloadStatus.STARTING); } } public void loadDownlaodPartMetadatas(List&lt;DownloadPartMetadata&gt; downloadPartMetadatas) { for (DownloadPartMetadata downloadPartMetadata : downloadPartMetadatas) { ConcurrentLinkedQueue queueCom = new ConcurrentLinkedQueue(); ConcurrentLinkedQueue queueRes = new ConcurrentLinkedQueue(); downloadPartMetadata.setDownloadMetadata(getDownloadMetadata()); DownloadPart downloadPart = new DownloadPart(downloadPartMetadata, queueCom, queueRes); downloadPartThreads.add(new DownloadPartThread(downloadPart, downloadPartMetadata, queueCom, queueRes)); } } public void createDownloadPartThreads() { int partID = 0; for (Part part : divideDownload()) { DownloadPartMetadata part_metadata = new DownloadPartMetadata(getDownloadMetadata(), partID, part); ConcurrentLinkedQueue queueCom = new ConcurrentLinkedQueue(); ConcurrentLinkedQueue queueRes = new ConcurrentLinkedQueue(); DownloadPart downloadPart = new DownloadPart(part_metadata, queueCom, queueRes); downloadPartThreads.add(new DownloadPartThread(downloadPart, part_metadata, queueCom, queueRes)); partID++; } } public void initialize() { //If download Part Threads is not empty and loaded from file then skip. if (downloadPartThreads.isEmpty()) { try { setHeaders(); } catch (IOException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); setStatus(DownloadStatus.ERROR); return; } createDownloadPartThreads(); } } private List&lt;Part&gt; divideDownload() { List&lt;Part&gt; parts = new ArrayList&lt;&gt;(); long start = 0; double size = (double) getDownloadMetadata().getSize() / getDownloadMetadata().getParts(); for (int cnt = 0; cnt &lt; getDownloadMetadata().getParts(); cnt++) { Part part = new Part(start, (int) Math.round(size * (cnt + 1))); parts.add(part); start = (int) Math.round(size * (cnt + 1)) + 1; } return parts; } private void setStatus(DownloadStatus downloadStatus) { getDownloadMetadata().setStatus(downloadStatus); } public DownloadStatus getStatus() { return getDownloadMetadata().getStatus(); } public boolean isDownloaded() { for (DownloadPartThread downloadThread : downloadPartThreads) { if (downloadThread.getDownloadPart().getStatus() != DownloadStatus.COMPLETED) { return false; } } return true; } public void joinThread(Thread thread) { if (thread != null &amp;&amp; !thread.isAlive()) { try { thread.join(); } catch (InterruptedException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } } } public void joinThreads() { for (DownloadPartThread downloadThread : downloadPartThreads) { joinThread(downloadThread.thread); } } public void waitUntilResponse(DownloadPartThread dthread, DownloadAction.Response response) { while (true) { if (!dthread.queueResponse.isEmpty() &amp;&amp; dthread.queueResponse.peek().equals(response)) { dthread.queueResponse.poll(); break; } } } public void pause() { if (getStatus() != DownloadStatus.DOWNLOADING) { return; } for (DownloadPartThread dthread : downloadPartThreads) { if (dthread.thread==null || !dthread.thread.isAlive()) { return; } dthread.queueCommand.add(DownloadAction.Command.PAUSE); waitUntilResponse(dthread, DownloadAction.Response.PAUSED); } setStatus(DownloadStatus.PAUSED); } public void resume() { if (getStatus() != DownloadStatus.PAUSED) { return; } for (DownloadPartThread dthread : downloadPartThreads) { if (dthread.thread==null || !dthread.thread.isAlive()) { return; } dthread.queueCommand.add(DownloadAction.Command.RESUME); waitUntilResponse(dthread, DownloadAction.Response.RESUMED); } setStatus(DownloadStatus.DOWNLOADING); } public void stop() { if (getStatus() == DownloadStatus.STOPPED) { return; } for (DownloadPartThread dthread : downloadPartThreads) { if (dthread.thread==null || !dthread.thread.isAlive()) { return; } dthread.queueCommand.add(DownloadAction.Command.STOP); waitUntilResponse(dthread, DownloadAction.Response.STOPPED); } setStatus(DownloadStatus.STOPPED); } public void startDownloadPartThreads() { if (!getDownloadMetadata().getAccelerated()) { setStatus(DownloadStatus.ERROR); return; } setStatus(DownloadStatus.DOWNLOADING); for (DownloadPartThread downloadThread : downloadPartThreads) { Thread thread = new Thread(downloadThread.getDownloadPart()); thread.setName(this.toString() + &quot; &quot; + downloadThread.downloadPart.toString()); downloadThread.thread = thread; thread.start(); } } public void deleteDownloadPartFiles() throws IOException { for (DownloadPartThread downloadThread : downloadPartThreads) { DownloadPart downloadPart = downloadThread.getDownloadPart(); Files.deleteIfExists(Paths.get(downloadPart.getFilename())); } } public void copyToStream(BufferedOutputStream outFile, BufferedInputStream inFile) throws IOException { int byt; while ((byt = inFile.read()) != -1 &amp;&amp; outFile != null) { outFile.write(byt); } } public void joinDownloadParts() { if (!isDownloaded()) { return; } setStatus(DownloadStatus.JOINING); try(BufferedOutputStream outFile = new BufferedOutputStream(new FileOutputStream(getDownloadMetadata().getFilename()))) { for (DownloadPartThread downloadThread : downloadPartThreads) { DownloadPart downloadPart = downloadThread.getDownloadPart(); try(BufferedInputStream inFile = new BufferedInputStream(new FileInputStream(downloadPart.getFilename()))){ copyToStream(outFile, inFile); } } setStatus(DownloadStatus.COMPLETED); deleteDownloadPartFiles(); } catch (FileNotFoundException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } } public void downloadLoop(){ while (!isDownloaded()) { try { Thread.sleep(100); } catch (InterruptedException ex) { setStatus(DownloadStatus.ERROR); Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex); } if (!this.queueCommand.isEmpty()) { DownloadAction.Command command = (DownloadAction.Command) this.queueCommand.poll(); switch (command) { case PAUSE: this.pause(); this.queueResponse.add(DownloadAction.Response.PAUSED); break; case STOP: this.stop(); this.joinThreads(); this.queueResponse.add(DownloadAction.Response.STOPPED); return; case RESUME: this.resume(); this.queueResponse.add(DownloadAction.Response.RESUMED); break; default: break; } } } } @Override public void run() { if (getDownloadMetadata().getStatus() == DownloadStatus.COMPLETED) { return; } this.initialize(); this.startDownloadPartThreads(); this.downloadLoop(); this.joinThreads(); this.joinDownloadParts(); } } </code></pre> <p><strong>DownloadThread.java</strong></p> <p>This is the class which holds a few objects. Namely, a DownloadMetadata object, the Download object itself, the Thread object where the download will run, and the Queues which are used to communicate with the DownloadPool object. In essence, the DownloadPool object holds various DownloadThread objects to control all downloads.</p> <pre><code>package downloadmanager; import java.util.concurrent.ConcurrentLinkedQueue; import javafx.beans.property.SimpleObjectProperty; /** * * @author gnik */ public class DownloadThread { public SimpleObjectProperty&lt;DownloadMetadata&gt; downloadMetadata; public SimpleObjectProperty&lt;Download&gt; download; public Thread thread; public ConcurrentLinkedQueue queueCommand; public ConcurrentLinkedQueue queueResponse; public DownloadThread(DownloadMetadata downloadMetadata, Download download, Thread thread, ConcurrentLinkedQueue queueCommand, ConcurrentLinkedQueue queueResponse) { this.downloadMetadata = new SimpleObjectProperty&lt;&gt;(downloadMetadata); this.download = new SimpleObjectProperty&lt;&gt;(download); this.thread = thread; this.queueCommand = queueCommand; this.queueResponse = queueResponse; } public Download getDownload(){ return download.getValue(); } public DownloadMetadata getDownloadMetadata() { return downloadMetadata.getValue(); } } </code></pre> <p><strong>DownloadMetadata.java</strong></p> <p>This class holds all the information regarding the download such as the size, URL, number of parts in which the download is divided etc. This object is later serialized into the disk so that the downloads are persistent even though the program is closed.</p> <pre><code>package downloadmanager; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Paths; import javafx.beans.property.SimpleObjectProperty; /** * * @author gnik */ public class DownloadMetadata{ private final SimpleObjectProperty&lt;URL&gt; url; private final SimpleObjectProperty&lt;Integer&gt; downloadID; private final SimpleObjectProperty&lt;String&gt; filename; private static final int parts=8; private final SimpleObjectProperty&lt;Long&gt; size=new SimpleObjectProperty&lt;&gt;(); private static final int timeout=10000; private final SimpleObjectProperty&lt;Boolean&gt; accelerated=new SimpleObjectProperty&lt;&gt;(false); private final SimpleObjectProperty&lt;DownloadStatus&gt; status=new SimpleObjectProperty&lt;&gt;(DownloadStatus.NEW); public DownloadMetadata(String url,int ID) throws MalformedURLException{ this.url=new SimpleObjectProperty&lt;&gt;(new URL(url)); this.downloadID=new SimpleObjectProperty(ID); String file=String.valueOf(ID)+&quot;_&quot;+Paths.get(this.url.getValue().getPath()).getFileName().toString(); this.filename=new SimpleObjectProperty&lt;&gt;(file); } public URL getUrl() { return url.getValue(); } public SimpleObjectProperty getUrlProperty() { return url; } public Integer getDownloadID() { return downloadID.getValue(); } public SimpleObjectProperty&lt;Integer&gt; getDownloadIDProperty() { return downloadID; } public String getFilename() { return filename.getValue(); } public SimpleObjectProperty getFilenameProperty() { return filename; } public long getSize() { return size.getValue(); } public SimpleObjectProperty getSizeProperty() { return size; } public void setSize(long s){ size.setValue(s); } public DownloadStatus getStatus() { return status.getValue(); } public SimpleObjectProperty getStatusProperty() { return status; } public void setStatus(DownloadStatus status) { this.status.setValue(status); } public boolean getAccelerated(){ return accelerated.getValue(); } public SimpleObjectProperty getAcceleratedProperty(){ return accelerated; } public void setAccelerated(boolean a){ accelerated.setValue(a); } public int getTimeout(){ return timeout; } public int getParts(){ return parts; } } </code></pre> <p><strong>DownloadPart.java</strong></p> <p>Okay, so this class is responsible for the download of one part of the download. As mentioned earlier, one single file download is divided into multiple parts. This class contains the methods to control the download of a specific part.</p> <pre><code>package downloadmanager; import java.io.IOException; import java.net.URLConnection; import java.io.*; import java.net.SocketTimeoutException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.SimpleObjectProperty; /** * * @author gnik */ public class DownloadPart implements Runnable { private final SimpleObjectProperty&lt;DownloadPartMetadata&gt; metadata; private final ConcurrentLinkedQueue queueCommand; private final ConcurrentLinkedQueue queueResponse; public DownloadPart(DownloadPartMetadata metadata, ConcurrentLinkedQueue queueCommand, ConcurrentLinkedQueue queueResponse) { this.queueCommand = queueCommand; this.queueResponse = queueResponse; this.metadata = new SimpleObjectProperty&lt;&gt;(metadata); } public DownloadPartMetadata getMetadata() { return metadata.getValue(); } @Override public String toString() { return &quot;DownloadPartID:&quot; + getMetadata().partID; } public DownloadStatus getStatus() { return getMetadata().getStatus(); } public void pause() { if (getMetadata().getStatus() == DownloadStatus.DOWNLOADING) { getMetadata().setStatus(DownloadStatus.PAUSED); } } public void resume() { if (getMetadata().getStatus() == DownloadStatus.PAUSED) { getMetadata().setStatus(DownloadStatus.DOWNLOADING); } } public void stop() { if (getMetadata().getStatus() == DownloadStatus.PAUSED || getMetadata().getStatus() == DownloadStatus.PAUSED) { getMetadata().setStatus(DownloadStatus.STOPPED); } } public String getFilename() { return getMetadata().getFilename(); } public boolean isComplete() { return ((getMetadata().getCompletedBytes() + getMetadata().getPart().getStartByte()) == getMetadata().getPart().getEndByte()); } private BufferedInputStream getConnectionStream() throws IOException { //Setting up the connection. URLConnection connection = getMetadata().downloadMetadata.getUrl().openConnection(); connection.setRequestProperty(&quot;Range&quot;, &quot;bytes=&quot; + String.valueOf(getMetadata().getPart().getStartByte() + getMetadata().getCompletedBytes()) + &quot;-&quot; + String.valueOf(getMetadata().getPart().getEndByte())); connection.setConnectTimeout(5000); connection.setReadTimeout(getMetadata().downloadMetadata.getTimeout()); connection.connect(); BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream()); return inputStream; } private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException { int byt; long completedBytes = getMetadata().getCompletedBytes(); while ((byt = inputStream.read()) != -1) { fileStream.write(byt); completedBytes++; getMetadata().setCompletedBytes(completedBytes); if (!queueCommand.isEmpty()) { if (queueCommand.peek().equals(DownloadAction.Command.PAUSE)) { pause(); queueCommand.poll(); queueResponse.add(DownloadAction.Response.PAUSED); return false; } else if (queueCommand.peek().equals(DownloadAction.Command.STOP)) { stop(); //I am not adding a poll here because it will stop execution in run thread as well. queueResponse.add(DownloadAction.Response.STOPPED); return false; } } } return true; } public void download() throws IOException, SocketTimeoutException { getMetadata().setStatus(DownloadStatus.DOWNLOADING); boolean append = (getMetadata().getCompletedBytes() != 0); BufferedInputStream inputStream = getConnectionStream(); BufferedOutputStream fileStream = new BufferedOutputStream(new FileOutputStream(getMetadata().filename, append)); try { if (copyToStream(inputStream, fileStream)) { getMetadata().setStatus(DownloadStatus.COMPLETED); } } finally { inputStream.close(); fileStream.close(); } } public void safeDownload() { try { download(); } catch (IOException ex) { getMetadata().setStatus(DownloadStatus.ERROR); getMetadata().incrementRetries(); Logger.getLogger(DownloadPart.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void run() { if (DownloadStatus.COMPLETED == getMetadata().getStatus()) { return; } safeDownload(); //Infinite loop until the downloadstatus is completed while (getMetadata().getStatus() != DownloadStatus.COMPLETED) { //Retry if there is any errors. if (getMetadata().getStatus() == DownloadStatus.ERROR) { safeDownload(); } try { Thread.sleep(200); } catch (InterruptedException ex) { Logger.getLogger(DownloadPart.class.getName()).log(Level.SEVERE, null, ex); } if (!queueCommand.isEmpty()) { DownloadAction.Command command = (DownloadAction.Command) queueCommand.poll(); switch (command) { case STOP: stop(); queueResponse.add(DownloadAction.Response.STOPPED); return; case RESUME: resume(); queueResponse.add(DownloadAction.Response.RESUMED); safeDownload(); break; default: break; } } } } } </code></pre> <p><strong>DownloadPartThread.java</strong></p> <p>This class is responsible for the storage of DownloadPart object and the thread it is running in. It contains a DownloadPart object, A download Metadata object and queue objects to communicate with the download object. A Download object contains several DownloadPartThread objects which enables the Download object to fully control the actions of each of the DownloadPart object and it's thread.</p> <pre><code>package downloadmanager; import java.util.concurrent.ConcurrentLinkedQueue; import javafx.beans.property.SimpleObjectProperty; /** * * @author gnik */ public class DownloadPartThread { public Thread thread; public SimpleObjectProperty&lt;DownloadPart&gt; downloadPart; public ConcurrentLinkedQueue queueCommand; public ConcurrentLinkedQueue queueResponse; public SimpleObjectProperty&lt;DownloadPartMetadata&gt; downloadPartMetadata; public DownloadPartThread(DownloadPart downloadPart, DownloadPartMetadata downloadPartMetadata, Thread thread, ConcurrentLinkedQueue queueCommand, ConcurrentLinkedQueue queueResponse) { this.thread = thread; this.downloadPart = new SimpleObjectProperty&lt;&gt;(downloadPart); this.downloadPartMetadata = new SimpleObjectProperty&lt;&gt;(downloadPartMetadata); this.queueCommand = queueCommand; this.queueResponse = queueResponse; } public DownloadPartThread(DownloadPart downloadPart, DownloadPartMetadata downloadPartMetadata, ConcurrentLinkedQueue queueCommand, ConcurrentLinkedQueue queueResponse) { this.downloadPart = new SimpleObjectProperty&lt;&gt;(downloadPart); this.downloadPartMetadata = new SimpleObjectProperty&lt;&gt;(downloadPartMetadata); this.queueCommand = queueCommand; this.queueResponse = queueResponse; } public DownloadPart getDownloadPart(){ return downloadPart.getValue(); } public void setDownloadPart(DownloadPart t){ downloadPart.setValue(t); } public DownloadPartMetadata getDownloadPartMetadata(){ return downloadPartMetadata.getValue(); } } </code></pre> <p><strong>DownloadPartMetadata.java</strong></p> <p>Similar to the DownloadMetadata object, this object holds the information regarding each of the part of the download. Such as size of each part, start and end byte, and the number of completed bytes. This object is also later serialized to the disk so that download can be paused and resumed later on.</p> <pre><code>package downloadmanager; import com.thoughtworks.xstream.annotations.XStreamOmitField; import javafx.beans.property.SimpleObjectProperty; /** * * @author gnik */ public class DownloadPartMetadata{ public SimpleObjectProperty&lt;Integer&gt; partID; public SimpleObjectProperty&lt;DownloadStatus&gt; status=new SimpleObjectProperty&lt;&gt;(DownloadStatus.STARTING); public String filename; //This field will be included multiple time if it is included @XStreamOmitField public DownloadMetadata downloadMetadata; public SimpleObjectProperty&lt;Part&gt; part; public SimpleObjectProperty&lt;Long&gt; completedBytes=new SimpleObjectProperty&lt;&gt;(0L); public SimpleObjectProperty&lt;Integer&gt; retries=new SimpleObjectProperty&lt;&gt;(0); public DownloadPartMetadata(DownloadMetadata downloadMetadata,int partID,Part part){ this.downloadMetadata=downloadMetadata; this.partID=new SimpleObjectProperty&lt;&gt;(partID); this.part=new SimpleObjectProperty&lt;&gt;(part); this.filename=downloadMetadata.getFilename()+&quot;.part&quot;+String.valueOf(partID); } public Part getPart(){ return part.getValue(); } public void setPart(Part p){ part.setValue(p); } public SimpleObjectProperty&lt;Part&gt; getPartProperty(){ return part; } public void setDownloadMetadata(DownloadMetadata downloadMetadata){ this.downloadMetadata=downloadMetadata; } public SimpleObjectProperty&lt;DownloadStatus&gt; getStatusProperty() { return status; } public DownloadStatus getStatus(){ return status.getValue(); } public void setStatus(DownloadStatus s) { status.setValue(s); } public void setCompletedBytes(long b){ completedBytes.setValue(b); } public long getCompletedBytes(){ return completedBytes.getValue(); } public SimpleObjectProperty&lt;Long&gt; getCompletedBytesProperty(){ return completedBytes; } public void setRetries(int r){ retries.setValue(r); } public int getRetries(){ return retries.getValue(); } public void incrementRetries(){ retries.setValue(retries.getValue()+1); } public SimpleObjectProperty&lt;Integer&gt; getRetriesProperty(){ return retries; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } } </code></pre> <p><strong>DownloadStatus.java</strong></p> <p>This file contains the enums of the DownloadStatus. Such as COMPLETED,PAUSED.</p> <pre><code>package downloadmanager; /** * * @author gnik */ public enum DownloadStatus{ NEW, STARTING, DOWNLOADING, PAUSED, STOPPED, ERROR, JOINING, COMPLETED, } </code></pre> <p><strong>DownloadState.java</strong></p> <p>When the user wants to exit the program, a list of these objects is written to the disk to make the downloads persistent. The object contains DownloadMetadata and several DownloadPartMetadata objects. It essentially represents the state of the download at the end of the program.</p> <pre><code>package downloadmanager; import java.util.List; /** * * @author gnik */ public class DownloadState { public DownloadMetadata downloadMetadata; public List&lt;DownloadPartMetadata&gt; downloadPartMetadata; public DownloadState(){ } public DownloadState(DownloadMetadata downloadMetadata, List&lt;DownloadPartMetadata&gt; downloadPartMetadata) { this.downloadMetadata = downloadMetadata; this.downloadPartMetadata = downloadPartMetadata; } } </code></pre> <p><strong>Part.java</strong></p> <p>This is just an object that contains the start and end byte of each DownloadPart. It is similar to Pair objects available in many languages (but not java).</p> <pre><code>package downloadmanager; /** * * @author gnik */ public class Part{ long startByte; long endByte; public Part(long startByte,long endByte){ this.startByte=startByte; this.endByte=endByte; } public long getStartByte() { return startByte; } public long getEndByte() { return endByte; } public void setStartByte(long startByte) { this.startByte = startByte; } public void setEndByte(long endByte) { this.endByte = endByte; } @Override public String toString(){ return String.valueOf(startByte)+&quot;-&quot;+String.valueOf(endByte); } } </code></pre> <p><strong>DownloadAction.java</strong></p> <p>This file contains the enums for the various action (and responses) a user can perform such as (Start a download/Pause a download). This is used to communicate in the queues with the thread.</p> <pre><code>package downloadmanager; /** * * @author gnik */ public class DownloadAction { enum Command { STOP, RESUME, PAUSE } enum Response{ STOPPED, RESUMED, PAUSED } } </code></pre> <p><strong>DownloadSaves.java</strong></p> <p>This class is responsible for writing and reading objects into the memory at the start and end of each program execution. A list of DownloadState objects is serialized in the disk to make the downloads persistent. It is loaded each time the program is run. Basically this is what stores the history of the class.</p> <pre><code>package downloadmanager; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author gnik */ public class DownloadSaves { private List&lt;DownloadState&gt; downloads = new ArrayList&lt;&gt;(); private final String saveFilename = &quot;history.dat&quot;; public DownloadSaves() { } public void addDownload(DownloadState download) { downloads.add(download); } public List&lt;DownloadState&gt; getDownloads() { return downloads; } public void clear() { downloads = new ArrayList&lt;&gt;(); } public void save() { XStream xstream = new XStream(new StaxDriver()); String object = xstream.toXML(downloads); try (OutputStreamWriter file = new OutputStreamWriter(new FileOutputStream(saveFilename), StandardCharsets.UTF_8)) { file.write(object); } catch (IOException ex) { Logger.getLogger(DownloadSaves.class.getName()).log(Level.SEVERE, null, ex); } } public void createNewFile() { String object=&quot;&lt;?xml version=\&quot;1.0\&quot; ?&gt;&lt;list&gt;&lt;/list&gt;&quot;; try (OutputStreamWriter file = new OutputStreamWriter(new FileOutputStream(saveFilename), StandardCharsets.UTF_8)) { file.write(object); } catch (IOException ex) { Logger.getLogger(DownloadSaves.class.getName()).log(Level.SEVERE, null, ex); } } public void load() { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(saveFilename), StandardCharsets.UTF_8)) { XStream xstream = new XStream(new StaxDriver()); downloads = (List&lt;DownloadState&gt;) xstream.fromXML(reader); } catch (FileNotFoundException ex) { Logger.getLogger(DownloadSaves.class.getName()).log(Level.SEVERE, null, ex); createNewFile(); } catch (IOException ex) { Logger.getLogger(DownloadSaves.class.getName()).log(Level.SEVERE, null, ex); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T10:32:21.433", "Id": "391122", "Score": "0", "body": "I would recommend that you add a short summary at the top of the overall design/structure of your code, just a short summary about what the classes do and interact, as you have m...
[ { "body": "<p>Upfront, I've just grabbed a couple of things that stuck out to me, I've\nnot dug too much into the details. Also while this got rather long, I\nthink the code is pretty well readable (which is easily one of the most important things) and it also deals with a good\nnumber of edge cases that obvio...
{ "AcceptedAnswerId": "203057", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T10:23:59.813", "Id": "202916", "Score": "4", "Tags": [ "java", "object-oriented", "multithreading", "javafx", "network-file-transfer" ], "Title": "Simple Java Download Manager" }
202916
<p>I share below my password hashing implementation with salt and pepper in C#, for your review and feedback. In my implementation methods like ValidatePassword(), ChangePassword() are in the user class.</p> <p>I recommend random.org's free random bytes generator coded in hexadecimal to get a secure Pepper for each installation. I prefer 128 bytes length. It separates each byte (every 2 digits in hexadecimal) with space. Copy-paste the pepper generated by random.org to the config file with the with the key "Pepper" like so: </p> <pre><code>&lt;add key="Pepper" value="25 4d 58 42 05 ba 0a f0 8a 72 .. .. e3"/&gt; </code></pre> <p>The simplified source code:</p> <pre><code>using System; using System.Text; using System.Configuration; using System.Globalization; using System.Security.Cryptography; namespace CryptoPassword { public static class Password { private const int SaltLength = 32; private const int KeyLength = 32; private const int IterationCount = 100000; private static readonly byte[] Pepper = ConvertSpacedHexToByteArray(ConfigurationManager.AppSettings["Pepper"]); //I recommend random.org's free 128 byte random bytes generator coded in hexadecimal //to get a secure pepper for each installation. //Copy-paste the pepper generated by the random.org to the config file with the key "Pepper" //like so: "&lt;add key="Pepper" value="25 4d 58 42 05 ba 0a f0 8a 72 .. .. e3"/&gt;" /// &lt;summary&gt; /// hexString should have its double hex digits corresponding to each byte separated by ' ' /// like so: "A1 23 F3 14". /// &lt;/summary&gt; /// &lt;param name="hexString"&gt;&lt;/param&gt; /// &lt;returns&gt;byte[] form&lt;/returns&gt; public static byte[] ConvertSpacedHexToByteArray(string hexString) { string[] hexValuesSplit = hexString.Split(' '); byte[] data = new byte[hexValuesSplit.Length]; for (var index = 0; index &lt; hexValuesSplit.Length; index++) { data[index] = byte.Parse(hexValuesSplit[index], NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return data; } // I dont recommend playing with salt length a lot. Make it a const, // and use the non-parametrized GenerateSalt() unless you know what you are doing. // Change the const SaltLength at major releases. public static byte[] GenerateSalt() { return GenerateSalt(SaltLength); } //this parameterized version is for the flexibility at knowledgable hands. public static byte[] GenerateSalt(int saltLength) { using (RNGCryptoServiceProvider saltCellar = new RNGCryptoServiceProvider()) { byte[] salt = new byte[saltLength]; saltCellar.GetBytes(salt); return salt; } } public static string GenerateHash(string password) { byte[] salt = GenerateSalt(); byte[] hash = GenerateHash(password, salt); return Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash); //store salt and hash together with ':' as the separator, coded in Base64. } public static byte[] GenerateHash(string password, byte [] salt) { //create an hmac hash of the password using the pepper value as the key using (var hmac = new HMACSHA512(Pepper)) { byte[] initialHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); //generate a key value using pbkdf2 that will serve as the password hash using (var pbkdf2 = new Rfc2898DeriveBytes(initialHash, salt, IterationCount)) //int.Parse(ConfigurationManager.AppSettings["IterationCount"]))) { return pbkdf2.GetBytes(KeyLength); } } } public static bool ValidatePassword(string password, string testPassword) { string[] hashParts = password.Split(':'); byte[] salt = Convert.FromBase64String(hashParts[0]); byte[] hash = Convert.FromBase64String(hashParts[1]); byte[] testHash = GenerateHash(testPassword, salt); //IMPORTANT!!! The following is required to defend against timing attacks. //We dont want to exit at the first byte mismatch but test every byte no matter what //so that timing is the same for valid and invalid passwords and //we dont want to leak information to the attacker about upto which byte his guess is correct. uint differences = (uint)hash.Length ^ (uint)testHash.Length; for (int position = 0; position &lt; Math.Min(hash.Length, testHash.Length); position++) differences |= (uint)(hash[position] ^ testHash[position]); return differences == 0; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T13:33:41.367", "Id": "391134", "Score": "1", "body": "Why not use something like Argon2/Bcrypt, but reinvent the wheel. If it is intentional, you might want to tag it as such." }, { "ContentLicense": "CC BY-SA 4.0", "Cre...
[ { "body": "<p>Not bad at all. Some remarks:</p>\n\n<ul>\n<li>The class should be parameterized and an instance should be used rather than just static methods.</li>\n<li>I'd never make the class itself dependent on a configured <code>Pepper</code> value (it's fine for an application to be configurable, but not f...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T10:25:13.997", "Id": "202917", "Score": "3", "Tags": [ "c#", ".net", "security", "cryptography" ], "Title": "Secure password hashing implementation with salt and pepper" }
202917
<p>I did <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf" rel="nofollow noreferrer">this programming challenge</a>. Part C of the challenge, is to find the salary you have to save every month to be able to buy a house in 36 months.</p> <p>This is my first time using bisection search so I just want to make sure that I did it correctly. I question the efficiency of my program because in test case 2 for part C, the supposed number of guesses is 9, but my program guesses 13 times.</p> <pre><code>annual_salary = int(input('Enter your annual salary.')) total_cost = 1000000 semi_annual_raise = .07 portion_down_payment = total_cost * 0.25 current_savings = 0 r = 0.04 guesses = 1 low = 0 high = 1 while abs(portion_down_payment-current_savings) &gt; 100: portion_saved = (low + high) / 2 salary = annual_salary current_savings = 0 for month in range(1, 37): if month % 6 == 1 and month != 1: salary += salary*semi_annual_raise current_savings += current_savings*r/12 current_savings += salary/12 * portion_saved if current_savings &gt;= portion_down_payment: high = portion_saved elif current_savings &lt; portion_down_payment: low = portion_saved portion_saved = (low+high)/2 guesses += 1 print(portion_saved, guesses) </code></pre>
[]
[ { "body": "<p>I don't think your code is an inefficient bisection search. The example which needed fewer iterations could simply be getting lucky and getting within the $100 terminal condition on one of its earlier steps. That said, here are a couple of implementation pointers:</p>\n<h3>Don't recalulate salar...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T11:40:28.580", "Id": "202920", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "binary-search" ], "Title": "Determining a salary for buying a house in 36 months" }
202920
<p>This function receives the id of an element (frame) and calculates the correct height and width so it fits inside its parent element, while keeping its aspect ratio. Before I had a way to calculate the frame ratio dynamically, but I decided it was easier to simply hard code it, it calculates it through naturalHeight and naturalWidth if it's an image, and use 0.5625 for the rest which are iframes, and that ratio makes sense for all of those. It works, tried it in different sizing scenarios, what I'm not 100% sure is if the math involved to calculate the correct width and height in all cases is correct.</p> <p>In all cases the element should fill as much as possible.</p> <pre><code>function fix_frame(frame_id) { var id = `#${frame_id}` var frame = $(id) if(frame_id === "media_image_frame") { var frame_ratio = frame[0].naturalHeight / frame[0].naturalWidth } else { var frame_ratio = 0.5625 } var parent = frame.parent() var parent_width = parent.width() var parent_height = parent.height() var parent_ratio = parent_height / parent_width var frame_width = frame.width() var frame_height = frame.height() if(parent_ratio === frame_ratio) { frame.width(parent_width) frame.height(parent_height) } else if(parent_ratio &lt; frame_ratio) { frame.width(parent_height / frame_ratio) frame.height(parent_height) } else if(parent_ratio &gt; frame_ratio) { frame.width(parent_width) frame.height(parent_width * frame_ratio) } } </code></pre>
[]
[ { "body": "<p>Although you posted your code it would help if you told us what you want help with?</p>\n\n<p>This is possible to do using CSS. I've seen multiple solitions, here is the first one I found on Google: <a href=\"http://www.mademyday.de/css-height-equals-width-with-pure-css.html\" rel=\"nofollow noref...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T12:03:22.473", "Id": "202921", "Score": "1", "Tags": [ "javascript", "layout" ], "Title": "Code to make elements fit within their container while keeping their aspect ratio" }
202921
<p>I have implemented this delete function for BST. Tt takes care of all the three cases, deleting node with 0, 1, or 2 children.</p> <p>I have added comments throughout to explain my decisions. Is it sloppy or acceptable? Will I get full marks if this was a question in an exam to implement the delete function of a BST?</p> <pre><code>//I am having the node start parameter, so I can specify from where the //deletion starts. So I can use it for recursion for the third case, //where the node to be deleted has 2 children. public void delete(Node start, int data) { if(root == null) return; /*If I want to call this method from any other class, I will pass in null as the start node, since I don't have reference to the root in that class. I have this start parameter because in the case of a node having 2 children, I am calling this method recursivly to delete, but I don't want to start from the root in that case. See below, last else */ Node parent = start == null ? root : start; Node current = parent; boolean isLeftNode = false; while(data != current.getData() &amp;&amp; current != null) { parent = current; if(data &lt; current.getData()) { current = current.getLeftNode(); isLeftNode = true; } else { current = current.getRightNode(); isLeftNode = false; } } //If not found. if(current == null) return; if(current == root) { root = null; return; } //Case 1: If node to be removed is a leaf, no children. if(current.getLeftNode() == null &amp;&amp; current.getRightNode() == null) { if(isLeftNode) parent.setLeftNode(null); else parent.setRightNode(null); } //Case 2: If node to be removed has only 1 child. else if(current.getLeftNode() != null &amp;&amp; current.getRightNode() == null) { if(isLeftNode) parent.setLeftNode(current.getLeftNode()); else parent.setRightNode(current.getLeftNode()); } else if(current.getLeftNode() == null &amp;&amp; current.getRightNode() != null) { if(isLeftNode) parent.setLeftNode(current.getRightNode()); else parent.setRightNode(current.getRightNode()); } //Case 3: If node to be deleted has 2 children. else { Node smallest = findSmallest(current.getRightNode()); current.setData(smallest.getData()); //Calling recursion to delete the smallest. Because the smallest //might have a right subtree. Explanation above relates to this. delete(current.getRightNode(), smallest.getData()); //Calling the delete method to start deleting from the right sub //tree since at this point there is a duplicate value, I can't //start from the root. } } public Node findSmallest(Node start) { //This is so in the main method, I can call findSmallest and pass in //null to search the whole tree. Because in main, I won't have reference //to the root. I have the start parameter so I can specifiy where to //start the search, because of the way I am dealing with deleting //a node with 2 children. See above. Node smallest = start == null ? root : start; while(smallest.getLeftNode() != null) { smallest = smallest.getLeftNode(); } return smallest; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T12:36:41.943", "Id": "391203", "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 y...
[ { "body": "<blockquote>\n<pre><code>public Node findSmallest(Node start) {\n //This is so in the main method, I can call findSmallest and pass in\n //null to search the whole tree. Because in main, I won't have reference\n //to the root. I have the start parameter so I can specifiy where to\n //star...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T12:18:15.297", "Id": "202922", "Score": "1", "Tags": [ "java", "tree" ], "Title": "Binary Search Tree delete function" }
202922
<p>I wrote a solution to <a href="http://codeforces.com/contest/1029/problem/B" rel="noreferrer">this question</a>. The task is to take an input of <em>n</em> increasing positive integers (1 ≤ <em>n</em> ≤ 2∙10<sup>5</sup>), each entry as large as 10<sup>9</sup>, and find the length of the longest subsequence where each element is no more than double the previous element.</p> <h3>Example input</h3> <pre><code>10 1 2 5 6 7 10 21 23 24 49 </code></pre> <h3>Example output</h3> <pre><code>4 </code></pre> <p>… because the longest subsequence is [5, 6, 7, 10].</p> <hr> <p>My solution works for small numbers, but exceeds the time limit for big inputs.</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;algorithm&gt; using namespace std; int main() { int n,a,c=1,max_count=1; cin&gt;&gt;n; vector&lt;int&gt;v; for(int i=0;i&lt;n;i++) { cin&gt;&gt;a; v.push_back(a); } for(int i=0;i&lt;n;i++) { int l=i+1; while((l&lt;n)&amp;&amp;(v[l]&lt;=2*v[i])) { c++; l++; max_count=max(max_count,c); } c=1; } cout&lt;&lt;""&lt;&lt;max_count; return 0; } </code></pre>
[]
[ { "body": "<p>There is no need to store the entries in a vector. There is also no need for a nested loop. This solution will run in O(<em>n</em>) time and O(1) space.</p>\n\n<p>Technically, <code>int</code> is only guaranteed to hold up to 16 bits. Use <code>long</code> to ensure that you can accommodate the l...
{ "AcceptedAnswerId": "202931", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T13:57:10.323", "Id": "202926", "Score": "5", "Tags": [ "c++", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "CodeForces: Creating the Contest" }
202926
<p>This script sorts files from current directory into known subdirectories. it is built for speed because the keyword database used can be up to 20kb. each line of the database has <code>subdirname,1,keywords?string</code> where the number is how many points this keyword is worth. It then counts these points and puts the file to the subdir with the most points. minimum points for a move is 2. The last line in each database file is <code>missing,0,not appearing in this directory</code>.</p> <pre><code>dir *.* /a-d &gt;nul 2&gt;nul || exit /b set "tempfile=%temp%\sortables" set "sourcedir=%~1" setlocal enabledelayedexpansion :: set datafile, categories according to where we are set "categories=" if /i "%cd%"=="d:\videos" ( set "datafile=videos" set "categories=series porno" ) if /i "%cd%"=="d:\videos\movies" ( set "datafile=movies" set "categories=features psychedelic pornography concerts standup featurettes documentaries" ) if /i "%cd%"=="d:\videos\movies\documentaries" ( set "datafile=docu" set "categories=1-scarcity 2-globalists 3-disinformation 4-agendas 5-abundance" ) if /i "%cd%"=="d:\videos\movies\features" ( set "datafile=films" set "categories=comedy drama action thriller venture crime horror mystery fantasy science western warfare" ) if /i "%cd%"=="d:\videos\series" ( set "datafile=series" set "categories=comedy stories1 stories2 reality trippy" ) if /i "%cd%"=="d:\videos\series\comedy" ( set "datafile=comedy" set "categories=cartoon classic modern reality sketch standup" ) if /i "%cd%"=="d:\videos\series\pilots" ( set "datafile=pilots" set "categories=reality drama comedy scifi fantasy crime mystery action thriller" ) if /i "%cd%"=="d:\videos\shorts" ( set "datafile=shorts" set "categories=psychedelic entertaining music media useful conspiracies" ) if /i "%cd%"=="d:\videos\shorts\media" ( set "datafile=media" set "categories=trailers games fandom extras facts analysis features" ) if /i "%cd%"=="d:\videos\shorts\music" ( set "datafile=music" set "categories=bigbeat classical clubbing country electro swing reggae dub experimental geeky metal rap rock synthwave triphop xxx" ) if not defined categories exit /b set database=d:\system\scripts\%datafile%.txt if not exist "%database%" echo critical error: database %datafile%.txt doesn't exist &amp;&amp; exit /b if defined v%~n0 echo sorting "%cd%" :: ============================================================================================================================= :: setup sorting categories (do not change anything lightly or without backup after this point) :: ============================================================================================================================= :: do not remove this echo off or this script will stop working @echo off set "sortingcategories=" for %%a in (%categories%) do set "sortingcategories=!sortingcategories!,%%~a" set "sortingcategories=%sortingcategories: =_%" :: ============================================================================================================================= :: create tempfile containing lines of: name|sortingcategory|weight :: ============================================================================================================================= ( for /f "tokens=1,2,*delims=," %%s in (%database%) do ( set "sortingcategory=%%s" set "sortingcategory=!sortingcategory: =_!" for /f "delims=" %%a in ( 'dir /b /a-d "%sourcedir%\*%%u*" 2^&gt;nul' ) do ( echo %%a^|!sortingcategory!^|%%t^|%%s^|%%u ) ) )&gt;"%tempfile%" type "%tempfile%" &gt;&gt;d:\system\scripts\sorter.log :: ============================================================================================================================= :: reset and call processing for each file in tempfile + dummy (helps counting the last score?) :: ============================================================================================================================= set "lastname=" for /f "tokens=1,2,3,*delims=|" %%a in ('sort "%tempfile%"') do call :resolve %%b %%c "%%a" call :resolve dummy 0 :: declare failures if defined v%~n0 if not "%datafile%"=="videos" if not "%datafile%"=="music" if not "%datafile%"=="media" ( dir "%~1\*" /a-d &gt;nul 2&gt;nul &amp;&amp; for /f "delims=" %%q in ('dir %1 /b /a-d') do echo unsortable in %datafile% "%%q" ) exit /b :resolve IF "%~3" equ "%lastname%" GOTO accum :: report and reset accumulators IF NOT DEFINED lastname GOTO RESET SET "winner=none" SET /a maxfound=1 FOR %%v IN (%sortingcategories%) DO ( FOR /f "tokens=1,2delims=$=" %%w IN ('set $%%v') DO IF %%x gtr !maxfound! (SET "winner=%%v"&amp;SET /a maxfound=%%x) ) if "%winner%"=="none" goto reset SET "winner=%winner:_= %" SET "lastname=%lastname:&amp;=and%" :: this has a problem with different type of dash - echo "%lastname%" | find /i ".tmp" &gt;nul &amp;&amp; exit /b :: this once overwrote a same-name, much smaller file, wtf? if "%winner%"=="porno" move "%sourcedir%\%lastname%" "d:\shame\" &gt;nul &amp;&amp; echo "d:\shame\%lastname%" if not "%winner%"=="porno" move "%sourcedir%\%lastname%" "%sourcedir%\%winner%\" &gt;nul &amp;&amp; echo "%sourcedir%\%winner%\%lastname%" if "%winner%"=="features" if exist "%sourcedir%\%lastname%" move "%sourcedir%\%lastname%" "%sourcedir%\%winner%\" &gt;nul &amp;&amp; echo "%sourcedir%\%winner%\%lastname%" :: before or after successful filing we could do a surgical dupe check for only that file, rendering the old style obsolete :RESET FOR %%v IN (%sortingcategories%) DO SET /a $%%v=0 SET "lastname=%~3" :accum SET /a $%1+=%2 </code></pre> <p>It runs nearly perfectly. However, for a file in <code>d:\videos</code> to find its way to, say, <code>d:\videos\shorts\music\electro</code>, this script will be run three times, once for every subdir. Should this be reworked so it can figure out the final resting place in one go? Would that be feasible? Would it require a single large database file, making it slow again?</p> <p>I know it's crazy this is done in batch but it's the only language I know. I would love to know about the better ways of doing this.</p>
[]
[ { "body": "<p>Maybe the following wrapper script could help:</p>\n\n<pre><code>@ECHO OFF\nSETLOCAL EnableExtensions\nset \"_OrigScript=D:\\bat\\CodeReview\\202927.bat\" # change to match your terms\nCD /D \"d:\\videos\"\nFOR /D /r %%G in (.) DO (\n pushd %%~fG\n call \"%_OrigScript%\"\n popd\n)\n</code></...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T13:58:06.703", "Id": "202927", "Score": "3", "Tags": [ "performance", "csv", "file-system", "batch" ], "Title": "Sorting files into subdirectories based on keyword scores" }
202927
<h2>1. Summary</h2> <p>I can't find, how I can to refactor multiple <code>with open</code> for one file.</p> <hr> <h2>2. Expected behavior of program</h2> <p>Program detect encoding for each file in the directory. If encoding ≠ UTF-8, file convert to UTF-8.</p> <hr> <h2>3. Minimal example of working code</h2> <p>(I'm sorry, Repl.it and another online Python interpreters incorrect works with non-UTF-8 files. But just in case, I created an <a href="https://repl.it/@Kristinita/democodereviewdecodefilestoutf8" rel="nofollow noreferrer"><strong>online demonstration</strong></a>.)</p> <ul> <li><code>kira_encoding.py</code></li> </ul> <pre class="lang-python prettyprint-override"><code># @Author: SashaChernykh # @Date: 2018-09-01 13:31:06 # @Last Modified time: 2018-09-01 14:39:30 """kira_encoding module.""" import codecs import glob import chardet ALL_FILES = glob.glob('*.md') def kira_encoding_function(): """Check encoding and convert to UTF-8, if encoding no UTF-8.""" for filename in ALL_FILES: # Not 100% accuracy: # https://stackoverflow.com/a/436299/5951529 # Check: # https://chardet.readthedocs.io/en/latest/usage.html#example-using-the-detect-function # https://stackoverflow.com/a/37531241/5951529 with open(filename, 'rb') as opened_file: bytes_file = opened_file.read() chardet_data = chardet.detect(bytes_file) fileencoding = (chardet_data['encoding']) print('fileencoding', fileencoding) if fileencoding in ['utf-8', 'ascii']: print(filename + ' in UTF-8 encoding') else: # Convert file to UTF-8: # https://stackoverflow.com/a/191403/5951529 with codecs.open(filename, 'r') as file_for_conversion: read_file_for_conversion = file_for_conversion.read() with codecs.open(filename, 'w', 'utf-8') as converted_file: converted_file.write(read_file_for_conversion) print(filename + ' in ' + fileencoding + ' encoding automatically converted to UTF-8 ') kira_encoding_function() </code></pre> <ul> <li><code>Kira1.md</code> in UTF-8:</li> </ul> <pre class="lang-text prettyprint-override"><code>Kira Goddess! </code></pre> <ul> <li><code>Kira2.md</code> in Cyrillic-1251:</li> </ul> <pre class="lang-text prettyprint-override"><code>Кира Богиня! </code></pre> <ul> <li><code>Kira3.md</code> in Central European Cyrillic 1250:</li> </ul> <pre class="lang-text prettyprint-override"><code>Kiara Istennő! </code></pre> <hr> <h2>4. Problem</h2> <p>I use <code>with</code> 3 times for opening same file. I don't think, that is a good practice.</p> <p><a href="https://radon.readthedocs.io/en/latest/intro.html#cyclomatic-complexity" rel="nofollow noreferrer"><strong>Radon Cyclomatic Complexity</strong></a> not <code>A</code>:</p> <pre class="lang-text prettyprint-override"><code>D:\SashaDebugging\KiraEncoding&gt;radon cc kira_encoding.py kira_encoding.py F 13:0 kira_encoding_function - B </code></pre> <p>I can not use <code>with</code>, but it <a href="https://docs.quantifiedcode.com/python-anti-patterns/maintainability/not_using_with_to_open_files.html" rel="nofollow noreferrer"><strong>anti-pattern</strong></a>.</p> <hr> <h2>5. Not helped</h2> <h3>5.1. Modes</h3> <ul> <li>That get encoding via chardet I need <code>rb</code> — bytes mode;</li> <li>That convert file via codecs I need non-bytes modes.</li> </ul> <p>I can't find, what can I do, that to have same mode for these actions.</p> <h3>5.2. decode</h3> <p>I can remove 1 <code>with</code>, if I know file encoding.</p> <pre class="lang-python prettyprint-override"><code>cyrillic_file = bytes_file.decode('cp1251') with codecs.open(filename, 'w', 'utf-8') as converted_file: converted_file.write(cyrillic_file) </code></pre> <ul> <li>Full file:</li> </ul> <pre class="lang-python prettyprint-override"><code># @Author: SashaChernykh # @Date: 2018-09-01 13:31:06 # @Last Modified time: 2018-09-01 16:26:57 """kira_encoding module.""" import codecs import glob import chardet ALL_FILES = glob.glob('*.md') def kira_encoding_function(): """Check encoding and convert to UTF-8, if encoding no UTF-8.""" for filename in ALL_FILES: # Not 100% accuracy: # https://stackoverflow.com/a/436299/5951529 # Check: # https://chardet.readthedocs.io/en/latest/usage.html#example-using-the-detect-function # https://stackoverflow.com/a/37531241/5951529 with open(filename, 'rb') as opened_file: bytes_file = opened_file.read() chardet_data = chardet.detect(bytes_file) fileencoding = (chardet_data['encoding']) print('fileencoding', fileencoding) if fileencoding in ['utf-8', 'ascii']: print(filename + ' in UTF-8 encoding') else: # Convert file to UTF-8: # https://stackoverflow.com/q/19932116/5951529 cyrillic_file = bytes_file.decode('cp1251') with codecs.open(filename, 'w', 'utf-8') as converted_file: converted_file.write(cyrillic_file) print(filename + ' in ' + fileencoding + ' encoding automatically converted to UTF-8') kira_encoding_function() </code></pre> <p>But the files may not necessarily be in <code>Cyrillic-1251</code>, they can be in any encoding. I can't find, How can I decode from any encoding. For example, <a href="https://stackoverflow.com/a/38102444/5951529"><strong>this</strong></a> can't work:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; kiragoddess = b'\xca\xe8\xf0\xe0 \xc1\xee\xe3\xe8\xed\xff!' &gt;&gt;&gt; kiragoddess.decode('cp1251') 'Кира Богиня!' &gt;&gt;&gt; kiragoddess.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte </code></pre> <h3>5.3. Nested syntax</h3> <p><a href="https://stackoverflow.com/a/1073814/5951529"><strong>Nested syntax</strong></a> doesn't work for me. If:</p> <pre class="lang-python prettyprint-override"><code>with codecs.open(filename, 'r') as file_for_conversion, codecs.open(filename, 'w', 'utf-8') as converted_file: read_file_for_conversion = file_for_conversion.read() converted_file.write(read_file_for_conversion) </code></pre> <ul> <li>Full file:</li> </ul> <pre class="lang-python prettyprint-override"><code># @Author: SashaChernykh # @Date: 2018-09-01 13:31:06 # @Last Modified time: 2018-09-01 16:01:29 """kira_encoding module.""" import codecs import glob import chardet ALL_FILES = glob.glob('*.md') def kira_encoding_function(): """Check encoding and convert to UTF-8, if encoding no UTF-8.""" for filename in ALL_FILES: # Not 100% accuracy: # https://stackoverflow.com/a/436299/5951529 # Check: # https://chardet.readthedocs.io/en/latest/usage.html#example-using-the-detect-function # https://stackoverflow.com/a/37531241/5951529 with open(filename, 'rb') as opened_file: bytes_file = opened_file.read() chardet_data = chardet.detect(bytes_file) fileencoding = (chardet_data['encoding']) print('fileencoding', fileencoding) if fileencoding in ['utf-8', 'ascii']: print(filename + ' in UTF-8 encoding') else: # Convert file to UTF-8: # https://stackoverflow.com/a/191403/5951529 with codecs.open(filename, 'r') as file_for_conversion, codecs.open(filename, 'w', 'utf-8') as converted_file: read_file_for_conversion = file_for_conversion.read() converted_file.write(read_file_for_conversion) print(filename + ' in ' + fileencoding + ' encoding automatically converted to UTF-8') kira_encoding_function() </code></pre> <p>Content of non-UTF-8 files will be removed in this case.</p> <h3>6. Do not offer</h3> <ol> <li>Yes, I know that I need to use logging, not <code>print</code> in real programs. Please, do not offer it; my question not about it.</li> <li>I need in-place conversion; my program must convert to UTF-8 to the same file, not to another.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T16:01:42.993", "Id": "391152", "Score": "0", "body": "If you know not to use print, why didn't you replace it with logging already or drop it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T16:06:53....
[ { "body": "<ol>\n<li><p>The code in the post uses the <code>chardet</code> library to determine the encoding of the file, but then the only use it makes of that information is to decide whether or not to try transcoding the file. The detected encoding should also be used to decode the content, using <a href=\"h...
{ "AcceptedAnswerId": "202985", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T14:02:55.263", "Id": "202928", "Score": "4", "Tags": [ "python", "python-3.x", "unicode", "cyclomatic-complexity", "utf-8" ], "Title": "Convert to UTF-8 all files in a directory" }
202928
<p>In an attempt to learn Rust, I've written up implementations of the bisection method and Newton's method for finding roots of an equation. Both methods come in two variants: the first one searches for a single root on a given interval (with assumption that there is at most one root there), and the second one tries to find all roots in the interval by splitting it into a number of smaller intervals, and calling the first variant on each.</p> <p>Everything seems to work as intended, but my main concern is whether or not it's idiomatic Rust.</p> <p>All of the code can be seen <a href="https://github.com/mpevnev/numerics" rel="nofollow noreferrer">here</a>, in the frozen branch <code>review-2018-09-01</code> (in particular, <code>src/roots.rs</code>).</p> <p>First, here's the <code>Epsilon</code> trait for approximately comparing things (because comparing floats exactly is almost always a bad idea), with a blanket implementation for everything that implements <code>Float</code> and <code>Signed</code> from the <code>num</code> package:</p> <pre><code>/// A trait for things that can be approximately equal. pub trait Epsilon { type RHS; type Precision; /// Return true if self and `other` differ no more than by a given amount. fn close(&amp;self, other: Self::RHS, precision: Self::Precision) -&gt; bool; /// Return true if self is close to zero. fn near_zero(&amp;self, precision: Self::Precision) -&gt; bool; } </code></pre> <p>Bisection method for a single root is implemented as follows:</p> <pre><code>/// Configuration structure for the bisection method (one root version). #[derive(Debug, Clone, Copy)] pub struct OneRootBisectCfg&lt;T&gt; { /// The real root, if any, will be no further than this from the reported /// root. pub precision: T, /// A limit on the number of iterations to perform. Pass `None` if you /// don't want a limit. pub max_iters: Option&lt;u32&gt; } /// Find a root for a given function in a given interval, assuming there is /// only one root there. pub fn bisect_one&lt;T, F&gt;(config: OneRootBisectCfg&lt;T&gt;, left: T, right: T, target: &amp;F) -&gt; Option&lt;T&gt; where T: Float + FromPrimitive + Signed, F: Fn(T) -&gt; T { let mut iter = 0; let mut left = left; let mut right = right; let mut left_val = target(left); let mut right_val = target(right); if left_val * right_val &gt; T::zero() { return None; } let mut mid = (left + right) / T::from_i32(2).unwrap(); let mut mid_val = target(mid); let max = config.max_iters; while right - left &gt; config.precision &amp;&amp; max.map_or(true, |m| iter &lt; m) { if left_val * mid_val &lt;= T::zero() { right = mid; right_val = mid_val; } else if mid_val * right_val &lt;= T::zero() { left = mid; left_val = mid_val; } else { return None; } iter += 1; mid = (left + right) / T::from_i32(2).unwrap(); mid_val = target(mid); } if abs(left_val) &lt; abs(mid_val) { Some(left) } else if abs(right_val) &lt; abs(mid_val) { Some(right) } else { Some(mid) } } </code></pre> <p>And here's the version that tries to find all roots in the given interval. It's written as an iterator. I have an additional question regarding this: is it better to export just <code>bisect_multi</code>, or export both <code>bisect_multi</code> and <code>MultiRootBisectState</code> (perhaps with a name change)? </p> <pre><code>/// Configuration structure for the bisection method (multiple roots version). #[derive(Debug, Clone, Copy)] pub struct MultiRootBisectCfg&lt;T&gt; { /// Real roots will be no further than this from the reported roots. pub precision: T, /// A limit on the number of iterations to perform. Pass `None` if you /// don't want a limit. pub max_iters: Option&lt;u32&gt;, /// The requested interval will be split into this many chunks, and each /// chunk will be tried for a root. pub num_intervals: usize } #[derive(Debug, Clone, Copy)] struct MultiRootBisectState&lt;'a, T, F: 'a&gt; { cfg: MultiRootBisectCfg&lt;T&gt;, left: T, right: T, target: &amp;'a F, cur_interval: usize, last_root: Option&lt;T&gt; } pub fn bisect_multi&lt;'a, T, F&gt;(config: MultiRootBisectCfg&lt;T&gt;, left: T, right: T, target: &amp;'a F) -&gt; impl Iterator&lt;Item=T&gt; + 'a where T: 'a + Float + FromPrimitive + Epsilon&lt;RHS=T, Precision=T&gt; + Signed, F: Fn(T) -&gt; T { MultiRootBisectState { cfg: config, left, right, target, cur_interval: 0, last_root: None } } impl&lt;'a, T, F&gt; Iterator for MultiRootBisectState&lt;'a, T, F&gt; where T: Float + FromPrimitive + Signed + Epsilon&lt;RHS=T, Precision=T&gt;, F: 'a + Fn(T) -&gt; T { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { if self.cur_interval &gt; self.cfg.num_intervals { return None } let num_ints = T::from_usize(self.cfg.num_intervals) .expect("Failed to convert the number of intervals into a float"); let interval_width = (self.right - self.left) / num_ints; while self.cur_interval &lt; self.cfg.num_intervals { let int = T::from_usize(self.cur_interval) .expect("Failed to convert an index into a float"); let left = self.left + interval_width * int; let right = left + interval_width; let one_cfg = OneRootBisectCfg { precision: self.cfg.precision, max_iters: self.cfg.max_iters }; let res = bisect_one(one_cfg, left, right, &amp;self.target); self.cur_interval += 1; if let Some(root) = res { let two = T::from_i32(2).unwrap(); let double_prec = two * self.cfg.precision; let mapper = |old: T| old.close(root, double_prec); let duplicate = self.last_root.map_or(false, mapper); if duplicate { continue } self.last_root = Some(root); return Some(root) } } None } } </code></pre> <p>Here's the Newton's method, single root version. It falls back to linearly interpolating the target function on the (possibly shrunk) interval and finding the root of that if the derivative of the target function gets too small, and fails altogether if it doesn't help either.</p> <pre><code>/// Configuration structure for the Newton's method (one root version). #[derive(Debug, Clone, Copy)] pub struct OneRootNewtonCfg&lt;T&gt; { /// The real root, if any, is most likely to be within this distance from /// the reported root, but this is not guaranteed. pub precision: T, /// A limit on the number of iterations to perform. Pass `None` if you /// don't want a limit. pub max_iters: Option&lt;u32&gt; } pub fn newton_one&lt;T, F, D&gt;(config: OneRootNewtonCfg&lt;T&gt;, left: T, right: T, first_approx: T, target: &amp;F, derivative: &amp;D) -&gt; Option&lt;T&gt; where T: Float + Epsilon&lt;RHS=T, Precision=T&gt;, F: Fn(T) -&gt; T, D: Fn(T) -&gt; T { let mut left = left; let mut right = right; let mut left_val = target(left); let mut right_val = target(right); let mut root = first_approx; let mut prev_root = None; let mut iter = 0; while prev_root.map_or(true, |old| !root.close(old, config.precision)) &amp;&amp; config.max_iters.map_or(true, |max| iter &lt; max) { iter += 1; if let Some(next) = next_newton_iter(config.precision, left, right, root, target, derivative) { prev_root = Some(root); root = next; } else if let Some(fallback_root) = linear_fallback(left, right, left_val, right_val) { prev_root = Some(root); root = fallback_root; } else { return None } let val_at_root = target(root); if left_val * val_at_root &lt;= T::zero() { right = root; right_val = val_at_root; } else { left = root; left_val = val_at_root; } } Some(root) } fn next_newton_iter&lt;T, F, D&gt;(prec: T, left: T, right: T, old: T, target: &amp;F, derivative: &amp;D) -&gt; Option&lt;T&gt; where T: Float + Epsilon&lt;RHS=T, Precision=T&gt;, F: Fn(T) -&gt; T, D: Fn(T) -&gt; T { let d = derivative(old); if d.near_zero(prec) { return None } let res = old - target(old) / d; if res &lt; left { None } else if res &gt; right { None } else { Some(res) } } fn linear_fallback&lt;T: Float&gt;(x1: T , x2: T, y1: T, y2: T) -&gt; Option&lt;T&gt; { let res = ((y2 - y1) * x1 - (x2 - x1) * y1) / (y2 - y1); if res &lt; x1 { None } else if res &gt; x2 { None } else { Some(res) } } </code></pre> <p>Multiple roots version of Newton's method more or less the same as the multiple roots version of the bisection algorithm - split, find roots, weed out duplicates. Again, should I export the iterator struct, or is exporting <code>newton_multi</code> sufficient?</p> <pre><code>/// Configuration structure for the Newton's method (multiple roots version). #[derive(Debug, Clone, Copy)] pub struct MultiRootNewtonCfg&lt;T&gt; { /// Real root will most likely be no further that this from the reported /// roots, but it's not guaranteed. pub precision: T, /// A limit on the number of iterations to perform. Pass `None` if you /// don't want to limit it. Note that this option governs maximum number of /// iterations on *each* chunk of the requested interval, not the number /// of iterations total. pub max_iters: Option&lt;u32&gt;, /// The requested interval will be split into this many chunks, and each /// chunk will be tested for a root separately. pub num_intervals: usize } #[derive(Debug, Clone, Copy)] struct MultiRootNewtonState&lt;'a, T, F: 'a, D: 'a&gt; { cfg: MultiRootNewtonCfg&lt;T&gt;, left: T, right: T, target: &amp;'a F, derivative: &amp;'a D, last_root: Option&lt;T&gt;, cur_interval: usize } pub fn newton_multi&lt;'a, T, F, D&gt;(cfg: MultiRootNewtonCfg&lt;T&gt;, left: T, right: T, target: &amp;'a F, derivative: &amp;'a D) -&gt; impl 'a + Iterator&lt;Item=T&gt; where T: 'a + Float + FromPrimitive + Epsilon&lt;RHS=T, Precision=T&gt;, F: 'a + Fn(T) -&gt; T, D: 'a + Fn(T) -&gt; T { MultiRootNewtonState { cfg, left, right, target, derivative, last_root: None, cur_interval: 0 } } impl&lt;'a, T, F, D&gt; Iterator for MultiRootNewtonState&lt;'a, T, F, D&gt; where T: Float + FromPrimitive + Epsilon&lt;RHS=T, Precision=T&gt;, F: 'a + Fn(T) -&gt; T, D: 'a + Fn(T) -&gt; T { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { if self.cur_interval &gt; self.cfg.num_intervals { return None } let intervals = T::from_usize(self.cfg.num_intervals) .expect("Failed to convert the number of intervals into a float"); let interval_width = (self.right - self.left) / intervals; while self.cur_interval &lt; self.cfg.num_intervals { let int = T::from_usize(self.cur_interval) .expect("Failed to convert an index into a float"); let left = self.left + interval_width * int; let right = left + interval_width; let one_cfg = OneRootNewtonCfg { precision: self.cfg.precision, max_iters: self.cfg.max_iters }; let two = T::from_i32(2).unwrap(); let res = newton_one(one_cfg, left, right, (right - left) / two, self.target, self.derivative); self.cur_interval += 1; if let Some(root) = res { let double_prec = self.cfg.precision * two; let is_close = |prev: T| prev.close(root, double_prec); let duplicate = self.last_root.map_or(false, is_close); if duplicate { continue } self.last_root = Some(root); return Some(root); } } None } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T14:54:55.303", "Id": "202930", "Score": "4", "Tags": [ "rust", "numerical-methods" ], "Title": "Bisection and Newton's method for finding a root of an equation" }
202930
<p>I created just for practice this leapyear script. </p> <p>What do you think about it? How can I make it more efficient? </p> <pre><code>package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.printf("Plese enter year: "); int chosedYear = input.nextInt(); leapYearMethod(chosedYear); } public static void leapYearMethod (int leapyear) { if ( leapyear % 4 == 0 ){ System.out.println("Yeeees!"); } else { int years = leapyear % 4; if(years == 1){ System.out.println("3 years later there is a leapyear."); } else if( years == 2) { System.out.println("2 years later there is a leapyear."); } else if( years == 3) { System.out.println("1 years later there is a leapyear."); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T10:35:04.563", "Id": "391283", "Score": "0", "body": "As you venture into the world of nit-picking (say hello programmers ;-)) you should be aware that your algorithm of leap-year calculation is not correct. See \"Algorithm\" in htt...
[ { "body": "<p>You should always close closeable resources such as <code>Scanner</code>. The preferred way to do this is a try-with-resources block</p>\n\n<pre><code>try (final Scanner input = new Scanner(System.in)) {\n //do stuff\n}\n</code></pre>\n\n<p>You should prefer making variables final where possibl...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T15:14:56.110", "Id": "202933", "Score": "2", "Tags": [ "java", "datetime" ], "Title": "Leap Year game in Java" }
202933
<p>I am doing the 100 Doors problem as an exercise to practice user input and loops. I do understand the problem can be solved by outputting every square number up to the maximum number, but it defeats the purpose of the exercise. The 100 Doors problem goes like this:</p> <blockquote> <p>\$N\$ doors are closed. In the first pass, I open all of them. In the second pass, I toggle every second door. In the third pass, I toggle every third door. I continue this until I have completed the \$N\$th pass. Find all the doors that will remain open after \$N\$ passes.</p> </blockquote> <p>Here is the code:</p> <pre><code>import java.io.IOException; import java.util.Scanner; public class hundredDoors { static boolean hasNum = false; public static void main(String[] args) throws IOException { while (!hasNum) { Scanner input = new Scanner(System.in); int numOfDoors = 0; System.out.print("Please enter the number of doors: "); if (input.hasNextInt()) { hasNum = true; numOfDoors = input.nextInt(); if (numOfDoors &lt; 1) { hasNum = false; System.out.println("Please enter an integer."); continue; } boolean[] doors = new boolean[numOfDoors]; for (boolean door : doors) { door = false; } for (int index = 1; index &lt;= numOfDoors; index++) { for (int door = index - 1; door &lt;= numOfDoors - 1; door += index) { doors[door] = !doors[door]; } } String output = "Doors still opened: \n"; int loops = 0; for (int door = 0; door &lt;= numOfDoors - 1; door++) { if (loops == 10) { output += "\n"; loops = 0; } if (doors[door]) { output += (door + 1 + " "); loops += 1; } } input.close(); System.out.println(output); } else { System.out.println("Please enter an integer."); } } } } </code></pre> <p>One note for this program is that \$N\$ is supplied by the user. The other is that for formatting sakes, each line will have a maximum of 10 numbers (# of door).</p> <p>My question here isn't how to make it more efficient (the most efficient method is to output every square since they have an odd number of factors as explained <a href="https://codereview.stackexchange.com/a/61315/71409">here</a>) but rather if the code can be more clean/clear (ie, names of indentifiers, loops can be shortened, input validation check can be better, etc).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T17:52:10.350", "Id": "391158", "Score": "0", "body": "Have you tried running this code? It has an obvious bug: you have to enter the same number twice, because the first `input.nextInt()` result is discarded." }, { "ContentL...
[ { "body": "<p>The program is difficult to read because all code is in the <code>main()</code>\nfunction. As an example, one has to jump to the end of the program in\norder to understand how the “get a positive integer from the user” loop\nworks.</p>\n\n<p>It is generally better to separate the I/O from the comp...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T16:16:26.987", "Id": "202938", "Score": "3", "Tags": [ "java", "programming-challenge", "simulation" ], "Title": "Classic Hundred Doors Simulation" }
202938
<p>I'm pretty new to this so constructive criticism is acceptable. I'm trying to find any way I can improve this system, all it does is take a string, determine if that string is a web address or a file location, if its a web address, it will download the elements, if file then it loads the elements.</p> <p>Pretty simple stuff, but is there any way I can improve here?</p> <pre><code>public class JsonConfigProvider : IConfigProvider { private readonly ILogger _logger; private IDictionary&lt;string, string&gt; _elements; public JsonConfigProvider( ILogger logger, IDictionary&lt;string, string&gt; elements) { _logger = logger; _elements = elements; } public void Load(string fileLocation, WebClient webClient = null) { try { _elements = Uri.TryCreate(fileLocation, UriKind.Absolute, out var uri) ? DownloadElements(uri, webClient) : LoadElements(fileLocation); } catch (WebException) { _logger.Error($"Failed to download the config from web address: {fileLocation}"); } catch (FileNotFoundException) { _logger.Error($"Failed to load config from file: {fileLocation}"); } catch (Exception) { _logger.Error("Something went wrong, we couldn't load the config file."); } } private static IDictionary&lt;string, string&gt; DownloadElements(Uri uri, WebClient webClient) { if (webClient == null) { throw new WebException("webClient is null."); } var content = webClient.DownloadString(uri); return JObject.Parse(content).ToFlatDictionary(content); } private static IDictionary&lt;string, string&gt; LoadElements(string configFile) { var content = File.ReadAllText(configFile); return JObject.Parse(content).ToFlatDictionary(content); } public string this[string key] =&gt; _elements[key]; public void Set(string key, string value, bool updateFile) { _elements[key] = value; } } </code></pre> <p>Not really needed, but here is the <code>ToFlatDictionary</code> method.</p> <pre><code>public static Dictionary&lt;string, string&gt; ToFlatDictionary(this JToken token, string path = null) { switch (token.Type) { case JTokenType.Object: return token.Children&lt;JProperty&gt;() .SelectMany(x =&gt; x.Value.ToFlatDictionary(x.Name)) .ToDictionary(x =&gt; path == null ? x.Key : string.Join(".", path, x.Key), x =&gt; x.Value); case JTokenType.Array: return token .SelectMany((x, i) =&gt; x.ToFlatDictionary(i.ToString())) .ToDictionary(x =&gt; path == null ? x.Key : string.Join(".", path, x.Key), x =&gt; x.Value); default: return new Dictionary&lt;string, string&gt; { [path] = ((JValue)token).Value.ToString() }; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T16:58:08.703", "Id": "202941", "Score": "1", "Tags": [ "c#", "beginner", ".net", "json", "configuration" ], "Title": "Simple json config provider" }
202941
<p>I wrote a function to convert seconds into the two biggest units of time and format it into a string. What I mean is that e.g. 134 second would be <code>02m14s</code> and 3665 seconds would become <code>1h1m</code>. Here is what I did:</p> <pre><code>def pprint_time(seconds): m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) format_str = lambda v1, v2, p: f"{v1:0&gt;2}{p[0]}{v2:0&gt;2}{p[1]}" if d &gt; 0: return format_str(d, h, ("d","h")) elif h &gt; 0: return format_str(h, m, ("h","m")) elif m &gt; 0: return format_str(m, s, ("m","s")) else: return f" {s:0&gt;2}sec" </code></pre> <p>I wonder if there is a more "pythonic" way of doing this since the <code>if-elif-else</code> statement does feel a bit clunky.</p>
[]
[ { "body": "<p>In general I think your code is pretty good. It is a simple function, and it does not need to get fancy. </p>\n\n<p>I do think one bit could be a bit cleaner. I believe this format string:</p>\n\n<pre><code>format_str = lambda v1, v2, p: f\"{v1:0&gt;2}{p[0]}{v2:0&gt;2}{p[1]}\"\nformat_str(d, h, ...
{ "AcceptedAnswerId": "202955", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T17:39:39.813", "Id": "202943", "Score": "4", "Tags": [ "python", "python-3.x", "datetime", "formatting" ], "Title": "Format seconds into the two biggest units of time" }
202943
<p>The task is to print the following series </p> <pre><code>1 2 1 3 2 5 3 7... </code></pre> <p>The elements at odd positions are Fibonacci series terms and the elements at even positions are prime numbers. Given an input 'n' the element at the nth position in the series has to be printed. eg. when n = 4, output will be 3. n = 7, output will be 3</p> <p>I've tried to solve the problem by returning nth prime number or nth fibonacci term. I am looking for any improvements that can be made to the code to optimize it further. </p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; int retPrime(int n) { //Using sieve of Eratosthenes to generate primes int size = n + 1; bool Primes[100]; int count = 0; memset(Primes, true, sizeof(Primes)); for (int i = 2; i&lt;sqrt(100); ++i) { if (Primes[i] == true) { for (int j = i * 2; j &lt;= 100; j = j + i) { Primes[j] = false; } } } int primeIndex=0; int i = 2; while (count != n) { if (Primes[i] == true) { count++; primeIndex = i; } ++i; } return primeIndex; } int retFib(int n) { if(n&lt;=1){ return n; } return retFib(n-1)+retFib(n-2); } int main() { int n; cin &gt;&gt; n; if(n%2==0) cout &lt;&lt; retPrime(n/2)&lt;&lt;" "; else cout &lt;&lt; retFib((n/2)+1)&lt;&lt;" "; return 0; } </code></pre>
[]
[ { "body": "<p>Don't use <code>#include &lt;bits/stdc++.h&gt;</code>.</p>\n\n<p>This include is not portable to every compiler and it's non-standard. Also, it includes every standard header which just bloats up the size of your executable.\nSee <a href=\"//stackoverflow.com/q/25311011\">this relevant Stack Overf...
{ "AcceptedAnswerId": "202959", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T17:49:50.123", "Id": "202945", "Score": "7", "Tags": [ "c++", "performance", "algorithm", "primes", "fibonacci-sequence" ], "Title": "alternating Fibonacci and prime series" }
202945
<blockquote> <p>Given an array of n elements in the following format <strong>{ a1, a2, a3, a4, ….., an/2, b1, b2, b3, b4, …., bn/2 }</strong>. The task is shuffle the array to <strong>{a1, b1, a2, b2, a3, b3, ……, an/2, bn/2 }</strong> without using extra space.</p> <p><strong>Input:</strong> </p> <p>The first line of input contains an integer T denoting the number of test cases. Then T test cases follow, Each test case contains an integer n denoting the size of the array. The next line contains n space separated integers forming the array.</p> <p><strong>Output:</strong> </p> <p>Print the shuffled array without using extra space.</p> <p><strong>Constraints:</strong> </p> <p>1&lt;=T&lt;=10^5 </p> <p>1&lt;=n&lt;=10^5 </p> <p>1&lt;=a[i]&lt;=10^5</p> <p><strong>Example:</strong> </p> <p><strong>Input:</strong> </p> <p>2 </p> <p>4 </p> <p>1 2 9 15 </p> <p>6 </p> <p>1 2 3 4 5 6</p> <p><strong>Output:</strong></p> <p>1 9 2 15 </p> <p>1 4 2 5 3 6</p> </blockquote> <p>My approach:</p> <pre><code>import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Arrays; class ShuffleArray { private static int [] getShuffledArray (int[] arr) { //List &lt;Integer&gt; arrList = new ArrayList&lt;&gt;(); return shuffleArray(arr,1,arr.length/2); } private static int [] shuffleArray (int[] arr, int swapInd1, int swapInd2) { if (swapInd2 == arr.length- 1) { return arr; } int temp = arr[swapInd2]; for (int i = swapInd2 ; i &gt; swapInd1; i--) { arr[i] = arr[i - 1]; } arr[swapInd1] = temp; return shuffleArray(arr, swapInd1 + 2, swapInd2 + 1); } public static void main (String[] args) { try (Scanner sc = new Scanner(System.in)) { int numTests = sc.nextInt(); while (numTests-- &gt; 0) { int size = sc.nextInt(); int[] arr = new int[size]; for (int i = 0; i &lt; size; i++) { arr[i] = sc.nextInt(); } int[] soln = getShuffledArray(arr); for (int i = 0; i &lt; soln.length; i++) { System.out.print(soln[i] + " "); } System.out.println(); } } } } </code></pre> <p>I have the following questions with regards to the above code:</p> <ol> <li><p>How can I further improve my approach?</p></li> <li><p>Is there a better way to solve this question?</p></li> <li><p>Are there any grave code violations that I have committed?</p></li> <li><p>Can space and time complexity be further improved?</p></li> </ol> <p><a href="https://practice.geeksforgeeks.org/problems/shuffle-integers/0" rel="nofollow noreferrer">Reference</a></p>
[]
[ { "body": "<ul>\n<li><p>The recursion results in \\$O(n)\\$ space complexity (each recursive invocation consumes some stack), so technically you did not fulfill the requirement of _not using extra space. Since it is a tail recursion, it can easy to eliminate. Unfortunately, Java doesn't do it, so you have to el...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T17:54:16.580", "Id": "202946", "Score": "1", "Tags": [ "java", "beginner", "recursion", "interview-questions", "complexity" ], "Title": "Rearrange an array in place such that the first and last halves are interleaved" }
202946
<p>This is my simple implementation of the Unix <code>cp</code> command. It is a C++ program but makes use of some of the lower level C library I/O functions.</p> <p>Any suggestions for style or performance improvements would be appreciated.</p> <pre><code>#include&lt;iostream&gt; #include&lt;fstream&gt; #include&lt;string&gt; #include&lt;vector&gt; #include&lt;fcntl.h&gt; #include&lt;unistd.h&gt; int main(int argc,char* argv[]) { // cmd : cp file1 file2 if ( argv[1] == nullptr || argv[2] == nullptr ){ std::cout &lt;&lt; "missing arguments: moderncp file1 file2 "; return 0; } const std::string input{argv[1]}; const std::string output{argv[2]}; // create a vector with 1024 byte allocated std::vector&lt;char&gt; buf(1024); // input file descriptor int infd = open(input.c_str(),O_RDONLY); // output file descriptor int outfd = open(output.c_str(),O_WRONLY|O_CREAT|O_EXCL,0664); while(true){ auto count = read(infd,buf.data(),buf.size()); if (count == 0) break; auto num_written = 0; auto num_to_write = count; while(num_written &lt; num_to_write){ num_written += write(outfd,buf.data()+num_written,count-num_written); } } close(infd); close(outfd); std::cout &lt;&lt; input &lt;&lt; '\t' &lt;&lt; output ; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T16:24:48.137", "Id": "391218", "Score": "0", "body": "`moderncp file1 file2` could become `moderncp from to`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T22:14:33.720", "Id": "391524", "Sco...
[ { "body": "<h1>The command</h1>\n\n<pre><code>// cmd : cp file1 file2\n</code></pre>\n\n<p>You then say:</p>\n\n<pre><code> std::cout &lt;&lt; \"missing arguments: moderncp file1 file2 \";\n</code></pre>\n\n<p>Is it <code>cp file1 file2</code> or <code>moderncp file1 file2</code>? </p>\n\n<p>In addition, I w...
{ "AcceptedAnswerId": "202984", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T18:14:05.620", "Id": "202947", "Score": "10", "Tags": [ "c++", "c++11", "file", "reinventing-the-wheel", "linux" ], "Title": "Implementation of Linux cp in modern C++" }
202947
<p>I'm writing a simple game with multiplayer mode in C++, using the SFML framework. Since I don't want to make it more complicated than necessary, I handle everything on a single thread, so that when the client is waiting for the remote player's turn, I check if there is an incoming message about the remote player's move. I do this in the following way, inside <code>OnlineGame</code> class.</p> <pre><code>void OnlineGame::PlayGame(int&amp; scoreOfPlayer1, int&amp; scoreOfPlayer2) { socket.setBlocking(false); WaitForStartSignal(); map.Show(gameWindow); currentPlayer-&gt;YourTurn(); while(!gameEnd) { RunOneGameCycle(); } SetPlayersScores(scoreOfPlayer1,scoreOfPlayer2); } void OnlineGame::RunOneGameCycle(){ gameWindow.GetInput(); GetRemoteMove(); if(turnEnd){ currentPlayer-&gt;YourTurn(); //the notification can only take place after the previous move was entirely completed, //so that the current move will only be handled by one player, who is finishing their turn turnEnd = false; } } </code></pre> <p>I wanted to refactor the <code>GetInput</code> method of <code>GameWindow</code> class, this method is the one responsible for getting input until some specific event happens, at which point the method should return.</p> <pre><code>void GameWindow::GetInput() { Event event{}; //clearing event queue while (pollEvent(event)); while (true) { while (pollEvent(event)) { if (active &amp;&amp; event.type == Event::KeyPressed){ switch (event.key.code) { case Keyboard::Up: NotifyOnDirectionSelected(up); return; case Keyboard::Down: NotifyOnDirectionSelected(down); return; case Keyboard::Right: NotifyOnDirectionSelected(right); return; case Keyboard::Left: NotifyOnDirectionSelected(left); return; case Keyboard::Escape: NotifyOnExit(); return; case Keyboard::Return: NotifyOnConfirmation(true); return; default: NotifyOnConfirmation(false); return; } } else if (event.type == Event::Closed) { NotifyOnExit(); close(); return; } else if (!active) return; } } } </code></pre> <p>It was obviously too long so I wanted to separate everything inside of the second while loop in a different method. Thus I refactored it in the following way:</p> <pre><code>void GameWindow::GetInput() { ClearEventQueue(); Event event{}; inputEnd = false; while (!inputEnd) { while (!inputEnd &amp;&amp; pollEvent(event)) { HandleEvent(event); } } } void GameWindow::ClearEventQueue() { Event event{}; while (pollEvent(event)); } void GameWindow::HandleEvent(const Event&amp; event) { if(active &amp;&amp; event.type == Event::KeyPressed){ HandleKeyPress(event.key.code); inputEnd = true; } else if(event.type == Event::Closed){ NotifyOnExit(); close(); inputEnd = true; } else if (!active){ inputEnd = true; } } void GameWindow::HandleKeyPress(const Keyboard::Key&amp; key) { switch (key) { case Keyboard::Up: NotifyOnDirectionSelected(up); break; case Keyboard::Down: NotifyOnDirectionSelected(down); break; case Keyboard::Right: NotifyOnDirectionSelected(right); break; case Keyboard::Left: NotifyOnDirectionSelected(left); break; case Keyboard::Escape: NotifyOnExit(); break; case Keyboard::Return: NotifyOnConfirmation(true); break; default: NotifyOnConfirmation(false); break; } } </code></pre> <p><code>inputEnd</code> is a member variable, and it is used to substitute the <code>return</code> statements in the previous solution. <code>active</code> denotes whether the window should wait for the local player's interaction (it is <code>true</code> when it's the local player's turn). I think that this second version looks much more cleaner and is much more readable than the first one, but I still find the double <code>while</code> loop with a partly same (similar looking) condition somewhat strange.</p> <p>The declarations of these classes (with all the relevant methods):</p> <p>GameWindow.h</p> <pre><code>using sf::RenderWindow; using sf::Keyboard; using sf::Event; class GameWindow : public RenderWindow { public: void GetInput(); /** * @brief Notifies the subscribed observers after the window containing the map has been closed. */ void NotifyOnExit() const; /** * @brief Notifies the subscribed observers after the user has selected a direction. */ void NotifyOnDirectionSelected(Direction) const; /** * @brief Notifies the subscribed observers whether the user has confirmed the action at hand. */ void NotifyOnConfirmation(bool) const; private: bool active; ///&lt; Should the window create events? bool inputEnd; void ClearEventQueue(); void HandleKeyPress(const Keyboard::Key&amp;); void HandleEvent(const Event&amp;); }; </code></pre> <p>OnlineGame.h</p> <pre><code>class OnlineGame : public Game { public: void PlayGame(int&amp; scoreOfPlayer1, int&amp; scoreOfPlayer2) override; private: /** * @brief Waits for the remote player's move and notifies the Player instance that * represents the remote player. */ void GetRemoteMove(); void WaitForStartSignal(); void RunOneGameCycle(); void SetPlayersScores(int&amp; scoreOfPlayer1, int&amp; scoreOfPlayer2); }; </code></pre> <p>Is there a way to make it even cleaner, and readable while retaining the same functionality? (it's important to note that the second <code>while</code> should stop right after some specific events happen, that's why I had to check the <code>inputEnd</code> there as well) Also, did I otherwise do a good job of refactoring the function, is there any modification I should make here?</p>
[]
[ { "body": "<h2>Logic separation:</h2>\n\n<p>At the moment, the <code>GameWindow</code> class appears to be responsible for event-handling, but also has parts of the game logic inside it, specifically:</p>\n\n<ul>\n<li>The <code>active</code> variable.</li>\n<li>The <code>inputEnd</code> variable.</li>\n<li>Clea...
{ "AcceptedAnswerId": "203128", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T18:25:19.997", "Id": "202949", "Score": "0", "Tags": [ "c++", "game", "event-handling", "sfml" ], "Title": "Double loop for input handling" }
202949
<p>I read <a href="https://codereview.stackexchange.com/questions/202938/classic-hundred-doors-simulation">this</a> question about the <a href="https://www.theodorenguyen-cao.com/2008/02/02/puzzle-100-doors/#.W4rrZOhKjyE" rel="nofollow noreferrer">"100 Doors" puzzle</a>, and thought that it would make for a good quick exercise.</p> <p>I ended up with two implementations. The first is more straightforward and uses a vector to store the boolean state of each door.</p> <p>This is quite slow though, and having a vector of <code>true</code> and <code>false</code>s seems off, so I decided to instead try making it use a set of open doors, and just toggle membership of the set. This is much faster, although the logic is a bit more complex.</p> <p>I'd like just general feedback on anything that's here. The need for <code>oneth-range</code> is unfortunate (as is its name), and any suggestions to avoid its use would be nice. I know this can probably be solved entirely using simple math, but I'd like suggestions on the "manual" algorithm.</p> <pre><code>; Example of set-version usage and time (let [n 5000] (time (find-open-doors-for n n))) "Elapsed time: 939.315276 msecs" =&gt; (1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900) </code></pre> <hr> <pre><code>(ns irrelevant.hundred-doors-vec) (defn- new-doors [n-doors] (vec (repeat n-doors false))) (defn- multiple-of? [n mutliple] (zero? (rem n mutliple))) (defn- oneth-range "Returns a range without 0. Max is inclusive." ([] (rest (range))) ([max] (rest (range (inc max))))) (defn- toggle-doors "Toggles the state of every nth door." [doors every-n] (mapv #(if (multiple-of? % every-n) (not %2) %2) (oneth-range), doors)) (defn- toggle-doors-for [doors max-n] (reduce toggle-doors doors (oneth-range max-n))) (defn find-open-doors-for "Simulates the opening and closing of n-doors many doors, up to a maximum skip distance of n." [n-doors n] (let [doors (new-doors n-doors) toggled (toggle-doors-for doors n)] (-&gt;&gt; toggled (map vector (oneth-range)) (filter second) (map first)))) </code></pre> <hr> <pre><code>(ns irrelevant.hundred-doors-set) (defrecord Doors [open n-doors]) (defn- new-doors [n-doors] (-&gt;Doors #{} n-doors)) (defn- multiple-of? [n multiple] (zero? (rem n multiple))) (defn- oneth-range "Returns a range without 0. Max is inclusive." ([] (rest (range))) ([max] (rest (range (inc max))))) (defn- toggle-doors "Toggles the state of every nth door." [doors every-n] (update doors :open (fn [open] (reduce (fn [acc-set n] (cond (not (multiple-of? n every-n)) acc-set (open n) (disj acc-set n) :else (conj acc-set n))) open (oneth-range (:n-doors doors)))))) (defn- toggle-doors-for [doors max-n] (reduce toggle-doors doors (oneth-range max-n))) (defn find-open-doors-for "Simulates the opening and closing of n-doors many doors, up to a maximum skip distance of n." [n-doors n] (let [doors (new-doors n-doors) toggled (toggle-doors-for doors n)] (-&gt; toggled (:open) (sort)))) </code></pre>
[]
[ { "body": "<p>My philosophy is \"A fundamentally mutable problem requires a fundamentally mutable solution\":</p>\n\n<pre><code>(def N 100)\n(def bound (inc N))\n\n(defn calc-doors []\n (verify (pos? N))\n (let [bound (inc N)\n doors (long-array bound 0) ]\n (doseq [step (range 1 bound)\n ...
{ "AcceptedAnswerId": "203197", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T21:42:28.063", "Id": "202953", "Score": "1", "Tags": [ "comparative-review", "clojure", "simulation" ], "Title": "Classic \"100 doors\" simulation in Clojure" }
202953
<p>I have a simple class like</p> <pre><code>class Item { Set&lt;String&gt; wordSet() {...} } </code></pre> <p>So each <code>item</code> has a set of words and I need the inverse relation, i.e., for each word find all <code>item</code>s containing it. This gets used a lot, so I want an <code>ImmutableSetMultimap</code> allowing me to retrieve it quickly.</p> <p>I'm using</p> <pre><code>ImmutableSetMultimap&lt;String, Item&gt; wordToItemsMultimap(Collection&lt;Item&gt; items) { Multimap&lt;Item, String&gt; itemToWords = items .stream() .collect(Multimaps.flatteningToMultimap( i -&gt; i, i -&gt; i.wordSet().stream(), HashMultimap::create)); Multimap&lt;String, Item&gt; wordToItems = Multimaps.invertFrom(itemToWords, HashMultimap.create()); return ImmutableSetMultimap.copyOf(wordToItems); } </code></pre> <p>for creating the map and it works, but I find it too complicated. I'm looking for a simpler solution.</p> <p>I don't care much about efficiency of the above snippet (as it gets called just once), but optimization hints are welcome as I'm doing a lot of similar things where speed matters.</p>
[]
[ { "body": "<p>Well, if your <code>items</code> has no null elements, you can use <a href=\"https://google.github.io/guava/releases/25.1-jre/api/docs/com/google/common/collect/ImmutableSetMultimap.html#flatteningToImmutableSetMultimap-java.util.function.Function-java.util.function.Function-\" rel=\"nofollow nore...
{ "AcceptedAnswerId": "202974", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T23:20:57.003", "Id": "202956", "Score": "0", "Tags": [ "java", "stream", "guava" ], "Title": "Collect all items containing a word to a Multimap" }
202956
<p>From <a href="https://www.codewars.com/kata/decode-the-morse-code/train/python" rel="noreferrer">Code Wars</a>:</p> <blockquote> <p>This kata is part of a series on the Morse code. After you solve this kata, you may move to the next one.</p> <p>In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world. The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·.</p> <p>NOTE: Extra spaces before or after the code have no meaning and should be ignored.</p> <p>In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words.</p> <p>Your task is to implement a function that would take the morse code as input and return a decoded human-readable string.</p> <p>For example:</p> <pre><code>decodeMorse('.... . -.-- .--- ..- -.. .') #should return "HEY JUDE" </code></pre> <p>NOTE: For coding purposes you have to use ASCII characters . and -, not Unicode characters.</p> <p>The Morse code table is preloaded for you as a dictionary, feel free to use it:</p> <p>Coffeescript/C++/Go/JavaScript/PHP/Python/Ruby/TypeScript: <code>MORSE_CODE['.--']</code><br> C#: <code>MorseCode.Get(".--")</code> (returns string)<br> Elixir: <code>morse_codes</code> variable<br> Haskell: <code>morseCodes ! ".--"</code> (Codes are in a Map String String)<br> Java: <code>MorseCode.get(".--")</code><br> Kotlin: <code>MorseCode[".--"] ?: ""</code> or <code>MorseCode.getOrDefault(".--", "")</code><br> Rust: <code>self.morse_code</code><br> All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly because otherwise the engine would simply ignore the tests, resulting in a "valid" solution.</p> <p>Good luck!</p> <p>After you complete this kata, you may try yourself at Decode the Morse code, advanced.</p> </blockquote> <p>I wrote a program that works, but it was essentially done with ad hoc patches to cover the edge cases/exceptions the program initially didn't cover. I'd appreciate a critique of my code, such as best practices and the program logic itself.</p> <pre><code># "Code Wars: Decode the Morse Code" def decodeMorse(morse_code): clear_text = '' char = '' index = 0 length = len(morse_code) delim1 = " " # Next character delimiter. delim2 = " " # Next word delimiter. while index &lt; (length): if morse_code[index] != delim1: # Build the character to be added to the clear text. char += morse_code[index] else: # When the delimiter is encountered. if char != '': # To cover the program encountering erroneous whitespace. clear_text += MORSE_CODE[char] # Add said character to clear text char = '' # Reset "char". if index &lt; (length-2): # If it is possible to encounter a space. if morse_code[index:(index+3)] == delim2: # When a space is encountered. clear_text += " " index += 2 if index == length-1: # If the last character in the code is a space, assign a control value to "char" char = "" index += 1 if char != "": # If the last character isn't a space. clear_text += MORSE_CODE[char] # Add the final character to the clear text. return clear_text </code></pre>
[]
[ { "body": "<h3>Iterating in Python</h3>\n\n<p>In Python if you find yourself writing something like:</p>\n\n<pre><code>while index &lt; (length): \n</code></pre>\n\n<p>There is good chance you are not writing Pythonic code. Looping over an index is just not needed that often. I will start with showing some ...
{ "AcceptedAnswerId": "202960", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-01T23:36:03.120", "Id": "202958", "Score": "7", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "morse-code" ], "Title": "Decode the Morse Code" }
202958
<p>I am developing an e-commerce website in ASP.NET MVC. Users can post advertisements of different types on the site. </p> <p>I am using inheritance to define my Ad types, and this review is mainly about taking advantage of the hierarchical structure to remove repeated code in Controllers and Views.</p> <p>I have different Ad types: <code>SimpleAd</code>, <code>Car</code> and <code>RealEstateRental</code>.</p> <p>Every Ad is derived from AdBase which has all the common properties:</p> <pre><code>public abstract class AdBase { public long AdBaseId { get; set; } public bool IsActive { get; set; } public long UserId { get; set; } public string Title { get; set; } public short AdDurationInDays { get; set; } public string PhotosFolder { get; set; } } </code></pre> <p>Now other Ads are derived from this base class:</p> <pre><code>public class SimpleAd : AdBase { public decimal Price { get; set; } } public class Car : AdBase { public decimal Price { get; set; } public string Make { get; set; } } public class RealEstateRental : AdBase { public decimal WeeklyRent { get; set; } public DateTime AvailableFrom { get; set; } public short NoOfBedrooms { get; set; } public short NoOfBathrooms { get; set; } } </code></pre> <p>I am using Entity Framework to interact with database and I am using Unit of Work and Repository patterns:</p> <p>I have an Abstract base repository (the intention is to avoid rewriting the same function for each Ad type, so I have put the common functions here):</p> <pre><code>public interface IAdBaseRepository&lt;TEntity&gt; where TEntity : AdBase { TEntity Get(long adBaseId); } public abstract class AdBaseRepository&lt;TEntity&gt; : IAdBaseRepository&lt;TEntity&gt; where TEntity : AdBase { public AdBaseRepository(ApplicationDbContext context) : base(context) { } public TEntity Get(long adBaseId) { return Context.AdBase.OfType&lt;TEntity&gt;() .Where(r =&gt; r.IsActive == true &amp;&amp; r.AdBaseId == adBaseId) .FirstOrDefault(); } } </code></pre> <p>Other ad repositories inherit from the above class:</p> <pre><code>public interface ISimpleAdRepository : IAdBaseRepository&lt;SimpleAd&gt; { } public class SimpleAdRepository : AdBaseRepository&lt;SimpleAd&gt;, ISimpleAdRepository { public SimpleAdRepository(ApplicationDbContext context) : base(context) { } } public interface ICarRepository : IAdBaseRepository&lt;Car&gt; { } public class CarRepository : AdBaseRepository&lt;Car&gt;, ICarRepository { public CarRepository(ApplicationDbContext context) : base(context) { } } </code></pre> <p>And this is my Unit of Work:</p> <pre><code>public class UnitOfWork : IUnitOfWork { protected readonly ApplicationDbContext Context; public UnitOfWork(ApplicationDbContext context) { Context = context; SimpleAd = new SimpleAdRepository(Context); RealEstateRental = new RealEstateRentalRepository(Context); Car = new CarRepository(Context); } public ISimpleAdRepository SimpleAd { get; private set; } public IRealEstateRentalRepository RealEstateRental { get; private set; } public ICarRepository Car { get; private set; } public int SaveChanges() { return Context.SaveChanges(); } public void Dispose() { Context.Dispose(); } } </code></pre> <p><strong>I am happy with everything so far... but the problem is I don't know how I can take advantage of this inheritance hierarchy in my Controllers and Views.</strong></p> <p>At the moment, I have 3 Controllers: <code>SimpleAdController</code>, <code>CarController</code> and <code>RealEstateRentalController</code>:</p> <pre><code>public class SimpleAdController : ControllerBase { private IUnitOfWork _unitOfWork; public SimpleAdController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } [HttpGet] public ActionResult Display(long id) { SimpleAd simpleAd = _unitOfWork.SimpleAd.Get(id); /* * I have not included my ViewModel Classes in this code review to keep * it small, but the ViewModels follow the same inheritance pattern */ var simpleAdDetailsViewModel = Mapper.Map&lt;SimpleAdDetailsViewModel&gt;(simpleAd); return View(simpleAdDetailsViewModel); } } </code></pre> <p><code>CarController</code> and <code>RealEstateRentalController</code> have similar display function, except the type of the Ad is different (e.g. in <code>CarController</code> I have):</p> <pre><code> public ActionResult Display(long id) { Car car = _unitOfWork.Car.Get(id); var carViewModel = Mapper.Map&lt;CarViewModel&gt;(car); return View(car); } </code></pre> <p>What I wanted to achieve was to create an <code>AdBaseController</code> to put all the common methods in it, something like this:</p> <pre><code>public class AdBaseController : ControllerBase { private IUnitOfWork _unitOfWork; public AdBaseController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } // Display for generic ad type [HttpGet] public ActionResult Display(long id) { // SimpleAd simpleAd = _unitOfWork.SimpleAd.Get(id); /* * I need to replace the above line with a generic ad type... * something like: _unitOfWork&lt;TAd&gt;.GenericAdRepository.Get(id) */ // var simpleAdDetailsViewModel = Mapper.Map&lt;SimpleAdDetailsViewModel&gt;(simpleAd); // return View(simpleAdDetailsViewModel); /* * similarly I have to replace the above 2 lines with a generic type */ } } </code></pre> <p>If I do the above, then my Ad Controllers can inherit from it and I don't need to repeat the same Display Method in every one of them... but then I need to make my <code>UnitOfWork</code> generic... or have 2 UoW (generic and non-generic)... which I am not sure if it is a good idea? <strong>Any recommendation on having a <code>AdBaseController</code></strong>?</p> <hr> <p>Similarly I am repeating a lot of code in my Views. For example, this is the display <code>SimpleAdView</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="row"&gt; &lt;div class="col-l"&gt; @*this partial view shows Ad photos and is common code for all ad types*@ @Html.Partial("DisplayAd/_Photos", Model) &lt;/div&gt; &lt;div class="col-r"&gt; &lt;div class="form-row"&gt; @*Common in all ads*@ &lt;h5&gt;@Model.Title&lt;/h5&gt; &lt;/div&gt; @*showing ad specific fields here*@ &lt;div class="form-row"&gt; &lt;h5 class="price"&gt;$@Model.Price&lt;/h5&gt; &lt;/div&gt; @*Ad heading is common among all ad types*@ @Html.Partial("DisplayAd/_AdBaseHeading", Model) &lt;/div&gt; &lt;/div&gt; @*Ad Description is common among all ad types*@ @Html.Partial("DisplayAd/_Description", Model) </code></pre> <p>And this is my display <code>CarView</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="row"&gt; &lt;div class="col-l"&gt; @*Common in all ads*@ @Html.Partial("DisplayAd/_Photos", Model) &lt;/div&gt; &lt;div class="col-r"&gt; &lt;div class="form-row"&gt; @*Common in all ads*@ &lt;h5&gt;@Model.Title&lt;/h5&gt; &lt;/div&gt; @*Price and Make are specific to Car*@ &lt;div class="form-row"&gt; &lt;h5 class="price"&gt;$@Model.Price&lt;/h5&gt; &lt;/div&gt; &lt;div class="form-row"&gt; &lt;h5 class="make"&gt;@Model.Make&lt;/h5&gt; &lt;/div&gt; @*Common in all ads*@ @Html.Partial("DisplayAd/_AdBaseHeading", Model) &lt;/div&gt; &lt;/div&gt; @*Common in all ads*@ @Html.Partial("DisplayAd/_Description", Model) </code></pre> <p>Again, I feel like I am repeating a lot of code in each view. I have tried to reduce the amount of repeated code by putting them in common Partial Views. <strong>I am not sure if there is a better way to do this?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-20T22:19:06.263", "Id": "393538", "Score": "0", "body": "See this post, with some great answers on this review: https://stackoverflow.com/questions/52284912/taking-advantage-of-inheritance-in-controllers-and-views" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T01:59:56.220", "Id": "202962", "Score": "1", "Tags": [ "c#", "generics", "inheritance", "asp.net-mvc", "repository" ], "Title": "E-commerce site for posting advertisements" }
202962
<p>I have been working on my own form of validation for XML other then xpath, as a toy project.</p> <p>First off, I use this class to add Validations to the graph to check for and validate they exist.</p> <pre><code>public class GraphValidation { public string Target { get; set; } = ""; public bool Result = false; } </code></pre> <p>Next I use this class to output a consistent number of strings:</p> <pre><code>public class GraphRow { //clone the columns down to show parent child relationships rather then just a single endpoint on each line. public GraphRow(string[] clone) { int i = 0; var values = clone.Where(x =&gt; x != "" &amp; x != null); foreach (var value in values) { Columns[i] = value ?? ""; i = i + 1; } } //Strings. public string[] Columns = new string[25]; //indexing the strings. public virtual string this[int i] { get { if (i &gt;= 0 &amp;&amp; i &lt; Columns.Length) { return this.Columns[i].ToString(); } else { return null; } } set { if (i &gt;= 0 &amp;&amp; i &lt; Columns.Length) { this.Columns[i] = value; } else { return; } } } #region IDisposable Support private static bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion IDisposable Support } public static class Grapher { public static Dictionary&lt;string, object&gt; roots { get; set; } //Row store public static List&lt;GraphRow&gt; Rows = new List&lt;GraphRow&gt;(); //Current row initialization private static GraphRow CurrentRow = new GraphRow(new string[25]); public static List&lt;GraphValidation&gt; Validations = new List&lt;GraphValidation&gt;(); public static List&lt;GraphValidation&gt; AddValidation(this List&lt;GraphValidation&gt; validations, string Attribute) { var Obj = new GraphValidation(); Obj.Target = Attribute; Validations.Add(Obj); return Validations; } public static List&lt;GraphValidation&gt; Validate(this List&lt;GraphValidation&gt; validations) { if (roots != null) { var AttributeGraph = Graph(roots); //AttributeGraph.ViewThis(); if (Validations.Count &gt; 0) { foreach(var validation in validations) { validation.Result = AttributeGraph.Select(x =&gt; x.ToString()).Any(x =&gt; x.Contains(validation.Target)); } } } return validations; } private static IQueryable&lt;object&gt; Graph(object roots, int Level = 0) { if (roots is IDictionary&lt;string, object&gt;) { foreach (var root in roots as IDictionary&lt;string, object&gt;) { //set key CurrentRow[Level] = root.Key; //loop around increasing the level as I dig down if (root.Value is IDictionary&lt;string, object&gt;) { Graph(root.Value as IDictionary&lt;string, object&gt;, Level + 1); } else if (root.Value is IList&lt;object&gt;) { Graph(root.Value as IList&lt;object&gt;, Level); } else { var ol = Level; while(ol &lt;= CurrentRow.Columns.Length -1 &amp;&amp; CurrentRow.Columns[ol + 1] != "" &amp;&amp; CurrentRow.Columns[ol + 1] != null) { CurrentRow.Columns[ol + 1] = ""; ol += 1; } //add the current row Rows.Add(CurrentRow); //Clone the Current row; CurrentRow = new GraphRow(CurrentRow.Columns); } } } else if (roots is List&lt;object&gt;) { foreach (var value in roots as List&lt;object&gt;) { if (value is IDictionary&lt;string, object&gt;) { Graph(value as IDictionary&lt;string, object&gt;, Level + 1); } else { if (value is IList&lt;object&gt;) { Graph(value as IList&lt;object&gt;, Level); } } } } else { //set end of path CurrentRow[Level] = roots.ToString(); var ol = Level; while (ol &lt;= CurrentRow.Columns.Length - 1 &amp;&amp; CurrentRow.Columns[ol + 1] != "" &amp;&amp; CurrentRow.Columns[ol + 1] != null) { CurrentRow.Columns[ol + 1] = ""; ol += 1; } //add the current row Rows.Add(CurrentRow); //Clone the Current row; CurrentRow = new GraphRow(CurrentRow.Columns); } return (from row in Rows select new { Column0 = row.Columns[0], Column1 = row.Columns[1], Column2 = row.Columns[2], Column3 = row.Columns[3], Column4 = row.Columns[4], Column5 = row.Columns[5], Column6 = row.Columns[6], Column7 = row.Columns[7], Column8 = row.Columns[8], Column9 = row.Columns[9], Column10 = row.Columns[10], Column11 = row.Columns[11], Column12 = row.Columns[12], Column13 = row.Columns[13], Column14 = row.Columns[14], Column15 = row.Columns[15], Column16 = row.Columns[16], Column17 = row.Columns[17], Column18 = row.Columns[18], Column19 = row.Columns[19], Column20 = row.Columns[20], Column21 = row.Columns[21], Column22 = row.Columns[22], Column23 = row.Columns[23], Column24 = row.Columns[24] }).AsQueryable(); } } </code></pre> <p>I then usually pass it into the <code>Viewthis()</code> function, which is just something I whipped together to view stuff:</p> <pre><code>public static class Extensions { const int MaxDepth = 2; private static int s_depth; public static int Depth { get =&gt; s_depth; set =&gt; s_depth = value; } public static void handler(object o, EventArgs _) { var otype = o as DataGridView; var CurrectRecipeId = (from row in otype.Rows.Cast&lt;DataGridViewRow&gt;() where row.Selected from cell in row.Cells.Cast&lt;DataGridViewCell&gt;() select cell.Value).FirstOrDefault(); var objObject = (from recipeParts in otype.Rows.Cast&lt;DataGridViewRow&gt;() where recipeParts.Cells[0].Value.ToString() == CurrectRecipeId.ToString() from parts in recipeParts.Cells.Cast&lt;DataGridViewCell&gt;() select new { parts.OwningColumn.Name, parts.Value }); objObject.ViewThis(handler); } public static void ViewThis(this IEnumerable&lt;object&gt; viewThis, EventHandler func = null) { if (Depth != MaxDepth) { Depth = Depth + 1; var ThreadForm = new Task(() =&gt; { Thread.CurrentThread.TrySetApartmentState(ApartmentState.STA); Form form = new Form(); DataGridView dgv = new DataGridView(); form.WindowState = FormWindowState.Maximized; dgv.DataBindingComplete += (o, _) =&gt; { var dataGridView = o as DataGridView; if (dataGridView != null) { dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Left; dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.Dock = DockStyle.Fill; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } }; dgv.DoubleClick += (o, _) =&gt; func(o, _); dgv.DataSource = viewThis.ToList(); form.Controls.Add(dgv); Application.Run(form); }); try { ThreadForm.Start(); ThreadForm.Wait(); Depth = Depth - 1; } catch (Exception) { throw; } } } </code></pre> <p>This is how I have it working now:</p> <pre><code>var xDoc = XDocument.Load(File.ReadAllText("2977501.xml").ValidateXML().ToStream()); Dictionary&lt;string, object&gt; roots = new Dictionary&lt;string, object&gt;(); XmlExtensions.XmlToDictionary(xDoc.Elements().First(), roots); Grapher.roots = roots; foreach( var validation in Grapher.Validations.AddValidation("externalFileLink").AddValidation("consumerStorageInstructions").Validate()) { if(validation.Result == false) { Console.WriteLine("Validation for " + validation.Target + " failed"); } else { Console.WriteLine("Validation Passed: " + validation.Target); } } </code></pre> <p>Can you review this and give me some points on what I can do to improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T22:45:11.880", "Id": "391253", "Score": "2", "body": "XML has absolutely fantastic schema validation. I’d suggest learning about it. Don’t reinvent a wheel if you don’t have to. https://docs.microsoft.com/en-us/dotnet/standard/data/...
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T03:31:18.153", "Id": "202965", "Score": "2", "Tags": [ "c#", "validation", "xml" ], "Title": "XML graphing, and attribute existence" }
202965
<p>I'm trying to create an <code>if</code>-<code>else</code> statement that pops up a modal with output in the body, and if there is no input detected then an alert pops up.</p> <pre><code> //fizzbuzz $("#btnfb").click(function () { var numfiz = $("#fizz").val(); var numbuz = $("#buzz").val(); var outputarray = []; for (var loop = 1; loop &lt;= 100; loop++) { if (loop % numfiz === 0 &amp; loop % numbuz === 0) { outputarray.push("&lt;span class='boldItalicPurple'&gt;Fizzbuzz&lt;/span&gt;"); } else if (loop % numfiz === 0) { outputarray.push("&lt;span class='boldItalicGreen'&gt;Fizz&lt;/span&gt;"); } else if (loop % numbuz === 0) { outputarray.push("&lt;span class='boldItalicOrane'&gt;Buzz&lt;/span&gt;"); } else { outputarray.push(loop); } $("fzbzout").html(outputarray.join(", ")); $('#myModel5').modal('show'); }); </code></pre>
[]
[ { "body": "<p><a href=\"http://wiki.c2.com/?FizzBuzzTest\" rel=\"nofollow noreferrer\">FizzBuzz is a popular interview question</a> so following good programming practices are a good idea.</p>\n\n<p>One key part of working with people on a larger project is readable code. Your code is very difficult to read be...
{ "AcceptedAnswerId": "202979", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T04:36:33.450", "Id": "202967", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Creating a popup of a modal with output" }
202967
<p>I hate having to format questions around here. Adding four spaces to each source file and the correct name at the top of each source file becomes a headache when I have to post longer questions.</p> <p>This is a <strong>simple python question parser</strong> that takes in arguments from the console and prints out correct format for a CodeReview question. <strong>Any suggestions</strong> on how to make this code more readable, concise and pythonic would be appreciated.</p> <p><strong>Question Parser.py</strong></p> <pre><code>import os import sys import argparse def format_string(PATH,EXTENSION): source_files=[f for f in os.listdir(PATH) if os.path.isfile(os.path.join(PATH,f))] source_files=[f for f in source_files if f.endswith(EXTENSION)] indentation=4 formatted_string="" for source_file in source_files: formatted_string+= ("**%s**\n\n" % source_file) with open(os.path.join(PATH,source_file)) as source: for line in source.readlines(): formatted_string+=(" "*indentation+"".join(line)) return formatted_string if __name__=="__main__": parser=argparse.ArgumentParser(description="Automatic formatter for CodeReview Stackexchange Questions") parser.add_argument("-p","--path",help="Path for the source files. Default is the current directory",nargs="?",default=os.getcwd(),const=os.getcwd()) parser.add_argument("header",help="The file that is added to the top of the question") parser.add_argument("-e","--extension",help="Filter by the type of source files that is present in the directory",nargs="+",default="") parser.add_argument("-o","--out",help="Output the result to a file. By default outputs to the console.",nargs="?") args=parser.parse_args() if not os.path.isfile(args.header): raise parser.error("Header file doesnot exist.\nPlease specify a correct header file path") if os.path.exists(args.path): question="".join(open(args.header).readlines()) question+="\n"+format_string(args.path,tuple(args.extension,)) if not (args.out==None): with open(args.out,"w") as outfile: outfile.write(question) else: print(question) else: raise parser.error("Path doesnot exist.") </code></pre>
[]
[ { "body": "<h1>PEP 8</h1>\n\n<p>I would review <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>. Some of your style choices are not considered best practice by the Python community. Some quick observations:</p>\n\n<ol>\n<li>Constants are given <code>CAPS_WITH_UNDERSCORES</code>...
{ "AcceptedAnswerId": "202969", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T05:26:42.660", "Id": "202968", "Score": "8", "Tags": [ "python", "file", "formatting", "stackexchange" ], "Title": "Python tool to assemble CodeReview posts from source files" }
202968
<p>Can it be made faster, and I am a newbie to complexity but I'm pretty sure the average case for this would be O(n). Am I wrong? Output for the first list should be: (1,9), (2,8), (5,5), (-11,21)</p> <p>The program finds pairs of an array whose sum is equal to ten.</p> <pre><code>#find pairs of an array whose sum is equal to ten #bonus do it im linear time list1 = [1,1,2,1,9,9,5,5,2,3,745,8,1,-11,21] list2 = [1,1,1,1,9,9,9,9,2,8,8,8,2,2,0,0,0] list3 = ["dog", "cat", "penguin", 9, 1] list4 = [] def find_pairs_sum_n(list1, n): set1 = set(list1) history = set() if not list1: print("list is empty") raise StopIteration if not all(isinstance(n, int) for n in list1): print("list must contain only integers") raise StopIteration for x in set1: history.add(x) if (n - x) in set1 and (n-x) not in history: yield (x, n - x) elif x == n/2 and list1.count(n/2) &gt; 1: yield (int(n/2), int(n/2)) x = find_pairs_sum_n(list1, 10) for i in x: print(i) y = find_pairs_sum_n(list2, 10) for i in y: print(i) z = find_pairs_sum_n(list3, 10) print(next(z)) w = find_pairs_sum_n(list4, 10) print(next(w)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T09:48:14.950", "Id": "391196", "Score": "0", "body": "What's the problem description, was this from a book? A programming challenge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T09:49:34.327", ...
[ { "body": "<p>In no particular order, a few suggestions to make the code more Pythonic.</p>\n\n<h3><code>return</code> from generator</h3>\n\n<p>You do not need to <code>raise StopIteration</code> in a generator, you can simply return. So this:</p>\n\n<pre><code>if not list1:\n print(\"list is empty\")\n ...
{ "AcceptedAnswerId": "202990", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T09:07:59.837", "Id": "202977", "Score": "2", "Tags": [ "python", "beginner", "k-sum" ], "Title": "Find the pairs of integers that sum to N" }
202977
<p>Here a string is taken as input and the program suppose to check whether the string is palindrome or not. <strong>Is there any way the code can be improved</strong>? Is it okay to use <em>foreach</em> to break the string into character.</p> <pre><code>class Program { static void Main(string[] args) { //input a string string orginalStr = Console.ReadLine().ToLower(); ; //call the palindrome method Console.WriteLine(CheckPalindrome(orginalStr) ? "This is palindrome" : "This is not palindrome"); Console.ReadKey(); } static bool CheckPalindrome(string orginalStr) { //call the string reverse method var reversedStr = ReverseString(orginalStr); if (reversedStr.Equals(orginalStr)) return true; return false; } static string ReverseString(string orginalStr) { string reversedStr = ""; foreach (char ch in orginalStr) { reversedStr = ch + reversedStr; } return reversedStr; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T16:32:44.700", "Id": "391219", "Score": "1", "body": "I think this is more efficient. https://codereview.stackexchange.com/questions/188234/palindrome-algorithm/188237#188237" }, { "ContentLicense": "CC BY-SA 4.0", "Cre...
[ { "body": "<p>All in all this code does, what you want it to do and you separate responsibility by splitting the code in meaningful functions.</p>\n\n<p>I don't like that <code>CheckPalindrome(...)</code> expects the input to be in a certain format (case). In other words: it should do the preparation of the <co...
{ "AcceptedAnswerId": "202981", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T10:09:57.017", "Id": "202978", "Score": "7", "Tags": [ "c#", "programming-challenge", ".net" ], "Title": "Palindrome program needs improvement" }
202978
<p>I'm a student, and most of my lab work includes writing programs (usually .cpp) run them, copy the source code and output to a word file and either mail a pdf to the concerned teacher or submit in print. (I still don't get the point of submitting a program in print or pdf file, but this is what we're asked to do)</p> <p>So I wrote a little shell script to help me automate this stuff. </p> <p>The packages I'm using are: </p> <ol> <li><code>enscript</code></li> <li><code>ps2pdf</code></li> <li><code>pdftk</code></li> </ol> <p>Here is the script code: </p> <pre><code>#!/bin/bash TARGET='/home/angg/code' cd $TARGET find . -type f -name '*.cpp' | while read CPPFILE do TITLE=$(basename $CPPFILE .cpp) g++ $TITLE.cpp echo $CPPFILE | xargs enscript --color=1 -C -Ecpp -B -t $TITLE -o - | ps2pdf - $TITLE.pdf ./a.out &gt; $TITLE.txt &amp;&amp; enscript -B $TITLE.txt -o - | ps2pdf - $TITLE.output.pdf pdftk $TITLE.pdf $TITLE.output.pdf cat output $TITLE.final.pdf rm $TITLE.output.pdf rm $TITLE.pdf done today=`date +%j-%M` pdftk *.pdf cat output $today.pdf </code></pre> <p>I referred this <a href="https://bits.mdminhazulhaque.io/cpp/convert-cpp-to-pdf-with-syntax-highlighting.html" rel="nofollow noreferrer">link</a> to convert all cpp files to pdf files, to add output at the end of each cpp file, I created a separate pdf for output of each program and merged the two pdfs together using <code>pdftk</code> and then removing pdfs not needed now</p> <p>I need a review regarding the code and if I can shorten it. Also, I'm new to all these packages used and would want to know if there's any redundancy I could avoid.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T16:05:05.990", "Id": "391217", "Score": "0", "body": "You're asked to deliver source code in PDF form? That's odd indeed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T17:13:03.950", "Id": "3912...
[ { "body": "<h1>Automated suggestions</h1>\n\n<p>If you don't have <code>shellcheck</code> installed, grab it, or use the online service. It reports a bunch of questionable constructs:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>202986.sh:4:1: warning: Use 'cd ... || exit' or 'cd ... || return' i...
{ "AcceptedAnswerId": "203013", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T15:44:43.350", "Id": "202986", "Score": "2", "Tags": [ "bash", "shell" ], "Title": "File generator in shell script" }
202986
<p>This code is working well. Is there a way to minimize the complexity of the code?</p> <pre><code>final = [] a = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] for i in range(len(a)): temp = [] for k in range(len(a)): m = 0 if i != k: for j in range(0, len(a)): DIFFERENCE = (a[i][j] - a[k][j])**2 m += DIFFERENCE p = (1/(2 * m)) * DIFFERENCE temp.append(p) final.append(temp) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T04:17:48.127", "Id": "391264", "Score": "2", "body": "What is the purpose of this operation? Maybe better alternatives exist..." } ]
[ { "body": "<p>You can use <code>numpy</code> in conjunction with <code>itertools</code> for this.</p>\n\n<p>First, <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"nofollow noreferrer\"><code>itertools.permutations(\"ABCD\", 2)</code></a> gives <code>AB AC AD BA BC BD CA...
{ "AcceptedAnswerId": "203018", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T17:30:10.803", "Id": "202987", "Score": "-1", "Tags": [ "python", "python-3.x" ], "Title": "Operation between one list and all other remaining lists excluding the operation between the selected list itself" }
202987
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/202680/cleaning-a-file-word-query">Cleaning a file / Word Query</a></p> <p>I incorporated the suggestions from the anwers there and turned the Word Query Programm into a GUI.</p> <p><a href="https://i.stack.imgur.com/ltFD0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ltFD0.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/QjVew.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QjVew.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/Xswea.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xswea.jpg" alt="enter image description here"></a></p> <p>For that I used the Support code of the Book which provides some basic functions for FLTK GUI toolkit. You can find it here: <a href="http://www.stroustrup.com/Programming/PPP2code/" rel="nofollow noreferrer">http://www.stroustrup.com/Programming/PPP2code/</a></p> <p>However I modified the code slightly because I didn't want to use the <code>std_lib_facilities.h</code> provided by Stroustrup since it includes a lot of bloat by including many headers which are not necessary.</p> <p>First of all I would like you to check the GUI implementation. Let me know if you find improvements for the code. Are there any bad practices? You can find it in <code>Word_query_window.h/cpp</code>.</p> <p>Feel also free to take a look in <code>Cleaned_words.h/cpp</code> and <code>Word_query.h/cpp</code>. They are improved Versions of the files provided in the original question without GUI: <a href="https://codereview.stackexchange.com/questions/202680/cleaning-a-file-word-query">Cleaning a file / Word Query</a></p> <p>In <code>Word_query.h</code> I would especially like to know how to simplify</p> <pre><code>std::vector&lt;std::pair&lt;Word, Occurences&gt;&gt; most_frequent_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; longest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; shortest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); </code></pre> <p>These functions were changed from the last question to here by returning more than one result. I feel like I compute the results to complicated. Also the three methods look quite similar in the implementation.</p> <p>The other files they are basically all from Stroustrup with <code>std_lib_facilities.h</code> removed as an include. I think it would be also interesting what could be improved in them nowadays. The Book is based on C++11 but feel also free to suggest improvements here using the latest standard (C++17).</p> <p>If you want this GUI get to run. I used MSVC 2017 and followed this tutorial how to get install FLTK to run: <a href="https://bumpyroadtocode.com/2017/08/05/how-to-install-and-use-fltk-1-3-4-in-visual-studio-2017-complete-guide/" rel="nofollow noreferrer">https://bumpyroadtocode.com/2017/08/05/how-to-install-and-use-fltk-1-3-4-in-visual-studio-2017-complete-guide/</a></p> <p>Here is the source code in order from important to less important:</p> <p><b>Word_query_window.h</b></p> <pre><code>#ifndef WORD_QUERY_WINDOW_GUARD_280820182111 #define WORD_QUERY_WINDOW_GUARD_280820182111 #include "Window.h" #include "GUI.h" #include "Point.h" #include &lt;fstream&gt; #include &lt;map&gt; namespace word_query_gui { using Word = std::string; using Occurences = int; class Word_query_window : public Graph_lib::Window { public: Word_query_window(); private: void init_window_open_file(); void show_window_open_file(); void hide_window_open_file(); void init_window_show_filename(); void show_window_show_filename(); void hide_window_show_filename(); void init_window_select(); void show_window_select(); void hide_window_select(); void init_window_display(); void show_window_display(); void hide_window_display(); static const Point window_offset_xy; static constexpr auto window_size_x = 1024; static constexpr auto window_size_y = 768; static constexpr auto window_label = "Word query"; static constexpr auto button_size_x = (window_size_x / 100) * 13; static constexpr auto button_size_y = (window_size_y / 100) * 8; // Error static const Point text_error_xy; static constexpr auto text_error_font_size = (window_size_y / 100) * 8; static constexpr auto text_error_color = Graph_lib::Color::red; static constexpr auto text_error_label_invalid = "Invalid input"; static constexpr auto text_error_label_no_file = "File does not exist"; Graph_lib::Text text_error; // "Window" open file static const Point in_box_filename_xy; static constexpr auto in_box_filename_size_x = (window_size_x / 100) * 59; static constexpr auto in_box_filename_size_y = button_size_y; static constexpr auto in_box_filename_label = "Enter Filename "; static constexpr auto in_box_filename_label_size = in_box_filename_size_y; static constexpr auto in_box_filename_text_size = in_box_filename_size_y; Graph_lib::In_box in_box_filename; static const Point button_open_file_xy; static constexpr auto button_open_file_size_x = button_size_x; static constexpr auto button_open_file_size_y = button_size_y; static constexpr auto button_open_file_label = "Open"; Graph_lib::Button button_open_file; void button_open_file_event(); // "Window" show filename static const Point button_change_file_xy; static constexpr auto button_change_file_size_x = button_size_x * 150 / 100; static constexpr auto button_change_file_size_y = button_size_y; static constexpr auto button_change_file_label = "Change File"; Graph_lib::Button button_change_file; void button_change_file_event(); static const Point text_current_filename_xy; static constexpr auto text_current_filename_font_size = button_change_file_size_y; static constexpr auto text_current_filename_color = Graph_lib::Color::black; Graph_lib::Text text_current_filename; // "Window" Select static constexpr auto window_select_count_of_buttons = 7; static constexpr auto window_select_button_size_y = (window_size_y - button_change_file_size_y) / window_select_count_of_buttons; static const Point button_occurences_xy; static constexpr auto button_occurences_size_x = button_size_x * 150 / 100; static constexpr auto button_occurences_size_y = window_select_button_size_y; static constexpr auto button_occurences_label = "Occurences of:"; Graph_lib::Button button_occurences; void button_occurences_event(); static const Point in_box_occurences_xy; static constexpr auto in_box_occurences_size_x = (window_size_x / 100) * 59; static constexpr auto in_box_occurences_size_y = window_select_button_size_y; static constexpr auto in_box_occurences_label = ""; static constexpr auto in_box_occurences_label_size = (window_select_button_size_y / 100) * 90; static constexpr auto in_box_occurences_text_size = (window_select_button_size_y / 100) * 90; Graph_lib::In_box in_box_occurences; static const Point text_occurences_xy; static constexpr auto text_occurences_font_size = window_select_button_size_y; static constexpr auto text_occurences_color = Graph_lib::Color::black; Graph_lib::Text text_occurences; static const Point button_most_frequent_xy; static constexpr auto button_most_frequent_size_x = button_size_x * 150 / 100; static constexpr auto button_most_frequent_size_y = window_select_button_size_y; static constexpr auto button_most_frequent_label = "Most frequent Word"; Graph_lib::Button button_most_frequent; void button_most_frequent_event(); static const Point button_longest_xy; static constexpr auto button_longest_size_x = button_size_x * 150 / 100; static constexpr auto button_longest_size_y = window_select_button_size_y;; static constexpr auto button_longest_label = "Longest Word"; Graph_lib::Button button_longest; void button_longest_event(); static const Point button_shortest_xy; static constexpr auto button_shortest_size_x = button_size_x * 150 / 100; static constexpr auto button_shortest_size_y = window_select_button_size_y; static constexpr auto button_shortest_label = "Shortest Word"; Graph_lib::Button button_shortest; void button_shortest_event(); static const Point button_starting_with_xy; static constexpr auto button_starting_with_size_x = button_size_x * 150 / 100; static constexpr auto button_starting_with_size_y = window_select_button_size_y; static constexpr auto button_starting_with_label = "Words starting with:"; Graph_lib::Button button_starting_with; void button_starting_with_event(); static const Point in_box_starting_with_xy; static constexpr auto in_box_starting_with_size_x = (window_size_x / 100) * 59; static constexpr auto in_box_starting_with_size_y = window_select_button_size_y; static constexpr auto in_box_starting_with_label = ""; static constexpr auto in_box_starting_with_label_size = (window_select_button_size_y / 100) * 90; static constexpr auto in_box_starting_with_text_size = (window_select_button_size_y / 100) * 90; Graph_lib::In_box in_box_starting_with; static const Point button_with_len_xy; static constexpr auto button_with_len_size_x = button_size_x * 150 / 100; static constexpr auto button_with_len_size_y = window_select_button_size_y; static constexpr auto button_with_len_label = "Words with len:"; Graph_lib::Button button_with_len; void button_with_len_event(); static const Point in_box_with_len_xy; static constexpr auto in_box_with_len_size_x = (window_size_x / 100) * 59; static constexpr auto in_box_with_len_size_y = window_select_button_size_y; static constexpr auto in_box_with_len_label = ""; static constexpr auto in_box_with_len_label_size = (window_select_button_size_y / 100) * 90; static constexpr auto in_box_with_len_text_size = (window_select_button_size_y / 100) * 90; Graph_lib::In_box in_box_with_len; static const Point button_show_all_xy; static constexpr auto button_show_all_size_x = button_occurences_size_x; static constexpr auto button_show_all_size_y = window_select_button_size_y; static constexpr auto button_show_all_label = "Show all Words"; Graph_lib::Button button_show_all; void button_show_all_event(); // "Window" display static const Point button_display_back_xy; static constexpr auto button_display_back_size_x = button_size_x; static constexpr auto button_display_back_size_y = button_size_y; static constexpr auto button_display_back_label = "Back"; Graph_lib::Button button_display_back; void button_display_back_event(); static const Point button_previous_page_xy; static constexpr auto button_previous_page_size_x = button_size_x; static constexpr auto button_previous_page_size_y = button_size_y; static constexpr auto button_previous_page_label = "Previous Page"; Graph_lib::Button button_previous_page; void button_previous_page_event(); static const Point button_next_page_xy; static constexpr auto button_next_page_size_x = button_size_x; static constexpr auto button_next_page_size_y = button_size_y; static constexpr auto button_next_page_label = "Next Page"; Graph_lib::Button button_next_page; void button_next_page_event(); static const Point text_display_xy; static constexpr auto text_display_font_size = in_box_filename_size_y / 2; static constexpr auto text_display_offset_y = text_display_font_size; static constexpr auto text_display_color = Graph_lib::Color::black; Graph_lib::Vector_ref&lt;Graph_lib::Text&gt; text_display; template&lt;typename T&gt; void init_text_display(const T&amp; container); static constexpr auto text_display_entrys_per_page = ((window_size_y - text_current_filename_font_size - button_next_page_size_y) / text_display_font_size) - 1; int page{ 0 }; void print_page(); std::string current_filename; std::map&lt;Word, Occurences&gt; words_in_file; }; inline bool file_exists(const std::string&amp; filename) { std::ifstream f(filename.c_str()); return f.good(); } inline void init_element(Graph_lib::Window&amp; window, Graph_lib::Text&amp; text, int font_size, Graph_lib::Color color) { window.attach(text); text.set_font_size(font_size); text.set_color(color); } inline void init_element(Graph_lib::Window&amp; window, Graph_lib::Button&amp; button) { window.attach(button); button.hide(); } inline void init_element(Graph_lib::Window&amp; window, Graph_lib::In_box&amp; in_box, int text_size, int label_size) { window.attach(in_box); in_box.set_text_size(text_size); in_box.set_label_size(label_size); in_box.hide(); } inline void make_gui_text_output(Graph_lib::Vector_ref&lt;Graph_lib::Text&gt;&amp; texts, const std::string&amp; output, Point pos_xy) { texts.push_back(new Graph_lib::Text{ pos_xy,output }); } inline void unselect(Graph_lib::Button&amp; button) // dirty hack to make button not longer preselected after it was pushed { button.hide(); button.show(); } inline std::string make_gui_output(const std::pair&lt;Word, Occurences&gt;&amp; p) { return p.first + " " + std::to_string(p.second); } inline std::string make_gui_output(const Word&amp; p) { return p; } template&lt;typename T&gt; void Word_query_window::init_text_display(const T&amp; container) { int entrys = 0; for (const auto&amp; element : container) { if (entrys == text_display_entrys_per_page) { // for case start display on order entrys = 0; } make_gui_text_output(text_display, make_gui_output(element), Point{ text_display_xy.x, text_display_xy.y + text_display_offset_y * entrys }); ++entrys; } } int word_query_application(); } #endif </code></pre> <p><b>Word_query_window.cpp</b></p> <pre><code>#include "Word_query_window.h" #include "Word_query.h" #include "Cleaned_words.h" namespace word_query_gui { const Point Word_query_window::window_offset_xy{ Point{ 50,50 } }; const Point Word_query_window::text_error_xy{ Point{ window_offset_xy.x + (window_size_x / 100) * 50,window_offset_xy.y } }; // "Window" open file const Point Word_query_window::in_box_filename_xy{ Point{ (window_size_x / 100) * 43,window_offset_xy.y + in_box_filename_size_y } }; const Point Word_query_window::button_open_file_xy{ Point{ window_size_x - button_open_file_size_x - (window_size_x / 100) * 2,in_box_filename_xy.y + in_box_filename_size_y } }; // "Window" show filename const Point Word_query_window::button_change_file_xy{ Point{0,0} }; const Point Word_query_window::text_current_filename_xy{ Point{ button_change_file_xy.x + button_change_file_size_x, button_change_file_xy.y + button_change_file_size_y*9/10 } }; // "Window" select const Point Word_query_window::button_occurences_xy{ Point{0, button_change_file_xy.y + button_change_file_size_y} }; const Point Word_query_window::in_box_occurences_xy{ Point{button_occurences_xy.x + button_occurences_size_x,button_occurences_xy.y} }; const Point Word_query_window::text_occurences_xy{ Point{in_box_occurences_xy.x + in_box_occurences_size_x,in_box_occurences_xy.y + in_box_occurences_size_y*9/10} }; const Point Word_query_window::button_most_frequent_xy{ Point{0, button_occurences_xy.y + button_occurences_size_y} }; const Point Word_query_window::button_longest_xy{ Point{0, button_most_frequent_xy.y + button_most_frequent_size_y} }; const Point Word_query_window::button_shortest_xy{ Point{0, button_longest_xy.y + button_longest_size_y} }; const Point Word_query_window::button_starting_with_xy{ Point{0, button_shortest_xy.y + button_shortest_size_y} }; const Point Word_query_window::in_box_starting_with_xy{ Point{button_starting_with_xy.x + button_starting_with_size_x,button_starting_with_xy.y} }; const Point Word_query_window::button_with_len_xy{ Point{0, button_starting_with_xy.y + button_starting_with_size_y} }; const Point Word_query_window::in_box_with_len_xy{ Point{button_with_len_xy.x + button_with_len_size_x,button_with_len_xy.y} }; const Point Word_query_window::button_show_all_xy{ Point{0, button_with_len_xy.y + button_with_len_size_y} }; // "Window" display order const Point Word_query_window::button_display_back_xy{ Point{ 0 , window_size_y - button_display_back_size_y } }; const Point Word_query_window::button_previous_page_xy{ Point{ window_size_x - button_previous_page_size_x - button_next_page_size_x, window_size_y - button_previous_page_size_y } }; const Point Word_query_window::button_next_page_xy{ Point{ window_size_x - button_next_page_size_x, window_size_y - button_previous_page_size_y } }; const Point Word_query_window::text_display_xy{ Point{0,window_offset_xy.y + text_current_filename_font_size } }; Word_query_window::Word_query_window() :Window{ window_offset_xy, window_size_x, window_size_y, window_label }, // Error text_error{ text_error_xy,"" }, // "Window" open file in_box_filename{ in_box_filename_xy,in_box_filename_size_x,in_box_filename_size_y,in_box_filename_label }, button_open_file{ button_open_file_xy,button_open_file_size_x,button_open_file_size_y,button_open_file_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_open_file_event(); } }, // all following Menus button_change_file{ button_change_file_xy,button_change_file_size_x,button_change_file_size_y,button_change_file_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_change_file_event(); } }, text_current_filename{ text_current_filename_xy,"" }, // "Window" Select Option button_occurences{ button_occurences_xy,button_occurences_size_x,button_occurences_size_y,button_occurences_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_occurences_event(); } }, in_box_occurences{ in_box_occurences_xy,in_box_occurences_size_x,in_box_occurences_size_y,in_box_occurences_label }, text_occurences{ text_occurences_xy,"" }, button_most_frequent{ button_most_frequent_xy,button_most_frequent_size_x,button_most_frequent_size_y,button_most_frequent_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_most_frequent_event(); } }, button_longest{ button_longest_xy,button_longest_size_x,button_longest_size_y,button_longest_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_longest_event(); } }, button_shortest{ button_shortest_xy,button_shortest_size_x,button_shortest_size_y,button_shortest_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_shortest_event(); } }, button_starting_with{ button_starting_with_xy,button_starting_with_size_x,button_starting_with_size_y,button_starting_with_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_starting_with_event(); } }, in_box_starting_with{ in_box_starting_with_xy,in_box_starting_with_size_x,in_box_starting_with_size_y,in_box_starting_with_label }, button_with_len{ button_with_len_xy,button_with_len_size_x,button_with_len_size_y,button_with_len_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_with_len_event(); } }, in_box_with_len{ in_box_with_len_xy,in_box_with_len_size_x,in_box_with_len_size_y,in_box_with_len_label }, button_show_all{ button_show_all_xy,button_show_all_size_x,button_show_all_size_y,button_show_all_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_show_all_event(); } }, // "Window" display button_display_back{ button_display_back_xy,button_display_back_size_x,button_display_back_size_y,button_display_back_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_display_back_event(); } }, button_previous_page{ button_previous_page_xy,button_previous_page_size_x,button_previous_page_size_y,button_previous_page_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_previous_page_event(); } }, button_next_page{ button_next_page_xy,button_next_page_size_x,button_next_page_size_y,button_next_page_label, [](Graph_lib::Address, Graph_lib::Address pw) { Graph_lib::reference_to&lt;Word_query_window&gt;(pw).button_next_page_event(); } } { init_element(*this, text_error, text_error_font_size, text_error_color); init_window_open_file(); init_window_show_filename(); init_window_select(); init_window_display(); show_window_open_file(); } void Word_query_window::init_window_open_file() { init_element(*this, in_box_filename, in_box_filename_text_size, in_box_filename_label_size); init_element(*this, button_open_file); } void Word_query_window::show_window_open_file() { in_box_filename.show(); button_open_file.show(); } void Word_query_window::hide_window_open_file() { in_box_filename.hide(); button_open_file.hide(); } void Word_query_window::init_window_show_filename() { init_element(*this, button_change_file); init_element(*this, text_current_filename, text_current_filename_font_size, text_current_filename_color); } void Word_query_window::show_window_show_filename() { button_change_file.show(); text_current_filename.set_label(current_filename); } void Word_query_window::hide_window_show_filename() { button_change_file.hide(); text_current_filename.set_label(""); } void Word_query_window::init_window_select() { init_element(*this, button_occurences); init_element(*this, in_box_occurences, in_box_occurences_text_size, in_box_occurences_label_size); init_element(*this, text_occurences, text_occurences_font_size, text_occurences_color); init_element(*this, button_most_frequent); init_element(*this, button_longest); init_element(*this, button_shortest); init_element(*this, button_starting_with); init_element(*this, in_box_starting_with, in_box_starting_with_text_size, in_box_starting_with_label_size); init_element(*this, button_with_len); init_element(*this, in_box_with_len, in_box_with_len_text_size, in_box_with_len_label_size); init_element(*this, button_show_all); } void Word_query_window::show_window_select() { button_occurences.show(); in_box_occurences.show(); button_most_frequent.show(); button_longest.show(); button_shortest.show(); button_starting_with.show(); in_box_starting_with.show(); button_with_len.show(); in_box_with_len.show(); button_show_all.show(); } void Word_query_window::hide_window_select() { button_occurences.hide(); in_box_occurences.empty(); in_box_occurences.hide(); text_occurences.set_label(""); button_most_frequent.hide(); button_longest.hide(); button_shortest.hide(); button_starting_with.hide(); in_box_starting_with.empty(); in_box_starting_with.hide(); button_with_len.hide(); in_box_with_len.empty(); in_box_with_len.hide(); button_show_all.hide(); } void Word_query_window::init_window_display() { init_element(*this, button_display_back); init_element(*this, button_previous_page); init_element(*this, button_next_page); } void Word_query_window::show_window_display() { button_display_back.show(); if (page != 0) { button_previous_page.show(); } if (text_display.size() &gt; text_display_entrys_per_page*(page + 1)) { button_next_page.show(); } } void Word_query_window::hide_window_display() { button_display_back.hide(); button_previous_page.hide(); button_next_page.hide(); } void Word_query_window::button_open_file_event() { text_error.set_label(""); current_filename = in_box_filename.get_string(); in_box_filename.empty(); if (current_filename.empty()) { button_open_file.hide(); // to prevent button is still preselected button_open_file.show(); text_error.set_label(text_error_label_invalid); } else if (!file_exists(current_filename)) { button_open_file.hide(); // to prevent button is still preselected button_open_file.show(); text_error.set_label(text_error_label_no_file); } else { words_in_file = cleaned_words::read_words_from_file(current_filename); hide_window_open_file(); show_window_show_filename(); show_window_select(); } } void Word_query_window::button_change_file_event() { hide_window_show_filename(); hide_window_select(); hide_window_display(); show_window_open_file(); } void Word_query_window::button_occurences_event() { unselect(button_occurences); auto search_word = in_box_occurences.get_string(); in_box_occurences.empty(); auto occurences = word_query::occurences_of_word(search_word, words_in_file); text_occurences.set_label(std::to_string(occurences)); } void Word_query_window::button_most_frequent_event() { unselect(button_most_frequent); auto most_frequent_words = word_query::most_frequent_words(words_in_file); init_text_display(most_frequent_words); hide_window_select(); show_window_display(); print_page(); } void Word_query_window::button_longest_event() { unselect(button_longest); auto longest_words = word_query::longest_words(words_in_file); init_text_display(longest_words); hide_window_select(); show_window_display(); print_page(); } void Word_query_window::button_shortest_event() { unselect(button_shortest); auto shortest_words = word_query::shortest_words(words_in_file); init_text_display(shortest_words); hide_window_select(); show_window_display(); print_page(); } void Word_query_window::button_starting_with_event() { unselect(button_starting_with); auto begin_str = in_box_starting_with.get_string(); in_box_starting_with.empty(); auto words_starting_with = word_query::words_starting_with(begin_str, words_in_file); init_text_display(words_starting_with); hide_window_select(); show_window_display(); print_page(); } void Word_query_window::button_with_len_event() { unselect(button_with_len); auto length = in_box_with_len.get_int(); in_box_with_len.empty(); if (length &gt; 0) { auto words_with_len = word_query::words_with_length(length, words_in_file); init_text_display(words_with_len); hide_window_select(); show_window_display(); print_page(); } } void Word_query_window::button_show_all_event() { unselect(button_show_all); init_text_display(words_in_file); hide_window_select(); show_window_display(); print_page(); } void Word_query_window::button_display_back_event() { for (int i = 0; i &lt; text_display.size(); ++i) { detach(text_display[i]); } text_display.~Vector_ref(); page = 0; hide_window_display(); show_window_select(); } void Word_query_window::button_previous_page_event() { --page; hide_window_display(); show_window_display(); print_page(); } void Word_query_window::button_next_page_event() { ++page; hide_window_display(); show_window_display(); print_page(); } void Word_query_window::print_page() { auto entrys_per_page = text_display_entrys_per_page; for (int i = 0; i &lt; text_display.size(); ++i) { detach(text_display[i]); } for (int i = entrys_per_page * page; i &lt; text_display.size() &amp;&amp; i &lt; entrys_per_page + (entrys_per_page*page); ++i) { text_display[i].set_font_size(text_display_font_size); text_display[i].set_color(text_display_color); attach(text_display[i]); } } int word_query_application() { Word_query_window win; return Graph_lib::gui_main(); } } </code></pre> <p><b> main.cpp </b></p> <pre><code>#include "Word_query_window.h" int main() { return word_query_gui::word_query_application(); } </code></pre> <p><b>Cleaned_words.h</b></p> <pre><code>#ifndef CLEAN_FILE290320180702_GUARD #define CLEAN_FILE290320180702_GUARD #include &lt;cctype&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; namespace cleaned_words { using Word = std::string; using Occurences = int; std::map&lt;Word, Occurences&gt; read_words_from_file(const std::string&amp; filename); std::map&lt;Word, Occurences&gt; read_cleaned_words_with_occurence(std::istream&amp; is); bool contains_digits(const Word&amp; word); Word remove_invalid_signs(Word word, const std::string&amp; invalid_signs); inline bool unsigned_isspace(unsigned char c) { return std::isspace(c); } inline bool unsigned_isdigit(unsigned char c) { return std::isdigit(c); } Word remove_whitespace(Word word); Word remove_capital_letters(Word word); std::vector&lt;Word&gt; remove_contractions(const Word&amp; word); void remove_plural(std::map&lt;Word, Occurences&gt;&amp; cleaned_words); void write_cleaned_words_to_file(const std::string&amp; filename, const std::map&lt;Word, Occurences&gt;&amp; cleaned_words); } #endif </code></pre> <p><b> Cleaned_words.cpp </b></p> <pre><code>#include "Cleaned_words.h" #include &lt;algorithm&gt; #include &lt;cctype&gt; #include &lt;filesystem&gt; #include &lt;fstream&gt; namespace cleaned_words { std::map&lt;Word, Occurences&gt; read_words_from_file(const std::string&amp; filename) { std::ifstream ifs{ filename }; if (!ifs) { throw std::runtime_error("void read_words_from_file(const std::string&amp; filename)\nFile could not be opened\n"); } return read_cleaned_words_with_occurence(ifs); } std::map&lt;Word, Occurences&gt; read_cleaned_words_with_occurence(std::istream&amp; is) { std::map&lt;Word, Occurences&gt; cleaned_words; for (Word word; is &gt;&gt; word;) { if (contains_digits(word)) continue; word = remove_invalid_signs(word, R"(°-_^@{}[]&lt;&gt;&amp;.,_()+-=?“”:;/\")"); word = remove_whitespace(word); word = remove_capital_letters(word); if (word.empty()) continue; std::vector&lt;Word&gt; words = remove_contractions(word); for (auto&amp; word : words) { // remove ' after concatenations were run to not erase them to early word = remove_invalid_signs(word, "'"); } for (const auto&amp; word : words) { if (word.size() == 1 &amp;&amp; word != "a" &amp;&amp; word != "i" &amp;&amp; word != "o") continue; ++cleaned_words[word]; } } remove_plural(cleaned_words); return cleaned_words; } bool contains_digits(const Word&amp; word) { if (word.empty()) return false; return std::any_of(word.begin(), word.end(), unsigned_isdigit); } Word remove_invalid_signs(Word word,const std::string&amp; invalid_signs) // replace invalid signs with whitespace { auto is_invalid = [&amp;](char c) { return invalid_signs.find(c) != std::string::npos; }; word.erase(std::remove_if(word.begin(), word.end(), is_invalid), word.end()); return word; } Word remove_whitespace(Word word) { if (word.empty()) return word; word.erase(std::remove_if(word.begin(), word.end(), unsigned_isspace), word.end()); return word; } Word remove_capital_letters(Word word) { for (auto&amp; letter : word) { letter = std::tolower(static_cast&lt;unsigned char&gt;(letter)); } return word; } std::vector&lt;Word&gt; remove_contractions(const Word&amp; word) { const std::map&lt;Word, std::vector&lt;Word&gt;&gt; shorts_and_longs { { "aren't",{ "are","not" }}, { "can't", {"cannot"} }, { "could've",{ "could","have" } }, { "couldn't",{ "could","not" } }, { "daresn't",{ "dare","not" } }, { "dasn't",{ "dare","not" } }, { "didn't",{ "did","not" } }, { "doesn't",{ "does","not" } }, { "don't",{ "do","not" } }, { "e'er",{ "ever" } }, { "everyone's",{ "everyone","is" } }, { "finna",{ "fixing","to" } }, { "gimme",{ "give","me" } }, { "gonna",{ "going","to" } }, { "gon't",{ "go","not" } }, { "gotta",{ "got","to" } }, { "hadn't",{ "had","not" } }, { "hasn't",{ "has","not" } }, { "haven't",{ "have","not" } }, { "he've",{ "he","have" } }, { "how'll",{ "how","will" } }, { "how're",{ "how","are" } }, { "I'm",{ "I","am" } }, { "I'm'a",{ "I","am","about","to" } }, { "I'm'o",{ "I","am","going","to" } }, { "I've",{ "I","have" } }, { "isn't",{ "is","not" } }, { "it'd",{ "it","would" } }, { "let's",{ "let","us" } }, { "ma'am",{ "madam" } }, { "mayn't",{ "may","not" } }, { "may've",{ "may","have" } }, { "mightn't",{ "might","not" } }, { "might've",{ "might","have" } }, { "mustn't",{ "must","not" } }, { "mustn't've",{ "must","not","have" } }, { "must've",{ "must","have" } }, { "needn't",{ "need","not" } }, { "ne'er",{ "never" } }, { "o'clock",{ "of","the","clock" } }, { "o'er",{ "over" } }, { "ol'",{ "old" } }, { "oughtn't",{ "ought","not" } }, { "shan't",{ "shall","not" } }, { "should've",{ "should","have" } }, { "shouldn't",{ "should","not" } }, { "that're",{ "that","are" } }, { "there're",{ "there","are" } }, { "these're",{ "these","are" } }, { "they've",{ "they","have" } }, { "those're",{ "those","are" } }, { "'tis",{ "it","is" } }, { "'twas",{ "it","was" } }, { "wasn't",{ "was","not" } }, { "we'd've",{ "we","would","have" } }, { "we'll",{ "we","will" } }, { "we're",{ "we","are" } }, { "we've",{ "we","have" } }, { "weren't",{ "were","not" } }, { "what'd",{ "what","did" } }, { "what're",{ "what","are" } }, { "what've",{ "what","have" } }, { "where'd",{ "where","did" } }, { "where're",{ "where","are" } }, { "where've",{ "where","have" } }, { "who'd've",{ "who","would","have" } }, { "who're",{ "who","are" } }, { "who've",{ "who","have" } }, { "why'd",{ "why","did" } }, { "why're",{ "why","are" } }, { "won't",{ "will","not" } }, { "would've",{ "would","have" } }, { "wouldn't",{ "would","not" } }, { "y'all",{ "you","all" } }, { "y'all'd've",{ "you","all","would","have" } }, { "yesn't",{ "yes","not" } }, { "you're",{ "you","are" } }, { "you've",{ "you","have" } }, { "whomst'd've",{ "whomst","would","have" } }, { "noun's",{ "noun","is" } }, }; auto it = shorts_and_longs.find(word); if (it == shorts_and_longs.end()) { return std::vector&lt;Word&gt;{word}; } else { return it-&gt;second; } return std::vector&lt;Word&gt;{}; } void remove_plural(std::map&lt;Word, Occurences&gt;&amp; cleaned_words) // assume a plural is a word with an additional s // e.g. ship and ships // if both are present ships gets deleted and ++ship { for (auto it = cleaned_words.begin(); it != cleaned_words.end();) { if(!it-&gt;first.empty() &amp;&amp; it-&gt;first.back() == 's') { Word singular = it-&gt;first; singular.pop_back(); // remove 's' at the end auto it_singular = cleaned_words.find(singular); if (it_singular != cleaned_words.end()) { cleaned_words[it_singular-&gt;first]+= it-&gt;second; it = cleaned_words.erase(it); } else { ++it; } } else { ++it; } } } void write_cleaned_words_to_file(const std::string&amp; filename, const std::map&lt;Word, Occurences&gt;&amp; cleaned_words) { std::ofstream ofs{ filename }; for (const auto&amp; word : cleaned_words) { ofs &lt;&lt; word.first &lt;&lt; " " &lt;&lt; word.second &lt;&lt; '\n'; } } } </code></pre> <p><b>Word_query.h</b></p> <pre><code>#ifndef WORD_QUERY_GUARD_270820181433 #define WORD_QUERY_GUARD_270820181433 #include &lt;map&gt; #include &lt;string&gt; #include &lt;vector&gt; namespace word_query { using Word = std::string; using Occurences = int; using Length = std::map&lt;Word, Occurences&gt;::size_type; int occurences_of_word(const Word&amp; word, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;std::pair&lt;Word, Occurences&gt;&gt; most_frequent_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; longest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; shortest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; words_starting_with(const Word&amp; begin_of_word, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); std::vector&lt;Word&gt; words_with_length(Length length, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences); } #endif </code></pre> <p><b>Word_query.cpp</b></p> <pre><code>#include "Word_query.h" #include &lt;algorithm&gt; namespace word_query { int occurences_of_word(const Word&amp; word, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) //How many occurences of x are there in a file? { auto it = words_with_occurences.find(word); if (it == words_with_occurences.end()) { return 0; } else { return it-&gt;second; } } std::vector&lt;std::pair&lt;Word, Occurences&gt;&gt; most_frequent_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) //Which word occurs most frequently? { using pair_type = std::map&lt;Word, Occurences&gt;::value_type; std::vector&lt;std::pair&lt;Word, Occurences&gt;&gt; words; auto it_begin = words_with_occurences.begin(); auto it_result = words_with_occurences.end(); auto it_last_result = words_with_occurences.end(); for(;;){ it_result = std::max_element( it_begin, words_with_occurences.end(), [](const pair_type a, const pair_type b) { return a.second &lt; b.second; } ); if (it_result == words_with_occurences.end()) { break; } else if (it_last_result == words_with_occurences.end() || it_last_result-&gt;second == it_result-&gt;second) { words.push_back(*it_result); } else { break; } it_last_result = it_result; it_begin = ++it_result; } return words; } std::vector&lt;Word&gt; longest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) //Which is the longest word in the file? { using pair_type = std::map&lt;Word, Occurences&gt;::value_type; std::vector&lt;Word&gt; words; auto it_begin = words_with_occurences.begin(); auto it_result = words_with_occurences.end(); auto it_last_result = words_with_occurences.end(); for (;;) { it_result = std::max_element( it_begin, words_with_occurences.end(), [](const pair_type a, const pair_type b) { return a.first.size() &lt; b.first.size(); } ); if (it_result == words_with_occurences.end()) { break; } else if (it_last_result == words_with_occurences.end() || it_last_result-&gt;first.size() == it_result-&gt;first.size()) { words.push_back(it_result-&gt;first); } else { break; } it_last_result = it_result; it_begin = ++it_result; } return words; } std::vector&lt;Word&gt; shortest_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) //Which is the shortest word in the file? { using pair_type = std::map&lt;Word, Occurences&gt;::value_type; std::vector&lt;Word&gt; words; auto it_begin = words_with_occurences.begin(); auto it_result = words_with_occurences.end(); auto it_last_result = words_with_occurences.end(); for (;;) { it_result = std::min_element( it_begin, words_with_occurences.end(), [](const pair_type a, const pair_type b) { return a.first.size() &lt; b.first.size(); } ); if (it_result == words_with_occurences.end()) { break; } else if (it_last_result == words_with_occurences.end() || it_last_result-&gt;first.size() == it_result-&gt;first.size()) { words.push_back(it_result-&gt;first); } else { break; } it_last_result = it_result; it_begin = ++it_result; } return words; } std::vector&lt;Word&gt; words_starting_with(const Word&amp; begin_of_word, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) { std::vector&lt;Word&gt; matched_words; for (const auto&amp; word : words_with_occurences) { if (word.first.substr(0, begin_of_word.size()) == begin_of_word) { matched_words.push_back(word.first); } } return matched_words; } std::vector&lt;Word&gt; words_with_length(Length length, const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences) //all words with n letters { std::vector&lt;Word&gt; words; for (const auto&amp; element : words_with_occurences) { if (element.first.size() == length) words.push_back(element.first); } return words; } } </code></pre> <p><b>Point.h</b></p> <pre><code>// This is a GUI support code to the chapters 12-16 of the book // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #ifndef POINT_GUARD #define POINT_GUARD struct Point { int x, y; Point(int xx, int yy) : x(xx), y(yy) { } Point() :x(0), y(0) { } }; inline bool operator==(Point a, Point b) { return a.x==b.x &amp;&amp; a.y==b.y; } inline bool operator!=(Point a, Point b) { return !(a==b); } #endif // POINT_GUARD </code></pre> <p><b>GUI.h</b></p> <pre><code>// // This is a GUI support code to the chapters 12-16 of the book // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #ifndef GUI_GUARD #define GUI_GUARD #include "Window.h" #include "Graph.h" #include &lt;string&gt; namespace Graph_lib { //------------------------------------------------------------------------------ typedef void* Address; // Address is a synonym for void* typedef void(*Callback)(Address, Address); // FLTK's required function type for all callbacks //------------------------------------------------------------------------------ template&lt;class W&gt; W&amp; reference_to(Address pw) // treat an address as a reference to a W { return *static_cast&lt;W*&gt;(pw); } //------------------------------------------------------------------------------ class Widget { // Widget is a handle to an Fl_widget - it is *not* an Fl_widget // We try to keep our interface classes at arm's length from FLTK public: Widget(Point xy, int w, int h, const std::string&amp; s, Callback cb) : loc(xy), width(w), height(h), label(s), do_it(cb) {} virtual void move(int dx, int dy) { hide(); pw-&gt;position(loc.x += dx, loc.y += dy); show(); } virtual void hide() { pw-&gt;hide(); } virtual void show() { pw-&gt;show(); } virtual void attach(Graph_lib::Window&amp;) = 0; Point loc; int width; int height; std::string label; Callback do_it; virtual ~Widget() { } protected: Graph_lib::Window* own; // every Widget belongs to a Window Fl_Widget* pw; // connection to the FLTK Widget private: Widget &amp; operator=(const Widget&amp;); // don't copy Widgets Widget(const Widget&amp;); }; //------------------------------------------------------------------------------ struct Button : Widget { Button(Point xy, int w, int h, const std::string&amp; label, Callback cb) : Widget(xy, w, h, label, cb) {} void attach(Graph_lib::Window&amp;); }; //------------------------------------------------------------------------------ struct In_box : Widget { In_box(Point xy, int w, int h, const std::string&amp; s) :Widget(xy, w, h, s, 0) { } int get_int(); std::string get_string(); void attach(Graph_lib::Window&amp; win); // Extensions not provided by Stroustrup: void set_text_size(int size); void set_label_size(int size); void empty(); // emptys the input field }; //------------------------------------------------------------------------------ struct Out_box : Widget { Out_box(Point xy, int w, int h, const std::string&amp; s) :Widget(xy, w, h, s, 0) { } void put(int); void put(const std::string&amp;); void attach(Graph_lib::Window&amp; win); // Extensions not provided by Stroustrup: void set_text_size(int size); void set_label_size(int size); }; //------------------------------------------------------------------------------ struct Menu : Widget { enum Kind { horizontal, vertical }; Menu(Point xy, int w, int h, Kind kk, const std::string&amp; label) : Widget(xy, w, h, label, 0), k(kk), offset(0) { } Vector_ref&lt;Button&gt; selection; Kind k; int offset; int attach(Button&amp; b); // Menu does not delete &amp;b int attach(Button* p); // Menu deletes p void show() // show all buttons { for (auto i = 0; i&lt;selection.size(); ++i) selection[i].show(); } void hide() // hide all buttons { for (auto i = 0; i&lt;selection.size(); ++i) selection[i].hide(); } void move(int dx, int dy) // move all buttons { for (auto i = 0; i&lt;selection.size(); ++i) selection[i].move(dx, dy); } void attach(Graph_lib::Window&amp; win) // attach all buttons { for (int i = 0; i &lt; selection.size(); ++i) { win.attach(selection[i]); } own = &amp;win; } }; //------------------------------------------------------------------------------ } // of namespace Graph_lib #endif // GUI_GUARD </code></pre> <p><b> GUI.cpp </b></p> <pre><code>#include "GUI.h" #include &lt;sstream&gt; using namespace Graph_lib; void Button::attach(Graph_lib::Window&amp; win) { pw = new Fl_Button(loc.x, loc.y, width, height, label.c_str()); pw-&gt;callback(reinterpret_cast&lt;Fl_Callback*&gt;(do_it), &amp;win); // pass the window own = &amp;win; } int In_box::get_int() { Fl_Input&amp; pi = reference_to&lt;Fl_Input&gt;(pw); // return atoi(pi.value()); const char* p = pi.value(); if (!isdigit(p[0])) return -999999; return atoi(p); } std::string In_box::get_string() { Fl_Input&amp; pi = reference_to&lt;Fl_Input&gt;(pw); return std::string(pi.value()); } void In_box::attach(Graph_lib::Window&amp; win) { pw = new Fl_Input(loc.x, loc.y, width, height, label.c_str()); own = &amp;win; } void In_box::set_text_size(int size) { reference_to&lt;Fl_Input&gt;(pw).textsize(size); } void In_box::set_label_size(int size) { reference_to&lt;Fl_Input&gt;(pw).labelsize(size); } void In_box::empty() // emptys the input field { reference_to&lt;Fl_Input&gt;(pw).value(""); } void Out_box::put(int i) { Fl_Output&amp; po = reference_to&lt;Fl_Output&gt;(pw); std::stringstream ss; ss &lt;&lt; i; po.value(ss.str().c_str()); } void Out_box::put(const std::string&amp; s) { reference_to&lt;Fl_Output&gt;(pw).value(s.c_str()); } void Out_box::attach(Graph_lib::Window&amp; win) { pw = new Fl_Output(loc.x, loc.y, width, height, label.c_str()); own = &amp;win; } void Out_box::set_text_size(int size) { reference_to&lt;Fl_Output&gt;(pw).textsize(size); } void Out_box::set_label_size(int size) { reference_to&lt;Fl_Output&gt;(pw).labelsize(size); } int Menu::attach(Button&amp; b) { b.width = width; b.height = height; switch (k) { case horizontal: b.loc = Point(loc.x + offset, loc.y); offset += b.width; break; case vertical: b.loc = Point(loc.x, loc.y + offset); offset += b.height; break; } selection.push_back(&amp;b); return int(selection.size() - 1); } int Menu::attach(Button* p) { // owned.push_back(p); return attach(*p); } </code></pre> <p><b> Window.h </b></p> <pre><code>#include "FL/fl_draw.H" #include "FL/Enumerations.H" #include "Fl/Fl_JPEG_Image.H" #include "Fl/Fl_GIF_Image.H" #include "Point.h" #include &lt;string&gt; #include &lt;vector&gt; namespace Graph_lib { class Shape; // "forward declare" Shape class Widget; class Window : public Fl_Window { public: Window(int w, int h, const std::string&amp; title); // let the system pick the location Window(Point xy, int w, int h, const std::string&amp; title); // top left corner in xy virtual ~Window() { } int x_max() const { return w; } int y_max() const { return h; } void resize(int ww, int hh) { w = ww, h = hh; size(ww, hh); } void set_label(const std::string&amp; s) { label(s.c_str()); } void attach(Shape&amp; s); void attach(Widget&amp; w); void detach(Shape&amp; s); // remove s from shapes void detach(Widget&amp; w); // remove w from window (deactivate callbacks) void put_on_top(Shape&amp; p); // put p on top of other shapes protected: void draw(); private: std::vector&lt;Shape*&gt; shapes; // shapes attached to window int w, h; // window size void init(); }; int gui_main(); // invoke GUI library's main event loop inline int x_max() { return Fl::w(); } // width of screen in pixels inline int y_max() { return Fl::h(); } // height of screen in pixels } #endif </code></pre> <p><b> Window.cpp </b></p> <pre><code>#include "Window.h" #include "Graph.h" #include "GUI.h" namespace Graph_lib { Window::Window(int ww, int hh, const std::string&amp; title) :Fl_Window(ww, hh, title.c_str()), w(ww), h(hh) { init(); } Window::Window(Point xy, int ww, int hh, const std::string&amp; title) : Fl_Window(xy.x, xy.y, ww, hh, title.c_str()), w(ww), h(hh) { init(); } void Window::init() { resizable(this); show(); } //---------------------------------------------------- void Window::draw() { Fl_Window::draw(); for (unsigned int i = 0; i&lt;shapes.size(); ++i) shapes[i]-&gt;draw(); } void Window::attach(Widget&amp; w) { begin(); // FTLK: begin attaching new Fl_Wigets to this window w.attach(*this); // let the Widget create its Fl_Wigits end(); // FTLK: stop attaching new Fl_Wigets to this window } void Window::detach(Widget&amp; b) { b.hide(); } void Window::attach(Shape&amp; s) { shapes.push_back(&amp;s); // s.attached = this; } void Window::detach(Shape&amp; s) { for (unsigned int i = shapes.size(); 0&lt;i; --i) // guess last attached will be first released if (shapes[i - 1] == &amp;s) shapes.erase(shapes.begin() + (i - 1));//&amp;shapes[i-1]); } void Window::put_on_top(Shape&amp; p) { for (auto i = 0; i&lt;shapes.size(); ++i) { if (&amp;p == shapes[i]) { for (++i; i&lt;shapes.size(); ++i) shapes[i - 1] = shapes[i]; shapes[shapes.size() - 1] = &amp;p; return; } } } int gui_main() { return Fl::run(); } } // Graph </code></pre> <p><b> Graph.h/cpp </b></p> <p>Due to limit of the characters per post i can't post Graph.h / cpp complete. You can find it here if necessary to look into: <a href="http://www.stroustrup.com/Programming/PPP2code/" rel="nofollow noreferrer">http://www.stroustrup.com/Programming/PPP2code/</a></p>
[]
[ { "body": "<h1>Classes</h1>\n\n<p>There are a few things you can do to simplify:</p>\n\n<pre><code>std::vector&lt;std::pair&lt;Word, Occurences&gt;&gt; most_frequent_words(const std::map&lt;Word, Occurences&gt;&amp; words_with_occurences);\nstd::vector&lt;Word&gt; longest_words(const std::map&lt;Word, Occurence...
{ "AcceptedAnswerId": "202997", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T17:35:30.360", "Id": "202988", "Score": "3", "Tags": [ "c++", "c++17", "fltk" ], "Title": "Cleaning a file / Word Query GUI (FLTK)" }
202988
<p>Asynchronous programming is tricky enough already, and VBA doesn't make life any easier. I wanted to create some basic functionality to allow async processes to mark completion without having to implement any complicated interfaces.</p> <p>The basic idea was to raise a regular stream of events, or <code>Ticks</code>, and then to check the value of a supplied variable each time. These are performed in the <em>Tick</em> method of a main class:</p> <h3>Class: <code>asyncTimer</code></h3> <pre><code>Option Explicit Implements ITicker 'to allow tick method to remain hidden Public Event Tick() Public Event Timeout() Public Event Complete() Private Const waitIndefinitely As Double = -1 Private Type tTimer tickFrequency As Double 'in seconds startTime As Double endTime As Double neverTimeout As Boolean conditionAddress As LongPtr End Type Private this As tTimer Public Sub Await(ByRef processComplete As Boolean, Optional ByVal tickFrequency As Double = 0.5, Optional ByVal maxWait As Double = 10) this.conditionAddress = VarPtr(processComplete) If maxWait = waitIndefinitely Then this.neverTimeout = True ElseIf maxWait &gt;= 0 Then this.startTime = timer this.endTime = this.startTime + maxWait Else Err.Raise 5, , "Max wait must be positive or -1 (for no timeout)" End If startTicking tickFrequency, Me End Sub Private Sub ITicker_Tick() If Peek(this.conditionAddress, vbBoolean) Then 'check if val has changed stopTicking RaiseEvent Complete ElseIf timer &gt; this.endTime Then stopTicking RaiseEvent Timeout Else RaiseEvent Tick End If End Sub Private Sub Class_Terminate() stopTicking End Sub </code></pre> <p>The class implements an interface in order to keep its methods secret.</p> <h3>Class: <code>ITicker</code></h3> <pre><code>Public Sub Tick() End Sub </code></pre> <p>A regular stream of events (well callbacks really) are what drives everything in its asynchronous glory. These are generated with a Windows API Timer to schedule regular function calls:</p> <h3>Module: <code>TickGenerator</code></h3> <pre><code>Option Explicit Private Declare Function SetTimer Lib "user32" ( _ ByVal HWnd As Long, ByVal nIDEvent As Long, _ ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long Private Declare Function KillTimer Lib "user32" ( _ ByVal HWnd As Long, ByVal nIDEvent As Long) As Long Private Type tGenerator caller As ITicker timerID As Long End Type Private this As tGenerator Public Sub startTicking(ByVal tickFrequency As Double, ByVal caller As ITicker) Set this.caller = caller this.timerID = SetTimer(0, 0, tickFrequency * 1000, AddressOf Tick) End Sub Private Sub Tick(ByVal HWnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long) this.caller.Tick End Sub Public Sub stopTicking() On Error Resume Next KillTimer 0, this.timerID End Sub </code></pre> <p>The whole setup runs until a certain condition is met, or the class raches a timeout value. The idea was to pass the condition <code>ByRef</code> which means if the caller code changed its value to <code>True</code> (marking the async task complete), the timer code would be aware of it. However a bit of trickery is required to monitor a value passed to a class <code>ByRef</code>, involving checking the memory at the address of the variable. A utility module holds the generic method (as described <a href="https://stackoverflow.com/a/52139564/6609896">here</a>)</p> <h3>Module: <code>asyncMethods</code></h3> <pre><code>Option Explicit Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _ Any, source As Any, ByVal bytes As Long) ' read a value of any type from memory Public Function Peek(ByVal address As Long, ByVal ValueType As VbVarType) As Variant Select Case ValueType Case vbByte Dim valueB As Byte CopyMemory valueB, ByVal address, 1 Peek = valueB Case vbInteger Dim valueI As Integer CopyMemory valueI, ByVal address, 2 Peek = valueI Case vbBoolean Dim valueBool As Boolean CopyMemory valueBool, ByVal address, 2 Peek = valueBool Case vbLong Dim valueL As Long CopyMemory valueL, ByVal address, 4 Peek = valueL Case vbSingle Dim valueS As Single CopyMemory valueS, ByVal address, 4 Peek = valueS Case vbDouble Dim valueD As Double CopyMemory valueD, ByVal address, 8 Peek = valueD Case vbCurrency Dim valueC As Currency CopyMemory valueC, ByVal address, 8 Peek = valueC Case vbDate Dim valueDate As Date CopyMemory valueDate, ByVal address, 8 Peek = valueDate Case vbVariant ' in this case we don't need an intermediate variable CopyMemory Peek, ByVal address, 16 Case Else Err.Raise 1001, , "Unsupported data type" End Select End Function </code></pre> <h1>What I'm after</h1> <p>I'd like a bit of feedback on a few areas in particular:</p> <ul> <li>Use of Api functions. They seem to be leading to a few crashes!</li> <li>Use of the <code>ITicker</code> interface. I've never used interfaces to <em>hide</em> methods before</li> <li>User interface; I've tried to keep it very simple with friendly VBA Events, but is this useful?</li> <li>Errors; how should I be raising them. This is a very simple application so I haven't done anything fancy</li> </ul> <h2>Test code</h2> <p>One example of using this is in monitoring user interaction such as worksheet selection changes</p> <h3>Sheet1:</h3> <pre><code>Option Explicit Private WithEvents testclass As asyncTimer Private countReached As Boolean Sub runtests() Set testclass = New asyncTimer countReached = False Range("A1") = 1 Range("B1") = 1 testclass.Await countReached, 0.5, 5 End Sub Private Sub testclass_Complete() MsgBox "done" End Sub Private Sub testclass_Tick() Range("B1") = Range("B1") + 1 End Sub Private Sub testclass_Timeout() MsgBox "timeout" End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) Range("A1") = Range("A1") + 1 countReached = Range("A1") &gt; 10 Range("A2") = countReached End Sub </code></pre> <p>Here the value of <code>A1</code> shows the number of selection change events, <code>A2</code> whether the condition (as seen by the timer) is True or False, and <code>B1</code> shows the number of elapsed Ticks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T21:06:54.337", "Id": "391241", "Score": "1", "body": "Doesn't that make VBA go into `[Running]` mode several times a second? If that's the case, that could be just bad if not worse than running synchronously because you're forcing t...
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T19:27:26.400", "Id": "202992", "Score": "3", "Tags": [ "vba", "asynchronous" ], "Title": "Await in... VBA?" }
202992
<p><a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow noreferrer">Heap's algorithm</a> is an algorithm to generate all permutations of a given array. It</p> <blockquote> <p>... generates each permutation from the previous one by interchanging a single pair of elements; the other n−2 elements are not disturbed.</p> </blockquote> <p>Here is my attempt to implement this algorithm in Swift 4 as a <code>Sequence</code>, so that all permutations of an array can be enumerated with <code>for .. in</code> loops and related techniques:</p> <pre><code>/* * A sequence of all permutations of a given array. Based on the * non-recursive version of Heap's algorithm as described in * https://en.wikipedia.org/wiki/Heap%27s_algorithm */ struct HeapPermutationSequence&lt;Element&gt;: Sequence, IteratorProtocol { private var current: [Element] private var c: [Int] private var i = 0 private var firstIteration = true init(elements: [Element]) { self.current = elements self.c = Array(repeating: 0, count: elements.count) } mutating func next() -&gt; [Element]? { if firstIteration { firstIteration = false } else { while i &lt; c.count { if c[i] &lt; i { if i % 2 == 0 { current.swapAt(0, i) } else { current.swapAt(c[i], i) } c[i] += 1 i = 0 break } else { c[i] = 0 i += 1 } } } return i &lt; c.count ? current : nil } } </code></pre> <p>Example usage:</p> <pre><code>for p in HeapPermutationSequence(elements: [1, 2, 3]) { print(p, terminator: ", ") } print() // Output: // [1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1], </code></pre> <p>Several techniques from @Hamish's answer <a href="https://codereview.stackexchange.com/questions/158799/sequence-based-enumeration-of-permutations-in-lexicographic-order/159375#159375">Sequence-based enumeration of permutations in lexicographic order</a> could be applied here as well to improve the performance:</p> <ul> <li>Avoid the cost of copy-on-write by <em>not</em> mutating the <code>current</code> array after it is returned as the next element.</li> <li>Have a single exit point in the <code>next()</code> method.</li> </ul> <p><strong>Benchmark:</strong></p> <pre><code>let N = 10 var count = 0 let start = Date() for _ in HeapPermutationSequence(elements: Array(1...N)) { count += 1 } let end = Date() print(count, end.timeIntervalSince(start)) </code></pre> <p>which takes about 0.03 seconds (on a 1.2 GHz Intel Core m5 MacBook, compiled in Release mode).</p> <p>All feedback is welcome, such as (but of course not restricted to):</p> <ul> <li>Performance improvements.</li> <li>Better variable names (<code>c</code> and <code>i</code> are simply copied from the Wikipedia pseudo-code).</li> <li>Simplifying the code, or making it better readable/understandable.</li> </ul>
[]
[ { "body": "<p><code>HeapPermutationSequence</code> computes all permutations of a given <em>array.</em> \nA common Swift idiom is not to operate on concrete types, but on <em>protocols.</em>\nIn this case, we need a mutable <em>collection</em> type which allows <em>efficient random access</em> to its elements. ...
{ "AcceptedAnswerId": "207182", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T19:40:08.647", "Id": "202994", "Score": "3", "Tags": [ "performance", "swift", "combinatorics" ], "Title": "Sequence-based enumeration of permutations with Heap's algorithm" }
202994
<p><strong>What is the expected behavior?</strong></p> <ol> <li><p>If there is a file in the state <code>(file != null)</code>, then <code>startUploadImage(file)</code> should be executed, followed by <code>startUpdateEvent(eventId, state)</code>.</p></li> <li><p>If there is no file <code>(file === null)</code> then only the <code>startUpdateEvent(eventId, state)</code> should be executed.</p></li> </ol> <p><strong>What is the problem I am encountering right now?</strong></p> <p>Currently I am struggling with writing a good piece of code, especially when it comes to conditional promises. In the code below you can see that I use some <code>if</code> / <code>else</code> (nested) methodology which leads to tremendously long code.</p> <pre><code>onSubmit = event =&gt; { event.preventDefault(); if ( (this.state, eventNameRegex.test(this.state.event_name) &amp;&amp; eventDescriptionRegex.test(this.state.event_description) &amp;&amp; priceRegex.test(this.state.ticket_price) &amp;&amp; eventDateRegex.test(this.state.event_date)) ) { // check if image changed or not then continue this.props.handleLoading(true); if (this.state.file != null) { startUploadImage(this.state.file).then(response =&gt; { this.setState({ event_image: response.data }); return this.props .startUpdateEvent(this.props.event.id, this.state) .then(() =&gt; { this.props.handleLoading(false); this.props.history.push("/events"); }) .catch(error =&gt; { this.props.handleLoading(false); this.setState({ error: error.status, errorMessage: error.data }); }); }); } else { return this.props .startUpdateEvent(this.props.event.id, this.state) .then(() =&gt; { this.props.handleLoading(false); this.props.history.push("/events"); }) .catch(error =&gt; { console.log("error"); this.props.handleLoading(false); this.setState({ error: error.status, errorMessage: error.data }); }); } } else { this.setState({ error: 400, errorMessage: "Please fill in all required fields with correct data. Please try again." }); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T22:50:59.113", "Id": "391254", "Score": "0", "body": "I'd recommend the book \"Clean Code\" by Robert C. Martin https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM" }, { "ContentLicense": "C...
[ { "body": "<p>I know nothing of react.js, so please forgive me if I missed something, but in a JS way I'd do it that way :</p>\n\n<pre><code>onSubmit = event =&gt; {\n event.preventDefault();\n //start with a dedicated part for testing values\n let fieldError=\"\";\n if(!eventNameReg...
{ "AcceptedAnswerId": "203020", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T22:07:55.323", "Id": "202999", "Score": "1", "Tags": [ "javascript", "react.js", "promise" ], "Title": "On form submission, upload an image if there is one, then start update event" }
202999
<p>This is my solution to the ECOO 2015 contest, problem 1, Fractorials. I'd appreciate any advice to improve readability, style, organization, etc.</p> <p><a href="https://i.stack.imgur.com/O1S1e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O1S1e.png" alt="enter image description here"></a></p> <pre><code>def main(): number = int(input()) fractorial = {} for i in range(2, number + 1): prime_factorization = prime_factor(i) update_fractorial(prime_factorization, fractorial) print(compute_fractorial_value(fractorial)) def prime_factor(number): primes = [2, 3, 5, 7, 11, 13, 17, 19] dict = {} i = 0 while i &lt; len(primes): p = 0 while number % primes[i] == 0: number = number // primes[i] p += 1 if p != 0: dict[primes[i]] = p i += 1 return dict def update_fractorial(prime_factorization, fractorial): for key in prime_factorization: if key in fractorial: if prime_factorization[key] &gt; fractorial[key]: fractorial[key] = prime_factorization[key] else: fractorial[key] = prime_factorization[key] # Or should I replace the if/else statements with: # # if key in fractorial: # if prime_factorization[key] &lt; fractorial[key]: # break # # fractorial[key] = prime_factorization[key] # # since it is shorter. def compute_fractorial_value(fractorial): value = 1 for key in fractorial: value *= key ** fractorial[key] return value main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T04:15:34.800", "Id": "391263", "Score": "3", "body": "So basically you've to find the lowest common multiple!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T08:04:07.957", "Id": "391271", "Sc...
[ { "body": "<p>Overall the code is quite easy to read, but it is more complicated than it needs to be.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> fractorial = {}\n for i in range(2, number + 1):\n prime_factorization = prime_factor(i)\n update_fractorial(prime_factorization, fractorial)\n\n ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T23:57:08.213", "Id": "203003", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "ECOO contest 2015: Problem 1" }
203003
<p>I created a <code>ContactsList</code> class in Java that holds <code>Person</code> objects. I consider this is a side project for my GitHub profile. Any kind of suggestion is appreciated.</p> <p><strong><code>Person</code> Class</strong></p> <pre><code>package contactsList; public class Person { private static final String FAVOURITE = "★"; private String firstName; private String lastName; private String fullName; private String phone; private String dob = ""; private String email = ""; private String favourite = ""; public Person(String firstName, String lastName, String phone) { setFirstName(firstName); setLastName(lastName); setFullName(this.getFirstName().concat(" ").concat(this.getLastName())); setPhone(phone); } public Person(String firstName, String lastName, String phone, String dob, String email) { this(firstName, lastName, phone, dob, email, false); } public Person(String firstName, String lastName, String phone, String dob, String email, boolean favourite) { this(firstName, lastName, phone); this.setDob(dob); this.setEmail(email); this.setFavourite(favourite); } public boolean getFavourite() { if(this.favourite.equals(FAVOURITE)) return true; else return false; } public void setFavourite(boolean favourite) { if(favourite) this.favourite = FAVOURITE; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", phone='" + phone + '\'' + ", dob='" + dob + '\'' + ", email='" + email + '\'' + ", favourite='" + favourite + '\'' + '}'; } } </code></pre> <p><strong><code>ContactsList</code> Class</strong></p> <pre><code>package contactsList; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import static java.lang.System.out; public class ContactsList implements Iterable&lt;Person&gt; { private List&lt;Person&gt; personList = new ArrayList &lt;&gt;(); private Person person; public ContactsList() {} public ContactsList(Person person) { this(person, false); } public ContactsList(Person person, boolean favourite) { this.person = person; this.person.setFavourite(favourite); personList.add(this.person); } public void addContacts(Person person) { personList.add(person); } public void addContacts(String firstName, String lastName, String phone) { this.addContacts(firstName, lastName, phone, "", "", false); } public void addContacts(String firstName, String lastName, String phone, String dob, String email) { this.addContacts(firstName, lastName, phone, dob, email, false); } public void addContacts(String firstName, String lastName, String phone, String dob, String email, boolean favourite) { this.person = new Person(firstName, lastName, phone, dob, email, favourite); this.personList.add(this.person); } public int getTotalContacts() { return personList.size(); } public boolean exists(Person person) { if(personList.contains(person)) return true; else return false; } public boolean exists(String fullName) { for(Person person : personList) { if(person.getFullName().equals(fullName)) return true; } return false; } public void removeContacts(Person person) { if(personList.remove(person)) return; } public void removeContacts(String fullName) { int index = -1; for(Person person : personList) { if(person.getFullName().equals(fullName)) index = personList.indexOf(person); } if(index &gt;= 0) personList.remove(index); } public void displayFavouriteContacts() { for(Person person : personList) { if(person.getFavourite()) out.println(person); } } public void sortBy(String by) { final String f = "f"; final String l = "l"; if(by.equalsIgnoreCase(f)) Collections.sort(personList, Comparator.comparing(Person::getFirstName)); else if(by.equalsIgnoreCase(l)) Collections.sort(personList, Comparator.comparing(Person::getLastName)); else Collections.sort(personList, Comparator.comparing(Person::getFullName)); } public List&lt;String&gt; getPhoneNumber(String fullName) { List&lt;String&gt; phoneList = new ArrayList &lt;&gt;(); for(Person person : personList) { if(person.getFullName().equals(fullName)) phoneList.add(person.getPhone()); } return phoneList; } public List&lt;String&gt; getPhoneByFirstName(String firstName) { List&lt;String&gt; phoneList = new ArrayList &lt;&gt;(); for(Person person : personList) { if(person.getFirstName().equals(firstName)) phoneList.add(person.getPhone()); } return phoneList; } public List&lt;String&gt; getPhoneByLastName(String lastName) { List&lt;String&gt; phoneList = new ArrayList &lt;&gt;(); for(Person person : personList) { if(person.getLastName().equals(lastName)) phoneList.add(person.getPhone()); } return phoneList; } public List&lt;Person&gt; getAllContacts() { List&lt;Person&gt; tempList = new ArrayList &lt;&gt;(); for(Person person : personList) tempList.add(person); return tempList; } @Override public String toString() { String longString = ""; for(Person person : personList) longString = longString.concat(person.toString().concat("\n")); return longString; } @Override public Iterator iterator() { return new ContactsListIterator(); } private class ContactsListIterator implements Iterator&lt;Person&gt; { int counter = 0; @Override public boolean hasNext() { return (counter &lt; personList.size()); } @Override public Person next() { return personList.get(counter++); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T05:47:52.773", "Id": "391265", "Score": "1", "body": "In your `Person` class, your favorite variable is a String, but you are using it as a boolean everywhere else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate":...
[ { "body": "<p>First to understand the purpose, contact-list is like a contact directory, where the application holding this list, should be able add, remove and query contact easily from other service-layers, Based on this proceeding to improvement of the code,</p>\n\n<p>Person.class has many type of constructo...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T01:21:59.773", "Id": "203004", "Score": "0", "Tags": [ "java", "performance", "object-oriented", "array", "sorting" ], "Title": "ContactsList implementation in Java" }
203004
<p>I have written a Reddit bot in Python (code below). Open to any improvements, especially on efficiency, as I am using PythonAnywhere to run it.</p> <p>The main function is to scan posts in reddit and when certain phrases are found in the text private message the reddit user. Furthermore, the reddit user shouldn't be messaged twice.</p> <pre><code>#------------------------------------------------------------------------------ def Github_text(): print("Open textfile...") data = urllib.request.urlopen("####").read() text = re.search("&lt;StartText&gt;(.+?)&lt;EndText&gt;", str(data)) if text: private_message_text = text.group(1) private_message_text = private_message_text.replace(r"\\n","\n") print("Text is ready!") return private_message_text def bot_login(): print("Login...") reddit = praw.Reddit(client_id="####", client_secret="####", password="####", user_agent="####", username="####") print("Login succesfull!") return reddit def run_bot(reddit): now = datetime.datetime.now() print("Start iteration..." + now.strftime("%Y-%m-%d %H:%M:%S")) for submission in reddit.subreddit("all").new(limit=1000): if any(sentence in submission.selftext for sentence in check_sentences) \ and submission.author not in users_messaged and not submission.stickied and submission.is_self: print(submission.selftext) if len(users_messaged) &gt; 50: del users_messaged[0] users_messaged.append(submission.author) else: users_messaged.append(submission.author) reddit.redditor(str(submission.author)).message(private_message_title, private_message_text) print("Message send to:" + str(submission.author)) time.sleep(120) #------------------------------------------------------------------------------ check_sentences = ["####", "####", "####", "####", "####", "####", "####", "####"] users_messaged = [] private_message_title = "####" private_message_text = Github_text() reddit = bot_login() print("Start loop!") while True: run_bot(reddit) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T10:15:25.027", "Id": "391281", "Score": "6", "body": "Hi! This code present issues with its indentation and can not work in its current shape. Can you [edit] your question to reflect the actual indentation of your code, thank." },...
[ { "body": "<h1>Pass values as parameters for modularity</h1>\n<p>You can make your code a lot more modular if you pass values to functions as parameters instead of hardcoding values in the function itself.</p>\n<p>Let's change the <code>bot_login()</code> function to this.</p>\n<pre><code>def bot_login(client):...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T09:44:20.113", "Id": "203017", "Score": "6", "Tags": [ "python", "python-3.x", "reddit" ], "Title": "A suicide prevention Redditbot" }
203017
<p>I just started learning Elixir and stumbled upon <a href="https://codegolf.stackexchange.com/q/171555/59487">this challenge</a> over on <a href="https://codegolf.stackexchange.com">Programming Puzzles &amp; Code Golf</a>. It is a well-suited task for beginners, so I chose to give it a go (to be clear, <em>give it a go</em> means <em>solve it normally</em>, not <a href="https://en.wikipedia.org/wiki/Code_golf" rel="nofollow noreferrer"><em>golfing</em></a> it). To keep this question self-contained, here is the task – citing the linked post:</p> <blockquote> <p>For a given positive integer \$n\$:</p> <ol> <li>Repeat the following until \$n &lt; 10\$ (until \$n\$ contains one digit).</li> <li>Extract the last digit.</li> <li>If the extracted digit is even (including 0) multiply the rest of the integer by \$2\$ and add \$1\$ ( \$2n+1\$ ). Then go back to <code>step 1</code> else move to <code>step 4</code>.</li> <li>Divide the rest of the integer with the extracted digit (integer / digit) and add the remainder (integer % digit), that is your new \$n\$.</li> </ol> </blockquote> <p>For example, \$61407\$ gives \$5\$ when ran through this mechanism. I've come up with the following code:</p> <pre class="lang-elixir prettyprint-override"><code>defmodule ExtractAndDivide do def extract_and_divide(x) do if x &lt; 10 do x else head = div x, 10 tail = rem x, 10 case rem tail, 2 do 0 -&gt; head * 2 + 1 |&gt; extract_and_divide 1 -&gt; div(head, tail) + rem(head, tail) |&gt; extract_and_divide end end end end </code></pre> <p>I'm seeking general advice, but mainly focusing on the following:</p> <ul> <li>Naming and Syntax better practices (usage of parenthesises, variable names etc.)</li> <li>Usage of <code>|&gt;</code> (pipe) in this context. Would you ever see it used the way I did it in production code? Should I switch to "normal" notation instead?</li> <li>Less verbose or more elegant way to avoid the seemingly unaesthetic <code>if x &lt; 10 do x ... else ... end</code> structure, perhaps using <code>case</code> would be better here?</li> <li>Is recursion the way to go? Should I stick to it or are there better, equivalent methods?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-18T21:30:28.550", "Id": "469004", "Score": "0", "body": "Since both clauses in your case end with the same pipe you could pipe the case. Have the 0 case just return head*2+1 and put the pipe after the case's end." } ]
[ { "body": "<p>I do not have much to say about the pipe operator. It looks fine to me, although maybe some else has something to say...</p>\n\n<p>As for the <code>if-else</code> clause, you can use <a href=\"https://elixir-lang.org/getting-started/case-cond-and-if.html#cond\" rel=\"nofollow noreferrer\"><code>co...
{ "AcceptedAnswerId": "203056", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T13:54:11.173", "Id": "203025", "Score": "1", "Tags": [ "recursion", "integer", "elixir" ], "Title": "Extract and divide algorithm implementation in Elixir" }
203025