body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>The code creates a table and adds rows and columns. </p>
<ul>
<li>Does it make sense to write the code like this? </li>
<li>Would you design it differently? </li>
<li>Is there a better OOP approach to this?</li>
</ul>
<pre><code>class Table
attr_reader :grid
def initialize(rows: , columns:)
@grid = construct(rows, columns)
end
def construct(rows, columns)
raise 'arguments must be arrays' unless rows.is_a?(Array) && columns.is_a?(Array)
table = []
rows = [] if rows.nil?
rows.each do |row|
table << columns.map do |c| c end
end
table
end
end
</code></pre>
<p>Here are the specs which describe what it is doing: </p>
<pre><code>require 'spec_helper'
require_relative '..\test'
RSpec.describe Table do
it 'is empty' do
table = Table.new(rows: [], columns: [])
expect(table.grid).to eq []
end
it 'raises if no array is given' do
expect {
Table.new(rows: [], columns: 1) }.to raise_error RuntimeError
expect {
Table.new(rows: 1, columns:[]) }.to raise_error RuntimeError
end
it 'has several rows and columns' do
row = double('row')
column = double('column')
col = Column.new.value = 14
table = Table.new(rows: [1, 3, 3], columns: [1, col])
expect(table.grid).to eq [
[1, 2],
[1, 2],
[1, 2]
]
end
end
</code></pre>
| [] | [
{
"body": "<h2>Refactored Code</h2>\n\n<p>This is a possible way to refactor the code to meet the style guidelines of <a href=\"https://rubystyle.guide/\" rel=\"nofollow noreferrer\">Ruby</a> using <a href=\"https://github.com/rubocop-hq/rubocop\" rel=\"nofollow noreferrer\">Rubocop</a>.</p>\n\n<pre><code># frozen_string_literal: true\n\n# A simple table with rows and cols\nclass Table\n attr_reader :grid\n\n def initialize(rows:, columns:)\n @grid = construct(rows, columns)\n end\n\n def construct(rows, columns)\n unless rows.is_a?(Array) && columns.is_a?(Array)\n raise 'arguments must be arrays'\n end\n\n table = []\n rows = [] if rows.nil?\n rows.each do |_row|\n table << columns.map { |c| c }\n end\n table\n end\nend\n</code></pre>\n\n<hr>\n\n<h2>Style Considerations</h2>\n\n<p>A guard clause should be appended wih an empty line. Also, since the line is over 80 characters, split it up in multi-line.</p>\n\n<blockquote>\n<pre><code>raise 'arguments must be arrays' unless rows.is_a?(Array) && columns.is_a?(Array)\ntable = []\n</code></pre>\n</blockquote>\n\n<pre><code>unless rows.is_a?(Array) && columns.is_a?(Array)\n raise 'arguments must be arrays'\nend\n\ntable = []\n</code></pre>\n\n<p>You have an unused block argument <code>row</code> and the map should be rewritten using <code>{..}</code>.</p>\n\n<blockquote>\n<pre><code>rows.each do |row|\n table << columns.map do |c| c end\nend\n</code></pre>\n</blockquote>\n\n<pre><code>rows.each do |_row|\n table << columns.map { |c| c }\nend\n</code></pre>\n\n<hr>\n\n<h2>General Guidelines and Conventions</h2>\n\n<p>The tool also complained about the following guidelines.</p>\n\n<ul>\n<li>use 2 instead of 4 white spaces for indentation</li>\n<li>remove any trailing white space</li>\n<li>remove space before comma</li>\n<li>add a frozen string literal comment <a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/FrozenStringLiteralComment\" rel=\"nofollow noreferrer\">justification</a></li>\n<li>add top level class documentation comment</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-21T09:51:45.810",
"Id": "224604",
"ParentId": "223834",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T21:36:12.437",
"Id": "223834",
"Score": "2",
"Tags": [
"beginner",
"object-oriented",
"ruby",
"unit-testing"
],
"Title": "Table class to fill array structure with values"
} | 223834 |
<p>We have an existing situation in an MVC ASP.NET app where it's possible for two threads to come back asynchronously, one from an external api(the payment gateway) and one from within the browser for each cart in an online shop. Only one should be able to run some further code, but they can come back almost simultaneously. We have something in place that kind of works, but is not working correctly all the time. The following code has been suggested to replace it.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Threading;
namespace semaphoreTest.Semaphore
{
public class NxSemaphore : SemaphoreSlim
{
public NxSemaphore() : base(1, 1){}
public DateTime Created { get; set; }
public DateTime LastUsed { get; set; }
public string Key { get; set; }
}
public static class AppSemaphoreDict
{
private static Dictionary<string, NxSemaphore> _cartSemaphores = new Dictionary<string, NxSemaphore>();
private static object _lockObj = new object();
public static NxSemaphore GetForCart(string nxID)
{
lock (_lockObj)
{
NxSemaphore semaphore;
if (_cartSemaphores.TryGetValue(nxID, out semaphore))
{
semaphore.LastUsed = DateTime.Now;
}
else
{
semaphore = new NxSemaphore()
{
Created = DateTime.Now,
Key = nxID,
LastUsed = DateTime.Now
};
_cartSemaphores.Add(semaphore.Key, semaphore);
}
return semaphore;
}
}
}
}
</code></pre>
<p>The idea is that a semaphore should be created for each cart (which has a unique id - NxId) and would be used in a manner below</p>
<pre><code>public async Task<string> DoStuffDict()
{
NxSemaphore semaphore = null;
try
{
//get a random cart id for testing
string NxGuid = SempahoreTest.Models.RandomNxGuid.GetRestrictedNxGuid(300);
semaphore = AppSemaphoreDict.GetForCart(NxGuid);
await semaphore.WaitAsync();
//Get some stuff from an api
NxApi api = new NxApi(NxRequestContext);
var data = await api.GetSomeStuff;
//write some stuff to the database
using (DataContext dbContext = new DataContext())
{
SemaphoreTest test = new SemaphoreTest();
test.Key = semaphore.Key;
test.DateTimeCreated = semaphore.Created;
test.DateTimeLastUsed = semaphore.LastUsed;
dbContext.SemaphoreTest.InsertOnSubmit(test);
dbContext.SubmitChanges();
}
return "All Good";
}
catch (Exception ex)
{
return ex.ToString();
}
finally
{
if (semaphore != null)
{
semaphore.Release();
}
};
}
</code></pre>
<p>I have run the above code using a WebSurge with a bunch of threads and it seems to pick up the correct existing SemaphoreSlim class for the same cart id. Obviously there needs to be some clean up run to remove old SemaphoreSlim instances from the in memory Dictionary which I have not added as yet. Not sure about the best way to go about this - any ideas ? Also, thoughts on this generally as a pattern ? Are there some glaring mistakes in there and a better method to employ ?</p>
<p><strong>Edit</strong>
There will potentially be a number of calls to this function with different cart ids. The same id can be used multiple times (but usually at least twice).The line below is just simulating passing an id to the function. It is using a fixed list of 300 keys and grabbing one each time. When I hit this with a load tester using 20 threads, it picks up the correct SempahoreSlim each time for the same id.</p>
<pre><code>SempahoreTest.Models.RandomNxGuid.GetRestrictedNxGuid(300);
</code></pre>
<p>In practice, the cart key will be passed in to the function.Currently there may be a hundred or so sessions at any point in time, but they won't all be trying to hit the code at the same time, unless everyone is paying for their cart simultaneously. The crucial part is that for each different cart id, there may be two different threads hitting the function and only one of them should run the task. I also omitted in the code above a check that is made to see if the other thread has done the job (and saved a record in the database), in which case the second thread coming through does not need to do anything. If we just have one SemaphoreSlim for all carts, my worry was that it would block the others too much as the api and database calls are quite heavy and may take up around 500ms to complete.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T04:31:59.560",
"Id": "434039",
"Score": "2",
"body": "How will this semaphore dic be used? Will there be many calls to it, with many different keys? Will the same key be used regularly? This question lacks crucial context in order to decide a strategy for memory management."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:50:49.620",
"Id": "434094",
"Score": "0",
"body": "I think you are creating an overly complex solution. You can probably get away with just using one `SemaphoreSlim` instance. Then measure how long average/max lock contention time is and decide if you require the additional complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T20:43:10.370",
"Id": "434151",
"Score": "0",
"body": "Do you have some mechanism or plan for removing semaphores for old carts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:51:49.427",
"Id": "434188",
"Score": "0",
"body": "@VisualMelon Not at the moment. Still trying to decide on the best approach to this.Currently it stores the last datetime it was used, so i was looking at a process to remove all items that are older than x minutes"
}
] | [
{
"body": "<h3>Review</h3>\n\n<p>I would say, KISS (keep it stupid simple). Try going for a single lock and benchmark both normal expected thoughput and peek scenarios. If you would manage with this setup, you're done.</p>\n\n<p>In case you would require a mutex for every unique key, using a lock to get that key is good practice. You have optimized lookup (tryget vs contains and get) <code>if (_cartSemaphores.TryGetValue(nxID, out semaphore))</code> and all actions inside this lock are fast.</p>\n\n<p>However, as mentioned in the comments, your cache might grow over time, and you'll eventually reach a point most keys would become lingering. You would need to think about how to perform some garbage collection on this cache. This can be tricky. Check out this post <a href=\"https://codereview.stackexchange.com/questions/223150/force-concurrentdictionary-in-a-singleton-registry-to-collect-removed-items-spac/223160#223160\">force-concurrentdictionary-in-a-singleton-registry-to-collect-removed-items-spac</a> to figure out C# collections are optimized for performance, not for memory management when cleaning up lingering items. So at some point, you would probably want to clear the cache completely, and re-assign a new instance of the cache. This could be very expensive, but required when your server runs 24/7 and has lots of new and stale semaphores.</p>\n\n<p>One possible way of cleaning the cache is to have a scheduled task that periodically (you should figure out a good cycle window) clears the cache.</p>\n\n<p><sub> in pseudo code (comments) </sub></p>\n\n<pre><code> lock (_lockObj)\n {\n // acquire the semaphore for each key in the dictionary\n // clear the dictionary\n // assign a new empty dictionary\n }\n</code></pre>\n\n<p>One other thing, you are assigning a slightly different update time than creation time:</p>\n\n<blockquote>\n<pre><code>semaphore = new NxSemaphore()\n{\n Created = DateTime.Now,\n Key = nxID,\n LastUsed = DateTime.Now\n};\n</code></pre>\n</blockquote>\n\n<p>This probably doesn't have a major impact, but it would better to have the initial state consistent.</p>\n\n<pre><code>public NxSemaphore()\n{\n Created = DateTime.Now;\n LastUsed = Created;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T19:20:42.573",
"Id": "226942",
"ParentId": "223842",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "226942",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T03:32:02.163",
"Id": "223842",
"Score": "3",
"Tags": [
"c#",
"thread-safety",
"asp.net-mvc"
],
"Title": "Use SemaphoreSlim to control access to a resource"
} | 223842 |
<p>I'm designing a scraping application using python, requests and BeautifulSoup4.</p>
<p>I decided to divide the logic into two classes:</p>
<ul>
<li><code>Spider</code> : gets the base url containing a list of job offers and logs them into a SQL table <code>logs</code> .</li>
<li><code>Extractor</code>: it pulls the urls of job offers' posts from the <code>logs</code> table and it dumps them into json files (one by one).</li>
</ul>
<p>I want to know how bad is the application design and how to improve it. and I'll appreciate some additional tips on how to improve my design skills (books, articles to read or courses to buy or follow + good python code to read ...)</p>
<p>Here is the <code>Spider</code>,</p>
<pre class="lang-py prettyprint-override"><code>import json
import os
import sqlite3
from bs4 import BeautifulSoup, UnicodeDammit
import requests
class Spider:
def __init__(self, main_url='https://www.rekrute.com/offres-emploi-metiers-de-l-it.html'):
self.main_url = main_url # first url to crowl
self.next_url = None # next url to crowl
self.links = [] # list of post links
self.connection = sqlite3.connect('log.db') # connect to database
# set self.response to main_url if it's the first round else set it to next_url
def init_response(self):
cookies = {
'PHPSESSID': 'my_cookie_here',
'PopUpHP': '1',
}
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
if self.next_url is None:
self.response = requests.get(self.main_url, cookies=cookies, headers=headers)
else:
headers['Referer'] = 'https://www.rekrute.com/offres-emploi-metiers-de-l-it.html'
self.response = requests.post(self.next_url, cookies=cookies, headers=headers)
# extract the list of links from the page
def parse_response(self):
soup = BeautifulSoup(self.response.text, 'html.parser')
sections = soup.find_all('li',class_='post-id')
for s in sections:
self.links.append(
{
'id': s['id'],
'title': UnicodeDammit(s.h2.text.strip()).unicode_markup,
'link': s.h2.a['href'],
'status': 'pending'
}
)
last_id = sections[-1].get('id')
base_url = 'https://www.rekrute.com/rekrute/UserJobOffer/GetJobOfferPagination/last_id/'
self.next_url = base_url + last_id
# save the posts into the database
def save_logs(self):
c = self.connection.cursor()
for l in self.links:
c.execute("INSERT INTO logs Values(?, ?, ?, ?)", ( l['id'], l['title'], l['link'], l['status']))
"""
with open('logs.csv', 'a') as logf:
if os.stat('logs.csv').st_size == 0:
logf.write(','.join(self.links[0].keys())+'\n')
for l in self.links:
logf.write(','.join(l.values())+'\n')
self.links = []
"""
def crawl(self):
# the crawling trigger
i = 0
print("Starting Crawling")
while True:
print("crowling {}".format(self.next_url))
self.init_response()
if self.response.text.strip() == '':
print("Nothing to Crawl! Bye!")
break
self.parse_response()
self.save_logs()
print("round {} is done starting round {}:".format(i,i+1))
i += 1
self.connection.commit()
self.connection.close()
</code></pre>
<p>Here is the Extractor</p>
<pre class="lang-py prettyprint-override"><code>import json
import re
import sqlite3
from bs4 import BeautifulSoup
import requests
class Extractor:
def __init__(self):
self.base_url = 'https://www.rekrute.com/'
self.post_urls = []
self.connection = sqlite3.connect('log.db')
# load urls from database
def load_urls(self, limit):
c = self.connection.cursor()
c.execute("SELECT * FROM logs WHERE status='pending' LIMIT ?", (limit,))
return c.fetchall()
# get the page by url, and parse it (returns dict)
def parse(self, post_id, post_url):
urll = self.base_url+post_url
response = requests.get(urll)
soup = BeautifulSoup(response.text, 'html.parser')
infos = soup.find('div', class_='info').text
infos = re.sub('\n\n','\n',re.sub('\r\n','',infos))
infos = infos.split('\n')
post_dict = {
'id' : post_id
}
for i in infos:
if i != '':
item = i.strip().split(':')
post_dict[item[0].strip()] = item[1].strip()
return post_dict
# save post_dict in a json file
def to_json(self, post):
filename = 'posts/post_'+ str(post.get('id'))+'.json'
with open(filename, 'w') as ff:
json.dump(post, ff, ensure_ascii=False)
# get all urls and parse the pages one by one, and save them to json files.
def start_parsing(self):
posts = self.load_urls(100)
for p in posts:
tmp_post = self.extract(p[0], p[2])
self.to_json(tmp_post)
c = self.connection.cursor()
c.execute("UPDATE logs SET status=? WHERE post_id=?", ('saved',p[0]))
self.connection.commit()
self.connection.close()
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T05:00:22.923",
"Id": "223844",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Scraping a hiring website using python's requests and BeautifulSoup"
} | 223844 |
<p>This is a code challenge, from Codewars, the details of the specific challenge in depth can be found here: <a href="https://www.codewars.com/kata/magnet-particules-in-boxes/javascript" rel="nofollow noreferrer">https://www.codewars.com/kata/magnet-particules-in-boxes/javascript</a>. </p>
<p>The summary of it though is a function which gives a sum of particles in a set of boxes given a number of rows and a number of columns to work with. You are given a specific function that calculates the number of particles in the box based off of the specific box that is being calculated. Here is the equation:</p>
<p><span class="math-container">$$ v(k,n) = \frac{1}{k(n + 1)^{2k}} $$</span></p>
<p><span class="math-container">$$
doubles (k_{max}, n_{max}) = \sum_{k=1}^{k_{max}} \sum_{n=1}^{n_{max}} v(k,n)
$$</span></p>
<p>Here is the function I came up with:</p>
<pre><code>function doubles(maxk, maxn) {
let total = 0
for(let k = 1; k <= maxk; k++){
const twoK = 2*k
for(let n = 1; n <= maxn; n++){
total += 1/(k*Math.pow(n+1, twoK))
}
}
return total
}
</code></pre>
<p>My function does the job perfectly, and comparing it to other responses marked as 'best practices' it is very similar. But I would like to know if anyone sees obvious ways to improve my function, or I would really love to see something that can improve the time complexity of the function, if that is possible.</p>
| [] | [
{
"body": "<p>Inside the inner loop, <span class=\"math-container\">\\$1/k\\$</span> is a constant term. So you could extract that multiplication from the inner loop, and apply it on the computed subtotal. This won't change the order of complexity though.</p>\n\n<p>I was wondering if there is a closed form for computing the sum of reciprocal powers (to replace the summing and thereby speed things up), but I couldn't find.</p>\n\n<p>I was also wondering if you inverted the direction of computations to sum by columns instead of summing by rows, would there be a closed form to replace the summing, but I couldn't find that either.</p>\n\n<p>Other than some clever math optimizations, the computation by rows or columns could run in parallel, but the input parameters would have to be large enough to be worth the overhead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T13:44:55.887",
"Id": "224563",
"ParentId": "223845",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T05:25:37.410",
"Id": "223845",
"Score": "3",
"Tags": [
"javascript",
"performance",
"programming-challenge",
"iteration"
],
"Title": "Find a Sum of Particles in A Set of Boxes Given a Number of Rows and Columns"
} | 223845 |
<p>I needed to synchronise several processes, so I developed this <code>ipn::Notifier</code> class that uses a mutex+condition variable stored in shared memory to notify all processes. </p>
<p>The <code>ControlBlock</code> structure is stored in shared memory and holds the sync elements as well as a counter of clients.</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef CONTROLBLOCK_H
#define CONTROLBLOCK_H
#include <cstdint>
#include <pthread.h>
namespace ipn
{
struct ControlBlock
{
pthread_mutex_t mutex;
pthread_cond_t cond;
uint8_t clients = 0;
};
}
#endif // CONTROLBLOCK_H
</code></pre>
<p>Next is the <code>Notifier</code> class. Processes that should be in sync should join named <em>regions</em> using the <code>attach</code> method. In order to be notified, they should setup a callback using the <code>setCallback</code> method. Here's the header:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef IPN_NOTIFIER_H
#define IPN_NOTIFIER_H
#include "ControlBlock.h"
#include <string>
#include <atomic>
#include <thread>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace ipn {
/**
* The Notifier class works as a inter-process notifier, allowing separate processes to be notified at the same time of
* an event. Processes that may want to be notified should attach to a named "region" and set up a callback to be
* notified of the event.
*/
class Notifier {
public:
/// Default constructor does nothing
Notifier() = default;
/// Makes sure the process detaches from the shared resources
~Notifier();
// Non-copyable
Notifier(const Notifier &) = delete;
Notifier & operator=(const Notifier &) = delete;
/// Attaches to a named shared region, creating (or opening) the shared memory area and initialising the synchronization elements
void attach(const std::string &region);
/// Detaches from the shared region
void detach();
/// Sends a notification to all attached processes
void notify();
/// Sets the callback to be called when the process is notified
void setCallback(const std::function<void()> &callback);
private:
/// Waits in a separate thread for notifications
void waitingLoop();
/// Waits for a period of time on the condition variable. Returns true if the condition variable was signaled, false otherwise.
bool wait();
/// Name of the shared memory region
std::string mRegion;
/// Data stored in the shared memory that contains the mutex and the condition variables
ControlBlock * mControlBlock = nullptr;
/// Shared memory manager
std::shared_ptr<boost::interprocess::managed_shared_memory> mShared;
/// Flag that indicates whether we're attached to a shared memory segment
std::atomic_bool mAttached = ATOMIC_VAR_INIT(false);
/// Thread that waits for the notifications
std::thread mThread;
/// Pointer to the function that should be called when a notification arrives
std::function<void()> mCallback;
};
}
#endif //IPN_NOTIFIER_H
</code></pre>
<p>And here's the definition:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Notifier.h"
#include <functional>
#include <iostream>
#include <stdexcept>
namespace bi = boost::interprocess;
void ipn::Notifier::attach(const std::string & region)
{
if (mAttached)
{
throw std::runtime_error("Already attached");
}
mRegion = region;
// Create the shared memory segment
mShared.reset(new bi::managed_shared_memory { bi::open_or_create, region.c_str(), 4096 });
// Get the stored control block
mControlBlock = mShared->find_or_construct<ControlBlock>(std::string("control_" + region).c_str())();
// The first client should initialise the mutex and condition varaibles
if (mControlBlock->clients == 0)
{
std::cerr << "Initialising elements in shared memory" << std::endl;
/* set mControlBlock->mutex shared between processes */
pthread_mutexattr_t mattr;
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&mControlBlock->mutex, &mattr) != 0)
{
perror("Mutex init failed");
throw std::runtime_error("Mutex init failed");
}
pthread_mutexattr_destroy(&mattr);
/* set condition shared between processes */
pthread_condattr_t cattr;
pthread_condattr_init(&cattr);
pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
if (pthread_cond_init(&mControlBlock->cond, &cattr) != 0)
{
perror("Condvar init failed");
throw std::runtime_error("Condvar init failed");
}
pthread_condattr_destroy(&cattr);
}
else
{
std::cerr << "Elements already initialised" << std::endl;
}
mControlBlock->clients++;
mAttached = true;
mThread = std::thread(std::bind(&Notifier::waitingLoop, this));
}
void ipn::Notifier::waitingLoop()
{
while (mAttached)
{
std::cerr << "Attached, locking mutex..." << std::endl;
pthread_mutex_lock(&mControlBlock->mutex);
std::cerr << "Locked mutex, starting to wait..." << std::endl;
while (mAttached)
{
if (wait())
{
std::cerr << "Breaking..." << std::endl;
break;
}
}
pthread_mutex_unlock(&mControlBlock->mutex);
// If still attached after breaking previous loop then there was a proper signal and not a detach
if (mAttached)
{
std::cerr << "Signaled!" << std::endl;
if (mCallback)
mCallback();
}
// Trigger callback if defined
}
}
void ipn::Notifier::notify()
{
pthread_mutex_lock(&mControlBlock->mutex);
pthread_cond_broadcast(&mControlBlock->cond);
pthread_mutex_unlock(&mControlBlock->mutex);
}
void ipn::Notifier::detach()
{
if (!mAttached)
return;
std::cerr << "Setting flag..." << std::endl;
mAttached = false;
std::cerr << "Flag set, joining thread..." << std::endl;
mThread.join();
std::cerr << "Thread joined" << std::endl;
mControlBlock->clients--;
if (mControlBlock->clients == 0)
{
pthread_mutex_unlock(&mControlBlock->mutex);
pthread_mutex_destroy(&mControlBlock->mutex);
pthread_cond_destroy(&mControlBlock->cond);
bi::shared_memory_object::remove(mRegion.c_str());
}
}
bool ipn::Notifier::wait()
{
timespec time;
timespec_get(&time, TIME_UTC);
// Wait 50ms
time.tv_nsec += 50000000;
time.tv_sec += time.tv_nsec / 1000000000;
time.tv_nsec %= 1000000000;
int n = pthread_cond_timedwait(&mControlBlock->cond, &mControlBlock->mutex, &time);
if (n == 0)
{
std::cerr << "Notified" << std::endl;
return true;
}
else
{
if (n == ETIMEDOUT)
{
std::cerr << "Timed out" << std::endl;
return false;
}
else if (n == EINVAL)
{
std::cerr << "Invalid value specified";
return false;
}
else
{
std::cerr << "Other error" << std::endl;
return false;
}
}
}
ipn::Notifier::~Notifier()
{
detach();
}
void ipn::Notifier::setCallback(const std::function<void()> & callback)
{
mCallback = callback;
}
</code></pre>
<p>Here's a test program, that you can run many times. If you press "n" in any of the processes, every other process should run the callback and print a message.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Notifier.h"
int main()
{
ipn::Notifier notifier;
notifier.attach("Region");
notifier.setCallback([](){ std::cout << "I'M THE CALLBACK" << std::endl; });
std::string option;
std::cout << "Waiting for option..." << std::endl;
while(std::cin >> option)
{
std::cout << "Chosen option: " << option << std::endl;
if (option == "n")
{
notifier.notify();
}
else if (option == "x")
{
break;
}
std::cout << "Waiting for option..." << std::endl;
}
std::cout << "Dettaching..." << std::endl;
notifier.detach();
return 0;
}
</code></pre>
<p>I first designed this using boost's <code>named_tuple</code> and <code>named_condition</code>, which worked great in Debian 7.x, but my target environment uses Rhel 7.3 and Boost 1.53 and somehow it didn't work there, so I had to stick to standard mutex and condition variables in shared memory.</p>
<p>I'd really appreciate if you could comment on:</p>
<ul>
<li>Caveats and race conditions I may not be aware of.</li>
<li>General coding style.</li>
<li>Logging strategies: currently I'm using lousy <code>std::cerr</code> during development but I'd rather use something else (or nothing at all).</li>
</ul>
<p>Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T07:01:24.197",
"Id": "434050",
"Score": "2",
"body": "Welcome to Code Review! What version of the C++ standard are you aiming for? From what I can see it should be at least C++11. Please add the according tag on top of the current ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T07:07:34.540",
"Id": "434053",
"Score": "2",
"body": "Do you have any sample/test program that exercises this library? If so, that would be useful for reviewers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T08:35:37.837",
"Id": "434059",
"Score": "1",
"body": "@AlexV I'm aiming at C++11, I've added the tag. Toby I've added a simple program to test the library. Thanks for the comments."
}
] | [
{
"body": "<p>You have a rather long if-else ladder. I think this can be simpler written as:</p>\n<pre><code> switch (n) {\n case 0:\n std::cerr << "Notified" << std::endl;\n return true;\n case ETIMEDOUT:\n std::cerr << "Timed out" << std::endl;\n return false;\n case EINVAL:\n std::cerr << "Invalid value specified";\n return false;\n default:\n std::cerr << "Other error" << std::endl;\n return false;\n }\n</code></pre>\n<p>The n==0 case (original code) is also at the different level of nesting that is confusing, even if it seems to me that the nesting does not have effect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T21:42:18.187",
"Id": "248973",
"ParentId": "223848",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T06:40:05.673",
"Id": "223848",
"Score": "6",
"Tags": [
"c++",
"c++11",
"pthreads",
"ipc"
],
"Title": "C++ simple inter-process notification system"
} | 223848 |
<p>Would there be a more clear/efficient way to write</p>
<pre><code>public function getModelName()
{
return substr(strtolower(substr(strrchr(preg_replace('/(?<!\ )[A-Z]/', '_$0', __CLASS__), "\\"), 1)), 1);
}
</code></pre>
<p>for example:</p>
<p><strong>__CLASS__</strong>: Namespace\To\SettingOption</p>
<p><strong>Output</strong>: setting_option</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T08:13:40.563",
"Id": "434058",
"Score": "0",
"body": "Your question is a bit terse, and given your example the code doesn't work. Could you give a real example? What does `__CLASS__` contain and what is the output? What if there's no namespace?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T09:14:27.690",
"Id": "434060",
"Score": "0",
"body": "@KIKOSoftware `__CLASS__` would contain the name of the class, as this method is in a trait, it would depend on the class it's used in. The class is always in a namespace, so accounting for it not being in one is not important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T10:21:54.893",
"Id": "434067",
"Score": "0",
"body": "Can you provide a correct class name example? In other words: What will be contained in `__CLASS__`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T10:58:48.647",
"Id": "434068",
"Score": "0",
"body": "@KIKOSoftware edited"
}
] | [
{
"body": "<p>There's actually not much I can do when it comes to efficiency, but it is clear that the code is not very readable. All these nested function calls make it very hard to track what's going on.</p>\n\n<p>My suggestion would be to split this single method into multiple methods. This is a very normal strategy in programming. A method should only do one thing, and do it well. This is also called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>, and although this is usually applied to classes it can apply to methods as well. </p>\n\n<p>Your code could look something like this:</p>\n\n<pre><code>public function getClassName()\n{\n // return class name only, without namespace, which must be present\n return substr(__CLASS__, strrpos(__CLASS__, '\\\\') + 1);\n}\n\npublic function getClassNameWords()\n{\n // return an array of the words in the camel case class name\n return preg_split('/(?=[A-Z])/', lcfirst($this->getClassName()));\n}\n\npublic function getModelName()\n{\n // return the name for the model as defined by the class name\n return strtolower(implode('_', $this->getClassNameWords()));\n}\n</code></pre>\n\n<p>Each of these three functions is clearly shorter and easier to read. The extra methods allow you to reuse the code they contain. The code is no longer locked up in a single method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:21:46.150",
"Id": "223866",
"ParentId": "223849",
"Score": "1"
}
},
{
"body": "<p>I won't go down the rabbit hole of debating what constitutes a \"<a href=\"https://stackoverflow.com/q/32731717/2943403\">valid Pascal/Studly-cased string</a>\" but there is <a href=\"https://stackoverflow.com/q/1993721/2943403\">plenty of debate here</a> if you want to read about fringe cases (like acronyms and multibyte characters). I will merely cross my fingers and hope that your project's naming convention does not wonder into tricky territory. Either way, the post-namespace substring portion of my pattern can be easily amended to suit your input and desired output.</p>\n\n<p>Effectively, you need to:</p>\n\n<ol>\n<li>Consume the namespace portion and omit it. My pattern matches zero or more sequences of <code>not \\\\</code> then <code>\\\\</code>.</li>\n<li>Then it matches a single uppercase letter followed by zero or more lowercase letters. (not very tricky)</li>\n<li>Inside of the custom callback function, I check if there is a namespace substring matched (<code>$m[1]</code>), if not I prepend an underscore.</li>\n<li>Finally, I convert the first letter of the matched classname word to lowercase and return the built string as the replacement value.</li>\n</ol>\n\n<p>PHP (<a href=\"https://3v4l.org/MHSrU\" rel=\"nofollow noreferrer\">Demo</a>) (<a href=\"https://regex101.com/r/VTiOGY/1\" rel=\"nofollow noreferrer\">Regex Pattern Demo</a>)</p>\n\n<pre><code>const testNamespacedClasses = [\n \"Namespace\\To\\SettingOption\",\n \"I\\Was\\Born\\InTheUSAIwas\",\n \"Something\\Onething\"\n];\n\nfunction testSnakeCasedModelNames() {\n foreach (testNamespacedClasses as $class) {\n echo \"$class => \";\n echo preg_replace_callback(\n '~([^\\\\\\\\]*\\\\\\\\)*([A-Z][a-z]*)~',\n function($m) {\n return ($m[1] ? '' : '_') . lcfirst($m[2]); \n },\n $class\n );\n echo \"\\n---\\n\";\n }\n}\n\necho testSnakeCasedModelNames();\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Namespace\\To\\SettingOption => setting_option\n---\nI\\Was\\Born\\InTheUSAIwas => in_the_u_s_a_iwas\n---\nSomething\\Onething => onething\n---\n</code></pre>\n\n<p>Alternative snippets might look like: <a href=\"https://3v4l.org/lXdbd\" rel=\"nofollow noreferrer\">https://3v4l.org/lXdbd</a> or <a href=\"https://3v4l.org/MMFni\" rel=\"nofollow noreferrer\">https://3v4l.org/MMFni</a> or <a href=\"https://3v4l.org/ITjTk\" rel=\"nofollow noreferrer\">https://3v4l.org/ITjTk</a></p>\n\n<p>To implement in your project:</p>\n\n<pre><code>public function getSnakeCasedModelName()\n{\n return preg_replace_callback(\n '~([^\\\\\\\\]*\\\\\\\\)*([A-Z][a-z]*)~',\n function($m) {\n return ($m[1] ? '' : '_') . lcfirst($m[2]); \n },\n __CLASS__\n );\n}\n</code></pre>\n\n<p>I considered using the <a href=\"https://stackoverflow.com/a/51286810/2943403\"><code>\\G</code> metacharacter</a> on this answer, but felt it overcomplicated the pattern and the desired result can be obtained without it</p>\n\n<p>When comparing KIKO's answer versus mine, consider if \"abstraction\" is beneficial to your project. It is completely plausible that it is. On the other hand if you don't want to break the string manipulation process into its most basic parts, you can avoid the overhead of subsequent method calls. <a href=\"https://medium.com/@thisdotmedia/the-cost-of-premature-abstraction-b5d71ffd6400\" rel=\"nofollow noreferrer\">\"Premature Abstraction\" is a thing.</a> It's an academic point, but you should consider the impacts of either approach on maintainability, testing, overhead, code size, readability, etc. I don't mean to say that there is anything wrong with KIKO's advice -- \"single responsibility\" is an important principle in writing professional-grade code.</p>\n\n<p>Finally, because I am using a <code>preg_</code> call to reformat the class string anyhow, I prefer to also use it to to remove the namespace. There are some <a href=\"https://stackoverflow.com/a/27457689/2943403\">benchmarks provided here</a> which include a Reflection-based technique, but those benchmarks are only half of the job that you require.</p>\n\n<p>If you are using <code>__CLASS__</code> then I assume that you can also use <code>__NAMESPACE__</code> which means that perhaps <code>str_replace(__NAMESPACE__ . '\\\\', __CLASS__)</code> can be used to trim the namespace substring from the class. Since you are using Laravel, you can use <a href=\"https://stackoverflow.com/a/26296283/2943403\">its helper function</a>: <code>$baseClass = class_basename($className);</code> ...then you only need to convert StudlyCase to snake_case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:07:29.927",
"Id": "223907",
"ParentId": "223849",
"Score": "1"
}
},
{
"body": "<h3>Efficiency & Clarity</h3>\n\n<p>For <strong>efficiency</strong> the only \"flaws\" (it's more for \"good habit\" than noticeable optimization - it doesn't matter for such a small strings) would be the order of functions (regexp is costly so it should be called on string processed as far as possible) and regexp itself which could be optimized for least amount of steps.</p>\n\n<p>When it comes to <strong>clarity</strong> it's enough to split those function calls into named variables, so you could later read what steps you're doing here. It can be later split into separate methods, but there's no need since method stays small (style) and <em>IS</em> responsible for one thing (see below).</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function getModelName(): string\n{\n $className = substr(strrchr(__CLASS__, \"\\\\\"), 1);\n $camelCase = lcfirst($className);\n $snakeCase = strtolower(preg_replace('/[A-Z]/', '_$0', $camelCase));\n\n return $snakeCase; //seems redundant, but don't be afraid to do that\n //when it helps in readability\n //it's more important than that 1ms/req\n}\n</code></pre>\n\n<h3>Things to consider</h3>\n\n<ul>\n<li>This method may be static - it doesn't rely on object fields, but refers to the\nclass, and static scope denotes that. It still might be called using instance\nidentifier: <code>$object::getModelName();</code></li>\n<li>You're dealing with meta programming\nmagic here - unless it's not some dev tool your first thought should\nbe <strong>don't do it</strong></li>\n<li><strong>SRP</strong> that @KIKOSoftware brought up is often misunderstood (vaugue naming),\nand it's not about doing one thing inside the class/method (that's hardly\npossible), but upon calling a method from the outside - responsibility towards\nclient that expects one concrete thing (coherent group of things). You're\nbreaking this principle anyway since your \"model name\" is not even an <em>instance\nmethod</em> and it represents some meta data next to, I persume, other methods of\nthe class (it's not important when this class is only a data structure, but you\nwill be coupled to convention here instead of abstraction).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T04:12:35.263",
"Id": "224000",
"ParentId": "223849",
"Score": "1"
}
},
{
"body": "<p>You tagged <code>laravel</code>, so this answer assumes you are using Laravel.</p>\n\n<p>Laravel has two built in helper functions that will help you do this. <code>class_basename()</code> will return the name of the class with the namespace stripped off, and <code>snake_case()</code> will convert a string to snake case.</p>\n\n<p>Combine them, and you get:</p>\n\n<pre><code>public function getModelName()\n{\n return snake_case(class_basename(__CLASS__));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T11:30:13.363",
"Id": "434705",
"Score": "0",
"body": "I didn't know about `snake_case()`. This looks like the cleanest solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T08:10:34.407",
"Id": "435113",
"Score": "0",
"body": "this is the best answer for my usecase, it's clear to read, uses logic that's already there, and it's short."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:12:21.757",
"Id": "224004",
"ParentId": "223849",
"Score": "3"
}
},
{
"body": "<h2>Subclassing</h2>\n\n<p>What's the point of this code? Since <code>__CLASS__</code> always refers to the class in which the code appears, rather than the class of the current object, this method doesn't work with subclassing. That is, with the following code, <code>(new SubModel())->getModelName()</code> would produce <code>base_model</code>, not <code>sub_model</code>:</p>\n\n<pre><code>class BaseModel {\n public function getModelName() {\n return substr(strtolower(substr(strrchr(preg_replace('/(?<!\\ )[A-Z]/', '_$0', get_class($this)), \"\\\\\"), 1)), 1);\n }\n}\n\nclass SubModel extends BaseModel {\n}\n</code></pre>\n\n<p>If that's the case, why not just hard-code the result of <code>getModelName()</code> rather than using reflection?</p>\n\n<p>Alternatively, if you want to make the code work with subclassing, use <code>get_class($this)</code> instead of <code>__CLASS__</code>.</p>\n\n<h2>Deciphering</h2>\n\n<p>That one-liner is hard to read because it does too many things. One problem is that it's hard to see which argument goes with which function call. Maybe indentation could help?</p>\n\n<pre><code>public function getModelName()\n{\n return substr(\n strtolower(\n substr(\n strrchr(\n preg_replace('/(?<!\\ )[A-Z]/', '_$0', __CLASS__),\n \"\\\\\"\n ),\n 1\n )\n ),\n 1);\n}\n</code></pre>\n\n<p>But even that is ridiculously hard to read, because there are no hints as to what each part of the code does. I don't know why there is a negative look-behind assertion in the regex. The outermost <code>substr(…, 1)</code> should be avoidable if the <code>preg_replace(…)</code> call were smarter. Maybe comments could help make it more decipherable?</p>\n\n<h2>Suggested solution</h2>\n\n<p>I suggest writing it as three statements:</p>\n\n<ol>\n<li>Get the name of the class, and discard the namespace (if any — your code doesn't handle un-namespaced classes).</li>\n<li>Find all the CamelCase components within the name.</li>\n<li>Join them with <code>_</code> and make the result lowercase.</li>\n</ol>\n\n\n\n<pre><code>public function getModelName() {\n $unqual_class = end(explode('\\\\', get_class($this)));\n preg_match_all('/.[^A-Z]*/', $unqual_class, $matches);\n return strtolower(implode('_', $matches[0]));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:18:09.003",
"Id": "224005",
"ParentId": "223849",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224004",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T07:03:08.680",
"Id": "223849",
"Score": "1",
"Tags": [
"performance",
"php",
"strings",
"reflection",
"laravel"
],
"Title": "PHP function to obtain model_name from Namespace\\To\\ModelName"
} | 223849 |
<p>The alpha that I create is not created in a crazily efficient way I know, but the main bottleneck in this code is in what I call the "Maximization step" (see comments in code). There are double for-loops twice (with list comprehensions inside), and the reason for this is that I need to use the computed vector from the first double for-loop in the second double for-loop. Here's some proof of my claim, I tested how long the different parts of the code took;</p>
<p>Finishing the vector <code>alphas</code> took <code>0.1451436 s</code>. </p>
<p>Finishing the first bottleneck for loops took <code>13.7402911 s</code></p>
<p>Finishing the second bottleneck for loops took <code>13.1357222 s</code></p>
<p>A single complete loop in the <code>while</code> step took <code>26.9219609 s</code></p>
<p>There should be a more numpy-focused way to update the three vectors <code>mu, pi, sigma_squared</code>, I just can't seem to figure out how. Any help to make this quicker would be greatly appreciated.</p>
<pre><code>import numpy as np
import random as rnd
from scipy.stats import norm
no_distributions = 2 # range of L
range_of_i = 255
range_of_m = 100
iterations = 100
mu = [5.7e-04, 5.9e-04]
sigma_squared = [9.5e-07, 9.5e-07]
weights = [0.49, 0.51]
alphas = []
for i in range(range_of_i):
alpha = []
for m in range(range_of_m):
sub_populations = [rnd.gauss(mu[i], np.sqrt(sigma_squared[i])) for i in range(no_distributions)]
alpha.append(rnd.choices(sub_populations, weights=weights)[0]) # index 0 to add float instead of list
alphas.append(alpha)
threshold = 10
thresh_limit = 1e-4
initial_parameters = np.array([[-1, 1], [0.2, 0.2], [0.5, 0.5]])
# we iterate between the expectation and maximization steps until convergence
while threshold > thresh_limit:
# mu, pi and sigma_squared need to be numpy arrays because we want to add vectors together the numpy way
mu_initial = initial_parameters[0, :]
sigma_squared_initial = initial_parameters[1, :]
pi_initial = initial_parameters[2, :]
mu_updated = np.zeros(no_distributions)
pi_updated = np.zeros(no_distributions)
sigma_squared_updated = np.zeros(no_distributions)
indicator_normalized = []
# Expectation step
for i in range(range_of_i):
indicator = [pi_initial[l] * norm.pdf(alphas[i], mu_initial[l], np.sqrt(sigma_squared_initial[l])) for l
in range(no_distributions)]
indicator_normalized.append([l / sum(indicator) for l in indicator])
indicator_normalized = np.array(indicator_normalized)
indicator_normalized = indicator_normalized.transpose(0, 2, 1)
# Maximization step
for i in range(range_of_i):
for j in range(np.array(alphas).shape[1]):
mu_updated += np.array(
[indicator_normalized[i][j][l] * alphas[i][j] / sum(sum(indicator_normalized))[l] for l in
range(no_distributions)])
pi_updated += np.array(
[indicator_normalized[i][j][l] / (range_of_i * range_of_m)
for l in range(no_distributions)])
# same for loop again needed because we want to use the complete mu_vector to calculate sigma_squared
for i in range(range_of_i):
for j in range(np.array(alphas).shape[1]):
sigma_squared_updated += np.array([indicator_normalized[i][j][l] * (
alphas[i][j] - mu_updated[l]) ** 2 / sum(sum(indicator_normalized))[l] for l in
range(no_distributions)])
# update parameters and calculate the new threshold to see if convergence has been met
parameters_updated = np.array([mu_updated, sigma_squared_updated, pi_updated])
threshold = sum(sum(np.abs(parameters_updated - initial_parameters)))
initial_parameters = parameters_updated
print (parameters_updated)
</code></pre>
<p>The code basically implements an EM-algorithm where the purpose is to find better estimates (better yet, the MLE) of the parameters <span class="math-container">\$\mu, \sigma, \pi\$</span>, which are part of a gaussian mixture model. If you want to understand where the calculations come from, I think the easiest way is just to show you a short description of the algorithm and the formulas below.</p>
<blockquote>
<ul>
<li><p>Suppose the initial parameter vector is <span class="math-container">\$\hat\theta = (\{\hat\pi_l\}_{l=1}^L, \{\hat\mu_l\}_{l=1}^L, \{\hat\sigma_l^2\}_{l=1}^L)\$</span></p></li>
<li><p>Expectation step: Compute the expected value of the indicator variable that indicates which population (e.g., the population of skilled or unskilled managers) <span class="math-container">\$\alpha_{ij}\$</span> is drawn from:<br>
<span class="math-container">\$\begin{align*}\hat{p}_{ijl} & = \hat{Pr}(\alpha_{ij}\text{ comes from Group }l) \\
& = \frac{\hat\pi_l\phi(\alpha_{ij};\hat\mu_l,\hat\sigma^2_l)}{\sum\limits_{l=1}^{L}\hat\pi_l\phi(\alpha_{ij};\hat\mu_l,\hat\sigma^2_l)}, i = 1, \ldots , N; j = 1, \ldots, M; l = 1, \ldots, L \end{align*}\$</span><br>
where <span class="math-container">\$\phi(\cdot;\mu,\sigma^2)\$</span> is the density of the normal distribution <span class="math-container">\$\mathcal{N}(\mu, \sigma^2)\$</span></p></li>
<li><p>Maximization Step: Compute the weighted means and variances with weights obtiained from the Expectation Step:<br>
<span class="math-container">\$\tilde\mu_l=\frac{\sum_{ij}\hat{p}_{ijl}~\alpha_{ij}}{\sum_{ij}\hat{p}_{ijl}}, \tilde\sigma^2_l = \frac{\sum_{ij}\hat{p}_{ijl}~(\alpha_{ij} - \tilde\mu_l)^2}{\sum_{ij}\hat{p}_{ijl}}, \tilde\pi_l = \frac{\sum_{ij}\hat{p}_{ijl}}{MN}, l = 1, \ldots, L.\$</span></p></li>
<li><p>Iterate between the Expectation Step and the Maximization Step until convergence.</p></li>
</ul>
</blockquote>
| [] | [
{
"body": "<p>I searched around this forum a bit more and found some advice to use the package <code>cProfile</code>. This helped me locate the problem which was the <code>sum(sum(indicator_normalized))</code> which took more than 95% of the total time for the complete algorithm. I just moved out the sum and the total time for my algorithm went down to 1/19 of the total time it took before.</p>\n\n<p>So the solution was to write this before the maximization step, and then use this variable inside the for loops;</p>\n\n<pre><code>indicator_sum = sum(sum(indicator_normalized))\n# Maximization step\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:01:26.160",
"Id": "434119",
"Score": "0",
"body": "Be that as it may, I would still leave your question open for others to suggest improvements to the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T11:46:10.717",
"Id": "223859",
"ParentId": "223852",
"Score": "3"
}
},
{
"body": "<p>Congratulations to you for finding a major bottleneck yourself. There are a few more to get rid of.</p>\n\n<hr>\n\n<p>Generally speaking it's quite a performance killer to convert data between Python and numpy repeatedly. And you do that a lot. You even do it to determine the number of iterations for some loops, e.g. in <code>for j in range(np.array(alphas).shape[1]):</code>. Since <code>alphas</code> is created beforehand and not expanded again, the first step would be to convert it into a numpy array <strong>once</strong>. But there is no real need to query its shape, since you know exactly how the shape of <code>alphas</code> is, it's exactly <code>(range_of_i, range_of_m)</code>. So you convert <span class=\"math-container\">\\$255 \\times 100\\$</span> elements to numpy just to get <code>range_of_m</code> as an answer. Not really efficient, isn't it?</p>\n\n<p>In addition, Python is also often not really fast at loops. There is a great talk from Jake VanderPlas from PyCon 2015 titled \"Losing your Loops - Fast Numerical Computing with NumPy\" (to be found on <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"nofollow noreferrer\">YouTube</a>) on that topic. I highly recommend watching it!</p>\n\n<hr>\n\n<p>After the general remarks, let's start from the beginning:</p>\n\n<hr>\n\n<p>When you generate <code>alphas</code>, you draw samples from <code>no_distributions</code> distributions, and then discard all but one value if I'm not terribly mistaken. So why not choose the distribution beforehand, and sample that one?</p>\n\n<pre><code>alphas = np.empty((range_of_i, range_of_m))\ndist_idxs = list(range(no_distributions))\nsigma = np.sqrt(sigma_squared)\nfor i in range(range_of_i):\n idxs = rnd.choices(dist_idxs, weights=weights, k=range_of_m)\n alphas[i, :] = [rnd.gauss(mu[idx], sigma[idx]) for idx in idxs]\n</code></pre>\n\n<p>This code snippet also includes the idea to have <code>alphas</code> as numpy array directly. You could also keep the original approach to have a list of lists and then convert that, but this helps you to save some variables. I also opted to remove the inner loop in favor of a list comprehension. Maybe there is even a clever way to get rid of the outer loop (without using a list comprehension!), but I'll leave that as an exercise to you.</p>\n\n<hr>\n\n<p>Next up on the list is the expectation step. Again, funny mix-up of Python and numpy/scipy code here. And although I have the strong feeling that there has to be a better solution, the following is the best I could come up with at the moment:</p>\n\n<pre><code>sigma_initial = np.sqrt(initial_parameters[1, :])\n\n# ... other code ...\n\n# Expectation step\nindicator_normalized = np.empty((range_of_i, no_distributions, range_of_m))\nfor i in range(range_of_i):\n indicator = np.array([\n pi_initial[l] * norm.pdf(alphas[i], mu_initial[l], sigma_initial[l])\n for l in range(no_distributions)\n ])\n indicator_normalized[i, ...] = indicator / indicator.sum(axis=0)\n\nindicator_normalized = indicator_normalized.transpose(0, 2, 1)\n# summing over multiple axis needs numpy >= 1.7\nindicator_sum = indicator_normalized.sum(axis=(0, 1))\n</code></pre>\n\n<hr>\n\n<p>Next up on the list: maximization.</p>\n\n<p>Let's get rid of some loops here. A first step in that direction might look as follows:</p>\n\n<pre><code># Maximization step\nfor i in range(range_of_i):\n for j in range(range_of_m):\n mu_updated += indicator_normalized[i, j, :] * alphas[i, j] / indicator_sum\n pi_updated += indicator_normalized[i, j, :] / (range_of_i * range_of_m)\n\n# same for loop again needed because we want to use the complete mu_vector to calculate sigma_squared\nfor i in range(range_of_i):\n for j in range(range_of_m):\n sigma_squared_updated += \\\n indicator_normalized[i, j, :] * (alphas[i, j] - mu_updated)**2 \\\n / indicator_sum\n</code></pre>\n\n<p>But we can do better! Enter numpy broadcasting and slicing!</p>\n\n<pre><code># Maximization step\nmu_updated = np.sum(\n indicator_normalized * alphas[..., np.newaxis] / indicator_sum,\n axis=(0, 1)\n)\npi_updated = np.sum(\n indicator_normalized / (range_of_i * range_of_m), axis=(0, 1)\n)\n\n# same for loop again needed because we want to use the complete mu_vector to calculate sigma_squared\nsigma_squared_updated = np.sum(\n indicator_normalized * (alphas[..., np.newaxis] - mu_updated)**2\n / indicator_sum,\n axis=(0, 1)\n)\n</code></pre>\n\n<p>Explaining the full beauty of this would be beyond the scope of what I can do here. I highly recommend reading the chapter <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/02.07-fancy-indexing.html\" rel=\"nofollow noreferrer\">\"Fancy Indexing\"</a> from the <em>Python Data Science Handbook</em> by Jake VanderPlas if you want to learn more. What this does in essence is to move those pesky loops into the numpy's C back end. You can check that those results really match by pasting both pieces of code into the same file and check with <code>np.allclose(...)</code>.</p>\n\n<hr>\n\n<p><strong>Results</strong><br/></p>\n\n<p>So what did we win be jumping through all those hoops and losing all those loops?</p>\n\n<p>Your proposed solution that moved the <code>sum(sum(...))</code> out of the loop takes around <span class=\"math-container\">\\$5s\\$</span> to converge here on my machine. With the code above in its most loop-reduced form the algorithm finishes in about <span class=\"math-container\">\\$0.2s\\$</span> to <span class=\"math-container\">\\$0.25 s\\$</span> with the same result (not exactly the same cause the random numbers also have a little impact here). That's a speed-up of 20-25x. I can live with that for the moment ;-). <br/>(<strong>Note:</strong> The timing results only cover the content of the <code>while</code> loop, not the initialization.)</p>\n\n<p>I'm actually not a 100% sure the implementation is fully correct, but the new implementation is at least as correct as the original one. If you find an error here in my code, it already existed in the original solution because I tested for agreement between your and my solution ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T10:27:25.970",
"Id": "434439",
"Score": "0",
"body": "I had to study this answer for a few hours before understanding it, I learned so much! Can't thank you enough, I'm gonna try using numpy for everything from here on out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:57:22.087",
"Id": "434453",
"Score": "0",
"body": "Welcome to the world of numpy ;-) I also still learn new things while working on different projects. A word of warning though: numpy is not a magic bullet! There are cases where numpy can slow your code down. But whenever you can use it to *vectorize* your code to get rid of nested loops as presented above, the performance will almost always be significantly better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:27:26.793",
"Id": "223980",
"ParentId": "223852",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223980",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T08:02:05.910",
"Id": "223852",
"Score": "2",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "Performance issues with double for loops, EM-algorithm"
} | 223852 |
<p>This code checks if "B2" and so on is filled in and if it is then it will generate a new ID number for the row of data that was transferred to the worksheet on the next empty row, I know this code creates opportunities for bugs so I want to make it better but I don't really know how I could do it. (PS: I am very bad at loops so if the solution is a loop please word yourself as if you were talking to a newcomer</p>
<pre><code>'Creating a variable for all the inputs from the textboxes
Dim inputs As Variant
inputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text)
' shipFrom, shipTo, shipDate, NP, desc, gramEx, tareWeight, weight, dims
'Declaring a variable for the next available row where the inputs are going
Dim nextRowB As Range
Set nextRowB = Sheets("Arkiv").Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
nextRowB.Resize(1, UBound(inputs) + 1).Value = inputs
'Delaring ID number for each row as a variable
Dim ID As Range
Set ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
If IsEmpty(Sheets("Arkiv").Range("B2").Value) Then 'How can I make this line better? I know this way of doing it creates oppertunities for many bugs
MsgBox "Please fill in the <Ship From> box"
Else
Sheets("Arkiv").Range("A2").Value = "1"
End If
If Not IsEmpty(Sheets("Arkiv").Range("C2").Value) Then
ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value + 1
End If
Sheets("Arkiv").Activate
MsgBox "The ID number for this data is: " & Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:32:20.607",
"Id": "434100",
"Score": "2",
"body": "What's using these ID values, and what happens when a row is deleted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:35:22.900",
"Id": "434101",
"Score": "3",
"body": "Step 1) Update your form and rename your text boxen. There's no reason to have a comment that `TextBox1 = shipFrom` when you could simply _rename_ `TextBox1` to `shipFrom`. When someone accidentally deletes that comment line, you and everyone who comes after you will thank you for taking the 5 minutes to do that rename!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T02:10:37.253",
"Id": "434195",
"Score": "0",
"body": "Could you use the row number as your index, or if you have a header, the row number - 1?"
}
] | [
{
"body": "<h2>Creating an Unique ID Without Loops</h2>\n\n<p>The problem with incrementing the next ID based on the last cell in a column is you will have to sort the data to ensure that it is in ID order. This really can take away from the user experience. A better approach would be to use the <code>WorksheetFunction.Max()</code> to find the current max ID.</p>\n\n<h2>\"<strong>I am very bad at loops</strong>\"</h2>\n\n<p>You should start by watching these videos:</p>\n\n<ul>\n<li><p><a href=\"https://www.youtube.com//watch?v=c8reU-H1PKQ&index=5&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)</a></p></li>\n<li><p><a href=\"https://www.youtube.com//watch?v=wGauctajWPQ&index=16&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 15 - Do Until and Do While Loops</a></p></li>\n<li><a href=\"https://www.youtube.com//watch?v=_ZVSV9Y7TGw&index=17&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 15a - Find and FindNext</a></li>\n<li><a href=\"https://www.youtube.com//watch?v=JyWrLH7monI&index=18&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 16 - For Next Loops</a></li>\n<li><a href=\"https://www.youtube.com//watch?v=R2nlDu-2E4o&index=19&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 17 - For Each Loops</a></li>\n</ul>\n\n<p>Notice that the first video teaches you how to define ranges. Well, If you are having problems with loops in Excel then chances are you are having problems defining the range to loop over. </p>\n\n<p>The best advice that I can give you when you are having problems with a coding pattern is to practice it. Printout a worksheet with several different types of loops and every morning choose a couple of the patterns and type them up several times until you can recite them from memory. Another great way to practice is to start answering questions on Stackoverflow.com. This will challenge you with unique situations that you would not normally see. Your answers will get progressively better or time as you respond to the comments from other users.</p>\n\n<h2>Miscellaneous</h2>\n\n<p>TextBox1, TextBox2 TextBox3 ... ugh!! In the time it takes you to the write comments to describe what each one does, you could have just gave them meaningful names. I generally preface all my textboxes with <strong>txt</strong> like this txtShipFrom, txtShipTo, txtShipDate but simply using shipFrom, shipTo, shipDate also works.</p>\n\n<p><code>Sheets(\"Arkiv\")</code> is used 6 times. Using <code>With Sheets(\"Arkiv\")</code> will not only make you code easier to read, modify, and debug but is also more efficient (the compiler only has to resolve the reference 1 time).</p>\n\n<p>Refactored code:</p>\n\n<pre><code>Sub AddNewShippingRow_Click()\n Dim inputs As Variant\n Dim ID As Long\n Dim nextRow As Range\n\n ID = getNextShippingID\n Set nextRow = getNextShippingRow\n\n inputs = Array(ID, shipFrom.Text, shipTo.Text, shipDate.Text, NP.Text, desc.Text, gramEx.Text, tareWeight.Text, Weight.Text, dims.Text)\n\n nextRow.Resize(UBound(inputs) + 1).Value = inputs\nEnd Sub\n\nFunction getNextShippingRow() As Range\n With Sheets(\"Arkiv\")\n Set getNextShippingRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1)\n End With\nEnd Function\n\nFunction getNextShippingID() As Long\n With Sheets(\"Arkiv\")\n getNextShippingID = WorksheetFunction.Max(.Range(\"A1\", .Cells(.Rows.Count, 1).End(xlUp))) + 1\n End With\nEnd Function\n</code></pre>\n\n<p>In my refactored code I simplified the main subroutine by using helper functions to perform some of the tasks. The fewer tasks that a subroutine performs the easier it is to read, modify and debug. </p>\n\n<p>For instance say that you wanted to change the way you create your ID's because we are using a helper function we can modify and test that function without have to run the larger block of code.</p>\n\n<p>Here I modify and tested 4 different versions <code>getNextShippingID()</code> without having to make any changes to the main routine. Of course, I would have to change the datatype of the main routines ID variable but that is not to after I completed my testing.</p>\n\n<pre><code>Function getNextShippingID() As Double\n getNextShippingID = CLng(Date) & (Timer * 100)\nEnd Function\n\nFunction getNextShippingID() As Double\n Const StartDate As Date = #1/1/2019#\n getNextShippingID = CLng(Date - StartDate) & (Timer * 100)\nEnd Function\n\nFunction getNextShippingID() As Double\n getNextShippingID = Format(Now, \"ddmmyyhhmmssnn\")\nEnd Function\n\nFunction getNextShippingID() As String\n Dim s As String\n s = CreateObject(\"Scriptlet.TypeLib\").GUID\n getNextShippingID = Mid(s, 2, Len(s) - 4)\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:27:28.543",
"Id": "434203",
"Score": "0",
"body": "Thanks a lot! Great response, I have been wanting to find some good videos to teach myself loops because I notice how often I feel like a loop would be possible if I understood them an knew the different ways to do them. By the way, I have never programmed before and this is like 4 days into my first language, is this something I should be proud over or am I hanging far behind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:39:28.403",
"Id": "434287",
"Score": "0",
"body": "@SanderJensen you are doing great!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:21:06.707",
"Id": "223875",
"ParentId": "223854",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T08:35:51.300",
"Id": "223854",
"Score": "0",
"Tags": [
"vba",
"excel",
"validation"
],
"Title": "Generate an ID number for each new row of text that is pasted into the worksheet"
} | 223854 |
<p>I use JS/JQuery validation for radioboxes, input field etc. Because of AJAX I use one global validation (in a separate file) and 4-5 other files to coverage actions in a relevant registration form pages. These actions are repeated in a few places so I need to refactor it to be in line with DRY.</p>
<p>I have validation for checkbox which I use in global validation (below) and I have to use the same code, four times in a separate file for each registration pages (if I delete just them in those files, global validation doesn't replace it). Is there any way to be in line with DRY principle? can I take the whole global action to variable var globalValidation and refer to him in individual actions like in method in Rails?</p>
<p><strong>global validations</strong></p>
<pre><code>$(document).ready(function () {
var form = $('#userRegistrationForm');
var submit = form.find('input[type="submit"]');
submit.click(function(evt) {
evt.preventDefault();
var invalidInput = $('input:invalid');
if (invalidInput.length === 0) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateRadios();
}
});
function validateRadios() {
var radio = $('input[type=radio]');
var radioInvalid = $('input[type=radio]:invalid');
var radioMsg = $('.radio-invalid-msg')
if (radio) {
if (radioInvalid.length > 0) {
radioMsg.addClass('invalid');
}
radio.click(function () {
if (radio.is(':checked')) {
radio.removeClass('invalid');
radioMsg.removeClass('invalid');
} else if (radio.is(':not(:checked)')) {
radio.addClass('invalid');
radioMsg.addClass('invalid');
}
});
}
}
});
</code></pre>
<p><strong>repeated validation in create.rb</strong></p>
<pre><code>$(document).ready(function () {
var form = $('#userRegistrationForm');
var submit = form.find('input[type="submit"]');
submit.click(function(evt) {
evt.preventDefault();
var invalidInput = $('input:invalid');
if (invalidInput.length === 0) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateRadios();
}
});
function validateRadios() {
var radio = $('input[type=radio]');
var radioInvalid = $('input[type=radio]:invalid');
var radioMsg = $('.radio-invalid-msg')
if (radio) {
if (radioInvalid.length > 0) {
radioMsg.addClass('invalid');
}
radio.click(function () {
if (radio.is(':checked')) {
radio.removeClass('invalid');
radioMsg.removeClass('invalid');
} else if (radio.is(':not(:checked)')) {
radio.addClass('invalid');
radioMsg.addClass('invalid');
}
});
}
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Forms are generated by AJAX, if user reload one page of the form, <code>global validation</code> will take care of validation (replacing validations for a given step).</p>
<p>for example - this is a view for on of the page:</p>
<p><strong>_update_user.html.erb</strong></p>
<pre><code><%= link_to t('registrations.new.back'), back_registrations_path(step: 1), remote: true, class: "back-btn"%>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 update-user__header">
<h3 class="text__blue"><%= t('.whats_your_name') %></h3>
</div>
</div>
<%= form_for current_user, as: :user, url: user_path, method: :patch, aria_role: "form", html: { id: "userRegistrationForm" }, remote: true do |f| %>
<div class="row">
<div class="update-user__input-wrapper">
<div class="col-sm-6 col-md-6 col-xs-12 update-user__name-input--first">
<div class="floating-label">
<%= f.text_field :first_name, class: "update-user__name-input floating-field", placeholder: t('.first_name'), required: true, aria_required: true %>
<%= f.label :first_name, t('.first_name'), class: "floating-label-placeholder" %>
<span class="update-user__name-input--invalid-msg">
<%= t'.obligatory' %></span>
</div>
</div>
<div class="col-sm-6 col-md-6 col-xs-12 update-user__name-input--last">
<div class="floating-label">
<%= f.text_field :last_name, class: "update-user__name-input floating-field", placeholder: t('.last_name'), required: true, aria_required: true %>
<%= f.label :last_name, t('.last_name'), class: "floating-label-placeholder" %>
<span class="update-user__name-input--invalid-msg">
<%= t'.obligatory' %></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="text-gray update-user__gender-wrapper">
<div class="col-md-12 col-sm-12 col-xs-12">
<%= t('.whats_your_gender') %>
</div>
</div>
<div class="col-sm-2 col-md-2 col-xs-12">
<div class="vr-radio-group">
<div class="vr-radio update-user__radio">
<label>
<%= f.radio_button :gender, "female", class: "update-user__radio-input", required: true %>
<div class="vr-radio__radio"></div>
<span class="vr-radio__desc update-user__radio-desc text-gray">
<%= t'.female' %></span>
</label>
</div>
<br>
<div class="vr-radio update-user__radio">
<label>
<%= f.radio_button :gender, "male", class: "update-user__radio-input", required: true %>
<div class="vr-radio__radio"></div>
<span class="vr-radio__desc update-user__radio-desc text-gray">
<%= t'.male' %></span>
</label>
</div>
<span class="radio-invalid-msg">
<%= t'.obligatory' %></span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-xs-12 form-submit text-center">
<%= f.submit t('.submit'), class: "submit-btn" %>
</div>
</div>
<% end %>
</code></pre>
<p>And here are the validation for this action:</p>
<p><strong>create.js.erb</strong></p>
<pre><code>$(".card-content").html("<%= escape_javascript(render(partial: 'users/update_user') ) %>");
animateSidebar();
$(document).ready(function () {
var form = $('#userRegistrationForm');
var submit = form.find('input[type="submit"]');
submit.click(function(evt) {
evt.preventDefault();
var invalidInput = $('input:invalid');
var firstName = $('#user_first_name').val();
var lastName = $('#user_last_name').val();
$("#user-name").text(firstName + " " + lastName);
if (invalidInput.length === 0) {
form.submit();
} else {
invalidInput.addClass('invalid');
validateInput();
validateRadios();
}
});
function validateInput() {
$('input').change(function () {
if ($(this).is(':valid')) {
$(this).removeClass('invalid');
}
});
}
function validateRadios() {
var radio = $('input[type=radio]');
var radioInvalid = $('input[type=radio]:invalid');
var radioMsg = $('.radio-invalid-msg')
if (radio) {
if (radioInvalid.length > 0) {
radioMsg.addClass('invalid');
}
radio.click(function () {
if (radio.is(':checked')) {
radio.removeClass('invalid');
radioMsg.removeClass('invalid');
} else if (radio.is(':not(:checked)')) {
radio.addClass('invalid');
radioMsg.addClass('invalid');
}
});
}
}
});
</code></pre>
<p>I think the best way is to remove validation from <code>create.js</code>, put it all in to <code>global validation</code>, pack it as <code>function formValidation</code> and placing it in four places where I have the same validation. Is it possible? Should I refer to it in some way? e.g. after <code>submit.click</code> ? I don't know if JQuery allows in such a practice.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:28:45.497",
"Id": "434113",
"Score": "0",
"body": "Welcome to Code Review. Please show enough context for the code (such as how you generate the forms), so that we can give you specific advice that is more helpful than \"Well, just don't write the same code twice!\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T18:06:29.447",
"Id": "434133",
"Score": "0",
"body": "Hi @200_success thank you for your response! I did not want to flood with unnecessary code, this app is quite big for me. Post is updated, please let me know if you want to see something more."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T10:11:38.767",
"Id": "223857",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"validation",
"ruby-on-rails",
"form"
],
"Title": "jQuery validation for multi-page registration form"
} | 223857 |
<p>I wrote a simple image scraper for the Desktop Wallpaper project by The Fox is Black. The site is a fantastic (yet, apparently dead) blog full of fabulous images. However, there's no way to download an entire bundle of images, hence this simple scraper.</p>
<p>I'm putting the code up for scrutiny. Any areas for code style and/or implementation improvements? I'd appreciate your feedback.</p>
<pre><code>#!/usr/bin/python
import os
import requests
from bs4 import BeautifulSoup as bs
MAX_PAGES = 1 # Max. number of pages is 41
SAVE_DIRECTORY = 'fox_backgrounds'
BASE_URL = "http://www.thefoxisblack.com/category/the-desktop-wallpaper-project/page"
RESOLUTIONS = [
"1280x800", "1440x900", "1680x1050", "1920x1200", "2560x1440",
"iphone", "iphone-5", "iphone6", "iphone-6-plus", "iphone6plus",
"ipad",
]
def fetch_url(url):
return requests.get(url).text
def clip_url(href):
return href[href.rfind('/'):]
def save_image(href):
print(f"Downloading: {clip_url(href)}")
request = requests.get(href)
with open(f"fox_backgrounds{clip_url(href)}", 'wb') as output:
output.write(request.content)
def get_images_from_page(url):
html = fetch_url(url)
soup = bs(html, "html.parser")
for link in soup.find_all("a", class_="btn_download"):
href = link["href"]
for resolution in RESOLUTIONS:
if resolution in href:
save_image(href)
def make_dir():
os.makedirs(SAVE_DIRECTORY, exist_ok=True)
def get_backgrounds():
make_dir()
for page in range(0, MAX_PAGES):
get_images_from_page(BASE_URL + str(page + 1))
def main():
get_backgrounds()
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:00:43.787",
"Id": "434106",
"Score": "1",
"body": "This was fun to work on. There was a moment of trepidation when I didn't know what kind of \"pictures\" this site hosted, but it worked out in the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:13:16.143",
"Id": "434108",
"Score": "0",
"body": "I'm glad you enjoyed it!"
}
] | [
{
"body": "<p>Suggested:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python\n\nimport os\nimport requests\n\n\nfrom bs4 import BeautifulSoup as bs\nfrom pathlib import Path\nfrom shutil import copyfileobj\n\n\nMAX_PAGES = 1 # Max. number of pages is 41\nSAVE_DIRECTORY = Path('fox_backgrounds')\nBASE_URL = 'http://www.thefoxisblack.com/category/the-desktop-wallpaper-project/page'\nRESOLUTIONS = {\n '1280x800', '1440x900', '1680x1050', '1920x1200', '2560x1440',\n 'iphone', 'iphone-5', 'iphone6', 'iphone-6-plus', 'iphone6plus',\n 'ipad'\n}\n\n\ndef fetch_url(url):\n return requests.get(url).text\n\n\ndef clip_part(href):\n return href.rpartition('/')[-1]\n\n\ndef save_image(href):\n part = clip_part(href)\n print(f' Downloading: {part}')\n fn = SAVE_DIRECTORY / part\n with requests.get(href, stream=True) as response, \\\n open(fn, 'wb') as output:\n copyfileobj(response.raw, output)\n\n\ndef get_images_from_page(url):\n html = fetch_url(url)\n soup = bs(html, 'html.parser')\n for link in soup.find_all('a', class_='btn_download'):\n href = link['href']\n if any(href.endswith(f'-{res}.jpg') for res in RESOLUTIONS):\n save_image(href)\n else:\n print(f'Unknown resolution {href}')\n\n\ndef make_dir():\n os.makedirs(SAVE_DIRECTORY, exist_ok=True)\n\n\ndef get_backgrounds():\n make_dir()\n for page in range(1, MAX_PAGES+1):\n print(f'Fetching page {page}...')\n get_images_from_page(f'{BASE_URL}{page}')\n\n\ndef main():\n get_backgrounds()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Comments:</p>\n\n<ul>\n<li>You initialized <code>SAVE_DIRECTORY</code> but then use it for creation and not file write</li>\n<li><code>RESOLUTIONS</code> should be a set, or maybe a tuple</li>\n<li><code>clip_url</code> is slightly misleading; it returns a URL part and not a whole URL</li>\n<li>It's best if you have a prompt before downloading the index page; otherwise it hangs without the user knowing what's happening</li>\n<li>Stream your content so that you don't use up memory for big files</li>\n<li>Your <code>RESOLUTIONS</code> check is a little puzzling. Maybe it's a validation step? But if it's a validation step, you silently fail instead of printing a warning. Also, you keep iterating even after you've found the correct resolution. I rewrote this to just check the current resolution, and also be a little bit more careful about where it's seen in the filename.</li>\n<li><code>range(0, ...)</code> is redundant, but for your use case you're better off with <code>range(1</code> anyway.</li>\n<li><code>rpartition</code> does basically the same thing as what you wrote, but doesn't require any fancy array slicing</li>\n<li>Don't call <code>clip_path</code> twice</li>\n</ul>\n\n<hr>\n\n<h1>Edit</h1>\n\n<p>The following version makes sane use of generators so that the iteration functions only need to know about their iteration, and not the inner business logic.</p>\n\n<p>Also, your resolution check needs to be case-insensitive for many of the files on the site; and the site has gif and png images as well as jpg. You were missing some resolutions and some alternate iPhone spellings. I don't think that it's worth doing a resolution check at all, especially given these edge cases, but I left it in.</p>\n\n<pre><code>#!/usr/bin/python\n\nimport os\nimport requests\n\n\nfrom bs4 import BeautifulSoup as bs\nfrom pathlib import Path\nfrom shutil import copyfileobj\n\n\nMAX_PAGES = 1 # Max. number of pages is 41\nSAVE_DIRECTORY = Path('fox_backgrounds')\nBASE_URL = 'http://www.thefoxisblack.com/category/the-desktop-wallpaper-project/page'\nRESOLUTIONS = {\n '1280x800', '1440x900', '1680x1050', '1920x1200', '2560x1440', '3840x2400',\n 'iphone', 'iphone5', 'iphone-5', 'iphone6', 'iphone-6-plus', 'iphone6plus', 'iphone6-plus',\n 'ipad'\n}\n\n\ndef clip_part(href):\n return href.rpartition('/')[-1]\n\n\ndef save_image(href):\n part = clip_part(href)\n print(f' Downloading: {part}')\n fn = SAVE_DIRECTORY / part\n with requests.get(href, stream=True) as response, \\\n open(fn, 'wb') as output:\n copyfileobj(response.raw, output)\n\n\ndef urls_from_page(url):\n soup = bs(requests.get(url).text, 'html.parser')\n for link in soup.find_all('a', class_='btn_download'):\n href = link['href']\n if any(href.lower().contains(f'-{res}.') for res in RESOLUTIONS):\n yield href\n else:\n print(f'Unknown resolution {href}')\n\n\ndef make_dir():\n os.makedirs(SAVE_DIRECTORY, exist_ok=True)\n\n\ndef all_urls():\n for page in range(1, MAX_PAGES+1):\n print(f'Fetching page {page}...')\n yield from urls_from_page(f'{BASE_URL}{page}')\n\n\ndef main():\n make_dir()\n for url in all_urls():\n save_image(url)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:12:47.483",
"Id": "434107",
"Score": "1",
"body": "This a great review. Thank you! Even though, this is a relatively short and simple script, I've still missed a couple of things here and there, but that's a good learning experience for me. I appreciate your time and effort!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:27:51.947",
"Id": "223870",
"ParentId": "223858",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223870",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T11:32:14.913",
"Id": "223858",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "the fox is black - a simple image scraper"
} | 223858 |
<p>I would like to ask a code review regarding a concrete exercise. Let's suppose I have to get the number of all specific substrings in a string.</p>
<p>We call something <em>specific</em> if any of these conditions are is true:</p>
<blockquote>
<ul>
<li><p>The string consists of similar characters. For example: "aaaaa"</p>
</li>
<li><p>The string consists of similar characters except the middle one, which can be anything. For example: "aabaa"</p>
</li>
</ul>
</blockquote>
<p>To do this, I first decided to get all combinations into a list. I did it in an O(n³) solution just with 2 basic <code>for</code> loops and using <code>substring()</code> (<a href="https://stackoverflow.com/questions/4679746/time-complexity-of-javas-substring">see more</a>), this way:</p>
<pre><code>private static List<String> allCombinations(String s) {
List<String> output = new ArrayList<>();
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j <= s.length() - i; j++) {
output.add(s.substring(j, j + i));
}
}
return output;
}
</code></pre>
<p>Subsequently, I used this method to count how many of these are special:</p>
<pre><code>static long substrCount(String s) {
long res = 0L;
List<String> output = allCombinations(s);
for (String x : output) {
if(isSpecial(x)){
res++;
}
}
return res;
}
</code></pre>
<p><code>isSpecial()</code> looks like this:</p>
<pre><code>private static boolean isSpecial(String input) {
Set<Character> occurrences = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
occurrences.add(input.charAt(i));
}
if (occurrences.size() > 2) {
return false;
}
if (occurrences.size() == 1) {
return true;
}
return input.length() % 2 == 1 && input.charAt(0) == input.charAt(input.length() - 1) && input.charAt(input.length() / 2) != input.charAt(0);
}
</code></pre>
<p>I've got 2 questions:</p>
<ol>
<li><p>This is a practice exercise with provided tests, and most of the test cases failed due to time complexity problems. How could I reduce the time complexity of my solution?</p>
</li>
<li><p>If you could give me any general feedback what to improve in - based on my code - I would be really thankful.</p>
</li>
</ol>
<p>Thank you in advance.</p>
| [] | [
{
"body": "<p>First off, I believe you are confusing the terms \"specific\" and \"special\" in the description.</p>\n\n<h1>Method <code>isSpecial</code></h1>\n\n<ul>\n<li><p>You could move the <code>if (occurrences.size() > 2)</code> statement into the for loop, because once you know that there are more than 2 different characters, there is no need to continue adding more characters to the <code>Set</code>. Then you can also initialize the <code>HashSet</code> to an initial size of <code>3</code>, because it never can grow larger than that.</p></li>\n<li><p>You don't need the part <code>input.charAt(0) == input.charAt(input.length() - 1)</code> in the final expression, because when the length is more than two and if there are exactly two different characters, it can never be \n<code>false</code> when <code>input.charAt(input.length() / 2) != input.charAt(0)</code> is <code>true</code>.</p></li>\n<li><p>Finally I'd put <code>input.length</code> into a local variable. That will speed up the <code>for</code> loop by a tiny amount by avoiding the method call and it will make the final expression a bit shorter and thus better to read</p></li>\n</ul>\n\n<p> </p>\n\n<pre><code>private static boolean isSpecial(String input) {\n int len = input.length();\n Set<Character> occurrences = new HashSet<>(3);\n for (int i = 0; i < len; i++) {\n occurrences.add(input.charAt(i));\n if (occurrences.size() > 2) {\n return false;\n }\n }\n if (occurrences.size() == 1) {\n return true;\n }\n return len % 2 == 1 && input.charAt(len / 2) != input.charAt(0);\n}\n</code></pre>\n\n<h1>Method <code>substrCount</code></h1>\n\n<p>This method can be shorten significantly by using Java 8's Stream API:</p>\n\n<pre><code>static long substrCount(String s) {\n return allCombinations(s).stream().filter(ClassName::isSpecial).count();\n}\n</code></pre>\n\n<p><em>(<code>ClassName</code> is the name of the class <code>isSpecial</code>is in.)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:38:38.033",
"Id": "223951",
"ParentId": "223863",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T12:52:46.890",
"Id": "223863",
"Score": "2",
"Tags": [
"java",
"algorithm",
"strings",
"complexity"
],
"Title": "Find the number of all specific substrings in a string"
} | 223863 |
<p>The task is to find the maximum number in an array of numbers.
I have taken every number in the array to be byte-sized.
I have written the code such that the result is stored in <code>ch</code> at the end.</p>
<p>The code is written to run on Intel 8086.</p>
<p>Code optimization and improvement required.</p>
<pre><code> org 100h
;registers: bx - to store the base address of the array of numbers
;si : to store the index of the current number in the array
;dl: to store the iterator value of the for loop in the program
;dh: to store the value of n(size of the array)
;ch: to store the maximum element
;ah: temporary register to store the current element, and to compare with
;the number in ch
lea bx,array
mov si,0h
mov dl,0h
mov dh,n
cmp dl,dh
jge end
mov cx,0h
;to move the first value into the min-register to compare with other elements
mov ch,[bx+si]
inc dl
inc si
loop:
cmp dl,dh
jge end
mov ah,[bx+si]
inc si
inc dl
cmp ah,ch
jle loop
mov ch,ah
jmp loop
end:
mov ax,0h
mov dx,0h
mov bx,0h
mov si,0h
ret
array DB 4h,45h,32h,23h,9h
n DB 5
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:54:25.637",
"Id": "434095",
"Score": "0",
"body": "Welcome to Code Review! This looks a worthwhile challenge, but please [edit] to identify the processor (x86?) and OS (if any) on which this is intended to run. Thanks!"
}
] | [
{
"body": "<h2>Undefined Behaviour</h2>\n\n<p>If you execute this code with <code>n DB 0</code>, it returns without setting <code>ch</code> to any value, leaving the result as undefined.</p>\n\n<h2>Signed Length</h2>\n\n<pre><code>mov dl,0h\nmov dh,n\n\ncmp dl,dh\njge end\n</code></pre>\n\n<p>If <code>n</code> happens to be between 128 and 255, the <code>jge</code> will treat the comparison as if it was a signed comparison, and since 0 is not greater than or equal to any value between -128 and -1, inclusive, immediately jump to the end, again leaving <code>ch</code> as an undefined value.</p>\n\n<p>You should use <code>jae</code> instead, so you can have up to 255 values in <code>array</code>.</p>\n\n<h2>Signed comparison</h2>\n\n<p>Does your array of values represent unsigned bytes, or signed bytes? If your array contains <code>0FFh</code>, is that the largest possible value, or one smaller than zero?</p>\n\n<p>If the data is supposed to be signed, you're good. If it was supposed to be unsigned bytes, you again should change the <code>jle</code> to <code>jbe</code>.</p>\n\n<h2>Unnecessary Register Usage</h2>\n\n<p>You execute <code>mov cx,0h</code>, but nowhere do you use <code>cl</code>, so are unnecessarily destroying <code>cl</code>.</p>\n\n<p>You execute <code>mov ah,[bx+si]</code> and use <code>mov ax,0h</code> to clean-up at the end. Again, nowhere have you used <code>al</code>, so you've unnecessarily destroyed <code>al</code>.</p>\n\n<p>If you used <code>cl</code> instead of <code>ah</code>, you wouldn't need to destroy <code>ax</code> at all.</p>\n\n<p>Use of <code>si</code> appears unnecessary. Instead of based-index addressing mode:</p>\n\n<pre><code>mov cl,[bx+si]\ninc si\n</code></pre>\n\n<p>you could use register indirect addressing mode:</p>\n\n<pre><code>mov cl,[bx]\ninc bx\n</code></pre>\n\n<h2>Better Registers</h2>\n\n<p><code>cx</code> is the standard for loop counts. <code>ax</code> is the standard for function return values. <code>si</code> is the standard for source indexing. So ...</p>\n\n<p>Have your function store and return the maximum in <code>al</code>. Use <code>ah</code> to fetch values from the <code>array</code>, and zero it at the end. As a bonus, <code>ax</code> could also be considered the return value. (If the array is intended to hold signed data, then use <code>cbw</code> to sign extend <code>al</code> into <code>ax</code> instead of zeroing <code>ah</code>.)</p>\n\n<p>If you used <code>cx</code> for your array length, and decrement to zero, you could use one <code>LOOP</code> instruction instead of a pair of instructions to perform the compare-and-branch. As another bonus, it will already be zero by the end, so you won't need to clear it.</p>\n\n<p>Store the <code>array</code> address in <code>si</code>, and use <code>cx</code> for double duty by using based-index addressing (<code>mov ah, [cx+si]</code>) to index into your <code>array</code>. Of course, you'll be searching backwards, which still fine for finding the maximum. You'd just have to be careful to include the 0th value, and exclude the nth value (<code>dec cx</code> before the fetch, not afterwards).</p>\n\n<p>Final tally:</p>\n\n<ul>\n<li>return value in <code>ax</code></li>\n<li><code>cx</code> zeroed (automatically)</li>\n<li><code>si</code> cleared (manually)</li>\n<li>All other registers unchanged.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-18T15:24:49.923",
"Id": "435353",
"Score": "2",
"body": "Why did you promote a __non-existing addressing mode__ ? The 8086 has limited possibilities for addressing memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:30:19.987",
"Id": "223913",
"ParentId": "223864",
"Score": "4"
}
},
{
"body": "<h2>Optimizations</h2>\n\n<p>Why are you so keen on zeroing the registers at the completion of the program? Drop those and you'll have made your first optimization already.</p>\n\n<p>Don't use <code>mov si, 0</code> to zero the register. Use <code>xor si, si</code>. It's shorter (codesize) and faster (execution speed).</p>\n\n<p>Instead of using <code>lea bx, array</code> use <code>mov bx, array</code> (NASM style) or <code>mov bx, offset array</code> (MASM style). The <code>mov</code> variant has a shorter encoding.</p>\n\n<p>Addressing the array will be simpler using a single index (or base) register.</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code> ORG 100h\n\n mov cl, n\n mov ch, -128 ;Array has numbers ranging from -128 to +127\n jcxz Done ;In case the array is empty\n mov si, array\nMore:\n cmp [si], ch\n jle NotBigger\n mov ch, [si] ;New MAX goes from -128 -> 4 -> 69\nNotBigger:\n inc si\n dec cl\n jnz More\nDone:\n ret ;Back to DOS\n\narray DB 04h, 45h, 32h, 23h, 09h\nn DB 5\n</code></pre>\n\n<hr>\n\n<p>For a faster code, because that's what you get with <strong>less jumping around</strong> (but not necessarily less jump instructions!):</p>\n\n<p>If the array has <strong>unsigned</strong> numbers use <code>mov ch, 0</code> and also <code>jbe More</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ORG 100h\n\n mov cl, n\n mov ch, 0 ;Array has numbers ranging from 0 to 255\n mov si, array-1\nMore:\n inc si\n sub cl, 1\n jb Done ;Happens first time if the array is empty\n cmp [si], ch\n jbe More ;NotBigger\n mov ch, [si] ;New MAX goes from 0 -> 4 -> 69\n jmp More\nDone:\n ret ;Back to DOS\n\narray DB 04h, 45h, 32h, 23h, 09h\nn DB 5\n</code></pre>\n\n<p>The speed gain comes from the fact that a conditional jump that is <strong>taken</strong> requires many more cycles than a conditional jump that is <strong>not taken</strong>.</p>\n\n<hr>\n\n<p>If the array has <strong>signed</strong> numbers use <code>mov ch, -128</code> and also <code>jle More</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> ORG 100h\n\n mov cl, n\n mov ch, -128 ;Array has numbers ranging from -128 to +127\n mov si, array-1\nMore:\n inc si\n sub cl, 1\n jb Done ;Happens first time if the array is empty\n cmp [si], ch\n jle More ;NotBigger\n mov ch, [si] ;New MAX goes from -128 -> 4 -> 69\n jmp More\nDone:\n ret ;Back to DOS\n\narray DB 04h, 45h, 32h, 23h, 09h\nn DB 5\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-18T15:21:58.503",
"Id": "224416",
"ParentId": "223864",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223913",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:14:19.130",
"Id": "223864",
"Score": "5",
"Tags": [
"assembly",
"x86"
],
"Title": "Find the maximum number in an array of numbers"
} | 223864 |
<p>I am trying to improve the following code to make it more broadly applicable and quick to use.</p>
<pre><code># IMPORTS
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.optimize import curve_fit
# THE INEFFICIENT PARSING: SELECTING VALUES FROM SEVERAL TABLES ONE BY ONE
skip_bottom_lines = 5 # currently i skip all lines but one at the time, cumbersome
skip_top_lines = (7-skip_bottom_lines) # always number of picked picks + 1
residue_id = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 0, dtype = str, delimiter = "-")
a_value00 = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
a_value01 = np.genfromtxt("322.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
a_value02 = np.genfromtxt("323.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)
...
a_valueXX
a_noise00 = np.genfromtxt("321.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
a_noise01 = np.genfromtxt("322.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
a_noise02 = np.genfromtxt("323.list", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 6, unpack = True)
...
a_noiseXX
# NORMALIZATION OF SAID PARSED VALUES
a_norm00 = a_value00/a_value00
a_norm01 = a_value01/a_value00
a_norm02 = a_value02/a_value00
...
a_normXX
a_noiseval00 = a_norm00/a_noise00/2
a_noiseval01 = a_norm01/a_noise01/2
a_noiseval02 = a_norm02/a_noise02/2
...
a_noisevalXX
# FITTING AND PLOTTING
spin_lock_durations = (0.005, 0.010, 0.020, 0.050, 0.100)
y_signal_a = (a_norm00, a_norm01, a_norm02,..., a_normXX)
e_signal_a = (a_noiseval00, a_noiseval01, a_noiseval02,..., a_noisevalXX)
new_x = np.linspace(0, 0.105)
def exp_decay():
x = spin_lock_durations
y_signal_a = (a_norm00, a_norm01, a_norm02,..., a_normXX)
x = np.array(x, dtype = float)
y_signal_a = np.array(y_signal_a, dtype = float)
plt.errorbar(x, y_signal_a, yerr = e_signal_a, fmt = ".k", markersize = 8, capsize = 3)
def exp(x, a, b):
return a * np.exp(-b * x)
popt, pcov = curve_fit(exp, x, y_signal_a)
par_err = np.sqrt(np.diag(pcov))
print(par_err)
plt.plot(new_x, exp(new_x, *popt))
plt.tight_layout()
plt.show()
exp_decay()
</code></pre>
<p>All the tables (321.list, 322.list, etc.) are formatted in exactly the same manner, so I am confident the process can be improved via a for loop of some kind. I am currently trying to import all the files and parse them via the following:</p>
<pre><code>for file in os.listdir('.'): # loop through all the files in your current folder
if file.endswith('.list'): # find .list files
file_name, file_extension = os.path.splitext(file) # split file name and extension
tot_data = pd.read_fwf(file, header = 0) # import data
print(tot_data)
</code></pre>
<p>But then, I fail at selecting the correct columns and proceed with the fitting plotting.</p>
<p>One file looks like:</p>
<pre class="lang-none prettyprint-override"><code> Assignment w1 w2 w1 (Hz) w2 (Hz) Data Height S/N
X1H-H 9.482 9.482 7588.56 7588.56 926279 129
C4H7-H7 9.419 9.419 7538.63 7538.59 2029781 282
</code></pre>
<p>Any help would be enormously appreciated! Thanks for your time!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:38:26.193",
"Id": "434093",
"Score": "0",
"body": "I am failing at making it better. The original, inefficient code works.\nI am trying to parse all the relevant entries at the same time without calling them one by one the way I do now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:14:19.337",
"Id": "434096",
"Score": "0",
"body": "so to clarify, `a_value00 = np.genfromtxt(\"321.list\", skip_header = skip_top_lines, skip_footer = skip_bottom_lines, usecols = 5, unpack = True)` reads 1 value from a file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:20:38.393",
"Id": "434097",
"Score": "0",
"body": "@MaartenFabré exactly! by changing skip_top_lines (and thus skip_bottom_lines) I select a specific entry in each of the files. It would be much better if I can write the script so that it would do this automatically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:40:52.053",
"Id": "434102",
"Score": "0",
"body": "A problem I just realized, but is very relevant, it that the files have mixed delimiters (distinct number of white spaces from column to column, which is the reason why I am unable to generate a proper df.DataFrame. I am currently focusing on this issue."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T13:21:42.597",
"Id": "223865",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"numpy",
"pandas",
"matplotlib"
],
"Title": "Parsing and plotting with numpy (or pandas)"
} | 223865 |
<p>I am new to C, and I have very little formal education on programming (Although I am currently in college). I work as a Robot Automation technician, and me and my team are required to document a lot of things. I wrote a program that we run on our robot computers to do this, but the language (RAPID by ABB Robotics) had its limitations, and the versions of operating systems vary from machine to machine. To get to the point, I decided that I need to re-write the application in a general language that would be better suited for this.</p>
<p>This code works, although I did not include the header files or other C files that are included to make this run because I am mainly looking for constructive criticism on the readability and design of this code. If necessary I can provide the other files, but I don't think they will be needed for what I'm asking.</p>
<p>Basically, this program reads the source code that I have pasted in a text file and writes all of the data to a csv file, which is then pasted into an Excel workbook that is formatted as a report.</p>
<p>In the text file that contains the source code that this program reads, there is an 80×15 array that I need all of the data from, and then there Is a procedure in the program that I look for after that.</p>
<p>In the 80×15 array, each array represents a robot position, and each index is a value that is used for that position. 4 of the digits are whole numbers that actually represent a binary byte, while the other 2 digits are a float and a whole number. All of the data that I get from the array goes into a struct array that is in another C file.</p>
<p>After the array is read, it looks for a procedure called <code>SPRAY_POSITIONS()</code>. In this function we have all the statements that tell the robot how to move and etc, For each statement, I increment my counter, and when the <code>RETURN</code> statement is reached, it will exit and store the total positions used in that function. Most of this data is also stored in the same struct array. </p>
<p>The syntax of the source code being read is similar to C, so it may help to just imagine that I'm parsing a C source code for an array declaration and a function declaration, and am extracting the necessary information from the code. </p>
<p>I apologize in advance if this is not a good question for this site, but I'm the only one at my work that knows how to program anything besides an <code>if</code>/<code>else</code> statement or a <code>loop</code>, and I definitely want to get some feedback on my code so that I can improve. Thank you all for your time!</p>
<pre><code> /******************************************************************************
* Title: Rapid Parser
* Author:
* Date: 7/5/2019
*
*
*
* Purpose:
* 1) Parses a RAPID source file and extracts the following data ->
* ! Sweep Patterns
* ! Dwell Patterns
* ! Sweep Speeds
* ! Dwell Times
* ! Movement type 'j,l,c'
* ! Total Positions Used
*
* 2) Sets all data from purpose #1 to the sprayPositions structure array
*
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "spray_positions.h"
#include "Rapid_Parser.h"
#define RAPID_FILEPATH "rapid_program.txt"
#define MAX_STR_LENGTH 1000
#define COVER_HALF 1
#define EJECTOR_HALF 2
#define TRUE 1
#define FALSE 0
typedef int bool;
//Prototypes
static char* removeWhiteSpace(char* string);
static char* getDwellTime(char* line, int linePosition);
static char* getSweepSpeed(char* line, int linePosition);
static char* getDwellPattern(char* line, int linePosition, int side);
static char* getSweepPattern(char* line, int linePosition, int side);
static char* reverseString(char* input);
static char* getNozzlePattern(int wholeNumber, int side);
static void getAdditionalCommands(char* line);
static void getZoneType(char* line);
static void getMoveType(char* line);
static void updateLineIndex(int counter);
static bool checkForReturn(char* line);
static bool findWord(char* string, char* substring);
static void readSrcFile();
static void openSrcFile();
int getTotalPositions();
static FILE *fp;
static int totalSprayPositions = 1;
static int currentLineIndex = 0; //Used to update line index
static bool foundSprayFunctionArray = FALSE;
static bool foundSprayPositions = FALSE;
static void readSrcFile()
{
char ch;
char dwellTime[5] = {0};
char sweepPattern[10] = {0};
char dwellPattern[10] = {0};
char sweepSpeed[5] = {0};
char currentLine[MAX_STR_LENGTH] = {0};
//Boolean type integers
bool insideBrackets = FALSE;
//Counters
int i;
int currentPosition = 0; //Same as dim1, but used for readability
int dim1 = 0; //Array dimension 1
int dim2 = 0; //Array dimension 2
//Array Indexes for dimension 2
int sweepA = 0;
int sweepB = 1;
int dwellA = 5;
int dwellB = 6;
int speed = 10;
int time = 11;
while (fgets (currentLine, MAX_STR_LENGTH, fp) != NULL)
{
//Convert line to uppercase to simplify string comparison
strupr (currentLine);
if (findWord (currentLine, "PERS NUM SPRAY_FUNCTION{80,15}"))
foundSprayFunctionArray = TRUE;
if (findWord (currentLine, "PROC SPRAY_POSITIONS()"))
foundSprayPositions = TRUE;
//If the sprayFunction array is found, read it
if (foundSprayFunctionArray)
{
// Loop through current line
for (i = 0; i < strlen(currentLine); i++)
{
ch = currentLine[i];
//If we hit a ';' we know it's the end of the declaration
if (ch == ';')
{
foundSprayFunctionArray = FALSE;
break;
}
//Used to tell if we're in an array or not
if (ch == '[')
insideBrackets = TRUE;
else if (ch == ']')
insideBrackets = FALSE;
//If we're inside an array, and not at a comma
if ((insideBrackets) && (ch != '[') && (ch != ']') && (ch != ','))
{
//Sweep Pattern @ Index 0 & 1
if (dim2 == sweepA)
strcpy(sweepPattern, getSweepPattern(currentLine, i, COVER_HALF));
else if (dim2 == sweepB)
strcat(sweepPattern, getSweepPattern(currentLine, i, EJECTOR_HALF));
//Dwell Pattern @ Index 5 & 6
else if (dim2 == dwellA)
strcpy(dwellPattern, getDwellPattern(currentLine, i, COVER_HALF));
else if (dim2 == dwellB)
strcat(dwellPattern, getDwellPattern(currentLine, i, EJECTOR_HALF));
//Sweep Speed @ Index 10
else if (dim2 == speed)
strcpy(sweepSpeed, getSweepSpeed(currentLine, i));
//Dwell Time @ Index 11
else if (dim2 == time)
strcpy(dwellTime, getDwellTime(currentLine, i));
//Update Index counter
dim2++;
//Increment I to the current line index
i += currentLineIndex;
//Reset Index
currentLineIndex = 0;
//If all 15 elements have been read in array
if (dim2 == 15)
{
//Copy all data to position struct
setPositionSweepPattern(currentPosition, sweepPattern);
setPositionDwellPattern(currentPosition, dwellPattern);
setPositionSweepSpeed(currentPosition, sweepSpeed);
setPositionDwellTime(currentPosition, dwellTime);
////Reset sweepPattern, dwellPattern, sweepSpeed, Dwelltime
memset(dwellTime,0,sizeof(dwellTime));
memset(sweepSpeed, 0, sizeof(sweepSpeed));
memset(sweepPattern, 0, sizeof(dwellPattern));
memset(dwellPattern, 0, sizeof(dwellPattern));
//Update Current Array position, and reset dim2
currentPosition++;
dim1++;
dim2 = 0;
}
}
}
}
if (foundSprayPositions)
{
printf("%s\n", removeWhiteSpace(currentLine));
//If line isn't commented, read it
if (!findWord (currentLine, "!"))
{
if (checkForReturn(currentLine))
{
foundSprayPositions = FALSE;
//Print data for debugging
printArrayDataByPosition(totalSprayPositions);
system("pause");
break;
}
else
{
getMoveType(currentLine);
getZoneType(currentLine);
getAdditionalCommands(currentLine);
}
}
}
}
}
/* Checks to see if a certain substring exists in the line */
static bool findWord (char* string, char* substring)
{
if (strstr (string, substring) != NULL)
return TRUE;
else
return FALSE;
}
/* Opens the RAPID source file for reading */
static void openSrcFile()
{
fp = fopen (RAPID_FILEPATH, "r");
if (fp == NULL)
{
perror ("Error while opening the file\n");
exit (EXIT_FAILURE);
}
}
/* Closes the RAPID source file */
static void closeSrcFile()
{
printf("CLOSING RAPID SOURCE FILE\n");
fclose(fp);
}
/**********************************************************************
* Takes a whole number, checks the '1' bits to determine which
* Nozzles are turned on, then returns it as a string in readable format
*
* EX: (input)2 (input) 255
* (byte)00000010 (byte) 11111111
* (output) 2 (output) 12345678
*
* @param wholeNumber = The number representing the nozzle pattern
* @param side = cover or ejector half, to determing the starting nozzle
**********************************************************************/
static char* getNozzlePattern(int wholeNumber, int side)
{
char nozzlePattern[9] = {0};
char* ptr = malloc(sizeof(char)*sizeof(nozzlePattern));
int i,j=0;
int startingNozzle = 0;
memset(ptr, 0, sizeof(nozzlePattern));
if (side == EJECTOR_HALF)
startingNozzle = 2;
for (i = 8; i > 0; i--)
{
if (wholeNumber & 1 << (i-1))
{
nozzlePattern[j] = (i + startingNozzle) + '0';
j++;
}
}
strcpy(ptr, nozzlePattern);
strcpy(ptr, reverseString(ptr));
return ptr;
}
/**********************************************************************
* Takes a string as input, returns that same string reversed
* Used to reverse the order a nozzle pattern to read from left to right
* But also may be used to reverse any string
**********************************************************************/
static char* reverseString(char* input)
{
int i,j;
int stringSize = strlen(input);
char* output = malloc(sizeof(char)*stringSize+1);
memset(output, 0, stringSize+1);
for (i = stringSize, j = 0; i > 0; i--, j++)
output[j] = input[i-1];
return output;
}
/**********************************************************************
* Checks current line for 'MOVEJ', 'MOVEL', 'MOVEC' commands
* If present, sets the movement type for the current spray position
**********************************************************************/
static void getMoveType(char* line)
{
int i;
char* moveType[] = {"MOVEJ", "MOVEL", "MOVEC"};
size_t arraySize = sizeof(moveType)/sizeof(moveType[0]);
for (i = 0; i < arraySize; i++)
{
if (findWord (line, moveType[i]))
{
setPositionMoveType(totalSprayPositions-1, moveType[i]);
break;
}
}
}
/**********************************************************************
* Checks the current line for zone/fine commands
* If present, sets the zone type for the current spray position
**********************************************************************/
static void getZoneType(char* line)
{
int i;
char* zoneType[] = {"FINE", "Z200", "Z150", "Z100", "Z80", "Z60", "Z50", "Z40", "Z30", "Z20", "Z15", "Z10", "Z5", "Z1"};
size_t arraySize = sizeof(zoneType)/sizeof(zoneType[0]);
for (i = 0; i < arraySize; i++)
{
if (findWord (line, zoneType[i]))
{
setPositionZoneType(totalSprayPositions-1, zoneType[i]);
totalSprayPositions++;
break;
}
}
}
/**********************************************************************
* Checks the current line for other commands such as ->
* Commands for cores in, blasters, etc
* If present, it will put that line in the additional commands
* Attribute for the current position
**********************************************************************/
static void getAdditionalCommands(char* line)
{
int i;
char* otherCommands[] = {"PULSEDO", "SET", "RESET", "WAITDO", "WAITDI"};
size_t arraySize = sizeof(otherCommands)/sizeof(otherCommands[0]);
for (i = 0; i < arraySize; i++)
{
if (findWord (line, otherCommands[i]))
{
setPositionAdditionalCommands(totalSprayPositions-1, removeWhiteSpace(line));
break;
}
}
}
/************************************************************************
* Checks to see if the *RETURN statement is present in the line
* If it is, decrement the total positions and return true
************************************************************************/
static bool checkForReturn(char* line)
{
if (findWord (line, "RETURN"))
{
totalSprayPositions--;
printf ("TOTAL POSITIONS: %d\n", totalSprayPositions);
return TRUE;
}
else
return FALSE;
}
/**********************************************************************
* Gets the whole number that represents the *SWEEP* nozzle pattern
* Breaks it down to binary, then flips it and formats it to read
* as we would write it '1234'
**********************************************************************/
static char* getSweepPattern(char* line, int linePosition, int side)
{
int i;
char temp[5] = {0};
char* pattern = malloc(sizeof(char) * 10);
memset(pattern, 0, 10);
for (i = 0; line[linePosition+i] != ','; i++)
temp[i] = line[i+linePosition];
updateLineIndex(i);
//Sweep A
if (side == COVER_HALF)
strcpy(pattern, getNozzlePattern(atoi(temp), COVER_HALF));
//Sweep B
else
strcpy(pattern, getNozzlePattern(atoi(temp), EJECTOR_HALF));
return pattern;
}
/**********************************************************************
* Gets the whole number that represents the *DWELL* nozzle pattern
* Breaks it down to binary, then flips it and formats it to read
* as we would write it '1234'
**********************************************************************/
static char* getDwellPattern(char* line, int linePosition, int side)
{
//printf("Getting dwell pattern side %d\n", side);
int i;
char temp[5] = {0};
char* pattern = malloc(sizeof(char) * 10);
memset(pattern, 0, 10);
for (i = 0; line[linePosition+i] != ','; i++)
temp[i] = line[i+linePosition];
updateLineIndex(i);
//DWELL A
if (side == COVER_HALF)
strcpy(pattern, getNozzlePattern(atoi(temp), COVER_HALF));
//DWELL B
else
strcpy(pattern, getNozzlePattern(atoi(temp), EJECTOR_HALF));
return pattern;
}
/**********************************************************************
* Starts at the current line position, reads it until it hits a comma
* Then sets the sweep speed attribute for the current spray position
* Updates the line position also
**********************************************************************/
static char* getSweepSpeed(char* line, int linePosition)
{
int i;
char temp[5] = {0};
char* speed = malloc(sizeof(char) * 6);
memset(speed, 0, sizeof(temp));
//printf("Getting sweep speed\n");
for (i = 0; line[linePosition+i] != ','; i++)
temp[i] = line[i+linePosition];
updateLineIndex(i);
strcpy(speed, temp);
return speed;
}
/**********************************************************************
* Starts at the current line position, reads it until it hits a comma
* Then sets the dwell time attribute for the current spray position
* Updates the line position also
**********************************************************************/
static char* getDwellTime(char* line, int linePosition)
{
int i;
char temp[5] = {0};
char* time = malloc(sizeof(char) * 5);
memset(time, 0, sizeof(temp));
//printf("Getting Dwell Time\n");
for (i = 0; line[linePosition+i] != ','; i++)
temp[i] = line[linePosition + i];
updateLineIndex(i);
strcpy(time, temp);
return time;
}
/**********************************************************************
* Updates the line position after a function has parsed the line
* looking for information such as sweep speed, dwell time, etc
* to keep up with the position in the array
*
* ex: starting character for sweep speed may be 5,
* but the value may be 5000, so we would need to update
* the line position after the other 3 characters were read
**********************************************************************/
static void updateLineIndex(int counter)
{
currentLineIndex += counter;
}
/******************************************************************
* Takes a string as input, returns it without tabs or spaces
* Used to put whole line into the additional commands
* Attribute, but can be used for any string
******************************************************************/
static char* removeWhiteSpace(char* string)
{
int i;
int j;
int len = strlen(string);
char ch;
char carriageReturn = '\r';
char lineFeed = '\n';
char space = ' ';
char tab = '\t';
char* result = malloc(sizeof(char)*len+1);
memset(result, 0, len+1);
j=0;
for (i=0; i<len; i++)
{
ch = string[i];
if ((ch == carriageReturn) || (ch == lineFeed))
break;
if ((ch != space) && (ch != tab))
{
result[j] = ch;
j++;
}
}
result[j] = '\0';
return result;
}
int getTotalPositions()
{
return totalSprayPositions;
}
/* Global function that is called by main */
void getDataFromRapidSrcFile()
{
openSrcFile();
readSrcFile();
closeSrcFile();
}
</code></pre>
<p>The Spray Positions header contents</p>
<pre><code>/************************************************************************
* The functions in this module are used
* to set data for a spray position struct
* There are 80 structures created, since
* there are a max of 80 spray positions.
*
* @param positionNumber is the current
* spray position to be updated
*
* @param movement type is the type of move
* used in that position, L,J,C
*
* @param zoneType is the type of zone used
* in the position, FINE,Z1-100
*
* @param additionalCommands is used to
* store other commands associated with a certain
* position such as SET, RESET, PULSDO etc
*
* @param sweepPattern is the formatted version
* of the binary byte that tells us which nozzles
* are turned on during the sweep function for the
* specified position.
* Example: *0011* would translate to *12* and *12*
* would be the pattern used
*
* @param dwellPattern is the same as the sweepPattern,
* but is used to show which nozzles are on during the
* dwell function of the specified position
*
* @param sweepSpeed is how fast the robot is moving
* to the specified position
*
* @param dwellTime is how long the robot stays
* at the specified position before moving to the
* next positon
**************************************************************************/
void setPositionMoveType(int positionNumber, char* movementType);
void setPositionZoneType(int positionNumber, char* zoneType);
void setPositionAdditionalCommands(int positionNumber, char* additionalCommands);
void setPositionSweepPattern(int positionNumber, char* sweepPattern);
void setPositionDwellPattern(int positionNumber, char* dwellPattern);
void setPositionSweepSpeed(int positionNumber, char* sweepSpeed);
void setPositionDwellTime(int positionNumber, char* dwellTime);
void writeSprayData(int totalSprayPositions, FILE* fp);
/* Used for debugging, prints all data for each position that is used */
void printArrayDataByPosition(int position);
</code></pre>
<p>The rapid parser header file (I don't think I actually should have included this in my main code because It comes from the same module)</p>
<pre><code>/*********************************************************
* Gets all of the data stored in the program file
* Then updates each spray position struct
* With the information obtained from that file
*********************************************************/
void getDataFromRapidSrcFile();
/* Returns the total amount of spray positions in use */
int getTotalPositions();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:54:33.860",
"Id": "434117",
"Score": "0",
"body": "the posted code includes two 'home grown' header files, but fails to post the contents of those files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:05:32.587",
"Id": "434120",
"Score": "0",
"body": "@user3629249 apologies, I posted them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:56:41.493",
"Id": "434460",
"Score": "0",
"body": "Whenever I see code where someone is manually parsing text like this, my first question has to be, why are not just using a proper lexer/parser? I'm sure this would be a lot more maintainable if you used Flex/Bison or similar. Personally I like Boost::Spirit though that's C++ only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:18:47.610",
"Id": "434463",
"Score": "0",
"body": "@SeanBurton wow I can't believe I didn't think of that lol. I will definitely look into what you posted, but I still plan on finishing this project because the main goal is to gain a deeper understanding of C as well as programming in general."
}
] | [
{
"body": "<p>Regarding:</p>\n\n<blockquote>\n<pre><code>char* speed = malloc(sizeof(char) * 6);\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p>The expression <code>sizeof(char)</code> is defined in the C standard as 1. Multiplying anything by 1 has no effect and just clutters the code, making it more difficult to understand, debug, etc.</p></li>\n<li><p>When calling any of the heap allocation functions: <code>malloc()</code> <code>calloc()</code> <code>realloc()</code>, always check (!=NULL) the returned value to assure the operation was successful. </p></li>\n<li><p>It is a poor programming practice to use dynamic memory allocation (the call to <code>malloc()</code>) in an embedded application.</p></li>\n</ol>\n\n<hr>\n\n<p>Regarding:</p>\n\n<blockquote>\n<pre><code>char temp[5] = {0};\nchar* speed = malloc(sizeof(char) * 6);\n\nmemset(speed, 0, sizeof(temp));\n</code></pre>\n</blockquote>\n\n<p>The call to <code>malloc()</code> allocated 6 bytes, but <code>sizeof temp</code> is only 5 bytes. The result is that the last byte of <code>speed</code> is not initialized.</p>\n\n<p>Suggest calling <code>calloc()</code> rather than <code>malloc()</code>, which will initialize the allocated memory to all <code>0x00</code>.</p>\n\n<p>Regarding the numbers 5, 6. 10.</p>\n\n<p>These are 'magic' numbers. 'magic' numbers have no basis. Suggest using an <code>enum</code> statement or <code>#define</code> statements to give those 'magic' numbers meaningful names, then use those meaningful names throughout the code.</p>\n\n<p>regarding: </p>\n\n<pre><code>typedef int bool;\n</code></pre>\n\n<p>there is already the header file: <code>stdbool.h</code> which defines <code>bool</code>, <code>true</code>, <code>false</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:15:55.090",
"Id": "434175",
"Score": "8",
"body": "To be fair I think that `element_type *foo = malloc(sizeof(element_type) * n_elements)` is a perfectly good thing to write, and if the type happens to be `char` then so be it... it's consistent and there's absolutely no loss in understandability. It's not \"clutter\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:14:53.570",
"Id": "434180",
"Score": "2",
"body": "@hobbs I think it's objectively safer to use the variable, and not its type, as argument of `sizeof`. `ptr = malloc(sizeof(*ptr) * nmemb);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:35:45.927",
"Id": "434183",
"Score": "0",
"body": "@CacahueteFrito, The `ptr = malloc( sizeof( *ptr ) * nmemb );` Has the problem that `sizeof( *ptr )` (in the posted code ) would be the size of a char I.E. 1, Not what is wanted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:36:53.427",
"Id": "434184",
"Score": "0",
"body": "@hobbs, It is clutter to write code that does nothing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:50:24.060",
"Id": "434187",
"Score": "4",
"body": "@user3629249 The code does not do nothing - it tells maintainers of the code what object we want multiples of. Code that conveys information to humans is significantly more important than code that gets compiled to machine instructions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:17:56.400",
"Id": "434202",
"Score": "2",
"body": "`...poor programming practice to use dynamic memory allocation ... in an embedded application` you got a citation for that? If the system *has* a heap then why not use it? I should add, don't use it like this though, it has a leak (which I'm going to add as an answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:04:31.717",
"Id": "434222",
"Score": "1",
"body": "If we do pointlessly multiply by 1, we should at least multiply the whole size by 1: eg `result = malloc(sizeof(char)*len + 1)` should be `result = malloc(sizeof *result * (len+1))` so that if it's changed to a `wchar_t`, we allocate a whole `wchar_t` for the terminating null."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:54:11.043",
"Id": "434360",
"Score": "0",
"body": "@Rodney, In embedded applications, 1) either allocate ALL the needed heap at the very beginning of the program and free before exiting the program (perhaps via a `atexit()` statement.) Or always use 'static' arrays. Messing with dynamic allocation is a good way to ruin an embedded application"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:58:10.900",
"Id": "434361",
"Score": "0",
"body": "The OPs code has statements like: `char* ptr = malloc(sizeof(char)*sizeof(nozzlePattern));` Which means `*ptr` is the size of a pointer, not what the OP wants"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T23:36:45.603",
"Id": "434370",
"Score": "0",
"body": "@TobySpeight, changing `sizeof(char)*len +1` to `sizeof( *result ) * (len+1)` does not make the characters allocated into `wchar_t` Remember that in all cases, the OPs target variable is `char *result` So `*result` is the size of a pointer, which (depending on the underlying architecture) could be 4 or 8 bytes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T23:44:39.620",
"Id": "434372",
"Score": "0",
"body": "@TobySpeight, If you want wide characters, then a reasonable method is : `wchar_t *ptr = malloc( sizeof( wchar_t ) * len );` Of course then you will need to use `L` infront of strings so they are wide characters and `wprintf()` for printing, and etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:33:52.717",
"Id": "434413",
"Score": "0",
"body": "@user3629249: no, you still need to multiply by `(len + 1)`, i.e. `wchar_t *ptr = malloc(sizeof *ptr * (len+1));`, **not** `(sizeof *ptr * len + 1)`. It's important that the terminating null is the same size as the characters, rather than always being 1 `char` in size. And I think you misunderstood when you say \"in all cases, ... `char *result`\" - I was specifically referring to an alternative with `wchar_t *result`. And `*result` is *not* the size of a pointer; `result` is a pointer, `*result` is the pointed-to type."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:10:30.957",
"Id": "223883",
"ParentId": "223869",
"Score": "4"
}
},
{
"body": "<p>These declarations are not prototypes:</p>\n\n<blockquote>\n<pre><code>void getDataFromRapidSrcFile();\n\nint getTotalPositions();\n</code></pre>\n</blockquote>\n\n<p>These declare functions that can be called with any number of arguments. It appears that they should take no arguments; we indicate that like this:</p>\n\n<pre><code>void getDataFromRapidSrcFile(void);\n\nint getTotalPositions(void);\n</code></pre>\n\n<p>It's a good idea to make the same change where the functions are defined, too.</p>\n\n<hr>\n\n<p>You could remove a repetitive (error-prone) construct using a macro to determine the number of elements in an array:</p>\n\n<pre><code>#define ARRAY_SIZE(x) (sizeof (x) / sizeof (x)[0])\n</code></pre>\n\n<hr>\n\n<p>Sorry I didn't get time for a full review of this - you do have a few other good answers now, though. If you ask a new question to review your improved code, then I hope to be able to look at that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:59:55.857",
"Id": "434179",
"Score": "3",
"body": "For completeness: C17::6.11.6:\n\n*\"Function declarators\n\nThe use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.\"*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:07:03.223",
"Id": "434461",
"Score": "0",
"body": "@Toby Speight hey no problem man, I'm grateful for any help I can get. I was a little concerned that this code would be hard to review since I'm assuming most of the people reading it probably don't work in robotics. It was a pleasant surprise to see so many people willing to help. And I do plan to apply the good suggestions people have provided, and repost it as soon as I get the time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T17:25:37.853",
"Id": "223889",
"ParentId": "223869",
"Score": "11"
}
},
{
"body": "<p>Functions should be very short: as a maximum, 2 or 3 screens (considering a screen size of 24 lines), but much less if possible; and shouldn't indent more than 2 or 3 levels of indentation normally. You should try to break that big fat function into a lot of small functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:11:52.387",
"Id": "223909",
"ParentId": "223869",
"Score": "6"
}
},
{
"body": "<p>You have a memory leak. Well several.</p>\n\n<p>All of the <code>static char *</code> functions allocate memory using <code>malloc()</code> which is never freed.</p>\n\n<p>Now let's take a look at how they are used, for example</p>\n\n<pre><code>strcpy(sweepSpeed, getSweepSpeed(currentLine, i));\n</code></pre>\n\n<p>So <code>getSweepSpeed()</code> is returning a pointer to a string, which is immediately copied into another string <code>sweepSpeed</code>, then the returned pointer is discarded and the buffer allocated by <code>getSweepSpeed()</code> is leaked.</p>\n\n<p>An alternative which would work here would be to get <code>getSweepSpeed()</code> to write its result directly into the buffer <code>sweepSpeed</code>. So the call becomes</p>\n\n<pre><code>getSweepSpeed(currentLine, i, sweepSpeed);\n</code></pre>\n\n<p>and the function definition becomes</p>\n\n<pre><code>static void getSweepSpeed(char* line, int linePosition, char * speed)\n</code></pre>\n\n<p>I'm sure you can do the rest..</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:16:23.733",
"Id": "434212",
"Score": "0",
"body": "Yes that does look like a better answer. I thought that function variables only existed in the function though, so I thought that the memory allocated inside the function would automatically free after the function is complete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:32:38.717",
"Id": "434214",
"Score": "2",
"body": "@RobotMan memory allocated with `malloc()` can only be freed using `free()`. The fact that you assigned the return value of malloc to a pointer which is local to that function does not mean the buffer it points to will be deallocated at the end of the function. Your buffer temp[] is automatically allocated and deallocated since temp *is* a buffer, not just a pointer to one. But you shouldn't return temp as this would be returning a pointer to a buffer that's been deallocated, which is undefined behaviour."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:30:25.693",
"Id": "223922",
"ParentId": "223869",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223889",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:24:12.040",
"Id": "223869",
"Score": "6",
"Tags": [
"beginner",
"c",
"parsing"
],
"Title": "Parse source code of the RAPID robot-automation language"
} | 223869 |
<p>I would like to know any suggestions about to improve my code solution and your rating of my approach to the problem, I based my code on the fact that if the strings have different length removing one character from the longer string is equal to add one character to the shorter one.</p>
<p><strong>Description</strong></p>
<blockquote>
<p>One away : There are three types of edits that can be performed on
strings: insert a character, remove a character and replace a
character. Given two strings, write a function to check if they are
one edit (or zero edits) away.</p>
</blockquote>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int helper_one_way(const char *str1, const char * str2,
size_t len1, size_t flag) {
size_t nchars = 0;
size_t i, j;
for (i = 0, j = 0; i < len1; ++i, ++j) {
if (str1[i] != str2[j]) {
if (++nchars > 1) return 0;
if (flag && i) --i;
}
}
return 1;
}
/* check if str1 can be obtained from string2 adding, deleting, replacing
* at last one char */
int one_way(const char *str1, const char *str2) {
size_t len1 = strlen(str1), len2 = strlen(str2);
size_t diff = abs(len1 - len2);
if (diff > 1) return 0;
if (!diff) return helper_one_way(str1, str2, len1, 0);
if (len1 > len2) return helper_one_way(str2, str1, len2, 1);
return helper_one_way(str1, str2, len1, 1);
}
int main(void) {
printf("%d\n", one_way("pale", "ple"));
printf("%d\n", one_way("pales", "pale"));
printf("%d\n", one_way("pale", "bale"));
printf("%d\n", one_way("pale", "bake"));
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T02:29:34.590",
"Id": "434196",
"Score": "0",
"body": "`adding, deleting, removing` what is the difference between the latter two items?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:37:59.437",
"Id": "434295",
"Score": "0",
"body": "@greybeard: I meant replacing but I wrote removing, I updated my post."
}
] | [
{
"body": "<p>This is more of a suggestion on substance than a review of the code style; I'll leave that for other reviewers.</p>\n\n<p>Your solution looks pretty good to me. I think you could streamline it a bit by doing it all in one shot, without checking the length of the strings first. For example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int one_way(const char *a, const char *b)\n{\n int misses = 0, ia = 0, ib = 0, missed_index = 0;\n while (a[ia] || b[ib]) {\n /* Characters at this position match? Keep going... */\n if (a[ia] == b[ib]) {\n if (a[ia]) ++ia;\n if (b[ib]) ++ib;\n /* Mismatched characters? */\n } else {\n /* Already missed once; backtrack if skipped earlier, or bail. */\n if (++misses > 1) {\n if (missed_index) {\n ia = missed_index;\n ib = missed_index;\n missed_index = 0;\n }\n else return 0;\n /* No misses yet... */\n } else {\n /* Skip buffer A ahead if its next char matches buffer B. */\n if (a[ia] && a[ia + 1] == b[ib]) {\n ++ia;\n missed_index = ia;\n }\n /* Skip buffer B ahead if its next char matches buffer A. */\n if (b[ib] && b[ib + 1] == a[ia]) {\n ++ib;\n missed_index = ib;\n }\n /* Skip both buffers ahead, if neither was skipped. */\n if (!missed_index) {\n if (a[ia]) ++ia;\n if (b[ib]) ++ib;\n }\n }\n }\n }\n return 1;\n}\n\n</code></pre>\n\n<p>You can test it out here: <a href=\"https://onlinegdb.com/B1C76fNZS\" rel=\"nofollow noreferrer\">https://onlinegdb.com/B1C76fNZS</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T22:43:51.707",
"Id": "434171",
"Score": "0",
"body": "Try `\"aa\"` and `\"ba\"`. Sorry I gave you the wrong test-case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:11:16.367",
"Id": "434174",
"Score": "1",
"body": "@Deduplicator thanks for catching that, had a feeling this wasn't quite complete. I think you could probably add something like this to let the other iterator \"catch up\" after this situation happens: http://beta.pastie.org/iH3jbXzFRKhh ... but it's not exactly model clean code at this point. Will think about this a bit and edit or remove this answer later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:28:16.790",
"Id": "434177",
"Score": "0",
"body": "I took a different approach which also resulted in a single traversal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:40:56.553",
"Id": "434185",
"Score": "0",
"body": "@Deduplicator I *think* it's fixed now, but I'm not even sure at this point. I like your solution better now that this one's gotten hairy; yours is actually closer to what I had in mind initially."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:07:02.263",
"Id": "223882",
"ParentId": "223872",
"Score": "3"
}
},
{
"body": "<p>Generally nice code: easy to read, good use of <code>const char*</code> for the string arguments.</p>\n<hr />\n<p>It's great that we have unit tests; we can improve them by making them self-checking:</p>\n<pre><code>/* return number of test failures (0 or 1) */\nint test_one_away(const char *str1, const char *str2, int expected)\n{\n const int actual = one_way(str1, str2);\n if (actual == expected)\n return 0;\n fprintf(stderr, "one_way \\"%s\\", \\"%s\\" expected %d but got %d\\n",\n str1, str2, expected, actual);\n return 1;\n}\n\n\nint main(void)\n{\n return\n + test_one_away("pale", "ple", 1)\n + test_one_away("pales", "pale", 1)\n + test_one_away("pale", "bale", 1)\n + test_one_away("pale", "bake", 0);\n}\n</code></pre>\n<hr />\n<p>We should add some more tests. When I start writing tests (usually before the production code) I usually write the very simplest tests first, probably passing <code>NULL</code> to exercise the error recovery. I'm going to assume that the code won't be testing for null pointers, but would certainly start with the next simplest case: are two empty strings within one change:</p>\n<pre><code> + test_one_away("" "", 1)\n</code></pre>\n<p>Then compare one- and two-character strings against the empty string, and for strings that differ by one or two deletions at the beginning, middle and end. A good guideline for testing functions that return a boolean value is to identify the boundaries where the result should change between false and true (e.g. remove one character from the front ⇒ true; remove two characters from front ⇒ false) and write one test for each side of that transition.</p>\n<p>Here's a test that exposes a <strong>bug</strong> in the code:</p>\n<pre><code> + test_one_away("pale", "ale", 1)\n</code></pre>\n<p>This is because we don't accept deletion of the first character:</p>\n<blockquote>\n<pre><code> if (flag && i) --i;\n</code></pre>\n</blockquote>\n<p>The fix is to remove the second part of the condition (remember, unsigned overflow is well-defined, and will exactly match the <code>++i</code> in the loop increment):</p>\n<pre><code> if (flag) --i;\n</code></pre>\n<hr />\n<p>I'm not sure why <code>flag</code> needs to be a <code>size_t</code>; a simple <code>int</code> should be sufficient. If/when we have access to a C99 compiler (which should be soon; it's around 20 years old now), we could include <code><stdbool.h></code> and make it a <code>bool</code>. It also needs a better name; I had to look to the call site to understand what it's for (it seems that a true value means that we're looking for a deletion rather than a replacement).</p>\n<hr />\n<p>The conditions in the wrapper function could be expressed more clearly with a single <code>switch</code> on the difference in length:</p>\n<pre><code>/* check if str1 can be obtained from string2 adding, deleting, removing\n * at last one char */\nbool one_way(const char *str1, const char *str2)\n{\n\n size_t len1 = strlen(str1);\n size_t len2 = strlen(str2);\n\n switch (len2 - len1) {\n case (size_t)-1: return helper_one_way(str2, str1, len2, true);\n case 0: return helper_one_way(str1, str2, len1, false);\n case 1: return helper_one_way(str1, str2, len2, true);\n default: return false;\n }\n}\n</code></pre>\n<hr />\n<p>We don't need to pass the length to <code>helper_one_way</code>, because it can simply stop when it reaches the terminating null char:</p>\n<pre><code> for (i = 0, j = 0; str1[i]; ++i, ++j) {\n</code></pre>\n<hr />\n<p>Given that we're iterating over strings, it's more idiomatic to use a char pointer than to repeatedly index into the string (though a good compiler ought to generate the same code):</p>\n<pre><code>static bool helper_one_way(const char *a, const char *b,\n bool allow_deletion)\n{\n size_t nchars = 0;\n while (*a) {\n if (*a++ != *b++) {\n if (++nchars > 1) return false;\n if (allow_deletion) --b;\n }\n }\n return true;\n}\n</code></pre>\n<hr />\n<p>Finally: the name - should <code>one_way</code> be spelt <code>one_away</code>?</p>\n<hr />\n<h1>Modified code</h1>\n<p>Applying the above suggestions, we get:</p>\n<pre><code>#include <stdbool.h>\n#include <string.h>\n\nstatic bool helper_one_away(const char *a, const char *b,\n bool allow_deletion)\n{\n size_t nchars = 0;\n while (*a) {\n if (*a++ != *b++) {\n if (++nchars > 1) return false;\n if (allow_deletion) --b;\n }\n }\n return true;\n}\n\n/* Return true if a can be obtained from string2 by adding,\n deleting, or removing at most one character */\nbool one_away(const char *a, const char *b)\n{\n switch (strlen(a) - strlen(b)) {\n case (size_t)-1: return helper_one_away(b, a, true);\n case 0: return helper_one_away(a, b, false);\n case 1: return helper_one_away(a, b, true);\n default: return false;\n }\n}\n\n\n/* Test code */\n\n#include <stdio.h>\n\n/* return number of test failures (0 or 1) */\nstatic int test_one_away(const char *a, const char *b,\n bool expected)\n{\n const int actual = one_away(a, b);\n if (actual == expected)\n return 0;\n fprintf(stderr, "one_away \\"%s\\", \\"%s\\" expected %d but got %d\\n",\n a, b, expected, actual);\n return 1;\n}\n\nint main(void)\n{\n return\n + test_one_away("", "", true)\n + test_one_away("", "a", true)\n + test_one_away("pale", "", false)\n + test_one_away("pale", "le", false)\n + test_one_away("pale", "ale", true)\n + test_one_away("pale", "pale", true)\n + test_one_away("pale", "pal", true)\n + test_one_away("pale", "pa", false)\n + test_one_away("pale", "ple", true)\n + test_one_away("ple", "pale", true)\n + test_one_away("pales", "pale", true)\n + test_one_away("pale", "bale", true)\n + test_one_away("pale", "bake", false);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:39:28.913",
"Id": "434306",
"Score": "0",
"body": "Great review, just one question: how you chose the strings being tested in the main() ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:44:23.160",
"Id": "434307",
"Score": "1",
"body": "Partly by reading the implementation (\"*I wonder if we've tested that line when `flag` is true and `i` is zero?*\") and partly by experience of known problem cases (empty strings, one-character strings). The rest were just copied uncritically from the original. For completeness, it might be worth having a test with a change (rather than insert/delete) of the first character, and of the last character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:51:53.087",
"Id": "434310",
"Score": "0",
"body": "Also, checking boundary conditions, where the result should flip from one to the other (e.g. remove one character from the front ⇒ true; remove two characters from front ⇒ false; no need to test three chars at front)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T18:11:18.260",
"Id": "223891",
"ParentId": "223872",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Using a <code>size_t</code> for a boolean flag, and calling it <code>flag</code>, is nearly an obfuscation. Use <code>int</code> pre-C99 and call it something descriptive like <code>substitute</code>.</p></li>\n<li><p><code>strlen()</code> is likely a waste, though it makes describing the algorithm easier. Try to do without the additional iteration.</p></li>\n<li><p>Getting the length of the longest common prefix looks like a well-defined task which can be extracted, and a useful building-block. Do so.</p></li>\n<li><p><code>one_way</code>, <code>one_away</code>, or <code>one_microsoft_way</code>? Having a properly-spelled correctly-selected name is Always very important.</p></li>\n<li><p>Change to a single-traversal algorithm:</p>\n\n<p>Remove the common prefix.</p>\n\n<p>Measuring the common prefix without the first characters is quite instructive.</p>\n\n<p>With <code>x</code> and <code>y</code> different from <code>a</code>, call <code>n = strlen_common(++a, ++b)</code>:</p>\n\n<ol>\n<li><p>At most one substitution at the start:</p>\n\n<pre><code>xaaaabcde\nyaaaabcde\n</code></pre>\n\n<p>Result n == 8, a[n] == b[n].</p></li>\n<li><p>Deletion from the first:</p>\n\n<pre><code>xaaaabcde\naaaabcde\n</code></pre>\n\n<p>n == 3, strcmp(a + n, b + n - 1) != 0</p></li>\n<li><p>Same way for deletion from second.</p></li>\n</ol></li>\n</ol>\n\n<p>The modified code (also <a href=\"http://coliru.stacked-crooked.com/a/ee6f59e4e5790ae9\" rel=\"nofollow noreferrer\">live on coliru</a>):</p>\n\n<pre><code>size_t strlen_common(const char* a, const char* b) {\n size_t r = 0;\n while (*a && *a++ == *b++)\n ++r;\n return r;\n}\n\nint one_away(const char* a, const char* b) {\n size_t n = strlen_common(a, b);\n a += n;\n b += n;\n if (!*a++)\n return !*b || !b[1];\n if (!*b++)\n return !*a;\n n = strlen_common(a, b);\n return a[n] == b[n]\n || !strcmp(a + n - 1, b + n)\n || !strcmp(a + n, b + n - 1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:45:54.873",
"Id": "434308",
"Score": "0",
"body": "Great review, as you described in the second point I will try your version without calling strlen()."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T21:19:52.337",
"Id": "223901",
"ParentId": "223872",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223891",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T14:33:04.483",
"Id": "223872",
"Score": "7",
"Tags": [
"algorithm",
"c",
"programming-challenge",
"edit-distance",
"c89"
],
"Title": "Cracking the Coding Interview — 1.5 One Away"
} | 223872 |
<p>I am currently refactoring a larger solution where the compiler gave multiple warnings about disposing the used <code>System.Timers.Timer</code> instances. The timers are running in short intervals so I would have to check before I dispose the timer if the elapsed callback is currently active. </p>
<p>Following the implementation with which I want to replace the <code>System.Timers.Timer</code> instances. </p>
<pre><code>public class DisposableSafeTimer : IDisposable
{
public event ElapsedEventHandler Elapsed;
private System.Timers.Timer _timer;
private readonly object _syncObject = new object();
private volatile bool _isDisposing = false;
public double Interval
{
get { return _timer.Interval; }
set { _timer.Interval = value; }
}
public DisposableSafeTimer()
{
_timer = new System.Timers.Timer();
_timer.Elapsed += _timer_Elapsed;
}
public void ExternalStart()
{
_timer.Start();
}
public void ExternalStop()
{
_timer.Stop();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
lock (_syncObject)
{
if(_isDisposing)
{
return;
}
if (disposing)
{
_isDisposing = disposing;
_timer.Stop();
_timer.Elapsed -= _timer_Elapsed;
_timer.Dispose();
}
}
}
private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (_syncObject)
{
if (_isDisposing)
{
return;
}
try
{
_timer.Stop();
Elapsed?.Invoke(sender, e);
}
finally
{
_timer.Start();
}
}
}
}
</code></pre>
<p>The Methods <code>ExternalStart()</code> and <code>ExternalStop()</code> are named with the intention that I get compiler errors wherever the <code>Timer.Start()</code> and <code>Timer.Stop()</code> methods are called. The stops and starts from the classes which use my timer implementation shouldn't care about the cyclic starts and stops of the internal timer.</p>
<p>So far I had no problems with my tests. I just want to make sure that I haven't overlooked something. Suggestions for improvements are welcome. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:39:58.290",
"Id": "434218",
"Score": "2",
"body": "What compiler errors do you get? It doesn't look like there would be any name conflicts..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:10:26.453",
"Id": "434242",
"Score": "0",
"body": "There are no Errors in the class. I want them to appear if the System.Timers.Timer is replaced with my implementation, as I can then check if the Start() and Stop() calls are valid."
}
] | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>property <code>Interval</code> and methods <code>ExternalStart</code>, <code>ExternalStart</code> should throw <code>ObjectDisposedException</code> if <code>_isDisposing</code> is <code>true</code></li>\n<li>property <code>Interval</code> and methods <code>ExternalStart</code>, <code>ExternalStart</code> should also acquire a lock on <code>_syncObject</code></li>\n<li>when implementing the <a href=\"https://stackoverflow.com/questions/898828/finalize-dispose-pattern-in-c-sharp\"><code>dispose pattern</code></a> make sure to include a destructor <code>~DisposableSafeTimer</code> or seal your class</li>\n<li><code>_isDisposing</code> should be renamed to <code>_disposed</code></li>\n<li>when disposing, you should also clean your event listeners <code>Elapsed = null</code> <a href=\"https://stackoverflow.com/questions/4526829/why-and-how-to-avoid-event-handler-memory-leaks\">to avoid a memory leak</a></li>\n<li>do you really want to put <code>Elapsed?.Invoke(sender, e);</code> inside the lock? Think about possible race conditions or other side effects. What if a registered listener calls <code>Dispose</code> in the listener?</li>\n<li>check out <a href=\"https://stackoverflow.com/questions/1042312/how-to-reset-a-timer-in-c\">different suggestions</a> to reset the timer. Yours is fine though.</li>\n<li>a tiny enhancement might be to create the lock only when it is <code>null</code> using <code>Interlocked.CompareExchange</code>, instead of immediately creating an instance.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:43:45.147",
"Id": "434207",
"Score": "1",
"body": "Why do you mean that it's necessary to implement a finalizer/destructor in this case? There isn't allocated any unmanaged resources to release here. The `Dispose()` should be sufficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:45:40.657",
"Id": "434208",
"Score": "0",
"body": "@HenrikHansen Recently someone asked about this exact scenario, where there are no unmanaged resources. I can't seem to find the post atm. Since the class is not sealed, it was considered good practice to create the destructor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:13:52.687",
"Id": "223884",
"ParentId": "223877",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code>private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n lock (_syncObject)\n {\n if (_isDisposing)\n {\n return;\n } \n try\n {\n _timer.Stop();\n Elapsed?.Invoke(sender, e);\n }\n finally\n {\n _timer.Start();\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>As dfhwze writes - you can't lock in this way because it's a candidate for race conditions. And the only reason - I can see - you have to do it, is because you halts the timer, while the event consumers do their job. This also means that you effectively hands over the timer interval to the laziest event handler. Theoretically that could be one that opens a modal message box (which is not closed because the operator is to lunch or on vacation) with an error or something else that prevent it from finishing its job - which will cause all consumers (on different threads) to wait, and you then effectively disables the benefits/necessity of the multithreaded design. I anticipate that you stop and start the timer here, because you don't want the event handlers to be called if the previous call hasn't returned?</p>\n\n<p>The above code actual acts as a single thread bottleneck that synchronize the threads with the slowest thread/event handler. Is that by design?</p>\n\n<p>If you want to let the different threads work independently of each other you could invoke each handler in a thread by it self:</p>\n\n<pre><code>private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n try\n {\n foreach (Delegate handler in Elapsed.GetInvocationList())\n {\n ThreadPool.QueueUserWorkItem(_ =>\n {\n handler.DynamicInvoke(sender, e);\n });\n }\n }\n finally\n {\n }\n}\n</code></pre>\n\n<p>The above doesn't prevent a handler to be called before the previous call to that handler has finished. To Handle that situation, you'll have to maintain a dictionary (<code>ConcurrentDictionary<Delegate, bool></code> for instancce) that controls if a handler is ready for a new call or not.</p>\n\n<p>I of course have no idea of which impact this will have on your application otherwise - you'll have to test that thoroughly. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:25:42.410",
"Id": "434227",
"Score": "0",
"body": "Is there a reason you favor _ThreadPool.QueueUserWorkItem_ over _SynchronizationContex.Current.Post_ or _Task.Run_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:35:31.220",
"Id": "434232",
"Score": "0",
"body": "@dfhwze: Not really, I just read the question as it's about an \"old school\" multithreaded environment so it was my first choice. Are there any good reasons to choose one of the others?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:37:48.870",
"Id": "434233",
"Score": "1",
"body": "In the order I posted them, they get a bit less performant, but with better API support for extensibility, continuations, error handling, dispatching to other threading models etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:08:13.773",
"Id": "434241",
"Score": "0",
"body": "It is a project that communicates with multiple PLC's. Each timer event is only consumed once by the class which creates the timer. In the Event handler, data is checked and written to the PLC. The write must finish before the timer can start again. Concerning the race conditions, how would you handle the check in the dispose method if the timer Event is currently running and wait for it to finish?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:19:12.343",
"Id": "434246",
"Score": "0",
"body": "_how would you handle the check in the dispose method if .._ You could use a semaphore or manualresetevent. I would ask a follow-up question if you desire this behavior. It's also good to know you have a single listener."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:20:29.460",
"Id": "434247",
"Score": "0",
"body": "@AFrueh: You could do that by maintaining a list of `AutoResetEvent` objects - one per thread"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:26:38.737",
"Id": "434277",
"Score": "0",
"body": "@HenrikHansen: I checked it with the `AutoResetEvent` which should be disposed as stated by the Compiler which I can then never set again. So the possible concurrent `_timer_Elapsed` will never finish. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:32:18.377",
"Id": "434291",
"Score": "0",
"body": "@AFrueh: But you'll have to keep track of which `AutoResetEvent`s that is active. Save them in a `ConcurrentDictionary<Delegate, AutoResetEvent>` and then in `Dispose()` you should check that and wait for them to signal. Before a call to a eventhandler you create an `AutoResetEvent` and when the event handler returns you call its `Set()` method, removes it from the dictionary and disposes if of. Inn `Dispose()` you dispose the remaining `AutoResetEvent`s when all are signaled."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:19:46.750",
"Id": "223924",
"ParentId": "223877",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223884",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:41:17.950",
"Id": "223877",
"Score": "7",
"Tags": [
"c#",
".net",
"memory-management",
"thread-safety",
"timer"
],
"Title": "Safe Dispose of Timer"
} | 223877 |
<p>Consider this code:</p>
<pre><code>class AssemblyFactory
{
public function makeAssembly(array $params)
{
if (array_key_exists('modelNumber', $params))
$pump = $pumpFactory->fromModelNumber($params['modelNumber']);
else if (array_key_exists('productId', $params))
$pump = $pumpFactory->fromProductId($params['productId']);
else
throw new \InvalidArgumentException("FAIL");
}
}
</code></pre>
<p>Is there a way to write this code better using PHP facilities? For example, I considered instead of <code>$params</code> to include <code>$modelNumber</code> and <code>$productId</code> directly, but I am not sure that it will be appropriate, since there will only be one legally valid parameter used at any one time.</p>
<p>Namely I need a way to create a pump using EITHER model number OR product id. </p>
<p>to call:</p>
<pre><code>$factory = new AssemblyFactory();
$pump = $factory->makeAssembly(array(
'productId' => 33
));
$pump = $factory->makeAssembly(array(
'modelNumber' => 'AAA-50'
));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T03:01:22.383",
"Id": "434198",
"Score": "0",
"body": "Does the params array possibly have more than one param? Semantics says yes, but your sample inputs say no. Might a params array have both identifiers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T04:28:58.693",
"Id": "434200",
"Score": "0",
"body": "Can you tell me how you hope to modify your code? Maybe I am misunderstanding the goal. Is this going the wrong direction? https://3v4l.org/C6h1o (IMOyou aren't doing anything \"bad\" with your posted code.) Do we need to see more of your code? `$pumpFactory` seems to fly in from nowhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:59:02.600",
"Id": "434311",
"Score": "0",
"body": "yes, `$params` can have more than one param. It can have other keys and values. It may even have both `productId` and `modelNumber` (doesn't matter which one takes precedence, although if required `productId` can take precedence over `modelNumber`). I was hoping for a way to better use PHP facilities, to where any errors with input or any other errors are shown early, so that I can fix them. Or there is more clarity in the code. With the array, it is not immediately clear what are the actual expected parameters, so future programmers will have harder time deciphering and understanding code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:38:01.630",
"Id": "434356",
"Score": "0",
"body": "I don't really see anything to improve. I find the code easy to read and straight forward."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:23:41.400",
"Id": "434465",
"Score": "0",
"body": "Thank you. My concern was that `$params` was hiding the parameters. i.e. not clear how many parameters there are, or if valid parameters are being passed."
}
] | [
{
"body": "<p>You could make your code \"more dynamic\" by creating a whitelist of \"actionable keys\" and the associated method name to be called, but that seems like unnecessary convolution.</p>\n\n<p>Your current method is direct and literal and <em>probably</em> makes sense to those on your development team. I only have a few minor suggestions, but overall you should keep your basic structure.</p>\n\n<p>It is not clear where <code>$pump</code> and <code>$pumpFactory</code> come from in your posted method, so I cannot offer advice on those variables. I also don't know what processes are actioned by the subsequent method calls, nor do I know the value type (boolean?, array?, string?, etc) or value of the return. A DocBlock would be a wise choice.</p>\n\n<pre><code>class AssemblyFactory\n{\n /**\n * Generates assembly data based on model number or product id.\n *\n * @param array $params An array of pump details expected\n * to contain model number or product id.\n *\n * @throws InvalidArgumentException if $params does not contain a \n * model number or product id.\n *\n * @return string Pump assembly name \n */\n public function makeAssembly(array $params)\n {\n if (array_key_exists('modelNumber', $params)) {\n return $pumpFactory->fromModelNumber($params['modelNumber']);\n }\n if (array_key_exists('productId', $params)) {\n return $pumpFactory->fromProductId($params['productId']);\n }\n throw new \\InvalidArgumentException(\"FAIL\");\n }\n}\n</code></pre>\n\n<p>When seemingly simple code doesn't feel clear enough (or if you really love documentation blocks), then use DocBlocks to explain your script and avoid misinterpretation or lost time in the future.</p>\n\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md\" rel=\"nofollow noreferrer\">PSR-5: PHPDoc</a></p>\n\n<p>Here's an example that is relevant to your code: <a href=\"https://docs.phpdoc.org/references/phpdoc/tags/throws.html\" rel=\"nofollow noreferrer\">https://docs.phpdoc.org/references/phpdoc/tags/throws.html</a></p>\n\n<p>Beyond your provided code, I feel that you should determine which lookup method is more efficient within your application (If this is a database lookup, is one column a Primary Key and another one not?). Make the more efficient process the default one.</p>\n\n<p>Alternatively, if you have two separate collections of data containing redundant data, consider merging the data storage so that only one lookup is necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T22:22:57.643",
"Id": "224064",
"ParentId": "223879",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224064",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T15:46:38.273",
"Id": "223879",
"Score": "1",
"Tags": [
"php",
"factory-method"
],
"Title": "Create a pump object from either one of pump model number or pump product id"
} | 223879 |
<p>The following code is checking if the user's browser is IE and if this is the case and there's no localStorage yet, it sets a localStorage, which should be valid for only 24 hours.</p>
<pre><code>(function ieAlert () {
var isIE = document.documentMode
var lastClear = window.localStorage.getItem('myLocalStorage')
var timeNow = (new Date()).getTime()
if (!isIE && lastClear === null) {
window.alert(ieWarningText)
// Setting a localStorage with 1 day expiry date
if ((timeNow - lastClear) > 1000 * 60 * 60 * 24) {
window.localStorage.clear()
window.localStorage.setItem('myLocalStorage', timeNow)
}
}
})()
</code></pre>
<p>How could the script be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T21:00:17.283",
"Id": "434153",
"Score": "0",
"body": "Might need more context on this one. Why do you need to clear the localStorage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T22:08:20.423",
"Id": "434160",
"Score": "0",
"body": "I just thought I need to clear the old localStorage after 24 hours and set a new one. Don't I need to clear it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:05:10.117",
"Id": "434173",
"Score": "0",
"body": "Your function does not make any sense. You check if `lastClear === null` then you subtract it (null) from the time. Thus the test `(timeNow - lastClear) > 8.64e7` will always pass (well apart from the first day of 1970) as `null` will be coerced to 0"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T16:16:57.833",
"Id": "223885",
"Score": "2",
"Tags": [
"javascript",
"cache",
"browser-storage"
],
"Title": "localStorage should expire after 24 hours"
} | 223885 |
<p>I just submitted this code to solve the <a href="https://www.codechef.com/problems/MEDIC" rel="nofollow noreferrer">"<strong>When to take medicine"</strong> challenge on CodeChef</a>:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <sstream>
int countDays(int dd, int subtract)
{
return ((subtract - dd) / 2) + 1;
}
int main()
{
int t {0};
std::cin >> t;
std::cin.ignore();
while (t--)
{
std::string date {};
std::getline(std::cin, date);
std::stringstream ss {date};
int yy {0}, mm {0}, dd {0};
std::string temp {};
std::getline(ss, temp, ':');
yy = std::stoi(temp);
std::getline(ss, temp, ':');
mm = std::stoi(temp);
std::getline(ss, temp, ':');
dd = std::stoi(temp);
int subtract {0};
bool leap {false};
if (yy % 4 == 0 && (!(yy % 100 == 0) || yy % 400 == 0))
leap = true;
switch (mm)
{
case 2:
if (leap)
subtract = 29;
else
subtract = 59;
break;
case 4: case 6: case 9: case 11:
subtract = 61;
break;
default:
subtract = 31;
}
std::cout << countDays(dd, subtract) <<'\n';
}
}
</code></pre>
<p>In short, it is a program to tell how many days a guy has took his pill correctly, considering that he has to take a pill every 2 days and only takes it in odd or even days, depending on the day he started to take the pill. We provide a number of test cases in the first line and then we provide a date in a single line in the format <code>yyyy:mm:dd</code>. Check the link above if you're interested in reading the whole problem. </p>
<p>The thing is that I am not really satisfied with the way I am parsing the <code>string</code> separated by the char <code>:</code></p>
<p>I also want to mention that I want to stay away from any C code like the <code>scanf()</code> function. It would make things a lot easier, but I don't want to use C in C++. </p>
<p>So, how could I redesign my string parse code to make it look nicer? I am just a newbie with C++ so all feedback / criticism is greatly appreciated.</p>
| [] | [
{
"body": "<ol>\n<li><p>You don't check whether the input is invalid.</p></li>\n<li><p>Try to extract useful well-named functions, like <code>int days(int month, int year)</code> and <code>bool is_leap_year(int year)</code>.</p></li>\n<li><p>You can extract the numbers directly from <code>std::cin</code>, the colon will be left behind.<br>\nAnd the colon can thereafter be extracted like any other single character.</p></li>\n<li><p>As an aside, using <code>scanf()</code> would probably be easier than juggling streams.</p></li>\n<li><p><code>break</code> should be indented like any other Statement. It does not deserve more indentation (first occurrence), nor less (second occurrence).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:25:08.923",
"Id": "434225",
"Score": "0",
"body": "1, 2, 3 - all good tips!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:25:40.723",
"Id": "434226",
"Score": "0",
"body": "4 - I just wanted to avoid using C code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:26:30.323",
"Id": "434228",
"Score": "0",
"body": "5 - I think that indentation was a copy / paste mistake. Overall, thanks for your review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:06:18.857",
"Id": "434302",
"Score": "0",
"body": "Re 4: There are projects doing their best to mate the usability of format-string driven `printf`/`scanf` with the safety, flexibility and potential performance of templates. It's just that this code shows `<iostream>` at its most cumbersome."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T21:51:33.903",
"Id": "223903",
"ParentId": "223888",
"Score": "2"
}
},
{
"body": "<p>It might be overkill for just the task at hand, but I've found it useful to write an overload of <code>operator>></code> to read and match a string literal:</p>\n\n<pre><code>std::istream &operator>>(std::istream &is, char const *s) { \n while (*s && *s == is.peek()) {\n ++s;\n is.ignore(1);\n }\n if (*s != '\\0')\n is.setstate(std::ios_base::failbit);\n return is;\n}\n</code></pre>\n\n<p>With this, reading in your data becomes much simpler, and (at least IMO) the intent becomes much more apparent:</p>\n\n<pre><code>int yy;\nint mm;\nint dd;\n\nstd::cin >> yy >> \":\" >> mm >> \":\" >> dd;\n</code></pre>\n\n<p>Depending on what you want/need, you can make this a bit more elaborate. For one example, it can be useful to have the literals act a little like scanf format strings, so any white space in the string matches an arbitrary amount of white space in the stream. You might also want to turn that behavior on/off, depending on whether the stream's <code>skipws</code> flag is set.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:29:00.163",
"Id": "434230",
"Score": "0",
"body": "What does the `*s && *s` mean? Not null?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:46:25.720",
"Id": "434236",
"Score": "0",
"body": "@msmilkshake: You have to look at the whole thing: `*s && *s == is.peek()`. The first `*s` is equivalent to `*s != 0`, so with a C-style string, it means \"we haven't reached the end of the string yet\". the second part is `*s == is.peek()`, which means the character in the string passed matches with the next character to be read from the stream."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:51:04.310",
"Id": "434262",
"Score": "0",
"body": "oh yea, operator precedence. i was not considdering it lol."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:43:47.963",
"Id": "223915",
"ParentId": "223888",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T17:17:14.787",
"Id": "223888",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"datetime",
"c++14"
],
"Title": "\"When to take medicine\" CodeChef Challenge MEDIC"
} | 223888 |
<p>I'd like some constructive feedback on the code that I have written to test the API for smartsh33t.com I wrote it in Python. </p>
<p>I wrote the program to take .json files and read them into the testrunner. then invoke the companies API for the create sheet functions, then record the results. </p>
<p>I am interested in general structural/design/architecture improvements and other feedback to improve future work. </p>
<pre><code>#! usr/bin/env python3
import json
import logging
import smartsheet
import smartsheet.exceptions
import smartsheet.models
import access_token
import urllib.error
# logger setup
logging.basicConfig(filename="err_log.txt", level=logging.ERROR, format=' %(asctime)s - %(levelname)s - %(message)s')
open("err_log.txt", "w")
# Initialize client, actual access token kept in local file only.
smartsheet_client = smartsheet.Smartsheet(access_token.token)
# Make sure we don't miss any errors
smartsheet_client.errors_as_exceptions(True)
class TestRunner:
passed: int
failed: int
test_count: int
# initial test setup
def __init__(self):
self.passed = 0
self.failed = 0
self.test_count = 0
# sheet 0 happy path test while sheets 1 & 2 throw errors
self.tests = ["Testrc/sheet0.json", "Testrc/sheet1.json", "Testrc/sheet2.json"]
self.json_files_to_test(self.tests)
# function to iterate through the files.
def json_files_to_test(self, json_tests):
for test in json_tests:
self.prepare_json_file(test)
# printing the pass/fail report for the tests.
print('\n\nTest Report')
print('====================================================')
print('tests passed = ' + str(self.passed))
print('tests failed = ' + str(self.failed))
print('percent of tests passing = ' + str(100*(self.passed/self.test_count)) + "%")
print('total number of tests = ' + str(self.test_count))
print('====================================================')
# load json files to be tested and then the tests to be run.
def prepare_json_file(self, test):
with open(test, "r+") as read_file:
read_json: object = json.load(read_file)
spec_sheet = smartsheet.models.Sheet(read_json)
self.create_test(smartsheet_client, spec_sheet)
self.create_in_folder_test(smartsheet_client, spec_sheet)
self.create_in_workspace_test(smartsheet_client, spec_sheet)
# sends a minimal sheet to be created in the Default folder(Home)
def create_test(self, ss_client, spec_sheet):
self.test_count += 1
try:
response = ss_client.Home.create_sheet(spec_sheet)
self.record_success(response)
except (smartsheet.exceptions.ApiError, urllib.error.HTTPError) as e:
logging.exception(e)
self.handle_exception(e, spec_sheet)
# sends a minimal sheet to be created in a folder by id
def create_in_folder_test(self, ss_client, spec_sheet):
self.test_count += 1
# found id via curl -X GET -H "Authorization: Bearer ttctt6u346l1wya2oxc0g80g2k"
# "https://api.smartsheet.com/2.0/home/folders"
folder_id = 2843491320522628
try:
response = ss_client.Folders.create_sheet_in_folder(folder_id, spec_sheet)
self.record_success(response)
except (smartsheet.exceptions.ApiError, urllib.error.HTTPError) as e:
logging.exception(e)
self.handle_exception(e, spec_sheet)
# sends a minimal sheet to be created in a workspace by id
def create_in_workspace_test(self, ss_client, spec_sheet):
self.test_count += 1
# found id via curl -X GET -H "Authorization: Bearer vpj1fg3b92qlorn6yibodw2w0u"
# "https://ai.smartsheet.com/2.0/workspaces"
workspace_id = 7730152571463556
try:
response = ss_client.Workspaces.create_sheet_in_workspace(workspace_id, spec_sheet)
self.record_success(response)
except (smartsheet.exceptions.ApiError, urllib.error.HTTPError) as e:
logging.exception(e)
self.handle_exception(e, spec_sheet)
def record_success(self, response):
parsed_json = json.loads(str(response))
print(parsed_json["result"]["name"] + " passed in the default instance")
self.passed += 1
def handle_exception(self, e, spec_sheet):
parsed_spec_sheet = json.loads(str(spec_sheet))
parsed_err = json.loads(str(e))
print(parsed_spec_sheet["name"] + "\nfailure = " + parsed_err["result"]["name"] + " " + str(
parsed_err["result"]["errorCode"]))
print(json.dumps(parsed_err, sort_keys=True, indent=4))
self.failed += 1
def print_test_results(self):
print('\n\n Test Report')
print('====================================================')
print('tests succeed = ' + str(self.passed))
print("tests failed = " + str(self.failed))
print('percent of tests passing = ' + str(100 * (self.passed / self.test_count)) + "%")
print('total number of tests = ' + str(self.test_count))
print('====================================================')
if __name__ == "__main__":
TestRunner()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T18:45:47.710",
"Id": "434136",
"Score": "2",
"body": "I sincerly hope this is not your real API token or that the token does not need to be confidential..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T20:54:04.200",
"Id": "435230",
"Score": "0",
"body": "@AlexV I recall editing it to not be valid, however, it has now been removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T22:39:08.533",
"Id": "436603",
"Score": "0",
"body": "@AlexV do you have any other feedback or critics? I can take it."
}
] | [
{
"body": "<p>I have no experience with smartsheet or their API, so there only will be general remarks regarding Python and testing.</p>\n\n<hr>\n\n<h2>Use a testing framework</h2>\n\n<p>You have started to write your own testing framework. Don't! There are a lot of battletested Python test frameworks out there that do all the tedious work for you, e.g. finding test cases, running them, and collecting their results in an appropriate, usually also configurable manner.</p>\n\n<p>Just to name the most common ones<sup>*</sup>:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\"><code>unittest</code></a>: comes directly with Python</li>\n<li><a href=\"https://nose.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\"><code>nose</code></a>/<a href=\"https://nose2.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\"><code>nose2</code></a>: an external library available through pip, which claims to \"extend unittest to make testing easier\". <code>nose2</code> is an extension of <code>nose</code> which claims to make testing even easier</li>\n<li><a href=\"https://docs.pytest.org/\" rel=\"nofollow noreferrer\"><code>pytest</code></a>: has a different flavor from the previous two, but also does the job quite good. This is what I actually use if I write tests.</li>\n</ul>\n\n<p>I invite you to have a look at all of them, where <code>unittest</code> and <code>nose</code> can likely be treated as equivalent with regard to the way they structure text. There is are a lot of different blog posts on that topic, e.g. on <a href=\"https://realpython.com/python-testing/\" rel=\"nofollow noreferrer\">RealPython</a> or <a href=\"http://pythontesting.net/start-here/\" rel=\"nofollow noreferrer\">PYTHON TESTING</a>, that show them either in comparison or separately.</p>\n\n<p>It might not make a big difference for what you want to do at the moment, but will make all the difference once you start to have more tests.</p>\n\n<h2>Use string formatting</h2>\n\n<p>If you bring together static text with variables to create dynmic output, it's usually better to use string formatting instead of manually <code>str(...)</code>inging all the variables and then concatenate them together. If you are working with Python 3.6 or higher, you can use <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">f-strings</a> to do this. An example from your code rewritten using f-strings:</p>\n\n<pre><code>def print_test_results(self):\n print('\\n\\n Test Report')\n print('====================================================')\n print(f'tests succeed = {self.passed}')\n print(f'tests failed = {self.failed}')\n print(\n f'percent of tests passing = {100 * (self.passed / self.test_count)}%'\n )\n print(f'total number of tests = {self.test_count}')\n print('====================================================')\n</code></pre>\n\n<p>There is also an <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">Real Python article</a> on this topic where the classical ways using <code>%</code> and <code>str.format(...)</code> are compared with the new f-strings.</p>\n\n<h2>Don't just open files</h2>\n\n<p>When you set up the logger, you do this:</p>\n\n<pre><code># logger setup\nlogging.basicConfig(filename=\"err_log.txt\", level=logging.ERROR, format=' %(asctime)s - %(levelname)s - %(message)s')\nopen(\"err_log.txt\", \"w\")\n</code></pre>\n\n<p>There is <em>no need</em> to do this and you also propably <em>should not</em> do it. <code>open(\"err_log.txt\", \"w\")</code> likely has no effect whatsoever on your program. <code>logging</code> will open the file itself before starting to write to it. Maybe it has even done so at that point. Apart from that <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\">it's good practice to use <code>open(...)</code> in conjuction with the <code>with</code>-statement</a> to make sure the file gets closed properly even in the case of an exception.</p>\n\n<hr>\n\n<p><sup>*</sup>Based on my experience while researching that topic quite a while ago.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T07:56:03.570",
"Id": "225017",
"ParentId": "223890",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "225017",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T18:00:08.243",
"Id": "223890",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "test oriented design; Python test script to test a company's API, print test results, log exceptions"
} | 223890 |
<p>I'm learning about the command design pattern and would like you to critique it for division of responsibility, especially with regards to how the robot "undoes" commands it previously executed and where those commands are stored (inside <code>RobotController</code>)</p>
<p>Everything seems to work correctly.</p>
<p>I do have a question: </p>
<p>If I were to create another receiver (say, <code>FlyingRobot</code>), is it customary to create another set of concrete commands for it? What would I have to change if I wanted receivers to share some commands but not others?</p>
<pre><code>from collections import deque, namedtuple
# Invoker
class RobotController(object):
inst_count = 0
def __init__(self, name=None, commands=None):
if not name:
self.name = f"RobotController #{RobotController.inst_count}"
else:
self.name = name
if not commands:
self._commands = deque()
else:
self._commands = commands
self.previously_executed_cmds = deque()
RobotController.inst_count += 1
def __str__(self):
return self.name
@property
def commands(self):
return self._commands
@commands.setter
def commands(self, other):
for cmd in other:
self._commands.append(cmd)
# Batch-Execute
def ExecuteCommand(self, batch_size=None):
'''Execute commands from queue of commands, up to batch_size number of commands'''
if not batch_size:
batch_size = len(self.commands)
execute_results = deque()
while len(self.commands) >= 1 and batch_size > 0:
cmd = self.commands.popleft() # Get the next command in the queue
execute_results.append((cmd, cmd.Execute()))
self.previously_executed_cmds.append(cmd)
batch_size -= 1
return execute_results
def UndoCommands(self):
'''Execute previously executed command but in reverse.'''
while self.previously_executed_cmds:
cmd = self.previously_executed_cmds.pop()
cmd.Undo()
# Receiver
class Robot(object):
inst_count = 0
supportedMoveAction = ["Forward", "Backwards", "Left", "Right", "Stop", "No-Op"]
def __init__(self, name=None):
if not name:
self.name = f"Robot #{Robot.inst_count}"
else:
self.name = name
Robot.inst_count += 1
def __str__(self):
return self.name
def Move(self, moveAction, distance):
if moveAction in Robot.supportedMoveAction:
actiontaken = f'{self}: Moving [{moveAction}, {distance}].'
else:
actiontaken = f'{self}: Move Failed: Unsupported move action {moveAction}.'
print(actiontaken) # Perform the action
return actiontaken
# Command (Base/Abstract)
class RobotCommand(object):
def __init__(self):
pass
# API Common to all Command subclasses
def Execute(self):
pass # Performs a Robot Command
def Undo(self):
pass # Reverts Robot to the state it was in before .Execute() was called
# Command (Concrete): Aware of the Receiver object's API
class Move(RobotCommand):
undo_movement = {'Forward':'Backwards', 'Backwards':'Forward', 'Left':'Right', 'Right':'Left', 'Stop':'Stop', 'No-Op':'No-Op'}
def __init__(self, receiver, action="No-Op", distance=0):
self.receiver = receiver
self.action = action
self.distance = distance
def Execute(self):
return self.receiver.Move(self.action, self.distance)
def Undo(self):
'''
Notice that the Move Command stores state information about:
1. What Receiver object was called (the specific Robot instance)
2. The details with which to pass to Robot.Move() (i.e., `action` and `distance`)
This necessarily relinquishes the responsibility of the Receiver to implement
"Undo" and store state information (i.e., what it was previously told to do)
'''
self.receiver.Move(Move.undo_movement[self.action], self.distance)
# To avoid duplicating code and as a way to assign maneuvers to arbitrary robot receivers
def get_maneuver(robot_receiver):
L_maneuver = deque([
Move(robot_receiver, 'Forward', 5),
Move(robot_receiver, 'Left', 4)
])
cww_maneuver = deque([
Move(robot_receiver, 'Forward', 3),
Move(robot_receiver, 'Left', 3),
Move(robot_receiver, 'Backwards', 3),
Move(robot_receiver, 'Right', 3)
])
return L_maneuver, cww_maneuver
if __name__ == '__main__':
maneuvers = namedtuple('Maneuvers', ['LManeuver', 'CcwCircle'])
# Create our actors
Wallie = Robot('Wallie')
Eve = Robot('Eve')
# Initiatize their maneuvers
wallie_maneuvers = maneuvers(*get_maneuver(Wallie))
eve_maneuvers = maneuvers(*get_maneuver(Eve))
# Initialize a controller
Nasah = RobotController(name='Nasah')
# Should be harmless if no commands were previously provided
Nasah.ExecuteCommand()
Nasah.UndoCommands()
print('L Maneuver:')
Nasah.commands = wallie_maneuvers.LManeuver
Nasah.ExecuteCommand()
Nasah.UndoCommands()
print('3-2-1 Stroll:')
Nasah.commands.append(Move(Wallie, 'Forward', 3))
Nasah.commands.append(Move(Wallie, 'Forward', 2))
Nasah.commands.append(Move(Wallie, 'Forward', 1))
Nasah.ExecuteCommand(batch_size=1)
Nasah.ExecuteCommand(batch_size=2)
Nasah.UndoCommands() # Backwards 1, Backwards 2, Backwards 3
print('Counterclockwise Circle Maneuver:')
Nasah.commands = wallie_maneuvers.CcwCircle
Nasah.ExecuteCommand()
Nasah.UndoCommands()
print('Eve\'s Turn:')
Nasah.commands = eve_maneuvers.LManeuver
Nasah.commands = eve_maneuvers.CcwCircle
Nasah.UndoCommands() # Should do nothing
Nasah.ExecuteCommand() # Eve to perform LManeuver and CcwCircle
Nasah.UndoCommands()
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code>L Maneuver:
Wallie: Moving [Forward, 5].
Wallie: Moving [Left, 4].
Wallie: Moving [Right, 4].
Wallie: Moving [Backwards, 5].
3-2-1 Stroll:
Wallie: Moving [Forward, 3].
Wallie: Moving [Forward, 2].
Wallie: Moving [Forward, 1].
Wallie: Moving [Backwards, 1].
Wallie: Moving [Backwards, 2].
Wallie: Moving [Backwards, 3].
Counterclockwise Circle Maneuver:
Wallie: Moving [Forward, 3].
Wallie: Moving [Left, 3].
Wallie: Moving [Backwards, 3].
Wallie: Moving [Right, 3].
Wallie: Moving [Left, 3].
Wallie: Moving [Forward, 3].
Wallie: Moving [Right, 3].
Wallie: Moving [Backwards, 3].
Eve's Turn:
Eve: Moving [Forward, 5].
Eve: Moving [Left, 4].
Eve: Moving [Forward, 3].
Eve: Moving [Left, 3].
Eve: Moving [Backwards, 3].
Eve: Moving [Right, 3].
Eve: Moving [Left, 3].
Eve: Moving [Forward, 3].
Eve: Moving [Right, 3].
Eve: Moving [Backwards, 3].
Eve: Moving [Right, 4].
Eve: Moving [Backwards, 5].
</code></pre>
| [] | [
{
"body": "<p>Having the undo in the global controller object is fine. It implies that the undo action is global. I probably would have saved the state of the robot to the queue each time a command is received. Then undo is just restoring the state to what it was at a previous time. It also makes going back 'n' moves at a time much cheaper.</p>\n\n<p>It is generally considered more \"Pythonic\" to try to execute the move in a try block and catch the resulting failure instead of having a function that tells you if the move is legal. Alternatively you can use <code>hasattr()</code> to check if the function you want to call is an attribute of this particular object before you call it. Raising an exception in Python is much cheaper than in some other languages and is often used if it doesn't obfuscate the code.</p>\n\n<p>I would think this application is a good candidate for using Python's multiple inheritance by creating mix-in classes. These are classes that can be inherited from but cannot be instantiated on their own (since they do not have an <code>__init__</code> method). So a MovingRobot would inherit from Robot (which can be instantiated and supplies the undo functionality) and Mover (which supplies state information about position). Similarly FlyingRobot would inherit from both Robot and Flyer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:36:20.073",
"Id": "434383",
"Score": "0",
"body": "Interesting first point. I think the choice to store `Receiver` states or to store `Commands` depends on what the Receiver actually is. If it were some class with a large number of attributes and you had defined a state-transition function (specifying how the object needs to change to get from one state to another), saving state would be a good idea. If code for the Receiver was actually located on a resource-constrained platform (e.g., a microcontroller), saving the commands on the controller-platform (which may be less resource-constrictive) is a better idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:55:19.440",
"Id": "434384",
"Score": "0",
"body": "With a try-block, I'd have to raise an exception in `Robot.Move()` and wrap every call to `Robot.Move()` with a try-except (or write a function to take a collection of Move Commands and try each `Command`). The latter isn't so bad but it depends on the `Receiver`. If the error in the Receiver is dire enough (and so *should* crash the program) or if it's more concise to let the language deal with bad inputs rather than depending on the programmer to exhaustively specify what to do with bad inputs on a case-by-case basis, exceptions is the way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:58:19.537",
"Id": "434385",
"Score": "0",
"body": "Hadn't heard of mix-in classes. Reminds me of C# interfaces / C++ abstract classes. Great suggestion!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:24:52.177",
"Id": "223971",
"ParentId": "223893",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:04:39.707",
"Id": "223893",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"design-patterns"
],
"Title": "Command Design Pattern Implementation: Moving Robot with Undo-movement (Python)"
} | 223893 |
<p>The script downloads images and videos from a user's profile page on Instagram. It works fine, but I'd like to know if there are ways to improve it. All ideas and suggestions are welcome.</p>
<pre><code>import sys
import os
import requests
import urllib.request
import time
import json
from colorama import init, deinit
from termcolor import colored, cprint
import argparse
print_green = lambda x: cprint(x, 'green') #print out text in green
print_magenta = lambda x : cprint(x, 'magenta') #print out text in magenta
print_yellow = lambda x: cprint(x, 'yellow') #print out text in yellow
print_cyan = lambda x: cprint(x, 'cyan') #print out text in cyan
# download images
def image_downloader(edge, images_path):
display_url = edge['node']['display_url']
file_name = edge['node']['taken_at_timestamp']
download_path = images_path + '\\' + str(file_name) + '.jpg'
if not os.path.exists(download_path):
print_yellow('Downloading ' + str(file_name) + '.jpg...........')
urllib.request.urlretrieve(display_url, download_path)
print_green(str(file_name) + '.jpg Downloaded')
print('\n')
else:
print_green(str(file_name) + '.jpg has been downloaded before')
print('\n')
# download videos
def video_downloader(shortcode, videos_path):
r = requests.get('https://www.instagram.com/p/' + shortcode + '/?__a=1')
video_url = r.json()['graphql']['shortcode_media']['video_url']
file_name = r.json()['graphql']['shortcode_media']['taken_at_timestamp']
download_path = videos_path + '\\' + str(file_name) + '.mp4'
if not os.path.exists(download_path):
print_yellow('Downloading ' + str(file_name) + '.mp4...........')
urllib.request.urlretrieve(video_url, download_path)
print_green(str(file_name) + '.mp4 Downloaded')
print('\n')
else:
print_green(str(file_name) + '.mp4 has been downloaded before')
print('\n')
# download images and videos from posts containing more than one pictures or videos`
def sidecar_downloader(shortcode, images_path, videos_path):
r = requests.get('https://www.instagram.com/p/' + shortcode + '/?__a=1')
num = 1
for edge in r.json()['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']:
is_video = edge['node']['is_video']
if is_video == False:
display_url = edge['node']['display_url']
file_name = r.json()['graphql']['shortcode_media']['taken_at_timestamp']
download_path = images_path + '\\' + str(file_name) + '_' + str(num) + '.jpg'
if not os.path.exists(download_path):
print_yellow('Downloading ' + str(file_name) + '_' + str(num) + '.jpg...........')
urllib.request.urlretrieve(display_url, download_path)
print_green(str(file_name) + '_' + str(num) + '.jpg Downloaded')
print('\n')
else:
print_green(str(file_name) + '_' + str(num) + '.jpg has been downloaded before')
print('\n')
else:
video_url = edge['node']['video_url']
file_name = r.json()['graphql']['shortcode_media']['taken_at_timestamp']
download_path = videos_path + '\\' + str(file_name) + '_' + str(num) + '.mp4'
if not os.path.exists(download_path):
print_yellow('Downloading ' + str(file_name) + '_' + str(num) + '.mp4...........')
urllib.request.urlretrieve(video_url, download_path)
print_green(str(file_name) + '_' + str(num) + '.mp4 Downloaded')
print('\n')
else:
print_green(str(file_name) + '_' + str(num) + '.mp4 has been downloaded before')
print('\n')
num += 1
def main(account_json_info, path):
init()
r = requests.get(account_json_info)
user_id = r.json()['graphql']['user']['id']
end_cursor = ''
next_page = True
is_video = False
images_path = path + '\\Images'
videos_path = path + '\\Videos'
if os.path.exists(path) == False:
os.makedirs(path)
if os.path.exists(images_path) == False:
os.makedirs(images_path)
if os.path.exists(videos_path) == False:
os.makedirs(videos_path)
print_magenta('User Folder Created!\n')
else:
print_magenta('User Folder Has Been Created Before!\n')
while next_page == True:
r = requests.get('https://www.instagram.com/graphql/query/',
params = {
'query_id': '17880160963012870',
'id': user_id,
'first': 12,
'after': end_cursor
}
)
graphql = r.json()['data']
for edge in graphql['user']['edge_owner_to_timeline_media']['edges']:
__typename = edge['node']['__typename']
if __typename == 'GraphImage':
image_downloader(edge, images_path)
elif __typename == 'GraphVideo':
shortcode = edge['node']['shortcode']
video_downloader(shortcode, videos_path)
elif __typename == 'GraphSidecar':
shortcode = edge['node']['shortcode']
sidecar_downloader(shortcode, images_path, videos_path)
end_cursor = graphql['user']['edge_owner_to_timeline_media']['page_info']['end_cursor']
next_page = graphql['user']['edge_owner_to_timeline_media']['page_info']['has_next_page']
time.sleep(10)
deinit()
if __name__ == '__main__':
print('\n\n')
init(autoreset = True)
print_cyan('Instagram Media Downloader'.center(os.get_terminal_size().columns, '-'))
deinit()
parser = argparse.ArgumentParser(description = 'Download Instagram Images and Videos from a User\'s Profile Page')
parser.add_argument('-u', '--user', dest = 'username', required = True, help = 'Username on Instagram')
parser.add_argument('-p', '--path', dest = 'path', required = True, help = 'Root path where downloaded Instagram Media is saved')
args = parser.parse_args()
account_json_info = 'https://www.instagram.com/' + args.username + '/?__a=1' #insert username into the link
args.path += '\\' + args.username #add username to the directory given
main(account_json_info, args.path)
</code></pre>
| [] | [
{
"body": "<ul>\n<li><strong>Organizing Imports</strong>: I ordered your import statements alphabetically. While this is not a required style point, it's a person preference that you can decide to follow if you want.</li>\n<li><strong>Unused Imports</strong>: You had a few unused imports (<code>json</code>, <code>sys</code>, <code>termcolor</code>)</li>\n<li><strong>String Formatting</strong>: You concatenate multiple strings with variables everywhere in your code. You can format your string with <code>f\"...\"</code>, so you can directly implement variables in your strings, like so: <code>download_path = f\"{videos_path}\\\\{file_name}.mp4\"</code>.</li>\n<li><strong>Variable Assignment/Parameter Spacing</strong>: There should only be one space before the <code>=</code> and after the <code>=</code> when assigning variables. For default parameters, there should be no spaces. I'm not sure if this is a practice that's taught, but it's how I learned my python styling.</li>\n<li><strong>DRY</strong>: Don't Repeat Yourself! Your <code>print_...</code> lambda's do the exact same thing, with only one string being different. These four lambdas can be simplified to a simple method, with passing the text and color to print. <em>I'm pretty sure <code>termcolor</code> has a built-in method <code>colored</code> that does the exact thing, but I'd have to double check</em>.</li>\n<li><strong>Truth/False Comparisons</strong>: As an example, <code>if is_video == False</code> should be changed to <code>if not is_video</code>. It does the exact same thing, without the verbose <code>== False</code>, and utilizing <code>not</code>. You use both ways in your code, but you should really avoid <code>== False</code>/<code>== True</code>.</li>\n<li><strong>Constant Variable Names</strong>: Variables that are constants should be UPPERCASE.</li>\n<li><strong>Docstrings</strong>: You had the right idea with regular comments describing what the method does. You should move these comments into a docstring inside the method, so any documentation can tell what your method is supposed to do.</li>\n</ul>\n\n<p><strong><em>Final Code</em></strong></p>\n\n<pre><code>import argparse\nimport os\nimport requests\nimport time\nimport urllib.request\nfrom colorama import init, deinit\nfrom termcolor import cprint\n\ndef print_in_color(text, color):\n \"\"\" Prints `text` in passed `color` \"\"\"\n cprint(text, color)\n\ndef image_downloader(edge, images_path):\n \"\"\" Downloads images \"\"\"\n display_url = edge['node']['display_url']\n file_name = edge['node']['taken_at_timestamp']\n download_path = f\"{images_path}\\\\{file_name}.jpg\"\n if not os.path.exists(download_path):\n print_in_color(f\"Downloading {str(file_name)}.jpg...........\", \"yellow\")\n urllib.request.urlretrieve(display_url, download_path)\n print_in_color(f\"{file_name}.jpg downloaded.\\n\", \"green\")\n else:\n print_in_color(f\"{file_name}.jpg has been downloaded already.\\n\", \"green\")\n\ndef video_downloader(shortcode, videos_path):\n \"\"\" Downloads videos \"\"\"\n videos = requests.get(f\"https://www.instagram.com/p/{shortcode}/?__a=1\")\n video_url = videos.json()['graphql']['shortcode_media']['video_url']\n file_name = videos.json()['graphql']['shortcode_media']['taken_at_timestamp']\n download_path = f\"{videos_path}\\\\{file_name}.mp4\"\n if not os.path.exists(download_path):\n print_in_color(f\"Downloading {file_name}.mp4...........\", \"yellow\")\n urllib.request.urlretrieve(video_url, download_path)\n print_in_color(f\"{file_name}.mp4 downloaded.\\n\", \"green\")\n else:\n print_in_color(f\"{file_name}.mp4 has been downloaded already.\\n\", \"green\")\n\ndef sidecar_downloader(shortcode, images_path, videos_path):\n \"\"\" Downloads images and videos from posts containing more than one pictures or videos \"\"\"\n r = requests.get(f\"https://www.instagram.com/p/{shortcode}/?__a=1\")\n num = 1\n for edge in r.json()['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']:\n is_video = edge['node']['is_video']\n if not is_video:\n display_url = edge['node']['display_url']\n file_name = r.json()['graphql']['shortcode_media']['taken_at_timestamp']\n download_path = f\"{images_path}\\\\{file_name}_{num}.jpg\"\n if not os.path.exists(download_path):\n print_in_color(f\"Downloading {file_name}_{num}.jpg...........\", \"yellow\")\n urllib.request.urlretrieve(display_url, download_path)\n print_in_color(f\"{file_name}_{num}.jpg downloaded.\\n\", \"green\")\n else:\n print_in_color(f\"{file_name}_{num}.jpg has been downloaded already.\\n\", \"green\")\n else:\n video_url = edge['node']['video_url']\n file_name = r.json()['graphql']['shortcode_media']['taken_at_timestamp']\n download_path = f\"{videos_path}\\\\{file_name}_{num}.mp4\"\n if not os.path.exists(download_path):\n print_in_color(f\"Downloading {file_name}_{num}.mp4...........\", \"yellow\")\n urllib.request.urlretrieve(video_url, download_path)\n print_in_color(f\"{file_name}_{num}.mp4 downloaded.\\n\", \"green\")\n else:\n print_in_color(f\"{file_name}_{num}.mp4 has been downloaded already.\\n\", \"green\")\n num += 1\n\ndef main(account_json_info, path):\n \"\"\" Runs methods that download photos/videos from the user \"\"\"\n init()\n r = requests.get(account_json_info)\n user_id = r.json()['graphql']['user']['id']\n end_cursor = ''\n next_page = True\n images_path = f\"{path}\\\\Images\"\n videos_path = f\"{path}\\\\Videos\"\n if not os.path.exists(path):\n os.makedirs(path)\n if not os.path.exists(images_path):\n os.makedirs(images_path)\n if not os.path.exists(videos_path):\n os.makedirs(videos_path)\n print_in_color(\"User Folder Created!\\n\", \"magenta\")\n else:\n print_in_color(\"User Folder Has Been Created Already!\\n\", \"magenta\")\n\n while next_page:\n r = requests.get('https://www.instagram.com/graphql/query/',\n params={\n 'query_id': '17880160963012870',\n 'id': user_id,\n 'first': 12,\n 'after': end_cursor\n }\n )\n graphql = r.json()['data']\n for edge in graphql['user']['edge_owner_to_timeline_media']['edges']:\n __typename = edge['node']['__typename']\n if __typename == 'GraphImage':\n image_downloader(edge, images_path)\n elif __typename == 'GraphVideo':\n shortcode = edge['node']['shortcode']\n video_downloader(shortcode, videos_path)\n elif __typename == 'GraphSidecar':\n shortcode = edge['node']['shortcode']\n sidecar_downloader(shortcode, images_path, videos_path)\n\n end_cursor = graphql['user']['edge_owner_to_timeline_media']['page_info']['end_cursor']\n next_page = graphql['user']['edge_owner_to_timeline_media']['page_info']['has_next_page']\n time.sleep(10)\n deinit()\n\nif __name__ == '__main__':\n print('\\n\\n')\n init(autoreset=True)\n print_in_color('Instagram Media Downloader'.center(os.get_terminal_size().columns, '-'), \"cyan\")\n deinit()\n\n PARSER = argparse.ArgumentParser(description='Download Instagram Images and Videos from a User\\'s Profile Page')\n PARSER.add_argument('-u', '--user', dest='username', required=True, help='Username on Instagram')\n PARSER.add_argument('-p', '--path', dest='path', required=True, help='Root path where downloaded Instagram Media is saved')\n ARGS = PARSER.parse_args()\n\n #Insert username into link\n ACCOUNT_JSON_INFO = f\"https://www.instagram.com/{ARGS.username}/?__a=1\"\n ARGS.path += f\"\\\\{ARGS.username}\"\n main(ACCOUNT_JSON_INFO, ARGS.path)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T12:27:12.237",
"Id": "436330",
"Score": "0",
"body": "Import standard in python is to import standard library packages/modules as one block first, then external packages/modules as another block, then personal packages/modules - each block separated by an empty line."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T06:22:12.040",
"Id": "224863",
"ParentId": "223894",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:05:38.950",
"Id": "223894",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Python Script to download images and videos from a user's profile on Instagram"
} | 223894 |
<p>My code parses through a contiguous range of data in a spreadsheet (orng) and creates subranges from orng that contain the same string value (lot number) in the 6th column of orng. orng has 42 rows and 38 columns and each subrange has 1-15 rows and 38 columns.</p>
<p>As far as I know, I can't create a new range object for each subrange since the number of subranges is unknown. I've created an array that contains the data for the subranges (aData). I</p>
<p>have gotten it to work with the code below, but I feel like there is a much cleaner way of doing it that I can't figure out. I've also tried using a dictionary with no success. I will eventually have to call upon all the data for calculations and using multiple nested for loops to access each element seems convoluted.</p>
<p>I would prefer that the array was dynamic, but whenever I attempted the ReDim Preserve method the values would not be saved to the array. The size of the array would be correct, but every element was "Empty". According to <a href="https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/can-t-assign-to-an-array" rel="nofollow noreferrer">Microsoft</a> "each element of an array must have its value assigned individually" so it seems as though the only way I can keep the values when creating the array is to assign to each element. </p>
<p>After I found that webpage I implemented an array with a predetermined structure and the nested for loops. Is it possible to add the entire subrange to the array in one go? If not, what about a row?</p>
<p>Ideally, I could separate orng into different Areas, but since it is contiguous I am unable to do so (I'm not aware of a way to create Areas in a contiguous range). </p>
<p>What I'd like to know are:</p>
<ol>
<li><p>is there a better way to do what I am trying to do (collection, dictionary, etc.) </p></li>
<li><p>if there is not a better way, can I get some advice on how to make this code cleaner (Easier to read, faster, less code, dynamic range, better structure)?</p></li>
</ol>
<pre class="lang-vb prettyprint-override"><code> Private Sub rangetest()
Dim twb As Workbook: Set twb = ThisWorkbook
Dim cws As Worksheet: Set cws = twb.Sheets("Cleaned_2019+")
Dim orng As Range
Dim datelot As String, datelotcomp As String
Dim c As Long, i As Long, j As Long, k As Long, numrows As Long, lastrow
As Long, numlots As Long, _
curRow As Long, lotRows As Long, startRow As Long, layerRows As Long,
aRow As Long
Dim aLot() As Variant, aData(9, 49, 37) As Variant
Dim Z As Boolean
Set orng = cws.Range("A973:AL1014") 'Set initial range to work with.
numrows = orng.Rows.Count 'Number of rows in orng.
curRow = 1 'Current row in orng.
startRow = 1 'Starting row in orng for next
layer (changes when lot changes).
i = 0 'Layer of array (for aLot and aData arrays).
j = 0 'Row in orng where values for previous layer ended.
Z = False
Do Until Z = True
datelot = Left(orng.Cells(curRow, 6).Value, 10) 'Lot that we want the data for. Corresponds to a layer in the aData array.
datelotcomp = Left(orng.Cells(curRow + 1, 6).Value, 10) 'Lot of the next row in data sheet.
If datelot <> datelotcomp Then 'If datelotcomp <> to datelot then we want a new layer for array.
layerRows = curRow - j 'Number of rows for a particular layer
ReDim Preserve aLot(i) 'Array of lot names
aLot(i) = datelot 'Assign lot name to aLot array
For aRow = 1 To layerRows 'Row index in array
For lotRows = startRow To curRow 'Loops through orng rows and sets those values in array
For c = 1 To 38 'Loops through columns. There are always 38 columns
aData(i, aRow - 1, c - 1) = orng.Cells(lotRows, c).Value 'Add values to each index in array
Next c
Next lotRows
Next aRow
j = curRow
i = i + 1
startRow = curRow + 1
End If
If curRow = numrows Then 'End loop at end of orng
Z = True
End If
curRow = curRow + 1
Loop
numlots = i
End Sub
</code></pre>
<p>The result I get is an array with the structure aData(9, 49, 37) that contains data in the first 4 layers aData(1-3, , ). This corresponds with the unique number of lots (criteria from column 6 of orng) so the code is working correctly. I'd just like advice on if I'm doing anything inefficiently.</p>
<p>I will be checking back to answer questions or to add clarification.</p>
<p><strong>Edit 1:</strong> </p>
<p>The orng size will change based on user input. I have the user inputting a start and end date and orng is created based on those values. Once I have the subranges from orng I will then use other criteria from other columns of the subrange to determine which rows to apply calculations to. The end result will be the lot number(s) with the calculations for the lot(s) printed out for the user.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T22:17:47.667",
"Id": "434161",
"Score": "0",
"body": "Ever thought of using a pivot table to do this work for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T22:19:12.843",
"Id": "434162",
"Score": "0",
"body": "Yes, there is a better way, and yes you can make the code cleaner. Are you able to post up some sample data and expected output as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:09:38.497",
"Id": "434303",
"Score": "0",
"body": "A pivot table will not work with what I am going to be doing with the ranges for the end result. Do I just post a picture of the data? I tried adding the data to the original post, but the formatting was a mess. Thank you for your response!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T22:52:31.190",
"Id": "434366",
"Score": "0",
"body": "If the image is readable on this site, then posting an image should suffice."
}
] | [
{
"body": "<p>There is not much to review as far as the code goes other than avoid using 3D arrays. The problem with 3D arrays is that you need to know the exact size of the first 3 dimensions because only the last dimension is resizable</p>\n\n<blockquote>\n <p>I attempted the ReDim Preserve method the values would not be saved to the array.</p>\n</blockquote>\n\n<p>You may want to post your attempts to use <code>ReDim Preserve</code> on StackOverflow because <code>ReDim Preserve</code> does save the values in the array. </p>\n\n<blockquote>\n <p>Ideally, I could separate orng into different Areas, but since it is contiguous I am unable to do so (I'm not aware of a way to create Areas in a contiguous range). What I'd like to know is 1) is there a better way to do what I am trying to do (collection, dictionary, etc.) and 2) if there is not a better way, can I get some advice on how to make this code cleaner (Easier to read, faster, less code, dynamic range, better structure)?</p>\n</blockquote>\n\n<p>It is hard to give advice without knowing what you are trying to do with the data other than group it. What I can do is show you how to store non-contiguous ranges in a Dictionary by Lot number and then work with the ranges afterwards.</p>\n\n<pre><code>Private Sub Dictionarytest()\n Dim map As New Scripting.Dictionary, rw As Range\n Dim key As Variant\n 'Join Ranges Based on Lot Number and Add them to the Dictionary Map\n\n With ThisWorkbook.Sheets(\"Cleaned_2019+\")\n For Each rw In .Range(\"A973:AL1014\").Rows\n key = rw.Columns(6).Value\n\n If map.Exists(key) Then\n Set map(key) = Union(map(key), rw)\n Else\n map.Add key, rw\n End If\n Next\n End With\n\n Dim subRange As Range\n\n 'Iterate of the Dictionary Map Keys and Print the Join Ranges Addresses\n For Each key In map\n Set subRange = map(key)\n Debug.Print subRange.Address(False, False)\n Next\n\n Dim item As Variant\n 'Iterate of the Dictionary Map Items and Print the Join Ranges Addresses\n For Each item In map.Items()\n Debug.Print item.Address(False, False)\n Next\n\n Dim Data As Variant\n 'Create an Array From the Dictionary Items\n Data = map.Items()\n 'Iterate of the Data Array and Print the Join Ranges Addresses\n For Each item In Data\n Debug.Print item.Address(False, False)\n Next\n\n Dim results As Variant\n Dim r As Long, c As Long, rowCount As Long\n 'Iterate of the Dictionary Map Keys and Create Array From the Join Ranges Addresses\n 'Note: the Results Array Contains all the Data for a Single Lot Number\n For Each key In map\n Set subRange = map(key)\n rowCount = subRange.Cells.CountLarge / subRange.Columns.Count\n ReDim results(1 To rowCount, 1 To subRange.Columns.Count)\n r = 0\n For Each rw In subRange.Rows\n r = r + 1\n For c = 1 To UBound(results, 2)\n results(r, c) = rw.Columns(c).Value\n Next\n Next\n Next\n\nEnd Sub\n</code></pre>\n\n<p>Immediate Window Print Out</p>\n\n<blockquote>\n <p>A973:AL973,A975:AL975,A979:AL979,A985:AL985,A989:AL989,A1006:AL1006\n A974:AL974,A982:AL982,A991:AL991,A1002:AL1002,A1013:AL1013\n A976:AL976,A1007:AL1007\n A977:AL977,A981:AL981,A1001:AL1001\n A978:AL978,A988:AL988,A994:AL994,A996:AL996,A1014:AL1014\n A980:AL980,A984:AL984,A990:AL990,A998:AL998,A1004:AL1004,A1009:AL1009\n A983:AL983,A986:AL986,A993:AL993,A997:AL997,A999:AL999,A1003:AL1003\n A987:AL987,A992:AL992,A995:AL995\n A1000:AL1000,A1005:AL1005,A1008:AL1008,A1010:AL1011\n A1012:AL1012</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:43:37.507",
"Id": "434193",
"Score": "0",
"body": "as usual (from you) Brilliant use of union with dictionary. I am only started thinking about avoiding use of 3D array. Forcing me to be hardened fan of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:41:42.870",
"Id": "434288",
"Score": "0",
"body": "@AhmedAU thank you sir!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:13:40.283",
"Id": "434304",
"Score": "0",
"body": "I will work on implementing this today and get back to you with the results. This definitely looks more like what I was trying to do, but lacked the know-how. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T22:50:20.523",
"Id": "435060",
"Score": "0",
"body": "This was the core code I ended up using. I had to add some qualifiers, but it worked as intended in the end. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T08:58:58.637",
"Id": "435120",
"Score": "0",
"body": "@lifeuhfindsaway I'm glad that it helped. Thanks for accepting my answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:28:45.667",
"Id": "223912",
"ParentId": "223897",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223912",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:53:37.143",
"Id": "223897",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Store subranges from contiguous range into array based on criteria"
} | 223897 |
<p>I attempt to write a STL-like vector, mostly to figure out how it works. I wonder which parts look weird or what I made stupid. Any kind of comment is appreciated:</p>
<h3>alloc.hpp</h3>
<pre><code>#pragma once
#include <limits>
#include <memory>
namespace p1v0t {
template <class T>
class allocator {
public:
using value_type = T;
template <class U>
struct rebind {
typedef allocator<U> other;
};
allocator() noexcept = default;
template <class U>
allocator(allocator<U> const &) noexcept {}
// Use pointer if pointer is not a value_type*
[[nodiscard]] value_type *allocate(std::size_t n) {
return static_cast<value_type *>(::operator new(n * sizeof(value_type)));
}
// Use pointer if pointer is not a value_type*
void deallocate(value_type *p, std::size_t) noexcept { ::operator delete(p); }
using propagate_on_container_copy_assignment = std::false_type;
using propagate_on_container_move_assignment = std::false_type;
using propagate_on_container_swap = std::false_type;
using is_always_equal = std::is_empty<allocator>;
};
template <class T, class U>
bool operator==(allocator<T> const &, allocator<U> const &) noexcept {
return true;
}
template <class T, class U>
bool operator!=(allocator<T> const &x, allocator<U> const &y) noexcept {
return !(x == y);
}
} // namespace p1v0t
</code></pre>
<h3>vector.hpp</h3>
<pre><code>#pragma once
#include "alloc.hpp"
#include <algorithm>
#include <initializer_list>
#include <limits>
namespace p1v0t {
template <typename T, class Allocator = allocator<T>>
class vector {
public:
using allocator_type = Allocator;
using value_type = T;
using reference = value_type &;
using const_reference = const value_type &;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer =
typename std::allocator_traits<Allocator>::const_pointer;
using iterator = value_type *;
using const_iterator = const value_type *;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = const std::reverse_iterator<const_iterator>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
allocator_type m_allocator;
T *m_data = nullptr;
size_type m_capacity = 0;
size_type m_size = 0;
constexpr vector() noexcept(noexcept(Allocator()));
explicit vector(size_type n_);
constexpr vector(std::initializer_list<T> il_);
constexpr vector(size_t elm_, const value_type &val_);
template <class InputIt>
constexpr vector(InputIt first, InputIt last);
constexpr vector(const vector<T, Allocator> &other_);
constexpr vector &operator=(const vector &other_);
constexpr vector &operator=(std::initializer_list<value_type> il_);
constexpr vector(vector &&other_) noexcept(
std::is_nothrow_move_constructible<allocator_type>::value);
constexpr vector &operator=(vector &&other_) noexcept(
allocator_type::propagate_on_container_move_assignment::value ||
allocator_type::is_always_equal::value);
virtual ~vector() noexcept;
constexpr void assign(size_type, const T &);
template <class InputIt>
constexpr void assign(InputIt, InputIt);
constexpr void assign(std::initializer_list<T>);
constexpr allocator_type get_allocator() const noexcept;
constexpr reference at(size_type);
constexpr const_reference at(size_type) const;
constexpr reference operator[](size_type);
constexpr const_reference operator[](size_type) const;
constexpr reference front();
constexpr const_reference front() const;
constexpr reference back();
constexpr const_reference back() const;
constexpr pointer data() noexcept;
constexpr const_pointer data() const noexcept;
constexpr iterator begin() noexcept;
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;
constexpr reverse_iterator rbegin() noexcept;
constexpr const_reverse_iterator rbegin() const noexcept;
constexpr const_reverse_iterator crbegin() const noexcept;
constexpr iterator end() noexcept;
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
constexpr reverse_iterator rend() noexcept;
constexpr const_reverse_iterator rend() const noexcept;
constexpr const_reverse_iterator crend() const noexcept;
[[nodiscard]] constexpr bool empty() const noexcept;
constexpr difference_type max_size() const noexcept;
constexpr size_type capacity() const noexcept;
constexpr size_type size() const noexcept;
constexpr void reserve(size_type new_cap_);
constexpr void shrink_to_fit();
constexpr void clear() noexcept;
constexpr iterator insert(const_iterator, const T &);
constexpr iterator insert(const_iterator, T &&);
constexpr iterator insert(const_iterator, size_type, const T &);
template <class InputIt>
constexpr iterator insert(const_iterator, InputIt, InputIt);
constexpr iterator insert(const_iterator, std::initializer_list<T>);
constexpr void push_back(const T &);
constexpr void push_back(T &&);
template <class... Args>
constexpr reference emplace_back(Args &&...);
template <class... Args>
constexpr iterator emplace(const_iterator pos_, Args &&...);
constexpr iterator erase(const_iterator pos_);
constexpr iterator erase(const_iterator first_, const_iterator last_);
constexpr void pop_back();
constexpr void resize(size_type count_);
constexpr void resize(size_type count_, const value_type &value_);
constexpr void swap(vector &other_) noexcept;
private:
const uint8_t m_growing_rate = 2;
}; // end class vector
template <typename T, class Allocator>
constexpr vector<T, Allocator>::vector() noexcept(noexcept(Allocator())) {
m_size = 0;
reserve(1);
}
template <typename T, class Allocator>
vector<T, Allocator>::vector(size_type n_) {
reserve(n_ * m_growing_rate);
m_size = n_;
}
template <typename T, class Allocator>
constexpr vector<T, Allocator>::vector(size_t n_, const value_type &val_) {
m_size = m_capacity = n_;
m_data = m_allocator.allocate(m_capacity);
std::fill(begin(), end(), val_);
}
template <typename T, class Allocator>
template <class InputIt>
constexpr vector<T, Allocator>::vector(InputIt first_, InputIt last_) {
assign(first_, last_);
}
template <typename T, class Allocator>
constexpr vector<T, Allocator>::vector(std::initializer_list<T> lst_) {
reserve(lst_.size() * m_growing_rate);
std::move(lst_.begin(), lst_.end(), this->begin());
m_size = lst_.size();
}
template <typename T, class Allocator>
constexpr vector<T, Allocator>::vector(const vector<T, Allocator> &other_) {
reserve(other_.size() * m_growing_rate);
std::move(other_.begin(), other_.end(), this->begin());
m_size = other_.size();
}
template <typename T, class Allocator>
constexpr vector<T, Allocator> &vector<T, Allocator>::
operator=(const vector &other_) {
assign(other_.begin(), other_.end());
return *this;
}
template <typename T, class Allocator>
constexpr vector<T, Allocator> &vector<T, Allocator>::
operator=(std::initializer_list<value_type> il_) {
m_size = il_.size();
m_capacity = m_size * m_growing_rate;
m_data = m_allocator.allocate(m_capacity);
std::move(il_.begin(), il_.end(), this->begin());
return *this;
}
template <typename T, class Allocator>
constexpr vector<T, Allocator>::vector(vector &&other_) noexcept(
std::is_nothrow_move_constructible<allocator_type>::value) {
m_data = std::move(other_.m_data);
m_size = other_.m_size;
m_capacity = other_.m_capacity;
other_.m_data = nullptr;
other_.m_capacity = 0;
other_.m_size = 0;
}
template <typename T, class Allocator>
constexpr vector<T, Allocator> &vector<T, Allocator>::
operator=(vector &&other_) noexcept(
allocator_type::propagate_on_container_move_assignment::value ||
allocator_type::is_always_equal::value) {
m_data = std::move(other_.m_data);
m_size = other_.m_size;
m_capacity = other_.m_capacity;
other_.m_data = nullptr;
other_.m_capacity = 0;
other_.m_size = 0;
return *this;
}
template <typename T, class Allocator>
vector<T, Allocator>::~vector() noexcept {
m_allocator.deallocate(m_data, m_capacity);
m_size = 0;
m_capacity = 0;
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::assign(size_type count_, const T &value_) {
reserve(count_ * m_growing_rate);
m_size = count_;
std::fill(begin(), end(), value_);
}
template <typename T, class Allocator>
template <class InputIt>
constexpr void vector<T, Allocator>::assign(InputIt first_, InputIt last_) {
size_type length_of_interval =
static_cast<size_type>(std::distance(first_, last_));
reserve((size() + length_of_interval) * m_growing_rate);
std::move(first_, last_, begin());
m_size += static_cast<size_type>(std::distance(first_, last_) * 2);
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::assign(std::initializer_list<T> il_) {
reserve(il_.size() * m_growing_rate);
std::move(il_.begin(), il_.end(), begin());
m_size = il_.size();
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::allocator_type
vector<T, Allocator>::get_allocator() const noexcept {
return m_allocator;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reference
vector<T, Allocator>::at(size_type index_) {
if (index_ >= size()) {
throw std::out_of_range("Billions of Bilious Blue Blistering Barnacles! "
"You attempted to access out of range");
}
return m_data[index_];
}
template <typename T, class Allocator>
typename vector<T, Allocator>::const_reference constexpr vector<
T, Allocator>::at(size_type index_) const {
if (index_ >= size()) {
throw std::out_of_range("Billions of Bilious Blue Blistering Barnacles! "
"Attemp to access out of range");
}
return m_data[index_];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reference vector<T, Allocator>::
operator[](size_type pos_) {
return m_data[pos_];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reference vector<T, Allocator>::
operator[](size_type pos_) const {
return m_data[pos_];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reference
vector<T, Allocator>::front() {
return m_data[0];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reference
vector<T, Allocator>::front() const {
return m_data[0];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reference
vector<T, Allocator>::back() {
return m_data[m_size - 1];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reference
vector<T, Allocator>::back() const {
return m_data[m_size - 1];
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::pointer
vector<T, Allocator>::data() noexcept {
return m_data;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_pointer
vector<T, Allocator>::data() const noexcept {
return m_data;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::begin() noexcept {
return (m_data + 0);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::begin() const noexcept {
return (m_data + 0);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::cbegin() const noexcept {
return (m_data + 0);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reverse_iterator
vector<T, Allocator>::rbegin() noexcept {
return reverse_iterator(end());
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rbegin() const noexcept {
return const_reverse_iterator(end());
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::crbegin() const noexcept {
return static_cast<const_reverse_iterator>(end());
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::end() noexcept {
return (m_data + m_size);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::end() const noexcept {
return (m_data + m_size);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::cend() const noexcept {
return (m_data + m_size);
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::reverse_iterator
vector<T, Allocator>::rend() noexcept {
return reverse_iterator(begin());
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rend() const noexcept {
return const_reverse_iterator(begin());
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::crend() const noexcept {
return const_reverse_iterator(cbegin());
}
template <typename T, class Allocator>
[[nodiscard]] constexpr bool vector<T, Allocator>::empty() const noexcept {
return size() == 0;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::difference_type
vector<T, Allocator>::max_size() const noexcept {
return std::numeric_limits<difference_type>::max();
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::size_type
vector<T, Allocator>::capacity() const noexcept {
return m_capacity;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::size_type
vector<T, Allocator>::size() const noexcept {
return m_size;
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::shrink_to_fit() {
m_capacity = m_size;
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::reserve(size_type new_cap_) {
if (new_cap_ > m_capacity) {
if (new_cap_ > max_size())
throw std::length_error("Megacycle Pyromaniac! Length ERROR!!!");
if (empty()) {
m_data = m_allocator.allocate(new_cap_);
m_capacity = new_cap_;
} else {
T *tmp = m_allocator.allocate(new_cap_);
std::move(begin(), end(), tmp);
m_allocator.deallocate(m_data, m_capacity);
m_data = std::move(tmp);
m_capacity = new_cap_;
}
}
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::clear() noexcept {
m_size = 0;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(const_iterator pos_, const T &val_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = val_;
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
if (empty()) {
*begin() = val_;
++m_size;
return begin();
}
return ret;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(const_iterator pos_, T &&val_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = std::move(val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
if (empty()) {
*begin() = std::move(val_);
++m_size;
return begin();
}
return ret;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(const_iterator pos_, size_type count_,
const T &val_) {
iterator ret = const_cast<iterator>(pos_);
if (empty() && capacity() < count_) {
reserve(count_ * m_growing_rate);
m_size = count_;
std::fill(begin(), end(), val_);
return begin();
} else {
m_size += count_;
std::move_backward(ret, end() - count_, end());
std::fill(ret, ret + count_, val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
}
template <typename T, class Allocator>
template <class InputIt>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(const_iterator pos_, InputIt first_,
InputIt last_) {
iterator ret = const_cast<iterator>(pos_);
size_type diff = static_cast<size_type>(std::distance(first_, last_));
m_size += diff;
std::move_backward(ret, end() - diff, end());
std::move(first_, last_, ret);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(const_iterator pos_,
std::initializer_list<T> lst_) {
iterator ret = const_cast<iterator>(pos_);
m_size += lst_.size();
std::move_backward(ret, end() - lst_.size(), end());
std::move(lst_.begin(), lst_.end(), ret);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::push_back(const T &val_) {
m_data[m_size++] = val_;
if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::push_back(T &&val_) {
m_data[m_size++] = std::move(val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
}
template <typename T, class Allocator>
template <class... Args>
constexpr typename vector<T, Allocator>::reference
vector<T, Allocator>::emplace_back(Args &&... args_) {
++m_size;
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
*(end() - 1) = std::move(T(std::forward<Args>(args_)...));
return *(end() - 1);
}
template <typename T, class Allocator>
template <class... Args>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::emplace(const_iterator pos_, Args &&... args_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = std::move(std::forward<Args>(args_)...);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(const_iterator pos_) {
if (pos_ == begin()) {
--m_size;
return ++m_data;
}
iterator ret = const_cast<iterator>(pos_);
std::move(ret + 1, end(), ret);
--m_size;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
return ret;
}
template <typename T, class Allocator>
constexpr typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(const_iterator first_, const_iterator last_) {
difference_type diff = last_ - first_;
iterator ret = const_cast<iterator>(first_);
std::move(last_, cend(), ret);
m_size -= static_cast<size_type>(diff);
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
return ret;
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::pop_back() {
if (!empty()) {
--m_size;
}
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::resize(size_type count_) {
m_size = count_;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::resize(size_type count_,
const value_type &value_) {
size_type old_size = m_size;
m_size = count_;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
if (old_size > count_) {
fill(begin() + count_, begin() + old_size, value_);
} else {
fill(begin() + old_size, begin() + count_, value_);
}
}
template <typename T, class Allocator>
constexpr void vector<T, Allocator>::swap(vector &other_) noexcept {
size_type tmp_size = other_.size();
size_type tmp_capacity = other_.capacity();
auto tmp_data = other_.data();
other_.m_size = m_size;
other_.m_capacity = m_capacity;
other_.m_data = m_data;
m_size = tmp_size;
m_capacity = tmp_capacity;
m_data = tmp_data;
}
template <typename T, class Allocator>
constexpr bool operator==(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return (lhs_.size() == rhs_.size() and
std::equal(lhs_.begin(), lhs_.end(), rhs_.begin()));
}
template <typename T, class Allocator>
constexpr bool operator!=(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return !(lhs_ == rhs_);
}
template <typename T, class Allocator>
constexpr bool operator<(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return std::lexicographical_compare(lhs_.begin(), lhs_.end(), rhs_.begin(),
rhs_.end());
}
template <typename T, class Allocator>
constexpr bool operator>=(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return !(lhs_ < rhs_);
}
template <typename T, class Allocator>
constexpr bool operator>(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return rhs_ < lhs_;
}
template <typename T, class Allocator>
constexpr bool operator<=(const p1v0t::vector<T, Allocator> &lhs_,
const p1v0t::vector<T, Allocator> &rhs_) {
return !(rhs_ < lhs_);
}
template <typename T, class Allocator>
constexpr void
swap(vector<T, Allocator> &lhs_,
vector<T, Allocator> &rhs_) noexcept(noexcept(lhs_.swap(rhs_))) {
lhs_.swap(rhs_);
}
template <typename T, class Allocator, class U>
constexpr void erase(p1v0t::vector<T, Allocator> &container_, const U &value_) {
container_.erase(std::remove(container_.begin(), container_.end(), value_),
container_.end());
}
template <typename T, class Allocator, class Pred>
constexpr void erase_if(p1v0t::vector<T, Allocator> &container_,
const Pred predicate_) {
container_.erase(
std::remove_if(container_.begin(), container_.end(), predicate_),
container_.end());
}
template <class Allocator>
class vector<bool, Allocator> {
public:
using allocator_type = Allocator;
using value_type = bool;
using reference = value_type &;
using const_reference = const value_type &;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer =
typename std::allocator_traits<Allocator>::const_pointer;
using iterator = value_type *;
using const_iterator = const value_type *;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = const std::reverse_iterator<const_iterator>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
allocator_type m_allocator;
value_type *m_data = nullptr;
size_type m_capacity = 0;
size_type m_size = 0;
explicit constexpr vector();
explicit constexpr vector(size_type count_);
constexpr vector(size_type n_, const bool &val_);
constexpr vector(std::initializer_list<bool>);
template <class InputIt>
constexpr vector(InputIt first_, InputIt last_);
constexpr vector(const vector<bool, Allocator> &other_);
constexpr vector<bool, Allocator> &
operator=(const vector<bool, Allocator> &other_);
constexpr vector &operator=(std::initializer_list<bool>);
constexpr vector(vector &&);
constexpr vector<bool, Allocator> &operator=(vector<bool, Allocator> &&);
virtual ~vector() noexcept;
constexpr void assign(size_type, const bool &);
template <class InputIt>
constexpr void assign(InputIt, InputIt);
constexpr void assign(std::initializer_list<bool>);
constexpr allocator_type get_allocator() const noexcept;
constexpr reference at(size_type n_);
constexpr const_reference at(size_type n_) const;
constexpr reference operator[](size_type n_);
constexpr const_reference operator[](size_type n_) const;
constexpr reference front();
constexpr const_reference front() const;
constexpr reference back();
constexpr const_reference back() const;
constexpr iterator begin() noexcept;
constexpr const_iterator begin() const noexcept;
constexpr iterator end() noexcept;
constexpr const_iterator end() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
constexpr const_iterator cbegin() const noexcept;
constexpr const_iterator cend() const noexcept;
const_reverse_iterator crbegin() const noexcept;
const_reverse_iterator crend() const noexcept;
constexpr size_type size() const noexcept;
constexpr size_type max_size() const noexcept;
constexpr void resize(size_type);
constexpr void resize(size_type, const bool &);
constexpr size_type capacity() const noexcept;
[[nodiscard]] constexpr bool empty() const noexcept;
constexpr void reserve(size_type n);
constexpr void shrink_to_fit();
template <class... Args>
constexpr void emplace_back(Args &&...);
constexpr void push_back(const bool &);
constexpr void push_back(bool &&);
constexpr void pop_back();
template <class... Args>
constexpr iterator emplace(const_iterator, Args &&...);
constexpr iterator insert(const_iterator, const bool &);
constexpr iterator insert(const_iterator, bool &&);
constexpr iterator insert(const_iterator, size_type, const bool &);
template <class InputIt>
constexpr iterator insert(const_iterator, InputIt, InputIt);
constexpr iterator insert(const_iterator, std::initializer_list<bool>);
constexpr iterator erase(const_iterator);
constexpr iterator erase(const_iterator, const_iterator);
constexpr void swap(vector<bool, Allocator> &);
constexpr static void swap(reference x, reference y) noexcept;
constexpr void flip() noexcept;
constexpr void clear() noexcept;
private:
const uint8_t m_growing_rate = 2;
}; // end class vector bool
template <class Allocator>
constexpr vector<bool, Allocator>::vector() {
reserve(1);
m_size = 0;
}
template <class Allocator>
constexpr vector<bool, Allocator>::vector(size_type n_) {
reserve(n_ * m_growing_rate);
m_size = n_;
}
template <class Allocator>
constexpr vector<bool, Allocator>::vector(size_type n_, const bool &val_) {
m_size = m_capacity = n_;
m_data = m_allocator.allocate(m_capacity);
std::fill(begin(), end(), val_);
}
template <class Allocator>
template <class InputIt>
constexpr vector<bool, Allocator>::vector(InputIt first_, InputIt last_) {
assign(first_, last_);
}
template <class Allocator>
constexpr vector<bool, Allocator>::vector(std::initializer_list<bool> lst_) {
reserve(lst_.size() * m_growing_rate);
std::move(lst_.begin(), lst_.end(), this->begin());
m_size = lst_.size();
}
template <class Allocator>
constexpr vector<bool, Allocator>::vector(
const vector<bool, Allocator> &other_) {
reserve(other_.size() * m_growing_rate);
std::move(other_.begin(), other_.end(), this->begin());
m_size = other_.size();
}
template <class Allocator>
constexpr vector<bool, Allocator> &vector<bool, Allocator>::
operator=(const vector<bool, Allocator> &other_) {
assign(other_.begin(), other_.end());
return *this;
}
template <class Allocator>
constexpr vector<bool, Allocator> &vector<bool, Allocator>::
operator=(std::initializer_list<value_type> il_) {
reserve(il_.size() * m_growing_rate);
std::move(il_.begin(), il_.end(), this->begin());
m_size = il_.size();
return *this;
}
template <class Allocator>
constexpr vector<bool, Allocator>::vector(vector &&other_) {
m_data = std::move(other_.m_data);
m_size = other_.m_size;
m_capacity = other_.m_capacity;
other_.m_data = nullptr;
other_.m_capacity = 0;
other_.m_size = 0;
}
template <class Allocator>
constexpr vector<bool, Allocator> &vector<bool, Allocator>::
operator=(vector &&other_) {
m_data = std::move(other_.m_data);
m_size = other_.m_size;
m_capacity = other_.m_capacity;
other_.m_data = nullptr;
other_.m_capacity = 0;
other_.m_size = 0;
return *this;
}
template <class Allocator>
vector<bool, Allocator>::~vector() noexcept {
m_allocator.deallocate(m_data, m_capacity);
m_size = 0;
m_capacity = 0;
}
template <class Allocator>
constexpr void vector<bool, Allocator>::assign(size_type count_,
const bool &value_) {
reserve(count_ * m_growing_rate);
m_size = count_;
std::fill(begin(), end(), value_);
}
template <class Allocator>
template <class InputIt>
constexpr void vector<bool, Allocator>::assign(InputIt first_, InputIt last_) {
size_type length_of_interval =
static_cast<size_type>(std::distance(first_, last_));
reserve((size() + length_of_interval) * m_growing_rate);
std::move(first_, last_, begin());
m_size += static_cast<size_type>(std::distance(first_, last_) * 2);
}
template <class Allocator>
constexpr void
vector<bool, Allocator>::assign(std::initializer_list<bool> il_) {
reserve(il_.size() * m_growing_rate);
std::move(il_.begin(), il_.end(), begin());
m_size = il_.size();
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::allocator_type
vector<bool, Allocator>::get_allocator() const noexcept {
return m_allocator;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::reference
vector<bool, Allocator>::at(size_type index_) {
if (index_ >= size()) {
throw std::out_of_range("Billions of Bilious Blue Blistering Barnacles! "
"You attempted to access out of range");
}
return m_data[index_];
}
template <class Allocator>
typename vector<bool, Allocator>::const_reference constexpr vector<
bool, Allocator>::at(size_type index_) const {
if (index_ >= size()) {
throw std::out_of_range("Billions of Bilious Blue Blistering Barnacles! "
"Attemp to access out of range");
}
return m_data[index_];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::reference vector<bool, Allocator>::
operator[](size_type pos_) {
return m_data[pos_];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_reference
vector<bool, Allocator>::operator[](size_type pos_) const {
return m_data[pos_];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::reference
vector<bool, Allocator>::front() {
return m_data[0];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_reference
vector<bool, Allocator>::front() const {
return m_data[0];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::reference
vector<bool, Allocator>::back() {
return m_data[m_size - 1];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_reference
vector<bool, Allocator>::back() const {
return m_data[m_size - 1];
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::begin() noexcept {
return (m_data + 0);
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_iterator
vector<bool, Allocator>::begin() const noexcept {
return (m_data + 0);
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_iterator
vector<bool, Allocator>::cbegin() const noexcept {
return (m_data + 0);
}
template <class Allocator>
typename vector<bool, Allocator>::reverse_iterator
vector<bool, Allocator>::rbegin() noexcept {
return reverse_iterator(end());
}
template <class Allocator>
typename vector<bool, Allocator>::const_reverse_iterator
vector<bool, Allocator>::rbegin() const noexcept {
return const_reverse_iterator(end());
}
template <class Allocator>
typename vector<bool, Allocator>::const_reverse_iterator
vector<bool, Allocator>::crbegin() const noexcept {
return const_reverse_iterator(end());
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::end() noexcept {
return (m_data + m_size);
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_iterator
vector<bool, Allocator>::end() const noexcept {
return (m_data + m_size);
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::const_iterator
vector<bool, Allocator>::cend() const noexcept {
return (m_data + m_size);
}
template <class Allocator>
typename vector<bool, Allocator>::reverse_iterator
vector<bool, Allocator>::rend() noexcept {
return reverse_iterator(begin());
}
template <class Allocator>
typename vector<bool, Allocator>::const_reverse_iterator
vector<bool, Allocator>::rend() const noexcept {
return const_reverse_iterator(begin());
}
template <class Allocator>
typename vector<bool, Allocator>::const_reverse_iterator
vector<bool, Allocator>::crend() const noexcept {
return const_reverse_iterator(cbegin());
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::size_type
vector<bool, Allocator>::size() const noexcept {
return m_size;
}
template <class Allocator>
constexpr void vector<bool, Allocator>::resize(size_type count_) {
m_size = count_;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
}
template <class Allocator>
constexpr void vector<bool, Allocator>::resize(size_type count_,
const value_type &value_) {
size_type old_size = m_size;
m_size = count_;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
if (old_size > count_) {
std::fill(begin() + count_, begin() + old_size, value_);
} else {
std::fill(begin() + old_size, begin() + count_, value_);
}
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::size_type
vector<bool, Allocator>::capacity() const noexcept {
return m_capacity;
}
template <class Allocator>
constexpr bool vector<bool, Allocator>::empty() const noexcept {
// return m_size == 0;
return begin() == end();
}
template <class Allocator>
constexpr void vector<bool, Allocator>::reserve(size_type new_cap_) {
if (new_cap_ != m_capacity) {
if (new_cap_ > max_size())
throw std::length_error("You, imitation Incas, you... Length ERROR!!!");
if (empty()) {
m_data = m_allocator.allocate(new_cap_);
m_capacity = new_cap_;
} else {
bool *tmp = m_allocator.allocate(new_cap_);
std::move(begin(), end(), tmp);
m_allocator.deallocate(m_data, m_capacity);
m_data = tmp;
tmp = nullptr;
m_capacity = new_cap_;
}
}
}
template <class Allocator>
constexpr void vector<bool, Allocator>::shrink_to_fit() {
m_capacity = m_size;
}
template <class Allocator>
template <class... Args>
constexpr void vector<bool, Allocator>::emplace_back(Args &&... args_) {
++m_size;
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
*(end() - 1) = std::move(bool(std::forward<Args>(args_)...));
}
template <class Allocator>
constexpr void vector<bool, Allocator>::push_back(const bool &val_) {
m_data[m_size++] = val_;
if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
}
template <class Allocator>
constexpr void vector<bool, Allocator>::push_back(bool &&val_) {
m_data[m_size++] = std::move(val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
}
template <class Allocator>
constexpr void vector<bool, Allocator>::pop_back() {
if (!empty()) {
--m_size;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
}
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::size_type
vector<bool, Allocator>::max_size() const noexcept {
return std::numeric_limits<difference_type>::max();
}
template <class Allocator>
template <class... Args>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::emplace(const_iterator pos_, Args &&... args_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = std::move(std::forward<Args>(args_)...);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::insert(const_iterator pos_, const bool &val_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = val_;
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
if (empty()) {
*begin() = val_;
++m_size;
return begin();
}
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::insert(const_iterator pos_, bool &&val_) {
iterator ret = const_cast<iterator>(pos_);
++m_size;
std::move_backward(ret, end() - 1, end());
*ret = std::move(val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
if (empty()) {
*begin() = std::move(val_);
++m_size;
return begin();
}
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::insert(const_iterator pos_, size_type count_,
const bool &val_) {
iterator ret = const_cast<iterator>(pos_);
if (empty() && capacity() < count_) {
reserve(count_ * 2);
m_size = count_;
std::fill(begin(), end(), val_);
return begin();
} else {
m_size += count_;
std::move_backward(ret, end() - count_, end());
std::fill(ret, ret + count_, val_);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
}
template <class Allocator>
template <class InputIt>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::insert(const_iterator pos_, InputIt first_,
InputIt last_) {
iterator ret = const_cast<iterator>(pos_);
size_type diff = static_cast<size_type>(std::distance(first_, last_));
m_size += diff;
std::move_backward(ret, end() - diff, end());
std::move(first_, last_, ret);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::insert(const_iterator pos_,
std::initializer_list<bool> lst_) {
iterator ret = const_cast<iterator>(pos_);
m_size += lst_.size();
std::move_backward(ret, end() - lst_.size(), end());
std::move(lst_.begin(), lst_.end(), ret);
if (size() * 2 >= capacity())
reserve(capacity() * m_growing_rate);
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::erase(const_iterator pos_) {
iterator ret = const_cast<iterator>(pos_);
std::move(ret + 1, end(), ret);
--m_size;
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
return ret;
}
template <class Allocator>
constexpr typename vector<bool, Allocator>::iterator
vector<bool, Allocator>::erase(const_iterator first_, const_iterator last_) {
difference_type diff = last_ - first_;
iterator ret = const_cast<iterator>(first_);
std::move(last_, cend(), ret);
m_size -= static_cast<size_type>(diff);
if (size() <= capacity() / 4)
reserve(size() / m_growing_rate);
else if (size() * 2 >= capacity())
reserve(m_capacity * m_growing_rate);
return ret;
}
template <class Allocator>
constexpr void vector<bool, Allocator>::flip() noexcept {
std::for_each(begin(), end(), [](bool &element) { element = !element; });
}
template <class Allocator>
constexpr void vector<bool, Allocator>::clear() noexcept {
m_size = 0;
}
template <class Allocator>
constexpr void vector<bool, Allocator>::swap(vector<bool, Allocator> &other_) {
size_type tmp_size = other_.size();
size_type tmp_capacity = other_.capacity();
auto tmp_data = other_.m_data;
other_.m_size = m_size;
other_.m_capacity = m_capacity;
other_.m_data = m_data;
m_size = tmp_size;
m_capacity = tmp_capacity;
m_data = tmp_data;
}
template <class Allocator>
constexpr void vector<bool, Allocator>::swap(reference x,
reference y) noexcept {
reference tmp = x;
x = y;
y = tmp;
}
} // namespace p1v0t
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:09:14.863",
"Id": "434223",
"Score": "0",
"body": "@L.F. I really didn't know how to write it and simply copy pasted it from [here](https://howardhinnant.github.io/allocator_boilerplate.html#new). It encouraged me to write rest of implementation."
}
] | [
{
"body": "<p>Here are some suggestions.</p>\n\n<h1>Non conformance</h1>\n\n<p>Many of your functions are marked <code>constexpr</code>. This is non-conforming. Per <a href=\"http://eel.is/c++draft/constexpr.functions\" rel=\"nofollow noreferrer\">[constexpr.functions]</a>:</p>\n\n<blockquote>\n <p>This document explicitly requires that certain standard library\n functions are <code>constexpr</code> ([dcl.constexpr]).\n <strong>An implementation shall not declare any standard library function signature as <code>constexpr</code> except for those where it is explicitly\n required.</strong> Within any header that provides any non-defining\n declarations of constexpr functions or constructors an implementation\n shall provide corresponding definitions.</p>\n</blockquote>\n\n<p>And generally speaking, you cannot expect allocation to be constexpr anyway.</p>\n\n<p>You are missing allocator overloads for the constructors. Specifically, the following overloads vanish altogether:</p>\n\n<blockquote>\n<pre><code>explicit vector(const Allocator&) noexcept; \nvector(const vector&, const Allocator&);\nvector(vector&&, const Allocator&);\n</code></pre>\n</blockquote>\n\n<p>And the allocator parameters are missing in the following overloads:</p>\n\n<blockquote>\n<pre><code>explicit vector(const Allocator&) noexcept;\nexplicit vector(size_type n, const Allocator& = Allocator());\nvector(size_type n, const T& value, const Allocator& = Allocator());\ntemplate<class InputIterator>\n vector(InputIterator first, InputIterator last, const Allocator& = Allocator());\nvector(const vector&, const Allocator&);\nvector(vector&&, const Allocator&);\nvector(initializer_list<T>, const Allocator& = Allocator());\n</code></pre>\n</blockquote>\n\n<p>They aren't hard to implement, so why not implement them anyway?</p>\n\n<p>You mark your destructor virtual. This is definitely wrong. <code>vector</code> is not designed for runtime polymorphism. Marking the destructor virtual can lead to severe consequences.</p>\n\n<p><code>max_size</code> returns <code>size_type</code>, not <code>difference_type</code>. <code>data</code> returns <code>T*</code> and <code>const T*</code>, not <code>pointer</code> and <code>const_pointer</code> (they can be different). <code>swap</code> is not unconditionally <code>noexcept</code>; the correct version is</p>\n\n<blockquote>\n<pre><code>void swap(vector&)\n noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value ||\n allocator_traits<Allocator>::is_always_equal::value);\n</code></pre>\n</blockquote>\n\n<p>You use <code>fill</code> on uninitialized memory:</p>\n\n<pre><code>template <typename T, class Allocator>\nconstexpr vector<T, Allocator>::vector(size_t n_, const value_type &val_) {\n m_size = m_capacity = n_;\n m_data = m_allocator.allocate(m_capacity);\n\n std::fill(begin(), end(), val_);\n}\n</code></pre>\n\n<p>This is undefined behavior because the lifetime of the objects are not started. You should use <code>uninitialized_fill</code> instead, which requires <code>#include <memory></code>. (This happens multiple times in your code.)</p>\n\n<p>The iterator overload of the constructor participates in overload resolution only when <code>InputIt</code> is an input iterator. The extent to which the library determines input iterators is unspecified, but at least integer types should not qualify as input iterator. Your version participates in overload resolution even if <code>InputIt</code> is an integer type. This can be fixed with SFINAE:</p>\n\n<pre><code>template <class InputIt, typename std::iterator_traits<InputIt>::iterator_category* = nullptr>\nvector(InputIt first, InputIt last);\n</code></pre>\n\n<p>Or, with C++20, concepts:</p>\n\n<pre><code>template <std::input_iterator InputIt>\nvector(InputIt first, InputIt last);\n</code></pre>\n\n<p>Moving from <code>initializer_list</code> does not do what you expect it to do because the elements of <code>initializer_list</code> are const. Moreover, using <code>move</code> on uninitialized memory is undefined behavior. Use <code>uninitialized_copy</code> instead.</p>\n\n<p>The copy constructor of <code>vector</code> calls <code>std::allocator_traits<allocator_type>::select_on_container_copy_construction</code> to select the appropriate allocator. And again, don't use <code>move</code>. Use <code>uninitialized_copy</code>.</p>\n\n<p>Similarly, the copy assignment operator should decide whether to propagate the allocator depending on whether <code>std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment</code> is true or not.</p>\n\n<p>These also apply to the move operations. And consider using the <a href=\"https://stackoverflow.com/q/3279543\">copy-and-swap</a> idiom when feasible.</p>\n\n<p>Your <code>shrink_to_fit</code> is problematic:</p>\n\n<pre><code>template <typename T, class Allocator>\nvoid vector<T, Allocator>::shrink_to_fit() {\n m_capacity = m_size;\n}\n</code></pre>\n\n<p>This breaks the class invariant and causes problems on deallocation.</p>\n\n<p>You never call constructors or destructors on the elements. This makes your <code>vector</code> unable to handle nontrivial types.</p>\n\n<h1>Other suggestions</h1>\n\n<p>Generally speaking, <code>#pragma once</code> is OK for me. But in this case, since you are implementing a component in the standard library, I'd advise you to resort to <code>#ifndef</code> — <code>#define</code> — <code>#endif</code> for portability.</p>\n\n<p>Your data members <code>m_allocator</code>, <code>m_data</code>, <code>m_capacity</code>, and <code>m_size</code> are all public. I don't see a reason. I suggest making them private. Also, why is <code>m_growing_rate</code> of type <code>uint8_t</code> (which should be <code>std::uint8_t</code> and requires <code>#include <cstdint></code>), and why is it not <code>constexpr</code>?</p>\n\n<p>You love assignment and hate initializer clauses. This way, you first default initialize (or use the in class member initializer) and then assign, causing performace degradation. Use initializer clauses. Instead of:</p>\n\n<pre><code>template <typename T, class Allocator>\nvector<T, Allocator>::vector() noexcept(noexcept(Allocator())) {\n m_size = 0;\n reserve(1);\n}\n</code></pre>\n\n<p>It is sufficient to do</p>\n\n<pre><code>template <typename T, class Allocator>\nvector<T, Allocator>::vector() noexcept(noexcept(Allocator())) { }\n</code></pre>\n\n<p>Since you already provided an in class initializer for <code>m_size</code>.</p>\n\n<p>Your allocation policy is to always reserve a lot of space. <code>vector</code> is not always resized. If the user doesn't intend to grow it, your policy actually decreases efficiency. I would suggest reserving space only on <code>insert</code> or the like.</p>\n\n<p>It is not wrong to use <code>m_allocator.allocate(m_capacity)</code>, but it is still advised to do <code>std::allocator_traits<Allocator>::allocate(m_allocator, m_capacity)</code>.</p>\n\n<p>Your code features duplication. For example, it may be a good idea to let the <code>initializer_list</code> overloads delegate to the iterator overloads.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:16:49.150",
"Id": "434224",
"Score": "0",
"body": "Gosh... Thanks from the heart!! I will definitely consider all the things you point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:28:42.957",
"Id": "434229",
"Score": "0",
"body": "Can you give me one more pointer for how to implement one of the member functions that take the allocator as a parameter. I checked out the some other Standard Library implementations, the vector class inherited from other base class. I thought it's something related with it and didn't try to implement them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:16:44.753",
"Id": "434258",
"Score": "2",
"body": "@adem You do not necessarily need to use inheritance. Simply initialize `m_allocator` with the given argument and use `std::allocator_traits<Allocator>::allocate(m_allocator, ...)` to allocate memory, `std::allocator_traits<Allocator>::deallocate(m_allocator, ...)` to deallocate memory, `std::allocator_traits<Allocator>::construct(m_allocator, ...)` to construct the elements, and `std::allocator_traits<Allocator>::destroy(m_allocator, ...)` to destroy them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:17:51.833",
"Id": "434259",
"Score": "0",
"body": "@adem Also, implementing `vector` properly is extremely nontrivial. You should probably start simpler if you consider yourself a beginner. I cannot say for sure I can implement `vector` well either :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T10:47:42.930",
"Id": "434272",
"Score": "2",
"body": "Yeah, when I saw the `propagate` things... I got 'umm I shouldn't be here' feeling :)))"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:38:40.147",
"Id": "223914",
"ParentId": "223899",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "223914",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T20:38:27.923",
"Id": "223899",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel",
"vectors"
],
"Title": "STL-like vector implemention in C++"
} | 223899 |
<h2>Overview</h2>
<p>I got rubber-stamped in code review today even though I called out specific concerns about my own code and asked for advice, so I'm turning to this community for advice. Thank you for taking a look!</p>
<p>I'm implementing a simple protocol in C. The protocol is composed mostly of fixed-width messages, each of which can be directly expressed as a single <code>struct</code>.</p>
<p>I've abstracted the protocol in this post for simplicity and to focus on one aspect that is complicating the design of my client library.</p>
<p>Quick note: this is in an embedded environment, I am trying to avoid heap allocations, and all the structs are packed so byte alignment isn't done on their underlying layout.</p>
<h2>Description</h2>
<p>Each message has a message id, which are defined in an enum:</p>
<pre><code>typedef enum {
NJ_MESSAGE_ID_LOGIN_REQUEST = 0x00000000,
NJ_MESSAGE_ID_LOGIN_RESPONSE = 0x00008000,
NJ_MESSAGE_ID_REGISTER_REQUEST = 0x00000100,
NJ_MESSAGE_ID_REGISTER_RESPONSE = 0x00008100,
} nj_message_id;
</code></pre>
<p>All messages have a header, which is defined in a struct:</p>
<pre><code>typedef struct {
uint16_t protocol_version;
uint16_t message_id;
uint16_t sequence_id;
} nj_header;
</code></pre>
<p>Each message has its own struct that starts with the header:</p>
<pre><code>typedef struct {
nj_header header;
uint8_t username[32];
uint8_t password[32];
} nj_login_request;
</code></pre>
<p>Finally, there is the <code>nj_send</code> function:</p>
<pre><code>void nj_send(nj_header *message, nj_message_id message_id);
</code></pre>
<p>The <code>nj_send</code> function accepts a pointer to <code>nj_header</code> but it is expected that this is actually a pointer to a full message that has been casted.</p>
<p>Here is an example of how to construct and send a message:</p>
<pre><code>#include <string.h>
#include "nj.h"
int main(void)
{
nj_login_request login_request = { 0 };
strncpy(login_request.username, "joe", sizeof(login_request.username));
strncpy(login_request.password, "joe", sizeof(login_request.password));
nj_send((nj_header *) login_request, NJ_MESSAGE_ID_LOGIN_REQUEST);
}
</code></pre>
<p>I like this because:</p>
<ul>
<li>It's not verbose and easy to do on the stack.</li>
<li>Working directly with the flat struct enables sizeof.</li>
<li>The object is in exactly the same format it will be on the wire.</li>
</ul>
<h2>Challenge</h2>
<p>Most of the protocol is fixed-width, and for those messages the example above is perfect.</p>
<p>There is one message, however, that is variable-width: the register request. In this message, the client may specify zero or more "services", each of which have an "id" and "flags".</p>
<p>So a definition for that message type might look like this:</p>
<pre><code>typedef struct {
uint8_t id;
uint8_t flags;
}
typedef struct {
nj_header header;
uint8_t services_count;
nj_services *services;
} nj_register_request;
</code></pre>
<p>However, this is no longer a flat struct. That makes things difficult to deal with on the stack, and complicates my <code>nj_send</code> logic which so far has been able to assume that the pointer it is given refers to a byte-for-byte flat representation of the full image.</p>
<p>To address that, I've created a struct <code>nj_register_request_partial</code> (rather than <code>nj_register_request</code>, which doesn't exist in my code):</p>
<pre><code>typedef struct {
nj_header header;
uint8_t services_count;
// will be followed by some number of `nj_service` structs
} nj_register_request_partial;
</code></pre>
<p>And two functions that get and set services within a buffer which is assumed to start with the <code>nj_register_request_partial</code> struct:</p>
<pre><code>nj_service *nj_get_register_request_service(nj_register_request_partial *request,
uint8_t index)
{
off_t offset = 0;
if (index > request->services_count)
{
return NULL;
}
offset = sizeof(nj_register_request_partial) + sizeof(nj_service) * index;
return (nj_service *) request + offset;
}
void nj_set_register_request_service(nj_register_request_partial *request,
nj_service *service, uint8_t index)
{
off_t offset = 0;
if (index > request->services_count)
{
return;
}
offset = sizeof(nj_register_request_partial) + sizeof(nj_service) * index;
memcpy(request + offset, service, sizeof(nj_service));
}
</code></pre>
<p>To construct and send a register request message would look like this:</p>
<pre><code>#include <stdint.h>
#include <string.h>
#include "nj.h"
int main(void)
{
// create a buffer of the maximum size, then a pointer to the front of
// that buffer. the pointer represents the portion that is described by
// the `nj_register_request_partial` struct. the remaining bytes can store
// instances of the `nj_service` struct.
uint8_t buffer[NJ_MAX_MESSAGE_LEN] = { 0 };
nj_register_request_partial *request = (nj_register_request_partial *) buffer;
request->services_count = 2;
for (int i = 0; i < 2; i++)
{
nj_service service = { 0 };
service.id = i;
service.flags = 0x00;
nj_set_register_request_service(request, &service, i);
}
nj_send((nj_header *) request, NJ_MESSAGE_ID_REGISTER_REQUEST);
}
</code></pre>
<p>I'm not satisfied with this because:</p>
<ul>
<li>It requires allocating a buffer for the max message length.</li>
<li>It requires the user to do type punning in a non-obvious way (if they want to avoid heap allocations).</li>
<li>But most of all, the message definition is not obvious from looking at the struct definition.</li>
</ul>
<p>However, I do like that I'm still dealing with the direct byte representation of what will go on the wire.</p>
<p><strong>Is there a better way to represent variable-width messages as a composition of structs?</strong></p>
<hr>
<h2>Full Source</h2>
<p>nj.h</p>
<pre><code>#pragma once
#include <stdint.h>
#define NJ_PROTOCOL_VERSION 0x00000001
#define NJ_MAX_MESSAGE_LEN 256
typedef enum {
NJ_MESSAGE_ID_LOGIN_REQUEST = 0x00000000,
NJ_MESSAGE_ID_LOGIN_RESPONSE = 0x00008000,
NJ_MESSAGE_ID_REGISTER_REQUEST = 0x00000100,
NJ_MESSAGE_ID_REGISTER_RESPONSE = 0x00008100,
} nj_message_id;
#pragma pack(push, 1)
typedef struct {
uint8_t id;
uint8_t flags;
} nj_service;
typedef struct {
uint16_t protocol_version;
uint16_t message_id;
uint16_t sequence_id;
} nj_header;
typedef struct {
nj_header header;
uint8_t username[32];
uint8_t password[32];
} nj_login_request;
typedef struct
{
nj_header header;
uint8_t error;
} nj_login_response;
typedef struct
{
nj_header header;
uint8_t sevices_count;
// will be followed by some number of `nj_service` structs
} nj_register_request_partial;
typedef nj_login_response nj_register_response;
#pragma pack(pop)
void nj_send(nj_header *message, nj_message_id message_id);
nj_service *nj_get_register_request_service(nj_register_request_partial *request,
uint8_t index);
void nj_set_register_request_service(nj_register_request_partial *request,
nj_service *service, uint8_t index);
</code></pre>
<p>nj.c</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include "nj.h"
static uint16_t nj_get_unique_sequence_id(void)
{
static uint16_t rolling_counter = 0;
return rolling_counter++;
}
static void nj_populate_header(nj_header *message, nj_message_id message_id)
{
message->protocol_version = NJ_PROTOCOL_VERSION;
message->message_id = message_id;
message->sequence_id = nj_get_unique_sequence_id();
}
static size_t nj_sizeof(nj_header *msg)
{
if (msg->message_id == NJ_MESSAGE_ID_REGISTER_REQUEST)
{
nj_register_request_partial *req = (nj_register_request_partial *) message;
size_t size = sizeof(nj_register_request_partial);
size += req->services_count * sizeof(nj_service);
return size;
}
switch (msg->message_id)
{
case NJ_MESSAGE_ID_LOGIN_REQUEST:
return sizeof(nj_login_request);
case NJ_MESSAGE_ID_LOGIN_RESPONSE:
return sizeof(nj_login_response);
case NJ_MESSAGE_ID_REGISTER_RESPONSE:
return sizeof(nj_register_response);
default:
break;
}
return 0;
}
void nj_send(nj_header *message, nj_message_id message_id)
{
uint8_t buffer[NJ_MAX_MESSAGE_LEN] = { 0 };
size_t size = nj_sizeof(message);
size_t iterator = 0;
if (message == NULL)
{
return;
}
nj_populate_header(message, message_id);
// implementation not important
// `message` is treated as a void pointer and its bytes are put directly
// onto the wire. single datagram packet.
// instead i'm just printing the buffer.
memcpy(buffer, message, size);
while (iterator < size)
{
printf("0x%02x ", buffer[iterator++]);
if (iterator % 0x10 == 0)
{
printf("\n");
}
}
printf("\n");
}
nj_service *nj_get_register_request_service(nj_register_request_partial *request,
uint8_t index)
{
off_t offset = 0;
if (index > request->services_count)
{
return NULL;
}
offset = sizeof(nj_register_request_partial) + sizeof(nj_service) * index;
return (nj_service *) request + offset;
}
void nj_set_register_request_service(nj_register_request_partial *request,
nj_service *service, uint8_t index)
{
off_t offset = 0;
if (index > request->services_count)
{
return;
}
offset = sizeof(nj_register_request_partial) + sizeof(nj_service) * index;
memcpy(request + offset, service, sizeof(nj_service));
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:59:26.150",
"Id": "434312",
"Score": "0",
"body": "Where is the definition of the type `nj_register_request`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:25:55.933",
"Id": "434315",
"Score": "0",
"body": "@CacahueteFrito hello! that was a mistake, it should be `nj_register_request_partial`. i've updated the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:02:30.297",
"Id": "434343",
"Score": "0",
"body": "I don't see what is going on in these lines: `uint8_t buffer[NJ_MAX_MESSAGE_LEN] = { 0 };\n nj_register_request_partial *request = (nj_register_request_partial *) buffer;` . The size of the `struct` is fixed, so I don't see why you need to use an array and not just directly declare a `struct`. Could you add some extra comments about that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:33:56.160",
"Id": "434347",
"Score": "0",
"body": "@CacahueteFrito your confusion pretty good evidence that my solution leaves a lot to be desired. :) i've tried to explain that a little bit more in my most recent edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:35:39.483",
"Id": "434348",
"Score": "0",
"body": "@CacahueteFrito basically, because `nj_register_request_partial` is a _partial_ definition of the full register request message. it will be followed by some number of `nj_service` structs, and i'm trying to find an elegant way of expressing that while keeping the byte representation flat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:38:56.563",
"Id": "434350",
"Score": "0",
"body": "Maybe a `union`. Or a new compatible `struct` that has has the maximum size."
}
] | [
{
"body": "<h2><code>for</code></h2>\n\n<pre><code>size_t iterator = 0;\nwhile (iterator < size) {\n printf(\"0x%02x \", buffer[iterator++]);\n if (iterator % 0x10 == 0)\n {\n printf(\"\\n\");\n }\n}\n</code></pre>\n\n<p>should use a <code>for</code> loop:</p>\n\n<pre><code>for (size_t i = 0; i < size; i++) {\n printf(\"0x%02X\", buffer[i]);\n if ((i + 1) % 16)\n putchar(' ');\n else\n putchar('\\n');\n}\n</code></pre>\n\n<p>Note that I also removed the trailing space, which was unneeded.</p>\n\n<p>Also note that I used uppercase for the hex number to differentiate it from the <code>0x</code> prefix.</p>\n\n<hr>\n\n<h2><code>const</code></h2>\n\n<p>Functions that accept a pointer but are not going to modify it's contents should note this, to allow some optimizations, and as documentation:</p>\n\n<pre><code>static size_t nj_sizeof(const nj_header *msg)\n</code></pre>\n\n<hr>\n\n<h2><code>typedef</code></h2>\n\n<p>I would advise to differentiate <code>typedef</code> names from any other name, so that when I read the code it is visually clear that it's a type, and not the name of a variable or function.</p>\n\n<p>Being <code>typedef</code>s to <code>struct</code> I would add the suffix <code>_s</code>:</p>\n\n<pre><code>struct My_Struct {\n int a;\n};\ntypedef struct My_Struct my_struct_s;\n</code></pre>\n\n<p>However, I wouldn't even typedef. It just hides the information that the type is a <code>struct</code>, which I prefer to know even if I write 5 extra characters</p>\n\n<hr>\n\n<h2><code>ARRAY_SIZE()</code></h2>\n\n<p>I recently found an interesting thing:</p>\n\n<p>Consider your line <code>strncpy(login_request.username, \"joe\", sizeof(login_request.username));</code></p>\n\n<p>It's obvious that you know that <code>login_request.username</code> is a <code>char []</code>, but let's imagine that some day you (or worse, someone else that doesn't have the same knowledge of the program as you) change it to be a <code>char *</code>. That line of the <code>strncpy</code> will probably get unnoticed, but will produce a wrong result.</p>\n\n<p>Solution: Use the following:</p>\n\n<pre><code>#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))\n\nstrncpy(login_request.username, \"joe\", ARRAY_SIZE(login_request.username));\n</code></pre>\n\n<p>If the array changes to a pointer, it will be noticed by the compiler (at least on a decent compiler). On GCC this is a warning: <code>-Wsizeof-pointer-div</code> (GCC 8 has it enabled in <code>-Wall</code>. It's a very recent warning, and don't expect to have it in old GCC versions).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:44:57.980",
"Id": "434296",
"Score": "0",
"body": "hi! these are good style comments, thank you. regarding `for`: our style guide requires declaring and initializing all variables at the top of scope. so, generally, `while` ends up getting used instead of `for` in most cases (since the iterator is already initialized). we actually have found it to be liberating, because `while` is easier to read (more closely matches the way humans speak naturally) and it lets us do things after the increment (avoiding the `+ 1` in your `if`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:47:30.827",
"Id": "434298",
"Score": "0",
"body": "`const` is absolutely a good idea and an oversight on my part. as for the `typedef`s, our style guide discourages hungarian notation except in the case of real-world units like \"ms\" (milliseconds), but i see your point about hiding the underlying data so ultimately i'm going to do away with the `typedef`s entirely and just use (e.g.) `struct nj_login_request` and `enum nj_message_id` directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:48:45.307",
"Id": "434299",
"Score": "0",
"body": "any advise for a clean way to manage variable-width messages as a composition of multiple `struct`s?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:07:30.183",
"Id": "223942",
"ParentId": "223905",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T23:58:25.543",
"Id": "223905",
"Score": "1",
"Tags": [
"c",
"protocols"
],
"Title": "Simple protocol client library"
} | 223905 |
<p>An alternative to <code>std::function</code> for when compile time is more important than runtime performance. Doesn't pull in any headers.</p>
<p>(<code>#include <functional></code> pulls in 19k lines of code.)</p>
<p>This satisfies my needs, but I'm curious how it could be improved (without adding any dependencies).</p>
<pre><code>template<typename>
class func;
// Alternative to std::function for when compile time is
// more important than runtime performance. Doesn't pull in
// any headers.
template<typename Result, typename... Arguments>
class func<Result (Arguments...)> {
struct holder {
virtual ~holder() {}
virtual Result call(Arguments...) = 0;
virtual holder* clone() = 0;
};
template<typename Lambda>
struct lambda_holder : public holder {
virtual ~lambda_holder() {}
Lambda lambda;
lambda_holder(Lambda l) : lambda(l) { }
Result call(Arguments... args) override {
return lambda(args...);
}
holder* clone() override {
return new lambda_holder<Lambda>(lambda);
}
};
public:
func() { }
func(const func& f) {
holder = f.holder->clone();
}
func& operator=(const func& f) {
if(holder) { delete holder; }
holder = f.holder ? f.holder->clone() : nullptr;
return *this;
}
// Create from a lambda.
template<class F>
func(F f) {
holder = new lambda_holder<F>{f};
}
~func() {
if(holder) { delete holder; }
}
Result operator()(Arguments... args) const {
assert(holder);
return holder->call(args...);
}
operator bool() const {
return holder;
}
private:
holder *holder = nullptr;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:53:12.410",
"Id": "434189",
"Score": "0",
"body": "Did you aim to have the same semantics as `std::function`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T03:45:56.767",
"Id": "434199",
"Score": "0",
"body": "@L.F. Not really. I'm not even familiar with the finer points."
}
] | [
{
"body": "<ol>\n<li><p>Self-assignment may be expensive, but it should be a no-op instead of UB. I suggest copy-and-swap.</p></li>\n<li><p>Omitting move-semantics will most certainly cost you.</p></li>\n<li><p>Your naming of the internal class suggests all callables are lambdas. Not true!</p></li>\n<li><p>You cannot store any move-only callables. Admittedly <code>std::function</code> is also crippled in that respect. Just throw an exception if the non-copyable object needs to be copied.</p></li>\n<li><p>If your <code>function</code> has return-type <code>void</code>, it should simply discard the callables return-value. You don't.</p></li>\n<li><p><code>std::function</code> throws an exception if empty when called. Using <code>assert()</code> is less than a pale imitation.</p></li>\n<li><p><code>delete p;</code> if <code>p</code> is a null pointer is a no-op. No need to double-check.</p></li>\n<li><p>Conversion to <code>bool</code> should be <code>explicit</code>. Otherwise, conversion to any arithmetic type can happen.</p></li>\n<li><p>As you said, yours is less efficient. That's especially the case when <code>std::function</code> benefits from mandatory small-object-optimization.</p></li>\n<li><p>You don't use SFINAE when creating from a callable. That can be inconvenient.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:49:32.167",
"Id": "434194",
"Score": "0",
"body": "`std::function` can't do (4) either, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T02:37:41.770",
"Id": "434197",
"Score": "1",
"body": "@Taylor I don't think it can. But that hole is easily filled by deferring the error to runtime (throw exception when attempting to copy)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:49:51.137",
"Id": "434309",
"Score": "0",
"body": "I don't care much about performance of copying the function, but could I get similar calling performance as `std::function` without too much effort?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:36:23.067",
"Id": "223911",
"ParentId": "223908",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223911",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T00:10:53.180",
"Id": "223908",
"Score": "3",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"callback"
],
"Title": "std::function alternative with no dependencies"
} | 223908 |
<p>My code works fine but I definitely have unecessary repeat code. I'd like to use functions so I don't have repeat code. I would appreciate any advise on how to make my password generator code more concise.</p>
<p>I've tried looking through other forums but I couldn't find the answer I'm looking for.</p>
<pre><code>import string
import random
lowerCase = string.ascii_lowercase[:26]
upperCase = string.ascii_uppercase[:26]
numberList = ["1","2","3","4","5","6","7","8","9"]
specialCharacters = ["*","&","@","!"]
responseList = ["weak","medium","strong"]
randomCharacters =[ ]
i=0
while True:
choice = input("Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong. ")
if choice in responseList:
if choice == "weak":
while i<=5:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
i += 1
elif choice == "medium":
while i<=4:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
randomLetterUpper = random.choice(upperCase)
randomCharacters.append(randomLetterUpper)
i += 1
elif choice == "strong":
while i<=1:
randomLetterLower = random.choice(lowerCase)
randomCharacters.append(randomLetterLower)
randomLetterUpper = random.choice(upperCase)
randomCharacters.append(randomLetterUpper)
randomNumber = random.choice(numberList)
randomCharacters.append(randomNumber)
randomSpecialCharacter = random.choice(specialCharacters)
randomCharacters.append(randomSpecialCharacter)
i += 1
output = " ".join(randomCharacters)
print(output)
i = 0
randomCharacters =[]
else:
break
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T18:45:19.733",
"Id": "438780",
"Score": "0",
"body": "I'll write this up as an answer later, but if you are using Python 3.6 or newer for this, you should be using the `secrets` module for cryptographically secure random character selection; `random` was not designed for cryptographically secure random generation."
}
] | [
{
"body": "<p>A flexible and manageable approach would be to create a custom <code>PasswordGenerator</code> which will comprise all functionality for particular password levels. Putting it a separate module, thus it can be imported and used in any place of an application on demand.</p>\n\n<p>The one of possible implementations (considering your conditions):</p>\n\n<p><strong><code>password_generator.py</code></strong> :</p>\n\n<pre><code>import string\nimport random\n\n\nclass PasswordGenerator:\n\n LOWERCASE = string.ascii_lowercase[:26]\n UPPERCASE = string.ascii_uppercase[:26]\n NUMBERS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n SPECIAL_CHARS = [\"*\", \"&\", \"@\", \"!\"]\n LEVELS = (\"weak\", \"medium\", \"strong\") # password levels\n\n @staticmethod\n def _compose_passphrase(iter_num, char_types):\n return ''.join(random.choice(c_type) for i in range(iter_num)\n for c_type in char_types)\n\n @classmethod\n def weak(cls):\n iter_num = 6 # number of iterations\n char_types = (cls.LOWERCASE,)\n return cls._compose_passphrase(iter_num, char_types)\n\n @classmethod\n def medium(cls):\n iter_num = 5\n char_types = (cls.LOWERCASE, cls.UPPERCASE)\n return cls._compose_passphrase(iter_num, char_types)\n\n @classmethod\n def strong(cls):\n iter_num = 2\n char_types = (cls.LOWERCASE, cls.UPPERCASE, cls.NUMBERS, cls.SPECIAL_CHARS)\n return cls._compose_passphrase(iter_num, char_types)\n</code></pre>\n\n<p>Client script <strong><code>prompt_password.py</code></strong> :</p>\n\n<pre><code>from password_generator import PasswordGenerator\n\nwhile True:\n choice = input(\"Want to create a password? To make your choice for your password strength, \"\n \"please respond with one of the following: weak/medium/strong \")\n\n if choice in PasswordGenerator.LEVELS:\n print(getattr(PasswordGenerator, choice)()) # calling a respective method (password level)\n else:\n break\n</code></pre>\n\n<hr>\n\n<p>Running <code>prompt_password.py</code>:</p>\n\n<pre><code>Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong weak\nylwwcj\nWant to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong weak\nkktnkx\nWant to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong medium\njLiAoWaHbA\nWant to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong strong\nqG8@sM7*\nWant to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong strong\ntY8&eL7@\nWant to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong best\n\n\nProcess finished with exit code 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:03:05.763",
"Id": "223940",
"ParentId": "223910",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T19:24:48.117",
"Id": "223910",
"Score": "3",
"Tags": [
"python",
"strings",
"random"
],
"Title": "Random password generator with choice of three strengths"
} | 223910 |
<p>I've been starting to migrate some C++ code from imperative to more of a functional style. I'm new to functional programming so I'm trying to get a sense of how well this code fits into the functional programming paradigm.</p>
<p>The purpose of the code is to scan tokens from CSV files, and currently passes all the written tests I have.</p>
<p>Here's the header.</p>
<pre><code>#pragma once
#include <cstddef>
/// Enumerates the several types of CSV tokens.
enum class csvTokenType {
/// A null token.
Null,
/// A newline sequence.
Newline,
/// A separator character.
Separator,
/// A quoted cell.
QuotedCell,
/// An unquoted cell.
UnquotedCell
};
/// Contains data belonging to a token.
class csvToken final {
/// The type of this token.
csvTokenType type;
/// The character data belonging to the token.
const char* data;
/// The number of characters in the token.
size_t size;
public:
/// Constructs a null token.
csvToken() noexcept : type(csvTokenType::Null), data(""), size(0) { }
/// Constructs a CSV token.
/// @param t The type to assign the token.
/// @param d The data to assign the token.
/// @param s The size of the data being assigned to the token.
csvToken(csvTokenType t, const char* d, size_t s) noexcept : type(t), data(d), size(s) { }
/// Indicates if this is a valid token or not.
/// @returns True if it's a valid token, false otherwise.
operator bool () const noexcept {
return type != csvTokenType::Null;
}
/// Checks for token type equality.
/// @param otherType The type of token to check for.
/// @returns True if the types are equal, false otherwise.
bool operator == (csvTokenType otherType) const noexcept {
return type == otherType;
}
/// Checks for equality with string data.
/// @param str The string to check.
/// @returns True if the strings are equal, false otherwise.
bool operator == (const char* str) const noexcept;
};
/// Scans for a token.
/// @param data The data to scan.
/// @param size The size of the data to scan.
/// @returns The resultant token.
csvToken csvScan(const char* data, size_t size) noexcept;
</code></pre>
<p>Here's the implementation.</p>
<pre><code>#include "csvScan.hpp"
#include <algorithm>
#include <string.h>
namespace {
/// A simple class for quick and safe
/// string scanning.
struct csvStringView final {
/// The string data.
const char* data;
/// The size of the string.
size_t size;
/// Constructs the string view.
csvStringView(const char* d, size_t s) noexcept : data(d), size(s) { }
/// Gets a character at a specified offset.
/// @param i The offset of the character to get.
/// @returns The character at the specified offset.
/// If the offset is out of bounds, then zero is returned instead.
char operator [] (size_t i) const noexcept {
return (i < size) ? data[i] : 0;
}
/// Returns a beginning iterator.
/// @returns The beginning iterator.
const char* begin() const noexcept {
return data;
}
/// Returns the ending iterator.
/// @returns The ending iterator.
const char* end() const noexcept {
return data + size;
}
};
/// Returns the first non-null token
/// generated by one of the functions in the parameter list.
/// @tparam FirstMatcher The type of the first callable token scanner.
/// @tparam OtherMatchers The type of the other callable token scanners.
/// @param strView The string view to scan.
/// @param firstMatcher The first token scanner.
/// @param otherMatchers The other token scanners.
/// @returns The first non-null token from the given matchers.
template <typename FirstMatcher, typename... OtherMatchers>
csvToken csvFirstMatch(const csvStringView& strView, FirstMatcher firstMatcher, OtherMatchers... otherMatchers) {
auto token = firstMatcher(strView);
return token ? token : csvFirstMatch(strView, otherMatchers...);
}
/// The last resort matching function.
/// @tparam LastMatcher The type of the last token matcher.
/// @param strView The string view being scanned.
/// @param lastMatcher The last token matcher.
/// @returns The resultant token.
template <typename LastMatcher>
csvToken csvFirstMatch(const csvStringView& strView, LastMatcher lastMatcher) {
return lastMatcher(strView);
}
/// Indicates if a character is
/// a separator or not.
/// @param c The character to check.
/// @returns True if the character is
/// a separator, false if it is not.
bool csvIsSeparator(char c) noexcept {
return (c == ',') || (c == ';') || (c == '\t');
}
/// Indicates if the specified character
/// can be part of a newline sequence.
/// @param c The character to check.
/// @returns True if the character can
/// be part of a newline sequence, false otherwise.
bool csvIsNewline(char c) noexcept {
return (c == '\n') || (c == '\r');
}
/// Indicates if the specified
/// character can terminate an unquoted cell.
/// @param c The character to check.
/// @returns True if the character can terminate
/// the call, false otherwise.
bool csvIsCellTerminal(char c) noexcept {
return csvIsSeparator(c) || csvIsNewline(c);
}
/// Attempts to scan a separator character.
/// @param strView The string view to scan.
/// @returns The resultant token.
csvToken csvScanSeparator(const csvStringView& strView) noexcept {
bool match = csvIsSeparator(strView[0]);
csvToken goodToken(csvTokenType::Separator, strView.data, 1);
return match ? goodToken : csvToken();
}
/// Attempts to scan a line feed.
/// @param strView The string being scanned.
/// @returns The resultant token.
csvToken csvScanLF(const csvStringView& strView) noexcept {
csvToken goodToken(csvTokenType::Newline, strView.data, 1);
auto match = (strView[0] == '\n');
return match ? goodToken : csvToken();
}
/// Attempts to scan a line feed.
/// @param strView The string being scanned.
/// @returns The resultant token.
csvToken csvScanCRLF(const csvStringView& strView) noexcept {
csvToken goodToken(csvTokenType::Newline, strView.data, 2);
auto match = (strView[0] == '\r') && (strView[1] == '\n');
return match ? goodToken : csvToken();
}
/// Attempts to scan any known newline sequence.
/// @param strView The string being scanned.
/// @returns The resultant token.
csvToken csvScanNewline(const csvStringView& strView) noexcept {
return csvFirstMatch(strView, csvScanCRLF, csvScanLF);
}
/// Scans the contents of an unquoted cell.
/// @param strView The string view to scan.
/// @returns The resultant token.
csvToken csvScanUnquotedCell(const csvStringView& strView) noexcept {
const auto* it = std::find_if(strView.begin(), strView.end(), csvIsCellTerminal);
auto match = (it != strView.end());
csvToken goodToken(csvTokenType::UnquotedCell, strView.begin(), it - strView.begin());
return match ? goodToken : csvToken();
}
/// Scans a string view.
/// @param strView The string view to scan.
/// @returns The resultant token.
csvToken csvScan(const csvStringView& strView) noexcept {
return csvFirstMatch(strView, csvScanSeparator, csvScanNewline, csvScanUnquotedCell);
}
} // namespace
bool csvToken::operator == (const char* str) const noexcept {
size_t strSize = strlen(str);
return (size == strSize) && (memcmp(str, data, strSize) == 0);
}
csvToken csvScan(const char* data, size_t size) noexcept {
csvStringView strView(data, size);
return csvScan(strView);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:37:00.800",
"Id": "434321",
"Score": "0",
"body": "A usage example would be nice."
}
] | [
{
"body": "<p>Your code isn't functional, neither in the sense of working properly, nor in the sense of respecting the principles of functional programming.</p>\n\n<p>To parse a file, you need a way to consume the file. How would you do it with your function?</p>\n\n<pre><code>csvStringView fh = readFile(filepath.csv);\ncsvToken tok = csvFirstMatch(fh); \n// ???\n</code></pre>\n\n<p>You could imagine to compute a new <code>string_view</code> from the token length:</p>\n\n<pre><code>// ...\nauto fh2 = remove_prefix(fh, tok.length);\ncsvToken tok2 = csvFirstMatch(fh2);\n</code></pre>\n\n<p>But you'll need to do it an unspecified number of times. So either you do this in a loop, but a loop isn't functional, or you muscle-up your parsing function to return not only the token, but also the stream:</p>\n\n<pre><code>std::pair<Token, std::string_view> parse_token(std::string_view stream);\n</code></pre>\n\n<p>That's well and good, but once you consider it, you realize you need to take up a new challenge: how will you chain or compose in any way two calls to <code>parse_token</code> if the return type isn't the same as the argument type?</p>\n\n<p>The answer is actually quite obvious since we're talking about functional programming: you need a function to do that. Let's say we want to combine several parsers in an either/or way. We have a <code>parse_quoted_cell</code> and <code>parse_unquoted_cell</code> for instance and want to have the result of the fitting one:</p>\n\n<pre><code>auto parse_result = parse_quoted_cell(stream);\nif (parse_result.first.type == Token::failure)\n return parse_unquoted_cell(stream);\nreturn parse_result;\n</code></pre>\n\n<p>That can be easily generalized:</p>\n\n<pre><code>using Parse_result = std::pair<Token, Stream>;\nusing Parser = std::function<Parse_result(Stream)>;\n\nParser either_or(Parser f, Parser s) {\n return [f,s](Stream s) {\n auto res = f(stream);\n if (res.first.type == Token::failure) return s(stream);\n return res;\n };\n}\n</code></pre>\n\n<p>\"Either / or\" isn't the only composition type you need. There's also an \"and then\". For instance, to parse a cell, you need to either parse a quoted or an unquoted cell, but also either a separator or the end of file. How would you do that? With a function, of course, and it would look like this:</p>\n\n<pre><code>Parser and_then(Parser f, Parser s) {\n return [f,s](Stream s) {\n auto res = f(stream);\n if (res.first.type == Token::failure) return res;\n auto res2 = s(res.second);\n return Parse_result(combine(res.first, res2.first), res2.second);\n };\n}\n</code></pre>\n\n<p>Now we can create our cell parser from our building blocks:</p>\n\n<pre><code>Parser parse_cell = and_then(either_or(parse_quoted_cell, parse_unquoted_cell),\n either_or(parse_separator, parse_eof));\n</code></pre>\n\n<p>It is rather interesting to see that <code>parse_quoted_cell</code> can itself be built from other building blocks:</p>\n\n<pre><code>Parser parse_quoted_cell = and_then(and_then(parse_quote, parse_unquoted_cell),\n parse_quote);\n</code></pre>\n\n<p>There are many cases where the same parser must be applied an unknown number of times. For instance, to parse the whole file, <code>parse_cell</code> should be applied repeatedly, until the end of file:</p>\n\n<pre><code>Parser parse_file = repeat(parse_cell);\n</code></pre>\n\n<p>where <code>repeat</code> can be defined recursively:</p>\n\n<pre><code>Parser repeat(Parser p) {\n return [p](Stream s) {\n auto res = p(stream);\n if (res.first.type == Token::failure) return res;\n auto res2 = repeat(p)(res.second);\n return Parse_result(combine(res.first, res2.first), res2.second);\n };\n}\n</code></pre>\n\n<p>I admit that I didn't review your code in detail, but I feel like you should think the whole thing through again and then submit a revised program for a more detailed review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:55:06.340",
"Id": "434281",
"Score": "0",
"body": "Parsing a quoted cell can't be done the way you described it because different characters are allowed in a quoted cell then in a non quoted one. I'll revise and post again once it's done, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:14:08.043",
"Id": "434284",
"Score": "0",
"body": "@tay10r: you're right, I've over-simplified the csv part. I think the functional canvas is still valid though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:19:15.550",
"Id": "434285",
"Score": "0",
"body": "@papagada yeah you had some good feedback. I didn't plan on making the parser functional, hence the scan function being designed that way. Now though I'm kind of thinking on giving it a shot. Thanks for your feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:15:57.300",
"Id": "434293",
"Score": "0",
"body": "After reading this a bit more closely, the only thing you suggested that I didn't already implement in the code that I posted is the recursive `repeat` function. The `either_or` and `and_then` are implemented by the `csvFirstMatch` function. I don't think I would ever recursively parse a file, because doing that with a large enough CSV file would cause a stackoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:49:30.320",
"Id": "434300",
"Score": "0",
"body": "@tay10r: `either_or` and `and_then` can't be implemented *inside* a function, because their purpose is to compose functions into new, more powerful functions. But even that is besides the main point: you need a way to consume the file progressively, and the only way to do it functionally is to return the partially consumed file along with the parsed token. And there's no way around recursive parsing either if you want to keep your program functional. But it's perfectly respectable no to commit to functional programming"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:52:07.733",
"Id": "434301",
"Score": "0",
"body": "@tay10r: it's an interesting experience to try a functional-programming only language, such as Haskell, to see if it's something your really want to invest into"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T15:17:26.743",
"Id": "434305",
"Score": "0",
"body": "@papagada Yeah I'll have to give it a whirl. Thanks!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T10:21:39.020",
"Id": "223937",
"ParentId": "223916",
"Score": "2"
}
},
{
"body": "<p>A small observation on the includes and namespaces:</p>\n\n<p>We have <code>#include <cstddef></code>, but then use <code>size_t</code> in the global namespace, which is not portable according to the standard. We should be using <code>std::size_t</code> instead.</p>\n\n<p>In the other file, we include the C compatibility header <code><string.h></code> - prefer to include <code><cstring></code> in new code, so that the names are available unambiguously in the <code>std</code> namespace (e.g. <code>std::memcmp</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:57:27.043",
"Id": "434282",
"Score": "0",
"body": "Interesting, I didn't know size_t to not be portable in the global namespace. I was more looking to see how this code does in a functional paradigm but I'm glad you pointed this out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:34:42.043",
"Id": "434319",
"Score": "0",
"body": "@tay10r If you include <stdef.h> then size_t is in the global namespace (and may be in standard). If you include <cstddef> then size_t is in standard (and may by in the global namespace). Basically if you use the C++ header files the wrap the C standard library all the types are placed in the standard namespace. If you use the C language headers this has no concept of namespaces and thus places them in global scope. Note: The implications from this are that when writting C++ you should use the C++ header files and use the version that is in the standard namespace."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:04:47.457",
"Id": "223941",
"ParentId": "223916",
"Score": "1"
}
},
{
"body": "<p>My main observation is that there seem to be a lot of free standing functions:</p>\n\n<pre><code>csvToken csvFirstMatch(const csvStringView& strView, FirstMatcher firstMatcher, OtherMatchers... otherMatchers)\ncsvToken csvFirstMatch(const csvStringView& strView, LastMatcher lastMatcher)\nbool csvIsNewline(char c) noexcept\nbool csvIsCellTerminal(char c) noexcept\ncsvToken csvScanSeparator(const csvStringView& strView) noexcept\ncsvToken csvScanLF(const csvStringView& strView) noexcept\ncsvToken csvScanCRLF(const csvStringView& strView) noexcept\ncsvToken csvScanNewline(const csvStringView& strView) noexcept\ncsvToken csvScanUnquotedCell(const csvStringView& strView) noexcept\ncsvToken csvScan(const csvStringView& strView) noexcept\n</code></pre>\n\n<p>And three classes</p>\n\n<pre><code>enum class csvTokenType\nclass csvToken final\nstruct csvStringView final\n</code></pre>\n\n<p>But it does not spring out at my how to use this.<br>\nPersonally I would like to see something like:</p>\n\n<pre><code>CSVFile file(\"FileName\");\nfor(auto loop = file.begin(); loop != file.end(); ++loop) {\n // loop is now an iterator to a token.\n}\n\n// If you can do that with C++11\n// Then the simpler syntax for C++14 make it easier:\n\nCSVString data(stringLoadedFromASourceThatIsNotAFile);\nfor(auto const& token: data) {\n // token is now a reference to the next token in the loop.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:58:40.287",
"Id": "434362",
"Score": "0",
"body": "What's your point about free standing functions? The suggestions you made are confusing. What is being iterated in `CSVFile`? Is the the rows or columns? Anyone reading that is not going to know what's going on, especially since you named the iterator `loop` instead of something more standard (like `it`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T22:01:50.667",
"Id": "434364",
"Score": "0",
"body": "-1 because the code you suggested makes the style more imperative instead of functional. I clearly stated in the post that I wanted to know how well my code fits into the functional paradigm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T23:36:24.370",
"Id": "434369",
"Score": "0",
"body": "@tay10r Sad :-( The -1 will affect my score. Sorry you did not understand my review of your code. I'll refrain from further updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:27:39.873",
"Id": "434956",
"Score": "0",
"body": "@MartinYork Apparently the OP doesn't know what *functional* means at all, so +1 to compensate :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:28:38.983",
"Id": "434957",
"Score": "0",
"body": "@tay10r Functional programming never means more functions. This post is helping you make your code more functional."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:37:37.280",
"Id": "434960",
"Score": "0",
"body": "@L.F. Keeping functions small is something that was mentioned in one of Robert C. Martin's books, Clean Code. I keep functions small as best as I can and the result is generally there's more functions. It has nothing to do with functional programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T01:00:33.460",
"Id": "434966",
"Score": "0",
"body": "@MartinYork I realize the down vote was probably a bit harsh. I went ahead and up voted another one of your answers that I thought was useful. Thanks for the feedback, sorry I was a bit hostile!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:47:29.113",
"Id": "223960",
"ParentId": "223916",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223937",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T01:43:59.357",
"Id": "223916",
"Score": "4",
"Tags": [
"c++",
"functional-programming",
"csv"
],
"Title": "Functional CSV Parser"
} | 223916 |
<p>I have began to practice Python after a couple of years and for my first Project, i decided to make a fighting/rpg-like game with different characters. So far, I am only familiar with loops and functions, not classes or OOP. Please give me any feedback on how I could improve my code, through debugging, optimization, or adding more content (In case the game doesn't start due to the absence of highscore.txt, please make a text file called highscore, and of the first line insert an interger, and on the second put any name. This should not happen, but just in case :P).</p>
<pre><code>import random as r
######Getting High Score#####
try:
hs = open("highscore.txt","r+")
except:
hs = open("highscore.txt","x")
hs = open("highscore.txt","r+")
try:
score = hs.readlines(1)
score = int(score[0])
leader = hs.readlines(2)
leader = str(leader[0])
except:
hs = open("highscore.txt","w")
hs.write("0\n")
hs.write("null")
hs = open("highscore.txt","r")
score = hs.readlines(1)
score = int(score[0])
leader = hs.readlines(2)
leader = str(leader[0])
#####Introduction, Initializing player#####
print("\nWELCOME TO WONDERLANDS RPG!")
print("The High Score is:",score,"by",leader)
points = 0
player_name = input("\nEnter your hero's name: ")
#####Classes [health, attack 1 (only does set damage), attack 2 min, attack 2 max, attack 3 min, attack 3 max, heal min, heal max], Getting player's Class#####
knight = [100,10,5,15,0,25,5,10] #health: 100, attack 1: 10, attack 2: 5-15, attack 3: 5-25, heal: 5-10
mage = [50,15,10,20,-5,25,10,15] #health: 50, attack 1: 15, attack 2: 10-20, attack 3: -5-25, heal: 10-15
healer = [150,5,5,10,5,15,10,20] #health: 150, attack 1: 5, attack 2: 5-10, attack 3: 5-15, heal: 10-20
while True:
print("\n1. Knight: Health: ",knight[0],"; Attack 1:",knight[1],"; Attack 2:",knight[2],"-",knight[3],"; Attack 3:",knight[4],"-",knight[5],"; Heal:",knight[6],"-",knight[7])
print("2. Mage: Health: ",mage[0],"; Attack 1:",mage[1],"; Attack 2:",mage[2],"-",mage[3],"; Attack 3:",mage[4],"-",mage[5],"; Heal:",mage[6],"-",mage[7])
print("3. Healer: Health: ",healer[0],"; Attack 1:",healer[1],"; Attack 2:",healer[2],"-",healer[3],"; Attack 3:",healer[4],"-",healer[5],"; Heal:",healer[6],"-",healer[7])
player_class = input("\nSelect your class: 1, 2, or 3: ")
if player_class == "1":
player_class = knight
print("You have selected the Knight")
break
if player_class == "2":
player_class = mage
print("You have selected the Mage")
break
if player_class == "3":
player_class = healer
print("You have selected the Healer")
break
else:
print("Please select a valid class.")
continue
player_heal_max = player_class[0]
#####Difficulty/Upgrade Functions#####
def level_up(player,health_max):
while True:
lv_choice = input("\nWould you like to:\n Increase max health by 20 (1)\n Increase Healing Factor by 5 (2)\n increase your damage by 5 (3) ")
if lv_choice == "1":
health_max += 20
player[0] = health_max
return player,health_max
elif lv_choice == "2":
player[6] +=5
player[7] +=5
player[0] = health_max
return player, health_max
elif lv_choice == "3":
player[1] +=5
player[2] +=5
player[3] +=5
player[4] +=5
player[5] +=5
player[0] = health_max
return player, health_max
else:
print("Please enter in a valid number")
continue
def difficulty(ai,health_max,level):
if level == 1:
return ai
else:
ai[0] = health_max+15*round(0.5*level+0.5)
ai[1] +=5*round(0.5*level+0.5)
ai[2] +=5*round(0.5*level+0.5)
ai[3] +=5*round(0.5*level+0.5)
ai[4] +=5*round(0.5*level+0.5)
ai[5] +=5*round(0.5*level+0.5)
ai[6] +=5*round(0.5*level+0.5)
ai[7] +=5*round(0.5*level+0.5)
return ai
def ai_stats(s):
s[0] += r.randint(-20,20)
s[1] += r.randint(-3,3)
s[2] += r.randint(-3,3)
s[3] += r.randint(-3,3)
s[4] += r.randint(-3,3)
s[5] += r.randint(-3,3)
s[6] += r.randint(-3,3)
s[7] += r.randint(-3,3)
return s
#####Game Loop#####
level = 1
print("\n----------------------- GAME START -----------------------")
while True:
#####Determining AI Class/Stats#####
#####(AI classes must be in the Game loop otherwise if an enemy chooses the same class twice, it would have <=0 HP, thus being an instant win)#####
ai_knight = [100,10,5,15,0,25,5,10] #health: 100, attack 1: 10, attack 2: 5-15, attack 3: 5-25, heal: 5-10
ai_mage = [50,15,10,20,-5,25,10,15] #health: 50, attack 1: 15, attack 2: 10-20, attack 3: -5-25, heal: 10-15
ai_healer = [150,5,5,10,5,15,10,20] #health: 150, attack 1: 5, attack 2: 5-10, attack 3: 5-15, heal: 10-20
ai = r.randint(1,3)
if ai == 1:
ai = ai_stats(ai_knight)
print("\nYou are fighiting a knight with",ai[0],"HP!")
if ai == 2:
ai = ai_stats(ai_mage)
print("\nYou are fighiting a mage with",ai[0],"HP!")
if ai == 3:
ai = ai_stats(ai_healer)
print("\nYou are fighiting a healer with",ai[0],"HP!")
ai_heal_max = ai[0]
ai = difficulty(ai,ai_heal_max,level)
#####Gameplay Loop#####
while True:
#####Player Attack#####
player_move = input("\nWould you like to use attack (1), attack (2), attack (3), or heal (4)? ")
print("")
if player_move == "1":
player_damage = player_class[1]
ai[0] = ai[0]- player_damage
print(player_name," did",player_damage,"damage!")
elif player_move == "2":
player_damage = r.randint(player_class[2],player_class[3])
ai[0] = ai[0]- player_damage
print(player_name," did",player_damage,"damage!")
elif player_move == "3":
player_damage = r.randint(player_class[4],player_class[5])
if player_damage<0:
player_class[0] = player_class[0]+player_damage
print(player_name," damaged themselves for",player_damage,"HP!")
else:
ai[0] = ai[0]- player_damage
print(player_name," did",player_damage,"damage!")
elif player_move == "4":
player_heal = r.randint(player_class[6],player_class[7])
if player_class[0] + player_heal > player_heal_max:
player_class[0] = player_heal_max
else:
player_class[0] = player_class[0] + player_heal
print(player_name," healed for",player_heal,"HP")
else:
print("Please enter in a valid move.")
continue
#####Detecting Death#####
if player_class[0]<=0:
break
elif ai[0]<=0:
points += player_class[0]*level
level +=1
print("You have bested your opponent! You Have",points,"points. \nNow starting level",level)
player_class,player_heal_max = level_up(player_class,player_heal_max)
break
#####AI Turn#####
if ai[0] <= (ai_heal_max/5):
ai_move = r.sample(set([1,2,3,4,4,4]), 1)[0]
elif ai[0] >= (ai_heal_max*.8):
ai_move = r.sample(set([1,2,3,1,2,3,4]), 1)[0]
elif ai[0] == ai_heal_max:
ai_move = r.randint(1,3)
else:
ai_move = r.randint(1,4)
if ai_move == 1:
ai_damage = ai[1]
player_class[0] = player_class[0]- ai_damage
print("Your opponent did",ai_damage,"damage!")
elif ai_move == 2:
ai_damage = r.randint(ai[2],ai[3])
player_class[0] = player_class[0]- ai_damage
print("Your opponent did",ai_damage,"damage!")
elif ai_move == 3:
ai_damage = r.randint(ai[4],ai[5])
if ai_damage<0:
ai[0] = ai[0]+ai_damage
print("Your opponent damaged themselves for",ai_damage,"HP!")
else:
player_class[0] = player_class[0]- ai_damage
print("Your opponent did",ai_damage,"damage!")
elif ai_move == 4:
ai_heal = r.randint(ai[6],ai[7])
if ai[0] + ai_heal > ai_heal_max:
ai[0] = ai_heal_max
else:
ai[0] = ai[0] + ai_heal
print("Your opponent healed for",ai_heal,"HP")
#####Displaying HP#####
print("\nYour health is:",player_class[0],"HP")
print("Your opponent's health is",ai[0],"HP")
#####Detecting Loss#####
if player_class[0]<=0:
break
elif ai[0]<=0:
points += player_class[0]*level
level +=1
print("You have bested your opponent! You Have",points,"points. \nNow starting level",level)
player_class,player_heal_max = level_up(player_class,player_heal_max)
break
else:
continue
#####Finishing Game, Checking/Updating High Score#####
if player_class[0]<=0:
print("\nYou Died! :(")
if points>score:
hs = open("highscore.txt","w")
hs.write(str(points))
hs.write("\n")
print("You have the new high score of",points,"!")
hs.write(player_name)
else:
print("\nYou finished with",points,"points.")
print("The high score is:",score,"by",leader)
input("")
hs.close()
break
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T00:13:24.417",
"Id": "434374",
"Score": "1",
"body": "Really cool game here. Thanks for sharing. Expect an answer soon."
}
] | [
{
"body": "<p>In your game, which I've played, you have 3 main warriors: knight, mage, and healer. These warriors all have similar behaviors, health, attacks, and heals - <em>they are essentially objects of a class</em>, <code>Warrior</code>.</p>\n\n<p><strong>Tip 1:</strong> Let's create a <code>Warrior</code> class:</p>\n\n<ul>\n<li>You will be able to create new Warriors (ie Archers, Brutes, Zombies) later with ease.</li>\n<li>You can interface your AI player as a Warrior.</li>\n<li>You can simply control all of your Warrior objects.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Warrior:\n def __init__(self, health, attack_1, attack_2, attack_3, heal):\n self.health = health\n self.attack_1 = attack_1\n self.attack_2 = attack_2 # tuple ie (5,25) representing range for attack value\n self.attack_3 = attack_3 # tuple ie (10,20) representing range for attack value\n self.heal = heal # tuple ie (10,20) representing range for health value\n\n def attributes(self):\n # string containing the attributes of the character\n string = \"Health: \"+ str(self.health) + \" Attack 1: \"+ str(self.attack_1) + \" Attack 2: \"+ str(self.attack_2[0]) + \"-\"+ str(self.attack_2[1])+ \" Attack 3: \"+ str(self.attack_3[0]) + \"-\"+ str(self.attack_3[1]) + \" Heal:\"+ str(self.heal[0]) + \"-\" + str(self.heal[0])\n return string\n\n def is_dead(self):\n return self.health <= 0\n</code></pre>\n\n<p>You may want to add other functions later. For instance, <code>def attack_3(self)</code>, which would return the value of an attack. We then initialize the knight, mage, healer, and ai as so:</p>\n\n<pre><code>knight = Warrior(100, 10, (5,15), (5,25), (5,10))\nmage = Warrior(50, 15, (10,20), (-5,25), (10,15))\nhealer = Warrior(150, 5, (5,10), (5,15), (10,20))\n\nwhile True:\n # Determining AI Class/Stats\n ai_knight = Warrior(100, 10, (5,15), (5,25), (5,10))\n ai_mage = Warrior(50, 15, (10,20), (-5,25), (10,15))\n ai_healer = Warrior(150, 5, (5,10), (5,15), (10,20))\n ai_classes = [ai_knight, ai_mage, ai_healer]\n\n ai = ai_classes[r.randint(0,2)]\n randomize_ai(ai)\n if ai == ai_knight:\n print(\"\\nYou are fighting a knight with \", ai.health,\"HP!\")\n elif ai == ai_mage:\n print(\"\\nYou are fighting a mage with \", ai.health,\"HP!\")\n elif ai == ai_healer:\n print(\"\\nYou are fighting a healer with \", ai.health,\"HP!\")\n</code></pre>\n\n<p><strong>Tip 2:</strong> <code>elif</code> is your best friend. If your <code>if</code> statements are mutually exclusive, you can cut down on the complexity of your program, by using <code>elif</code>(which you used successfully in your program, just not always):</p>\n\n<pre><code>if ai == 1:\n #code\nif ai == 2:\n #code\nif ai == 3:\n #code\n\n# should instead be...\n# because ai can't be three values at once\n\nif ai == 1:\n #code\nelif ai == 2:\n #code\nelif ai == 3:\n #code\n</code></pre>\n\n<p><strong>Tip 3:</strong> The style in which you program is critical to your actual program. A few basic things you should know about coding styles:</p>\n\n<ul>\n<li>Do not use too many <code>#</code> when you are commenting. Instead of <code>######Displaying HP#######</code> try <code># Display HP</code>. The latter is more readable for someone else or yourself reading/reviewing your code.</li>\n<li>If you have a section header comment, you can try a special commenting style such as:</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>###########\n# CLASSES #\n###########\n</code></pre>\n\n<ul>\n<li>Do not add extra spaces to your code -- this makes your code longer than it <em>needs to</em> and <em>should</em> be. Make your code shorter if it doesn't reduce readability.</li>\n<li>To improve the user experience, avoid typos when possible</li>\n<li>And whatever you do, be consistent. It's easiest to read, review, and edit code that is consistent in style.</li>\n<li>Style is one of those things that just takes experience and practice. You will get better over time.</li>\n</ul>\n\n<p><strong>With these three tips in mind, your final code should look more like:</strong></p>\n\n<pre><code>import random as r\n\ntry:\n hs = open(\"highscore.txt\",\"r+\")\nexcept:\n hs = open(\"highscore.txt\",\"x\")\n hs = open(\"highscore.txt\",\"r+\")\n\ntry:\n score = int(hs.readlines(1)[0])\n score = int(score[0])\n leader = hs.readlines(2)\n leader = str(hs.readlines(2)[0])\nexcept:\n hs = open(\"highscore.txt\",\"w\")\n hs.write(\"0\\nnull\")\n hs = open(\"highscore.txt\",\"r\")\n score = int(hs.readlines(1)[0])\n leader = str(hs.readlines(2)[0])\n\n# Introduce and name the player\nprint (\"\\nWELCOME TO WONDERLANDS RPG!\")\nprint (\"The High Score is:\", score, \"by\", leader)\npoints = 0\nplayer_name = input (\"\\nEnter your hero's name: \")\n\n\n###########\n# CLASSES #\n###########\n\nclass Warrior:\n def __init__(self, health, attack_1, attack_2, attack_3, heal):\n self.health = health\n self.attack_1 = attack_1\n self.attack_2 = attack_2 # tuple ie (5,25) representing range for attack value\n self.attack_3 = attack_3 # tuple ie (10,20) representing range for attack value\n self.heal = heal # tuple ie (10,20) representing range for health value\n\n def attributes(self):\n # string containing the attributes of the character\n string = \"Health: \"+ str(self.health) + \" Attack 1: \"+ str(self.attack_1) + \" Attack 2: \"+ str(self.attack_2[0]) + \"-\"+ str(self.attack_2[1])+ \" Attack 3: \"+ str(self.attack_3[0]) + \"-\"+ str(self.attack_3[1]) + \" Heal:\"+ str(self.heal[0]) + \"-\" + str(self.heal[0])\n return string\n\n def is_dead(self):\n return self.health <= 0\n\nknight = Warrior(100, 10, (5,15), (5,25), (5,10))\nmage = Warrior(50, 15, (10,20), (-5,25), (10,15))\nhealer = Warrior(150, 5, (5,10), (5,15), (10,20))\n\nwhile True:\n print(\"\\n1. Knight: \", knight.attributes())\n print(\"\\n2. Mage: \", mage.attributes())\n print(\"\\n3. Healer: \", healer.attributes())\n player_class = input(\"\\nSelect your class: 1, 2, or 3: \")\n if player_class == \"1\":\n player_class = knight\n print(\"You have selected the Knight class.\")\n break\n elif player_class == \"2\":\n player_class = mage\n print(\"You have selected the Mage\")\n break\n elif player_class == \"3\":\n player_class = healer\n print(\"You have selected the Healer\")\n break\n else:\n print(\"Please select a valid class.\")\n continue\n\nplayer_heal_max = player_class.health\n\n\n################################\n# Difficulty/Upgrade Functions #\n################################\n\ndef level_up(player,health_max):\n while True:\n lv_choice = input(\"\\nWould you like to:\\n 1. Increase max health by 20 \\n 2. Increase Healing Factor by 5 \\n 3. increase your damage by 5\\n\")\n if lv_choice == \"1\":\n health_max += 20\n player.health = health_max\n return player, health_max\n elif lv_choice == \"2\":\n player.heal += (5,5)\n player.health = health_max\n return player, health_max\n elif lv_choice == \"3\":\n player.attack_1 += 5\n player.attack_2 += (5,5)\n player.attack_3 += (5,5)\n player.health = health_max\n return player, health_max\n else:\n print(\"Please enter in a valid number\")\n continue\n\ndef difficulty(ai,health_max,level):\n if level == 1:\n return ai\n else:\n ai.health = health_max + 15 * round(0.5 * level + 0.5)\n ai.attack_1 += 5 * round(0.5 * level + 0.5)\n ai.attack_2 += (5 * round(0.5 * level + 0.5),5 * round(0.5 * level + 0.5))\n ai.attack_3 += (5 * round(0.5 * level + 0.5),5 * round(0.5 * level + 0.5))\n ai.heal += (5 * round(0.5 * level + 0.5),5 * round(0.5 * level + 0.5))\n return ai\n\ndef randomize_ai(ai):\n ai.health += r.randint(-20,20)\n ai.attack_1 += r.randint(-3,3)\n ai.attack_2 += (r.randint(-3,3),r.randint(-3,3))\n ai.attack_3 += (r.randint(-3,3),r.randint(-3,3))\n ai.heal += (r.randint(-3,3),r.randint(-3,3))\n return ai\n\n#############\n# Game Loop #\n#############\n\nlevel = 1\nprint(\"\\n----------------------- GAME START -----------------------\")\n\nwhile True:\n # Determining AI Class/Stats\n ai_knight = Warrior(100, 10, (5,15), (5,25), (5,10))\n ai_mage = Warrior(50, 15, (10,20), (-5,25), (10,15))\n ai_healer = Warrior(150, 5, (5,10), (5,15), (10,20))\n ai_classes = [ai_knight, ai_mage, ai_healer]\n\n ai = ai_classes[r.randint(0,2)]\n randomize_ai(ai)\n if ai == ai_knight:\n print(\"\\nYou are fighting a knight with \", ai.health,\"HP!\")\n elif ai == ai_mage:\n print(\"\\nYou are fighting a mage with \", ai.health,\"HP!\")\n elif ai == ai_healer:\n print(\"\\nYou are fighting a healer with \", ai.health,\"HP!\")\n\n ai_heal_max = ai.health\n\n ai = difficulty(ai, ai_heal_max, level)\n\n # Gameplay Loop\n while True:\n # Player Attack\n player_move = input(\"\\nWould you like to use attack (1), attack (2), attack (3), or heal (4)? \")\n print(\"\")\n if player_move == \"1\":\n player_damage = player_class.attack_1\n ai.health = ai.health - player_damage\n print(player_name,\" did\",player_damage,\"damage!\")\n elif player_move == \"2\":\n player_damage = r.randint(player_class.attack_2[0],player_class.attack_2[1])\n ai.health = ai.health - player_damage\n print(player_name,\" did\",player_damage,\"damage!\")\n elif player_move == \"3\":\n player_damage = r.randint(player_class.attack_3[0],player_class.attack_3[1])\n ai.health = ai.health - player_damage\n print(player_name,\" did\", player_damage, \" damage!\")\n elif player_move == \"4\":\n player_heal = r.randint(player_class.heal[0],player_class.heal[1])\n if player_class.health + player_heal > player_heal_max:\n player_class.health = player_heal_max\n else:\n player_class.health = player_class.health + player_heal\n print(player_name,\" healed for\",player_heal,\"HP\")\n else:\n print(\"Please enter in a valid move.\")\n continue\n\n # Detecting Death\n if player_class.is_dead():\n break\n elif ai.is_dead():\n points += player_class.health * level\n level += 1\n print(\"You have bested your opponent! You Have\",points,\"points. \\nNow starting level\",level)\n player_class, player_heal_max = level_up(player_class,player_heal_max)\n break\n\n # AI Turn\n if ai.health <= (ai_heal_max/5):\n ai_move = r.sample(set([1,2,3,4,4,4]), 1)[0]\n elif ai.health >= (ai_heal_max*.8):\n ai_move = r.sample(set([1,2,3,1,2,3,4]), 1)[0]\n elif ai.health == ai_heal_max:\n ai_move = r.randint(1,3)\n else:\n ai_move = r.randint(1,4)\n\n if ai_move == 1:\n ai_damage = ai.attack_1\n player_class.health = player_class.health - ai_damage\n print(\"Your opponent did\",ai_damage,\"damage!\")\n elif ai_move == 2:\n ai_damage = r.randint(ai.attack_2[0],ai.attack_2[1])\n player_class.health = player_class.health- ai_damage\n print(\"Your opponent did \",ai_damage,\" damage!\")\n elif ai_move == 3:\n ai_damage = r.randint(ai.attack_3[0],ai.attack_3[1])\n player_class.health = player_class.health - ai_damage\n print(\"Your opponent did \", ai_damage,\" damage!\")\n elif ai_move == 4:\n ai_heal = r.randint(ai.heal[0],ai.heal[1])\n if ai.health + ai_heal > ai_heal_max:\n ai.health = ai_heal_max\n else:\n ai.health = ai.health + ai_heal\n print(\"Your opponent healed for \", ai_heal,\" HP\")\n\n # Displaying HP \n print(\"\\nYour health is:\", player_class.health,\"HP\")\n print(\"Your opponent's health is \", ai.health,\" HP \")\n\n # Detecting Death\n if player_class.is_dead():\n break\n elif ai.health <= 0:\n points += player_class.health * level\n level += 1\n print(\"You have bested your opponent! You Have\",points,\"points. \\nNow starting level\",level)\n player_class, player_heal_max = level_up(player_class,player_heal_max)\n break\n\n # Finishing Game, Checking/Updating High Score\n if player_class.health<=0:\n print(\" \\ nYou Died !: (\")\n if points > score:\n hs = open(\" highscore.txt \",\" w \")\n hs.write(str(points))\n hs.write(\" \\ n \")\n print(\" You have the new high score of \",points,\" !\")\n hs.write(player_name)\n else:\n print(\" \\ nYou finished with \",points,\" points.\")\n print(\" The high score is:\",score,\" by \",leader)\n input(\" \")\n hs.close()\n break\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:30:27.937",
"Id": "434510",
"Score": "1",
"body": "I made lots of other small edits. If you're curious about one of them, leave a comment and I'll be sure to respond."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:29:48.157",
"Id": "224047",
"ParentId": "223917",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224047",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T02:56:12.440",
"Id": "223917",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"role-playing-game",
"battle-simulation"
],
"Title": "Text-based fighting game in Python 3.0"
} | 223917 |
<p>Report time at whole hours </p>
<pre><code>#!/usr/bin/python3
import time
from datetime import datetime
from pydub import AudioSegment
from pydub.playback import play
bell_sound = AudioSegment.from_wav("/home/me/Music/audio/bell.wav")
while True:
now = datetime.now()
# repeats = 1 if now.hour % 3 == 0 else now.hour % 3
repeats = now.hour % 3 + 1
if now.hour < 6:
break
# report on whole hour
if now.minute == 0:
for _ in range(repeats): # bell the hours
play(bell_sound)
time.sleep(60 * 58) # save the computation
if now.minute != 0:
time.sleep(10)
# quit 23 later
if now.hour == 23:
break
</code></pre>
<p>Any ideas to improve it?</p>
| [] | [
{
"body": "<p>I would have the <code>now.minute != 0</code> as an else since the <code>if</code> above is the exact opposite case.</p>\n\n<p>I would also assign a 'sleep_time' value inside both branches and call the sleep function after the <code>if - else</code> to emphasize that sleep is always done.</p>\n\n<p>I also don't like <code>while True</code> since it means I have to search the code for the exit condition. I would have the <code>now = datetime.now()</code> line twice, one before the <code>while</code> and once at the end of the block and make the condition <code>while now.hour != 23:</code>. This is personal, some people are more against the duplicated line than the <code>while True:</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:36:15.483",
"Id": "223974",
"ParentId": "223918",
"Score": "1"
}
},
{
"body": "<pre><code>while True:\n now = datetime.now()\n # repeats = 1 if now.hour % 3 == 0 else now.hour % 3\n repeats = now.hour % 3 + 1\n\n if now.hour < 6:\n break\n</code></pre>\n\n<p>The <code>repeats</code> is not used in the condition of the <code>break</code>. Therefore you should reorder your code like this, to avoid computing things you don't need later:</p>\n\n<pre><code> now = datetime.now()\n if now.hour < 6:\n break\n\n repeats = now.hour % 3 + 1\n</code></pre>\n\n<p>I was confused by the last line of code. I thought it would mean to ring the bell 3 times at 2 o'clock. What confused me was that <code>now.hour</code> does not correspond to my intuitive understanding of <code>now</code> anymore, since by the time the bell will ring, some time has passed.</p>\n\n<p>To avoid this confusion, you should define a variable <code>next_hour = now.hour + 1</code>. When you then define <code>repeats = (next_hour - 1) % 3 + 1</code>, that may look even more confusing because of the <code>- 1</code> at the beginning and the <code>+ 1</code> at the end. That's probably why you considered <code>repeats = 3 if next_hour % 3 == 0 else next_hour % 3</code>, and it's good that you did that.</p>\n\n<p>Continuing with your code:</p>\n\n<pre><code> # report on whole hour\n if now.minute == 0:\n for _ in range(repeats): # bell the hours\n play(bell_sound)\n time.sleep(60 * 58) # save the computation\n</code></pre>\n\n<p>I hope that each bell takes only a few seconds. As soon as they become longer, you might miss the next hour completely. The \"save the computation\" part feels dangerous to me. This is because on practically all operating systems you can put a process to sleep and later resume it. I don't know how exactly this affects the clock and the measurement of <code>datetime.now()</code>, but that's definitely something you should experiment with.</p>\n\n<p>It's better to define a high-level overview first:</p>\n\n<pre><code>def ring_until_midnight():\n current_hour = datetime.now().hour\n if current_hour < 6:\n break\n\n while current_hour < 23:\n wait_until_hour(current_hour + 1)\n ring_the_bell(current_hour + 1)\n current_hour += 1\n</code></pre>\n\n<p>This raises the question what to do if the hour steps forward fast, such as when the daylight saving time changes. Since you probably don't want the clock to ring 5 times in a row, it's better to replace the last line above with:</p>\n\n<pre><code> current_hour = datetime.now().hour # instead of current_hour + 1\n</code></pre>\n\n<p>Next, it's time to fill the missing details, which are <code>wait_until_hour</code> and <code>ring_the_bell</code>. For <code>wait_until</code> I propose this simple solution:</p>\n\n<pre><code>def wait_until_hour(hour):\n while datetime.now().hour < hour:\n time.sleep(1)\n</code></pre>\n\n<p>Note that I intentionally wrote <code>< hour</code> instead of <code>!= hour</code>. Just in case the process is stopped for 3 hours. If I had written <code>!= hour</code>, the code would continue to wait until the next day. Again, it depends on your exact requirements whether <code><</code> or <code>!=</code> is appropriate in this situation. In any case, you have to make this choice consciously.</p>\n\n<p>Having a possible clock offset of 1 second (from the above <code>sleep(1)</code>) sounds acceptable to me. If you need more precision, you can say <code>time.sleep(0.1)</code> instead as well.</p>\n\n<p>The second detail, <code>ring_the_bell</code>, is similarly simple:</p>\n\n<pre><code>def ring_the_bell(hour):\n repeats = (hour - 1) % 3 + 1\n\n for _ in range(repeats):\n play(bell_sound)\n</code></pre>\n\n<p>Now that I think of it, in the definition of <code>ring_until_midnight</code> above, I made an unfortunate choice:</p>\n\n<pre><code> ring_the_bell(current_hour + 1)\n</code></pre>\n\n<p>This should rather be:</p>\n\n<pre><code> ring_the_bell(datetime.now().hour)\n</code></pre>\n\n<p>The point is that during all this waiting, there is much that can happen, and there is no guarantee that waiting for \"the next hour\" will finally arrive at exactly that hour. Therefore better ask for the then-current time again.</p>\n\n<p>When you build your programs out of composable pieces like these, you will find that you can reuse some parts by just copying them to your next project, which is good because it saves you the work of writing the same code over and over again, plus you will build up your library of small, hopefully tested code that you know you can trust.</p>\n\n<p>As you saw in the process I outlined above, even writing a simple ring-the-bell program can be made quite complicated. It needs lots of decisions that you might not think about when you first decide to write such a program. The complexity arises mainly because this program is dealing with time and measurement and calendars, which always gets complicated. That's the way it is.</p>\n\n<p>You also saw that it is of utmost importance to get the exact wording right in every line of the code. Is saying \"the current hour\" really the best way to express your requirement? What does \"current\" mean, when was it measured, for how long is that measurement valid, what happens in between? Lots of questions, and you sometimes have to revise your initial program. I'm quite experienced, and I didn't get it right either on the first attempt.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T01:44:44.073",
"Id": "233650",
"ParentId": "223918",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T03:12:18.757",
"Id": "223918",
"Score": "5",
"Tags": [
"python",
"timer",
"audio"
],
"Title": "Report time on whole hours"
} | 223918 |
<p>I am using this syntax to query a table and return a record set and if the number of times total the customer has been emailed is less than 5, send an email with a canned response. If the number of times emailed is >= 6 then the draft is saved with bold text so the user knows to review this (case by case basis of what should be sent.)</p>
<p>I'm sure this code can be optimized, but I lack the know-how...</p>
<pre><code>Sub GetAccountsNeedingAttention()
Dim rs As DAO.Recordset
Dim primaryContact As String
Dim searchEmail As String
Dim startDate As String
Dim emailsSent As Integer
Dim emailOpener As String
Dim emailBody As String
Dim fullEmailBody As String
Dim emailSig As String: emailSig = "html syntax to put in the text for email sig"
Set rs = CurrentDb.OpenRecordset("Select *, CDate(Mid(NR, InStrRev(NR, ' ')+1) & '/01/' & [Year] As Date From prodInfo Having CDate(Mid(NR, ' ')+1) & '/01/' & [Year] <= DateValue(CStr(Now()))")
With rs
.MoveLast
.MoveFirst
Do While Not .EOF
primaryContact = rs![Name]
emailOpener = "<p>Hello,</p>"
startDate = rs![Date]
If InStr(1, rs![contactEmail], InStr(rs![contactEmail], ", ") - 1) Then
'we have a comma
searchEmail = Left(rs![contactEmail], InStr(rs![contactEmail], ", ") - 1)
Else
'we do not have a comma
searchEmail = rs![contactEmail]
End If
If primaryContact <> "Both" Then
If InStr(primaryContact, ",") > 0 Then
primaryContact = Left(primaryContact, InStr(1, primaryContact, " ") - 1)
Else
primaryContact = primaryContact
End If
emailsSent = GetNumberOfTimesEmailed(searchEmail, startDate)
If emailsSent >= 6 Then
fullEmailBody = "<p><strong>PLEASE REVIEW</strong></p>"
Else
emailBody = DLookup("Response", "_Responses", "ID = " & emailsSent)
fullEmailBody = emailOpener & "<p>" & emailBody & "</p> & emailSig"
End If
ComposeResponse searchEmail, fullEmailBody
End If
.MoveNext
Loop
End With
rs.Close
End Sub
Function GetNumberOfTimesEmailed(searchEmail As String, startDate As String) As Integer
Dim currDateTime As Date: currDateTime = Now()
Dim OLApp As Outlook.Application
Dim olNS As NameSpace
Dim Fldr As MAPIFolder
Dim olReply As Outlook.MailItem
Dim msg As Object
Set OLApp = New Outlook.Application
Set olNS = OLApp.GetNamespace("MAPI")
Set Fldr = olNS.GetDefaultFolder(olFolderSentMail)
startDate = startDate & " 07:00:00 AM"
GetNumberOfTimesEmailed = 1
For Each msg In Fldr.Items
If TypeName(msg) = "MailItem" Then
For Each recip In msg.Recipients
If recip.Address = searchEmail Then
If msg.SentOn >= startDate And msg.SentOn <= currDateTime Then
GetNumberOfTimesEmailed = GetNumberOfTimesEmailed + 1
End If
End If
Next recip
End If
Next msg
End Function
Function ComposeResponse(searchEmail As String, fullEmailBody As String)
Dim currDateTime As Date: currDateTime = Now()
Dim tenDayPrior As Date: tenDayPrior = DateValue(CStr(Now())) - 10 & " 07:00:00 AM"
Dim OLApp As Outlook.Application
Dim olNS As NameSpace
Dim Fldr As MAPIFolder
Dim olReply As Outlook.MailItem
Dim msg As Object
Set OLApp = New Outlook.Application
Set olNS = OLApp.GetNamespace("MAPI")
Set Fldr = olNS.GetDefaultFolder(olFolderSentMail)
For Each msg In Fldr.Items
If TypeName(msg) = "MailItem" Then
For Each recip In msg.Recipients
If recip.Address = searchEmail Then
If msg.SentOn >= tenDayPrior And msg.SentOn <= currDateTime Then
Set olReply = msg.ReplyAll
With olReply
.BodyFormat = olFormatHTML
.HTMLBody = Replace(.HTMLBody, "&nbsp;", fullEmailBody, Count:=1)
.Save
.Close olSave
End With
End If
End If
Next recip
End If
Next msg
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:49:43.440",
"Id": "434289",
"Score": "1",
"body": "`GetAccountsNeedingAttention()` did not paste properly. Please fix the code so that it will compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:45:13.890",
"Id": "434297",
"Score": "0",
"body": "@TinMan - my mistake. Try it now. Compile fine for me now :)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T03:34:06.960",
"Id": "223919",
"Score": "2",
"Tags": [
"vba",
"datetime",
"email"
],
"Title": "Code to email past-due accounts"
} | 223919 |
<h3>Problem statement</h3>
<p>There are sometimes <code>foreach</code> scenarios that require <em>deep</em> nesting due to multiple disposable objects involved that look like this:</p>
<blockquote>
<pre><code>using(..)
{
foreach(..)
{
using(..)
{
}
}
}
</code></pre>
</blockquote>
<p>or a real-world example from one of my applications:</p>
<blockquote>
<pre><code>using (_logger.BeginScope().CorrelationHandle("TestBundle").AttachElapsed())
using (Disposable.Create(() =>
{
foreach (var item in cache.Values) item.Dispose();
}))
{
_logger.Log(Abstraction.Layer.Service().Meta(new { TestBundleFileName = testBundle.FileName }));
foreach (var current in tests)
{
using (_logger.BeginScope().CorrelationHandle("TestCase").AttachElapsed())
{
// body
}
}
}
</code></pre>
</blockquote>
<p>I find this code is very ugly and there is virtually no other way of writing this (or it's just me and I cannot think of any). </p>
<hr>
<h3>Suggested solution</h3>
<p>So, in order to make it prettier I created the <code>Using</code> extension that encapsulates the <em>outer</em> and <em>inner</em> <code>using</code>s within the loop.</p>
<p>Its body is identical to the <code>using/foreach/using</code> <em>pattern</em> I'd like to get rid of elsewhere:</p>
<pre><code>public static class EnumerableExtensions
{
public static IEnumerable<(TItem Current, TInner Context)> Using<TItem, TOuter, TInner>
(
this IEnumerable<TItem> source,
TOuter outer,
Func<TItem, TInner> inner
)
{
using (new Disposer<TOuter>(outer))
{
foreach (var item in source)
{
using (var context = new Disposer<TInner>(inner(item)))
{
yield return (item, context);
}
}
}
}
}
</code></pre>
<p>This is using a helper <code>struct</code> for disposing <code>TOuter</code> and <code>TInner</code></p>
<pre><code>public readonly struct Disposer<T> : IDisposable
{
public Disposer(T value)
{
Value = value;
}
public T Value { get; }
public void Dispose()
{
if (Value is IDisposable disposable)
{
disposable.Dispose();
}
else
{
foreach (var property in typeof(T).GetProperties())
{
if (property.GetValue(Value) is IDisposable disposableProperty)
{
disposableProperty.Dispose();
}
}
}
}
public static implicit operator T(Disposer<T> disposer) => disposer.Value;
}
</code></pre>
<p>And here is the <code>Disposable</code> helper:</p>
<pre><code>public class Disposable : IDisposable
{
private readonly Action _dispose;
private Disposable(Action dispose)
{
_dispose = dispose;
}
public static IDisposable Empty => new Disposable(() => { });
public static IDisposable Create(Action dispose)
{
return new Disposable(dispose);
}
public void Dispose()
{
_dispose();
}
}
</code></pre>
<h3>Example usage</h3>
<p>Now, when I have such a scenario, I can put everything inside the loop:</p>
<pre><code>void Main()
{
var numbers = new[] { 1, 2, 3 };
foreach (var (item, context) in numbers.Using
(
outer: Disposable.Create (() => Console.WriteLine("Outer disposed.")),
inner: _ => Disposable.Create (() => Console.WriteLine("Inner disposed.")))
)
{
item.Dump();
context.Dump();
}
}
</code></pre>
<p>Then, when I refactor the previous ugly piece of code with this extension it turns into this:</p>
<blockquote>
<pre><code>foreach (var (current, context) in tests.Using
(
outer: new
{
Scope = _logger.BeginScope().CorrelationHandle("TestBundle").AttachElapsed(),
CleanUp = Disposable.Create(() =>
{
foreach (var item in cache.Values) item.Dispose();
})
},
inner: _ => _logger.BeginScope().CorrelationHandle("TestCase").AttachElapsed())
)
{
// body
}
</code></pre>
</blockquote>
<h3>Questions</h3>
<ul>
<li>What do you think of this helper? </li>
<li>Would you say the code is now easier to read?</li>
<li>Can the <code>Using</code> extension or the <code>Disposer<T></code> be improved?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:32:32.347",
"Id": "434205",
"Score": "3",
"body": "Rewriting C# again, eh? :-) Could you give an example where you would need this code fragment? _foreach (var property in typeof(T).GetProperties()) /* .. */ disposableProperty.Dispose();_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:34:16.720",
"Id": "434206",
"Score": "0",
"body": "@dfhwze haha, as always :-P see the second quoted code, this is my current ugly use-case that this extension should replace. The refactored version is at the bottom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:57:27.343",
"Id": "434209",
"Score": "0",
"body": "This is a very specific construct: using -> foreach -> using. Wouldn't it be more reusable to make a using -> foreach, and then be able to nest several such patterns?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:04:04.547",
"Id": "434210",
"Score": "1",
"body": "@dfhwze maybe... but my imagination is currently unable to project it :-["
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:35:40.187",
"Id": "434215",
"Score": "3",
"body": "In c# 8.0 there is actually no need nestling for using statements ;) See: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:37:57.773",
"Id": "434217",
"Score": "1",
"body": "@HelloWorld this is nice! I'll definitely use it... someday, when it's official ;-)"
}
] | [
{
"body": "<p>I'd argue that no, this does not make the code easier to understand. Instead of a combination of familiar general-purpose constructs (<code>using</code> and <code>foreach</code>), you now have an undocumented custom special-purpose construct <code>Using(outer, inner)</code> that must be understood before one can make sense of the code. This use-case seems too uncommon to be worth that trade-off.</p>\n\n<p>The main problem I have with the original piece of code is that it looks like a 'camel' because of the <code>Disposable.Create</code> hump at the start. Your alternative is still a camel, just with a bigger hump at the front and a flatter one at the back. With a <code>DisposeAll</code> extension method, you could turn it into a dromedary. It's still a tall hump, but now the shape actually matches its single-loop nature:</p>\n\n<pre><code>using (_logger.BeginScope().CorrelationHandle(\"TestBundle\").AttachElapsed())\nusing (Disposable.Create(() => cache.Values.DisposeAll()))\n{\n _logger.Log(Abstraction.Layer.Service().Meta(new { TestBundleFileName = testBundle.FileName }));\n foreach (var current in tests)\n {\n using (_logger.BeginScope().CorrelationHandle(\"TestCase\").AttachElapsed())\n {\n // TODO\n }\n }\n}\n</code></pre>\n\n<p>Another thing you can do is to move the loop body to a separate method or local function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:00:51.940",
"Id": "434238",
"Score": "1",
"body": "haha, I like the _camel_ analogy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:07:48.133",
"Id": "434240",
"Score": "0",
"body": "I stole this terminology in my answer, I hope you don't have a patent pending..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:14:02.493",
"Id": "434244",
"Score": "3",
"body": "@dfhwze: if I had, and it came to court, then we'd have a camel-case... ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:18:08.697",
"Id": "434260",
"Score": "1",
"body": "ok, you both have good points for not using this _invention_ ;-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T07:55:49.647",
"Id": "223926",
"ParentId": "223921",
"Score": "6"
}
},
{
"body": "<p>I agree with Pieter Witvoet it doesn't improve readability. What you could do, since I know you like lambda's, is make additional convenience helpers to reduce <em>camel</em> code.</p>\n\n<blockquote>\n<pre><code>Disposable.Create(() =>\n{\n foreach (var item in cache.Values) item.Dispose();\n})\n</code></pre>\n</blockquote>\n\n<pre><code>Disposable.Create(cache.Values, (item) => item.Dispose());\n</code></pre>\n\n<p>Additional method:</p>\n\n<pre><code>public static IDisposable Create<T>(IEnumerable<T> source, Action<T> action)\n{\n return new Disposable(() =>\n {\n foreach (var item in source) action(item);\n });\n}\n</code></pre>\n\n<p>I am not a big fan of this:</p>\n\n<blockquote>\n<pre><code>foreach (var property in typeof(T).GetProperties())\n{\n if (property.GetValue(Value) is IDisposable disposableProperty)\n {\n disposableProperty.Dispose();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Can we really assume all of the properties that implement <code>IDisposable</code> <em>want</em> to be disposed here? In addition, <code>property.GetValue(Value)</code> throws errors in this naive <code>GetProperties</code> call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:07:18.073",
"Id": "223927",
"ParentId": "223921",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223926",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T05:25:59.423",
"Id": "223921",
"Score": "5",
"Tags": [
"c#",
"reflection",
"extension-methods"
],
"Title": "Reducing using/foreach/using nesting with a helper extension"
} | 223921 |
<p><strong>Description:</strong></p>
<p>I wrote a Java program that checks whether the content of the given file begins with the Java class File Format magic number <code>0xCAFEBABE</code>, in big-endian byte order.</p>
<p>It prints a success message if:</p>
<ul>
<li>The first 4 bytes match the magic number</li>
</ul>
<p>It prints an error message if:</p>
<ul>
<li>The file doesn't exist or cannot be read</li>
<li>The file contains less than 4 bytes</li>
<li>The first 4 bytes don't match the magic number</li>
</ul>
<p>It prints a usage message if:</p>
<ul>
<li>A file is not given as input</li>
</ul>
<p><strong>Code:</strong></p>
<pre><code>import java.io.*;
public class Magic {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java Magic <FILE>");
return;
}
try {
if (isMagicPresent(args[0])) {
System.out.println(String.format("'%s' contains the magic number.", args[0]));
} else {
System.out.println(String.format("'%s' doesn't contain the magic number.", args[0]));
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
private static boolean isMagicPresent(String file) throws IOException {
try (InputStream instream = new FileInputStream(file)) {
byte[] bytes = new byte[4];
int readCount = instream.read(bytes);
if (readCount == 4) {
return Byte.toUnsignedInt(bytes[0]) == 0xCA &&
Byte.toUnsignedInt(bytes[1]) == 0xFE &&
Byte.toUnsignedInt(bytes[2]) == 0xBA &&
Byte.toUnsignedInt(bytes[3]) == 0xBE;
}
}
return false;
}
}
</code></pre>
<p><strong>Question:</strong></p>
<p>How can I improve the above code in terms of:</p>
<ul>
<li>Readability</li>
<li>Performance</li>
<li>Boundary case and error handling</li>
</ul>
| [] | [
{
"body": "<p>For me overall it was very easy to read and follow.</p>\n\n<p>Nitpicking:</p>\n\n<ul>\n<li><p>Since you want to accept a single input, you can actually check for <code>if (args.length == 1)</code></p></li>\n<li><p>You are already chaining the conditionals so why not the following?</p></li>\n</ul>\n\n<pre><code>private static boolean isMagicPresent(String file) throws IOException {\n try (InputStream is = new FileInputStream(file)) {\n byte[] bytes = new byte[4];\n return is.read(bytes) == 4 &&\n Byte.toUnsignedInt(bytes[0]) == 0xCA &&\n Byte.toUnsignedInt(bytes[1]) == 0xFE &&\n Byte.toUnsignedInt(bytes[2]) == 0xBA &&\n Byte.toUnsignedInt(bytes[3]) == 0xBE;\n }\n}\n</code></pre>\n\n<ul>\n<li><p>You can present the example usage within quotes as in <code>'filename.ext'</code> since whitespaces are allowed in most operating systems and I may try running your program as in <code>java Magic Mag ic.class</code> which would return <code>Mag (No such file or directory)</code> but running with <code>java Magic 'Mag ic.class'</code> returns <code>'Mag ic.class' contains the magic number.</code> when I actually have this file..</p></li>\n<li><p><code>isMagicPresent</code> can accept an <code>InputStream</code> instead of a file path which would make testing the method easier and de-coupling it from a file.</p></li>\n</ul>\n\n<pre><code>private static boolean isMagicPresent(InputStream is) throws IOException {\n byte[] bytes = new byte[4];\n return is.read(bytes) == 4 &&\n Byte.toUnsignedInt(bytes[0]) == 0xCA &&\n Byte.toUnsignedInt(bytes[1]) == 0xFE &&\n Byte.toUnsignedInt(bytes[2]) == 0xBA &&\n Byte.toUnsignedInt(bytes[3]) == 0xBE;\n}\n</code></pre>\n\n<p>Keep up the good work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:13:35.487",
"Id": "223985",
"ParentId": "223923",
"Score": "1"
}
},
{
"body": "<h2>Interface</h2>\n\n<p>For clarity, <code>isMagicPresent()</code> should accept a <code>java.io.File</code> (or <code>java.nio.file.Path</code>) to emphasize that the argument is a path and not the contents of a file.</p>\n\n<p>The default constructor should be suppressed.</p>\n\n<h2>Implementation</h2>\n\n<p>To read a big-endian <code>int</code>, use <a href=\"https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readInt%28%29\" rel=\"nofollow noreferrer\"><code>DataInputStream.readInt()</code></a>. Then you can compare the magic number to <code>0xCAFEBABE</code> rather than four bytes.</p>\n\n<h2>Driver</h2>\n\n<p>I recommend returning a non-zero exit code to indicate that an error has occurred.</p>\n\n<p>When no argument is given, the error message should go to <code>System.err</code>. (If you supported a <code>-h</code> or <code>--help</code> option, then its output should go to <code>System.out</code>, because that <em>would</em> be the requested output.)</p>\n\n<p>Instead of <code>System.out.println(String.format(…))</code>, you should just call <code>System.out.format(…)</code>. Here, I've chosen to combine both cases into one print statement, but you don't have to.</p>\n\n<h2>Suggested implementation</h2>\n\n<pre><code>import java.io.*;\n\npublic class Magic {\n private Magic() {}\n\n public static boolean isMagicPresent(File f) throws IOException {\n try (InputStream inStream = new FileInputStream(f);\n DataInputStream dataInStream = new DataInputStream(inStream)) {\n return dataInStream.readInt() == 0xCAFEBABE;\n }\n }\n\n public static void main(String[] args) {\n if (args.length < 1) {\n System.err.println(\"Usage: java Magic <FILE>\");\n System.exit(1);\n }\n\n File f = new File(args[0]);\n try {\n System.out.format(\n \"'%s' %s the magic number.%n\",\n f,\n isMagicPresent(f) ? \"contains\" : \"doesn't contain\"\n );\n } catch (IOException ex) {\n System.err.println(ex.getMessage());\n System.exit(1);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:49:18.737",
"Id": "223998",
"ParentId": "223923",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T06:59:16.070",
"Id": "223923",
"Score": "5",
"Tags": [
"java",
"file-structure"
],
"Title": "Java program to detect the Java class File Format magic number, in a given file"
} | 223923 |
<p>I have two versions of a function that performs the same task, however I'm not sure which one to use. Speed is something to take into consideration, but I also want to know what the best practice is. Below is the same function, except one uses an If statement to throw an exception where as the other uses the try catch.</p>
<pre><code>private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
try
{
var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
if (campaignSegments.Any())
{
return campaignSegments.Single().Url;
}
return string.Empty;
}
catch (InvalidOperationException ex)
{
throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found", ex);
}
}
private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
if (campaignSegments.Any())
{
if (campaignSegments.Count() != 1)
{
throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found");
}
return baseFilters.Single(x => x.SegmentType == UrlSegmentType.Campaign).Url;
}
return string.Empty;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:46:29.233",
"Id": "434252",
"Score": "0",
"body": "This one is rather interesting, because LINQ is used alot in the projects I am currently working on at work. We sometimes get an _InvalidOperationException_ in production, because of the use of _Single_ etc. Perhaps this is a sign of bad (lazy) design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:48:43.033",
"Id": "434253",
"Score": "0",
"body": "That's what I'm trying to avoid. In the past I've always just used TryCatch and handled `Exception` rather than a specific exception. I'm trying to smarter about how I handle exceptions now."
}
] | [
{
"body": "<h3>Throwing custom exception</h3>\n\n<p>I find the second version is cleaner as it clearly communicates which condition caused the exception. With the first one, you need to know it's about <code>Single</code> which you need to read the documentation for.</p>\n\n<h3>Implemention</h3>\n\n<p>However, as far as the implementation logic is concerned this is doing a lot of querying and the source <code>baseFilters</code> will be queried 3 times!</p>\n\n<p>I'd be a good idea to call <code>ToList</code> on this to make it a one-time operation:</p>\n\n<pre><code>baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign).ToList()\n</code></pre>\n\n<h3>Alternative</h3>\n\n<p>I have an extension to deal with such cases. I call it <code>SingleOrThrow</code>. It lets you to define two exceptions. One for when there are no elements and one for when there are too many. Otherwise it uses default ones.</p>\n\n<pre><code> [CanBeNull]\n public static T SingleOrThrow<T>([NotNull] this IEnumerable<T> source, Func<T, bool> predicate, Func<Exception> onEmpty = null, Func<Exception> onMultiple = null)\n {\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n var result = default(T);\n var count = 0;\n\n using (var enumerator = source.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n if (predicate(enumerator.Current))\n {\n if (++count > 1)\n {\n throw onMultiple?.Invoke() ?? DynamicException.Create\n (\n $\"{source.GetType().ToPrettyString()}ContainsMoreThanOneElement\",\n $\"There is more than one element that matches the specified predicate.\"\n );\n }\n\n result = enumerator.Current;\n }\n }\n }\n\n if (count == 0)\n {\n throw onEmpty?.Invoke() ?? DynamicException.Create\n (\n $\"{source.GetType().ToPrettyString()}Empty\",\n $\"There is no element that matches the specified predicate.\"\n );\n }\n\n return result;\n }\n</code></pre>\n\n<p>With it you could do just that:</p>\n\n<pre><code>baseFilters.SingleOrThrow(\n x => x.SegmentType == UrlSegmentType.Campaign, \n onMultiple: () => new InvalidDuplicateUrlSegmentException(\"Multiple Campaign Url Segments Found\", ex));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:06:20.363",
"Id": "434256",
"Score": "1",
"body": "In order to adapt it, you need to replace my exception generators `DynamicException.Create` with your own ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:07:15.520",
"Id": "434257",
"Score": "0",
"body": "I think you make some very good points, I'll definitely be implementing the `.ToList()` change and specifying which condition causes the exception does seem like the better option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:12:42.517",
"Id": "434274",
"Score": "2",
"body": "I spot a _using while if if throw_ are you thinking what I am thinking ... :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:13:46.343",
"Id": "434275",
"Score": "0",
"body": "Indeed! A new use-case where C# has to be fixed :-P"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:59:29.017",
"Id": "223932",
"ParentId": "223929",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "223932",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T08:37:42.600",
"Id": "223929",
"Score": "5",
"Tags": [
"c#",
"comparative-review",
"error-handling",
"url"
],
"Title": "Detecting the presence of multiple URL segments"
} | 223929 |
<p>Security assessment of our codebase reported the following vulnerability - </p>
<blockquote>
<p><strong>Vulnerability Description</strong></p>
<p>The method x() in xyz.java stores sensitive data in a String object,
making it impossible to reliably purge the data from memory. </p>
<p><strong>Vulnerability Risk</strong></p>
<p>Sensitive data (such as passwords, social security numbers, credit
card numbers etc) stored in memory can be leaked if memory is not
cleared after use. Often, Strings are used store sensitive data,
however, since String objects are immutable, removing the value of a
String from memory can only be done by the JVM garbage collector. The
garbage collector is not required to run unless the JVM is low on
memory, so there is no guarantee as to when garbage collection will
take place. In the event of an application crash, a memory dump of the
application might reveal sensitive data.</p>
</blockquote>
<p>Sample code, with comment against line on which vulnerability has been reported - </p>
<pre><code>String expDetails = "";
// extract expiry year in YYYY
if (!CommonUtil.isEmpty(paymentDetails.getExpiryYear())) {
expDetails = paymentDetails.getExpiryYear();
}
// expiry month in MM
String monthStr = "";
if (!CommonUtil.isEmpty(paymentDetails.getExpiryMonth())) {
int month = Integer.parseInt(paymentDetails.getExpiryMonth()) + 1;
expDetails += month > 9 ? String.valueOf(month) : "0" + month; //Vulnerability reported in this line - String.valueOf() operation it seems.
}
try {
reqParams.put("CardNum",
encrypt(params[4], paymentDetails.getCardNumber()));
reqParams.put("expiryDate", encrypt(params[4], expDetails));
reqParams.put("CVVNum",
encrypt(params[4], paymentDetails.getCvvNumber()));
} catch (Exception e) {
}
</code></pre>
<blockquote>
<p><strong>Remediation</strong></p>
<p>Always be sure to clear sensitive data when it is no longer needed.
Instead of storing sensitive data in immutable objects like Strings,
use byte arrays or character arrays that can be programmatically
cleared.</p>
</blockquote>
<p>If I alter this code to following, using a byte array, instead of a string - </p>
<pre><code> byte[] expDetailsNew = null;
// extract expiry year in YYYY
if (!CommonUtil.isEmpty(paymentDetails.getExpiryYear())) {
expDetailsNew = paymentDetails.getExpiryYear().getBytes();
}
// expiry month in MM
String monthStr = "";
if (!CommonUtil.isEmpty(paymentDetails.getExpiryMonth())) {
int month = Integer.parseInt(paymentDetails.getExpiryMonth()) + 1;
if(month>9)
{
byte[] combined = new byte[expDetailsNew.length + Integer.toString(month).length()];
System.arraycopy(expDetailsNew, 0, combined, 0, expDetailsNew.length);
System.arraycopy(Integer.toString(month).getBytes(), 0, combined, expDetailsNew.length, Integer.toString(month).length());
expDetailsNew = combined;
}
}
try {
reqParams.put("CardNum",
encrypt(params[4], paymentDetails.getCardNumber()));
reqParams.put("expiryDate", encrypt(params[4], new String(expDetailsNew))); //I still need to do new String() here
expDetailsNew = null;
reqParams.put("CVVNum",
encrypt(params[4], paymentDetails.getCvvNumber()));
} catch (Exception e) {
}
</code></pre>
<p>I still need to do new String() at one point, as commented above. Does the vulnerability still remain?</p>
<p><strong>Update</strong></p>
<p>The same vulnerability has also been reported in the following segment as well -</p>
<pre><code>String decValue = null;
if(someCondition)
{
decValue = CitruspgEncryptionUtil.decrypt(encText, key); //Not reported here
}
.. many else if blocks which assign string value to decValue variable, but not reported on these
..
else if(someOtherCondition)
{
decValue = String.valueOf(someMethodReturningStringOutput); //Vulnerability reported due to the String.valueOf() it seems.
}
</code></pre>
<p>It is not clear how the last case only is vulnerable. Also, what would be the fix here. </p>
<p><strong>Update 2</strong></p>
<p>Method encrypt being called from try block of 1st example - </p>
<pre><code>private String encrypt(String pKey, String pData) throws Exception {
byte[] lKey = Hex.fromString(pKey);
byte[] lData = Hex.fromString(pData);
//lKey, lData are then used as such..
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:47:58.603",
"Id": "434325",
"Score": "0",
"body": "Please provide more context. Is this code in a web application? Where do the parameters come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T10:22:30.707",
"Id": "434438",
"Score": "0",
"body": "Seems a bit pointless - there already are Strings with card details in `paymentDetails `object, it is impossible to clear them. Also that rule makes more sense in case of encryption keys - and it looks like `params[4]` is also a String instead of char[]/byte[]"
}
] | [
{
"body": "<p>I'll attempt to make two points:</p>\n\n<ol>\n<li>Differentiate where Strings are held in a pool; and,</li>\n<li>Evaluate the code-duration where the sting value is held (i.e. start-to-finish number lines of code).</li>\n</ol>\n\n<p>Since Java 11 (if I recall correctly), all strings not using Unicode are byte arrays. So the discussion should be about whether the reference to a string is shared (within a pool) and how long the memory of its contents exist.</p>\n\n<p>Code that creates a string without thy key word 'new' (e.g. <code>String monthStr = \"\";</code>) will create the string reference in a pool shared within the JVM. I do not recommend sensitive data in a shared pool of strings.</p>\n\n<p>Since you are performing string manipulation, I recommend the StringBuilder class. This class uses a character array. You should be able to avoid false-positive code scans with this class. As soon as you are done with the contents of the StringBuilder class you should clear its memory with either: <code>expDetails.replace(0, expDetails.length(), \"*\");</code> or <code>expDetails.delete(0, expDetails.length());</code> If you continue with your byte array solution I recommend implementing code that writes over the array data after you call the <code>.put(...) method</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T22:25:39.567",
"Id": "225161",
"ParentId": "223934",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:34:42.887",
"Id": "223934",
"Score": "2",
"Tags": [
"java",
"strings",
"security"
],
"Title": "Remediation for security vulnerability due to storing sensitive information in strings"
} | 223934 |
<p>I have extensively reviewed 2 old articles on the subject: <a href="https://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript">https://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript</a> and <a href="https://stackoverflow.com/questions/5529934/javascript-numbers-to-words">https://stackoverflow.com/questions/5529934/javascript-numbers-to-words</a> and the answers therein using various methods for spelling a number into words in English.</p>
<p>I have tried to come-up with new different and simple method I am calling it a Single Loop String Triplets (SLST) and thus avoid the use of excessive arithmetic number operations, switches, array manipulations, reversing or splitting strings/arrays, or function recursion.</p>
<p>The method is not limited to JavaScript and can be used in other programming languages as the structure and flow is simple to code.</p>
<p>The principle applied here is to follow the human reading logic of pronouncing and writing the number (in US English) from Left to Right using the standard US English (i.e. without an “and” after the hundred parts).</p>
<p>The function is made to work for whole numbers (integers). But may be called twice for whole and fractional parts after a number split at the decimal point.</p>
<p>Also currency and sub-currency words could be added easily if a whole/fractional split is made.</p>
<p><strong>It is not intended for the function to do everything or check everything as this could be left to a another higher function that will call this function, therefore the following are not accounted for simplicity:</strong></p>
<p><strong>- No checks for negative numbers.</strong></p>
<p><strong>- No checks for non-number (NaN) strings/data.</strong></p>
<p><strong>- No checks or conversion for exponential notations.</strong></p>
<p>However, large numbers can be passed as a String if necessary.</p>
<p>The “Scale” Array may be increased by adding additional scales above “Decillion”.</p>
<p>It is simple to add a Comma "," after each scale words (except last) as some would prefer that.</p>
<p>Here how it works with an example:</p>
<p>Example Number: <strong>1223000789</strong></p>
<p><strong>One Billion Two Hundred Twenty-Three Million Seven Hundred Eighty-Nine</strong>.</p>
<p><strong>1.</strong> Stringfy and convert to shortest triplets padded with zero:</p>
<pre><code>NumIn = "0".repeat(NumIn.length * 2 % 3) + NumIn;
</code></pre>
<p>The stringfied Number in Triplets is now (2 zeros added to the LH):</p>
<blockquote>
<p>001223000789</p>
</blockquote>
<p>In other words the number is now:
<a href="https://i.stack.imgur.com/llZLj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/llZLj.png" alt="enter image description here"></a></p>
<p>In our example, no triplets exist for scales above Billions, so no Trillions or above num scales.</p>
<p><strong>2.</strong> Get count of Triplets: in this case 4 Triplets (i.e. count 3 to 0):</p>
<pre><code>Triplets = NumIn.length / 3 - 1
</code></pre>
<p><strong>3.</strong> Loop starting from the Most Significant Triplet (MST) (i.e. like you read the number) and:</p>
<p>(a) Convert each Triplet number to words (1 to 999) and add the scale name after it.</p>
<p>(b) If a triplet is empty (i.e. 000) then skip it.</p>
<p>(c) Join the new Triplet words to the end of the previous one.</p>
<p>Line 7 of the code ensures a hyphen is inserted for numbers between 21 to 99 in accordance with English numerals writing (i.e. Twenty-One, Fifty-Seven, etc.). You could delete that if it does not apply to you together with the associated variable declaration.</p>
<p><strong>Graphical Example of the above:</strong></p>
<p><a href="https://i.stack.imgur.com/l1Z5U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l1Z5U.png" alt="enter image description here"></a></p>
<p><strong>Result</strong>:</p>
<p><strong>One Billion Two Hundred Twenty-Three Million Seven Hundred Eighty-Nine</strong>.</p>
<p>I have found this to be the simplest method to understand and code.</p>
<p>I have also coded the same function in VBA.</p>
<p>I would like the code to be reviewed for any bugs, optimization, or improvements. I am sure there is room for improvements and corrections.</p>
<p>Thanks in advance to all, your valuable inputs and feedback appreciated.</p>
<p>Mohsen Alyafei</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function NumToWordsInt(NumIn) {
//-------------------------------------------------------
//Convert Integer Number to English Words
//Using a Single Loop String Triplets (SLST) Methods
//Mohsen Alyafei 10 July 2019
//Call it for a whole number and fractional separately
//-------------------------------------------------------
if (NumIn==0) return "Zero";
var Ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
var Tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
var Scale = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"];
var N1, N2, Sep, L, j, i, h,Trplt,tns="", NumAll = "";
NumIn += ""; //NumIn=NumIn.toString()
//----------------- code start -------------------
NumIn = "0".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded
j = 0; //Start with the highest triplet from LH
for (i = NumIn.length / 3 - 1; i >= 0; i--) { //Loop thru number of triplets from LH most
Trplt = NumIn.substring(j, j + 3); //Get a triplet number starting from LH
if (Trplt != "000") { //Skip empty triplets
h = ""; //Init hundreds //-------inner code for 1 triplet
Trplt[2] != "0" ? Sep="-":Sep=" "; //Only if hyphen needed for nums 21 to 99
N1 = Number(Trplt[0]); //Get Hundreds digit
N2 = Number(Trplt.substr(1)); //Get 2 lowest digits (00 to 99)
N2 > 19 ? tns = Tens[Number(Trplt[1])] + Sep + Ones[Number(Trplt[2])]:tns = Ones[N2]
if (N1 > 0) h = Ones[N1] + " Hundred" //Add " hundred" if needed
Trplt = (h + " " + tns).trim() + " " + Scale[i]; //Create number with scale ----inner code ends
NumAll = NumAll + Trplt + " "; //join the triplets scales to previous
}
j += 3; //Go for next lower triplets (move to RH)
}
//----------------- code end ---------------------
return NumAll.trim(); //Return trimming excess spaces
}
//
//
//================= for testing ================
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = NumToWordsInt(document.getElementById('number').value);
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="words"></span>
<input id="number" type="text" /></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:42:03.917",
"Id": "434405",
"Score": "0",
"body": "You are partially skipping non-number glyphs. They are taken into account for the magnitude of the number, but not the triplets. Is this as designed? For instance, _1pppp0_ yields _One Hundred undefined Thousand undefined_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:24:07.647",
"Id": "434411",
"Score": "0",
"body": "@dfhwze not sure what is \"1pppp0\" is this an integer in any form or language?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:27:40.893",
"Id": "434412",
"Score": "0",
"body": "It is probably not, but I wonder whether you have implemented behavior for negative paths like this, or whether you don't care about bad input. That's all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T10:54:19.933",
"Id": "434444",
"Score": "0",
"body": "@dfhwze Thanks. It is intended that bad inputs including negative numbers, fractional numbers, etc. are caught at a higher level function before called this function"
}
] | [
{
"body": "<p>The following code with revised variable names and less coding</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function NumToWordsInt(NumIn) {\n//---------------------------------------\n//Convert Integer Number to English Words\n//Using a Loop String Triplets\n//Mohsen Alyafei 10 July 2019\n//Call for whole and for fractional parts\n//---------------------------------------\n\n if (NumIn==0) return \"Zero\";\n var Small = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"];\n var Tens = [\"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"];\n var Scale = [\"\", \"Thousand\", \"Million\", \"Billion\", \"Trillion\", \"Quadrillion\", \"Quintillion\", \"Sextillion\", \"Septillion\", \"Octillion\", \"Nonillion\", \"Decillion\"];\n var NHundred, NSmall, Sep, TripletPos, WHundred,TotalTriplets,Triplet,WordSmall=\"\", NumAll = \"\";\n NumIn+=\"\" //NumIn=NumIn.toString()\n//----------------- code start -------------------\n NumIn = \"0\".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded\n TripletPos = 0; //Start with the highest triplet from LH\n for (TotalTriplets = NumIn.length / 3 - 1; TotalTriplets >= 0; TotalTriplets--) { //Loop thru number of triplets from LH most\n Triplet = NumIn.substring(TripletPos, TripletPos + 3); //Get a triplet number starting from LH\n if (Triplet != \"000\") { //Skip empty triplets\n//------- One Triplet Loop decode ---------\n Triplet[2] != \"0\" ? Sep=\"-\":Sep=\" \"; //Only for dash for 21 to 99\n NHundred = Number(Triplet[0]); //Get Hundreds digit\n NSmall = Number(Triplet.substr(1)); //Get 2 lowest digits (00 to 99) \n NSmall > 19 ? WordSmall = Tens[Number(Triplet[1])] + Sep + Small[Number(Triplet[2])]:WordSmall = Small[NSmall]\n //Add \" hundred\" if needed, Create number with scale, and join the Triplet scales to previous\n NumAll = NumAll + ((NHundred>0 ? WHundred = Small[NHundred] + \" Hundred\": WHundred=\"\") + \" \" + WordSmall).trim() + \" \" + Scale[TotalTriplets]+ \" \"; \n }\n TripletPos += 3; //Go for next lower triplets (move to RH)\n }\n//----------------- code end --------------------- \n return NumAll.trim(); //Return trimming excess spaces\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><input type=\"text\" name=\"number\" placeholder=\"Number\" onkeyup=\"word.innerHTML=NumToWordsInt(this.value)\" />\n<div id=\"word\"></div>\n\n<script>\nfunction NumToWordsInt(NumIn) {\n//---------------------------------------\n//Convert Integer Number to English Words\n//Using a Loop String Triplets\n//Mohsen Alyafei 10 July 2019\n//Call for whole and for fractional parts\n//---------------------------------------\n\n if (NumIn==0) return \"Zero\";\n var Small = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"];\n var Tens = [\"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"];\n var Scale = [\"\", \"Thousand\", \"Million\", \"Billion\", \"Trillion\", \"Quadrillion\", \"Quintillion\", \"Sextillion\", \"Septillion\", \"Octillion\", \"Nonillion\", \"Decillion\"];\n var NHundred, NSmall, Sep, TripletPos, WHundred,TotalTriplets,Triplet,WordSmall=\"\", NumAll = \"\";\n NumIn+=\"\" //NumIn=NumIn.toString()\n//----------------- code start -------------------\n NumIn = \"0\".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded\n TripletPos = 0; //Start with the highest triplet from LH\n for (TotalTriplets = NumIn.length / 3 - 1; TotalTriplets >= 0; TotalTriplets--) { //Loop thru number of triplets from LH most\n Triplet = NumIn.substring(TripletPos, TripletPos + 3); //Get a triplet number starting from LH\n if (Triplet != \"000\") { //Skip empty triplets\n//------- One Triplet Loop decode ---------\n Triplet[2] != \"0\" ? Sep=\"-\":Sep=\" \"; //Only for dash for 21 to 99\n NHundred = Number(Triplet[0]); //Get Hundreds digit\n NSmall = Number(Triplet.substr(1)); //Get 2 lowest digits (00 to 99) \n NSmall > 19 ? WordSmall = Tens[Number(Triplet[1])] + Sep + Small[Number(Triplet[2])]:WordSmall = Small[NSmall]\n //Add \" hundred\" if needed, Create number with scale, and join the Triplet scales to previous\n NumAll = NumAll + ((NHundred>0 ? WHundred = Small[NHundred] + \" Hundred\": WHundred=\"\") + \" \" + WordSmall).trim() + \" \" + Scale[TotalTriplets]+ \" \"; \n }\n TripletPos += 3; //Go for next lower triplets (move to RH)\n }\n//----------------- code end --------------------- \n return NumAll.trim(); //Return trimming excess spaces\n}\n</script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:54:57.290",
"Id": "434710",
"Score": "0",
"body": "thanks for this. Really helps make my variables human :-) and the shorter 3 line less code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:57:40.970",
"Id": "434719",
"Score": "0",
"body": "I like this one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T14:21:09.610",
"Id": "434876",
"Score": "2",
"body": "This answer is basically a code dump, or alternate solution. It would be a great answer on stackoverflow but it might be considered a poor answer on code review. The goal on code review is to make observations about the code to help the original poster improve their code generally. Please see the code review guidelines at https://codereview.stackexchange.com/help/how-to-answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:39:48.957",
"Id": "224147",
"ParentId": "223936",
"Score": "2"
}
},
{
"body": "<p>I would use a <a href=\"https://javascript.info/closure\" rel=\"nofollow noreferrer\">Closure</a> to avoid excessive memory usage and allow for reusability of the method. Try also to adhere to <a href=\"https://www.w3schools.com/js/js_conventions.asp\" rel=\"nofollow noreferrer\">styling and naming conventions</a>. I don't mind variable names <code>a, i, j, ..</code>. Make sure you document them well. Replace <code>var</code> with respectively <code>let</code> and <code>const</code>.</p>\n\n<p><a href=\"https://jsfiddle.net/3egc2p4z/\" rel=\"nofollow noreferrer\">Fiddle</a></p>\n\n<pre><code>(function() {\n \"use strict\";\n\n function toLongNumber() {\n\n return function() {\n\n const ones = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"];\n const tens = [\"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"];\n const scale = [\"\", \"Thousand\", \"Million\", \"Billion\", \"Trillion\", \"Quadrillion\", \"Quintillion\", \"Sextillion\", \"Septillion\", \"Octillion\", \"Nonillion\", \"Decillion\"];\n\n return function(n) {\n\n let n1, n2, s, i, h, triplet, j = 0, tns = \"\", m = \"\";\n n += \"\";\n n = \"0\".repeat(n.length * 2 % 3) + n;\n\n for (i = n.length / 3 - 1; i >= 0; i--) {\n triplet = n.substring(j, j + 3);\n if (triplet != \"000\") {\n h = \"\";\n triplet[2] != \"0\" ? s = \" -\" : s = \" \";\n n1 = Number(triplet[0]);\n n2 = Number(triplet.substr(1));\n n2 > 19 ? tns = tens[Number(triplet[1])] +\n s + ones[Number(triplet[2])] : tns = ones[n2]\n if (n1 > 0) h = ones[n1] + \" Hundred\"\n triplet = (h + \" \" + tns).trim() + \" \" + scale[i];\n m = m + triplet + \" \";\n }\n j += 3;\n }\n return m.trim();\n }\n }();\n }\n\n window.toLongNumber = toLongNumber();\n})();\n</code></pre>\n\n<p>and usage..</p>\n\n<pre><code>word.innerHTML=toLongNumber(this.value)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:56:51.303",
"Id": "434711",
"Score": "0",
"body": "Thanks for your additions and code improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:00:26.687",
"Id": "434712",
"Score": "1",
"body": "I added a fiddle to show how to reuse the function, declaring all arrays just once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:03:50.247",
"Id": "434713",
"Score": "0",
"body": "Good point indeed. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:10:27.257",
"Id": "434714",
"Score": "0",
"body": "Thanks. Appreciate your comments on the methodolgy priciple and the use of the (n = \"0\".repeat(n.length * 2 % 3) + n;) as this the core SLST method. Once you get this, you can do whatever with the triplet string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:28:23.193",
"Id": "434716",
"Score": "1",
"body": "Why do you need to nest 4 functions? I think 2 are enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:33:09.580",
"Id": "434717",
"Score": "0",
"body": "@RolandIllig I made more functions, in order to be able to refactor the method to some API easier. This is why I put _window.toLongNumber = toLongNumber();_ in an outer function. This leaves me with 3 functions. I could extract the const array declarations and take out that function, but then I wouldn't have been able to provide this closure function, where the arrays are only declared once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:42:40.130",
"Id": "434735",
"Score": "0",
"body": "Thanks to all for sharing their code but the theory is **single loop string triplets (SLST)**. There are many methods to convert numbers to words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T05:28:46.963",
"Id": "434814",
"Score": "0",
"body": "@dfhwze Thanks for your suggestions. The use of \"const\" variables could limit the variable as it cannot be updated, say if required to be updated in case the output is required as \"all small letters\" or \"all capital letters\" or as an example: \"initially capitalized triplets\" words e.g.: \"Two thousand Two hundred twenty-two\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T05:29:45.227",
"Id": "434815",
"Score": "1",
"body": "Be agile, when you need a _const_ to get updated, replace it with _let_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T07:07:23.780",
"Id": "434827",
"Score": "0",
"body": "@dfhwze tried that but encountered some errors with old versions of Acrobat JS in PDF files; using old versinos of Acrobat."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:52:24.403",
"Id": "224149",
"ParentId": "223936",
"Score": "3"
}
},
{
"body": "<p>Your code is quite short, which is good. On the other hand, it is equally unreadable as short, which makes it worse.</p>\n\n<ul>\n<li><p>You chose really bad variable names. Most of them are one-letter variables and do not tell the reader anything about what they contain or what their purpose is.</p></li>\n<li><p>Your code looks inconsistent. Sometimes you write a space around operators, like in <code>h = \"\"</code>, and sometimes you leave out the space, as in <code>Sep=\"-\"</code>.</p></li>\n<li><p>Your habit of adding a comment to every line of code might come from the 1960s, where many programs were written in assembly language and were not abstracted enough to be understandable without a detailed explanation. 60 years later, the programming languages have evolved and are much more expressive. Having this many comments is a sign that the code is not as clearly written as possible.</p></li>\n<li><p>You are using the <code>==</code> and <code>!=</code> operators, which should not be used in reliable JavaScript programs. Prefer to use the <code>===</code> and <code>!==</code> operators instead.</p></li>\n</ul>\n\n<pre><code>function NumToWordsInt(NumIn) {\n//-------------------------------------------------------\n//Convert Integer Number to English Words\n//Using a Single Loop String Triplets (SLST) Methods\n//Mohsen Alyafei 10 July 2019\n//Call it for a whole number and fractional separately\n//-------------------------------------------------------\n</code></pre>\n\n<p>Your introductory comment mentions that this function could be applied to fractions. This doesn't make sense. While <code>1.1</code> is pronounced as <code>one dot one</code>, the fraction <code>1.100</code> has the same mathematical value but would be pronounced as <code>one dot one thousand</code>. Therefore you should omit the last sentence from the documentation.</p>\n\n<pre><code> if (NumIn==0) return \"Zero\";\n var Ones = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"];\n var Tens = [\"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"];\n var Scale = [\"\", \"Thousand\", \"Million\", \"Billion\", \"Trillion\", \"Quadrillion\", \"Quintillion\", \"Sextillion\", \"Septillion\", \"Octillion\", \"Nonillion\", \"Decillion\"];\n</code></pre>\n\n<p>Your code currently creates these arrays anew at every call of the function. This is not necessary since these arrays are never modified. The JavaScript compiler should be smart enough to recognize this and optimize that part for you, so that these arrays are placed in some static storage. As of 2019, I don't know how optimizing the JavaScript compilers are, so if you benchmark your program and find out that this single function is the bottleneck, this might be a thing to optimize.</p>\n\n<pre><code> var N1, N2, Sep, L, j, i, h,Trplt,tns=\"\", NumAll = \"\";\n</code></pre>\n\n<p>It's hard to see what all these variables are used for. Regarding the names, you should not omit vowels. Say <code>Triplet</code> instead of <code>Trplt</code>, to clearly tell the reader that the code is not about <code>Trumpletters</code>.</p>\n\n<pre><code>//----------------- code start -------------------\n</code></pre>\n\n<p>Instead of this line you should rather just insert an empty line into the code. This makes it much more obvious that there is a pause here, and a new section starts.</p>\n\n<pre><code> Trplt[2] != \"0\" ? Sep=\"-\":Sep=\" \";\n</code></pre>\n\n<p>The <code>?:</code> operator is meant to be used for simple expressions, not as a way to structure code. Currently you mention <code>Sep=</code> twice, which can be rewritten like this:</p>\n\n<pre><code> sep = triplet[2] !== '0' ? '-' : ' ';\n</code></pre>\n\n<p>This change makes the code look much lighter. The main action (assigning some value to <code>sep</code>) is clearly presented at the very left. The variable names do not use abbreviations, the <code>!==</code> operator makes the comparison predictable and the single quotes make the strings look lighter than the double quotes from before.</p>\n\n<pre><code> N1 = Number(Trplt[0]); //Get Hundreds digit\n</code></pre>\n\n<p>You could have omitted the comment <code>Get Hundreds digit</code> if you had renamed <code>N1</code> to <code>hundreds</code> or <code>hundredsDigit</code>.</p>\n\n<pre><code> N2 > 19 ? tns = Tens[Number(Trplt[1])] + Sep + Ones[Number(Trplt[2])]:tns = Ones[N2]\n</code></pre>\n\n<p>This line is very long and complicated. Can you read it aloud and remember what it does? I cannot, therefore I would write it like this:</p>\n\n<pre><code> if (rem100 > 19)\n tens = Tens[+triplets[1]] + sep + Ones[+triplets[2]];\n else\n tens = Ones[+rem100];\n</code></pre>\n\n<p>Sure, it's a bit longer but the if-then-else structure is clearly visible, which allows a reader to quickly understand what is happening here. The <code>?:</code> that is deeply hidden in the middle of the line is not that clear.</p>\n\n<pre><code> (h + \" \" + tns).trim()\n return NumAll.trim();\n</code></pre>\n\n<p>When you explain to a human how to spell out the numbers, you would probably not need to mention that extraneous whitespace needs to be trimmed. Yet your code does exactly that. This is another sign that your code is not as human-like as it could be.</p>\n\n<p>Since you didn't provide any unit tests, it is hard to see whether this code works as intended. It is also hard to read and hard to step through using a debugger, because of the many badly named variables.</p>\n\n<p>To improve the code, I started with your code and finally arrived at the following code:</p>\n\n<ul>\n<li>There are no comments because the code is expressive enough.</li>\n<li>The code is structured into manageable pieces that fit on a single screen each.</li>\n<li>There is one function for small numbers, one function for large numbers, and a self-test.</li>\n<li>All variables are lowercase and have expressive names.</li>\n<li>The constants are line-wrapped so that they fit comfortably on a screen.</li>\n<li>The constants are arranged in groups of 5 (or 3 for the long words in <code>scale</code>).</li>\n</ul>\n\n<pre><code>(function () {\n \"use strict\";\n\n const ones = [\n \"Zero\", \"One\", \"Two\", \"Three\", \"Four\",\n \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\",\n \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\",\n \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"\n ];\n const tens = [\n \"\", \"\", \"Twenty\", \"Thirty\", \"Forty\",\n \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"\n ];\n const hundred = \"Hundred\";\n const scale = [\n \"\", \"Thousand\", \"Million\",\n \"Billion\", \"Trillion\", \"Quadrillion\",\n \"Quintillion\", \"Sextillion\", \"Septillion\",\n \"Octillion\", \"Nonillion\", \"Decillion\"\n ];\n\n function strRem1000(rem1000) {\n const result = [];\n if (rem1000 >= 100) {\n result.push(ones[rem1000 / 100 | 0], hundred);\n }\n\n const rem100 = rem1000 % 100;\n if (rem100 === 0) {\n // do nothing\n } else if (rem100 < 20) {\n result.push(ones[rem100]);\n } else if (rem100 % 10 === 0) {\n result.push(tens[rem100 / 10]);\n } else {\n result.push(tens[rem100 / 10 | 0] + '-' + ones[rem100 % 10]);\n }\n\n return result.join(' ');\n }\n\n function toLongNumber(n) {\n let result = [];\n\n if (n === '0') {\n return ones[0];\n }\n\n let scaleIndex = 0;\n for (let end = n.length; end > 0; end -= 3) {\n const start = Math.max(0, end - 3);\n\n let aaa = n.substring(start, end);\n let nnn = parseInt(aaa, 10);\n if (nnn > 0) {\n if (scaleIndex > 0) {\n result.unshift(scale[scaleIndex]);\n }\n result.unshift(strRem1000(nnn));\n }\n scaleIndex++;\n }\n\n return result.join(' ');\n }\n\n function test() {\n function testcase(n, words) {\n const result = toLongNumber(n)\n if (result !== words) {\n console.log('expected', words, 'for', n, 'got', result);\n }\n }\n\n testcase('0', 'Zero');\n testcase('5', 'Five');\n testcase('10', 'Ten');\n testcase('20', 'Twenty');\n testcase('21', 'Twenty-One');\n testcase('75', 'Seventy-Five');\n testcase('100', 'One Hundred');\n testcase('150', 'One Hundred Fifty');\n testcase('157', 'One Hundred Fifty-Seven');\n testcase('999', 'Nine Hundred Ninety-Nine');\n testcase('1000', 'One Thousand');\n testcase('10000', 'Ten Thousand');\n testcase('123456', '' +\n 'One Hundred Twenty-Three Thousand ' +\n 'Four Hundred Fifty-Six');\n testcase('123456789', '' +\n 'One Hundred Twenty-Three Million ' +\n 'Four Hundred Fifty-Six Thousand ' +\n 'Seven Hundred Eighty-Nine');\n testcase('1000000890', 'One Billion Eight Hundred Ninety');\n testcase('1000000000000000000000000000000000', 'One Decillion');\n }\n\n test();\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T07:12:45.927",
"Id": "434828",
"Score": "0",
"body": "will take up your advice and recommendations with a revised code. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:31:08.663",
"Id": "224156",
"ParentId": "223936",
"Score": "4"
}
},
{
"body": "<h2>Update 30 June 2020 with a new Updated/Improved Version.</h2>\n<p>While maintaining the same concept of using the Single Loop String Triples (SLTS) method, the code has been updated and improved as follows:</p>\n<ul>\n<li>Variables names are now more readable.</li>\n<li>Use of <code>let</code> instead of <code>var</code>.</li>\n<li>Removed the counter <code>var ‘j’</code> to track the scale positions. Now computed from the triplet position.</li>\n<li>Words are concatenated by the addition assignment operator (+=).</li>\n<li>The need to use <code>trim()</code> to trim trailing spaces from concatenated "wordified" numbers is no longer necessary.</li>\n<li>Added unit testing code to test the accuracy of the outputs.</li>\n<li>Scale names and units, tens arrays are being moved to the top of their scope before code execution; gives a slight performance improvement.</li>\n<li>Generating the scales (thousands, millions, etc.) needs one statement.</li>\n<li>Generating the words for numbers from 1 to 999 needs only two (2) statements:</li>\n</ul>\n<pre><code>if (DigitTensUnits<20) WordUnitsTens = UnitsTensTable[DigitTensUnits]; // Word 1 to 99\nelse WordUnitsTens = EntiesTable[Number(Triplet[1])] + Hyphen +\n UnitsTensTable[Number(Triplet[2])];\n\nWordHundreds = DigitHundreds > 0 ? UnitsTensTable[DigitHundreds] + " Hundred" : ""; // Word 100 to 900\n</code></pre>\n<ul>\n<li>Other improvements suggested in the posts.</li>\n</ul>\n<p>The code using the SLTS method has been benchmarked against other methods and is found to be of better performance; in some cases is almost over twice faster.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*********************************************************************\n* @function : NumToWordsUnsignedInt()\n* @purpose : Converts Unsigned Integers to Words (Wordify Number)\n* Using the SLST Method.\n* @version : 0.12\n* @author : Mohsen Alyafei\n* @date : 28 June 2020\n* @param : {number} [integer numeric or string]\n* @returns : {string} The wordified number string\n**********************************************************************/\n\nvar UnitsTensTable = [\"\",\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\",\"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"],\n EntiesTable = [\"\",\"\",\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"],\n ScaleTable = [\"\",\"Thousand\",\"Million\",\"Billion\",\"Trillion\",\"Quadrillion\",\"Quintillion\",\"Sextillion\",\"Septillion\",\"Octillion\",\"Nonillion\",\"Decillion\"];\n\nfunction NumToWordsUnsignedInt(NumIn=0) {\nif (NumIn===0) return \"Zero\";\nlet Result = \"\";\nNumIn += \"\";\nNumIn = \"0\".repeat(NumIn.length * 2 % 3) + NumIn; // Create shortest string triplets 0 padded\n\nfor (let TripletCount = NumIn.length; TripletCount> 0; TripletCount-=3){ // Loop thru all triplets\n TripletPosition = (NumIn.length - TripletCount); // Triplet position\n let Triplet = NumIn.substring(TripletPosition,TripletPosition+3); // 1 triplet\n\n if (Triplet !== \"000\"){ // Skip empty triplets\n let Hyphen = Triplet[2] !== \"0\" ? \"-\" : \"\", // Hyphens only for 21 to 99\n DigitHundreds = Number(Triplet[0]), // Hundreds digit\n DigitTensUnits= Number(Triplet.substr(1)), // Lowest digits (01 to 99)\n WordScales = ScaleTable[TripletCount/3-1]; // Scale Name\n\n if (DigitTensUnits < 20) WordUnitsTens = UnitsTensTable[DigitTensUnits]; // Word 1- to 99\n else WordUnitsTens = EntiesTable[Number(Triplet[1])] + Hyphen +\n UnitsTensTable[Number(Triplet[2])];\n WordHundreds = DigitHundreds > 0 ? UnitsTensTable[DigitHundreds] + \" Hundred\" : \"\"; // Word 100 to 900\n\n // Join Unit, Tens, Hund, and Scale Name (insert necessary spaces if needed)\n Result += (Result ? \" \" : \"\") + WordHundreds + \n (DigitHundreds && DigitTensUnits ? \" \" : \"\") + WordUnitsTens;\n Result += (Result && WordScales ? \" \" : \"\") + WordScales;\n }\n}\nreturn Result;\n}\n\n//=========================================\n// Test Code\n//=========================================\nvar r=0; // test tracker\nr |= test(0,\"Zero\");\nr |= test(5,\"Five\");\nr |= test(10,\"Ten\");\nr |= test(19,\"Nineteen\");\nr |= test(33,\"Thirty-Three\");\nr |= test(100,\"One Hundred\");\nr |= test(111,\"One Hundred Eleven\");\nr |= test(890,\"Eight Hundred Ninety\");\nr |= test(1234,\"One Thousand Two Hundred Thirty-Four\");\nr |= test(12345,\"Twelve Thousand Three Hundred Forty-Five\");\nr |= test(123456,\"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six\");\nr |= test(1234567,\"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven\");\nr |= test(12345678,\"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight\");\nr |= test(123456789,\"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine\");\nr |= test(1234567890,\"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety\");\nr |= test(1001,\"One Thousand One\");\nr |= test(10001,\"Ten Thousand One\");\nr |= test(100001,\"One Hundred Thousand One\");\nr |= test(1000001,\"One Million One\");\nr |= test(10000001,\"Ten Million One\");\nr |= test(100000001,\"One Hundred Million One\");\nr |= test(12012,\"Twelve Thousand Twelve\");\nr |= test(120012,\"One Hundred Twenty Thousand Twelve\");\nr |= test(1200012,\"One Million Two Hundred Thousand Twelve\");\nr |= test(12000012,\"Twelve Million Twelve\");\nr |= test(120000012,\"One Hundred Twenty Million Twelve\");\nr |= test(75075,\"Seventy-Five Thousand Seventy-Five\");\nr |= test(750075,\"Seven Hundred Fifty Thousand Seventy-Five\");\nr |= test(7500075,\"Seven Million Five Hundred Thousand Seventy-Five\");\nr |= test(75000075,\"Seventy-Five Million Seventy-Five\");\nr |= test(750000075,\"Seven Hundred Fifty Million Seventy-Five\");\nr |= test(1000,\"One Thousand\");\nr |= test(1000000,\"One Million\");\nr |= test(1000000000,\"One Billion\");\nr |= test(1000000000000,\"One Trillion\");\nr |= test(\"1000000000000000\",\"One Quadrillion\");\nr |= test(\"1000000000000000000\",\"One Quintillion\");\nr |= test(\"1000000000100100100100\",\"One Sextillion One Hundred Billion One Hundred Million One Hundred Thousand One Hundred\");\n\nif (r==0) console.log(\"All Passed.\");\n\nfunction test(n,should) {\nlet result = NumToWordsUnsignedInt(n);\nif (result !== should) {console.log(`${n} Output : ${result}\\n${n} Should be: ${should}`);return 1;}\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T18:29:52.107",
"Id": "244806",
"ParentId": "223936",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "244806",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T09:55:26.043",
"Id": "223936",
"Score": "9",
"Tags": [
"javascript",
"number-systems",
"numbers-to-words"
],
"Title": "Simple Number to Words using a Single Loop String Triplets in JavaScript"
} | 223936 |
<p>I'm currently writing an activity reporting system based on users; upon looking through a lot of files I'm noticing that I do a lot of <code>if</code> statements that clearly can be rewritten;</p>
<p>How would you improve this structure of file? I can then take any ideas/improvements from this file & apply them to the rest of the project.</p>
<p>Any improvements are welcome! </p>
<pre><code>const conf = require('../../conf');
const globals = require('../../globals');
const ping_history = require('./ping_history');
const ConsumerAccounts = require('../models/Consumeraccounts');
const redis = globals.redis();
module.exports = active = {};
active.prefix = 'activeusers';
active.expires_secs = globals.secs('3 minutes');
active.payout = {
amount_cents: conf.consumerportal.country_payments["default"].daily_cents,
prefix: 'activepayouts',
history_prefix: 'activepayoutshistory',
threshold_secs: globals.secs('1 hours'),
increment_secs_per_ping: 60
};
active.mark_installed = mark_installed = async function(uuid) {
await ConsumerAccounts.findOne({_id: uuid}).then(result => {
if (result.software_installed) {
return false;
} else {
return result.mark_installed(uuid);
}
}).catch(err => {
});
};
active.payout_increment = async function(uuid, cb) {
let amount_cents, amount_owed, history_key, k, max_amount, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, tally_key, v;
let today = await globals.today();
tally_key = [this.payout.prefix, globals.today(), uuid].join(':');
history_key = [this.payout.history_prefix, globals.today(), uuid].join(':');
await redis.incrby(tally_key, parseInt(this.payout.increment_secs_per_ping));
await redis.get(tally_key).then((tally) => {
if (tally && (+tally) >= this.payout.threshold_secs) {
let history = redis.get(history_key).catch((err) => {
throw err;
});
ConsumerAccounts.findOne({_id: uuid}).then((consumer) => {
ping_history.add(uuid, today);
//checks here!
if (!consumer.payout_eligible) {
return cb(null, false);
}
redis.set(history_key, 1);
amount_cents = this.payout.amount_cents;
max_amount = conf != null ? (ref3 = conf.consumerportal) != null ? (ref4 = ref3.country_payments) != null ? (ref5 = ref4["default"]) != null ? ref5.payout_cap_cents : void 0 : void 0 : void 0 : void 0;
if (typeof consumer !== "undefined" && consumer !== null ? (ref6 = consumer.questionnaire) != null ? ref6.country : void 0 : void 0) {
ref7 = conf.consumerportal.country_payments;
for (k in ref7) {
v = ref7[k];
if (k === consumer.questionnaire.country) {
amount_cents = v != null ? v.daily_cents : void 0;
max_amount = v != null ? v.payout_cap_cents : void 0;
}
}
}
if ((conf != null ? (ref8 = conf.consumerportal) != null ? ref8.limit_amount_owed : void 0 : void 0) && this.payout_eligible) {
amount_owed = (function(_this) {
return function() {
let cents, i, len, ref10, ref9, x;
cents = 0;
ref10 = (ref9 = _this.revenue_history) != null ? ref9 : [];
for (i = 0, len = ref10.length; i < len; i++) {
x = ref10[i];
cents = x.amount_cents;
}
return cents;
};
})(this)();
if (amount_owed >= max_amount) {
this.payout_eligible = false;
consumer.mark_ineligible();
return false;
}
}
consumer.assign_revenue(globals.today(), amount_cents);
consumer.record_event({
event: 'daily_payout_assigned',
amount_cents: amount_cents
});
}).catch(err => {
console.log('Consumer account was not found');
});
} else {
console.log("We haven't hit the correct number yet!");
console.log(tally + " - " + this.payout.threshold_secs);
}
}).catch((err) => {
console.log(err);
console.log("Error Getting Tally Key!")
});
};
active.ws_ping = async function(obj, cb) {
let expires_secs, ref, val;
if (!obj.uuid) {
return cb(new Error('Property `uuid` required'));
}
expires_secs = (ref = obj.expires_secs) != null ? ref : this.expires_secs;
await this.mark_installed(obj.uuid);
await this.payout_increment(obj.uuid);
val = 'u';
return redis.set(this.prefix + ":" + obj.uuid, val, 'EX', expires_secs);
};
active.ping = async function(obj, cb) {
let expires_secs, ref, val;
if (!obj.ip) {
return cb(new Error('Property `ip` required'));
}
if (!obj.port) {
return cb(new Error('Property `port` required'));
}
if (!obj.relay_ip) {
return cb(new Error('Property `relay_ip` required'));
}
if (!obj.relay_port) {
return cb(new Error('Property `relay_port` required'));
}
if (!obj.uuid) {
return cb(new Error('Property `uuid` required'));
}
expires_secs = (ref = obj.expires_secs) != null ? ref : this.expires_secs;
await this.mark_installed(obj.uuid);
val = obj.ip + "_" + obj.port + "_" + obj.relay_ip + "_" + obj.relay_port;
return redis.setex(this.prefix + ":" + obj.uuid, expires_secs, val);
};
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<pre><code>active.mark_installed = mark_installed = async function(uuid) {\n await ConsumerAccounts.findOne({_id: uuid}).then(result => {\n if (result.software_installed) {\n return false;\n } else {\n return result.mark_installed(uuid);\n }\n }).catch(err => {\n\n });\n};\n</code></pre>\n\n<p>Note that <code>async</code>/<code>await</code> is just sugar syntax for promises. Few key things to remember when using it:</p>\n\n<ul>\n<li><code>await</code> \"waits\" for promises.</li>\n<li><code>async</code> functions return a promise.</li>\n<li>Returned values from an <code>async</code> function resolves the promise it returns.</li>\n<li>Thrown errors inside async rejects the promise it returns.</li>\n</ul>\n\n<p>Nothing is wrong with chaining <code>then</code> in <code>async</code>/<code>await</code>, the syntax is perfectly legit. I often use it to inline some operations. However, it's usually not needed. If you're going <code>async</code>/<code>await</code>, go all-in with it.</p>\n\n<p>This could be rewritten as:</p>\n\n<pre><code>active.mark_installed = mark_installed = async function(uuid) {\n try {\n const result = await ConsumerAccounts.findOne({_id: uuid})\n return result.software_installed ? false : result.mark_installed(uuid)\n } catch(error) {\n\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>active.ws_ping = async function(obj, cb) {\n\nactive.ping = async function(obj, cb) {\n</code></pre>\n\n<p>This is an anti-pattern. You're using an <code>async</code> function (which returns a promise that should inform you if the asynchronous operation succeeded or failed), but then you pass in a callback for the error.</p>\n\n<p>Instead of passing in the callback, have the caller attach a <code>then</code> with the callback as the error callback, or <code>await</code> the call in a <code>try-catch</code>.</p>\n\n<pre><code>active.ping = async function(obj) {\n\n // Throwing an error in an async effectively rejects the returned promise.\n if (!obj.ip) throw new Error('Property `ip` required')\n if (!obj.port) throw new Error('Property `port` required')\n if (!obj.relay_ip) throw new Error('Property `relay_ip` required')\n if (!obj.relay_port) throw new Error('Property `relay_port` required')\n if (!obj.uuid) throw new Error('Property `uuid` required')\n\n const ref = obj.expires_secs\n const expires_secs = ref != null ? ref : this.expires_secs\n\n await this.mark_installed(obj.uuid)\n\n const val = `${obj.ip}_${obj.port}_${obj.relay_ip}_${obj.relay_port}`\n\n return redis.setex(`${this.prefix}:${obj.uuid}`, expires_secs, val)\n}\n\n// Usage\nactive.ping(obj).then(result => {\n\n}, error => {\n\n})\n\n// or\ntry {\n const result = await active.ping(obj)\n} catch (error) {\n\n}\n</code></pre>\n\n<hr>\n\n<p>Few other minor nitpicks:</p>\n\n<ul>\n<li>Not a big fan of \"declare all variables ahead of time\". What happens is cognitive overhead, you scroll up to know what's there/what you can assign to. Declare variables as you need it.</li>\n<li>Most of your variables are only ever assigned a value once. Use <code>const</code> for those variables.</li>\n<li>Use Template Literals to construct interpolated strings.</li>\n<li>JavaScript uses camelCase for naming. While your data could be snake-case due to its origins, use camelCase stay consistent on the JS side of things.</li>\n<li>For temporary variables in blocks (i.e. loops, ifs), use <code>let</code>/<code>const</code> within the loop block. This way, you're sure that the variable is scoped to that block, and never leaks out to the outer scopes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:38:19.833",
"Id": "434292",
"Score": "0",
"body": "thankyou very much! my main issue is trying to rewrite the `payout_increment` function; seems so clunky!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:03:57.373",
"Id": "223946",
"ParentId": "223943",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "223946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T11:55:44.227",
"Id": "223943",
"Score": "0",
"Tags": [
"javascript",
"node.js"
],
"Title": "Clean up nodeJS function"
} | 223943 |
<h3>Problem statement</h3>
<p>I have an application that needs to get files from various sources (disk, embedded, http, ftp, ...) so I use a common API for them:</p>
<blockquote>
<pre><code>interface IResourceProvider { }
</code></pre>
</blockquote>
<p>Then I just provide implementations:</p>
<blockquote>
<pre><code>class PhysicalFileProvider : IResourceProvider { }
class HttpProvider : IResourceProvider
{
public HttpProvider(IClient client)
{
client.Dump();
}
}
</code></pre>
</blockquote>
<p>I register them as <code>Named</code> services:</p>
<blockquote>
<pre><code>builder.RegisterType<PhysicalFileProvider>().Named<IResourceProvider>("App");
builder.RegisterType<HttpProvider>().Named<IResourceProvider>("Remote");
</code></pre>
</blockquote>
<p>I do this because I want to be able to replace them for testing so I need to know which service I'm replacing. Here, <code>PhysicalFileProvider</code> gets replaces by a <em>mock</em>.</p>
<blockquote>
<pre><code>builder.RegisterType<PhysicalFileProviderMock>().Named<IResourceProvider>("Remote");
</code></pre>
</blockquote>
<p>All these services are injected into the <code>CompositeProvider</code> which knows how to find a resource (usually by trying all of them).</p>
<blockquote>
<pre><code>class CompositeProvider : IResourceProvider
{
public CompositeProvider(IEnumerable<IResourceProvider> providers)
{
}
}
</code></pre>
</blockquote>
<p>This service should not know anything about the names so <code>IIndexed</code> isn't an option. It gets injected where required and it knows how to determine the correct provider.</p>
<h3>Resolving <code>IResourceProvider</code></h3>
<p>In order to inject all <code>Named</code> services to the <code>CompositeProvider</code> I do some <em>magic</em>. I search for <code>KeyedService</code>s where their <code>ServiceType</code> is <code>IResourceProvider</code>. Then I group them by name and pick the last one as this one would be registered by the test as these registrations happen last just before I call <code>builder.Build()</code>.</p>
<pre><code>builder.Register(context =>
{
var services =
from r in context.ComponentRegistry.Registrations
from s in r.Services.OfType<KeyedService>()
where typeof(IResourceProvider).IsAssignableFrom(s.ServiceType)
group (r, s) by s.ServiceKey into g
let last = g.Last()
select last.r.Activator.ActivateInstance(context, Enumerable.Empty<Parameter>());
return new CompositeProvider(services.Cast<IResourceProvider>());
});
</code></pre>
<h3>Where's the catch?</h3>
<p>Usually, you would register services with <code>As<T></code> so that it flawlessly works with <code>IEnumerable<T></code> but this <em>disables</em> <code>Named</code> and without additional filtering you would end up with three services injected into <code>CompositeProvider</code> These extensions seem to be mutually exclusive. That's what the manual <code>Register</code> and service search is for. It needs to pick the last <code>Named</code> service from a group of servcies with the same name.</p>
<h3>Demo</h3>
<p>In order to test this logic I create this demo code. Interface and class names are real. They just don't have bodies here.</p>
<pre><code>void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<PhysicalFileProvider>().Named<IResourceProvider>("App");
builder.RegisterType<HttpProvider>().Named<IResourceProvider>("Remote");
builder.RegisterType<WebClient>().As<IClient>();
builder.Register(context =>
{
var services =
from r in context.ComponentRegistry.Registrations
from s in r.Services.OfType<KeyedService>()
where typeof(IResourceProvider).IsAssignableFrom(s.ServiceType)
group (r, s) by s.ServiceKey into g
let last = g.Last()
select last.r.Activator.ActivateInstance(context, Enumerable.Empty<Parameter>());
return new CompositeProvider(services.Cast<IResourceProvider>());
});
// Override B for testing
builder.RegisterType<PhysicalFileProviderMock>().Named<IResourceProvider>("Remote");
var container = builder.Build();
var scope = container.BeginLifetimeScope();
scope.ResolveNamed<IResourceProvider>("App").Dump();
scope.ResolveNamed<IResourceProvider>("Remote").Dump();
scope.Resolve<CompositeProvider>().Dump();
scope.Resolve<IClient>().Dump();
}
interface IResourceProvider { }
interface IClient { }
class WebClient : IClient { }
class PhysicalFileProvider : IResourceProvider { }
class HttpProvider : IResourceProvider
{
public HttpProvider(IClient client)
{
client.Dump();
}
}
class PhysicalFileProviderMock : IResourceProvider { }
class CompositeProvider : IResourceProvider
{
public CompositeProvider(IEnumerable<IResourceProvider> providers)
{
providers.Dump();
}
}
</code></pre>
<h3>Questions</h3>
<ul>
<li>Would you say this solution is sane?</li>
<li>Is there a better one?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:27:03.917",
"Id": "434333",
"Score": "0",
"body": "I'm a bit confused, doesn't the latest registration overwrite earlier ones? https://stackoverflow.com/questions/15754702/override-autofac-registration-with-plugin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:29:07.507",
"Id": "434334",
"Score": "0",
"body": "@dfhwze yes and no; it does when you resolve `Remote` so you'll get the latest registration but you'll get all three when you manually search them o_O this is why I need the grouping and last."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:35:29.083",
"Id": "434335",
"Score": "0",
"body": "Wouldn't it be better to make an extension method on _container_ that does this for you given any type _T_ ? I think _ComponentRegistry_ is available on the container as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:37:20.257",
"Id": "434336",
"Score": "0",
"body": "@dfhwze mhmm... usually yes but this kind of _tricks_ are so rare that I actually wasn't going to reuse it anywhere else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:52:38.567",
"Id": "434339",
"Score": "0",
"body": "The unit test does not care about the name. How will you let it use the mock if _scope.Resolve<CompositeProvider>()_ returns the last registered value for each named key?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:55:27.143",
"Id": "434340",
"Score": "0",
"body": "@dfhwze I'm not sure I understand the question... the last registered service for each key is the one that was registered by a unit-test and this one should be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:56:21.393",
"Id": "434341",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96054/discussion-between-dfhwze-and-t3chb0t)."
}
] | [
{
"body": "<p>I'm not into that whole brevity thing, so I like longer variable names, even for lambda expressions. Plus I like method chaining over query comprehension syntax. I'm weird like that. So the big wiring up block gets a little bigger .. definitely not better, but I wanted to just show an alternative for funsies.</p>\n\n<pre><code>builder.Register(context => new CompositeProvider(context.ComponentRegistry.Registrations\n .SelectMany(\n registration => registration.Services.OfType<KeyedService>(),\n (registration, service) => (registration, service))\n .Where(registrationService => typeof(IResourceProvider).IsAssignableFrom(registrationService.service.ServiceType))\n .GroupBy(registrationService => registrationService.service.ServiceKey, registrationService => (registrationService.registration, registrationService.service))\n .Select(registrationService => (registrationService, Last: registrationService.Last()))\n .Select(registrationService => registrationService.Last.registration.Activator.ActivateInstance(context, Enumerable.Empty<Parameter>()) as IResourceProvider)));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T04:45:51.213",
"Id": "434394",
"Score": "2",
"body": "I think you lose readability when using long variable names in lambda expressions. Besides that, since we now have _ValueTuple_, I would also prefer that over an anonymous class, if used as a local intermediate class, again for readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:16:42.967",
"Id": "434471",
"Score": "1",
"body": "`ValueTuple` - excellent call!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:25:59.383",
"Id": "223972",
"ParentId": "223944",
"Score": "1"
}
},
{
"body": "<p>Your solution is sane, and it can easily be extended to a generic extension method. <code>Last()</code> is the best you can do. It would have been better if <code>context.ComponentRegistry.Registrations</code> somehow stored some registration meta info like <code>DateTime</code> of registration. There is a <em>meta</em> dictionary foreseen, but it is unclear what is stored inside.</p>\n\n<pre><code>public static class AutofacExtension\n{\n public static void RegisterComposite<T, TComposite>(\n this ContainerBuilder builder) where TComposite : class\n {\n if (builder == null) throw new ArgumentNullException(nameof(builder));\n\n builder.Register(context =>\n {\n var services =\n from r in context.ComponentRegistry.Registrations\n from s in r.Services.OfType<KeyedService>()\n where typeof(T).IsAssignableFrom(s.ServiceType)\n group (r, s) by s.ServiceKey into g\n let last = g.Last()\n select last.r.Activator.ActivateInstance(\n context, Enumerable.Empty<Parameter>());\n\n return Activator.CreateInstance(\n typeof(TComposite), services.Cast<IResourceProvider>());\n });\n }\n}\n</code></pre>\n\n<p>And registered..</p>\n\n<pre><code>builder.RegisterComposite<IResourceProvider, CompositeProvider>();\n</code></pre>\n\n<p>Instead of..</p>\n\n<blockquote>\n<pre><code>builder.Register(context =>\n{\n var services =\n from r in context.ComponentRegistry.Registrations\n from s in r.Services.OfType<KeyedService>()\n where typeof(IResourceProvider).IsAssignableFrom(s.ServiceType)\n group (r, s) by s.ServiceKey into g\n let last = g.Last()\n select last.r.Activator.ActivateInstance(context, Enumerable.Empty<Parameter>());\n\n return new CompositeProvider(services.Cast<IResourceProvider>());\n});\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:04:13.803",
"Id": "224003",
"ParentId": "223944",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224003",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:40:00.670",
"Id": "223944",
"Score": "4",
"Tags": [
"c#",
"dependency-injection",
"reflection",
"autofac"
],
"Title": "Registering Named services and resolving them by T"
} | 223944 |
<p>I've decided to code Perlin noise generator in Java. It works pretty well, I just want to know If I am doing everything right and if it is a valid implementation!</p>
<p>PS : The <code>metaVector2f</code> and <code>metaVector2i</code> are just 2D vector classes</p>
<pre><code>public float[][] generate(long seed, metaVector2i size, metaVector2i gridSize) {
Random rand = new Random(seed);
metaVector2f[][] gvectors = new metaVector2f[gridSize.x][gridSize.y];
for (int y = 0; y < gridSize.y; y++)
for (int x = 0; x < gridSize.x; x++)
gvectors[x][y] = new metaVector2f(rand.nextFloat(),rand.nextFloat());
float[][] data = new float[size.x][size.y];
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++) {
data[x][y] = perlinPoint(new metaVector2f(x/(float)(size.x/gridSize.x),y/(float)(size.y/gridSize.y)), gvectors);
}
return data;
}
private float perlinPoint(metaVector2f position, metaVector2f[][] gvectors) {
int x0 = (int)position.x;
int y0 = (int)position.y;
int x1 = (int)position.x+1;
int y1 = (int)position.y+1;
float dx0 = position.x-x0;
float dy0 = position.y-y0;
float dx1 = position.x-x1;
float dy1 = position.y-y1;
float h1 = dotProduct(new metaVector2f(dx0, dy0), gvectors[x0%gvectors.length][y0%gvectors[0].length]);
float h2 = dotProduct(new metaVector2f(dx1, dy0), gvectors[x1%gvectors.length][y0%gvectors[0].length]);
float fin1 = lerp(h1, h2, dx0);
float v1 = dotProduct(new metaVector2f(dx0, dy1), gvectors[x0%gvectors.length][y1%gvectors[0].length]);
float v2 = dotProduct(new metaVector2f(dx1, dy1), gvectors[x1%gvectors.length][y1%gvectors[0].length]);
float fin2 = lerp(v1, v2, dx0);
return lerp(fin1,fin2,dy0);
}
private float lerp(float x, float y, float t) {
return (1.0f - t)*x + t*y;
}
private float dotProduct(metaVector2f vec, metaVector2f grad) {
return vec.x*grad.x+vec.y*grad.y;
}
</code></pre>
<p>Here is the output (value/2+0.5f) :</p>
<p><img src="https://i.stack.imgur.com/rIoBx.png" alt="1"></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T23:12:18.073",
"Id": "436258",
"Score": "0",
"body": "That output doesn't look right. Generally the x/y coordinates within each square are passed through a smoothstep function, otherwise you get those artifacts around the edges of each square (can clearly see a 10x10 grid here, it shouldn't be that apparent). This article is good if you haven't seen it: http://flafla2.github.io/2014/08/09/perlinnoise.html"
}
] | [
{
"body": "<p>Consider warmwaffle's code at GitHub (re: <a href=\"https://github.com/warmwaffles/Noise\" rel=\"nofollow noreferrer\">https://github.com/warmwaffles/Noise</a>). The one difference I see between the two solutions is how the 'metaVector2f's are created. Your code is using non-repeatable random numbers; whereas, the other uses a mathematical calculation which includes prime numbers and bit shifting operations. The latter would produce a repeatable solution with the same seed versus yours. This may be worth something if you're testing or troubleshooting elsewhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T20:14:19.090",
"Id": "224837",
"ParentId": "223947",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:08:51.590",
"Id": "223947",
"Score": "2",
"Tags": [
"java",
"algorithm",
"random"
],
"Title": "Java Perlin noise implementation"
} | 223947 |
<p>I have written the below code to read a huge text file of size 20+ MB and insert the values to a PostgreSQL table. The code is working fine, but I'm facing below issues in the code.</p>
<p>1) The code is taking too long to complete (nearly 2 hour). Is there a way to make it faster?
2) I wrote a condition (<code>if field6!=field8</code>: in the code) to check and insert only those lines which are having a difference in values, but in the execution of the code similar values are also being executed.</p>
<p>3) Since I separate each value using space as a separator, the date "25.02.2019 17:17:08:" is split into two parts and at the last ":" is there, so I have to append those fields by converting them to TEXT fields. Is there any better option?
4) The code is not so perfect. Is there a way to generalise this without hardcoding the file name and assigning the fields manually? </p>
<pre><code>import psycopg2
import time
start_time = time.perf_counter()
try:
conn = psycopg2.connect(host="localhost", database="postgres", user="postgres",
password="postgres", port="5432")
print('DB connected')
except (Exception, psycopg2.Error) as error:
# Confirm unsuccessful connection and stop program execution.
print ("Error while fetching data from PostgreSQL", error)
print("Database connection unsuccessful.")
quit()
try:
filepath = filePath='''/Users/linu/Downloads/log'''
table='staging.stock_dump'
SQL="""DROP TABLE IF EXISTS """+ table + """;CREATE TABLE IF NOT EXISTS """+ table + """
(created_date TEXT, product_sku TEXT, previous_stock TEXT, current_stock TEXT );"""
cursor = conn.cursor()
cursor.execute(SQL)
conn.commit()
with open(filePath, 'r') as file:
for line in file:
if 'Stock:' in line:
fields=line.split(" ")
date_part1=fields[0]
date_part2=fields[1][:-1]
sku=fields[3]
prev_stock=fields[5]
current_stock=fields[7]
if prev_stock.strip()==current_stock.strip():
continue
else:
#print("insert into " + table+"(created_date, product_sku, previous_stock , current_stock)" + " select CAST('" + date_part1+ " "+ date_part2 + "' AS TEXT)" +", CAST('"+sku+"' AS TEXT),CAST('" + prev_stock +"' AS TEXT),CAST('" +current_stock + "' AS TEXT) ;")
cursor.execute("insert into " + table+"(created_date, product_sku, previous_stock , current_stock)" + " select CAST('" + date_part1+ " "+ date_part2 + "' AS TEXT)" +", CAST('"+sku+"' AS TEXT),CAST('" + prev_stock +"' AS TEXT),CAST('" +current_stock + "' AS TEXT);")
conn.commit()
cursor.close()
conn.close()
print("Data loaded to DWH from text file")
print("Data porting took %s seconds to finish---" % (time.perf_counter() - start_time))
except (Exception, psycopg2.Error) as error:
print ("Error while fetching data from PostgreSQL", error)
print("Error adding information.")
quit()
</code></pre>
<p>Sample part of the text file is given below,</p>
<pre><code>25.02.2019 18:17:08: Runcode: admin
25.02.2019 17:17:08: Initialising stockitem processor
25.02.2019 17:17:08: Running stockitem processor
25.02.2019 17:17:09: Reading bunch of 50 new stocks...
25.02.2019 17:17:09: Reading bunch of 50 products...
25.02.2019 17:17:09: stopping execution after 1 exceptions!
25.02.2019 18:30:01: Runcode: admin
25.02.2019 17:30:01: Initialising stockitem processor
25.02.2019 17:30:01: Running stockitem processor
25.02.2019 17:30:02: Reading bunch of 50 products...
25.02.2019 17:30:02: stopping execution after 1 exceptions!
25.02.2019 18:45:01: Runcode: admin
25.02.2019 19:30:01: Initialising stockitem processor
25.02.2019 19:30:01: Running stockitem processor
25.02.2019 19:30:02: Reading bunch of 50 products...
25.02.2019 19:30:02: stopping execution after 1 exceptions!
25.02.2019 20:45:01: Runcode: admin
25.02.2019 20:00:02: Initialising stockitem processor
25.02.2019 20:00:02: Running stockitem processor
25.02.2019 20:00:03: Reading bunch of 50 products...
25.02.2019 20:00:03: stopping execution after 1 exceptions!
25.02.2019 21:15:01: Runcode: admin
26.02.2019 10:30:09: Reading bunch of 50 products...
26.02.2019 10:30:09: stopping execution after 1 exceptions!
26.02.2019 11:45:01: Runcode: admin
26.02.2019 11:00:01: Initialising stockitem processor
26.02.2019 11:00:01: Running stockitem processor
26.02.2019 11:00:02: Reading bunch of 50 new stocks...
26.02.2019 11:00:03: Reading bunch of 50 new stocks...
26.02.2019 11:00:03: Reading bunch of 50 products...
26.02.2019 11:00:05: mapped 66 stocks from openerp to magento
26.02.2019 11:00:05: Stock: 3982 from 1 to 99
26.02.2019 11:00:05: Stock: 4758 from 8 to 6
26.02.2019 11:00:05: Stock: 1814 from 53 to 68
26.02.2019 11:00:05: Stock: 0437-bio from 111 to 114
26.02.2019 11:00:05: Stock: 2924-bio from 247 to 252
26.02.2019 11:00:05: Stock: 4806 from 262 to 263
26.02.2019 11:00:05: Stock: 3893 from 117 to 121
26.02.2019 11:00:05: Stock: 1486 from 0 to 0
26.02.2019 11:00:05: Stock: 4134 from 115 to 151
26.02.2019 11:00:05: Stock: 0129 from 24 to 30
26.02.2019 11:00:05: Stock: 1534-bio from 99 to 107
26.02.2019 11:00:05: Stock: 3032-bio from 187 to 211
26.02.2019 11:00:05: Stock: 1533-bio from 143 to 202
26.02.2019 11:00:05: Stock: 3596 from 67 to 91
26.02.2019 11:00:05: Stock: 3816-bio from 147 to 160
26.02.2019 11:00:05: Stock: 4776 from 0 to 0
26.02.2019 11:00:05: Stock: 2914 from 196 to 208
26.02.2019 11:00:05: Stock: 5449 from 24 to 25
26.02.2019 11:00:05: Stock: 4395 from 1191 to 1336
26.02.2019 11:00:05: Stock: 4752 from 7 to 7
26.02.2019 11:00:05: Stock: 4361 from 1375 to 1472
26.02.2019 11:00:05: Stock: 4794-bio from 265 to 332
26.02.2019 11:00:05: Stock: 0964-bio from 19 to 79
26.02.2019 11:00:05: Stock: 4791-bio from 356 to 417
26.02.2019 11:00:05: Stock: 4142-bio from 229 to 299
26.02.2019 11:00:05: Stock: 3814-bio from 61 to 69
26.02.2019 11:00:05: Stock: 1386-bio from 72 to 93
26.02.2019 11:00:05: Stock: 1692-bio from 0 to 176
26.02.2019 11:00:05: Stock: 1201 from 49 to 64
26.02.2019 11:00:05: Stock: 1385-bio from 288 to 321
26.02.2019 11:00:05: Stock: 1390-bio from 176 to 187
26.02.2019 11:00:05: Stock: 4737-bio from 120 to 127
26.02.2019 11:00:05: Stock: 0014 from 167 to 180
26.02.2019 11:00:05: Stock: 3621 from 23 to 27
26.02.2019 11:00:05: Stock: 4792-bio from 264 to 278
26.02.2019 11:00:05: Stock: 3900-bio from 98 to 116
26.02.2019 11:00:05: Stock: 0391 from 31 to 28
26.02.2019 11:00:05: Stock: 1804 from 0 to 0
26.02.2019 11:00:05: Stock: 4797-bio from 354 to 414
26.02.2019 11:00:05: Stock: 4024 from 1278 to 1427
26.02.2019 11:00:05: Stock: 4026 from 1076 to 1132
26.02.2019 11:00:05: Stock: 4447 from 163 to 230
26.02.2019 11:00:05: Stock: 3606 from 133 to 157
26.02.2019 11:00:05: Stock: 3926 from 380 to 490
26.02.2019 11:00:05: Stock: OIL-K25-001 from 0 to 0
26.02.2019 11:00:05: Stock: 3604 from 999 to 1068
26.02.2019 11:00:05: Stock: 4303-bio from 4 to 104
26.02.2019 11:00:05: Stock: 4456-bio from 11 to 195
26.02.2019 11:00:05: Stock: 4451 from 174 to 199
26.02.2019 11:00:05: Stock: 4476 from 68 to 92
26.02.2019 11:00:05: Stock: 4521 from 92 to 112
26.02.2019 11:00:05: Stock: 4477-bio from 187 to 193
26.02.2019 11:00:05: Stock: 4478-bio from 186 to 188
26.02.2019 11:00:05: Stock: 4421 from 356 to 770
26.02.2019 11:00:05: Stock: 3957 from 1781 to 2069
26.02.2019 11:00:05: Stock: 4358 from 725 to 783
26.02.2019 11:00:05: Stock: 3956 from 389 to 458
26.02.2019 11:00:05: Stock: 4598 from 915 to 1106
26.02.2019 11:00:05: Stock: 4597 from 1163 to 1438
26.02.2019 11:00:05: Stock: 3662 from 69 to 70
26.02.2019 11:00:05: Stock: 3989 from 0 to 12
26.02.2019 11:00:05: Catched 0 exceptions
26.02.2019 12:15:03: Runcode: admin
26.02.2019 11:15:03: Initialising stockitem processor
26.02.2019 11:15:03: Running stockitem processor
26.02.2019 11:15:04: No new stocks were found
26.02.2019 11:15:04: Catched 0 exceptions
26.02.2019 12:30:17: Runcode: admin
26.02.2019 11:30:17: Initialising stockitem processor
26.02.2019 11:30:17: Running stockitem processor
26.02.2019 11:30:18: No new stocks were found
26.02.2019 11:30:18: Catched 0 exceptions
26.02.2019 12:45:04: Runcode: admin
26.02.2019 11:45:04: Initialising stockitem processor
26.02.2019 11:45:05: Running stockitem processor
26.02.2019 11:45:06: No new stocks were found
26.02.2019 11:45:06: Catched 0 exceptions
26.02.2019 13:00:01: Runcode: admin
</code></pre>
| [] | [
{
"body": "<p>A couple of things jump out immediately:\nYou are only inserting data from lines with the string \"Stock:\" and this word occurs in exactly the same position in each line. Instead of asking for a search of the line you could check that a specific slice be checked. </p>\n\n<pre><code># setup outside read loop\nstock_str = \" Stock: \"\nstock_pos = 21\nstock_end = stock_pos + len(stock_str)\n</code></pre>\n\n<p>...</p>\n\n<pre><code># right after you read a line\n if line[stock_pos:stock_end] != stock_str:\n continue\n</code></pre>\n\n<p>(An aside: I prefer to use <code>continue</code> to short circuit loops rather than creating another indent level that I have to look down to find the end of. To me a <code>continue</code> says 'This path is uninteresting' and the interesting path is all at the same level.)</p>\n\n<p>Another option for you is to use the <code>csv_reader</code> in the <code>csv</code> module, which is part of the standard library. You can specify a field delimiter character as an option. In your case that is the blank. I don't think this will make your code faster, but as the reader returns a list of strings your code will be cleaner.</p>\n\n<p>There is no need to copy the fields from the array to named variables. Use <code>field[8]</code> where you are using <code>field8</code>. Actually those are terrible names which tell the reader of the code nothing about what you expect in the field. Better names would be something like <code>stock_to = 8</code>, <code>stock_from = 6</code> and you would then be inserting <code>field[stock_from]</code>, <code>field[stock_to]</code> which immediately tells the reader what value is expected at that position.</p>\n\n<p>You say you are writing to postgresql. In that case you should not be creating a new string to be passed to the database for each row. You should be using \"prepared statements\" where the variables are the only thing that changes with each insert call. The parsing of the statement is thus done only once, when <code>prepare()</code> is called. This will probably give you a good speed up.</p>\n\n<p>You don't say how often you expect to run this code. That influences how much time you should spend on speeding it up. If it is to be run every hout then it will be worthwhile to optimize it more. A once a week run, then the above changes are good enough and the expense of your time doing the optimization will not be recovered.</p>\n\n<p>If you do want to optimize more you should profile the code (see the standard library profile module doc). If that shows, as I suspect, that the insertion into the database is your slow step then you can set up threads, communicating with your read loop in the main thread through a synchronous queue or a message passing library like RabbitMQ. The database will then have lots of data queued up to go to disk as long as you are reading from the input file. Check execution times with timeit() to be sure your code is getting faster and have a \"standard\" input file to run against. Creating a threaded version of a database program is a lot of work but can give you significant speedup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:37:43.323",
"Id": "434429",
"Score": "0",
"body": "Thanks a lot for this brief explanation, I will try your suggestions and will update you, I have searched for this prepare statements but could not find any suitable post to guide me with an example, Since i'm new to python programming i'm learning information gradually from these blogs. I'm planning to execute this script 3 or 4 times a day. I have modified my script a little bit and now it is taking around 40-50 minutes to complete the execution, used the strip() method for comparing the strings and now only the differed values are taking for insertion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:39:25.217",
"Id": "434431",
"Score": "0",
"body": "If there is an example for the prepare() statement you can show to me, it will be of great help.Finally i need to insert it to the PostgreSQL database and if there is a way to reduce the execution time further more , then it will be really helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:41:25.517",
"Id": "434432",
"Score": "0",
"body": "Also this statement need to be called after the for loop right, But does it make any difference ? i tired it in the For loop but saw it was rather slow, So confused whether i have done anything wrong .Can you please guide? \n if line[stock_pos:stock_end] != stock_str:\n continue"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:48:18.267",
"Id": "434436",
"Score": "0",
"body": "Have you mentioned the prepare() like this ? \n PREPARE stock_plan (text, text, text, text) AS\n INSERT INTO staging.stock_dump VALUES($1, $2, $3, $4);\nEXECUTE stock_plan(date_part1+ date_part2 , sku, prev_stock, current_stock);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:42:27.833",
"Id": "434536",
"Score": "0",
"body": "Good, I see you found Postgreql's PREPARE. Yes, printing will slow your program down, especially if you are printing to a \"terminal\" on your screen. Output is much slower than moving stuff around in memory. To update the screen your system needs to move the printed data to the terminal process, the terminal process needs to format that data for the width of the terminal, and then the windowing software needs to turn the characters of the text into bitmaps that can be moved into the screen buffer for the next screen update cycle. This is actually a lot more work than the DB call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T13:56:48.513",
"Id": "435173",
"Score": "0",
"body": "This is getting into a different problem. Please ask it as a new question after checking existing questions to see if this error has already been covered and a solution posted. At least that way we can read your code without mental gymnastics :-)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T19:57:35.457",
"Id": "223968",
"ParentId": "223948",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223968",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:24:01.517",
"Id": "223948",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"postgresql"
],
"Title": "Port the data from a TEXT file to Postgres table using Python"
} | 223948 |
<p>Sometimes I use <code>std::unique_ptr<BaseClass></code> when all I really want is polymorphism. For fun, I made this container that skips the heap allocation. The downside is that it needs to know all possible derived types it will store in order to know how much space to reserve.</p>
<p>Any feedback is appreciated, but I'm especially interested in how this implementation enables/prevents compiler optimizations you would otherwise have with virtual types.</p>
<p>Edit: I am also intersted in supporting constexpr access, but right now the <code>reinterpret_cast</code> prevents constexpr dereference.</p>
<pre><code>#include <algorithm>
#include <type_traits>
template <typename B, size_t Size, size_t Align>
struct PolyUnionSize {
template <typename D>
explicit PolyUnionSize(D&& d) noexcept (std::is_nothrow_copy_constructible_v<D>) {
new(&storage) D(std::forward<D>(d));
}
template <typename D>
PolyUnionSize& operator=(D&& d) noexcept(std::is_nothrow_assignable_v<B, D>) {
this->~PolyUnionSize();
*(new(&storage) D) = std::forward<D>(d);
return *this;
}
~PolyUnionSize() noexcept {
(*this)->~B();
}
B const& operator*() const noexcept {
return *reinterpret_cast<B const*>(&storage);
}
B& operator*() noexcept {
return *reinterpret_cast<B*>(&storage);
}
B const* operator->() const noexcept {
return reinterpret_cast<B const*>(&storage);
}
B* operator->() noexcept {
return reinterpret_cast<B*>(&storage);
}
private:
typename std::aligned_storage<Size, Align>::type storage;
};
constexpr auto max(std::initializer_list<std::size_t> const& t) noexcept {
return *std::max_element(std::begin(t), std::end(t));
}
template <typename B, typename ... Ds>
struct PolyUnion : public PolyUnionSize<B, max({sizeof(Ds)... }), max({alignof(Ds)... })> {
using PUSize = PolyUnionSize<B, max({sizeof(Ds)... }), max({alignof(Ds)... })>;
template <typename D>
explicit PolyUnion(D&& d) noexcept(std::is_nothrow_copy_constructible_v<D>)
: PUSize(std::forward<D>(d))
{
static_assert((std::is_base_of_v<B, Ds> && ...));
AssertDinDs<D>();
}
template <typename D>
PolyUnion& operator=(D&& d) noexcept(std::is_nothrow_assignable_v<B, D>) {
AssertDinDs<D>();
PUSize::operator=(std::forward<D>(d));
return *this;
}
private:
template <typename D>
constexpr void AssertDinDs() const& noexcept{
static_assert((std::is_same_v<D, Ds> || ...));
}
};
</code></pre>
<p>Sample usage:</p>
<pre><code>struct Base {
virtual int Foo() const { return 1; }
};
struct A : Base {
int Foo() const final { return 2; }
};
struct B : Base {
int Foo() const final { return 3; }
};
int main() {
PolyUnion<Base, A, B> pu(A{});
pu = B{};
return pu->Foo();
}
</code></pre>
<p>Compiles with <code>-std=c++17</code> or <code>-std=c++2a</code></p>
| [] | [
{
"body": "<ol>\n<li><p>I suggest not codifying the derived types suggested in the type. Only note the ultimate base, size and alignment. Thus you are open to later change.</p>\n<p>Add a templated alias to get the proper type from base plus candidates.</p>\n</li>\n<li><p>Assure that no over-sized object is ever assigned in <code>PolyUnionSize</code>, probably best using SFINAE. No need to defer to the user.</p>\n</li>\n<li><p>Don't assume constructing the new object will never fail.</p>\n</li>\n<li><p><code>PolyUnionSize::PolyUnionSize<class D>(D&& d)</code> and <code>PolyUnionSize::operator=<class D>(D&& d)</code> use perfect forwarding. You don't account for that by using <code>std::decay_t</code> where needed, nor heed it when computing <code>noexcept</code>.</p>\n</li>\n<li><p>The implicit copy-/move- ctor / assignment are only appropriate for trivial types. And in that case, why override the dtor?</p>\n</li>\n<li><p>As casts should be used sparingly, consider delegating between <code>op*</code> and <code>op-></code>.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:21:19.710",
"Id": "434313",
"Score": "0",
"body": "Thanks for your response. I think I already do 1? 2 is a good idea. I thought for a while about 3, but I don't see how it's possible (isn't this the reason std::variant can be valueless by exception?). I don't know how to write 4 but it sounds like a good idea. For 5, I could add a move ctor, but I think the copy ctor is enough for now. And I write a dtor because the storage won't call the dtor automatically. re 6, fair point could refactor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:38:38.047",
"Id": "434322",
"Score": "0",
"body": "@sudorm-rfslash No, you have a base which does most of point 1. As the ultimate base must have a polymorphic dtor (check with [`std::has_virtual_destructor`](https://en.cppreference.com/w/cpp/types/has_virtual_destructor), you could make a short sortie into implementation-details, and take advantage of every known implementation putting a non-null virtual pointer first for an identifying marker. Simply disable the implicit functions. As an aside, consider swallowing the overhead and starting with a pointer to an array of helper-functions for a fuller experience and better conformance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:13:30.020",
"Id": "223956",
"ParentId": "223952",
"Score": "4"
}
},
{
"body": "<p>We're in C++17, so we can use <code>std::aligned_storage_t</code>:</p>\n\n<pre><code>typename std::aligned_storage_t<Size, Align> storage = {};\n</code></pre>\n\n<p>(I added the initializer to pacify <code>g++ -Weffc++</code>; I also added <code>virtual ~Base() = default;</code> for the same reason).</p>\n\n<p>One thing that breaks is that I can't assign a <code>B</code> to the object unless the base is explicitly listed as one of the <code>Ds...</code>. Perhaps that's intentional; it's certainly worth noting in the documentation if it is (I note that the posted code has <em>no</em> documentary comments - that really should be fixed).</p>\n\n<p>I get a long cascade of errors if I instantiate with only the base type and empty <code>Ds...</code>:</p>\n\n<pre><code>PolyUnion<Base> foo(Base{});\n</code></pre>\n\n<p>We can reduce that greatly by constraining with concepts, or just make this degenerate case be valid, by including the base type in the <code>max()</code> call:</p>\n\n<pre><code>template <typename B, typename ... Ds>\nstruct PolyUnion\n : public PolyUnionSize<B,\n max({sizeof(B), sizeof(Ds)... }),\n max({alignof(B), alignof(Ds)... })>\n{\n using PUSize = PolyUnionSize<B,\n max({sizeof(B), sizeof(Ds)... }),\n max({alignof(B), alignof(Ds)... })>;\n</code></pre>\n\n<p>I tried adding a <code>static_assert()</code> to force non-empty <code>Ds...</code>, but that didn't reduce the log spam very much, and I was unable to use <code>std::enable_if</code> to SFNIAE the template out for empty <code>Ds</code>. I did get a useful, short error message by specializing the template for that case, though:</p>\n\n<pre><code>template <typename B>\nclass PolyUnion<B>; // deliberately incomplete\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T21:27:05.950",
"Id": "434353",
"Score": "0",
"body": "I was not sure exactly what kind of Base classes I want to accept, so I did not make any design choices about that. My original goal was to get virtual function calls to work. However this implementation doesn't work with non virtual overloads (you'll always call the base class version -- not sure if there's any way around that without adding additional overhead). Therefore I ignore (but do not disallow) creating a Base object. You're right that this should be documented in a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:39:12.650",
"Id": "434414",
"Score": "0",
"body": "I think your definition of \"*doesn't work with non virtual overloads*\" is actually \"*works exactly the same as a reference or (raw/smart) pointer to the base class*\" - i.e. exactly what a programmer expects. I don't see a problem there. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:40:53.217",
"Id": "434415",
"Score": "1",
"body": "yes, but it's not the same as a union/variant. if you store pu = Derived then call pu->novirtualfunc, it's not very obvious from the call site that you're using the base class reference"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:54:33.667",
"Id": "223961",
"ParentId": "223952",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T13:43:54.737",
"Id": "223952",
"Score": "4",
"Tags": [
"c++",
"collections",
"c++17",
"polymorphism"
],
"Title": "A polymorphic union in C++"
} | 223952 |
<p>I did two simple functions in VBA (see below). </p>
<p>When a user calls <code>TirNoPer360</code> in Excel he must select cashflows and dates (as range), then he will get a rate (through iterations according to the second function <code>TirNoPer360</code>).</p>
<pre><code>Function Opt(Caja, Fecha As Range, tasa As Double)
Dim i As Integer
Dim sum As Double
Dim Initial As Date
Initial = Fecha(1, 1)
For i = 1 To Caja.Rows.Count
sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))
Next i
Opt = sum
End Function
</code></pre>
<p>======================</p>
<pre><code>Function TirNoPer360(Cash, Dates As Range, rate As Double)
Dim tolerance As Double
tolerance = 0.00001
For Iteration = 1 To 100
If Opt(Cash, Dates, rate) > 0 And Opt(Cash, Dates, rate) > tolerance Then
rate = rate + 0.0000001
ElseIf Opt(Cash, Dates, rate) < 0 And Opt(Cash, Dates, rate) < tolerance * -1 Then
rate = rate - 0.0000001
Else
rate = rate
End If
TirNoPer360 = rate
Next Iteration
End Function
</code></pre>
<p>When cashflows and dates increase I need more than 100 tries in order to get a good rate (approximated to four decimals) and time increases a lot. So, I would like to speed up my code.
I think I must improve the root finder algorithm, but I don't know how exactly I can do it.
Can anyone help me?</p>
<p>PD: I read Excel uses <a href="https://docs.microsoft.com/en-us/office/troubleshoot/excel/algorithm-of-xirr-funcation" rel="nofollow noreferrer">Newton's</a> algorithm to find the root for a function.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:27:35.863",
"Id": "434346",
"Score": "0",
"body": "What is a \"good rate\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:38:32.427",
"Id": "434349",
"Score": "0",
"body": "One quick comment for speed-up is that you're calling the `Opt` function four times with the exact same parameters when you should only call it once. Set up a variable `Dim sum As Double; sum = Opt(Cash, Dates, rate)`, then use that result in the `If` statement: `If sum > 0 And sum > tolerance Then...`. Additionally, we could help a bit more if you can supply a table of test data to run against so we know what to look for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:44:14.913",
"Id": "434537",
"Score": "0",
"body": "Just to point out that I improved optimization (root finder) through bisection method."
}
] | [
{
"body": "<p>I want to understand this because it seems like an interesting problem, but it's difficult because the parameters are in Spanish and I don't really understand the business domain.</p>\n\n<p>Some things to consider: are you sure there isn't a plugin somewhere that does this calculation? </p>\n\n<p>If not, avoid repeat calculations. Instead of calling Opt four times, store it once to a variable and use that instead. </p>\n\n<p>Also, try to think of a way you can store previous results in general. Do users keep calculating the same things over and over again? Could you store that in a table instead?</p>\n\n<p>Could you maybe attach a spreadsheet with sample data that does the calculation? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T16:25:32.077",
"Id": "223958",
"ParentId": "223954",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>Function TirNoPer360(Cash, Dates As Range, rate As Double)\n</code></pre>\n</blockquote>\n\n<p>The function is implicitly <code>Public</code>, implicitly returns a <code>Variant</code>, and implicitly receives all its parameters <code>ByRef</code>; <code>Cash</code> is implicitly a <code>Variant</code>, and the name isn't making it obvious that...</p>\n\n<blockquote>\n<pre><code>If Opt(Cash, Dates, rate)\n</code></pre>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n<pre><code>Function Opt(Caja, Fecha As Range, tasa As Double)\n '...\n For i = 1 To Caja.Rows.Count\n</code></pre>\n</blockquote>\n\n<p>...that <code>Cash</code> (and <code>Caja</code>) really needs to be a <code>Range</code> object, otherwise things can go all kinds of wrong.</p>\n\n<p>Make these things explicit, pass parameters <code>ByVal</code>, and keep the same identifiers when concepts are the same:</p>\n\n<pre><code>Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double) As Double\n</code></pre>\n\n\n\n<pre><code>Private Function Opt(ByVal Cash As Range, ByVal Dates As Range, ByVal rate As Double) As Double\n</code></pre>\n\n<p>Now it's much clearer that...</p>\n\n<ul>\n<li><code>TirNoPer360</code> is the public UDF, and <code>Opt</code> is a private implementation detail of it.</li>\n<li><code>Cash</code> in <code>TirNoPer360</code> is the same thing as what you had as <code>Caja</code> in <code>Opt</code>.</li>\n<li>The function(s) return a <code>Double</code></li>\n</ul>\n\n\n\n<p>This block needs immediate attention:</p>\n\n<pre><code>If Opt(Cash, Dates, rate) > 0 And Opt(Cash, Dates, rate) > tolerance Then\n rate = rate + 0.0000001\nElseIf Opt(Cash, Dates, rate) < 0 And Opt(Cash, Dates, rate) < tolerance * -1 Then\n rate = rate - 0.0000001 \nElse\n rate = rate\nEnd If\n</code></pre>\n\n<p>The entire <code>Else</code> block is no-op and should be removed. <code>rate</code> is already equal to <code>rate</code>, but the biggest inefficiency here is the fact that, in the worst case, <code>Opt</code> is invoked 4 times, and it's a very expensive function call. Pull it into a local variable (<a href=\"https://codereview.stackexchange.com/a/223958/23788\">as was already suggested</a>) and call it <em>once</em>:</p>\n\n<pre><code>Dim optResult As Double\noptResult = Opt(Cash, Dates, rate)\n</code></pre>\n\n<p>And now the conditionals become:</p>\n\n<pre><code>If optResult > 0 And optResult > tolerance Then\n rate = rate + 0.0000001\nElseIf optResult < 0 And optResult < tolerance * -1 Then\n rate = rate - 0.0000001 \nEnd If\n</code></pre>\n\n<p>The <code>tolerance</code> looks like it should be an optional parameter, with a default value of <code>0.00001</code>. You could amend the function's signature like this:</p>\n\n<pre><code>Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double, Optional ByVal tolerance As Double = 0.00001) As Double\n</code></pre>\n\n<p>Variable <code>Iteration</code> is not declared. I like that it's a fully spelled-out identifier and not just <code>i</code>, but given the variable has no use other than counting the number of iterations... so <code>i</code> wouldn't hurt at all. Just <em>declare it</em> - the fact that the code is allowed to run without this variable being declared indicates that <code>Option Explicit</code> is not specified at the top of the module, and that's a very dangerous thing, because any typo will merrily compile and run.. and produce the wrong results... and typos can be hard to spot. Spare yourself the trouble, and <em>always</em> put <code>Option Explicit</code> at the top of <em>every</em> module you ever write any code in.</p>\n\n<blockquote>\n <p><em>I need more than 100 tries in order to get a good rate</em></p>\n</blockquote>\n\n<p>Your function needs to define a concept of what a \"good rate\" is, and bail out (<code>Exit Function</code>, or <code>Exit For</code>) when it gets one. Currently, the function performs 100 iterations every time, regardless of whether the 2nd or 99th iteration yielded a \"good rate\".</p>\n\n<blockquote>\n<pre><code> TirNoPer360 = rate\nNext Iteration\n</code></pre>\n</blockquote>\n\n<p>You're re-assigning the function's return value at every iteration. That's a redundant step, just assign it once, after the loop:</p>\n\n<pre><code>Next Iteration\nTirNoPer360 = rate\n</code></pre>\n\n<p>Now, about that <code>Opt</code> function...</p>\n\n<blockquote>\n<pre><code>For i = 1 To Caja.Rows.Count\n sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))\nNext i\n</code></pre>\n</blockquote>\n\n<p><code>i</code> should be declared as a <code>Long</code>, not an <code>Integer</code>. I don't know how many rows this function is iterating, but <code>Caja</code> being a <code>Range</code> means it's absolutely possible that there are more than 32,767 (the maximum value an <code>Integer</code> can take).</p>\n\n<p>The function would be more efficient if you were iterating a single-dimensional <code>Variant</code> array rather than a <code>Range</code>.</p>\n\n<p>Consider declaring <code>Caja</code> and <code>Fecha</code> parameters <code>ByVal...As Variant</code>, and passing them from <code>TirNo360</code> like so:</p>\n\n<pre><code>Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double, Optional ByVal tolerance As Double = 0.00001) As Double\n\n Dim cashValues As Variant\n cashValues = Application.WorksheetFunction.Transpose(Cash.Value)\n\n Dim dateValues As Variant\n dateValues = Application.WorksheetFunction.Transpose(Dates.Value)\n\n Dim optResult As Double\n optResult = Opt(cashValues, dateValues, rate)\n</code></pre>\n\n<p>Now instead of this:</p>\n\n<blockquote>\n<pre><code>For i = 1 To Caja.Rows.Count\n sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))\nNext i\n</code></pre>\n</blockquote>\n\n<p>You'll have this (assuming the <code>Caja</code> parameter is now named <code>cashValues</code>):</p>\n\n<pre><code>Dim firstDate As Date\nfirstDate = dateValues(1)\n\nFor i = LBound(cashValues) To UBound(cashValues)\n sum = sum + cashValues(i) / ((1 + rate) ^ (Application.WorksheetFunction.Days360(firstDate, dateValues(i)) / 360))\nNext\n</code></pre>\n\n<p>Now the only thing left to address, is the function names: I've no idea what <code>TirNoPer360</code> actually stands for, and <code>Opt</code> is very cryptic. Give your functions meaningful names that ideally start with a verb, like, <code>FindOptimalRate</code> or something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:41:15.307",
"Id": "434535",
"Score": "0",
"body": "thank very much for the feedbacks. I really appreciated it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:58:08.483",
"Id": "223967",
"ParentId": "223954",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T14:32:56.853",
"Id": "223954",
"Score": "2",
"Tags": [
"vba",
"mathematics"
],
"Title": "VBA root finder algorithm"
} | 223954 |
<p>I have a PivotTable with a slicer that has 5 filters. I'm looking to have these filters to each be selected individually one by one and run a copy/paste code for every filter selected.</p>
<p>I've set up the code to work for each filter so far with completely rewriting/copying each code for each filter and everything works but it seems like a lot of unnecessary code</p>
<pre><code>Sub InsertData()
Dim wsCopy As Worksheet, wsDest As Worksheet
Dim DefCopyLastRow As Long, DefDestLastRow As Long
'Set variables for copy and destination sheets
Set wsCopy = Workbooks("Warranty Template.xlsm").Worksheets("PivotTable")
Set wsDest = Workbooks("QA Matrix Mar 2019 copy.xlsm").Worksheets("Plant Sheet")
'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row
'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row
'3. Copy & Paste Data For Each Filter Selection
'Backhoes
With ActiveWorkbook.SlicerCaches("Slicer_Model_Family_Description")
.SlicerItems("Backhoes Case Burlington").Selected = True
.SlicerItems("CE Tractor Loader Burlington").Selected = False
.SlicerItems("Corn Headers Burlington").Selected = False
.SlicerItems("Dozer Case Calhoun Burlington").Selected = False
.SlicerItems("Draper & Pickup Headers Burlington").Selected = False
.SlicerItems("Forklift Case Burlington").Selected = False
.SlicerItems("Grain Headers Burlington").Selected = False
If .SlicerItems("Backhoes Case Burlington").Selected Then
'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row
'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row
'3. Copy and Paste Data
wsCopy.Range("A5:A" & DefCopyLastRow).Copy
wsDest.Range("J" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("L" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("M" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("D5:D" & DefCopyLastRow).Copy
wsDest.Range("P" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("E5:E" & DefCopyLastRow).Copy
wsDest.Range("S" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
NewLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Row
wsDest.Range("AG" & DefDestLastRow & ":AG" & NewLastRow).Value = "Final Customer"
wsDest.Range("D" & DefDestLastRow & ":D" & NewLastRow).Value = "TLB"
End If
End With
'TLs
With ActiveWorkbook.SlicerCaches("Slicer_Model_Family_Description")
.SlicerItems("Backhoes Case Burlington").Selected = False
.SlicerItems("Backhoes Case Burlington").Selected = False
.SlicerItems("CE Tractor Loader Burlington").Selected = True
.SlicerItems("Corn Headers Burlington").Selected = False
.SlicerItems("Dozer Case Calhoun Burlington").Selected = False
.SlicerItems("Draper & Pickup Headers Burlington").Selected = False
.SlicerItems("Forklift Case Burlington").Selected = False
.SlicerItems("Grain Headers Burlington").Selected = False
If .SlicerItems("CE Tractor Loader Burlington").Selected Then
'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row
'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row
'3. Copy and Paste Data
wsCopy.Range("A5:A" & DefCopyLastRow).Copy
wsDest.Range("J" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("L" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("M" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("D5:D" & DefCopyLastRow).Copy
wsDest.Range("P" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("E5:E" & DefCopyLastRow).Copy
wsDest.Range("S" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
NewLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Row
wsDest.Range("AG" & DefDestLastRow & ":AG" & NewLastRow).Value = "Final Customer"
wsDest.Range("D" & DefDestLastRow & ":D" & NewLastRow).Value = "TL"
End If
End With
'Corn
With ActiveWorkbook.SlicerCaches("Slicer_Model_Family_Description")
.SlicerItems("CE Tractor Loader Burlington").Selected = False
.SlicerItems("CE Tractor Loader Burlington").Selected = False
.SlicerItems("Backhoes Case Burlington").Selected = False
.SlicerItems("Corn Headers Burlington").Selected = True
.SlicerItems("Dozer Case Calhoun Burlington").Selected = False
.SlicerItems("Draper & Pickup Headers Burlington").Selected = False
.SlicerItems("Forklift Case Burlington").Selected = False
.SlicerItems("Grain Headers Burlington").Selected = False
If .SlicerItems("Corn Headers Burlington").Selected Then
'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row
'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row
'3. Copy & Paste Data For Each Filter Selection
wsCopy.Range("A5:A" & DefCopyLastRow).Copy
wsDest.Range("J" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("L" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("B5:B" & DefCopyLastRow).Copy
wsDest.Range("M" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("D5:D" & DefCopyLastRow).Copy
wsDest.Range("P" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
wsCopy.Range("E5:E" & DefCopyLastRow).Copy
wsDest.Range("S" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues
NewLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Row
wsDest.Range("AG" & DefDestLastRow & ":AG" & NewLastRow).Value = "Final Customer"
wsDest.Range("D" & DefDestLastRow & ":D" & NewLastRow).Value = "Corn"
End If
End With
End Sub
</code></pre>
<p>The [COPY/PASTE CODE HERE] should be the same code for all slicers which is why I assume looping would be a more efficient way of setting this up</p>
| [] | [
{
"body": "<p>Repeating code within a subroutine is a sign that the procedure needs to be broken up into multiple subroutines. Ideally, a subroutine should perform only one or two tasks. Delegating tasks to other subroutines makes the project easier to read, modify and debug. </p>\n\n<p>Consider the code below. You can easily test the various slicer filters without having to run the whole code. You can also test the column assignments individually.</p>\n\n<pre><code>Sub InsertData()\n 'Backhoes\n FilterSlicer_Model_Family_Description False, True, False, False, False, False, False\n AppendAllColumnsToPlanetSheets\n FillAGandD \"TLB\"\n 'TLs\n FilterSlicer_Model_Family_Description True, False, False, False, False, False, False\n AppendAllColumnsToPlanetSheets\n FillAGandD \"TL\"\n 'Corn\n FilterSlicer_Model_Family_Description False, False, True, False, False, False, False\n AppendAllColumnsToPlanetSheets\n FillAGandD \"Corn\"\n\n\nEnd Sub\n\nSub AppendAllColumnsToPlanetSheets()\n AppendColumnDataToPlanetSheets \"A\", \"J\"\n AppendColumnDataToPlanetSheets \"B\", \"L\"\n AppendColumnDataToPlanetSheets \"B\", \"M\"\n AppendColumnDataToPlanetSheets \"D\", \"P\"\n AppendColumnDataToPlanetSheets \"S\", \"AG\"\nEnd Sub\n\nSub AppendColumnDataToPlanetSheets(SourceColumn As Variant, DestColumn As Variant)\n Dim Values As Variant\n With Workbooks(\"Warranty Template.xlsm\").Worksheets(\"PivotTable\")\n Values = .Range(.Cells(5, SourceColumn), .Cells(.Rows.Count, SourceColumn).End(xlUp)).Value\n End With\n\n With Workbooks(\"QA Matrix Mar 2019 copy.xlsm\").Worksheets(\"Plant Sheet\")\n With .Cells(.Rows.Count, DestColumn).End(xlUp).Offset(1)\n .Resize(UBound(Values)).Values = Values\n .EntireRow.Columns(\"AG\").Value = \"Final Customer\"\n .EntireRow.Columns(\"D\").Value = ColumnDValue\n End With\n End With\nEnd Sub\n\nSub FillAGandD(ColumnDValue As String)\n With Workbooks(\"QA Matrix Mar 2019 copy.xlsm\").Worksheets(\"Plant Sheet\")\n With .Cells(.Rows.Count, 1).End(xlUp).Offset(1)\n .Resize(UBound(Values)).Values = Values\n .EntireRow.Columns(\"AG\").Value = \"Final Customer\"\n .EntireRow.Columns(\"D\").Value = ColumnDValue\n End With\n End With\nEnd Sub\n\nSub FilterSlicer_Model_Family_Description(CETractorLoaderBurlington As Boolean, _\n BackhoesCaseBurlington As Boolean, _\n CornHeadersBurlington As Boolean, _\n DozerCaseCalhounBurlington As Boolean, _\n DraperPickupHeadersBurlington As Boolean, _\n ForkliftCaseBurlington As Boolean, _\n GrainHeadersBurlington As Boolean)\n\n With ActiveWorkbook.SlicerCaches(\"Slicer_Model_Family_Description\")\n .SlicerItems(\"CE Tractor Loader Burlington\").Selected = CETractorLoaderBurlington\n .SlicerItems(\"Backhoes Case Burlington\").Selected = BackhoesCaseBurlington\n .SlicerItems(\"Corn Headers Burlington\").Selected = CornHeadersBurlington\n .SlicerItems(\"Dozer Case Calhoun Burlington\").Selected = DozerCaseCalhounBurlington\n .SlicerItems(\"Draper & Pickup Headers Burlington\").Selected = DraperPickupHeadersBurlington\n .SlicerItems(\"Forklift Case Burlington\").Selected = ForkliftCaseBurlington\n .SlicerItems(\"Grain Headers Burlington\").Selected = GrainHeadersBurlington\n End With\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T11:24:58.070",
"Id": "434858",
"Score": "0",
"body": "how would I set this up to run with the push of one button?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T11:29:14.040",
"Id": "434859",
"Score": "0",
"body": "Inserdata runs the whole sequence."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:21:41.970",
"Id": "224102",
"ParentId": "223965",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T17:43:37.520",
"Id": "223965",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "loop code through each slicer value selection"
} | 223965 |
<p>I have created my own personal data structure libraries for C and I've re-engineered it about two times now and I've added alot of preprocessor checks and defines concerning OS type and compiler type.</p>
<p>One thing I've wanted to add to my personal libraries is having an informal <em>"standard"</em> fixed-size floating-point types.</p>
<pre><code>#ifndef __float32_t_defined
# if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
# define __float32_t_defined
typedef float float32_t TYPE_MODE(__SF__);
# elif FLT_MANT_DIG==24
# define __float32_t_defined
typedef float float32_t;
# elif DBL_MANT_DIG==24
# define __float32_t_defined
typedef double float32_t;
# endif
#endif
#ifndef __float64_t_defined
# if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
# define __float64_t_defined
typedef float float64_t TYPE_MODE(__DF__);
# elif FLT_MANT_DIG==53
# define __float64_t_defined
typedef float float64_t;
# elif DBL_MANT_DIG==53
# define __float64_t_defined
typedef double float64_t;
# elif LDBL_MANT_DIG==53
# define __float64_t_defined
typedef long double float64_t;
# endif
#endif
#ifndef __floatmax_t_defined
# if defined(COMPILER_CLANG) || defined(COMPILER_GCC)
# define __floatmax_t_defined
typedef double floatmax_t TYPE_MODE(__XF__);
# elif LDBL_MANT_DIG>=64
# define __floatmax_t_defined
typedef long double floatmax_t;
# elif DBL_MANT_DIG>=64
# define __floatmax_t_defined
typedef double floatmax_t;
# else
# define __floatmax_t_defined
typedef float floatmax_t;
# endif
#endif
</code></pre>
<p>For Clang and GCC, I use the compiler extension that checks machine mode and sets the type definition to the largest width of the floating point type. I added further type definition checks in the event Clang or GCC are not used.</p>
<p>my main question is that, given the macros in <code>float.h</code>, is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T02:00:46.967",
"Id": "436268",
"Score": "0",
"body": "It the goal to have a 32-bit `float32_t`, a 64-bit `float64_t` regardless of their internal proprieties?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T02:05:42.817",
"Id": "436269",
"Score": "0",
"body": "What is the goal of `floatmax_t`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T18:06:08.483",
"Id": "436566",
"Score": "1",
"body": "@chux No, the goal of `float32_t` and `float64_t` is that those types are always their fixed size. The goal of `floatmax_t` is to be the largest float width possible, which might either be the same as `float32_t`, or `float64_t`, or even higher than those two."
}
] | [
{
"body": "<p><strong><code>float32_t</code> <code>float64_t</code></strong></p>\n\n<p>Since the goal is: </p>\n\n<blockquote>\n <p><code>float32_t</code> and <code>float64_t</code> is that those types are always their fixed size</p>\n</blockquote>\n\n<p>the macros nearly achieve that.</p>\n\n<hr>\n\n<blockquote>\n <p>is checking float size by its mantissa a wise/safe thing to do? If not, what alternative can I take?</p>\n</blockquote>\n\n<p><strong>Big caveat</strong>: OP's expressed goal is <em>same size</em>, not same <em>encoding</em>. Two systems may have a 32-bit <code>float</code>, yet different mantissa, exponent range and other properties. The biggest \"safety\" concern is assuming same floating point properties with same <em>size</em>.</p>\n\n<p>C allows for a great diversity of implementations though. The macros accommodate most current compilers well, yet they are not specified to be always <code>typedef</code> 32/64 bit types.</p>\n\n<p>To be clear, checking <code>xxx_MANT_DIG, FLT_RADIX, xxx_MIN_EXP, ...</code> is <strong>not</strong> sufficient, in general, even though it may be practically sufficient.</p>\n\n<p>It fundamental comes down to:</p>\n\n<blockquote>\n <p>what should code do if it encounters a novel implementation? </p>\n</blockquote>\n\n<p>I'd go with testing for the <a href=\"https://www.youtube.com/watch?v=vtSmfws0_To\" rel=\"nofollow noreferrer\">usual suspects</a> and expand code when I encounter a true counter case.</p>\n\n<pre><code>#ifndef __float64_t_defined\n #if FLT_RADIX==2 && DBL_MANT_DIG==53 && DBL_MIN_EXP == -1021\n #define __float64_t_defined\n typedef double float64_t;\n #elif FLT_RADIX==2 && FLT_MANT_DIG==53 && FLT_MIN_EXP == -1021\n #define __float64_t_defined\n typedef float float64_t;\n // Expand list for variants that I have found \n #elif FLT_RADIX==2 && DBL_MANT_DIG==TBD && DBL_MIN_EXP == TBD\n #else\n #error TBD code for float64_t\n #endif\n#endif\n</code></pre>\n\n<p>Note: Code like <code>DBL_MANT_DIG==24</code> is not even C compliant with <code>FLT_RADIX==2</code>. <code>DBL_MANT_DIG >= 34</code> to meet precision requirements. This looks like a test for a non-real machine.</p>\n\n<hr>\n\n<p>I recommend 2 additions:</p>\n\n<p>Report fail to <code>typedef</code> right away with <code>#error</code></p>\n\n<pre><code># elif LDBL_MANT_DIG==53\n# define __float64_t_defined\n typedef long double float64_t;\n\n// Add\n# else\n# error TBD code for float64_t\n\n# endif\n</code></pre>\n\n<p>With C11 or later, use <code>_Static_assert</code></p>\n\n<pre><code>_Static_assert(sizeof (float64_t)*CHAR_BIT == 64, \"Unexpected `float64_t` size\");\n</code></pre>\n\n<p>With early compilers, see <a href=\"https://stackoverflow.com/a/3385694/2410359\">Static assert in C</a> and others.</p>\n\n<hr>\n\n<p><strong>floatmax_t</strong></p>\n\n<p>After taking advantage or known <code>COMPILER_CLANG, COMPILER_GCC</code> compilers, I'd recommend more conventional code - Simply test for <a href=\"https://stackoverflow.com/a/4991754/2410359\">C99 or later</a>.</p>\n\n<pre><code>#ifndef __floatmax_t_defined\n# if defined(COMPILER_CLANG) || defined(COMPILER_GCC)\n# define __floatmax_t_defined\n typedef double floatmax_t TYPE_MODE(__XF__);\n# elif (__STDC_VERSION__ >= 199901L)\n# define __floatmax_t_defined\n typedef long double floatmax_t;\n# else\n# define __floatmax_t_defined\n typedef double floatmax_t;\n# endif\n#endif\n</code></pre>\n\n<hr>\n\n<p>Similar question I posed</p>\n\n<p><a href=\"https://codereview.stackexchange.com/q/215113/29485\">Detecting unicorn and dinosaur compilers</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T17:24:40.760",
"Id": "225427",
"ParentId": "223966",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "225427",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T18:38:31.273",
"Id": "223966",
"Score": "3",
"Tags": [
"c",
"floating-point"
],
"Title": "Fixed-Size Floating-Point Types"
} | 223966 |
<p>The question is pretty self-explanatory. I wrote a regex pattern which should (in theory) match all possible integers and decimal numbers. The pattern is as follows:</p>
<pre><code>import re
pattern = '^[+-]?((\d+(\.\d*)?)|(\.\d+))$'
re.compile(pattern)
</code></pre>
<p>How foolproof is this pattern? I tested out quite a few scenarios, and they all worked fine. Am I missing some edge case here? Thanks for any help.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T23:25:00.120",
"Id": "434368",
"Score": "1",
"body": "Your expression matches numbers with digits before the decimal point but no digits after the decimal point, e.g. `33.`. Is this intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T04:59:20.513",
"Id": "434396",
"Score": "2",
"body": "You regex fails on exponential notation numbers, like `1e15` and `1e-15`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:27:45.507",
"Id": "434404",
"Score": "2",
"body": "A regex pattern without a clear spec or sufficient unit tests to see what should get matched and what not, is impossible to review."
}
] | [
{
"body": "<p>Your expression looks just fine, maybe we would slightly modify that to:</p>\n<pre><code>^[+-]?((\\d+(\\.\\d+)?)|(\\.\\d+))$\n</code></pre>\n<p>for failing these samples, <code>3.</code>, <code>4.</code>, for instance, just in case maybe such samples might be undesired. Other than that, you have some capturing groups that I'm guessing you'd like to keep those.</p>\n<hr />\n<h3>Test the capturing groups with <code>re.finditer</code></h3>\n<pre><code>import re\n\nregex = r"^[+-]?((\\d+(\\.\\d+)?)|(\\.\\d+))$"\n\ntest_str = ("0.00000\\n"\n "0.00\\n"\n "-200\\n"\n "+200\\n"\n "200\\n"\n "200.2\\n"\n "-200.2\\n"\n "+200.2\\n"\n ".000\\n"\n ".1\\n"\n ".2\\n"\n "3.\\n"\n ".")\n\nmatches = re.finditer(regex, test_str, re.MULTILINE)\n\nfor matchNum, match in enumerate(matches, start=1):\n \n print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))\n \n for groupNum in range(0, len(match.groups())):\n groupNum = groupNum + 1\n \n print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))\n</code></pre>\n<hr />\n<h3>Test with <code>re.findall</code></h3>\n<pre><code>import re\n\nregex = r"^[+-]?((\\d+(\\.\\d+)?)|(\\.\\d+))$"\n\ntest_str = ("0.00000\\n"\n "0.00\\n"\n "-200\\n"\n "+200\\n"\n "200\\n"\n "200.2\\n"\n "-200.2\\n"\n "+200.2\\n"\n ".000\\n"\n ".1\\n"\n ".2\\n"\n "3.\\n"\n ".")\n\nprint(re.findall(regex, test_str, re.MULTILINE))\n</code></pre>\n<p>The expression is explained on the top right panel of <a href=\"https://regex101.com/r/Ljm5oV/1/\" rel=\"nofollow noreferrer\">this demo</a>, if you wish to explore/simplify/modify it, and in <a href=\"https://regex101.com/r/Ljm5oV/1/debugger\" rel=\"nofollow noreferrer\">this link</a>, you can watch how it would match against some sample inputs step by step, if you like.</p>\n<hr />\n<h3>RegEx Circuit</h3>\n<p><a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n<p><a href=\"https://i.stack.imgur.com/LBHmf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LBHmf.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:05:53.557",
"Id": "434401",
"Score": "2",
"body": "`3` is an integer, `3.` is a float value. I would expect that latter string to match as well, so I would leave the `\\.\\d*` I modified."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T04:49:57.380",
"Id": "224002",
"ParentId": "223970",
"Score": "4"
}
},
{
"body": "<h2>Here's one:</h2>\n\n<pre><code>number_regex = re.compile(\n r'^[-+]?(?:(?:(?:[1-9](?:_?\\d)*|0+(_?0)*)|(?:0[bB](?:_?[01])+)'\n r'|(?:0[oO](?:_?[0-7])+)|(?:0[xX](?:_?[0-9a-fA-F])+))'\n r'|(?:(?:(?:\\d(?:_?\\d)*)?(?:\\.(?:\\d(?:_?\\d)*))|(?:\\d(?:_?\\d)*)\\.)'\n r'|(?:(?:(?:\\d(?:_?\\d)*)|(?:(?:\\d(?:_?\\d)*)?(?:\\.(?:\\d(?:_?\\d)*))'\n r'|(?:\\d(?:_?\\d)*)\\.))(?:[eE][-+]?(?:\\d(?:_?\\d)*)))))$',\n re.UNICODE)\n</code></pre>\n\n<h2>But seriously, Python numbers are complicated</h2>\n\n<p>If you really a regex that will match <strong>ALL</strong> valid forms of Python numbers, it will be a complex regex. Integers include decimal, binary, octal, and hexadecimal forms. Floating point numbers can be in exponent form. As of version 3.6 all kinds of numbers can have '_' in them, but it can't be first or last. And integers > 0 can't start with '0' unless it's 0b 0o or 0x</p>\n\n<p>From the Python documentation, here is the BNF for <code>integer</code>:</p>\n\n<pre><code>integer ::= decinteger | bininteger | octinteger | hexinteger\ndecinteger ::= nonzerodigit ([\"_\"] digit)* | \"0\"+ ([\"_\"] \"0\")*\nbininteger ::= \"0\" (\"b\" | \"B\") ([\"_\"] bindigit)+\noctinteger ::= \"0\" (\"o\" | \"O\") ([\"_\"] octdigit)+\nhexinteger ::= \"0\" (\"x\" | \"X\") ([\"_\"] hexdigit)+\nnonzerodigit ::= \"1\"...\"9\"\ndigit ::= \"0\"...\"9\"\nbindigit ::= \"0\" | \"1\"\noctdigit ::= \"0\"...\"7\"\nhexdigit ::= digit | \"a\"...\"f\" | \"A\"...\"F\"\n</code></pre>\n\n<p>and here is the BNF for <code>floatnumber</code>:</p>\n\n<pre><code>floatnumber ::= pointfloat | exponentfloat\npointfloat ::= [digitpart] fraction | digitpart \".\"\nexponentfloat ::= (digitpart | pointfloat) exponent\ndigitpart ::= digit ([\"_\"] digit)*\nfraction ::= \".\" digitpart\nexponent ::= (\"e\" | \"E\") [\"+\" | \"-\"] digitpart\n</code></pre>\n\n<p>Note that the '+' or '-' isn't technically part of the number; it is a unary operator. But it is easy enough to include an optional sign in the regex.</p>\n\n<p>To create the regex, simply translate the BNF into the corresponding regex patterns. Using non-grouping parenthesis (?: ) and f-strings helps a lot (rf\"...\" is a raw format string).</p>\n\n<p>Integer:</p>\n\n<pre><code>decint = r\"(?:[1-9](?:_?\\d)*|0+(_?0)*)\"\nbinint = r\"(?:0[bB](?:_?[01])+)\"\noctint = r\"(?:0[oO](?:_?[0-7])+)\"\nhexint = r\"(?:0[xX](?:_?[0-9a-fA-F])+)\"\ninteger = rf\"(?:{decint}|{binint}|{octint}|{hexint})\"\n</code></pre>\n\n<p>floatnumber:</p>\n\n<pre><code>digitpart = r\"(?:\\d(?:_?\\d)*)\"\nexponent = rf\"(?:[eE][-+]?{digitpart})\"\nfraction = rf\"(?:\\.{digitpart})\"\npointfloat = rf\"(?:{digitpart}?{fraction}|{digitpart}\\.)\"\nexponentfloat = rf\"(?:(?:{digitpart}|{pointfloat}){exponent})\"\nfloatnumber = rf\"(?:{pointfloat}|{exponentfloat})\"\n</code></pre>\n\n<p>and put it all together, with an optional sign, to get:</p>\n\n<pre><code>number = re.compile(rf\"^[-+]?(?:{integer}|{floatnumber})$\")\n</code></pre>\n\n<p>Which is how I got the regex at the top of this answer. This has not been thoroughly tested, just spot checked:</p>\n\n<pre><code>tests = \"\"\"\n 0\n 1\n 123\n 100_000\n 1_2_3\n 1000000\n 1.0\n 1.\n .2\n 0.2\n 3.4\n 1_234.567_89\n 0o123\n 0b1111_0000\n 0X12_34_ab_cd\n 1e-10\n 1E001\n .2e-2\n\"\"\"\ntests = tests.split()\n\nfor s in tests:\n m = number.match(s)\n print(f\"'{s}' => {m[0] if m else 'NOT a number'}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:53:10.090",
"Id": "224011",
"ParentId": "223970",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "224002",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:14:34.393",
"Id": "223970",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "A regex pattern that matches all forms of integers and decimal numbers in Python"
} | 223970 |
<p>I have written a function <code>buildGroupRequests()</code> to build an array of multiple groups.</p>
<p>It checks the size of the request group. If a request group is greater than <code>MAXSIZE = 50</code> then it will create another group in an array.</p>
<p>The logic seems to be complicated, is there a way to rewrite this to be more readable and maintainable in future?</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>console.log(
buildGroupRequests([
{ put: "/firstName=Danny" },
{ put: "/lastName=Williams" },
{ put: "/email=danny.w@domain.com" }
])
);
function buildGroupRequests(lists) {
const MAXSIZE = 50;
return lists.reduce((group, insert) => {
const LASTINDEX = group.length - 1;
if (!group.length) {
group.push({ put: "PUT " + insert.put });
return group;
}
const putGroup = group[LASTINDEX];
const tempPutSet = putGroup.put + " + " + insert.put;
if (tempPutSet.length > MAXSIZE) {
group.push({ put: "PUT " + insert.put });
return group;
}
group[LASTINDEX].put = tempPutSet;
return group;
}, []);
}</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Maintainability</h2>\n<p>Maintainability is a measure of how long it takes to modify some code.</p>\n<p>Some things that help improve maintainability.</p>\n<ul>\n<li><p>Use a consistent style throughout the code base. If the code is a group effort then that style must be established before the start of the project.</p>\n</li>\n<li><p>For naming adopt the language standardized or informal style (Informal for JS as it does not have a standard style). In JavaScript we use <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a> variable names, PascalCase for instantiate-able objects via the <code>new</code> operator.</p>\n<p>For constants <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">UPPERCASE_SNAKE</a> with the general rule that we uppercase read-only properties of objects. Though many will also use them for all constants. There is no real consensus regarding the naming of constants but it is not good to be inconsistent in the use of UPPERCASE_SNAKE.</p>\n<p>Arrays, lists, and array like objects should use the plural name to indicate that it is more than one entity.</p>\n<p>Be consistent in naming items. Do not call the same abstract different names in different locations. EG you called the list of requests <code>lists</code> and <code>group</code>. You called a request <code>insert</code> and <code>putGroup</code>. (see example)</p>\n</li>\n<li><p>Magic numbers and strings should be in one place so that they don't need to be hunted down to make changes. As they are separated from the code it pays to always comment these constants, include type, limits, and what they are used for. (see example)</p>\n<p>To ensure constants are not modified use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\"><code>object.freeze</code></a> to make them read only. This instills trust in the state of the constants so the coder modifying the code does not have to hunt down each usage of the value to ensure it has not been modified if there are problems.</p>\n</li>\n<li><p>Reduce the complexity by reducing operator and token counts. Eg <code>if (!foo.length) { a = b } else { b = a }</code> is better as <code>if (foo.length) { b = a } else { a = b }</code></p>\n<p>Reduce the number of return points and keep it DRY. Eg in two places you create a new group and return it. With a little rearranging of the logic the two can be one. (see example)</p>\n</li>\n</ul>\n<h2>Readability</h2>\n<p>This comes hand in hand with maintainability. Low readability also means low maintainability.</p>\n<h2>Example</h2>\n<p>not quite how I would have written it (I would use a <code>while</code> loop and have the param <code>requests</code> AKA <code>lists</code> as a safe to mutate copy). Also would have used default params for the constants. However the example is consistent with your original.</p>\n<p>I also prefer 4 space indent as I find it much more readable with my old eyes.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const grouping = Object.freeze({ // Request grouping constants for buildGroupRequests\n MAX_SIZE: 50, // Max length of string per group. Last item may be longer.\n DELIMITER: \" + \", // String used to separate groups. Len < MAX_SIZE\n PREFIX: \"PUT \", // String used to prefix groups. Len < MAX_SIZE\n});\n\nfunction buildGroupRequests(requests) {\n return requests.reduce((groupedReqs, request) => {\n if (groupedReqs.length) {\n const lastReq = groupedReqs[groupedReqs.length - 1];\n const putGroup = lastReq.put + grouping.DELIMITER + request.put;\n if (putGroup.length <= grouping.MAX_SIZE) {\n lastReq.put = putGroup;\n return groupedReqs;\n }\n }\n groupedReqs.push({put: grouping.PREFIX + request.put});\n return groupedReqs;\n }, []);\n}\n\n\n\nconsole.log(\n buildGroupRequests([\n { put: \"/firstName=Danny\" },\n { put: \"/lastName=Williams\" },\n { put: \"/email=danny.w@domain.com\" },\n { put: \"/address=1984 Some St, Very long named place. Woop Woop 6162\" }\n ])\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Update</h2>\n<p>As requested in comment. Using a while loop and more along the lines as I would write it to be consistent with internal standards. Please note this is not as maintainable if used in a general JS work environment.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const grouping = Object.freeze({ \n maxSize: 50, \n delimiter: \" + \",\n prefix: \"PUT \", \n requests(reqs, {maxSize: max, delimiter: del, prefix: pre} = grouping) {\n var prev = {put: pre + reqs.shift().put};\n const grouped = [prev];\n while (reqs.length) {\n const next = reqs.shift().put;\n const putGroup = prev.put + del + next;\n if (putGroup.length <= max) { prev.put = putGroup }\n else { grouped.push(prev = {put: pre + next}) }\n }\n return grouped;\n },\n});\n\n\nconst requests = [\n { put: \"/firstName=Danny\" },\n { put: \"/lastName=Williams\" },\n { put: \"/email=danny.w@domain.com\" },\n { put: \"/address=1984 Some St, Very long named place. Woop Woop 6162\" }\n];\n\nconsole.log( grouping.requests([...requests]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T20:51:03.217",
"Id": "434539",
"Score": "1",
"body": "I think you mean \"PascalCase\" rather than \"Pascal_Case\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T20:56:57.240",
"Id": "434541",
"Score": "0",
"body": "@MJ713 yes thank you for spotting it.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:32:00.833",
"Id": "434548",
"Score": "0",
"body": "Very nice answer, thank you. Could you provide an example how you would do it in while loop as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T22:14:55.147",
"Id": "434554",
"Score": "0",
"body": "@user11767153 I have added the while loop version under Update"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T22:51:09.033",
"Id": "434555",
"Score": "0",
"body": "@Blindman67 Thank you. I feel your first example is much cleaner and understandability."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T20:11:43.513",
"Id": "224057",
"ParentId": "223973",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:29:15.233",
"Id": "223973",
"Score": "5",
"Tags": [
"javascript",
"node.js"
],
"Title": "Build multiple groups in an array"
} | 223973 |
<p>I am working on a simple NodeJS express app that accepts an incoming payload from a few different systems. There is a single route that ships the data off to another method and waits for the promise.</p>
<p>I am trying to make the incoming endpoint more secure to at least define an expected schema of the post data.</p>
<p><code>Payload Example</code> - I require a topic that must be a string, and a data object which can really be anything as shown. The key/values are all dynamic in the <code>data</code> property so I can't define specifically what I want.</p>
<p>What is the best way to add some security to an incoming endpoint like this?</p>
<pre><code>{
"topic": "tool-ingest",
"data": {
"firstName": "Jim",
"lastName": "Bob",
"age": 28,
"department": "None",
"campus": "A2",
"state": "Florida"
}
}
</code></pre>
<p>-</p>
<pre><code>/**
*
* server.js
*
* Handles the routing of the application.
* We wait for data to be sent over to the defined
* endpoints and then get routed accordingly.
*
*/
// Defined variables
require("dotenv").config();
const asyncHandler = require("express-async-handler"),
producer = require("./producer"),
express = require("express"),
app = express(),
bodyParser = require("body-parser"),
port = process.env.PORT || 5000,
utilities = require("./utilities");
// Express Config
app.use(bodyParser.json());
// Receive our incoming payload
app.post(
"/payload",
asyncHandler(async (req, res, next) => {
let result = await producer.sendToProducer(req.body);
res.json(result);
})
);
// Begin Listening
app.listen(port, () => {
utilities.logError(`Server Listening...`);
});
/**
*
* producer.js
*
* After receiving a payload from ingest,
* send our data to the kafka producer
* which will contain the topic and message.
*
*/
// Defined variables
const kafka = require("kafka-node"),
HighLevelProducer = kafka.HighLevelProducer,
utilities = require("./utilities");
module.exports = {
sendToProducer: async function(payload) {
return new Promise((resolve, reject) => {
var client = new kafka.KafkaClient(),
producer = new HighLevelProducer(client);
let mappedData = utilities.mapFields(payload);
mappedData.message_uuid = uuidv1();
// Define our topic object
const topicObj = [
{
topic: payload.topic,
messages: JSON.stringify(mappedData)
}
];
// On producer ready
producer.on("ready", function() {
// Send our payload to our topic
producer.send(topicObj, function(err, data) {
if (err) {
utilities.logError("Producer Sent received error", {
error: error,
data: data
});
reject(err);
}
producer.close();
resolve(data);
});
});
// On producer error
producer.on("error", function(err) {
utilities.logError("Producer received error", err);
producer.close();
reject(err);
});
});
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:40:54.117",
"Id": "434475",
"Score": "0",
"body": "Hi, and welcome to the site. Unfortunately, this question isn't really a code review, but more of a request for help adding a new feature (security) - and that makes it off topic."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:40:30.347",
"Id": "223976",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"express.js",
"apache-kafka"
],
"Title": "Node Express App - Create structure around incoming payload"
} | 223976 |
<p>I am having a hard time to come up with a simple TCP client, that should use one socket and two threads (one for sending and one for receiving).</p>
<p>As using TPL tasks is the way asynchrony should be handled in C#, I am trying to use the <code>*Async</code> methods provided by the <code>SocketTaskExtensions</code> class. </p>
<p>This is what my class looks so far:</p>
<pre><code>public class TcpConnector
{
private readonly Socket socket;
public bool IsConnected => this.socket.Connected;
public TcpConnector()
{
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public async Task ConnectAsync(IPEndPoint endpoint)
{
await this.socket.ConnectAsync(endpoint);
}
public async Task<int> SendAsync(string message)
{
if (!this.IsConnected)
{
throw new SocketException((int) SocketError.NotConnected);
}
ArraySegment<byte> buffer = Encoding.UTF8.GetBytes(message);
return await this.socket.SendAsync(buffer, SocketFlags.None);
}
public async Task ReceiveAsync()
{
if (!this.IsConnected)
{
throw new SocketException((int) SocketError.NotConnected);
}
var segment = new ArraySegment<byte>(new byte[4]);
while (true)
{
var receiveTask = this.socket.ReceiveAsync(segment, SocketFlags.None);
receiveTask.Wait();
var message = Encoding.UTF8.GetString(segment.Array, 0, receiveTask.Result);
}
}
}
</code></pre>
<p>And this is one of my unit tests:</p>
<pre><code>[Fact]
[Trait("Category", "UnitTest")]
public async Task Should_Successfully_ReceiveAsync()
{
// Arrange
var client = new TcpConnector();
var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
// Act
await client.ConnectAsync(endpoint);
var receiveTask = client.ReceiveAsync();
await receiveTask;
// Assert
...
}
</code></pre>
<p><strong>Notes</strong></p>
<ol>
<li><p>I intentionally choose the buffer to be that small to test/learn about the behaviour if received data doesn't fit into the buffer. </p></li>
<li><p>The code works so far, in that it keeps receiving and that sending is possible from another thread.</p></li>
<li><p>When starting to receive, the client doesn't notice when the server shuts down, while waiting for data. </p></li>
</ol>
<p><strong>Questions</strong></p>
<ol>
<li><p>From what I understand is that a TCP socket provides a way of a bidirectional and asynchronous communication. Which means a client should be able to send and receive at the same time. Is that assumption correct?</p></li>
<li><p>How can I properly use ArraySegment here? Should the data to be send and received be hold in one (private) <code>ArraySegment<byte></code> buffer? What are the benefits of using this struct over a plain byte buffer?</p></li>
<li><p>Using a <code>while(true)</code> loop somehow feels wrong, although <code>ReceiveAsync</code> seems to block the thread and therefor no CPU cycles are getting wasted. What would be a more TPL-like approach to this?</p></li>
<li><p>Microsoft's documentation is mentioning <code>socket.Available</code>, which (according to the doc) should be used especially in conjunction with the <code>ReceiveAsync</code> method. But replacing the <code>while(true)</code> with <code>while(socket.Available != 0)</code> will prematuraly end my receiving thread, when no data is available. So how would one use that properly? </p></li>
<li><p>How should I handle socket errors? E.g. when the server side closes the connection or something else occurs while receiving? </p></li>
<li><p>How should I properly handle/implement timeouts? </p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T04:41:41.130",
"Id": "434393",
"Score": "2",
"body": "Your code so far is not really useful. Method _ReceiveAsync_ for instance, is only half-implemented. Could you complete the implementation of your methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:01:22.860",
"Id": "434399",
"Score": "2",
"body": "`ReceiveAsync` is unclear and impossible to review, because we can't see how you want to handle the result, and what to do after a single received operation is completed. You have to show a full implementation and a working use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T06:52:18.690",
"Id": "434410",
"Score": "1",
"body": "Thanks for replying and not voting down. I will invest more time and come up with a full implementation."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T20:55:14.667",
"Id": "223978",
"Score": "1",
"Tags": [
"c#",
"socket",
"task-parallel-library"
],
"Title": "Some questions about a simple asynchronous socket client"
} | 223978 |
<p>An alternative to <code>shared_ptr</code> to minimize compile time. Intrusive. Reference count changes are not thread safe.</p>
<p>(<code>#include<memory></code> pulls in 17k lines of code)</p>
<p>This satisfies my needs, but I'm curious how it could be improved (without adding any dependencies).</p>
<p>It's not particularly good at handling incomplete types (<code>ref<T>::get</code> cannot be used on an incomplete type). Is it possible to improve that?</p>
<pre><code>// Derive from this to be refcounted.
struct refcount {
int rc = 0;
virtual ~refcount() { }
};
void queued_delete(refcount*);
template<class T>
class ref {
public:
ref() { }
ref(T* obj) : obj(obj) {
if(obj) {
obj->rc++;
}
}
~ref() {
if(obj) {
if(--(obj->rc) == 0) {
queued_delete(obj);
}
}
}
ref(const ref& r) {
if(r.obj) {
obj = r.obj;
obj->rc++;
}
}
template<class T2>
ref(const ref<T2>& r) {
if(r.get()) {
obj = r.get();
obj->rc++;
}
}
ref& operator=(const ref& r) {
ref(r).swap(*this);
return *this;
}
template<class T2>
ref& operator=(const ref<T2>& r) {
ref(r).swap(*this);
return *this;
}
T* operator->() { return static_cast<T*>(obj); }
const T* operator->() const { return static_cast<const T*>(obj); }
T& operator*() { return *get(); }
T& operator*() const { return *get(); }
T* get() const { return static_cast<T*>(obj); }
unsigned long id() const { return (unsigned long) obj; }
void swap(ref& p) {
auto tmp = obj;
obj = p.obj;
p.obj = tmp;
}
explicit operator bool() const {
return obj;
}
bool operator==(const ref& other) const {
return obj == other.obj;
}
bool operator!=(const ref& other) const {
return obj != other.obj;
}
template<class T2>
ref<T2> cast() {
return ref<T2>(dynamic_cast<T2*>(obj));
}
private:
refcount *obj = nullptr;
};
</code></pre>
<p>Optional deletion which can handle deep nesting (can also do this with <code>shared_ptr</code> using a custom deleter):</p>
<pre><code>// Ensure deeply nested data structures can
// be deleted without running out of stack.
void queued_delete(refcount* p) {
static bool deleting = false;
static std::vector<refcount*> stack;
stack.push_back(p);
if(!deleting) {
deleting = true;
while(stack.size()) {
auto top = stack.back();
stack.pop_back();
delete top;
}
deleting = false;
}
}
</code></pre>
| [] | [
{
"body": "<p>You didn't post a complete header file (no include-guard/<code>#pragma once</code>), so it's unclear whether you also omitted a <code>namespace Taylor {</code> somewhere in there. But you should definitely use a namespace around a name as common as <code>ref</code>.</p>\n\n<hr>\n\n<pre><code> virtual ~refcount() { }\n</code></pre>\n\n<p>Nit: You could use <code>= default;</code> instead of <code>{ }</code> here, and you might get slightly better codegen on some compilers. (Virtual destructors are never actually \"trivial,\" unfortunately, but getting the compiler to write this quasi-trivial code for you can't hurt.)</p>\n\n<hr>\n\n<p>I notice that <code>refcount->rc</code> is <code>public</code>, not <code>private</code>. Was that a design decision?</p>\n\n<p>It occurs to me that the proper name for what you're calling <code>refcount</code> is actually <code>refcounted</code>. The <strong>refcount</strong>, physically, is the data member <code>rc</code>. A type which derives from your base class is a <strong>refcounted</strong> type.</p>\n\n<hr>\n\n<pre><code>ref(T* obj) : obj(obj) {\n if(obj) {\n obj->rc++;\n }\n}\n</code></pre>\n\n<p>I would write this as</p>\n\n<pre><code>explicit ref(T *obj) : obj_(obj) {\n if (obj_ != nullptr) {\n obj_->rc += 1;\n }\n}\n</code></pre>\n\n<p>Notice the whitespace edits, the use of some kind of sigil for data members (to avoid having two different variables named <code>obj</code> in scope), my preference for <code>+= 1</code> when the increment is a stand-alone statement, the explicit comparison against <code>nullptr</code> in place of contextual-conversion-to-<code>bool</code>, and the addition of <code>explicit</code>. Non-explicit constructors permit implicit conversions, e.g.</p>\n\n<pre><code>struct Widget : public refcount { int data = 42; };\n\nvoid print_data_of(ref<Widget> x) { std::cout << x->data << \"\\n\"; }\n\nint main() {\n Widget *p = new Widget;\n print_data_of(p);\n delete p; // OOPS! Double delete!\n}\n</code></pre>\n\n<p>It would be better (IMO of course) if this code did not compile.</p>\n\n<hr>\n\n<pre><code>template<class T2>\nref(const ref<T2>& r) {\n if(r.get()) {\n obj = r.get();\n obj->rc++;\n }\n}\n</code></pre>\n\n<p>This is extremely sketchy. Consider:</p>\n\n<pre><code>struct Widget : public refcount { int data = 42; };\nstruct Gadget : public refcount { int x = -1; int data = 42; };\nint main() {\n ref<Widget> w = new Widget; // OK...\n ref<Gadget> v = w; // ...sketchy...\n std::cout << v->data << \"\\n\"; // OOPS! Prints \"-1\", not \"42\"\n}\n</code></pre>\n\n<p>This constructor should be either completely removed, or else constrained (using <code>enable_if</code>, C++2a <code>requires</code>, or some other trickery) so that it participates in overload resolution only when <code>T2*</code> would be convertible to <code>T*</code>.</p>\n\n<p>One easy way to mostly-fix this would be to simply add an assertion:</p>\n\n<pre><code>template<class T2>\nref(const ref<T2>& r) {\n static_assert(std::is_convertible_v<T2*, T*>);\n if (r != nullptr) {\n obj_ = r.get();\n obj_->rc += 1;\n }\n}\n</code></pre>\n\n<p>Here we're lying to the library (e.g. <code>std::is_constructible_v<ref<Widget>, ref<Gadget>></code> will still be <code>true</code>), but at least we prevent the client programmer from accidentally writing a program like the test case above.</p>\n\n<hr>\n\n<p>Another way to fix the issue would be to rely on pointer-assignment to do the check for us. Instead of <code>refcount *obj_;</code>, let's make our data member look like <code>T *obj_;</code>. Then we can write</p>\n\n<pre><code>template<class T2>\nref(const ref<T2>& r) {\n if (r != nullptr) {\n obj_ = r.obj_; //HERE\n obj_->rc += 1;\n }\n}\n</code></pre>\n\n<p>And then if <code>T2*</code> <strong><em>isn't</em></strong> convertible to <code>T*</code>, we'll get an error on the line marked <code>//HERE</code>.</p>\n\n<p>Incidentally, this also solves your problem with <code>ref<T>::get()</code> and incomplete types.</p>\n\n<hr>\n\n<pre><code>T& operator*() { return *get(); }\nT& operator*() const { return *get(); }\n</code></pre>\n\n<p>You don't need both versions of the function, since they do exactly the same thing. Just write the <code>const</code> version. (Dereferencing a pointer doesn't need to modify the pointer, remember. <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">Const is a contract.</a>)</p>\n\n<pre><code>T* operator->() { return static_cast<T*>(obj); }\nconst T* operator->() const { return static_cast<const T*>(obj); }\n</code></pre>\n\n<p>And in this case you've got the two versions doing different things, but that's still wrong, because they <em>shouldn't</em> be doing different things! Dereferencing a pointer doesn't need to modify the pointer. What you meant in both cases was simply</p>\n\n<pre><code>T* get() const { return static_cast<T*>(obj); }\nT* operator->() const { return get(); }\nT& operator*() const { return *get(); }\n</code></pre>\n\n<hr>\n\n<p>Your <code>void swap(ref& p)</code> should be <code>noexcept</code> — just like your move-constructor, which I guess you didn't write. (You should do some move semantics here!)</p>\n\n<p>I recommend implementing your <code>swap</code> as a one-liner: <code>std::swap(obj_, rhs.obj_);</code>.</p>\n\n<p>A <strong><em>member</em></strong> <code>swap</code> function will not be picked up by any standard library algorithms. If you want your <code>swap</code> to be actually used, you'll need to provide an ADL <code>swap</code>, like this:</p>\n\n<pre><code>friend void swap(ref& a, ref& b) noexcept { a.swap(b); }\n</code></pre>\n\n<hr>\n\n<p>Your <code>queued_delete</code> is interesting. It's misnamed, in that its deletions are <strong>stacked</strong> (LIFO), not <strong>queued</strong> (FIFO). I don't know if that makes a difference to performance or anything like that, in practice.</p>\n\n<p>It's also thread-unsafe, which is not clear from your description/documentation. In standard C++, we can write</p>\n\n<pre><code>int main() {\n std::shared_ptr<Widget> p(new Widget);\n std::thread([q = p]() {\n q = nullptr;\n }).detach();\n p = nullptr;\n}\n</code></pre>\n\n<p>and be guaranteed that the writes to the refcount shared by <code>p</code> and <code>q</code> won't race with each other. Your documentation clearly states that we can't do that with your <code>ref<Widget></code>. But what is <strong><em>surprising</em></strong> to me is that we also can't do the following!</p>\n\n<pre><code>int main() {\n ref<Widget> p(new Widget);\n std::thread([]() {\n ref<Gadget> q(new Gadget);\n q = nullptr;\n }).detach();\n p = nullptr;\n}\n</code></pre>\n\n<p>Here, <code>p.obj->rc</code> and <code>q.obj->rc</code> are completely different objects, so there's no race there; but then they each call into <code>queued_delete</code> and try to write to <code>stack</code>, and <strong><em>those</em></strong> writes race with each other. So your <code>ref</code> is completely unsafe for use within a multi-threaded environment, even if you never share any objects between threads.</p>\n\n<p>In theory I guess you could \"fix\" this by replacing the storage class <code>static</code> with <code>thread_local</code> everywhere it appears; but, <a href=\"https://quuxplusone.github.io/blog/2018/11/14/fiber-local-storage/\" rel=\"nofollow noreferrer\">please don't do that.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T23:49:29.240",
"Id": "436259",
"Score": "0",
"body": "Thanks for the excellent review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T23:57:14.527",
"Id": "436260",
"Score": "0",
"body": "When I try to change `obj` to be a `T*`, I get errors because I can't `static_cast<refcount*>(obj)` when `T` is an incomplete type. `shared_ptr` doesn't have this issue because of the separately allocated control block. Not sure how to fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T00:10:54.013",
"Id": "436261",
"Score": "0",
"body": "\"Was that a design decision?\" actually, yes, because I'm thinking of having these refcounted objects also managed through a C API so I can use them from Swift. Perhaps a cleaner approach would be to have `retain` and `release` functions on `refcounted`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T00:33:11.377",
"Id": "436263",
"Score": "0",
"body": "Okay, true, if `obj` points to a `T` and `T` is incomplete, then the compiler won't know how to increment or decrement `obj->refcount` (because it won't know where the `refcount` member is located within the `T`). But my suggestion does *change* your pain point from \"I can't call `ref<T>::get()` when `T` is incomplete\" to \"I can't create, copy or destroy `ref<T>` when `T` is incomplete.\" I think that's at least a slightly better pain to have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T06:56:27.650",
"Id": "436287",
"Score": "0",
"body": "I managed to make it work with a `T*` by adding to `ref<T>` a pointer to a function which converts the `T*` to `refcounted*`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T22:49:22.490",
"Id": "224844",
"ParentId": "223981",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224844",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T23:36:58.457",
"Id": "223981",
"Score": "1",
"Tags": [
"c++",
"reinventing-the-wheel"
],
"Title": "shared_ptr alternative with no dependencies"
} | 223981 |
<p>For <a href="https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup" rel="nofollow noreferrer">this challenge on HackerRank</a>:</p>
<blockquote>
<p>A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.</p>
<p>Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.</p>
<p>For example, if Gary's path is s=[DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out and up into a mountain 2 units high. Finally, he returns to sea level and ends the hike.</p>
</blockquote>
<p>I reached a solution, but I'm sure it can be optimized:</p>
<pre><code>function countingValleys(n, s) {
let heightTracker = [];
let height = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "D") {
height--;
heightTracker.push(height);
}
if (s[i] === "U") {
height++;
heightTracker.push(height);
}
}
let planeTracker = [];
for (let j = 0; j < heightTracker.length; j++) {
if (heightTracker[j] < 0) {
planeTracker.push("valley");
}
if (heightTracker[j] > 0) {
planeTracker.push("mountain");
}
if (heightTracker[j] === 0) {
planeTracker.push("flat");
}
}
let newArray = [];
for (let k = 0; k < planeTracker.length; k++) {
if (planeTracker[k] === planeTracker[k - 1]) {
continue;
}
if (planeTracker[k] !== planeTracker[k - 1]) {
newArray.push(planeTracker[k]);
}
}
let valleyCount = 0;
for (let l = 0; l < newArray.length; l++) {
if (newArray[l] === "valley") {
valleyCount++;
}
}
return valleyCount;
}
</code></pre>
<p>My logic was to keep track of all negative and positive values in <code>s</code>.</p>
<ul>
<li>If <code>heightTracker[j]</code> is negative, push "valley" into <code>planeTracker</code></li>
<li>If <code>heightTracker[j]</code> is positive, push "mountain" into <code>planeTracker</code></li>
<li>Otherwise, push "flat" into <code>planeTracker</code></li>
</ul>
<p>So at that point, I'm left with:</p>
<p><code>[ 'valley', 'valley', 'valley', 'flat', 'valley', 'valley', 'valley', 'valley', 'valley', 'flat', 'mountain', 'flat' ]</code></p>
<p>And I'm wondering, is there a way to filter out any elements that are the same as the element before them? The goal was to generate the array:</p>
<p><code>[ 'valley', 'flat', 'valley', 'flat', 'mountain', 'flat']</code> and then count the number of times the word "valley" appears in that array. As you can see, I did this with a for-loop. But I'm wondering what other suggestions you'd have - maybe the <code>.filter()</code> method?</p>
| [] | [
{
"body": "<p>You're vastly overcomplicating the solution by introducing three arrays <code>heightTracker</code>, <code>planeTracker</code>, and <code>newArray</code>. None of those is needed: just track the <code>elevation</code> (which is a better name than <code>height</code>), and go by the definition:</p>\n\n<blockquote>\n <p>A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.</p>\n</blockquote>\n\n<p>So, the number of valleys traversed is the number of times Gary's elevation changes from -1 to 0.</p>\n\n<pre><code>function countingValleys(n, s) {\n let elevation = 0;\n let traversedValleys = 0;\n for (let i = 0; i < n; i++) {\n if (s[i] === \"D\") {\n --elevation;\n } else if (s[i] === \"U\") {\n if (++elevation === 0) traversedValleys++;\n }\n }\n return traversedValleys;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:40:25.630",
"Id": "434376",
"Score": "0",
"body": "Interesting, what is the difference between `--elevation` and `elevation--` or `++elevation` and `elevation++`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:44:54.497",
"Id": "434377",
"Score": "1",
"body": "See [Increment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_%28%29). `++elevation === 0` means to increment `elevation` _before_ comparing with 0."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:34:01.940",
"Id": "223987",
"ParentId": "223984",
"Score": "3"
}
},
{
"body": "<p>I found that instead of using the for-loop, I can use <code>filter()</code> like this:</p>\n\n<pre><code>planeTracker = planeTracker.filter((element, index, arr) => element !== arr[index + 1]);\n</code></pre>\n\n<p>To get rid of the elements that are the same as the previous element.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:47:23.453",
"Id": "434378",
"Score": "0",
"body": "You shouldn't need `planeTracker` in the first place. But this is also poor style, since it ventures one element past the end of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:00:08.850",
"Id": "434379",
"Score": "0",
"body": "What if I switched it to `arr[index - 1]` - still bad practice? Ventures one element before the start of the array, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:05:00.350",
"Id": "434387",
"Score": "0",
"body": "Accessing before the beginning of the array feels even ickier."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:34:13.013",
"Id": "223988",
"ParentId": "223984",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "223987",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T00:48:17.390",
"Id": "223984",
"Score": "3",
"Tags": [
"javascript",
"programming-challenge",
"array"
],
"Title": "Counting Valleys - HackerRank Challenge"
} | 223984 |
<p>I am writing a program to generate primes in range 1 upto 10^9 but it seems to be timing out. </p>
<p>It implements the <a href="https://en.wikipedia.org/wiki/Sieve_of_Atkin" rel="nofollow noreferrer">Sieve of Atkin</a></p>
<p>I have tried optimizing my code using bitsets and pragmas.</p>
<p>Please are there any other ways i can optimize my code. Code below </p>
<pre><code>#include<bitset>
#include<vector>
#include<iostream>
#include<algorithm>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
#define int long long
const int LIM = 1e9;
bitset<100000000> sieve;
void compute(int limit)
{
if (limit > 2)
cout<<"2 ";
if (limit > 3)
cout<<"3 ";
for (int x = 1; x * x < limit; x++) {
for (int y = 1; y * y < limit; y++) {
int n = (4 * x * x) + (y * y);
if (n <= limit && (n % 12 == 1 || n % 12 == 5))
sieve.flip(n);
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve.flip(n);
n = (3 * x * x) - (y * y);
if (x > y && n <= limit && n % 12 == 11)
sieve.flip(n);
}
}
for (int r = 5; r * r < limit; r++) {
if (sieve.test(r)) {
for (int i = r * r; i < limit; i += r * r)
sieve.reset(i);
}
}
for(int i=sieve._Find_first();i< sieve.size();i = sieve._Find_next(i))
{
if(i==0||i==1)continue;
cout<<i<<" ";
}
cout<<endl;
}
signed main()
{
compute(LIM);
return 0;
}
</code></pre>
<p>Thanks in advance. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:17:30.360",
"Id": "434380",
"Score": "0",
"body": "C++ code never times out unless you explicitly ask it to timeout. Are you saying that _it takes longer than allowed_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:40:34.397",
"Id": "434390",
"Score": "1",
"body": "You may want to comment your algorithm (or link to the description of the algorithm). Without context it would be hard to provide any advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T06:13:08.923",
"Id": "434408",
"Score": "0",
"body": "i don't have time for a full review. One tiny remark that may surprise you: using a bitset is often slow. That's not always true; a well optimised program built around a bitwise data structure is often faster than the similarly optimised one built around a less densely packed one. But if you are just looping over positions in a bitset and reading/writing them one at a time, you're liable to find it slows you down. At core, that's because it takes more work to address single bits, and you get a traffic jam effect when you're repeatedly reading and writing from the same addressable bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:32:53.210",
"Id": "434423",
"Score": "0",
"body": "Although not incorrect, `signed main()` is much less idiomatic than `int main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:31:13.730",
"Id": "434427",
"Score": "0",
"body": "@MartinYork I am using the sieve of atkin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:32:07.137",
"Id": "434428",
"Score": "0",
"body": "@AlexisWilke Yes I mean it takes a long time to execute"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:42:13.460",
"Id": "434558",
"Score": "0",
"body": "@Mr.Wilson, you may want to update your question and rephrase that part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T07:57:24.623",
"Id": "434588",
"Score": "0",
"body": "I'm suspecting this is [XY problem](http://xyproblem.info/). Are you sure you need all primes up to 10^9? This is unlikely. Maybe it would be better if you provide information about task you are solving. There are other ways to test if something is a prime number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T08:00:00.920",
"Id": "434590",
"Score": "0",
"body": "I've seen [other user](https://stackoverflow.com/q/57004265/1387438) posting exactly same code with same problem. So it is possible this code is not yours, do not trust that author that code."
}
] | [
{
"body": "<p>I'm not sure what your optimizations are doing(comments would be nice), but I did notice several inefficiencies:</p>\n\n<p>Never include a calculation in the limit test in a <code>for</code> loop. It get's re-calculated on every iteration. In this case set the limit to <code>sqrt(limit)</code>. the calculation is kind of expensive but it's done only once.</p>\n\n<p>The same goes for the iteration step, calculate it once before you enter the loop.</p>\n\n<p>In the tests, in the first set of loops, you use <code>3*x*x</code> twice and <code>y*y</code> 3 times. putting these in variables would be a lot cheaper.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:31:58.240",
"Id": "434422",
"Score": "0",
"body": "Any decent compiler should be able to hoist the `3*x*x` and `y*y` rather than generating code that calculates them multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:29:53.777",
"Id": "434426",
"Score": "0",
"body": "@tinstaafl can i just save the sqrt in a variable to reuse it later"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T09:43:18.600",
"Id": "434434",
"Score": "0",
"body": "Yes, sorry if I didn't make that clear. Put into a variable would mean it's calculated once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T08:09:45.270",
"Id": "434591",
"Score": "0",
"body": "@TobySpeight I find it an interesting question whether a developer should program taking into account the possible optimizations of a compiler, and to which extend."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:12:40.300",
"Id": "223994",
"ParentId": "223986",
"Score": "3"
}
},
{
"body": "<p>Here are a few things you could try...</p>\n\n<p>Including those mentioned by @tinstaafl</p>\n\n<p>I think that you can avoid a lot of the computations. I had a brief look at the Wikipedia page, it seems that you are otherwise properly following the algorithm.</p>\n\n<pre><code>#include<bitset>\n#include<vector>\n#include<iostream>\n#include<algorithm>\n#pragma GCC target (\"avx2\")\n#pragma GCC optimization (\"O3\")\n\n// this rarely helps--if anything it makes the code much bigger and you lose\n// on the Instruction Cache!\n//#pragma GCC optimization (\"unroll-loops\")\n\n// As a long time programmer, I never ever do that (I delete such statement when\n// I see them!) It's never safe it ignore namespaces.\nusing namespace std;\n\n// Never do that; redefine a basic type using a macro?! Big no no!\n// Also with any modern C/C++, you want to use typedef instead.\n#define int long long\n\nconst int LIM = 1e9;\nbitset<100000000> sieve;\nvoid compute(int limit) \n{ \n // to really be complete, you should verify the max. size\n // since you want to be able to access `limit` you must make sure\n // that this offset is also valid\n if(limit + 1 >= sieve.size())\n throw out_of_range(\"limit too large\");\n\n // Do you really need these optimizations? Do they buy you anything?\n // It looks like your loops below start at 1 anyway, so you should\n // decide on one or the other anyway!\n if (limit > 2) \n cout<<\"2 \";\n if (limit > 3) \n cout<<\"3 \";\n\n // as mentioned by @tinstaafl replace (x * x < limit) with (x < sqrt(limit))\n // but \"cache\" that limit like so:\n // also something to make a habit of is to use pre-increment, here it makes\n // no difference since all your variables are numbers, but when dealing with\n // iterators (for example) it's a different story!\n //for (int x = 1; x * x < limit; x++) { \n int const sqrt_limit(sqrt(limit));\n for (int x = 1; x < sqrt_limit; ++x) { \n\n // see note in inner loop\n x_square = x * x;\n\n // apply same here\n //for (int y = 1; y * y < limit; y++) { \n for (int y = 1; y < sqrt_limit; ++y) { \n\n // you calculate x * x and y * y multiple times\n // it often helps to have intermediate variables\n // (especially if you have intermediate calls which\n // could prevent the compiler from optimizing)\n // also X can be calculated outside the loop\n y_square = y * y;\n\n //int n = (4 * x * x) + (y * y); \n int n = 4 * x_square + y_square; \n\n if (n <= limit && (n % 12 == 1 || n % 12 == 5)) \n sieve.flip(n); \n\n // this one seems to be used twice, either it's wrong or\n // at least you can optimize by calculating it once only\n //n = (3 * x * x) + (y * y); \n n = 3 * x_square + y_square; \n\n {\n // if it is wrong and both are not the same, keep as you've done\n\n if (n <= limit && n % 12 == 7) \n sieve.flip(n);\n\n // so? same or needs fixing?\n n = (3 * x * x) - (y * y); // <- fix this...\n\n if (x > y && n <= limit && n % 12 == 11) \n sieve.flip(n);\n }\n // OR\n {\n // they are the same, then you can simplify on 'n'\n // this optimization is always available, it's up to you to\n // know which of the 3 equations give you the smallest number\n //\n // This is most certainly what you are looking for...\n if(n > limit)\n break;\n\n // remember that the % involves a division\n // and again the compile may or may not be able to optimize...\n // here I do it manually to be sure\n int const n_mod12 = n % 12;\n if (n_mod12 == 7)\n sieve.flip(n);\n\n if (x > y && n_mod12 == 11) \n sieve.flip(n);\n }\n } \n } \n\n // same sqrt() optimization\n //for (int r = 5; r * r < limit; ++r) { \n for (int r = 5; r < sqrl_limit; ++r) { \n\n if (sieve.test(r)) { \n\n // same optimization as above, pre-calculate square\n int r_square(r * r);\n //for (int i = r * r; i < limit; i += r * r) \n for (int i = r_square; i < limit; i += r_square) \n sieve.reset(i);\n } \n } \n\n // if you can eliminate an if() from inside your loops, do it\n //for(int i=sieve._Find_first();i< sieve.size();i = sieve._Find_next(i))\n for(int i = sieve._Find_next(1); i < sieve.size(); i = sieve._Find_next(i))\n\n {\n //if(i==0||i==1)continue; -- not necessary, we won't get 0 and 1\n cout<<i<<\" \";\n }\n cout<<endl;\n}\n\n// as mentioned by Toby Speight, you should use `int`, but of course...\n// since you did that `#define int long long` ...\nsigned main()\n{\n compute(LIM);\n return 0; \n}\n</code></pre>\n\n<p>The <strong>HUGE</strong> thing that C/C++ let you do but you should never ever do is:</p>\n\n<pre><code>#define int long long\n</code></pre>\n\n<p>That's going to get you fired from any sensible software company...</p>\n\n<p>The next one is these two lines I added:</p>\n\n<pre><code> if(n > limit)\n break;\n</code></pre>\n\n<p>That will probably be enough to get your algorithm to go fast. Right now you continue testing even when <code>n</code> is always going to be larger than <code>limit</code>.</p>\n\n<p>One final comment, it is really rare in C/C++ that you would use an inclusive limit. There is of course nothing against that, but it makes the entry test (which I added) look really weird for an old C/C++ programmer. I understand that the Wikipedia page used an inclusive limit and thus you decided to use that...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T04:43:24.213",
"Id": "224077",
"ParentId": "223986",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>#define int long long\n</code></pre>\n</blockquote>\n\n<p>Not only is redefining <code>int</code> a bad idea, but using <code>long long</code> should be reserved for legacy code. Use <code><cstdint></code> and (given the ranges used in this code) <code>std::uint_fast32_t</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (limit > 2) \n cout<<\"2 \";\n if (limit > 3) \n cout<<\"3 \";\n\n ... 21 lines ...\n for(int i=sieve._Find_first();i< sieve.size();i = sieve._Find_next(i))\n {\n if(i==0||i==1)continue;\n cout<<i<<\" \";\n }\n</code></pre>\n</blockquote>\n\n<p>Why not put the special cases (and the output in general) together at the end? And would it not be more transparent to do something like this?</p>\n\n<pre><code> // Special cases: numbers smaller than the first prime or used in the wheel.\n sieve.reset(0);\n sieve.reset(1);\n sieve.set(2);\n sieve.set(3);\n sieve.set(5);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> for (int x = 1; x * x < limit; x++) {\n for (int y = 1; y * y < limit; y++) {\n int n = (4 * x * x) + (y * y);\n if (n <= limit && (n % 12 == 1 || n % 12 == 5))\n sieve.flip(n);\n\n n = (3 * x * x) + (y * y);\n if (n <= limit && n % 12 == 7)\n sieve.flip(n);\n\n n = (3 * x * x) - (y * y);\n if (x > y && n <= limit && n % 12 == 11)\n sieve.flip(n);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This looks rather inefficient. The first step in speed optimisation is to split out the cases and for each one iterate only over the <code>(x,y)</code> pairs which yield the relevant residues. E.g. for <span class=\"math-container\">\\$4x^2 + y^2 \\in \\{1, 5\\} \\pmod{12}\\$</span> we have <span class=\"math-container\">\\$y \\in \\{1,5,7,11\\} \\pmod{12}\\$</span> with any <span class=\"math-container\">\\$x\\$</span>; or <span class=\"math-container\">\\$y \\equiv 3 \\pmod{6}\\$</span>, <span class=\"math-container\">\\$x \\not\\equiv 0 \\pmod{3}\\$</span>.</p>\n\n<p>Not only does this save a whole lot of <code>n % 12 == k</code> checks, but it allows you to break out of each loop independently when the quadratic form hits <code>limit</code>.</p>\n\n<p>Moreover, if you structure it carefully you can handle each residue with a separate <code>bitset</code>, which allows parallelisation.</p>\n\n<hr>\n\n<p>The second speed optimisation is to look at the binary quadratic forms (BQFs) used. If you split the residues modulo 60 instead of modulo 12 then I find that there's a theoretical improvement of about 6% by using <a href=\"https://codereview.stackexchange.com/q/168769/1402\">the following BQFs</a>:</p>\n\n<p><span class=\"math-container\">$$\\begin{array}{} n \\bmod 60 & \\textrm{BQF} \\\\\n1, 19, 31, 49 & 15x^2 + y^2 \\\\\n7, 43 & 3x^2 + y^2 \\\\\n11, 59 & 3x^2 - y^2 \\\\\n13, 29, 37, 41 & 4x^2 + y^2 \\\\\n17, 23, 47, 53 & 5x^2 + 3y^2 \\\\\n\\end{array}$$</span></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T10:15:19.677",
"Id": "434596",
"Score": "0",
"body": "Ha! Ha! I'm not sure that someone who write `#define int ...` is ready for parallelization... :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T12:31:11.467",
"Id": "434603",
"Score": "1",
"body": "@AlexisWilke, CR may be an edge case, but it's still part of the SE network, and answers can be valuable to people other than the OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:22:28.950",
"Id": "434954",
"Score": "0",
"body": "`#define int ...` is not only a bad idea, it is *undefined behavior*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T08:05:33.077",
"Id": "224081",
"ParentId": "223986",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T01:30:05.433",
"Id": "223986",
"Score": "1",
"Tags": [
"c++",
"performance",
"primes"
],
"Title": "Optimizing primes generating program in C++"
} | 223986 |
<p>Goal: Transfer Sheet <code>Test1</code> 2nd Column to Sheet <code>TestS</code> 2nd Column.</p>
<p><img src="https://i.stack.imgur.com/CvNY4.png" alt="Test1"></p>
<p><img src="https://i.stack.imgur.com/NKjQT.png" alt="TestS"></p>
<p>Where: </p>
<p>For each CPU in Test1. If CPU name in Sheet Test1 match CPU name in sheet TestS, copy 2nd column of that CPU in Test1 and paste in 2nd column of that CPU in TestS. </p>
<p>Else, create new row with the unfound CPU name and 2nd column after the last CPU of sheet <code>TestS</code>.</p>
<p>Final look in <code>TestS</code> looks like: </p>
<p><img src="https://i.stack.imgur.com/woSw4.png" alt="TestS"></p>
<p>This is my current working code where variables needs to be declared (string, integer etc):</p>
<pre><code> Sub automateCpu()
Dim noofComps As Long
noOfComps = Worksheets("Test1").Range("A1").CurrentRegion.Rows.Count-1
Dim x As Long
x = 0
Dim d As Integer
d = 0
Sheets("Test1").Select
Range("A1").Select
Do While x > noOfComps
Selection.Offset(1, 0).Select
Dim curComputer As String
curComputer = Selection.Value
Dim test1Row As Integer
d = d + 1
test1Row = ActiveCell.Row
Sheets("TestS").Select
Range("A1").Select
Dim y As Integer
y = 0
Dim z As Integer
z = 0
Dim LastRowSummary As integer
LastRowSummary = Worksheets("TestS").Range("A1").CurrentRegion.Rows.Count - 1
Do While y < LastRowSummary
Selection.Offset(1, 0).Select
If Selection.Value = curComputer Then
z = 1
Dim SummaryRow As Integer
SummaryRow = ActiveCell.Row
Sheets("Test1").Select
Range("B" & test1Row).Select
Dim curLogValue As Integer
curLogValue = Selection.Value
Sheets("TestS").Select
Range("B" & SummaryRow).Select
Selection.Value = curLogValue
Sheets("Test1").Select
Range("A" & test1Row).Select
Exit Do
End If
y = y + 1
Loop
If z = 0 Then
d = d + 1
Selection.Offset(1, 0).Select
Selection.Value = curComputer
SummaryRow = ActiveCell.Row
Sheets("Test1").Select
Range("B" & test1Row).Select
Dim curLogValue As Integer
curLogValue = Selection.Value
Sheets("TestS").Select
Range("B" & SummaryRow).Select
Selection.Value = curLogValue
Sheets("Test1").Select
Range("A" & test1Row).Select
End If
z = 0
d = d + 1
x = x + 1
Loop
End Sub
</code></pre>
<p>Pseudo Code:</p>
<p>1) Loop CPU in Test1</p>
<p>2) Find CPU in TestS by looping each computer</p>
<p>3) If CPU Matches for both Test1 & TestS paste 2nd Column</p>
<p>4) Else, create new row for new computer and 2nd column.</p>
<p>My question is how can I make this code more efficient?
Or any alternate method that can reduce the amount of codes etc.</p>
| [] | [
{
"body": "<p>Three initial points:</p>\n\n<ol>\n<li>Always use <code>Option Explicit</code> at the top of the module. Always!</li>\n<li>Properly indent your code to help with readability and exposure of some of the logic.</li>\n<li><a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba\">Avoid using <code>.Activate</code> and <code>.Select</code> in your code</a>. It is not necessary unless you want to bring something to the user's attention.</li>\n</ol>\n\n<p>You have <code>d</code>, <code>x</code>, <code>y</code>, <code>z</code> but no real understand what they mean. Particularly <code>d</code>, which is not used anywhere except to be incremented!</p>\n\n<p>Taking these points into account, you end up with:</p>\n\n<pre><code>Sub automateCpu()\nDim noofComps As Long\nDim test as Range\nDim testS as Range\nDim test1 as Range\n set test1 = Worksheets(\"Test1\").Range(\"A1\")\n noOfComps = testRange.CurrentRegion.Rows.Count-1\nDim x As Long\n x = 0\nDim d As Integer\n d = 0\n Do While x > noOfComps\n Set test1 = test1.Offset(1,0)\n Dim curComputer As String\n curComputer = testRange.Value\n Dim test1Row As Integer\n d = d + 1\n test1Row = test1.Row\n Dim testS as Range \n Set testS = Sheets(\"TestS\").Range(\"A1\") ' Why \"Sheets\" instead of \"Worksheets\" as in the other case? Consistency!\n Dim y As Integer\n y = 0\n Dim z As Integer\n z = 0\n Dim LastRowSummary As integer\n LastRowSummary = testS.CurrentRegion.Rows.Count - 1\n Do While y < LastRowSummary\n Set testS = testSRange.Offset(1, 0)\n If testS.Value = curComputer Then\n z = 1\n Dim SummaryRow As Integer\n SummaryRow = testS.Row\n Set test1 = Sheets(\"Test1\").Range(\"B\" & test1Row)\n Dim curLogValue As Integer\n curLogValue = test1.Value\n\n Set testS = Sheets(\"TestS\").Range(\"B\" & SummaryRow)\n testS.Value = curLogValue\n\n Set test1 = Sheets(\"Test1\").Range(\"A\" & test1Row)\n Exit Do\n End If\n y = y + 1\n Loop\n\n If z = 0 Then\n d = d + 1\n set test1 = test1.Offset(1, 0)\n test1.Value = curComputer\n SummaryRow = test1.Row\n\n\n set test1 = Sheets(\"Test1\").Range(\"B\" & test1Row)\n Dim curLogValue As Integer\n curLogValue = test1.Value\n\n Set testS = Sheets(\"TestS\").Range(\"B\" & SummaryRow)\n testS.Value = curLogValue\n\n Set test1 = Sheets(\"Test1\").Range(\"A\" & test1Row)\n End If\n z = 0\n d = d + 1\n x = x + 1\n Loop\n End Sub\n</code></pre>\n\n<p>But, looking at the code, you can see that there is a lot of shuffling of data into temporary variables. We can also clean this up with direct assignments.</p>\n\n<pre><code>Sub automateCpu()\nDim noofComps As Long\nDim test as Range\nDim testSA as Range\nDim test1A as Range\nDim testSB as Range\nDim test1B as Range\n set test1A = Worksheets(\"Test1\").Range(\"A1\")\n noOfComps = testRange.CurrentRegion.Rows.Count-1\nDim x As Long\n x = 0\n Do While x > noOfComps\n Set test1A = test1A.Offset(1,0)\n Dim curComputer As String\n curComputer = testRange.Value\n Dim test1Row As Integer\n test1Row = test1A.Row\n Set testSA = Sheets(\"TestS\").Range(\"A1\") ' Why \"Sheets\" instead of \"Worksheets\" as in the other case? Consistency!\n Dim y As Integer\n y = 0\n Dim z As Integer\n z = 0\n Dim LastRowSummary As integer\n LastRowSummary = testS.CurrentRegion.Rows.Count - 1\n Do While y < LastRowSummary\n Set testSA = testSRange.Offset(1, 0)\n If testSA.Value = curComputer Then\n z = 1\n Dim SummaryRow As Integer\n SummaryRow = testSA.Row\n Set test1B = Sheets(\"Test1\").Range(\"B\" & test1Row)\n Set testSB = Sheets(\"TestS\").Range(\"B\" & SummaryRow)\n testSB.Value = test1B.Value\n\n Set test1A = Sheets(\"Test1\").Range(\"A\" & test1Row)\n Exit Do\n End If\n y = y + 1\n Loop\n\n If z = 0 Then\n set test1A = test1A.Offset(1, 0)\n test1.Value = curComputer\n SummaryRow = test1A.Row\n\n set test1B = Sheets(\"Test1\").Range(\"B\" & test1Row)\n Set testSB = Sheets(\"TestS\").Range(\"B\" & SummaryRow)\n testSB.Value = test1B.Value\n\n Set test1A = Sheets(\"Test1\").Range(\"A\" & test1Row)\n End If\n z = 0\n x = x + 1\n Loop\nEnd Sub\n</code></pre>\n\n<p>Probably still some tidying up to do - but this gives the idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:24:35.160",
"Id": "434446",
"Score": "0",
"body": "That's some funky indenting on the `Dim x As Long` and `x = 0` lines, but I kinda like it! Of course, `x=0` immediately after the `Dim` is redundant in VBA since VBA initializes variables and doesn't leave them `Null` as `C` (among others) would."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T04:03:46.217",
"Id": "434577",
"Score": "0",
"body": "@FreeMan: - yes, leaving the implicit assignment (x=0) is fine and I did consider taking that approach, but personally, I like to be explicit wherever possible because it reduces the avenues for bugs in complex code. Plus, the OP is learning so being explicit in the first instance is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T04:05:09.790",
"Id": "434578",
"Score": "0",
"body": "@FreeMan: In addition, the implicit assignment works outside the loop, but inside the loop it may have a different effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T13:35:43.963",
"Id": "434868",
"Score": "0",
"body": "Both valid points. \"Write what you mean. Mean what you write.\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T06:58:47.320",
"Id": "224008",
"ParentId": "223991",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T00:58:03.970",
"Id": "223991",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "Matching and Merging CPU info between worksheets"
} | 223991 |
<p>Just looking for some feedback/ways to improve this basic networking layer written in Swift. I'm still learning, please elaborate with as much detail as possible.</p>
<pre><code>enum HTTPMethod: String {
case get = "GET"
}
class HTTPLayer {
let baseURL = URL(string: "https://example.com")!
func request(at endpoint: Endpoint, completion: @escaping (Data?, Error?) -> Void) {
let url = baseURL.appendingPathComponent(endpoint.path)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
completion(data, error)
}
task.resume()
}
}
enum Endpoint {
case listTransactions
case transactionDetails(String)
var method: HTTPMethod {
return .get
}
var path: String {
switch self {
case .listTransactions:
return "/api/transactions/"
case .transactionDetails(let id):
return "/api/transactions/id"
}
}
}
struct Transaction: Decodable {
let id: String
let amount: Double
}
struct TransactionDetails: Decodable {
let payload: [String: String]
}
enum Result<T> {
case success(T)
case failure(NSError)
}
class APIClient {
let httpLayer: HTTPLayer
init(httpLayer: HTTPLayer) {
self.httpLayer = httpLayer
}
func transactions(completion: @escaping (Result<[Transaction]>) -> Void) {
self.httpLayer.request(at: .listTransactions) { (data, error) in
if error != nil {
completion(.failure(error! as NSError))
} else {
do {
let transactions = try JSONDecoder().decode([Transaction].self, from: data!)
completion(.success(transactions))
} catch {
completion(.failure(self.defaultError))
}
}
}
}
func transactionDetails(for transaction: Transaction, completion: @escaping (Result<TransactionDetails>) -> Void) {
self.httpLayer.request(at: .transactionDetails(transaction.id)) { (data, error) in
if error != nil {
completion(.failure(error! as NSError))
} else {
do {
let transactions = try JSONDecoder().decode(TransactionDetails.self, from: data!)
completion(.success(transactions))
} catch {
completion(.failure(self.defaultError))
}
}
}
}
var defaultError: NSError = NSError(domain: "", code: 1, userInfo: nil)
}
</code></pre>
| [] | [
{
"body": "<p>There are few things that can be improved, will start with the major ones:</p>\n\n<p><strong>General</strong></p>\n\n<ul>\n<li>Instead of having function for each API call you can generalise it a bit like so:</li>\n</ul>\n\n<pre><code>/* Updated the name, since it's not only for transactions anymore\nSince we no longer know the exact endpoint we will have to pass it to the function\n\nI would also add `requestMeta` parameter that will contain any other information that would be needed to perform the api call\n`parameters`, `encoding`, `authenticationType`, `additionalHeaders`, `shouldReauthenticate`\nbut this is in case you need them\n*/\n\nfunc apiReques<T: Codable>(_ dataType: T.Type,\n endpoint: Endpoint,\n completion: @escaping (Result<[T], ResultError>) -> Void) {\n\n self.httpLayer.request(at: endpoint) { (data, error) in\n\n// In general an \"early return\" strategy is preferred, use guard when applicable and avoid nesting `if` statements\n if let error = error as NSError? {\n completion(.failure(error))\n return\n }\n\n// Do not force unwrap, it's better to show empty screen (or error) instead of crashing the app\n guard let data = data else {\n completion(.failure(NSError(domain: \"\", code: 1, userInfo: [:])))\n return\n }\n\n do {\n let transactions = try JSONDecoder().decode([T].self, from: data)\n completion(.success(transactions))\n } catch {\n completion(.failure(self.defaultError))\n }\n }\n }\n</code></pre>\n\n<p>So, since your structures are <code>Decodable</code> (consider using <code>Codable</code>) you can easily use generics.</p>\n\n<p>The <code>_ dataType: T.Type</code> is a bit tricky. Since we are not returning <code>T</code> we have to add it as a parameter so the compiler can infer the actual type (more on the topic can be found <a href=\"https://stackoverflow.com/questions/27965439/cannot-explicitly-specialize-a-generic-function\">here</a></p>\n\n<ul>\n<li>I would prefer keeping all the urls in one place, so I would move <code>baseURL</code> to endpoints enum. Again do not force unwrap</li>\n</ul>\n\n<pre><code>enum Endpoint {\n\n static let baseURLString = \"https://example.com\"\n\n case listTransactions\n case transactionDetails(String)\n}\n\nextension Endpoint {\n\n var method: HTTPMethod {\n return .get\n }\n\n var path: String {\n switch self {\n case .listTransactions:\n return Endpoint.baseURLString + \"/api/transactions/\"\n case .transactionDetails(let id):\n return Endpoint.baseURLString + \"/api/transactions/\\(id)\"\n }\n }\n}\n</code></pre>\n\n<p>This will affect your <code>request</code> func:</p>\n\n<pre><code>func request(at endpoint: Endpoint, completion: @escaping (Data?, Error?) -> Void) {\n\n guard let url = URL(string: endpoint.path) else { return }\n// endpoint.method is available as well if needed\n\n let task = URLSession.shared.dataTask(with: url) { (data, response, error) in\n completion(data, error)\n }\n task.resume()\n }\n</code></pre>\n\n<ul>\n<li>It seems that you are instantiating new <code>HTTPLayer</code> for every <code>APIClient</code>. In that case I would just go with <code>private let httpLayer: HTTPLayer = HTTPLayer()</code> and deleting the <code>init</code>. In that case you can mark <code>class HTTPLayer</code> as <code>fileprivate</code> so noone beside <code>APIClient</code> can access it and if any params needs to be passed to it will go through <code>APIClient</code> -> <code>apiReques()</code></li>\n</ul>\n\n<p><strong>Error handling</strong></p>\n\n<ul>\n<li>If you want to go a bit further you can update the <code>enum Result</code></li>\n</ul>\n\n<pre><code>enum Result<Value, Error: Swift.Error> {\n case success(Value)\n case failure(Error)\n}\n</code></pre>\n\n<p>and also adding your custom errors:</p>\n\n<pre><code>enum ResultError: Error {\n case general(String?)\n case specific(Int?)\n case `default` // default is a keyword so if you want to use it, you should wrap it in ``, imo don't and choose another name\n case whateverYouWant\n}\n\nextension ResultError {\n var errorString: String {\n switch self {\n...\n }\n }\n\n private func specificErrorString(_ errorCode: Int) -> String {\n switch errorCode {\n...\n }\n }\n}\n</code></pre>\n\n<p>This will affect the generic <code>apiRequest</code> a bit in the signature <code>@escaping (Result<[T], ResultError>) -> Void)</code> and ofc the <code>completions</code></p>\n\n<pre><code>completion(.failure(.general(\"something went wrong\")))\ncompletion(.failure(.specific(123))\ncompletion(.failure(.default)\n</code></pre>\n\n<p>Now you can delete <code>var defaultError: NSError = NSError(domain: \"\", code: 1, userInfo: nil)</code></p>\n\n<p><strong>How to use it</strong></p>\n\n<pre><code>APIClient(). apiReques(Transaction.self,endpoint: Endpoint.listTransactions) { data in\n\n switch data {\n case .success(let response):\n print(\"Success\")\n case .failure(let error):\n print(\"error\")\n }\n}\n</code></pre>\n\n<p><strong>Bonus</strong></p>\n\n<p>You can also split the completion into two completion <code>success</code> and <code>failure</code></p>\n\n<ul>\n<li>Signature</li>\n</ul>\n\n<pre><code>func apiReques <T: Decodable>(_ dataType: T.Type,\n endpoint: Endpoint,\n success: @escaping (([T]) -> Void),\n failure: @escaping ((ResultError) -> Void))\n</code></pre>\n\n<ul>\n<li>block calls</li>\n</ul>\n\n<pre><code>failure(.general(\"\"))\nfailure(.default)\nsuccess(data)\n</code></pre>\n\n<ul>\n<li>Usage</li>\n</ul>\n\n<pre><code>APIClient().transactions(Transaction.self,\n endpoint: Endpoint.listTransactions,\n success: { data in\n print(data)\n}, failure: { error in\n print(error)\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:39:40.463",
"Id": "225657",
"ParentId": "223995",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:13:52.603",
"Id": "223995",
"Score": "4",
"Tags": [
"beginner",
"json",
"swift",
"http"
],
"Title": "Basic network layer for a JSON API client"
} | 223995 |
<p>I wrote my first module in Verilog. The purpose is to maintain two counters and emit signals corresponding to VGA's HSync and VSync, as well as HBlank and VBlank pulses to be used by a video controller for the blanking intervals. The only input is a clock signal of 25.175 MHz. All timing information was acquired from <a href="http://tinyvga.com/vga-timing/640x480@60Hz" rel="nofollow noreferrer">here</a>.</p>
<pre><code>module sync (clk, hblank, hsync, vblank, vsync) ;
input clk;
output reg hblank = 0, hsync = 1, vblank = 0, vsync = 1;
reg [9:0] hcnt = 0, vcnt = 0;
always @(posedge clk) begin
case (hcnt)
640: hblank <= 1;
656: hsync <= 0;
752: hsync <= 1;
800: begin
hblank <= 0;
hcnt <= 0;
vcnt <= vcnt + 1;
end
endcase
case (vcnt)
480: vblank <= 1;
490: vsync <= 0;
492: vsync <= 1;
525: begin
vblank <= 0;
vcnt <= 0;
end
endcase
hcnt <= hcnt + 1;
end
endmodule
</code></pre>
| [] | [
{
"body": "<p>If you had ran simulation or loaded onto FPGA, you would noticed you didn't get the expected behavior. Run simulation and look at waveforms before loading to FPGA.</p>\n\n<p>You have <code>hcnt <= hcnt + 1;</code> at the bottom of your always block, this will override <code>hcnt <= 0;</code> which is not what you want. <code><=</code> is a non-blocking assignment which means it will be evaluated immediately but the value will not be updated until the end of the timestep. Order matters.</p>\n\n<p>The simplest solution is to move <code>hcnt <= hcnt + 1;</code> above the case statement.</p>\n\n<p>Be aware that your <code>hcnt</code> are counting from 0 to 800 which is 801 clocks. You may want to consider subtracting 1 from each case condition or initiating/resetting <code>hcnt</code> (and <code>vcnt</code>) as 1 instead of 0.</p>\n\n<p>Your <code>vcnt</code> will only be 525 for one clock, which don't look intentional. Consider moving it inside the <code>case(hcnt)</code>'s condition 800.</p>\n\n<p>I will recommend adding a reset input. And also recommend using an ANSI header Non-ANSI is required for Verilog-95 and pre IEEE1364. Since Verilog-2001, ANSI style is preferred mostly because it reduces the amount of typing.</p>\n\n<p>Below is my suggestion. Note I haven't tested that all functional requirements are met (that should be done in your testbench).</p>\n\n<pre><code>module sync (\n input clk, rst_n, // <-- ANSI header\n output reg hblank, hsync, vblank, vsync\n);\n reg [9:0] hcnt, vcnt;\n\n always @(posedge clk) begin\n if (!rst_n) begin // <-- synchronous reset logic\n hblank <= 1'b0;\n hsync <= 1'b1;\n vblank <= 1'b0;\n vsync <= 1'b1;\n hcnt <= 10'h001; // <-- init as 1 so case index doesn't need to change\n vcnt <= 10'h001; // <-- same as vcnt\n end\n else begin\n hcnt <= hcnt + 10'h001; // <-- default assignment, will be updated after the clock\n case (hcnt) // <-- uses the sampled value, not the result of the above line\n 10'd640: hblank <= 1'b1;\n 10'd656: hsync <= 1'b0;\n 10'd752: hsync <= 1'b1;\n 10'd800: begin\n hblank <= 1'b0;\n hcnt <= 10'h001; // <-- reset as 1, last assignment wins\n vcnt <= vcnt + 10'h001;\n case (vcnt)\n 10'd480: vblank <= 1'b1;\n 10'd490: vsync <= 1'b0;\n 10'd492: vsync <= 1'b1;\n 10'd525: begin\n vblank <= 1'b0;\n vcnt <= 10'h001; // <-- reset as 1, last assignment wins\n end\n endcase\n end\n endcase\n end\n end\nendmodule\n</code></pre>\n\n<p>You may want to consider using the 2-alway block coding style. It does require more lines of code small designs (usually reduces lines of code for large/complex desings). The main benefit is you can access to the present state and next state of a flop.</p>\n\n<pre><code>// sequential logic (uses non-blocking assignment and is synchronous)\nalways @(posedge clk) begin\n if (!rst_n) begin\n hblank <= 1'b0;\n hsync <= 1'b1;\n vblank <= 1'b0;\n vsync <= 1'b1;\n hcnt <= 10'h001;\n vcnt <= 10'h001;\n end\n else begin\n hblank <= next_hblank;\n hsync <= next_hsync;\n vblank <= next_vblank;\n vsync <= next_vsync;\n hcnt <= next_hcnt;\n vcnt <= next_vcnt;\n end\nend\n\n// combinational logic (uses blocking assignment and is asynchronous)\nalways @* begin\n next_hblank = hblank; // <-- default keep previous\n next_hsync = hsync;\n next_vblank = vblank;\n next_vsync = vsync;\n next_hcnt = hcnt + 10'h001; // <-- default increment\n next_vcnt = vcnt;\n\n // calc next values, update as needed\n case (hcnt)\n 10'd640: next_hblank = 1'b1;\n 10'd656: next_hsync = 1'b0;\n 10'd752: next_hsync = 1'b1;\n 10'd800: begin\n next_hblank = 1'b0;\n next_hcnt = 10'h001;\n next_vcnt = vcnt + 10'h001;\n case (vcnt)\n 10'd480: next_vblank = 1'b1;\n 10'd490: next_vsync = 1'b0;\n 10'd492: next_vsync = 1'b1;\n 10'd525: begin\n next_vblank = 1'b0;\n next_vcnt = 10'h001;\n end\n endcase\n end\n endcase\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:19:55.797",
"Id": "224770",
"ParentId": "223996",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T03:14:30.770",
"Id": "223996",
"Score": "6",
"Tags": [
"device-driver",
"verilog",
"fpga",
"hdl"
],
"Title": "VGA sync generator for 640x480@60Hz"
} | 223996 |
<p>I am good at logic and most of the time I write working code. But I want to learn writing code which follows best practices and is very efficient. I tried to implement some of them in my code but it still looks very unclean.
Could anyone please explain how I can make this code better and make it production standard code.</p>
<p>This is my ruby code: </p>
<pre><code>class Items
@@items = {}
def initialize(name, price)
@@items[name] = price
end
def self.all
@@items
end
end
class SaleItems
@@sale_items = {}
def initialize(name, units, price)
@@sale_items[name] = { 'units' => units, 'price' => price}
end
def self.all
@@sale_items
end
end
class PriceCalculator
def start_billing
input = get_input
@purchased_items = input.split(',').map(&:strip)
if !@purchased_items.empty?
quantity = count_items
price = calculate_bill(quantity)
billing_items = quantity.each_with_object(price) { |(k,v), billing_items|
billing_items[k] = {'units' => v, 'price' => price[k]}
}
display_bill(billing_items, quantity)
else
puts "Sorry! no items were given to process the bill"
end
end
private
def get_input
puts "Please enter all the items purchased separated by a comma"
input = gets.chomp
end
def count_items
@purchased_items.inject(Hash.new(0)){ |quantity, item|
quantity[item] += 1
quantity
}
end
def calculate_bill quantity
price = {}
quantity.each { |item,value|
if SaleItems.all[item].nil?
price[item] = quantity[item]*Items.all[item]
else
price[item] = (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])
end
}
price
end
def display_bill billing_items, quantity
total_price = billing_items.inject(0){ |tot, (item,v)|
tot + v['price']
}
actual_price = quantity.inject(0){ |tot, (item,units)|
tot + (units * Items.all[item])
}
puts "Item Quantity Price"
puts "------------------------------------------"
billing_items.each{ |item, v|
puts "#{item.ljust(20)} #{v['units']} $#{v['price']}"
}
puts "Total price : #{total_price.round(3)}"
puts "You saved #{(actual_price - total_price).round(3)} today."
end
end
begin
# creating inventory of items
Items.new('milk', 3.97)
Items.new('bread', 2.17)
Items.new('banana', 0.99)
Items.new('apple', 0.89)
# creating sale items
SaleItems.new('milk',2,5.00)
SaleItems.new('bread',3,6.00)
pc = PriceCalculator.new
puts pc.start_billing
end
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<h2>Rubocop Report</h2>\n\n<p>There is a nice topic on <a href=\"https://mixandgo.com/learn/how-to-avoid-the-ruby-class-variable-problem\" rel=\"nofollow noreferrer\">Class vs Instance variables</a> online. Are you sure you would like to use class variables in classes <code>Items</code> and <code>SalesItems</code>?</p>\n\n<blockquote>\n<pre><code>class Items\n @@items = {}\n ..\n</code></pre>\n</blockquote>\n\n<pre><code>class Items\n @items = {}\n ..\n</code></pre>\n\n<p>Class <code>PriceCalculator</code> has a couple of issues that need to be addressed.</p>\n\n<blockquote>\n<pre><code>billing_items = quantity.each_with_object(price) { |(k,v), billing_items|\n</code></pre>\n</blockquote>\n\n<p><code>billing_items</code> inside the <code>each_with_object</code> hides the member from the outer scope. To avoid confusion which variable is accessed, consider changing the name of the variable inside the inner call.</p>\n\n<blockquote>\n<pre><code>def get_input\n</code></pre>\n</blockquote>\n\n<p>Ruby guidelines don't like these java-style accessors. However, since the method isn't actually an accessor, it is acceptable (<a href=\"https://stackoverflow.com/questions/26097084/why-does-rubocop-or-the-ruby-style-guide-prefer-not-to-use-get-or-set\">Clarification</a>).</p>\n\n<blockquote>\n<pre><code>price[item] = (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])\n</code></pre>\n</blockquote>\n\n<p>Try to keep the length of your lines below 80 characters. Ruby is meant to read vertically. </p>\n\n<p>Other:</p>\n\n<ul>\n<li>Method <code>start_billing</code> might have many lines. Consider splitting up methods if they take more than 10 lines. Ruby likes short methods.</li>\n<li>The <a href=\"https://codeclimate.com/blog/deciphering-ruby-code-metrics/\" rel=\"nofollow noreferrer\">complexity</a> of method <code>calculate_bill</code> is too high. Consider splitting up its content into multiple methods, each doing their specific part. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T09:33:32.693",
"Id": "224659",
"ParentId": "224006",
"Score": "1"
}
},
{
"body": "<p>In addition to what @dfhwze has said, I wanted to give some suggestions on general ruby best practice and readibility:</p>\n\n<h2>Multiline Blocks</h2>\n\n<p>In <code>PriceCalculator#start_billing</code>, <code>PriceCalculator#count_items</code> and in a couple other methods you use muliline blocks like so:</p>\n\n<pre><code>foobar.each { |*args|\n # do stuff\n # more stuff\n}\n</code></pre>\n\n<p>The use of <code>{}</code> is really only intended for single line blocks -- when you have more than one line inside of the block, it's best to use <code>do ... end</code>. This will make your code a bit easier to read. From my example:</p>\n\n<pre><code>foobar.each do |*args|\n # do stuff\n # more stuff\nend\n</code></pre>\n\n<h2>Method Definitions</h2>\n\n<p>In ruby, while it's valid syntax to define methods like <code>def some_method argument</code>, it's really easy to misread that as <code>def some_method_argument</code>, and so it's considered better practice to put parentheses around your method definitions, like so: <code>def some_method(argument)</code>.</p>\n\n<h2>Other</h2>\n\n<p>I just wanted to take a look at this method:</p>\n\n<pre><code>def calculate_bill quantity\n price = {}\n quantity.each { |item,value| \n if SaleItems.all[item].nil? \n price[item] = quantity[item]*Items.all[item]\n else \n price[item] = (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])\n end \n }\n price\nend\n</code></pre>\n\n<p>Specifically, in the if statement, you could take advantage of a common ruby idiom for generating hashes, and instead of generating a <code>price</code> hash just return the hash you want:</p>\n\n<pre><code>def calculate_bill quantity\n quantity.map { |item,value| [item, SalesItems.all[item].nil? ? quantity[item]*Items.all[item] : (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])] }.to_h\nend\n</code></pre>\n\n<p>(note how I used the <code>{}</code> for a one line block). If you wanted to expand this to make it a bit more readable:</p>\n\n<pre><code>def calculate_bill quantity\n quantity.map do |item,value|\n v = if SalesItems.all[item].nil?\n quantity[item]*Items.all[item]\n else\n (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])\n end\n [item, v]\n end.to_h\nend\n</code></pre>\n\n<p>I'd also recommend breaking up that massive formula into some smaller pieces with better variable names to make it easier to tweak it later if you need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T18:27:53.590",
"Id": "225477",
"ParentId": "224006",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224659",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T05:45:58.607",
"Id": "224006",
"Score": "4",
"Tags": [
"beginner",
"object-oriented",
"ruby"
],
"Title": "Ruby price calculator for groceries"
} | 224006 |
<p>I am building a primitive Store Management System based on Qt and would appreciate some feedback.</p>
<p>Classes:</p>
<ul>
<li><code>ManagementSystem</code> - the logic unit of the system</li>
<li><code>User</code> - might be either Admin or Manager (they access the system)</li>
<li><code>Member</code> - the people who are the members of the Warehouse Club. Might be either Executive (obtains 3% of rebate from every purchase) and Regular.</li>
<li><code>MainWindow</code> - view layer of the system.</li>
<li><code>Sale</code> - stores one sale unit (item + quantity)</li>
<li><code>Item</code> - stores the name of the item, its price and how many of the has been sold so far.
I am using only one window and show or hide the respective elements depending on the context. </li>
</ul>
<p>Data Storage: </p>
<ul>
<li><p>7 day sales txt files. For every file (line by line):</p>
<ul>
<li>Purchase date</li>
<li>Customer membership number </li>
<li>Item purchased</li>
<li>[Sales price] [quantity purchased] (in one line)</li>
</ul></li>
<li><p>Members txt file (line by line) :</p>
<ul>
<li>Customer name</li>
<li>Customer membership number</li>
<li>Type of customer – Regular or Executive</li>
<li>Membership expiration date</li>
</ul></li>
<li>Users txt file (line by line):
<ul>
<li>login</li>
<li>password</li>
</ul></li>
</ul>
<p>ManagementSystem.h</p>
<pre><code>#ifndef MANAGEMENTSYSTEM_H
#define MANAGEMENTSYSTEM_H
#include "user.h"
#include "member.h"
#include "item.h"
#include "sale.h"
#include <QFile>
#include <QDebug>
#include <QVector>
#include <functional>
#define CREDENTIALS_FILE "/home/dominik/projects/study/BulkClub/BulkClub/login.txt"
#define DAY1_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day1.txt"
#define DAY2_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day2.txt"
#define DAY3_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day3.txt"
#define DAY4_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day4.txt"
#define DAY5_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day5.txt"
#define DAY6_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day6.txt"
#define DAY7_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/day7.txt"
#define MEMBERS_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/warehouse shoppers.txt"
#define TMP_FILE "/home/dominik/projects/study/BulkClub/BulkClub/resources/tmp.txt"
#define LINES_MEMBERS 4
#define LINES_SALES 4
enum CurrentlyLogged {
noOne, admin, manager
};
class ManagementSystem
{
public:
ManagementSystem();
void initializeUsers();
bool retrieveCredentials();
User getAdmin() const {return admin;}
User getManager() const {return manager;}
QVector<QVector<Sale>> getSales() const {return m_allSales;}
QVector<Member> getMembers() const {return m_members;}
CurrentlyLogged getCurrentlyLogged() const { return logged;}
void setCurrentlyLogged(CurrentlyLogged log) {logged=log;}
void setMembers(QVector<Member>& mem) {m_members=mem;}
bool populateMembersData(QFile& file);
bool populateDaySales(QFile* file);
void sortPurchasesByNumber();
Member* findMember(int id);
void sortMembers(bool is_byID);
QVector<int> getExecutiveMembers() const {return m_executiveMembers;}
QVector<int> getRegularMembers() const {return m_regularMembers;}
QVector<Sale> getAllSalesOneVec() const {return m_allSalesOneVec;}
QVector<Item*> getAllItems() const { return m_allItems;}
void addMemberToFile(Member& m);
//void deleteMemberFromFile(QString& member_name);
private:
User admin;
User manager;
QVector<Member> m_members;
CurrentlyLogged logged;//0=no one, 1=admin, 2=manager
QVector<QVector<Sale>> m_allSales;
QVector<Sale> m_allSalesOneVec;
QFile* m_salesFiles[7];
QVector<int> m_executiveMembers;
QVector<int> m_regularMembers;
QVector<Item*> m_allItems;
QVector<QString> m_allItemsNames;
};
#endif // MANAGEMENTSYSTEM_H
</code></pre>
<p>Member.h :</p>
<pre><code>#ifndef MEMBER_H
#define MEMBER_H
#include <QDateTime>
enum MembershipType {
Executive, Regular
};
class Member
{
public:
Member();
Member(QString name, int no, MembershipType type, QDate date, int total, int rebate);
QString getName() const {return m_name;}
int getNumber() const {return m_number;}
MembershipType getType() const {return m_type;}
QDate getDate() const {return m_date;}
int getTotalSpent() const {return m_totalSpent;}
int getRebate() const {return m_rebateAmount;}
void setName(QString name) {m_name = name;}
void setNumber(int number) {m_number = number;}
void setType(MembershipType type) {m_type = type;}
void setDate(QDate date) {m_date = date;}
void setTotalSpent(int spent) {m_totalSpent = spent;}
void setRebate(int rebate) {m_rebateAmount = rebate;}
private:
QString m_name;
int m_number;
MembershipType m_type;
QDate m_date;
int m_totalSpent=0; //in cents
int m_rebateAmount=0;
};
#endif // MEMBER_H
</code></pre>
<p>Sale.h</p>
<pre><code>#ifndef SALE_H
#define SALE_H
#include "member.h"
#include "item.h"
#include <QFile>
#include <QDate>
const float REBATE_PERCENT = 0.03;
class Sale
{
public:
Sale();
int getQuantity() const {return m_quantity;}
int getMembersID() const {return m_number;}
QDate getDate() const {return m_date;}
Item* getItem() {return m_item;}
void setMembersID(int number) {m_number=number;}
void setQuantity(int q) {m_quantity=q;}
void setDate(QDate date) {m_date=date;}
int getPriceBeforeTax() const {return m_item->getPrice()*(1-sales_tax);}
void setItem(Item* it) {m_item=it;}
private:
QDate m_date;
int m_number;
Item* m_item;
int m_quantity;
static int sales_tax;
};
#endif // SALE_H
</code></pre>
<p>User.h</p>
<pre><code>void setIsAdmin(bool is) {m_isAdmin = is;}
void setLogin(int login) {m_loginID = login;}
void setPsw(QString psw) {m_password = psw;}
void setLoggedNow(bool logged) {m_loggedNow = logged;}
bool getIsAdmin() const {return m_isAdmin;}
int getLogin() const {return m_loginID;}
QString getPsw() const {return m_password;}
bool getLoggedNow() const {return m_loggedNow;}
private:
bool m_isAdmin; //if true -> admin, if false -> store manager
int m_loginID;
QString m_password;
bool m_loggedNow;
};
#endif // USER_H
</code></pre>
<p>Item.h</p>
<pre><code>#ifndef ITEM_H
#define ITEM_H
#include <QString>
class Item
{
public:
Item();
int getPrice() const {return m_price;}
QString getName() const {
return m_name;
}
void setName(QString it) {m_name=it;}
void setPrice(int price) {m_price=price;}
int getCount() const {return count;}
void setCount(int c) {count = c;}
private:
QString m_name;
int m_price;
int count=0;
};
#endif // ITEM_H
</code></pre>
<p>ManagementSystem.cpp</p>
<pre><code>#include "managementsystem.h"
static int ccc=0;
ManagementSystem::ManagementSystem()
{
QFile file(MEMBERS_FILE);
m_salesFiles[0] = new QFile (DAY1_FILE);
m_salesFiles[1] = new QFile (DAY2_FILE);
m_salesFiles[2] = new QFile (DAY3_FILE);
m_salesFiles[3] = new QFile (DAY4_FILE);
m_salesFiles[4] = new QFile (DAY5_FILE);
m_salesFiles[5] = new QFile (DAY6_FILE);
m_salesFiles[6] = new QFile (DAY7_FILE);
initializeUsers();
retrieveCredentials();
populateMembersData(file);
//store IDs of regular and executive members in 2 vectors
for(auto& mem : m_members) {
if(mem.getType()==1) m_regularMembers.push_back(mem.getNumber());
else if(mem.getType()==0) m_executiveMembers.push_back(mem.getNumber());
}
//populate days data from 7 files
for(QFile* f : m_salesFiles) {
populateDaySales(f);
}
}
//users init
void ManagementSystem::initializeUsers() {
manager = User(false, 0, "");
admin = User(true, 0, "");
}
//initialize admin and user
bool ManagementSystem::retrieveCredentials() {
int counter=0;
QFile credentials_file(CREDENTIALS_FILE);
if(credentials_file.exists()){
if (!credentials_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << manager.getLogin();
return false;
}
while (!credentials_file.atEnd()) {
bool encoding;
QByteArray line = credentials_file.readLine();
line = line.trimmed();
if(counter==0) manager.setLogin(QString(line).toInt(&encoding, 10));
if(counter==1) manager.setPsw(QString(line));
if(counter==2) admin.setLogin(QString(line).toInt(&encoding, 10));
if(counter==3) admin.setPsw(QString(line));
counter++;
}
return true;
}
else {
qDebug() << "File doesnt exists";
return false;
}
}
//populate members data from file
bool ManagementSystem::populateMembersData(QFile& file){
Member* mem;
MembershipType type;
QString name_buf;
int number_buf;
MembershipType type_buf;
QDate date_buf;
int counter=0;
if(file.exists()){
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qInfo() << "STH WENT WRONG";
return false;
}
while (!file.atEnd()) {
bool encoding;
QByteArray line = file.readLine();
line = line.trimmed();
if(counter%LINES_MEMBERS==0) {
name_buf = QString(line);
}
else if((counter+3)%LINES_MEMBERS==0) {
number_buf = QString(line).toInt(&encoding, 10);
}
else if((counter+2)%LINES_MEMBERS==0) {
if(line.operator == ("Regular")) {
type_buf = MembershipType::Regular;
}
if(line.operator == ("Executive")) {
type_buf = MembershipType::Executive;
}
}
else if((counter+1)%LINES_MEMBERS==0) {
QString date_str = QString(line);
date_buf = QDate::fromString(date_str,"MM/dd/yyyy");
mem = new Member;
mem->setDate(date_buf);
mem->setName(name_buf);
mem->setNumber(number_buf);
mem->setType(type_buf);
m_members.push_back(*mem);
delete mem;
}
counter++;
}
}
else {
qDebug() << "File doesnt exists";
return false;
}
}
bool ManagementSystem::populateDaySales(QFile* file) {
QVector<Sale> day_vector;
int lines_number=4;
Sale* sale;
Item* item;
int number_buf;
QDate date_buf;
QString item_buf;
QString item_line_buf;
int item_price_buf;
int quantity_buf;
int counter=0;
if(file->exists()){
if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Populate Day sales doesnt work";
return false;
}
while (!file->atEnd()) {
bool encoding;
QByteArray line = file->readLine();
line = line.trimmed();
if(counter % LINES_SALES==0) {
QString date_str = QString(line);
date_buf = QDate::fromString(date_str,"MM/dd/yyyy");
}
else if((counter+3) % LINES_SALES==0) {
number_buf = QString(line).toInt(&encoding, 10);
}
else if((counter+2) % LINES_SALES==0) {
item_buf = QString(line);
}
else if((counter+1) % LINES_SALES==0) {
QStringList list;
list = QString(line).split('\t');
item_price_buf = static_cast<int>(QString(list[0]).toFloat()*100);
quantity_buf = QString(list[1]).toInt();
sale = new Sale;
sale->setDate(date_buf);
sale->setQuantity(quantity_buf);
sale->setMembersID(number_buf);
int i = m_allItemsNames.indexOf(item_buf);
// create a new item object if it doesn't exist yet
if(i==-1) {
item = new Item;
m_allItemsNames.append(item_buf);
item->setName(item_buf);
item->setPrice(item_price_buf);
m_allItems.push_back(item);
}
// use an existing item object
else {
for (int j=0; j < m_allItems.size(); j++) {
if(!m_allItems[j]->getName().compare(item_buf)) {
item = m_allItems[j];
}
}
}
//increment amount of items sold
item->setCount(item->getCount()+quantity_buf);
sale->setItem(item);
m_allSalesOneVec.push_back(*sale);
day_vector.push_back(*sale);
//find the member
Member* mem = findMember(number_buf);
mem->setTotalSpent(mem->getTotalSpent()+quantity_buf*item_price_buf);
//if the current member is executive, add rebate
if(m_executiveMembers.contains(number_buf)) {
qInfo() << mem->getRebate();
mem->setRebate(mem->getRebate()+REBATE_PERCENT*quantity_buf*item_price_buf);
}
}
counter++;
}
}
else {
qDebug() << "File doesnt exists";
return false;
}
m_allSales.push_back(day_vector);
}
Member* ManagementSystem::findMember(int id) {
for(auto &mem : m_members){
if(mem.getNumber() == id) {
return &mem;
}
}
qInfo() << "NOT FOUND";
return nullptr;
}
void ManagementSystem::sortPurchasesByNumber() {
std::sort(m_allSalesOneVec.begin(), m_allSalesOneVec.end(), [](Sale& a, Sale& b) {
return a.getMembersID() < b.getMembersID();
});
return;
}
//sorting members (true - by id, false - by rebate)
void ManagementSystem::sortMembers(bool is_byID) {
std::sort(m_members.begin(), m_members.end(), [&is_byID](Member& a, Member& b) {
return is_byID ? a.getNumber() < b.getNumber() : a.getRebate() > b.getRebate();
});
}
void ManagementSystem::addMemberToFile(Member& m) {
QFile file(MEMBERS_FILE);
if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
QTextStream stream(&file);
stream << m.getName() << endl;
stream << m.getNumber() << endl;
static_cast<bool>(m.getType()) ? stream << "Executive" << endl : stream << "Regular" <<endl;
stream << m.getDate().toString("dd/MM/yyyy") << endl;
}
}
</code></pre>
<p>MainWindow is mostly just calling the ManagementSystem methods inside slots.</p>
| [] | [
{
"body": "<p>Here are some things that may help you improve your program. One positive thing I feel I must note is that you've used <code>const</code> consistently and appropriately to mark read-only member functions. That's a very good practice and I hope you'll continue to do that as you go on!</p>\n\n<h2>Use consistent case for <code>#include</code> files</h2>\n\n<p>Your operating system might not be case sensitive with respect to files, but many are. To prevent problems with portability, instead of writing lines like this in <code>ManagementSystem.cpp</code>:</p>\n\n<pre><code>#include \"managementsystem.h\"\n</code></pre>\n\n<p>It should be this:</p>\n\n<pre><code>#include \"ManagementSystem.h\"\n</code></pre>\n\n<h2>Provide definitions for class members</h2>\n\n<p>In a number of classes, such as <code>Item</code>, there is a declaration for a construct such as <code>Item()</code> but no definition. Either omit the declaration and allow the compiler to generate the constructor or tell the compiler (and the reader!) explicitly to do so:</p>\n\n<pre><code>Item() = default;\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>There are several unused variables in the code, such as <code>type</code> in <code>ManagementSystem::populateMembersData()</code>. Unused variables are a sign of poor quality code, and you don't want to write poor quality code. Your compiler is probably smart enough to tell you about this if you ask it nicely.</p>\n\n<h2>Always <code>return</code> an appropriate value</h2>\n\n<p>Your <code>ManagementSystem::populateMembersData()</code> and <code>MangementSystem::populateDaySales</code> routines have control paths that cause them to end without <code>return</code>ing any <code>bool</code> value. This is an error and should be fixed.</p>\n\n<h2>Don't hardcode file names</h2>\n\n<p>Generally, it's not a good idea to hardcode a file name in software, and generally especially bad if it's an absolute file name (as contrasted with one with a relative path). Instead, it might be better to allow the user of the program to specify the name, as with a command line parameter or configuration file.</p>\n\n<h2>Think seriously about security</h2>\n\n<p>I understand that this is probably a project just for learning and exploring, but it's worthwhile to think about security provisions for this. First, it appears that logins and passwords are stored unencrypted in both memory and in the credentials file. Second, it's not clear how the logon is managed but the fact that the <code>ManagementSystem</code> class maintains its own <code>logged</code> flag telling whether an administrator or manager is logged in signals potential problems to me. If there is a bug that forgets to clear that value when an administrator logs out, that's potentially a security problem. Better might be to check the credentials of whomever is logged in every time higher privileges are needed which would also, potentially, take care of the risk that, say, a manager is demoted or fired while logged in but still has privileges on the system. There are myriad other considerations, of course; this is just to help remind you to think in that direction.</p>\n\n<h2>Use a <code>class</code> to maintain invariants</h2>\n\n<p>If a data structure has some invariant that it is enforcing, such as that if a membership type is changed, the date is reset, it makes sense to have that done via a <code>class</code>. However, in the case of a class <code>Member</code>, where there are public setters and getters for every data item and no enforcement of any invariant, just make this a <code>struct</code> instead and eliminate a bunch of useless code. This isn't Java. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-get\" rel=\"nofollow noreferrer\">C.131</a> for more details.</p>\n\n<h2>Think carefully about object ownership</h2>\n\n<p>The <code>Sale</code> class currently maintains a pointer to an <code>Item</code>. First, shouldn't that at least be a <code>const *</code> so that the <code>Sale</code> object can't alter the <code>Item</code>? Second, what happens if the <code>Item</code> is deleted before the <code>Sale</code> class is? It would mean that the <code>Sale</code> class instance would contain an invalid pointer. Those problems could be eliminated by using something like a <code>std::shared_ptr</code>.</p>\n\n<h2>Avoid C-style macros</h2>\n\n<p>There are few valid reasons left for using old-style C macros in modern C++ code. Better is to create <code>const</code> or <code>constexpr</code> variables instead. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-macros2\" rel=\"nofollow noreferrer\">ES.31</a></p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T18:47:41.060",
"Id": "224300",
"ParentId": "224009",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T06:59:15.890",
"Id": "224009",
"Score": "3",
"Tags": [
"c++",
"qt"
],
"Title": "Qt / C++/ Warehouse Club Management System"
} | 224009 |
<p>I have deliberately avoided any OOP for this project. I'm fairly happy with my implementation of the classic strategy game "Chomp". The computer just uses a random valid choice, so no AI.</p>
<p>I would appreciate feedback on points of style and correctness. Is the code basically OK? Does it seem to have a coherent style? What improvements would you make?</p>
<p>Thanks in advance.</p>
<pre><code>"""
Chomp - a strategy game
"""
import random
import time
NUM_ROWS = 5
NUM_COLS = 6
def print_title():
print(r"""
______ __ __ ______ __ __ ______
/\ ___\ /\ \_\ \ /\ __ \ /\ "-./ \ /\ == \
\ \ \____ \ \ __ \ \ \ \/\ \ \ \ \-./\ \ \ \ _-/
\ \_____\ \ \_\ \_\ \ \_____\ \ \_\ \ \_\ \ \_\
\/_____/ \/_/\/_/ \/_____/ \/_/ \/_/ \/_/
""")
def print_instructions():
print("Welcome to Chomp. Choose a square and all squares to the right")
print("and downwards will be eaten. The computer will do the same.")
print("The one to eat the poison square loses. Good luck!")
print()
def who_goes_first():
if random.randint(0, 1) == 0:
return "computer"
else:
return "human"
def play_again():
print("Would you like to play again? (yes or no)")
return input().lower().startswith("y")
def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end=" ")
print()
def validate_user_input(player_choice, board):
try:
row, col = player_choice.split()
except ValueError:
print("Bad input: The input should be exactly two numbers separated by a space.")
return False
try:
row = int(row)
col = int(col)
except ValueError:
print("Input must be two numbers, however non-digit characters were received.")
return False
if row < 0 or row > NUM_ROWS - 1:
print(f"The first number must be between 0 and {NUM_ROWS - 1} but {row} was passed.")
return False
if col < 0 or col > NUM_COLS - 1:
print(f"The second number must be between 0 and {NUM_COLS - 1} but {col} was passed.")
return False
if board[row][col] == " ":
print("That square has already been eaten!")
return False
return True
def update_board(board, row, col):
for i in range(row, len(board)):
for j in range(col, len(board[i])):
board[i][j] = " "
def get_human_move(board):
valid_input = False
while not valid_input:
player_choice = input("Enter the row and column of your choice separated by a space: ")
valid_input = validate_user_input(player_choice, board)
row, col = player_choice.split()
return int(row), int(col)
def get_computer_move(board):
valid_move = False
while not valid_move:
row = random.randint(0, NUM_ROWS - 1)
col = random.randint(0, NUM_COLS - 1)
if board[row][col] == " ":
continue
else:
valid_move = True
return row, col
def main():
board = []
for i in range(NUM_ROWS):
row = []
for j in range(NUM_COLS):
row.append("#")
board.append(row)
board[0][0] = "P"
game_is_playing = True
turn = "human"
print_title()
print_instructions()
while game_is_playing:
if turn == "human":
# Human turn
print("Human turn.")
print()
print_matrix(board)
print()
row, col = get_human_move(board)
if board[row][col] == "P":
print()
print("Too bad, the computer wins!")
game_is_playing = False
else:
update_board(board, row, col)
print()
print_matrix(board)
print()
turn = "computer"
time.sleep(1)
else:
# Computer turn
row, col = get_computer_move(board)
print(f"Computer turn. the computer chooses ({row}, {col})")
print()
if board[row][col] == "P":
print()
print("Yay, you win!")
game_is_playing = False
else:
update_board(board, row, col)
print_matrix(board)
print()
turn = "human"
if play_again():
main()
else:
print("Goodbye!")
raise SystemExit
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T10:21:33.203",
"Id": "451154",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T10:58:36.927",
"Id": "451156",
"Score": "0",
"body": "I was just removing \"clutter\" as the big ASCII title is superfluous. I didn't change anything else. I would prefer the simplified title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T12:37:05.973",
"Id": "451164",
"Score": "0",
"body": "The title is explicitly mentioned in an existing answer, so we can't do that."
}
] | [
{
"body": "<p>Your game has the same kind of flaw like a lot of the other games that have recently been here on Code Review: an unnecessary recursion in the main game flow:</p>\n\n<p>What do I mean by that? Let's look at your <code>main</code> function:</p>\n\n<pre><code>def main(): \n\n # ... all of the actual game here ...\n\n if play_again():\n main()\n else:\n print(\"Goodbye!\")\n raise SystemExit\n</code></pre>\n\n<p>As one can clearly see <code>main</code> will call <code>main</code> every time the player chooses to play another round, leading to deeper and deeper recursion. If someone would be really obsessed with your game and would try to play more than <code>sys.getrecursionlimit()</code> games (here on my machine it's 3000), there would be a <code>RuntimeError</code>.</p>\n\n<p>Fortunately this can easily be fixed using a simple <code>while</code> loop:</p>\n\n<pre><code>def main():\n while True:\n\n # ... all of the actual game here ...\n\n if not play_again():\n print(\"Goodbye!\")\n break\n</code></pre>\n\n<p>Recursion gone, welcome binge playing till your fingers bleed.</p>\n\n<hr>\n\n<p>Now that we have that sorted out, let's look at some of the details of your code.</p>\n\n<h2>print_*</h2>\n\n<p>Not much to critique here, but I would like to introduce you to <a href=\"https://docs.python.org/3/library/textwrap.html#textwrap.dedent\" rel=\"nofollow noreferrer\"><code>textwrap.dedent</code></a>. <code>textwrap.dedent</code> allows you to indent text blocks as you would do with code and then takes care to remove the additional leading whitespace.</p>\n\n<pre><code>from textwrap import dedent\n\n\ndef print_title():\n print(\n dedent(r\"\"\"\n ______ __ __ ______ __ __ ______ \n /\\ ___\\ /\\ \\_\\ \\ /\\ __ \\ /\\ \"-./ \\ /\\ == \\ \n \\ \\ \\____ \\ \\ __ \\ \\ \\ \\/\\ \\ \\ \\ \\-./\\ \\ \\ \\ _-/ \n \\ \\_____\\ \\ \\_\\ \\_\\ \\ \\_____\\ \\ \\_\\ \\ \\_\\ \\ \\_\\ \n \\/_____/ \\/_/\\/_/ \\/_____/ \\/_/ \\/_/ \\/_/ \n \"\"\")\n )\n</code></pre>\n\n<p>But it basically boils down to personal taste which version you prefer. The same logic could be applied to <code>print_instructions</code> to only need a single call to <code>print</code>.</p>\n\n<h2>who_goes_first</h2>\n\n<p><code>who_goes_first</code> could be simplified a little bit:</p>\n\n<pre><code>def who_goes_first():\n return random.choice((\"computer\", \"human\"))\n</code></pre>\n\n<p>Or even be left out? You current code does not use it.</p>\n\n<h2>print_matrix</h2>\n\n<p>Again, the code could be simplified a little bit, e.g. using <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>:</p>\n\n<pre><code>def print_matrix(matrix):\n for row in matrix:\n print(\" \".join(row))\n</code></pre>\n\n<p>From what you can actually see, there should be no difference to the previous output, but there is actually no trailig whitespace in this version. You could even go a little bit futher than this using a list comprehension:</p>\n\n<pre><code>def print_matrix(matrix):\n print(\"\\n\".join(\" \".join(row) for row in matrix))\n</code></pre>\n\n<h2>validate_user_input / get_human_move</h2>\n\n<p><code>validate_user_input</code> does a good job at validating the given user input, but keeps the results of the parsing to itself. That leads to duplicate code in <code>get_human_move</code>. With a little bit of rewriting that duplication can be removed:</p>\n\n<pre><code>def validate_user_input(player_choice, board):\n try:\n row, col = player_choice.split()\n except ValueError:\n raise ValueError(\n \"Bad input: The input should be exactly two numbers separated by a space.\"\n )\n\n try:\n row = int(row)\n col = int(col)\n except ValueError:\n raise ValueError(\n \"Input must be two numbers, however non-digit characters were received.\"\n )\n\n if row < 0 or row > NUM_ROWS - 1:\n raise ValueError(\n f\"The first number must be between 0 and {NUM_ROWS - 1} but {row} was passed.\"\n )\n\n if col < 0 or col > NUM_COLS - 1:\n raise ValueError(\n f\"The second number must be between 0 and {NUM_COLS - 1} but {col} was passed.\"\n )\n\n if board[row][col] == \" \":\n raise ValueError(\"That square has already been eaten!\")\n\n return row, col\n\n\ndef get_human_move(board):\n while True:\n player_choice = input(\"Enter the row and column of your choice separated by a space: \")\n try:\n row, col = validate_user_input(player_choice, board)\n break\n except ValueError as ex:\n print(ex)\n return row, col\n</code></pre>\n\n<p>So what has happened here?</p>\n\n<ol>\n<li><code>validate_user_input</code> now does not print the error message itself, but raises an informative exception instead.</li>\n<li>if no reason to raise an exception has occured, <code>validate_user_input</code> now returns <code>row</code> and <code>col</code>, to they do not need to be recomputed in <code>get_human_move</code></li>\n<li><code>get_human_move</code> was adapted to that change and now tries to get the validated user input, prints the reason if that fails, and asks the user to try again.</li>\n</ol>\n\n<p>Of course, raising exceptions is just one way to do this. There are many other ways that lead to a similar structure.</p>\n\n<p>If you decide to implement these changes, <code>parse_user_input</code> is maybe a more appropiate name now, given its new capabilites.</p>\n\n<p>You might want think about passing <code>NUM_ROWS</code>/<code>NUM_COLS</code> as parameters or determine it from <code>board</code> to cut down on global variables as well.</p>\n\n<p><strong>Quick sidenote:</strong> 0-based indexing might be unfamiliar to people that have no programming backgroud (or use MatLab all the time ;-)), so maybe allow the user to enter 1-based indices and substract 1 before validation.</p>\n\n<h2>update_board</h2>\n\n<p>Depending on your choice on the previous point, this is either the way to go, or you should use <code>NUM_ROWS</code>/<code>NUM_COLS</code> here too to be consistent.</p>\n\n<h2>get_computer_move</h2>\n\n<p>Maybe you shoud add some simple heuristics to make your computer a little bit smarter, e.g. it sometimes chooses to take the poison even if it still has alternatives, or even the possibilty to win. Also (theoretically), it is be possible that this random sampling algorithm never finds a valid solution ;-) To avoid that, generate a list of valid rows and values, and pick a sample from these lists.</p>\n\n<p>If you stick to the current approach, you can at least get rid of the \"support variable\" <code>valid_move</code>:</p>\n\n<pre><code>def get_computer_move(board):\n while True:\n row = random.randint(0, NUM_ROWS - 1)\n col = random.randint(0, NUM_COLS - 1)\n if board[row][col] == EMPTY_SPOT:\n continue\n else:\n break\n return row, col\n</code></pre>\n\n<h2>main</h2>\n\n<p><code>main</code> already had some structural remarks, so let's look at its code a little bit:</p>\n\n<p>This </p>\n\n<pre><code>board = []\nfor i in range(NUM_ROWS):\n row = []\n for j in range(NUM_COLS):\n row.append(\"#\")\n board.append(row)\n</code></pre>\n\n<p>can be recuded to a single nested list comprehension:</p>\n\n<pre><code>board = [[\"#\" for _ in range(NUM_COLS)] for _ in range(NUM_ROWS)]\n</code></pre>\n\n<p>Depending on your choice regarding the global variables, <code>NUM_ROWS</code>/<code>NUM_COLS</code> would need to be removed here to. Maybe even allow them to be set as <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">command line arguments</a> by the user?</p>\n\n<p>The rest of the code has some \"magic values\" (they are not so magic in your case), e.g. <code>board[0][0] = \"P\"</code>, <code>turn = \"computer\"</code>, and <code>turn = \"human\"</code> (there was also <code>\" \"</code> earlier to mark empty spots). The problem with those \"magic values\" is that your IDE has no chance to help you spot errors. You did write <code>\"p\"</code> instead of <code>\"P\"</code> and now the game does weird things? Too bad. You will have to find that bug yourself! The way to go about this would be to use global level constants, because this is what globals are actually good for, or an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> if you have several distint values like human and computer.</p>\n\n<p>This is a possible way to do it (with a sketch of how main would look like):</p>\n\n<pre><code>FILLED_SPOT = \"#\"\nPOISON_SPOT = \"P\"\nEMPTY_SPOT = \" \"\n\n\nclass Actor(enum.Enum):\n HUMAN = \"human\"\n COMPUTER = \"computer\"\n\n# ... lot of code here ...\n\ndef main():\n while True:\n board = [[FILLED_SPOT for _ in range(NUM_COLS)] for _ in range(NUM_ROWS)]\n\n board[0][0] = POISON_SPOT\n turn = Actor.HUMAN # or: who_goes_first()\n\n # ...\n\n while game_is_playing:\n if turn == Actor.HUMAN:\n # Human turn\n # ...\n if board[row][col] == POISON_SPOT:\n # ...\n else:\n # ...\n turn = Actor.COMPUTER\n else:\n # Computer turn\n # ...\n if board[row][col] == POISON_SPOT:\n # ...\n else:\n # ...\n turn = Actor.HUMAN\n\n if not play_again():\n print(\"Goodbye!\")\n break\n\n\n</code></pre>\n\n<p>I chose this to showcase both variants. In your case to could also just use either of those, no need to have both of them in the game.</p>\n\n<hr>\n\n<p>All of this may sound harsh, but it really isn't meant that way! Your code is actually quite enjoyable to review. Your style is quite consistent, the names are good and the general structure is clear.</p>\n\n<p>Keep up the good work!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T07:30:24.737",
"Id": "434585",
"Score": "0",
"body": "Thanks @AlexV That's exactly the kind of feedback I was looking for. One thing that confuses me though - I hear strong opinions about not using `while True` - that the condition should be made explicit, and yet it seems like a useful construct to me, and you are recommending it here. I'm guessing other reviewers would say to change it. Is it just a matter of taste?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T07:44:46.457",
"Id": "434586",
"Score": "0",
"body": "I don't have a strong opinion on that. But I think I prefer the `while True: ... break` approach for simple cases like here, simply because that helps me not to have to find another meaningful name for a variable. If you have to check multiple conditions, or the inner loop would also need to break the outer loop, the explicit approach is the way to go I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T08:40:40.523",
"Id": "447437",
"Score": "0",
"body": "I've just been revisiting this code, and noticed something weird with global variables. For example in `update_board` I pass `board` as a parameter, and update it inside the function, but don't return the updated board, yet it still gets updated. So it appears I'm basically using a global value for `board`. Should I remove the `board` parameter and use `global board` instead, to be at least coherent? I know globals are discouraged, but it's maybe at least better to be explicit about them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T09:15:16.683",
"Id": "447439",
"Score": "2",
"body": "@Robin: Python [has mutable (e.g. `list`, `dict`) and immutable types/objects (e.g. `int`, `string`, `tuple`) types](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/). `board` is a list of list and therefore mutable, so you can modify it directly without returning the modified version. I don't see how a global variable would make this more obvious."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:01:55.097",
"Id": "224065",
"ParentId": "224012",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "224065",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:26:16.950",
"Id": "224012",
"Score": "6",
"Tags": [
"python",
"game"
],
"Title": "Chomp Game in Python 3"
} | 224012 |
<p>I agree that using regex to parse HTML is not a <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">good way</a>, in particular I am worried about their fragility with respect to change in the HTML.</p>
<p>The problem is that any alternatives are really too slow.</p>
<p>I am parsing <a href="https://air.unimi.it/browse?type=author&authority=rp09852&sort_by=2&order=DESC&rpp=10&etal=0&submit_browse=Aggiorna" rel="nofollow noreferrer">this web page</a> which is quite big (3MB). Somewhere in the html there is:</p>
<pre><code><form class="form-inline" id="exportform" action="/references" class="hidden">
<input type="hidden" name="format" value="" />
<input type="hidden" name="item_id" value="678860" />
<input type="hidden" name="item_id" value="656680" />
<input type="hidden" name="item_id" value="678846" />
<input type="hidden" name="item_id" value="650319" />
<input type="hidden" name="item_id" value="651504" />
<input type="hidden" name="item_id" value="678849" />
<input type="hidden" name="item_id" value="649821" />
<input type="hidden" name="item_id" value="649835" />
<input type="hidden" name="item_id" value="651512" />
<input type="hidden" name="item_id" value="651510" />
</form>
</code></pre>
<p>I need to extract the 10 numbers in the <code>value</code> field. I know they are exactly 10.</p>
<p>I tried different approaches:</p>
<h2>BeautifulSoup</h2>
<pre><code>from bs4 import BeautifulSoup
def soup(html):
soup = BeautifulSoup(html, 'lxml')
form = soup.find("form", {'id': 'exportform'})
if not form:
return []
entries = form.find_all("input", {'name': 'item_id'})
result = [entry['value'] for entry in entries]
return result
</code></pre>
<h2>Regex</h2>
<pre><code>import re
import itertools
def regex(html):
r = re.compile(r'<input type="hidden" name="item_id" value="([0-9]+)">')
s = r.finditer(html)
result = []
for ss in itertools.islice(s, 10):
result.append(ss.group(1))
return result
</code></pre>
<h2>xpath</h2>
<pre><code>import lxml.html
from lxml import etree # same performance with this
def xpath(html):
root = lxml.html.fromstring(html)
result = root.xpath('//form[@class="form-inline"]/*[@name="item_id"]')
return [r.attrib['value'] for r in result]
</code></pre>
<p>I get the same results from the three, but very different timing:</p>
<ul>
<li>BeautifulSoup: 3.3</li>
<li>regex: 0.00013</li>
<li>xpath: 0.57</li>
</ul>
<p>In the regex case I am able to use the trick that I know there are exactly 10 numbers to find, gaining a factor 10. But also without that trick the regex approach is 400 times faster than xpath.</p>
<p>In addition asking xpath to give me the first 10:</p>
<pre><code>(//form[@class="form-inline"]/*[@name="item_id"])[position() < 11]
</code></pre>
<p>is not improving</p>
| [] | [
{
"body": "<p>Well, your regex solution is obviously badly broken - it will fail if the attributes are in a different order, if they are separated by newlines, if they are delimited by single quotes, etc etc. If you try to replace it with a more correct regex (it will never be 100% correct of course) then you are quite likely to lose some of this speed - perhaps dramatically, if it starts backtracking.</p>\n\n<p>The cost of the XPath solution is not actually in evaluating the XPath, it is (a) parsing the source document and building a tree representation, and (b) compiling the XPath expression. The key to getting a performance improvement is to make sure you are doing these operations only once. I don't know whether that's possible in your overall application scenario.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T02:02:09.330",
"Id": "434566",
"Score": "0",
"body": "Just to elaborate on \"more correct regex\" -- this could mean for example *case-insensitive* `<input`, non-greedy match-anything, `value`, optional whitespace, equals sign, more optional whitespace, character class containing double and single quote in a capture group, digits in a capture group, backreference to the previous quote; as in `egrep -i '<INPUT.*?VALUE\\s*=\\s*([\"\\'])([0-9]+)\\1'` ... or you could probably isolate just the form and let xpath parse that instead of the whole page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:30:55.333",
"Id": "434633",
"Score": "0",
"body": "A fully-correct regex should also ignore `<input` when it appears in a comment or CDATA section, it should allow a digit 5 in the value attribute to be written as 5, it should allow attribute values to be defaulted from the DTD, etc etc. In practice you only need to worry about such things if you are defending against malicious users; but it's worth being aware of."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T10:58:40.933",
"Id": "224018",
"ParentId": "224013",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:35:58.310",
"Id": "224013",
"Score": "2",
"Tags": [
"python",
"performance",
"regex",
"beautifulsoup",
"xpath"
],
"Title": "Beautifulsoup and lxml (xpath) too slow with respect to regex when parsing HTML"
} | 224013 |
<p>I'm pretty new and I posted on SO earlier because I wanted to make sure my code was right and all that and I got redirected here.
So I have this code that I put together (using <a href="https://docs.microsoft.com/en-us/windows/win32/seccrypto/example-c-proram--creating-an-md-5-hash-from-file-content" rel="nofollow noreferrer">Example C Program: Creating an MD5 Hash from File Content</a> and some some other code I found online) to try to hash a directory in SHA256. I am still somewhat a noob in programming so I'd love to get any kind of feedback on the code. I basically just mixed the directory iterator and hashing function together.
Also, I get a different hash when I run this function on a directory than another program I have. Someone pointed out that it might be because I read the files in a different order. He also pointed out that my code was "brittle". Is there any way I can improve this. How do I ensure that I get a "correct" hash?</p>
<p>Here's the code: </p>
<pre><code>#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <experimental/filesystem>
#define BUFSIZE 1024
#define SHA256LEN 32
#define PATH "C:\\SomeUser\\SomeDirectory"
using namespace std;
namespace filesys = std::experimental::filesystem;
std::vector<std::string> getAllFilesInDir(const std::string& dirPath, const std::vector<std::string> dirSkipList = { })
{
// Create a vector of string
std::vector<std::string> listOfFiles;
try {
// Check if given path exists and points to a directory
if (filesys::exists(dirPath) && filesys::is_directory(dirPath))
{
// Create a Recursive Directory Iterator object and points to the starting of directory
filesys::recursive_directory_iterator iter(dirPath);
// Create a Recursive Directory Iterator object pointing to end.
filesys::recursive_directory_iterator end;
// Iterate till end
while (iter != end)
{
// Check if current entry is a directory and if exists in skip list
if (filesys::is_directory(iter->path()) &&
(std::find(dirSkipList.begin(), dirSkipList.end(), iter->path().filename()) != dirSkipList.end()))
{
// Skip the iteration of current directory pointed by iterator
#ifdef USING_BOOST
// Boost Fileystsem API to skip current directory iteration
iter.no_push();
#else
// c++17 Filesystem API to skip current directory iteration
iter.disable_recursion_pending();
#endif
}
else
{
// Add the name in vector
listOfFiles.push_back(iter->path().string());
}
error_code ec;
// Increment the iterator to point to next entry in recursive iteration
iter.increment(ec);
if (ec) {
std::cerr << "Error While Accessing : " << iter->path().string() << " :: " << ec.message() << '\n';
}
}
}
}
catch (std::system_error& e)
{
std::cerr << "Exception :: " << e.what();
}
return listOfFiles;
}
DWORD hashDirectory()
{
DWORD dwStatus = 0;
BOOL bResult = FALSE;
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
HANDLE hFile = NULL;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[SHA256LEN];
DWORD cbHash = 0;
CHAR rgbDigits[] = "0123456789abcdef";
std::vector<std::string> listOfFiles = getAllFilesInDir(PATH);
for (auto str : listOfFiles)
{
if (!filesys::is_directory(str))
{
LPCSTR filename = str.c_str();
// Logic to check usage goes here.
hFile = CreateFile(filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
dwStatus = GetLastError();
printf("Error opening file %s\nError: %d\n", filename,
dwStatus);
return dwStatus;
}
// Get handle to the crypto provider
if (!CryptAcquireContext(&hProv,
NULL,
NULL,
PROV_RSA_AES,
CRYPT_VERIFYCONTEXT)
)
{
dwStatus = GetLastError();
printf("CryptAcquireContext failed: %d\n", dwStatus);
CloseHandle(hFile);
return dwStatus;
}
if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
{
dwStatus = GetLastError();
printf("CryptAcquireContext failed: %d\n", dwStatus);
CloseHandle(hFile);
CryptReleaseContext(hProv, 0);
return dwStatus;
}
while (bResult = ReadFile(hFile, rgbFile, BUFSIZE,
&cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
if (!CryptHashData(hHash, rgbFile, cbRead, 0))
{
dwStatus = GetLastError();
printf("CryptHashData failed: %d\n", dwStatus);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
return dwStatus;
}
}
if (!bResult)
{
dwStatus = GetLastError();
printf("ReadFile failed: %d\n", dwStatus);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
return dwStatus;
}
}
}
cbHash = SHA256LEN;
if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
{
//printf("SHA256 hash of file %s is: ", filename);
printf("sha256 Files:");
for (DWORD i = 0; i < cbHash; i++)
{
printf("%c%c", rgbDigits[rgbHash[i] >> 4],
rgbDigits[rgbHash[i] & 0xf]);
}
printf("\n");
}
else
{
dwStatus = GetLastError();
printf("CryptGetHashParam failed: %d\n", dwStatus);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
CloseHandle(hFile);
return dwStatus;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T05:18:04.167",
"Id": "434674",
"Score": "0",
"body": "Is there something wrong with the indentation at the end of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T06:02:12.653",
"Id": "434821",
"Score": "0",
"body": "Oh yeah I think it's supposed to be all the way to left because the for loop ends right above"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:47:54.027",
"Id": "224014",
"Score": "3",
"Tags": [
"c++",
"file-system",
"windows"
],
"Title": "SHA256 directory hash"
} | 224014 |
<p>I have built this hook to handle async calls. </p>
<ul>
<li><p>It should manage <code>state</code> for the <code>loading</code> and <code>error</code> status.</p></li>
<li><p>It should also not accept other calls while <code>loading === true</code>.</p></li>
<li><p>It should also works with synchronous functions without issues.</p></li>
</ul>
<p>Note that I used <code>useCallback</code> because I don't want <code>doAction</code> to change between renders, since I'll be using it a lot inside <code>useEffect()</code> in my components that make async calls. So I had to pass the <code>loading</code> from the component as a parameter <code>currentLoading</code>.</p>
<p><a href="https://i.stack.imgur.com/z0WOn.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z0WOn.gif" alt="enter image description here"></a></p>
<p><strong>QUESTION:</strong></p>
<p>Did I miss something? Will this work as per my requirements? Can I improve it somehow?</p>
<p>Sandbox Link: <a href="https://codesandbox.io/s/nice-carson-vk0nq" rel="nofollow noreferrer">https://codesandbox.io/s/nice-carson-vk0nq</a></p>
<hr>
<p><strong>useAsyncAction.js</strong></p>
<pre><code>import React, { useCallback, useState} from "react";
import ReactDOM from "react-dom";
function useAsyncAction(action) {
console.log("Rendering useAsyncAction...");
// STATE FOR LOADING AND ERROR STATUS
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// doAction AS AN useCallback SO IT WON'T CHANGE BETWEEN RENDERS
const doAction = useCallback(async (action,currentLoading) => {
if (currentLoading) {
console.log("There is one call in progress...");
return;
}
// TRY BLOCK
try {
setLoading(true);
setError(null);
await action();
setLoading(false);
// CATCH BLOCK
} catch (err) {
setError(err);
setLoading(false);
}
},[]);
return {
loading,
error,
doAction
};
}
</code></pre>
<p>How I'm using it:</p>
<p><strong>App.js</strong></p>
<pre><code>function App() {
console.log("Rendering App...");
const [myState, setMyState] = useState(null);
const { loading, error, doAction } = useAsyncAction();
// SIMULATES AN API RESPONSE
function mockAPI() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Here is your data");
}, 1500);
});
}
// EXAMPLE OF AN API ASYNC CALL
async function getNewData() {
const newData = await mockAPI();
setMyState(newData);
}
// EXAMPLE OF A SYNC CALL
function getNewDataSync() {
setMyState("SYNC DATA");
}
// THE BUTTONS ARE CALLING doAction(action,loading)
return (
<React.Fragment>
<div>myState: {myState}</div>
<div>loading: {JSON.stringify(loading)}</div>
<div>error: {JSON.stringify(error)}</div>
<button onClick={() => doAction(getNewData,loading)}>Do Action</button>
<button onClick={() => doAction(getNewDataSync,loading)}>Do Action Sync</button>
</React.Fragment>
);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T10:48:53.523",
"Id": "224017",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"async-await"
],
"Title": "Custom hook to handles async calls with loading and error state?"
} | 224017 |
<p>I wrote a simple prime number generator in C++17. The function <code>generate_primes(max)</code> generates all prime numbers up to <code>max</code>. I aimed for maximum portability. Here's the code:</p>
<pre><code>#include <cstdint>
#include <iostream>
#include <set>
#include <range/v3/view/iota.hpp>
namespace view = ranges::view;
using number_t = std::uint_fast32_t;
using numbers_t = std::set<number_t>;
numbers_t generate_primes(number_t max)
{
if (max < 2)
return {};
numbers_t primes{view::ints(number_t(2), max)};
for (number_t n = 2; n * n <= max; ++n) {
if (primes.find(n) != primes.end()) {
for (number_t m = 2; m <= max / n; ++m)
primes.erase(n * m);
}
}
return primes;
}
</code></pre>
<p>I used the <code>ints</code> utility from the <a href="https://ericniebler.github.io/range-v3/" rel="nofollow noreferrer">Ranges library</a> to populate <code>primes</code>. <code>view::ints(number_t(2), max)</code> lazily generates all the integers of type <code>number_t</code> that is greater or equal to 2 and that is less than or equal to <code>max</code> in ascending order. In C++20, the Ranges library is standardized.</p>
<p>Example usage:</p>
<pre><code>void print(std::ostream& os, const numbers_t& nums)
{
// convert to unsigned long so that it can be portability printed
for (unsigned long n : nums)
os << n << "\n";
}
int main()
{
print(std::cout, generate_primes(100));
}
</code></pre>
<p>Output:</p>
<pre><code>2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:39:43.427",
"Id": "434449",
"Score": "0",
"body": "@TobySpeight I only used `view::ints` a single time, does it deserve so much promotion? :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:01:23.527",
"Id": "434456",
"Score": "1",
"body": "Not really - I was just trying to find something different to give the question a unique title. I don't mind if you change it again. (I don't think the \"unique title\" rule works very well here on CR, unlike the other stacks...)"
}
] | [
{
"body": "<p>It may well be more efficient to compute <code>std::sqrt(max)</code> once upfront than to multiply <code>n * n</code> every time around the loop.</p>\n\n<p>Removing an element by value from the set is O(log <em>n</em>), where <em>n</em> is the set size at the time. This will likely make this method slower than writing to elements in a fixed-size storage (such as a <code>std::vector</code> that's never resized), and creating the return set from that. Also, <code>find()</code> is much slower than vector lookup.</p>\n\n<p>I think we can probably test <code>m * n <= max</code> instead of the more expensive <code>m <= max / n</code>, if we can arrange that the multiplication doesn't overflow. It will be fine if <code>2 * n < std::numeric_limits<number_t>::max() - max</code>. Also, no need to start at <code>2 * n</code> when removing - we can start at <code>n * n</code> instead, as all the lower multiples have already been removed due to their smaller factor(s).</p>\n\n<p>And a tiny improvement to the test code - we can stream a single character <code>'\\n'</code> to output rather than the string <code>\"\\n\"</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:28:58.083",
"Id": "434448",
"Score": "0",
"body": "How to make sure that `std::sqrt(max)` is decently accurate? I don't think a `uint_fast32_t` can be losslessly converted to `double` ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:07:18.907",
"Id": "434457",
"Score": "0",
"body": "That's a good question - you're right that there's only a lower bound on the size of `std::uint_fast32_t` and no upper bound. My instinct would be to simply round up the result using `std::ceil`, but you if you're sufficiently paranoid, you could always advance to the next representable value after that. Or, fall back to the `n * n` test using `||`, so the expensive version would only be evaluated the last time around the loop (or last two times if there's a rounding problem). (cont...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:08:57.807",
"Id": "434458",
"Score": "0",
"body": "... IOW, `auto const limit = static_cast<std::uint_fast32_t>(std::ceil(std::sqrt(max))); for (...; n <= limit || n * n <= max; ...)`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:14:13.720",
"Id": "224021",
"ParentId": "224019",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224021",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:05:51.840",
"Id": "224019",
"Score": "4",
"Tags": [
"c++",
"primes",
"c++17"
],
"Title": "Prime number sieve using ranges::view::ints"
} | 224019 |
<p>I am fairly new to C++ and programmed a maze game as an exercise. However, looking at it I can see it can be improved a lot. These are my requests if you don't mind:</p>
<ol>
<li>I do not want to use the library <code><conio.h></code>.</li>
<li>I want to use another method instead of <code>system("CLS")</code>.</li>
<li>This code is old; I think it has many unsafe codes in it and I cannot get used to C++11, C++17 etc. If you can help me update this game to the newer variants of C++, I would be more than happy.</li>
<li>In <code>main</code> function I just want to use function calling, so an <code>Update()</code> method would be nice.</li>
<li>OOP is highly appreciated.</li>
<li>Please do not hesitate to use advanced C++ like Lambda Expressions, auto type declarations etc. (see number 3). I don't know them yet, but I will try to understand.</li>
<li>Criticize like there is no tomorrow!</li>
</ol>
<pre><code>//maze game in console
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
// S: Start
// #: Wall
// .: Space
// F: Finish
// P: Player
const char maze[5][5]={{'#','S','#','#','#'},
{'#','.','.','#','#'},
{'#','#','.','#','#'},
{'#','.','.','.','#'},
{'#','#','#','F','#'}};
void Clear(){
system("CLS");//clear console
}
void InputHandle(int move, int &pX, int &pY){
switch(move=getch()){
case KEY_UP:
if( pY-1 >= 0 ){
if(maze[pY-1][pX] != '#'){//if it is not the limit or it is not the wall(#) move player
pY--;
}
}
break;
case KEY_DOWN:
if( pY+1 <= 4 ){
if(maze[pY+1][pX] != '#'){
pY++;
}
}
break;
case KEY_RIGHT:
if( pX+1 <= 4 ){
if(maze[pY][pX+1] != '#'){
pX++;
}
}
break;
case KEY_LEFT:
if( pX-1 >= 0 ){
if(maze[pY][pX-1] != '#'){
pX--;
}
}
}
}
void Display(int &pX, int &pY){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(j==pX && i==pY){//instead of the maze char, put player's 'P'
std::cout<<"P ";
continue;
}
std::cout<<maze[i][j]<<" ";
}
std::cout<<"\n";
}
}
bool CheckWinCondition(int &pX, int &pY){
if(pX==3 && pY ==4){
return true;
}
return false;
}
int main(){
//movement
int playerPosX=1;
int playerPosY=0;
int movement;
while(!CheckWinCondition(playerPosX,playerPosY)){//if player is not in the finish, loop
Display(playerPosX, playerPosY);//Show current maze
InputHandle(movement, playerPosX, playerPosY);//take input
Clear();//Clear the screen
}
std::cout<<"Congrats, you finished the maze!";
}
</code></pre>
| [] | [
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Use consistent formatting</h2>\n\n<p>The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently. </p>\n\n<h2>Use more whitespace</h2>\n\n<p>Lines like this one:</p>\n\n<pre><code>for(int i=0;i<5;i++){\n</code></pre>\n\n<p>are easier for most humans to read and understand with more whitespace like this:</p>\n\n<pre><code>for (int i = 0; i < 5; i++) {\n</code></pre>\n\n<h2>Don't use <code>system(\"cls\")</code></h2>\n\n<p>There are two reasons not to use <code>system(\"cls\")</code> or <code>system(\"pause\")</code>. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely <strong>must</strong> care about. Specifically, if some program is defined and named <code>cls</code> or <code>pause</code>, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions <code>cls()</code> and <code>pause()</code> and then modify your code to call those functions instead of <code>system</code>. Then rewrite the contents of those functions to do what you want using C++. For example, if your terminal supports <a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">ANSI Escape sequences</a>, you could use this:</p>\n\n<pre><code>void Clear()\n{\n std::cout << \"\\x1b[2J\";\n}\n</code></pre>\n\n<h2>Minimize the scope of variables</h2>\n\n<p>The variable <code>movement</code> is only used within <code>InputHandle</code>. This means that instead of a parameter, it could and should be a local variable within the member functions rather than a passed parameter.</p>\n\n<h2>Only update when needed</h2>\n\n<p>The current code updates the screen as fast as possible whether or not there's any reason to do so. This causes an annoying flicker on my computer and needlessly impedes the quick response of the program to user input. I'd suggest instead modifying the <code>InputHandle</code> routine to return a <code>bool</code> which is <code>true</code> only if the player's position has changed.</p>\n\n<h2>Prefer <code>std::array</code> to raw C-style arrays</h2>\n\n<p>Modern C++ provides <code>std::array</code> as an enhancement of a raw C array because it has knowledge of its own size, which helps with bounds checking.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>This code has a number of \"magic numbers,\" that is, unnamed constants such as 4, 5, etc. Generally it's better to avoid that and give such constants meaningful names. That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of \"5\" and then trying to determine if this <em>particular</em> 5 is relevant to the desired change or if it is some other constant that happens to have the same value.</p>\n\n<h2>Simplify your code</h2>\n\n<p>The current code contains this function:</p>\n\n<pre><code>bool CheckWinCondition(int &pX, int &pY)\n{\n if (pX == 3 && pY == 4) {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>This can be simplified:</p>\n\n<pre><code>bool CheckWinCondition(int &pX, int &pY)\n{\n return pX == 3 && pY == 4;\n}\n</code></pre>\n\n<h2>Use a portable library</h2>\n\n<p>You are right to want to eliminate the use of <code>conio.h</code> because it is neither standard nor portable. For example, your constants for keys don't work on my machine at all. One possible alternative would be to use the <code>ncurses</code> library. See <a href=\"https://codereview.stackexchange.com/questions/215366/ncurses-snake-game\">Ncurses Snake game</a> for inspiration on how to use the <code>ncurses</code> library in C++.</p>\n\n<h2>Use better names</h2>\n\n<p>The function <code>CheckWinCondition</code> and variable <code>maze</code> are good, descriptive names, but <code>InputHandle</code> and <code>pX</code> are not as good. I'd probably change <code>InputHandle</code> to <code>handleUserInput</code> and <code>pX</code> to simply <code>x</code>. Also, <code>CheckWinCondition</code> could be named <code>isPlayerAtGoal</code> to make it easy at a glance to understand what <code>true</code> and <code>false</code> might mean.</p>\n\n<h2>Don't use macros for constants</h2>\n\n<p>Instead of having <code>KEY_UP</code> and friends as old-style <code>#define</code> values, a better, more C++ approach is to use <code>constexpr</code> instead. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions\" rel=\"nofollow noreferrer\">ES.32</a> and <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#con5-use-constexpr-for-values-that-can-be-computed-at-compile-time\" rel=\"nofollow noreferrer\">Con.5</a>.</p>\n\n<h2>Use an object</h2>\n\n<p>The <code>Maze</code> would make a rather obvious object. It could include the maze structure, the player's current position and the goal's location. Methods (member functions) could include all of the current free-standing functions and the <code>main</code> could be reduced to this:</p>\n\n<pre><code>int main() {\n Maze maze;\n maze();\n}\n</code></pre>\n\n<h2>Further hints</h2>\n\n<p>Here's a rewritten <code>display()</code> function written using <code>ncurses</code> as a member function:</p>\n\n<pre><code>void Maze::display() const \n{\n clear();\n for (int row = 0; row < height; row++) {\n for (int col = 0; col < width; col++) {\n addch(tokenAt(row, col));\n addch(' ');\n }\n addch('\\n');\n }\n}\n</code></pre>\n\n<p>The <code>clear()</code> and <code>addch()</code> functions are from <code>ncurses</code> and <code>tokenAt()</code> looks like this:</p>\n\n<pre><code>char Maze::tokenAt(int row, int col) const {\n return (col == x && row == y) ? 'P' : maze[row][col];\n}\n</code></pre>\n\n<p>Here's the member function that actually runs the maze:</p>\n\n<pre><code>void Maze::operator()() {\n initscr();\n noecho();\n nodelay(stdscr, TRUE);\n keypad(stdscr, TRUE);\n display(); \n while (!isPlayerAtGoal()) { \n if (handleUserInput()) {\n display();\n }\n }\n endwin();\n std::cout << \"Congrats, you finished the maze!\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T06:33:06.353",
"Id": "434582",
"Score": "0",
"body": "Thank you, this is a good critique, any ideas for OOP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T06:51:50.627",
"Id": "434583",
"Score": "0",
"body": "Also, I learned that my terminal doesn't support ASCII codes, is there another way of getting rid of system(\"CLS\")?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T13:40:30.413",
"Id": "434606",
"Score": "1",
"body": "I've added to my answer to help answer those questions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:38:44.377",
"Id": "224035",
"ParentId": "224020",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224035",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:13:09.257",
"Id": "224020",
"Score": "2",
"Tags": [
"c++",
"game",
"console"
],
"Title": "Simple Console Maze Game"
} | 224020 |
<p>The goal of the following code is to calculate the mean and the standard error of vectors of randomly-generated numbers. I am looking for feedback both on the correctness of the calculation, and on its efficiency. </p>
<pre><code>import numpy as np
def mean_and_stderr(num_of_iterations:int, instance_generator) -> (float,float):
"""
Calculate the mean and standard error of the given generator.
:param instance_generator: a function that accepts no parameters,
and returns either a float or a numpy array.
:param num_of_iterations: number of times to run the instance_generator.
:return a tuple: (mean, standard_error)
Test on a degenerate (constant) generator of numbers:
>>> generator = lambda: 5
>>> mean_and_stderr(100, generator)
(5.0, 0.0)
Test on a degenerate (constant) generator of vectors:
>>> generator = lambda: np.array([1,2,3])
>>> mean_and_stderr(100, generator)
(array([ 1., 2., 3.]), array([ 0., 0., 0.]))
"""
sum = sumSquares = None
for i in range(num_of_iterations):
x_i = generator()
if sum is None:
sum = x_i
sumSquares = (x_i*x_i)
else:
sum += x_i
sumSquares += (x_i * x_i)
mean = sum / num_of_iterations
variance = sumSquares / num_of_iterations - (mean*mean)
stderr = np.sqrt(variance) / num_of_iterations
return (mean,stderr)
if __name__=="__main__":
generate_uniformly_random_number = np.random.random
print(mean_and_stderr(10, generate_uniformly_random_number))
# Typical output: (0.5863703739913031, 0.026898107452102943)
print(mean_and_stderr(1000, generate_uniformly_random_number))
# Typical output: (0.514204422858358, 0.0002934476865378269)
generate_uniformly_random_vector = lambda: np.random.random(3)
print(mean_and_stderr(10, generate_uniformly_random_vector))
# Typical output: (array([ 0.53731682, 0.6284966 , 0.48811251]), array([ 0.02897111, 0.0262977 , 0.03192519]))
print(mean_and_stderr(1000, generate_uniformly_random_vector))
# Typical output: (array([ 0.50520085, 0.49944188, 0.50034895]), array([ 0.00028528, 0.00028707, 0.00029089]))
</code></pre>
| [] | [
{
"body": "<p>I'd want to address the <code>generator</code>, to begin. <code>:param generator: accepts no parameters and returns a vector</code> is false. The generator returns a number (with floating point or not). This is pretty confusing. When I read the code at first, I thought the generator would be an iterable that returns numbers (like <code>range(0,10)</code> for example). </p>\n\n<p>In that case you wouldn't need to pass both the parameters <code>num_of_iterations</code> and <code>generators</code>. Otherwise, I don't think the parameter should be named <code>generator</code> or maybe your documentation should be stronger.</p>\n\n<p>Next thing, you shouldn't initialize <code>sum = sumSquares = None</code> this way. They are numbers, initialize them at zero, that would give you the opportunity to remove your if/else.</p>\n\n<pre><code>sum = sumSquares = 0\nfor i in range(num_of_iterations):\n x_i = generator()\n sum += x_i\n sumSquares = (x_i*x_i)\n</code></pre>\n\n<p>Apart from that, the coding style is a little off. Sometimes you use <code>camelCase</code> and sometimes <code>snake_case</code>.</p>\n\n<p>If we were to have an iterator instead of the generator, you could do something like this : </p>\n\n<pre><code>def mean_and_stderr(iterator) -> (float,float):\n sum = sumSquares = 0\n for x in iterator:\n sum = x\n sumSquares = (x*x)\n\n mean = sum / num_of_iterations\n variance = sumSquares / num_of_iterations - (mean*mean)\n stderr = np.sqrt(variance) / num_of_iterations\n return (mean,stderr)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:33:32.810",
"Id": "434493",
"Score": "1",
"body": "I think `whatever_that_is_case` is called `snake_case` (https://en.wikipedia.org/wiki/Snake_case)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:34:13.567",
"Id": "434495",
"Score": "0",
"body": "@AlexV thanks that's fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:46:27.500",
"Id": "434498",
"Score": "1",
"body": "It seems like the Python style guide itself refers to that style as [`lower_case_with_underscores`](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles). But it doesn't really matter :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:23:20.583",
"Id": "434640",
"Score": "0",
"body": "Thanks for the comments. Probably my use of the word \"generator\" was confusing. I meant generator in this sense: https://en.cppreference.com/w/cpp/algorithm/generate i.e., a function without parameters. Like in the phrase \"random number *generator*\". Can you suggest a less ambiguous term? \nAlso, the reason I initialize to None is that my \"generator\" can return not only a single number, but also a numpy array. See the second example in the doctest and the second example in the main program. Is there a more efficient way to handle both numbers and arrays in the same function?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:52:13.097",
"Id": "224039",
"ParentId": "224025",
"Score": "1"
}
},
{
"body": "<h3>Formulas are flawed</h3>\n\n<p>Both these formulas are incorrect. They seem made up variants of the correct ones.</p>\n\n<blockquote>\n<pre><code> variance = sumSquares / num_of_iterations - (mean*mean) \n stderr = np.sqrt(variance) / num_of_iterations\n</code></pre>\n</blockquote>\n\n<p>Here are the correct formulas:</p>\n\n<p><span class=\"math-container\">$$ \\newcommand{smallm}[0]{\\overset{n\\ \\gg\\ m}{\\longrightarrow}} \\begin{array}{|l|c|c|}\n \\hline \\\\\n & \\textrm{Formula} \\\\ \n \\hline \\\\ \\textrm{Variance} & \\sigma² = \\frac{1}{N}\\sum_{i=1}^N(x_i - \\mu)^2 \\\\ \n \\hline \\\\ \\textrm{Standard Deviation} & \\sigma = \\sqrt{\\sigma²} \\\\\n \\hline \\\\ \\textrm{Standard Error} & {\\sigma}_\\bar{x}\\ = \\frac{\\sigma}{\\sqrt{n}} \\\\\n \\hline \\end{array}$$</span></p>\n\n<h3>Verification</h3>\n\n<p>Tool used to verify: <a href=\"https://www.miniwebtool.com/standard-error-calculator/\" rel=\"nofollow noreferrer\">Online Standard Error Calculator</a></p>\n\n<p>Note that the online test is compliant to a sample space, not an entire population. \nThis means the formula used for variance is slightly different to take into account outliers: </p>\n\n<p><span class=\"math-container\">$$s² = \\frac{1}{n-1}\\sum_{i=1}^n(x_i - \\bar{x})^2$$</span></p>\n\n<p>Let's take a fixed input array to test your formulas.</p>\n\n<pre><code> input array: { 0, 0, 1, 2, 3, 12 }\n</code></pre>\n\n<p><span class=\"math-container\">$$ \\newcommand{smallm}[0]{\\overset{n\\ \\gg\\ m}{\\longrightarrow}} \\begin{array}{|l|c|c|}\n \\hline \\\\\n & \\textrm{Mean} & \\textrm{Standard Error} \\\\ \n \\hline \\\\ \\textrm{OP} & \\color{blue}{3} & \\color{red}{0.693888666488711} \\\\ \n \\hline \\\\ \\textrm{Corrected (sample space)} & \\color{blue}{3} & \\color{blue}{1.69967317119759} \\\\ \n \\hline \\\\ \\textrm{Corrected (population)} & \\color{blue}{3} & \\color{blue}{1.8618986725} \\\\ \n \\hline \\end{array}$$</span></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:01:04.103",
"Id": "434643",
"Score": "1",
"body": "Thanks a lot! You saved me from a severe bug. I did not use the standard formulas since they require to do two passes on the data: one to calculate the mean $\\mu$, and one to calculate the variance $\\sigma^2$. Now, I found a way to do the correct calculation in a single pass: \nmean = sum / num_of_iterations;\npopulation_variance = sumSquares / num_of_iterations - (mean * mean);\nsample_variance = population_variance*num_of_iterations/(num_of_iterations-1);\nstderr = np.sqrt(sample_variance / num_of_iterations);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:07:01.573",
"Id": "434644",
"Score": "0",
"body": "Glad to have been of assistance: this MathJax library was not easy to use :) For future questions, I would suggest you add unit tests to your code. This way you can find bugs like this from the get-go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:41:24.000",
"Id": "434648",
"Score": "0",
"body": "@ErelSegal-Halevi Btw, read the answers on this question for a single pass calculation of both mean and variance: https://codereview.stackexchange.com/questions/185450/compute-mean-variance-and-standard-deviation-of-csv-number-file?rq=1"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:28:00.737",
"Id": "224045",
"ParentId": "224025",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224045",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T11:53:16.073",
"Id": "224025",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"numpy",
"statistics"
],
"Title": "Calculate mean and standard error of a generator in Python"
} | 224025 |
<p>As an update (conversion) to my article “<a href="https://codereview.stackexchange.com/questions/223936/simple-number-to-words-using-a-single-loop-string-triplets-in-javascript">Simple Number to Words using a Single Loop String Triplets in JavaScript</a>” in JavaScript, I have converted the code to work as a VBA function using the same method of "<strong>Single Loop String Triplets</strong>".</p>
<p>The explanation of how it works is detailed in the above reference article with images and examples.</p>
<p>The function is for unsigned integers. But may be called twice for whole and fractional parts after a number split at the decimal point. Also currency and sub-currency words could be added easily if a whole/fractional split is made.</p>
<p><strong>It is not intended for the function to check for bad inputs, negative numbers, decimals, etc. as this could be left to a another higher function that will call this function, therefore the following are not accounted for simplicity:</strong></p>
<p><strong>- No checks for negative numbers.</strong></p>
<p><strong>- No checks for non-number (NaN) strings/data.</strong></p>
<p><strong>- No checks or conversion for exponential notations.</strong></p>
<p>However, large numbers can be passed as a String if necessary.</p>
<p>The “scle” Array may be increased by adding additional scales above “Decillion”.</p>
<p>Examples:</p>
<pre><code>Debug.Print NumToWordsUnsignedInt(777112999)
'Output:
'Seven Hundred Seventy-Seven Million One Hundred Twelve Thousand Nine Hundred Ninety-Nine
Debug.Print NumToWordsUnsignedInt(“222111333444555666777888999111222333”)
'Output:
'Two Hundred Twenty-Two Decillion One Hundred Eleven Nonillion Three Hundred Thirty-Three Octillion Four Hundred Forty-Four Septillion Five Hundred Fifty-Five Sextillion Six Hundred Sixty-Six Quintillion Seven Hundred Seventy-Seven Quadrillion Eight Hundred Eighty-Eight Trillion Nine Hundred Ninety-Nine Billion One Hundred Eleven Million Two Hundred Twenty-Two Thousand Three Hundred Thirty-Three
</code></pre>
<p>I would like the code to be reviewed for any bugs, optimization, or improvements. I am sure there is room for improvements and corrections.</p>
<p>Thanks in advance.</p>
<p>Mohsen Alyafei </p>
<pre><code>Function NumToWordsUnsignedInt(ByVal NumIn As String)
'-------------------------------------------------------------
'Convert Unsigned Integer Number to English Words (US System)
'Using a Single Loop String Triplets (SLST) Method
'Mohsen Alyafei 10 July 2019
'Call it separately for a whole number and a fraction
'-------------------------------------------------------------
Dim Ones(), Tens(), Scle(), Sep, NumAll As String, t As String, N1 As Integer, N2 As Integer, Triplet, L, i, j
Ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
Scle = Array("", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion")
NumIn = String((Len(NumIn) * 2) Mod 3, "0") & NumIn 'Create shortest string Triplets (0 padded)
L = Len(NumIn) / 3 - 1: j = 1 'Get total no. of Triplets and init count into Triplets
For i = L To 0 Step -1 'Loop starting with Most Signifct Triplet (MST)
Triplet = Mid(NumIn, j, 3) 'Get a Triplet starting from LH
If Triplet <> "000" Then 'Skip empty Triplets
Sep = IIf(Right(Triplet, 1) <> "0", "-", "") 'Only if hyphen needed for nums 21 to 99
N1 = Left(Triplet, 1): N2 = Right(Triplet, 2) 'Get Hundreds digit and 2 lowest digits (00 to 99)
'First Spell the 2 lowest digits in N2
If N2 > 19 Then t = Tens(Val(Mid(Triplet, 2, 1))) & Sep & Ones(Val(Right(Triplet, 1))) Else t = Ones(N2)
'Add " hundred" if needed, Create number with scale, and join the Triplet scales to previous
NumAll = NumAll & Trim(IIf(N1 > 0, Ones(N1) & " Hundred", "") & " " & t) & " " & Scle(i) & " "
End If
j = j + 3 'Point to next Triplet position
Next 'Go for next lower Triplets (move to RH)
NumToWordsUnsignedInt = Trim(NumAll) 'Return trimming excess spaces
End Function
</code></pre>
<h2>EDIT 1: Variables Re-Naming for better readability</h2>
<p>Variable names updated based on sugegstions.</p>
<pre><code>'-------------------------------------------------------------
Function NumToWordsUnsignedInt(ByVal NumIn As String)
'-------------------------------------------------------------
'Convert Unsigned Integer Number to English Words (US System)
'Using a Single Loop String Triplets (SLST) Method
'Mohsen Alyafei 12 July 2019
'Call it separately for a whole number and a fraction
'-------------------------------------------------------------
Dim Ones(), tens(), Scle(), Sep, NumAll, W_Tens, Triplet, TotalTriplets, i, TripletPos
Dim N_Hundrds As Integer, N_Tens As Integer
Ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
Scle = Array("", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion")
NumIn = String((Len(NumIn) * 2) Mod 3, "0") & NumIn 'Create shortest string Triplets (0 padded)
TotalTriplets = Len(NumIn) / 3 - 1: TripletPos = 1 'Get total no. of Triplets and init count into Triplets
For i = TotalTriplets To 0 Step -1 'Loop starting with Most Signifct Triplet (MST)
Triplet = Mid(NumIn, TripletPos, 3) 'Get a Triplet starting from LH
If Triplet <> "000" Then 'Skip empty Triplets
Sep = IIf(Right(Triplet, 1) <> "0", "-", "") 'Only if hyphen needed for nums 21 to 99
N_Hundrds = Left(Triplet, 1) 'Get the Hundreds digit
N_Tens = Right(Triplet, 2) 'Get 2 lowest digits (00 to 99)
'First Spell the 2 lowest digits in N_Tens into W_Tens
If N_Tens > 19 Then W_Tens = tens(Val(Mid(Triplet, 2, 1))) & Sep & Ones(Val(Right(Triplet, 1))) Else W_Tens = Ones(N_Tens)
'Add " hundred" if needed, Create number with scale, and join the Triplet scales to previous
NumAll = NumAll & Trim(IIf(N_Hundrds > 0, Ones(N_Hundrds) & " Hundred", "") & " " & W_Tens) & " " & Scle(i) & " "
End If
TripletPos = TripletPos + 3 'Point to next Triplet position
Next 'Go for next lower Triplets (move to RH)
NumToWordsUnsignedInt = Trim(NumAll) 'Return trimming excess spaces
End Function
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:08:54.420",
"Id": "434462",
"Score": "3",
"body": "Right off the bat, `Dim Ones(), Tens(), Scle(), Sep, NumAll As String` produces 3 `Variant` arrays, one `Variant` and one `String` variable. The code will, of course work with `Variants`, but if they're all expected to be `String`, then skipping the implicit conversion of `Variant` to `String` will improve performance and readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:36:17.543",
"Id": "434467",
"Score": "0",
"body": "@FreeMan Agree. Thanks. The same would apply to the variable \"t\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:14:29.410",
"Id": "434470",
"Score": "2",
"body": "Actually, `T` is declared `String`. `Triplet, L, i, j` however are all `Variant`. I'd strongly recommend some better names for those single letter variables - what _is_ `T`, anyway? `i` is OK as a loop index (pretty darn conventional), but `L`?, `j`? those are meaningless. `N1` and `N2` are pretty... vague as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:55:16.840",
"Id": "434500",
"Score": "0",
"body": "@FreeMan Thanks. I have updated the code (additional separate edit) with more meaningfull var names for better understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:00:28.130",
"Id": "434503",
"Score": "1",
"body": "One of the rules of CR is to not edit your code based upon the reviews. Having posted it as a separate section might be ok"
}
] | [
{
"body": "<p>A function should Do One Thing Well.</p>\n\n<p>Yes, this function <em>does</em> have a single stated goal.\nBut accomplishing that breaks down quite naturally into the goals of:</p>\n\n<ol>\n<li><code>SmallNumToWords(n)</code>, for input 0 <= <code>n</code> <= 999.</li>\n<li><code>NumToWords(n)</code> for non-negative <code>n</code>, which repeatedly breaks out small <code>n</code> and calls the helper function.</li>\n</ol>\n\n<p>Adding several unit tests would be a boon to the casual reader.</p>\n\n<p>Numbers a little bigger than ten are slightly annoying, granted.\nBut since they \"escaped\" from the one's place,\nperhaps <code>Small</code> would be a more accurate identifier?</p>\n\n<p>Pat Sajack would be happy to let you use <code>Scale</code>,\nyou don't even have to buy a vowel.</p>\n\n<p>nit: <code>Tens</code> would be more consistent with how you spelled the other identifiers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:30:58.407",
"Id": "434702",
"Score": "0",
"body": "thanks for your suggestions and advice. I started the inner part as function delaing with numbers from 000 to 999 only (i.e. one Triplet) (see this article https://codereview.stackexchange.com/questions/223615/very-simple-spell-number-to-words-001-to-999-in-vba) and the principal code liner to **create the string Triplets** was a separate article too here: https://stackoverflow.com/questions/56876655/padding-a-number-string-with-zeros-to-remain-as-a-multiple-of-3s-in-length. Each element was tested separately to ensure accuracy. Thanks again. The SLST metod spec (as I call it) is great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:32:27.347",
"Id": "434703",
"Score": "0",
"body": "The method can be easily adapted for Asian number conversion as they use Twins instead of Triplets above numbers of 99 thousand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T17:19:05.600",
"Id": "435202",
"Score": "2",
"body": "@MohsenAlyafei consider using an actual unit testing framework for the tests. [Rubberduck](http://rubberduckvba.com) has a boilerplate-free one that's fairly simple to use (full disclaimer: I own that website; Rubberduck is free and open-source)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-18T16:29:56.730",
"Id": "435380",
"Score": "1",
"body": "@MathieuGuindon Thanks. Great App, was looking for such an app for VBA. Just downloaded it and experimenting :-)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:50:02.020",
"Id": "224110",
"ParentId": "224027",
"Score": "4"
}
},
{
"body": "<p>A couple of things:\n- Some the non-variant variables data types are not declared\n- Avoid using underscores in variable names<br>\n- NumToWordsUnsignedInt reads as \"Number To Words Unsigned Int\" and that just doesn't make sense\n- I use IIF() quite often myself but it can take away from the readability of the code\n- Ones should be renamed because it contains numbers 1 to 19\n- <code>NumIn, NumAll</code> are very good variable names. Personally, I choose to use the same set of variable names for all my work (such as: value, values, data, result, results, source, target). I see value in my code I know that it is a single scalar value that I am working with. Values and data are arrays. Result is a scalar value that will generally be returned. Results is a array that will generally be returned. These variables names are also part of several patterns that I have memorized. Reusing these patterns speeds up the reading and writing of my code.</p>\n\n<h2>Refactored Code</h2>\n\n<p>With all the hard work done by the OP, this is how I would write the function:</p>\n\n<pre><code>Function NumbersToWords(ByVal Value As String)\n Dim nHundreds As Long, nOnes As Long, nTens As Long, nScale As Long, n As Long\n Dim result As String\n Dim Small(), Tens(), Scle()\n Small = Array(\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\")\n Tens = Array(\"\", \"\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\")\n Scle = Array(\"\", \"Thousand\", \"Million\", \"Billion\", \"Trillion\", \"Quadrillion\", \"Quintillion\", \"Sextillion\", \"Septillion\", \"Octillion\", \"Nonillion\", \"Decillion\")\n\n\n Value = String((Len(Value) * 2) Mod 3, \"0\") & Value 'Create shortest string Triplets (0 padded)\n\n For n = Len(Value) To 1 Step -3\n nOnes = Mid(Value, n - 2, 1)\n nTens = Mid(Value, n - 1, 1)\n nHundreds = Mid(Value, n, 1)\n If nScale > 0 Then result = Scle(nScale) & Space(1) & result\n\n If nOnes + nTens + nHundreds = 0 Then\n 'Skip Empty Triplet\n ElseIf nTens >= 2 And nOnes = 0 Then\n result = Tens(nTens) & Space(1) & result\n ElseIf nTens >= 2 Then\n result = Tens(nTens) & \"-\" & Small(nOnes) & Space(1) & result\n ElseIf nOnes > 0 Or nTens > 0 Then\n result = Small(nTens * 10 + nOnes) & Space(1) & result\n End If\n\n If nHundreds > 0 Then result = Small(nHundreds) & \" Hundred \" & result\n\n nScale = nScale + 1\n\n Next\n\n NumbersToWords = Trim(result)\n\nEnd Function\n</code></pre>\n\n<p>Edited per Roland Illig comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T09:12:46.077",
"Id": "434693",
"Score": "0",
"body": "Thanks for the alternative method and your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:04:21.673",
"Id": "434695",
"Score": "1",
"body": "@MohsenAlyafei it was may pleasure. Good job by the way. I originally started to write a recursive function but noticed gave up after I reread your specifications. It was a bit of a pain to do from scratch anyhow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:20:45.420",
"Id": "434715",
"Score": "0",
"body": "`(Len(Value) * 2) Mod 3` is really bad style. Calculating the number of missing digits has nothing to do with multiplying by 2. It is only by coincidence that this formula has the indented results. This is codereview, not codegolf."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:49:39.903",
"Id": "434718",
"Score": "0",
"body": "@RolandIllig the formula is not coincidental it is a formual that functions for any Multiple and is (I believe very sound) It is : (Len (value) * (Multiple-1)) Mod Multiple), please see this article for more details with answer at the end of the article: https://stackoverflow.com/questions/56876655/padding-a-number-string-with-zeros-to-remain-as-a-multiple-of-3s-in-length"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T14:31:04.987",
"Id": "434721",
"Score": "1",
"body": "@MohsenAlyafei ah, ok, my bad. I did not read the 2 as `n-1` but as being 2 for all cases, which would not have worked. Thanks for the explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T14:47:54.360",
"Id": "434725",
"Score": "0",
"body": "@RolandIllig The negative number made sense before I added the padding to the input value. Otherwise, the loop would skip the first Triplet. I edited my post because I agree that it was a bad practice as it was being used."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T05:29:15.303",
"Id": "224135",
"ParentId": "224027",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:17:47.900",
"Id": "224027",
"Score": "4",
"Tags": [
"vba",
"numbers-to-words"
],
"Title": "Simple Number to Words using a Single Loop String Triplets in VBA"
} | 224027 |
<blockquote>
<p>A bishop can capture any other bishop if it lies along the same
diagonal line, so long as no other bishop is in its path.
Given a list of coordinates of the bishops locations, and a board size, determine how many bishops are unsafe. </p>
</blockquote>
<p>This code has a time complexity of <span class="math-container">\$O(N*K)\$</span> where N is the number of bishops, K is (N- current index). </p>
<p>Is there a way to improve this? </p>
<pre><code>bishops = [(0, 0),
(1, 1),
(0, 2),
(1, 3),
(2, 0),
(2, 2)]
size = 5
moves = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
captured = []
for index, coordinates in enumerate(bishops):
remaining = bishops[index + 1:]
seen = bishops[:index + 1]
for dx, dy in moves:
x, y = coordinates
while 0 <= x + dx < size and 0 <= y + dy < size:
x += dx
y += dy
if (x, y) in seen:
break
if (x, y) in remaining:
remaining.remove((x, y))
capture = f"{coordinates} takes {x, y}"
captured.append(capture)
break
print(f"There are {len(captured)} moves")
print(*captured, sep = "\n")
</code></pre>
| [] | [
{
"body": "<h2>O(n)</h2>\n\n<p>You can transform the (row,column) coordinate of a bishop to a (row+column, row-column) coordinate. The row+column coordinate tells you which upper-left to lower right diagonal the bishop is on. The row-column coordinate tells you which upper-right to lower-left diagonal the bishop is on. </p>\n\n<pre><code> row + col row - col\n7 8 9 10 11 12 13 14 7 6 5 4 3 2 1 0\n6 7 8 9 10 11 12 13 6 5 4 3 2 1 0 -1\n5 6 7 8 9 10 11 12 5 4 3 2 1 0 -1 -2\n4 5 6 7 8 9 10 11 4 3 2 1 0 -1 -2 -3\n3 4 5 6 7 8 9 10 3 2 1 0 -1 -2 -3 -4\n2 3 4 5 6 7 8 9 2 1 0 -1 -2 -3 -4 -5\n1 2 3 4 5 6 7 8 1 0 -1 -2 -3 -4 -5 -6\n0 1 2 3 4 5 6 7 0 -1 -2 -3 -4 -5 -6 -7\n</code></pre>\n\n<p>Now create two dictionaries. One that maps each row+col value to a list of bishops on that diagonal. The other one similarly maps the row-col value. Any dict entry with more than one bishop, means all of those bishops are in danger.</p>\n\n<pre><code>bishops = [(0, 0),\n (1, 1),\n (0, 2),\n (1, 3),\n (2, 0),\n (2, 2)]\n\nnwse = {}\nnesw = {}\n\nfor row,col in bishops:\n nwse_index = row + col\n if nwse_index not in nwse:\n nwse[nwse_index] = [(row,col)]\n else:\n nwse[nwse_index].append((row,col))\n\n nesw_index = row - col\n if nesw_index not in nesw:\n nesw[nesw_index] = [(row,col)]\n else:\n nesw[nesw_index].append((row,col))\n\nin_danger = set()\n\nfor k,v in nwse.items():\n if len(v) > 1:\n in_danger.update(v)\n\nfor k,v in nesw.items():\n if len(v) > 1:\n in_danger.update(v)\n\nsafe_bishops = set(bishops) - in_danger\n\nprint(len(safe_bishops))\n</code></pre>\n\n<h2>Improved code</h2>\n\n<p>based on AJNeuman's answer and my comment below.</p>\n\n<p>The row - col index is offset by adding -8 so that all the values will be < 0.\nThe row + col index are all > 0. So just one dict is needed.</p>\n\n<pre><code>from collections import defaultdict\n\nbishops = [(0, 0),\n (1, 1),\n (0, 2),\n (1, 3),\n (2, 0),\n (2, 2)]\n\n\noccupied_diagonals = defaultdict(list)\n\nfor bishop in bishops:\n row, col = bishop\n occupied_diagonals[row + col].append(bishop)\n occupied_diagonals[row - col - 8].append(bishop)\n\nin_danger = set()\n\nfor bishop_list in occupied_diagonals.values():\n if len(bishop_list) > 1:\n in_danger.update(bishop_list)\n\nprint(len(in_danger))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:34:42.957",
"Id": "434549",
"Score": "0",
"body": "A nice answer (+1), but it could use [improvement](https://codereview.stackexchange.com/a/224060/100620)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:54:48.413",
"Id": "434552",
"Score": "0",
"body": "@AJNeufeld, yes, lots of room for improvement. I don't know the skill level of OP and wanted to explain it simply without a lot of things that might be new. It could use a defaultdict. And if you offset one of the \"diagonal\" indexes (e.g add -8 to the row-column) so the numbers don't overlap, it would only need one dict. That would cut the code in half."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:10:10.987",
"Id": "434741",
"Score": "0",
"body": "While I like the reduction in code, I dislike the magic number `-8`. The code will no longer work for larger (or infinite) boards. You could fix this by subtracting `max(row)+1`. Alternately, you could turn the indices into strings `f\"/{row+col}\"` and `fr\"\\{row-col}\"`, adding a leading `/` for indices on one diagonal, and \\ for the other. Or you could multiply the indices by 2, and then add 1 to partition by even/odd: `(row+col)*2` & `(row-col)*2+1`. Or, you could partition by int/str with `row+col` and `str(row-col)` or by int/float by adding `+0.5`, depending on how hacky you want to be."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:57:19.993",
"Id": "224052",
"ParentId": "224028",
"Score": "7"
}
},
{
"body": "<p>If bishop <code>X</code>, <code>Y</code> & <code>Z</code> are all on a diagonal, <code>X</code> can capture <code>Y</code>, <code>Y</code> can capture both <code>X</code> & <code>Z</code>, and <code>Z</code> can capture <code>Y</code>. All 3 are unsafe. If the problem has <em>no requirement to determine exactly which bishop captures which bishops</em> -- just determine the number which could be captured -- then you don't need to move each bishop along the each of the four <code>dx, dy in moves</code> directions until it encounters another bishop. That is just mechanical busy work.</p>\n\n<p>A bishop <code>X</code> is unsafe if any other bishop <code>Y</code> satisfies either (or both) of the following:</p>\n\n<ul>\n<li><code>bishop[X][0] + bishop[X][1] == bishop[Y][0] + bishop[Y][1]</code>, or</li>\n<li><code>bishop[X][0] - bishop[X][1] == bishop[Y][0] - bishop[Y][1]</code>.</li>\n</ul>\n\n<p>You can partition the bishops according to diagonals. If two or more bishops are on the same diagonal, all of those bishops are unsafe.</p>\n\n<p>Note that the <code>size</code> of the board is unnecessary.</p>\n\n<hr>\n\n<p>The following is a review of and improvement upon <a href=\"https://codereview.stackexchange.com/a/224052/100620\">@RootTwo's answer</a>.</p>\n\n<p>A vanilla dictionary is a poor choice for <code>nwse</code> and <code>nesw</code>. That requires you check if the diagonal index has already been created in the dictionary, to determine whether to store a new list in the dictionary, or to appended to the existing list. A better option is to use <a href=\"https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a>, which automatically creates the entry using the provided default if that entry is not present:</p>\n\n<pre><code>from collections import defaultdict\n\nnwse = defaultdict(list)\nnesw = defaultdict(list)\n</code></pre>\n\n<p>The <code>bishops</code> is already a collection of <code>tuple</code> coordinates. Creating your own tuples in <code>= [(row,col)]</code> and <code>.append((row,col))</code> is creating new objects identical to the existing ones in everything except identity. There is no need to pollute the memory with these new tuples; just reuse the existing ones:</p>\n\n<pre><code>for bishop in bishops:\n row, col = bishop\n nwse[row + col].append(bishop)\n nesw[row - col].append(bishop)\n</code></pre>\n\n<p>The <code>for k,v in nwse.items():</code> loop never uses the dictionary key value (<code>k</code>) in the body of the loop. It makes no sense to extract it from the dictionary. Just loop over the <code>values()</code> of the dictionaries:</p>\n\n<pre><code>in_danger = set()\n\nfor v in nwse.values():\n if len(v) > 1:\n in_danger.update(v)\n\nfor v in nesw.values():\n if len(v) > 1:\n in_danger.update(v)\n</code></pre>\n\n<p>The problem asks for \"how many bishops are unsafe\", not the number that are safe. So the output should be:</p>\n\n<pre><code>print(len(in_danger))\n</code></pre>\n\n<p>Finally, follow the PEP-8 standards. Specifically, you need a space after all of your commas.</p>\n\n<pre><code>from collections import defaultdict\n\nbishops = [(0, 0),\n (1, 1),\n (0, 2),\n (1, 3),\n (2, 0),\n (2, 2)]\n\nnwse = defaultdict(list)\nnesw = defaultdict(list)\n\nfor bishop in bishops:\n row, col = bishop\n nwse[row + col].append(bishop)\n nesw[row - col].append(bishop)\n\nin_danger = set()\n\nfor v in nwse.values():\n if len(v) > 1:\n in_danger.update(v)\n\nfor v in nesw.values():\n if len(v) > 1:\n in_danger.update(v)\n\nprint(len(in_danger))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:32:36.870",
"Id": "224060",
"ParentId": "224028",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "224060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T12:36:51.403",
"Id": "224028",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"chess"
],
"Title": "Bishop game - python"
} | 224028 |
<p>I have a very simlpe app built using Kivy, for performing bootstrap algorithm (statistics). We must input some samples in the form <code>x1,x2,...,xn</code> (these will be received as a string <code>"x1,...,xn"</code> but then will be transformed into a list of the samples. From these samples, we will perform the bootstrap algorithm to approximate the population's sampling mean distribution. </p>
<p>We have the main widget using <code>Widget</code> class, and we put a grid layout of 1 row, 2 columns (left one will be for the options, right one will be the plot of the disribution). For the option grid, we put another 4x4 grid layout, with the last grid be a 3x1 grid layout consisting the buttons for the result.</p>
<p>I wonder if there are better and efficient ways to write the code to perform the app.</p>
<hr>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/F2AZF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F2AZF.png" alt="enter image description here"></a></p>
<hr>
<p>Code:</p>
<pre><code>import random
import matplotlib.pyplot as plt
from kivy.config import Config
Config.set('graphics', 'resizable', False)
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
Window.clearcolor = (0,0.5,0.9,0.1)
Window.size = (800, 400)
#Bootstrap Method:
class BootstrapMethod(object):
def __init__(self):
self.start_button = BootstrapButton(text = "Bootstrap")
self.layout = BootstrapGrid()
self.options = BootstrapOptions()
class RunButtonLayout(GridLayout):
def __init__(self):
super().__init__(rows=3, cols=1)
self.add_widget(PlotNormed(text="Normed histogram"))
self.add_widget(PlotActual(text="Actual histogram"))
self.add_widget(BootstrapButton(text="Run bootstrap"))
class PlotNormed(Button):
def on_release(self):
xbars = self.parent.parent.parent.xbars
if xbars != None:
self.parent.parent.parent.ax.cla()
self.parent.parent.parent.ax.hist(xbars, normed = True)
self.parent.parent.parent.fig.figure.canvas.draw()
class PlotActual(Button):
def on_release(self):
xbars = self.parent.parent.parent.xbars
if xbars != None:
self.parent.parent.parent.ax.cla()
self.parent.parent.parent.ax.hist(xbars)
self.parent.parent.parent.fig.figure.canvas.draw()
class BootstrapButton(Button):
def on_release(self):
super().on_release()
sample_string = self.parent.parent.sample_input.text.split(',')
self.samples = [float(i) for i in sample_string]
self.bootstrap_algorithm()
def bootstrap_algorithm(self):
xbars = []
n = int(self.parent.parent.bootstrap_sample.text)
if n > len(self.samples):
n = len(self.samples)
nb = int(self.parent.parent.bootstrap_iteration.text)
for i in range(nb):
xbar = sum([random.sample(self.samples, 1)[0] for j in range(n)])/n
xbars.append(xbar)
self.parent.parent.parent.xbars = xbars
self.parent.parent.parent.ax.cla()
self.parent.parent.parent.ax.hist(xbars)
self.parent.parent.parent.fig.figure.canvas.draw()
class BootstrapOptions(GridLayout):
def __init__(self):
super().__init__(rows=2, cols=2)
self.sample_input = TextInput(text = "Sample input")
self.bootstrap_iteration = TextInput(text = "Number of bootstrap iterations")
self.bootstrap_sample = TextInput(text = "Number of sample for resampling")
self.run_layout = RunButtonLayout()
self.add_widget(self.sample_input)
self.add_widget(self.bootstrap_iteration)
self.add_widget(self.bootstrap_sample)
self.add_widget(self.run_layout)
class BootstrapGrid(GridLayout):
def __init__(self):
super().__init__(rows=1, cols=2, padding = 5, spacing = 5)
fig, ax = plt.subplots()
self.options = BootstrapOptions()
self.add_widget(self.options)
self.fig = FigureCanvasKivyAgg(fig)
self.ax = ax
self.add_widget(self.fig)
self.xbars = None
######################################################
class Front(Widget):
def __init__(self):
super().__init__()
self.start()
def start(self):
self.bs = BootstrapMethod()
self.add_widget(self.bs.layout)
self.bs.layout.size = (800, 400)
class mobilesuitApp(App):
def build(self):
root = Front()
return root
app = mobilesuitApp()
app.run()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T13:01:16.673",
"Id": "224029",
"Score": "3",
"Tags": [
"python",
"statistics",
"matplotlib",
"kivy"
],
"Title": "Simple Kivy App for Bootstrap Algorithm"
} | 224029 |
<p>I was tasked with using C++ to turn this</p>
<p><strong>"Hello Jarryd, do you like socks?"</strong></p>
<p>into:</p>
<p><strong>"socks? like you do Jarryd, Hello";</strong></p>
<p><strong>Edit:</strong> <em>The condition was to reverse this in place.</em></p>
<p>Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!</p>
<p><strong>.h</strong></p>
<pre><code>namespace SentenceFlipNamespace
{
class SentenceFlip
{
public:
SentenceFlip();
~SentenceFlip();
int FlipSentenceInPlace(char* in_Sentence);
void SentenceFlip::Move(int in_StartIndex, char in_String[]);
};
}
</code></pre>
<p><strong>.cpp</strong></p>
<pre><code>namespace SentenceFlipNamespace
{
SentenceFlip::SentenceFlip()
{
}
SentenceFlip::~SentenceFlip()
{
}
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
{
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
{
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
{
if (in_Sentence[i] == ' ' && i != length - 1)
{
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
}
}
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
}
return -1;
}
void SentenceFlip::Move(int in_StartIndex, char in_String[])
{
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
{
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
}
}
}
</code></pre>
<p><strong>Test Method,</strong> since I don't invoke it in main.</p>
<pre><code>namespace CodeChallengesTests
{
TEST_CLASS(TextFlip)
{
public:
TEST_METHOD(SentenceFlipInPlace)
{
SentenceFlipNamespace::SentenceFlip *testFlip = new SentenceFlipNamespace::SentenceFlip();
char input[] = "Hello Jarryd, do you like socks?";
char expectedResult[] = "socks? like you do Jarryd, Hello";
testFlip->FlipSentenceInPlace(input);
Assert::AreEqual(expectedResult, input, "Results do not match");
}
};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:24:58.550",
"Id": "434473",
"Score": "4",
"body": "Welcome to code review. We can do a better job of reviewing your code if you provide the entire SentenceFlip class and the main program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T04:20:55.920",
"Id": "434810",
"Score": "1",
"body": "I've added the .h, .cpp and my test method. Thank you, and I'll add these to future questions."
}
] | [
{
"body": "<p>Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.</p>\n\n<p>As an aside, the standard library provides <a href=\"https://en.cppreference.com/w/cpp/algorithm/rotate\" rel=\"nofollow noreferrer\"><code>std::rotate()</code></a> for moving part of a sequence from the end to the beginning, no need to write your own.</p>\n\n<p>There is an alternative in-place algorithm which swaps every character at most twice, and traverses three times. Thus it is trivially proven linear:</p>\n\n<ol>\n<li>Reverse every word in isolation. Remember the end if needed.</li>\n<li>Reverse everything.</li>\n</ol>\n\n<p>The standard library features <a href=\"https://en.cppreference.com/w/cpp/algorithm/reverse\" rel=\"nofollow noreferrer\"><code>std::reverse()</code></a> for implementing this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T04:08:59.107",
"Id": "434806",
"Score": "0",
"body": "Oh damn, I am completely out of touch with the standard library, which I need to remedy.\nAnd what a great idea, to reverse the words like that.\n\nThanks for taking the time to provide such a great answer, I've learned a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:31:44.517",
"Id": "224037",
"ParentId": "224031",
"Score": "6"
}
},
{
"body": "<p>I would probably do this by reading the words into a vector of strings, then rather than reversing the order, just traverse the vector in reverse order:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <iterator>\n#include <algorithm>\n\nint main() { \n std::vector<std::string> words { std::istream_iterator<std::string>(std::cin), {} };\n\n std::copy(words.rbegin(), words.rend(), \n std::ostream_iterator<std::string>(std::cout, \" \"));\n std::cout << '\\n';\n}\n</code></pre>\n\n<p>So a couple obvious points:</p>\n\n<ol>\n<li>Avoiding work is good.</li>\n<li>Letting your code avoid work is good too.</li>\n<li>The standard library has lots of stuff that can make programming a lot easier.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:56:50.360",
"Id": "434560",
"Score": "0",
"body": "Love that. Now if only if we had reverse ranges so we could use the range based for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T00:51:57.900",
"Id": "434563",
"Score": "0",
"body": "@MartinYork: Soon (C++20). Probably available already, if you use a reasonably new compiler."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:02:14.410",
"Id": "224066",
"ParentId": "224031",
"Score": "6"
}
},
{
"body": "<p>This quite simple task.<br>\nJust find words in reverse order and put them in new string.</p>\n\n<p>Code should be quite simple:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string reverse_words(std::string_view s)\n{\n std::string result;\n result.reserve(s.size());\n while(!s.empty()) {\n auto i = s.rfind(' ');\n result.append(s.begin() + i + 1, s.end());\n if (i == std::string_view::npos) break;\n result += ' ';\n s = s.substr(0, i);\n }\n return result;\n}\n</code></pre>\n\n<p>This code is fast since it does minimum allocations and minimum amount of coping.</p>\n\n<p><a href=\"https://wandbox.org/permlink/bYmojDyt0Z0xMJv0\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/bYmojDyt0Z0xMJv0</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T03:39:33.373",
"Id": "434573",
"Score": "0",
"body": "Welcome to code review. We do things a little differently than stack overflow, good answers actually comment on the users code rather than provide alternate solutions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:04:22.280",
"Id": "224067",
"ParentId": "224031",
"Score": "1"
}
},
{
"body": "<p>If it is important to execute the reversing in place, here is an example code (which implements the algorithm mentioned in <a href=\"https://codereview.stackexchange.com/a/224037\">https://codereview.stackexchange.com/a/224037</a>):</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n\nstatic void reverse_chars(char *s, int n)\n{\n int n2 = n / 2;\n for (int i = 0; i < n2; i++)\n {\n char tmp = s[i];\n s[i] = s[n - i - 1];\n s[n - i - 1] = tmp;\n }\n}\n\nstatic char *get_next_word(char *s, int *wlen)\n{\n while (*s && isspace(*s))\n s++;\n if (*s == '\\0')\n return nullptr;\n char *p = s; \n while (*p && !isspace(*p)) \n p++;\n *wlen = (p - s);\n return s;\n}\n\nstatic void reverse_words(char *s, int n)\n{\n reverse_chars(s, n);\n int wlen;\n char *w;\n while ((w = get_next_word(s, &wlen)) != nullptr)\n {\n reverse_chars(w, wlen);\n s += wlen;\n }\n}\n\nint main(int argc, char **argv)\n{\n if (argc < 2)\n {\n fprintf(stderr, \"Please, specify the string.\\n\");\n return 1;\n }\n printf(\"Original string: [%s]\\n\", argv[1]);\n reverse_words(argv[1], strlen(argv[1]));\n printf(\"Words reversed: [%s]\\n\", argv[1]);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T14:07:53.210",
"Id": "224287",
"ParentId": "224031",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224037",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:07:46.077",
"Id": "224031",
"Score": "5",
"Tags": [
"c++",
"strings"
],
"Title": "Reverse the word order in string, without reversing the words"
} | 224031 |
<p>I need to generate semi-complex throw-able passwords (just one use) in my application. I want it to be:</p>
<ul>
<li>at least 8 characters long;</li>
<li>contains at least 1 digit, 1 [a-z] char, 1 [A-Z] char;</li>
</ul>
<p>I generate a few passwords a day, and I don't mind about speed. I'm more looking for suggestions about code being maintainable (or not) and possible huge security flaws. Here's the code:</p>
<pre><code>public static string GenerateSimplePassword(int length = 8)
{
length = Math.Max(length, 8);
var allowedLower = new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
var allowedDigits = new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
var allowedUpper = allowedLower.Select(x => char.ToUpper(x)).ToArray();
var r = new Random();
var generatedCode = "";
generatedCode += allowedLower[r.Next(0, allowedLower.Length)];
generatedCode += allowedDigits[r.Next(0, allowedDigits.Length)];
generatedCode += allowedUpper[r.Next(0, allowedUpper.Length)];
var arrays = new[] { allowedLower, allowedUpper, allowedDigits };
for (var i = 0; i < length - 3; i++)
{
var array = arrays[r.Next(0, arrays.Length)];
generatedCode += array[r.Next(0, array.Length)];
}
return String.Join("", generatedCode.OrderBy(x => r.Next()));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:25:22.090",
"Id": "434482",
"Score": "1",
"body": "Are these password composition rules yours, or an external requirement? Consider that the number of possible 8-character passwords composed from \"0 or more characters from each list\" is actually smaller than the number of possible 8-character passwords composed from \"at least 1 character from each list\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:30:54.547",
"Id": "434483",
"Score": "0",
"body": "How are these passwords used? Can several people share the same random password? Does a password need to expire the next day?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:40:03.410",
"Id": "434484",
"Score": "0",
"body": "@benj2240 external requirement. I guess it avoid password with only lowercase char for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:40:46.937",
"Id": "434485",
"Score": "0",
"body": "@dfhwze it's for OTP. No expiration here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:46:15.873",
"Id": "434486",
"Score": "0",
"body": "No special characters such as `@, !, #, $` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:47:15.520",
"Id": "434487",
"Score": "1",
"body": "@pacmaninbw users are quite low tech, so yes, we avoid special char in this generator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T05:07:47.763",
"Id": "434580",
"Score": "3",
"body": "@benj2240 did you confuse \"smaller\" with \"larger\" in your above comment? It doesn't make sense to me in its current form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:54:05.060",
"Id": "434623",
"Score": "0",
"body": "What version of .NET are you using?"
}
] | [
{
"body": "<p>When calling your method like this:</p>\n\n<pre><code> for (int i = 0; i < 10; i++)\n {\n Console.WriteLine(GenerateSimplePassword());\n }\n</code></pre>\n\n<p>I get this result: </p>\n\n<pre><code> 88yuQg7H\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n u5UqU36o\n</code></pre>\n\n<p>which is not so random.</p>\n\n<p>The reason is the <code>Random</code> object being instantiated each time the method is called. Instead you must move the <code>Random</code> object outside the method as a <code>static</code> one time initialized field. </p>\n\n<hr>\n\n<p>You could make the valid chars as a static field string:</p>\n\n<pre><code>const string chars = \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nstatic int DigitStart = chars.IndexOf('0');\nstatic int UpperStart = chars.IndexOf('A');\n</code></pre>\n\n<hr>\n\n<p>Instead of concatenate strings throughout the process it would be better to use:</p>\n\n<p><code>char[] password = new char[length]</code></p>\n\n<p>it will improve both performance and readability: </p>\n\n<pre><code>password[0] = chars[random.Next(0, DigitStart)];\n</code></pre>\n\n<hr>\n\n<p>All in all my suggestion would be something like:</p>\n\n<pre><code>public static class PasswordGenerator\n{\n\n static readonly Random random = new Random();\n const string chars = \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n static int DigitStart = chars.IndexOf('0');\n static int UpperStart = chars.IndexOf('A');\n\n public static string GenerateSimplePassword(int length = 8)\n {\n length = Math.Max(length, 8);\n\n char[] password = new char[length];\n password[0] = chars[random.Next(0, DigitStart)];\n password[1] = chars[random.Next(DigitStart, UpperStart)];\n password[2] = chars[random.Next(UpperStart, chars.Length)];\n\n for (int i = 3; i < length; i++)\n {\n password[i] = chars[random.Next(0, chars.Length)];\n }\n\n return new string(password.OrderBy(_ => random.Next()).ToArray());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:11:07.967",
"Id": "434489",
"Score": "0",
"body": "Thanks for the answer. The string is shuffled with `generatedCode.OrderBy(x => r.Next()`, how the hacker could find out anything? But it gives a hint about bad code readability. I don't see how the simpler solution would assure that I get any of the 3 different char class. Does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:14:37.193",
"Id": "434491",
"Score": "0",
"body": "@ThomasAyoub: Sorry, I missed the last line of code. But why do you want at least one of each?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:25:03.333",
"Id": "434508",
"Score": "0",
"body": "Which version of .NET you use? According to @Eric Lippert this problem with Random is resolved in later versions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:30:00.320",
"Id": "434509",
"Score": "0",
"body": "@dfhwze: I use 4.8. I've see he commented that somewhere, but can't remember where. Apparently it is not solved yet. Maybe in core? [his blog](https://ericlippert.com/2019/01/31/fixing-random-part-1/): _\"Fortunately, I have just learned from an attentive reader that this problem has been fixed in some versions of the CLR; exactly which I am not sure...\"_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:32:04.750",
"Id": "434511",
"Score": "0",
"body": "@Eric Lippert Eric's answer here talks about it: https://codereview.stackexchange.com/questions/223593/deck-of-cards-with-shuffle-and-sort-functionality/223604#223604"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:36:52.030",
"Id": "434513",
"Score": "0",
"body": "@dfhwze: Yes - that's also my reference"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:07:10.043",
"Id": "224041",
"ParentId": "224033",
"Score": "8"
}
},
{
"body": "<p><strong>Fully Refactored Code:</strong> <a href=\"https://gist.github.com/Kittoes0124/d3b78a5c94a2bb0801ccbc50f51596d7\" rel=\"nofollow noreferrer\">see this Gist</a></p>\n\n<p><strong>Example Usage:</strong></p>\n\n<pre><code>static void Main(string[] args) {\n var generator = new PasswordGenerator(new PasswordGeneratorOptions {\n MinimumNumberOfLowerCaseCharacters = 1,\n MinimumNumberOfNumericCharacters = 1,\n MinimumNumberOfUpperCaseCharacters = 1,\n OutputLength = 8,\n SpecialCharacters = new char[0] { },\n });\n\n Console.WriteLine(generator.Next());\n}\n</code></pre>\n\n<p><strong>Review Comments:</strong></p>\n\n<p>First off, using <code>Random</code> as a source of entropy probably isn't the best idea since it is <em>possible</em> (however unlikely) that an attacker could gain the underlying seed; with it they would trivially be able to deduce all of the outputs used to generate our passwords. Let's implement a generator that uses a static instance of the <code>RNGCryptoServiceProvider</code> class instead:</p>\n\n<pre><code>// makes it easier to replace the implementation I demonstrate with something better\npublic interface ISecureRandom\n{\n uint Next(uint x, uint y);\n}\n\n// a possible implementation of a secure RNG, not exhaustively tested...\npublic sealed class SecureRandom : ISecureRandom\n{\n private static readonly RandomNumberGenerator DefaultRandomNumberGenerator = new RNGCryptoServiceProvider();\n\n public static SecureRandom DefaultInstance => new SecureRandom(DefaultRandomNumberGenerator);\n\n private readonly RandomNumberGenerator m_randomNumberGenerator;\n\n public SecureRandom(RandomNumberGenerator randomNumberGenerator) {\n if (null == randomNumberGenerator) {\n throw new ArgumentNullException(paramName: nameof(randomNumberGenerator));\n }\n\n m_randomNumberGenerator = randomNumberGenerator;\n }\n\n public byte[] GetBytes(byte[] buffer) {\n m_randomNumberGenerator.GetBytes(buffer);\n\n return buffer;\n }\n public byte[] GetBytes(int count) => GetBytes(new byte[count]);\n public uint Next() => BitConverter.ToUInt32(GetBytes(sizeof(uint)), 0);\n public uint Next(uint x, uint y) {\n if (x > y) {\n var z = x;\n\n x = y;\n y = z;\n }\n\n var range = (y - x);\n\n if (range == 0) {\n return x;\n }\n else if (range == uint.MaxValue) {\n return Next();\n }\n else {\n return (Next(exclusiveHigh: range) + x);\n }\n }\n\n private uint Next(uint exclusiveHigh) {\n var range = (uint.MaxValue - (((uint.MaxValue % exclusiveHigh) + 1) % exclusiveHigh));\n var result = 0U;\n\n do {\n result = Next();\n } while (result > range);\n\n return (result % exclusiveHigh);\n }\n}\n</code></pre>\n\n<p>Regarding maintainability, we could start by creating a proper class to encapsulate all of our settings:</p>\n\n<pre><code>public sealed class PasswordGeneratorOptions\n{\n private static readonly char[] DefaultSpecialChars = new[] { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '`', '~', '_', '+', ',', '.', '\\'', '\"', ';', ':', '?', '|', '/', '\\\\', '[', ']', '{', '}', '<', '>' };\n\n public int MinimumNumberOfNumericCharacters { get; set; }\n public int MinimumNumberOfLowerCaseCharacters { get; set; }\n public int MinimumNumberOfSpecialCharacters { get; set; }\n public int MinimumNumberOfUpperCaseCharacters { get; set; }\n public int OutputLength { get; set; }\n public ISecureRandom RandomNumberGenerator { get; set; }\n public IReadOnlyList<char> SpecialCharacters { get; set; }\n\n public PasswordGeneratorOptions() {\n MinimumNumberOfLowerCaseCharacters = 0;\n MinimumNumberOfNumericCharacters = 0;\n MinimumNumberOfSpecialCharacters = 0;\n MinimumNumberOfUpperCaseCharacters = 0;\n RandomNumberGenerator = SecureRandom.DefaultInstance;\n SpecialCharacters = DefaultSpecialChars;\n }\n}\n</code></pre>\n\n<p>Then we can declare a <code>PasswordGenerator</code> class that consumes our options:</p>\n\n<pre><code>public sealed class PasswordGenerator\n{\n private readonly PasswordGeneratorOptions m_options;\n\n public PasswordGenerator(PasswordGeneratorOptions options) {\n if (options.OutputLength < (options.MinimumNumberOfLowerCaseCharacters + options.MinimumNumberOfNumericCharacters + options.MinimumNumberOfSpecialCharacters + options.MinimumNumberOfUpperCaseCharacters)) {\n throw new ArgumentOutOfRangeException(message: \"output length must be greater than or equal to the sum of all MinimumNumber* properties\", actualValue: options.OutputLength, paramName: nameof(options.OutputLength));\n }\n\n m_options = options;\n }\n}\n</code></pre>\n\n<p>Now we can start thinking about implementation details, I personally like the idea of breaking things up into various categories so that we can provide more complex configuration options later. Let's try classifying your characters into <code>lower-case</code>, <code>upper-case</code>, <code>number</code>, and <code>special</code>. The ASCII encoding has largely taken care of all of this for us \"for free\" since three of these four classes have contiguous regions in the specification; we can write a simple generator for each like so:</p>\n\n<pre><code>var randomNumberGenerator = new SecureRandom();\n\nFunc<char> GetAsciiLetterLowerCase = () => ((char)randomNumberGenerator.Next(97, 123));\nFunc<char> GetAsciiLetterUpperCase = () => ((char)randomNumberGenerator.Next(65, 91));\nFunc<char> GetAsciiNumber = () => ((char)randomNumberGenerator.Next(48, 58));\n</code></pre>\n\n<p>Special characters aren't as easy so we'll resort to using a table of values:</p>\n\n<pre><code>var specialCharacters = new char[] { '!', '@', '#', };\n\nFunc<char> GetAsciiSpecial = () => specialCharacters[randomNumberGenerator.Next(0U, ((uint)specialCharacters.Count))];\n</code></pre>\n\n<p>The only remaining thing left to do is implement the generator function. This can be accomplished by more or less following the same strategy you already have in place. I chose to implement <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher–Yates shuffle</a> instead of using <code>LINQ</code> for the final randomization step:</p>\n\n<pre><code>public string Next() {\n var index = 0;\n var length = m_options.OutputLength;\n var randomNumberGenerator = m_options.RandomNumberGenerator;\n var result = new char[length];\n var useSpecial = (0 < m_options.SpecialCharacters.Count);\n\n for (var i = 0; (i < m_options.MinimumNumberOfLowerCaseCharacters); i++) {\n result[index++] = m_getAsciiLetterLowerCase();\n }\n\n for (var i = 0; (i < m_options.MinimumNumberOfNumericCharacters); i++) {\n result[index++] = m_getAsciiNumeric();\n }\n\n for (var i = 0; (i < m_options.MinimumNumberOfSpecialCharacters); i++) {\n result[index++] = m_getAsciiSpecial();\n }\n\n for (var i = 0; (i < m_options.MinimumNumberOfUpperCaseCharacters); i++) {\n result[index++] = m_getAsciiLetterUpperCase();\n }\n\n for (var i = index; (i < length); i++) {\n char c;\n\n switch (randomNumberGenerator.Next(0U, (useSpecial ? 4U : 3U))) {\n case 3U:\n c = m_getAsciiSpecial();\n break;\n case 2U:\n c = m_getAsciiNumeric();\n break;\n case 1U:\n c = m_getAsciiLetterLowerCase();\n break;\n case 0U:\n c = m_getAsciiLetterUpperCase();\n break;\n default:\n throw new InvalidOperationException();\n }\n\n result[i] = c;\n }\n\n FisherYatesShuffle(randomNumberGenerator, result);\n\n return new string(result);\n}\n\nprivate static void SwapRandom<T>(ISecureRandom randomNumberGenerator, IList<T> list, uint indexLowerBound, uint indexUpperBound) {\n var randomIndex = randomNumberGenerator.Next(indexLowerBound, indexUpperBound);\n var tempValue = list[(int)randomIndex];\n\n list[(int)randomIndex] = list[(int)indexUpperBound];\n list[(int)indexUpperBound] = tempValue;\n}\nprivate static void FisherYatesShuffle<T>(ISecureRandom randomNumberGenerator, IList<T> list) {\n var length = list.Count;\n var offset = 0U;\n\n while (offset < length) {\n SwapRandom(randomNumberGenerator, list, 0U, offset++);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:23:00.630",
"Id": "434545",
"Score": "0",
"body": "Is there really no predefined `SecureRandom` class in .NET? It sounds really strange that everyone would have to write this class by themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:27:34.110",
"Id": "434547",
"Score": "2",
"body": "This code looks really bloated, compared to the original code. Generating a password using a given simple and fixed scheme should take no more than 30 lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:35:13.413",
"Id": "434550",
"Score": "0",
"body": "@RolandIllig Sadly, there really isn't anything in the standard lib; I'd have used it. One concedes that the code is bloated but figured that having parameters is more \"maintainable\" in the long run; for example, one might be dealing with many clients that all have different configurations (or, heaven forbid, a client that changes their requirements over time)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:40:08.573",
"Id": "434557",
"Score": "0",
"body": "Very, very firm uptick for using `RNGCryptoServiceProvider`. While yes, it's very unlikely that an attacker will get the seed, it's always best to use cryptographically secure system when working with any part of authentication, especially CSPRNGs over DPRNGs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T13:54:47.363",
"Id": "434607",
"Score": "0",
"body": "The default `Random` class uses the system time as the seed. More specifically, the [`Environment.TickCount`](https://docs.microsoft.com/en-us/dotnet/api/system.environment.tickcount?view=netframework-4.8). This makes it REALLY EASY to guess the seed. There are so few options, you can just check them all! So, yes, in a serious implementation, using the `RNGCryptoServiceProvider` is a must. For homework, of course, the default `Random` class will be just fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:47:24.763",
"Id": "434622",
"Score": "0",
"body": "An extension method would be *far* simpler than using a completely separate class for generating integers, which is only required for the shuffle anyway. I also recommend against injecting instances of random number generators. A *very* common mistake in using RNGs is creating multiple instances rather than reusing the same one. Having a single, static final instance will discourage this mistake and give you a place to leave a comment reminding everyone to not to new up their own instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:05:58.757",
"Id": "434624",
"Score": "0",
"body": "Varying the minimum number of each type of character is also not a requirement and is an additional complication that is not needed here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:40:23.613",
"Id": "434627",
"Score": "0",
"body": "@jpmc26 While simpler, the static extension method wouldn't have been able to implement the ISecureRandom interface; a key feature that keeps the PasswordGenerator completely ignorant of how the numbers are generated (notice that the parameterless constructor now falls back to using a statically defined readonly rng). Varying the minimum characters might not be a requirement but it makes the code more generally useful. The OP actually has a decent approach and it seemed like a good idea to \"amplify\" it by making different variables available to a consumer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:52:40.673",
"Id": "434628",
"Score": "0",
"body": "@Kittoes0124 The interface is a bad idea. Injecting RNGs leads to the mistake of creating many instances. `PasswordGenerator` would not contain any more direct knowledge of the implementation RNG either way. And in fact, you could still inject an instance of `RNGCryptoServiceProvider` just as easily, if you absolutely insisted. There's no useful decoupling accomplished by it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:56:56.390",
"Id": "434629",
"Score": "0",
"body": "@Kittoes0124 Regarding \"amplifying,\" that is often how we get ourselves into trouble overcomplicating our problems. I would rather discourage this tendency for people asking for review than jump into it ourselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:15:48.357",
"Id": "434631",
"Score": "0",
"body": "@jpmc26 What you're saying about \"many instances\" is just nonsense though, it isn't up to us to decide how another developer uses their own tools; if they want to pass in a different RNG to each instance then so be it! The decoupling might be generally useless in most production scenarios but it ends up being immensely valuable in other contexts, such as unit testing. I understand where you're coming from regarding complication but it is hard to take you seriously when you're essentially complaining that arbitrary magic constants were converted into proper variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:39:26.470",
"Id": "434634",
"Score": "0",
"body": "@Kittoes0124 \"...if they want to pass in a different RNG to each instance then so be it!\" No. That will silently prevent the very randomness we seek to enforce. Code should be written to reduce risks. As for unit testing, no. Your unit tests should not try to replace an RNG directly. Ever. You should not be writing tests that assert on specific outputs when randomness is a core requirement of the method. *Maybe* you might want to fake out the thing that uses the RNG, but not the RNG itself. It's typically better to convert randomly generated items into a input, though, and avoid the coupling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:01:03.313",
"Id": "434635",
"Score": "0",
"body": "@jpmc26 \"That will silently prevent the very randomness we seek to enforce.\" What in the world are you talking about?! An RNG class that allows multiple instances isn't inherently broken in any way; some implementations might be broken but that doesn't mean we're forced to code around them. Requiring the `ISecureRandom` interface is a rather strong contract since no wild class is going to inherently have it; and yes, I do want to fake out the thing that uses the RNG... one huge reason for the interface is to send `PasswordGenerator` predictable inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:05:07.060",
"Id": "434636",
"Score": "0",
"body": "I'm talking about the kind of mistake the OP made. They created multiple instances of an RNG, which actually *reduces* the randomness. It may not be clear to some developers that the instance needs to be shared. \"one huge reason for the interface is to send `PasswordGenerator` predictable inputs.\" This doesn't make sense to me because it's required that `PasswordGenerator`'s output be random. As a result, sending it predictable inputs breaks its interface. I don't consider such a unit test to be meaningful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:07:18.247",
"Id": "434637",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96157/discussion-between-kittoes0124-and-jpmc26)."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:27:39.133",
"Id": "224044",
"ParentId": "224033",
"Score": "9"
}
},
{
"body": "<h1>Most of your variables should be <code>static readonly</code></h1>\n\n<p>There is no reason to new up a brand new copy of the arrays of characters each time you run this function. Instead:</p>\n\n<pre><code>public static readonly ReadOnlyCollection<char> AllowedLower = ReadOnlyCollection<char>(\"abcdefghijklmnopqrstuvwxyz\");\npublic static readonly ReadOnlyCollection<char> AllowedUpper = new ReadOnlyCollection<char>(AllowedLower.Select(x => char.ToUpper(x)));\npublic static readonly ReadOnlyCollection<char> AllowedDigits = new ReadOnlyCollection<char>(\"0123456789\");\n</code></pre>\n\n<p>Note that for static, read only lists of things, we use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.readonlycollection-1\" rel=\"nofollow noreferrer\"><code>ReadOnlyCollection</code></a> to prevent modification at run time. There are some alternative implementations of read only collections in .NET depending on your version; any of them is also fine.</p>\n\n<p>While we're at it, we can greatly improve readability by passing just one string, which implements <code>IEnumerable<char></code>.</p>\n\n<h1>Randomness problems</h1>\n\n<p>You have two incredibly major problems with randomness:</p>\n\n<ol>\n<li>The first is that you create a new instance of <code>Random</code> each time you invoke the function. That is <strong><em>wrong</em></strong>. You <em>must reuse</em> the same instance of a random number generator when generating many random numbers to ensure that it is sufficiently random.</li>\n<li>You're using <code>Random</code> which doesn't meet the level of randomness required for security algorithms. You need this level of randomness for generating passwords. You should use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rngcryptoserviceprovider\" rel=\"nofollow noreferrer\"><code>RNGCryptoServiceProvider</code></a>.</li>\n</ol>\n\n<pre><code>public static readonly RNGCryptoServiceProvider SecureRNG = new RNGCryptoServiceProvider();\n</code></pre>\n\n<h1>Selecting random characters</h1>\n\n<p>Once the minimum requirements for each group of characters is met, you use a two stage random selection to choose the remaining characters. Because each group is not of the same length, this actually reduces the randomness. Any single digit has a higher probability of being selected than any single letter.</p>\n\n<p>To resolve this, combine all of the characters into a single collection:</p>\n\n<pre><code>public static readonly ReadOnlyCollection<char> PasswordAlphabet = new ReadOnlyCollection<char>(AllowedLower.Concat(AllowedUpper).Concat(AllowedDigits));\n</code></pre>\n\n<p>And then select from that:</p>\n\n<pre><code>generatedPassword += PasswordAlphabet[randomIndex]\n</code></pre>\n\n<h1>Use a more standard shuffle algorithm</h1>\n\n<p>Since we can't use <code>Random</code> and <code>RNGCryptoServiceProvider</code> doesn't provide a <code>Next()</code>, using <code>OrderBy</code> to shuffle the password becomes more difficult. We need to ensure that our shuffling doesn't have biases in the order, and we need to do so without using <code>double</code>s.</p>\n\n<p>Luckily, this is a <a href=\"https://stackoverflow.com/a/1262619/1394393\">solved problem</a>. We'll use that solution.</p>\n\n<h1>Selecting a random character from the lists</h1>\n\n<p>You may have noticed that we skipped over how to generate <code>randomIndex</code> in the code above that selects a random character. That is because <code>RNGCryptoServiceProvider</code> does not readily implement a means of doing so. We'll need to implement the ability to randomly select from a range of values.</p>\n\n<p>The typical way of generating a random integer in a range is to <a href=\"https://stackoverflow.com/a/16907577/1394393\">first calculate a random <code>double</code> and then multiply it by the range's length</a>. We can do this with a couple extension methods that we'll implement later.</p>\n\n<h1>Prefer LINQ to loops</h1>\n\n<p>We don't need a <code>for</code> loop here. We can use LINQ:</p>\n\n<pre><code>generatedPassword += String.Join(\n \"\",\n Enumerable.Range(0, length - 3).Select(i => /* Get a random character */)\n);\n</code></pre>\n\n<h1>Don't silently replace inputs</h1>\n\n<p>While it's good that you restricted your method to require at least an 8 character password, it's <em>not</em> good to return something that the caller did not ask for. Instead of replacing the length, throw an error:</p>\n\n<pre><code>if (length < 8)\n{\n throw new ArgumentException(paramName: nameof(length), message: \"must be at least 8\");\n}\n</code></pre>\n\n<p>Higher levels of code may choose to replace user input, but that kind of logic belongs there in the caller, not here in the depths of the implementation.</p>\n\n<h1>What about dependency injection?</h1>\n\n<p>Should any of this be written in the dependency injection style?</p>\n\n<p>Firstly, I would say that the secure RNG instance should <strong>not</strong> be injected. A random number generator is one of the few elements of code where doing so is a bad idea. The reason is the very mistake you made in your code: you need a single, permanent instance of the RNG reused over and over. The secure version is <a href=\"https://stackoverflow.com/q/10525521/1394393\">notably thread safe</a>, so it's fine to have just a single instance. In fact, I would go so far as to say that if other classes need an RNG, then it should be move out of this class and into a global <code>static</code> one if possible. (It's possible performance requirements may override this advice, but in general, the fewer instances of RNGs you have and the more they're shared, the better.)</p>\n\n<p>Whether the method you're writing needs to be an instance that can be injected will depend on your requirements and the code base surrounding it. I don't see any particular harm in doing so, and I don't have enough context to know whether there's any benefit. The password generator I will present can be trivially converted into a stateless instance that could be injected, though.</p>\n\n<h1>Combining everything</h1>\n\n<p>First let's put our randomizing utilities in a separate class:</p>\n\n<pre><code>public static class SecureRandom\n{\n // We should only ever have one instance of this.\n // Other classes can use this freely, or methods can be added here.\n public static readonly RNGCryptoServiceProvider SecureRNG = new RNGCryptoServiceProvider();\n\n // NextDouble and Next based on https://stackoverflow.com/a/16907577\n\n public static double NextDouble(this RNGCryptoServiceProvider secureRNG)\n {\n var data = new byte[sizeof(uint)];\n secureRNG.GetBytes(data);\n var randUint = BitConverter.ToUInt32(data, 0);\n return randUint / (uint.MaxValue + 1.0);\n }\n\n public static int Next(this RNGCryptoServiceProvider secureRNG, int minValue, int maxValue)\n {\n if (minValue > maxValue)\n {\n throw new ArgumentOutOfRangeException();\n }\n\n return minValue + (int)((maxValue - minValue) * secureRNG.NextDouble());\n }\n\n public static int Next(this RNGCryptoServiceProvider secureRNG, int maxValue)\n {\n return secureRNG.Next(0, maxValue);\n }\n\n private static T SelectElement<T>(this RNGCryptoServiceProvider secureRNG, IList<T> choices)\n {\n return choices[SecureRNG.Next(choices.Count)];\n }\n\n // Based on https://stackoverflow.com/a/1262619\n private static void ToRandomOrder<T>(this RNGCryptoServiceProvider secureRNG, IEnumerable<T> sequence)\n {\n var workingList = new List<T>(sequence);\n\n int n = workingList.Count;\n while (n > 1)\n {\n byte[] box = new byte[1];\n do SecureRNG.GetBytes(box);\n while (!(box[0] < n * (Byte.MaxValue / n)));\n int k = (box[0] % n);\n n--;\n T value = workingList[k];\n workingList[k] = workingList[n];\n workingList[n] = value;\n }\n\n return workingList;\n }\n}\n</code></pre>\n\n<p>With our extension methods above, now we can write the full method:</p>\n\n<pre><code>using static SecureRandom;\n\npublic static class SimplePasswordGenerator\n{\n public static readonly ReadOnlyCollection<char> AllowedLower = ReadOnlyCollection<char>(\"abcdefghijklmnopqrstuvwxyz\");\n public static readonly ReadOnlyCollection<char> AllowedUpper = new ReadOnlyCollection<char>(AllowedLower.Select(x => char.ToUpper(x)));\n public static readonly ReadOnlyCollection<char> AllowedDigits = new ReadOnlyCollection<char>(\"0123456789\");\n\n public static readonly ReadOnlyCollection<char> PasswordAlphabet = new ReadOnlyCollection<char>(\n AllowedLower\n .Concat(AllowedUpper)\n .Concat(AllowedDigits)\n );\n\n public static string GenerateSimplePassword(int length = 8)\n {\n if (length < 8)\n {\n throw new ArgumentException(paramName: nameof(length), message: \"must be at least 8\");\n }\n\n IEnumerable<char> passwordCharacters = new [] { \n // At least one from each list\n SecureRNG.SelectElement(AllowedLower),\n SecureRNG.SelectElement(AllowedUpper),\n SecureRNG.SelectElement(AllowedDigits)\n }\n\n passwordCharacters = passwordCharacters.Concat(\n Enumerable.Range(0, length - 3)\n .Select(i => SecureRNG.SelectElement(PasswordAlphabet))\n );\n\n return String.Join(\"\", SecureRNG.ToRandomOrder(passwordCharacters));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:18:38.577",
"Id": "434638",
"Score": "0",
"body": "Great point about the biased entropy between digits and letters. And that's the first time I see a _do_ statement written like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:27:48.137",
"Id": "434641",
"Score": "1",
"body": "@dfhwze Just copy/pasted that `do`/`while` from the other source. lol. When I use other people's code, I try not to change it anymore than I really need to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:38:27.197",
"Id": "224107",
"ParentId": "224033",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:13:41.430",
"Id": "224033",
"Score": "6",
"Tags": [
"c#",
"beginner",
"security"
],
"Title": "Password maker in C#"
} | 224033 |
<p>As the title says, I'm loading (or at least trying to) two CSV files and store them in two separate arrays. What I have so far worked, but it isn't the most elegant, no efficient solution. </p>
<p>The end goal is to read in two CSV files and run comparisons on them both - that's why the separating them is important.</p>
<p><em>Note</em> - I use the <code>csv-parser</code> library, but am open to different solutions.</p>
<pre><code>const express = require("express");
const parse = require("csv-parser");
const fs = require("fs");
const app = express();
const port = 3000;
var CSVOne = [];
var CSVTwo = [];
fs.createReadStream("public/activity.csv")
.pipe(parse())
.on("data", data => CSVOne.push(data))
.on("end", () => {
sender = CSVOne.map(d => {
return {
email: d.Sender
};
});
fs.createReadStream("public/groups.csv")
.pipe(parse())
.on("data", dataTwo => CSVTwo.push(dataTwo))
.on("end", () => {
one = CSVTwo.map(d => {
return {
clinic: d.one
};
});
console.log(sender);
console.log(one);
});
});
app.listen(port, function() {
console.log("Server has started");
});
</code></pre>
| [] | [
{
"body": "<p>I don't know about elegant, but you could load the files in parallel for better performance. To do something when all CSV files are ready you can use promises or just a simple counter.</p>\n\n<p>The example also shows how you can use objects as return value in your arrow functions without the extra <code>{ return {...} }</code>.</p>\n\n<p>Example of loading in parallel using the counter method:</p>\n\n<pre><code>const express = require(\"express\");\nconst parse = require(\"csv-parser\");\nconst fs = require(\"fs\");\n\nconst app = express();\n\nconst port = 3000;\n\nvar CSVOne = [];\nvar CSVTwo = [];\nvar toGo = 2;\n\nfs.createReadStream(\"public/activity.csv\")\n .pipe(parse())\n .on(\"data\", data => CSVOne.push(data))\n .on(\"end\", () => {\n sender = CSVOne.map(d => ({\n email: d.Sender\n }));\n maybeDone();\n });\n\nfs.createReadStream(\"public/groups.csv\")\n .pipe(parse())\n .on(\"data\", dataTwo => CSVTwo.push(dataTwo))\n .on(\"end\", () => {\n one = CSVTwo.map(d => ({\n clinic: d.one\n }));\n maybeDone();\n });\n\nfunction maybeDone() {\n toGo -= 1;\n if (toGo === 0)\n done();\n}\n\nfunction done() {\n console.log(\"Both CSV files are ready\");\n console.log(CSVOne, CSVTwo);\n}\n\napp.listen(port, function() {\n console.log(\"Server has started\");\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T01:49:39.493",
"Id": "224073",
"ParentId": "224038",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T15:32:42.377",
"Id": "224038",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"csv"
],
"Title": "Loading in two CSV files and storing them in two separate arrays"
} | 224038 |
<p>I have two base classes: <code>City</code> and <code>Building</code>:</p>
<pre><code>public class City
{
public string Name { get; set; }
public double Area { get; set; }
}
public class Building
{
public string Name { get; set; }
public double Area { get; set; }
public int Stories { get; set; }
}
</code></pre>
<p>With two classes that inherit from <code>Building</code>, with their own <code>Id</code> property:</p>
<pre><code>public class MyBuilding : Building
{
public int MyId { get; set; }
}
public class HisBuilding : Building
{
public int HisId { get; set; }
}
</code></pre>
<p>And two classes that inherit from <code>City</code>, with their own <code>Id</code> and <code>IEnumerable<Building></code> properties:</p>
<pre><code>public class MyCity : City
{
public int MyId { get; set; }
public IEnumerable<MyBuilding> Buildings { get; set; }
}
public class HisCity : City
{
public int HisId { get; set; }
public IEnumerable<HisBuilding> Buildings { get; set; }
}
</code></pre>
<p>Below is a method I've created that returns a <code>KeyValuePair<City, Building></code> using generics:</p>
<pre><code>public static KeyValuePair<TCity, IEnumerable<TBuilding>> GetData<TCity, TBuilding>()
where TCity : City, new()
where TBuilding : Building, new()
{
TCity city = new TCity();
IEnumerable<TBuilding> buildings = new List<TBuilding>();
return new KeyValuePair<TCity, IEnumerable<TBuilding>>(city, buildings);
}
</code></pre>
<p>And in my <code>Main</code> method I've logic that instantiates a specific <code>City</code> object based on a user's input.</p>
<pre><code>int input = -1;
string strInput = Console.ReadLine();
int.TryParse(strInput, out input);
string json = string.Empty;
switch (input)
{
case 1:
KeyValuePair<MyCity, IEnumerable<MyBuilding>> myCity
= GetData<MyCity, MyBuilding>();
MyCity my = myCity.Key;
my.MyId = 1;
my.Buildings = myCity.Value;
json = JsonConvert.SerializeObject(my, Formatting.Indented);
break;
default:
KeyValuePair<HisCity, IEnumerable<HisBuilding>> hisCity
= GetData<HisCity, HisBuilding>();
HisCity his = hisCity.Key;
his.HisId = 2;
his.Buildings = hisCity.Value;
json = JsonConvert.SerializeObject(his, Formatting.Indented);
break;
}
Console.WriteLine(json);
Console.ReadLine();
</code></pre>
<p>The above generic method is just something I cobbled together in the last half hour, but I'm wondering if there is a more efficient way of creating these custom objects of mine, especially when each <code>City</code> has its own, different <code>IEnumerable<Building></code> property.</p>
<p><strong>EDIT</strong></p>
<p>Here is the code I have for building the <code>IEnumerable</code> inside my <code>GetData</code> method:</p>
<pre><code>public static IEnumerable<TBuilding> GetBuildingData<TBuilding>()
where TBuilding : Building, new()
{
DataTable table;
string myConnectionString = @"Data Source=(LocalDb)\MSSQLLocalDb;Initial Catalog=Test;Integrated Security=True;";
List<TBuilding> buildings = new List<TBuilding>();
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
using (SqlCommand command = new SqlCommand("[dbo].[GetListData]", connection) { CommandType = CommandType.StoredProcedure })
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
table = new DataTable();
adapter.Fill(table);
}
connection.Close();
}
}
foreach (DataRow row in table.Rows)
{
TBuilding building = new TBuilding();
building.Area = Convert.ToDouble(row["Area"]);
building.Name = row["Name"].ToString();
building.Stories = Convert.ToInt32(row["Stories"]);
buildings.Add(building);
}
return buildings;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:35:35.490",
"Id": "434496",
"Score": "0",
"body": "Could you provide a working example of how you would use such functionality? Atm you just have 2 objects with empty lists. What is the point of this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:56:24.800",
"Id": "434501",
"Score": "0",
"body": "Best practices you should make a constructor for types that have properties of ienumerable or collection types and fill them in with a default value and not return null. For IEnumerable just use Enumerable.Empty https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:18:04.683",
"Id": "434506",
"Score": "0",
"body": "@dfhwze I work with multiple clients and send them all notifications periodically. The notifications contain some of the same data, but `Id` properties are client-specific, so I'm working to build out the base objects generically, then add the custom ids later on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:22:22.280",
"Id": "434507",
"Score": "0",
"body": "Your method creates an empty list. How would you fill this list? I find this part crucial to review your code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:36:25.930",
"Id": "434512",
"Score": "1",
"body": "@dfhwze I edited my question to include the code I'm using to build that list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:43:29.070",
"Id": "434515",
"Score": "0",
"body": "Thanks for the edit. Is using an ORM an option for you or do you require custom mapping and SqlDataAdapter /DataTable interop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:47:56.040",
"Id": "434517",
"Score": "0",
"body": "I've never used ORM before nor have much of an idea of what it is."
}
] | [
{
"body": "<p>I will focus on..</p>\n\n<blockquote>\n <p>Creating custom objects with custom properties using generics </p>\n</blockquote>\n\n<p>Which you do in this method..</p>\n\n<blockquote>\n<pre><code>public static KeyValuePair<TCity, IEnumerable<TBuilding>> GetData<TCity, TBuilding>()\n where TCity : City, new()\n where TBuilding : Building, new()\n{\n TCity city = new TCity();\n IEnumerable<TBuilding> buildings = new List<TBuilding>();\n return new KeyValuePair<TCity, IEnumerable<TBuilding>>(city, buildings);\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>A <code>KeyValuePair</code> is archaic, you can use a <code>ValueTuple</code> nowadays</li>\n<li><code>TBuilding</code> does not require the <code>new()</code> constraint in this method</li>\n<li>The choice for <code>IEnumerable</code> over <code>IList</code> is questionable, since you retrieve the items later on and have no way of adding them to an <code>IEnumerable</code>. So why create the <code>IEnumerable</code> in this method?</li>\n<li>The name should reflect what you are doing. <code>CreateCity</code> seems more appropriate.</li>\n</ul>\n\n<p>I would refactor this method..</p>\n\n<pre><code>public static (TCity city, IList<TBuilding> buildings) CreateCity<TCity, TBuilding>()\n where TCity : City, new()\n where TBuilding : Building\n{\n var city = new TCity();\n var buildings = new List<TBuilding>();\n return (city, buildings);\n}\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Thinking about the refactored method. This doesn't even need to be a method anymore. It doesn't do anything but create objects for the types you specify.</p>\n\n<p>What I would really do is throw out this ancient way of ORM, and use an existing API (EF, NHibernate, Dapper).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:09:05.290",
"Id": "434522",
"Score": "2",
"body": "I'm afraid we might here at some point _this code is simplified, in my real code I actually do this and that_ :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:09:55.837",
"Id": "434523",
"Score": "0",
"body": "When I refactor my method using the code you've posted, by replacing the `KeyValuePair<TCity, IEnumerable<TBuilding>>` with `(TCity city, IList<TBuilding> buildings` I just end up with a bunch of errors. Could this be because I'm using Visual Studio 2015?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:11:04.577",
"Id": "434524",
"Score": "1",
"body": "ValueTuple is supported since https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/. You could keep using KeyValuePair instead, or use a regular Tuple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:11:01.907",
"Id": "434531",
"Score": "2",
"body": "...about the ancient tools... it looks like you should add another one to this list and suggest using VS2019 :-P"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T17:55:06.870",
"Id": "224049",
"ParentId": "224040",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>public class MyBuilding : Building\n{\n public int MyId { get; set; }\n}\n\npublic class HisBuilding : Building\n{\n public int HisId { get; set; }\n}\n</code></pre>\n</blockquote>\n\n<p>Why do you have the id as properties of the subclasses, it's a candidate for a base class member:</p>\n\n<pre><code>public class Building\n{\n public int Id { get; set; }\n</code></pre>\n\n<p>If the subclasses must have specialized names for their <code>Id</code> property, then provide that as:</p>\n\n<pre><code>public class MyBuilding : Building\n{\n public int MyId { get { return Id; } set { Id = value; } }\n}\n</code></pre>\n\n<p>but that is a rather odd concept that you should avoid if possible.</p>\n\n<p>The same holds for <code>Cities</code>.</p>\n\n<hr>\n\n<pre><code>public class MyCity : City\n{\n public int MyId { get; set; }\n public IEnumerable<MyBuilding> Buildings { get; set; }\n}\n</code></pre>\n\n<p>Normally you would have a materialized data set for buildings instead of an <code>IEnumerable<T></code> - unless you're creating the instances lazily/dynamically. You could maybe consider using a <code>IReadonlyList<T></code> as type, if you don't want it to be modifiable or else just a <code>IList<T></code></p>\n\n<hr>\n\n<blockquote>\n<pre><code>public static KeyValuePair<TCity, IEnumerable<TBuilding>> GetData<TCity, TBuilding>()\n where TCity : City, new()\n where TBuilding : Building, new()\n{\n TCity city = new TCity();\n IEnumerable<TBuilding> buildings = new List<TBuilding>();\n return new KeyValuePair<TCity, IEnumerable<TBuilding>>(city, buildings);\n}\n</code></pre>\n</blockquote>\n\n<p>If you changed the City base class to a generic like:</p>\n\n<pre><code>public class City<TBuilding> where TBuilding: Building\n{\n public IList<TBuilding> Buildings { get; set; }\n}\n</code></pre>\n\n<p>and dropped the buildings on the specialized cities, then you could return just the city from <code>GetData</code>, because you can initialize the <code>Buildings</code> property inside <code>GetData</code>, which I would rename to <code>CreateCity()</code></p>\n\n<pre><code>public static TCity CreateCity<TCity, TBuilding>()\nwhere TCity : City<TBuilding>, new()\nwhere TBuilding : Building, new()\n{\n TCity city = new TCity();\n city.Buildings = new List<TBuilding>();\n return city;\n}\n</code></pre>\n\n<hr>\n\n<p>Ideally you could have a common baseclass for <code>City</code> and <code>Building</code>, because they share some significant properties like <code>Id</code>, <code>Area</code> and <code>Name</code>:</p>\n\n<pre><code>public abstract class AreaObject\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public double Area { get; set; }\n}\n</code></pre>\n\n<p>A complete refactoring of your data model could then be:</p>\n\n<pre><code>public abstract class AreaObject\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public double Area { get; set; }\n}\n\n// For convenience a city base class without the generic type parameter:\npublic abstract class City : AreaObject\n{\n public abstract IEnumerable<Building> GetBuildings();\n}\n\npublic class City<TBuilding> : City where TBuilding : Building\n{\n public IList<TBuilding> Buildings { get; set; }\n\n public override IEnumerable<Building> GetBuildings()\n {\n return Buildings;\n }\n}\n\npublic class Building : AreaObject\n{\n public int Stories { get; set; }\n}\n\npublic class MyBuilding : Building\n{\n public int MyId { get { return Id; } set { Id = value; } }\n}\n\npublic class HisBuilding : Building\n{\n public int HisId { get { return Id; } set { Id = value; } }\n}\n\npublic class MyCity : City<MyBuilding>\n{\n public int MyId { get { return Id; } set { Id = value; } }\n}\n\npublic class HisCity : City<HisBuilding>\n{\n public int HisId { get { return Id; } set { Id = value; } }\n}\n</code></pre>\n\n<p>It's a little odd to have two different sub cities having specialized buildings instead of just <code>Building</code>s, but you may have reasons for that? (What if <code>MyCity</code> buys a building from <code>HisCity</code> can it then change from <code>His</code> to <code>My</code>?)</p>\n\n<hr>\n\n<blockquote>\n <p>Here is the code I have for building the <code>IEnumerable</code> inside my\n <code>GetData</code> method:</p>\n \n <p><code>public static IEnumerable<TBuilding> GetBuildingData<TBuilding>()...</code></p>\n</blockquote>\n\n<p>If that is going to be used inside <code>GetData()</code> shouldn't it then take a city id as argument in order to minimize the query? If so you can change the <code>GetData</code> to:</p>\n\n<pre><code>public static TCity CreateCity<TCity, TBuilding>(int id)\nwhere TCity : City<TBuilding>, new()\nwhere TBuilding : Building, new()\n{\n TCity city = new TCity();\n city.Buildings = GetBuildingData<TBuilding>(id);\n city.Id = id;\n return city;\n}\n</code></pre>\n\n<p>And you'll then have to modify your database query to only return the buildings for that city: </p>\n\n<pre><code>public static IList<TBuilding> GetBuildingData<TBuilding>(int cityId)\nwhere TBuilding : Building, new() {...}\n</code></pre>\n\n<hr>\n\n<p>All in all this could simplify your use case to:</p>\n\n<pre><code> int cityId = -1;\n string strInput = Console.ReadLine();\n int.TryParse(strInput, out cityId);\n if (cityId > 0)\n {\n City city = null;\n\n switch (cityId)\n {\n case 1:\n city = CreateCity<MyCity, MyBuilding>(cityId);\n break;\n case 2:\n city = CreateCity<HisCity, HisBuilding>(cityId);\n break;\n default:\n throw new InvalidOperationException(\"Invalid Id\");\n }\n\n string json = JsonConvert.SerializeObject(city, Formatting.Indented);\n Console.WriteLine(json);\n Console.ReadLine();\n }\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>As mentioned a couple of times in the above, the data model and class structure for especially <code>City</code> is rather unusual. A more conventional structure could be something like:</p>\n\n<pre><code>public abstract class AreaObject\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public double Area { get; set; }\n}\n\npublic abstract class City : AreaObject\n{\n public IList<Building> Buildings { get; set; }\n}\n\npublic class MyCity : City\n{\n // Uncomment if you really need this: public IList<MyBuilding> MyBuildings => Buildings.Where(b => b is MyBuilding).Cast<MyBuilding>().ToList();\n}\n\npublic class HisCity : City\n{\n // Uncomment if you really need this: public IList<HisBuilding> HisBuildings => Buildings.Where(b => b is HisBuilding).Cast<HisBuilding>().ToList();\n}\n\npublic class Building : AreaObject\n{\n public int Stories { get; set; }\n}\n\npublic class MyBuilding : Building\n{\n}\n\npublic class HisBuilding : Building\n{\n}\n</code></pre>\n\n<p>As shown, <code>City</code> owns the <code>Buildings</code> property. The original concept of having specialized building properties per city sub class, doesn't make much sense in real life, because what defines a building: its relation to a city or its materials, functionality etc.? Can't two cities have a copy of the same building? And a <code>MyCity</code> should be able to Buy a building from <code>HisCity</code> etc. And a city should be able to own different types of building.</p>\n\n<p>The factory method could then be simplified to this: </p>\n\n<pre><code> public static TCity CreateCity<TCity>(int id)\n where TCity : City, new()\n {\n TCity city = new TCity();\n city.Buildings = GetBuildingData(id);\n city.Id = id;\n return city;\n }\n\n public static IList<Building> GetBuildingData(int cityId)\n {\n // The sql stuff...\n }\n</code></pre>\n\n<p>And the use case to:</p>\n\n<pre><code> public static void Run()\n {\n int cityId = -1;\n string strInput = Console.ReadLine();\n int.TryParse(strInput, out cityId);\n if (cityId > 0)\n {\n City city = null;\n\n switch (cityId)\n {\n case 1:\n city = CreateCity<MyCity>(cityId);\n break;\n case 2:\n city = CreateCity<HisCity>(cityId);\n break;\n default:\n throw new InvalidOperationException(\"Invalid Id\");\n }\n\n string json = JsonConvert.SerializeObject(city, Formatting.Indented);\n Console.WriteLine(json);\n Console.ReadLine();\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:58:07.637",
"Id": "434737",
"Score": "0",
"body": "Why both an `abstract` `City` class and a normal `City` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T19:30:05.813",
"Id": "434762",
"Score": "0",
"body": "@Delfino: In order to make the polymorphism work properly, so you'll be able to write: `City city = new MyCity();`. Your need to have two different sub cities with specialized `Building` properties is highly unusual, and breaks the normal concept of inheritance and polymorphism. There is no good solution to that IMO. I'll update my answer with a more conventional data model in a moment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:07:32.087",
"Id": "224054",
"ParentId": "224040",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224049",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T16:05:43.427",
"Id": "224040",
"Score": "4",
"Tags": [
"c#",
"generics",
"inheritance"
],
"Title": "Creating custom objects with custom properties using generics"
} | 224040 |
<p>I'm trying to implement the enumerate built-in using iterators. So far it works but for unordered objects, such as sets or dictionaries, I'm not sure if this implementation is considered valid, although it works.</p>
<pre><code>class myEnumerate:
def __init__(self, iterable):
self.iterable = list(iterable)
self.index = -1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if self.index >= len(self.iterable):
raise StopIteration
return self.index, self.iterable.__getitem__(self.index)
if __name__ == '__main__':
for (i, ch) in myEnumerate("Python"):
print(i, ch)
# Output:
# 0 P
# 1 y
# 2 t
# 3 h
# 4 o
# 5 n
for (i, ch) in myEnumerate(set(["a", "b", "c"])):
print(i, ch)
# Output: (order might differ)
# 0 a
# 1 b
# 2 c
</code></pre>
<p>What do you guys think?</p>
| [] | [
{
"body": "<p>I think this is mistake:</p>\n\n<pre><code>self.iterable = list(iterable)\n</code></pre>\n\n<ol>\n<li><p>It requires loading the entire iterable into memory. Being able to avoid this and work with large collections efficiently is one of the big benefits of iterators.</p></li>\n<li><p>It won't work on non-ending iterators like <code>itertools.count()</code></p></li>\n</ol>\n\n<p>If instead, you make an iterator from the iterable, you can avoid both those problems and simplify your code by depending on the iterator's own <code>StopIteration</code> exception:</p>\n\n<pre><code>class myEnumerate:\n def __init__(self, iterable):\n self.iterable = iter(iterable)\n self.index = -1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.index += 1 \n return self.index, next(self.iterable)\n\n// this now works:\n\nfrom itertools import count, islice\nc = count()\nfor (i, ch) in islice(myEnumerate(count()), 1, 10):\n print(i, ch)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:17:16.317",
"Id": "434532",
"Score": "1",
"body": "You're absolutely right! Thx a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:13:02.397",
"Id": "224055",
"ParentId": "224051",
"Score": "3"
}
},
{
"body": "<p>As mentioned, expanding the iterable into a list is probably not always desired.\nAlso a class seems to be overkill, since it needs to carry around an instance dict that's not being used.\nAn implementation as a generator function seems more lightweight and feasible.</p>\n\n<pre><code>def enumerate(iterable, start=0):\n for item in iterable:\n yield (start, item)\n start += 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T15:32:44.747",
"Id": "224222",
"ParentId": "224051",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "224055",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:29:06.747",
"Id": "224051",
"Score": "2",
"Tags": [
"python",
"reinventing-the-wheel",
"iterator"
],
"Title": "Implementation of enumerate"
} | 224051 |
<p>I'm interested in a way to join three (or more) tables in a way that is more efficient (both in terms of conciseness of code and in terms of generating the results) than what I have currently.</p>
<p><strong>Underlying tables:</strong></p>
<pre><code>table ISIN
+---------------+----+------+
| isin | id | code |
+---------------+----+------+
| US0378331005 | 1 | NULL |
| AU0000XVGZA3 | 2 | z |
| GB0002634946 | 3 | y |
+---------------+----+------+
table additionalCredit
+------+----+
| code | id |
+------+----+
| h | 1 |
| i | 2 |
+------+----+
table codes
+--------+------+----------------------+
| codeId | code | description |
+--------+------+----------------------+
| 9 | h | ETM - Principal Only |
| 9 | i | ETM - Waiting Close |
| 8 | z | No Redemption |
| 8 | y | Partially Prerefunded|
+--------+------+----------------------+
</code></pre>
<p><strong>Expected results:</strong></p>
<pre><code>+---------------+-----------------------+----------------------+
| isin | type8 | type9 |
+---------------+-----------------------+----------------------+
| US0378331005 | null | ETM - Principal Only |
| AU0000XVGZA3 | No Redemption | ETM - Waiting Close |
| GB0002634946 | Partially Prerefunded | null |
+---------------+-----------------------+----------------------+
</code></pre>
<p><strong>Working Code</strong></p>
<pre><code>select
ISIN.isin,
min(type8), min(type9)
from
(select
ISIN.isin,
case when codes.codeId=8 then codes.description end as type8,
case when codes.codeId=9 then codes.description end as type9
from ISIN
left join codes
on ISIN.code=codes.code
union
select
ISIN.isin,
case when codes.codeId=8 then codes.description end as type8,
case when codes.codeId=9 then codes.description end as type9
from ISIN
left join additionalCredit ac
on ac.id=isin.id
left join codes
on codes.code=ac.code) as n
group by n.name
</code></pre>
<p><strong><a href="https://stackoverflow.com/questions/56403019/how-to-combine-multiple-rows-with-multiple-joins-from-multiple-tables-in-mysql/56403020">Context</a></strong> </p>
<p>...from the original Q&A at Stack Overflow that gives my thought process and steps taken, where the first commenter suggested there could be a better answer. Here's a <a href="https://www.db-fiddle.com/f/v4VCgd3XH9SRNjkzFJEvQM/1" rel="nofollow noreferrer">fiddle</a>.</p>
<p><strong>Can you help me find a better way than a union statement (in which nearly the entire query is duplicated)?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:25:16.070",
"Id": "434546",
"Score": "0",
"body": "You asked this on SE and CR. But the best place to ask questions like this is https://dba.stackexchange.com. And thanks alot for providing a Fiddle. This makes a review much easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T00:41:28.710",
"Id": "434562",
"Score": "1",
"body": "The schema and the sample data seem obfuscated. Could you provide more background and motivation for what this code does? See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T08:34:44.627",
"Id": "434593",
"Score": "0",
"body": "I agree with 200_success. I always find it a lot easier to work with tables and data that mean something to me. The db-fiddle did not help much either. The only thing I know now is that you're not using indexes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T22:48:59.080",
"Id": "434947",
"Score": "0",
"body": "@200_success I deobfuscated the sample, but as you can see, it does not really add too much to the question (and might unnecessarily complicate it). I'm not in control of the underlying schema."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T04:12:27.653",
"Id": "434979",
"Score": "0",
"body": "@200_success Nice edit of answer and fiddle ;-)"
}
] | [
{
"body": "<h3>DB Design</h3>\n\n<p>Your tables are not correctly normalized:</p>\n\n<ul>\n<li><code>codes.description</code> depends on <code>codes.code</code> → requires a table with <code>codes.code</code> as primary key</li>\n</ul>\n\n<p>You are also missing constraints:</p>\n\n<ul>\n<li><code>ISIN.id</code> primary key</li>\n<li><code>ISIN.name</code> unique key</li>\n<li><code>additionalCredit.id, additionalCredit.code</code> primary key</li>\n<li><code>codes.codeId, codes.code</code> primary key</li>\n</ul>\n\n<h3>Query Optimization</h3>\n\n<p>mysql does not come with a <em>pivot</em>, so we need to use an <em>aggregate function</em> - in this case <code>min(..)</code> - instead. This way we can avoid the <em>union</em> of redundant <em>quasi</em> code duplication.</p>\n\n<p><a href=\"https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=0ace357464829a6bd81403900ab35936\" rel=\"nofollow noreferrer\">Fiddle</a></p>\n\n<p>query..</p>\n\n<pre><code>select isin\n , min(if(codeId = 8, description, null)) Type8\n , min(if(codeId = 9, description, null)) Type9\nfrom (\n select codeId, code, description, ifnull(name1, name2) isin from (\n select codes.codeId, codes.code, codes.description, ISIN1.isin name1, ISIN2.isin name2\n from codes\n left join ISIN ISIN1 on ISIN1.code = codes.code\n left join additionalCredit on additionalCredit.code = codes.code\n left join ISIN ISIN2 on ISIN2.id = additionalCredit.id\n ) q1\n) p1\ngroup by isin\norder by isin\n;\n</code></pre>\n\n<p>yielding..</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>name Type8 Type9\nAU0000XVGZA3 No Redemption ETM - Waiting Close\nGB0002634946 Partial Prerefunded \nUS0378331005 ETM - Principal Only\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T21:23:18.753",
"Id": "435051",
"Score": "0",
"body": "Nice of you to update your answer with my changes to the original question; sorry to make more work for you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T04:20:47.893",
"Id": "435087",
"Score": "1",
"body": "@200_success courtesy of the community to keep the quality up."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T21:02:27.993",
"Id": "224059",
"ParentId": "224053",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "224059",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T18:58:17.280",
"Id": "224053",
"Score": "2",
"Tags": [
"sql",
"mysql",
"join"
],
"Title": "Join and pivot multiple tables of securities data in MySQL"
} | 224053 |
<p>I often like to get a feel for a text file containing a lot of numbers quickly by making a histogram. One can do this in plotting software like Gnuplot, but sometimes having something in the terminal is nice (or can even make plotting later easier).</p>
<p>To this end, I wrote a program that reads numbers from stdin and sorts them into bins of equal width. The output of the program is the bin centers and counts in each bin.</p>
<p>I am new to Rust. I found the <code>clap</code> library for parsing command line arguments, and I tried to use some language features for manipulating vectors.</p>
<p>I suspect the algorithm can be improved. Because the code outputs the bins sorted by bin center, I store the bin edges in a vector as they are created. However, to avoid comparing <code>float</code>s when checking if a bin is already present, I have another parallel vector with bin ID numbers that I compare instead.</p>
<pre><code>// binner
// Command-line tool for reading in a list of numbers and writing
// bins and counts for a specified bin width
//
// bins are defined [lower, upper), such that each output point
// has the form:
// (x,y) = ((lower + upper) / 2, counts)
// and lower - upper = specified binwidth
#[macro_use]
extern crate clap;
use std::io::{self, BufRead};
use std::cmp::Ordering;
use clap::{Arg, App}; // for parsing command-line arguments
fn bins(values: &Vec<f64>, binwidth: f64, binstart: f64) -> Vec<(f64, u32)> {
// Input: a vector of floats and a bin width
// Output: a vector of bin edges and counts for each bin
// unique integer identifier for each bin, to be used to check if bin is present
// the actual bin edges will be computed as floats, so this avoids
// checking for strict float equality
let mut bin_ids: Vec<i32> = Vec::new();
// computed bin edge values and counts
let mut edges_counts: Vec<(f64, u32)> = Vec::new();
for val in values {
let bin_id = (val / binwidth).floor() as i32;
// check if the bin is already in the vector
match bin_ids.iter().position(|&b| b == bin_id) {
// if it is, add to the corresponding counts
Some(i) => { edges_counts[i].1 += 1 },
// else, add a new bin
_ => {
bin_ids.push(bin_id);
edges_counts.push(
(binwidth * (((val - binstart) /
binwidth).floor() + 0.5) + binstart, 1)
);
},
};
}
// sort result by edge, then return. Since floats may contain NaN,
// we need to use partial_cmp since edges are floats,
// and specify what to do for errors
edges_counts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
return edges_counts;
}
fn main() {
// parse command line arguments and set up help with clap-rs
let arg_matches = App::new("binner")
.version("1.0")
.about("Read numbers from standard input, output bins and counts")
.arg(Arg::with_name("binwidth")
.short("w")
.value_name("WIDTH")
.help("Set bin width")
.takes_value(true)
.default_value("1.0"))
.arg(Arg::with_name("binstart")
.short("s")
.value_name("EDGE START")
.help("Set bin edge start")
.takes_value(true)
.default_value("0.0"))
.arg(Arg::with_name("INPUT")
.help("Input stream")
.index(1))
.get_matches();
// type-checking macro explaind in clap example 12_typed_values.rs
let binwidth: f64 = value_t!(arg_matches, "binwidth", f64).unwrap_or(1.0);
let binstart: f64 = value_t!(arg_matches, "binstart", f64).unwrap_or(0.0);
// parse stdin to make a list of values
let stdin = io::stdin();
let mut values: Vec<f64> = Vec::new();
for line in stdin.lock().lines() {
let elem: f64 = match line.unwrap().trim().parse() {
Ok(num) => num,
Err(_) => {
eprintln!("Invalid value entered");
continue;
},
};
values.push(elem);
}
// compute bins and print
let result = bins(&values, binwidth, binstart);
for bin in &result {
println!("{}\t{}", bin.0, bin.1);
}
}
#[cfg(test)]
mod tests{
use super::bins;
#[test]
fn sequence() {
// bin 10 numbers. bin edges start at binwdith / 2 intervals
let vals = vec![1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5];
let out = vec![(1.5, 2), (2.5, 2), (3.5, 2), (4.5, 2), (5.5, 2)];
assert_eq!(bins(&vals, 1.0, 1.0), out);
}
#[test]
fn unordered() {
let vals = vec![1.0, 55.6, -15.2, 55.9];
let out = vec![(-15.5, 1), (1.5, 1), (55.5, 2)];
assert_eq!(bins(&vals, 1.0, 1.0), out);
}
}
</code></pre>
<p>A simple use-case might be </p>
<p><code>seq 0 1 1000 | binner -w 10</code></p>
<p>which bins integers from 0 to 1000 in bins of width 10. </p>
| [] | [
{
"body": "<h1>negative</h1>\n<pre><code>// and lower - upper = specified binwidth\n</code></pre>\n<p>Wait a minute! Strike that, reverse it. Thank you.</p>\n<p>Also typo nit: "explaind"</p>\n<h1>helper</h1>\n<p>Please introduce a helper that maps from <code>val</code> to <code>bin_id</code>.\nI am skeptical that bin ids are compatible with edge counts currently,\nsince <code>binstart</code> does not participate in computing a <code>bin_id</code>.\nThis matters when <code>binstart</code> is not a multiple of <code>binwidth</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:37:05.640",
"Id": "224113",
"ParentId": "224056",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T19:20:21.307",
"Id": "224056",
"Score": "4",
"Tags": [
"rust",
"vectors"
],
"Title": "Bin Numbers from stdin"
} | 224056 |
<p>I made this program as a baby step to creating an animal shelter management system that will be used in a real life animal shelter. The goal is to move from text files to an online database, and from console interface to a GUI. Two things I'm yet to learn.</p>
<p>I set out with the goal of creating a CRUD program that stores the information in files.</p>
<p>The program runs with no compilation errors, and as far as I can see, no logical errors.</p>
<p>I am looking for any type of input. Whether it's naming, logic, or OOP choices.</p>
<p>Main.java</p>
<pre class="lang-java prettyprint-override"><code>public class Main {
public static void main(String[] args) {
UserTextInterface userTextInterface = new UserTextInterface();
userTextInterface.run();
}
}
</code></pre>
<p>Animal.java</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Date;
public class Animal {
private String name;
private int ID;
private String notes;
private String species;
private Date dateOfBirth;
public Animal(String name, int ID, String notes, String species, Date dateOfBirth){
this.name = name;
this.ID = ID;
this.notes = notes;
this.species = species;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString(){
return "Animal: " + species + ", Name: " + name + ", ID: " + ID + ", Notes: " + notes + ", Date of birth: " + dateOfBirth.toString() ;
}
}
</code></pre>
<p>UserTextInterface.java</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class UserTextInterface {
private Scanner reader;
private InputValidator inputValidator;
private AnimalHandler animalHandler;
public UserTextInterface(){
reader = new Scanner(System.in);
inputValidator = new InputValidator();
animalHandler = new AnimalHandler("src/animal.txt");
}
public void run(){
printOptions();
while(processInput());
animalHandler.saveArrayToFile();
}
public void printOptions(){
System.out.println("Options:");
System.out.println("0. Quit");
System.out.println("1. Add a new dog");
System.out.println("2. Add a new cat");
System.out.println("3. Print all animals");
System.out.println("4. Delete an animal");
System.out.println("5. Update an animal");
}
public boolean processInput(){
int input = inputValidator.readInt();
while(input != 0){
if(input == 1){
animalHandler.addDog();
}
else if(input == 2){
animalHandler.addCat();
}
else if(input == 3){
animalHandler.printAllAnimals();
}
else if(input == 4){
animalHandler.removeAnimal();
}
else if(input == 5){
animalHandler.updateAnimal();
}
else{
}
input = inputValidator.readInt();
}
return false;
}
}
</code></pre>
<p>FileHandler.java</p>
<pre class="lang-java prettyprint-override"><code>import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class FileHandler {
private String filePath;
private File filePointer;
private Scanner reader;
private SimpleDateFormat dateFormatter;
public FileHandler(String filePath){
this.filePath = filePath;
dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
}
public List<Animal> load(){
List<Animal> contents = new ArrayList<Animal>();try{
filePointer = new File(filePath);
reader = new Scanner(filePointer);
}
catch(Exception e){
return null;
}
while(reader.hasNextLine()){
String line = reader.nextLine();
String[] parts = line.split(":");
Date dateOfBirth = new Date();
try {
dateOfBirth = dateFormatter.parse(parts[4]);
}
catch(Exception e){
System.out.println(e.getMessage());
}
contents.add(new Animal(parts[0], Integer.parseInt(parts[1]), parts[2], parts[3], dateOfBirth));
}
reader.close();
return contents;
}
public boolean save(List<Animal> content){
FileWriter writer;
try{
writer = new FileWriter(filePath);
}
catch(Exception e){
return false;
}
for(Animal animal : content){
try{
writer.write(animal.getName() + ":" + animal.getID() + ":" + animal.getNotes() + ":" + animal.getSpecies() + ":" + dateFormatter.format(animal.getDateOfBirth())+ "\n");
}
catch (Exception e){
return false;
}
}
try{
writer.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
return true;
}
}
</code></pre>
<p>AnimalHandler.Java</p>
<pre class="lang-java prettyprint-override"><code>import java.text.SimpleDateFormat;
import java.util.*;
public class AnimalHandler {
private FileHandler fileHandler;
private List<Animal> fileArray;
private Scanner reader;
private InputValidator inputValidator;
private SimpleDateFormat dateFormatter;
public AnimalHandler(String filePath){
fileHandler = new FileHandler(filePath);
fileArray = new ArrayList<Animal>();;
reader = new Scanner(System.in);
inputValidator = new InputValidator();
dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
loadFileToArray();
}
public void loadFileToArray(){
fileArray = fileHandler.load();
}
public void saveArrayToFile(){
fileHandler.save(fileArray);
}
public void addCat(){
System.out.println("Enter the cat's name");
String name = reader.nextLine();
System.out.println("Enter the cat's ID");
int ID = readID();
System.out.println("Enter any notes:");
String notes = reader.nextLine();
Date date = readDate();
fileArray.add(new Animal(name, ID, notes, "Cat", date));
System.out.println("Cat added successfully");
}
public void addDog(){
System.out.println("Enter the dog's name");
String name = reader.nextLine();
System.out.println("Enter the dog's ID");
int ID = readID();
System.out.println("Enter any notes:");
String notes = reader.nextLine();
Date date = readDate();
fileArray.add(new Animal(name, ID, notes, "Dog", date));
System.out.println("Dog added successfully");
}
public void removeAnimal(){
System.out.println("Enter the ID of the animal you want to remove: ");
int ID = inputValidator.readInt();
for(Animal animal : fileArray){
if(animal.getID() == ID){
fileArray.remove(animal);
System.out.println("Animal: "+ animal.getSpecies() + ", Name: " + animal.getName() + ": Deleted successfully");
return;
}
}
System.out.println("Could not find animal with ID: " + ID);
}
public void updateAnimal(){
System.out.println("Enter the ID of the animal you want to update: ");
int ID = inputValidator.readInt();
if(!IDAlreadyExists(ID)){
System.out.println("Could not find animal with ID: " + ID);
return;
}
int index = -1;
for(Animal animal : fileArray){
if(animal.getID() == ID){
index = fileArray.indexOf(animal);
break;
}
}
if(index >= 0){
Animal animal = fileArray.get(index);
System.out.println("Found: Animal: " + animal.getSpecies() + ", Name: " + animal.getName() + ". Please enter new details below");
System.out.println("Would you like to enter a new name? Y/N: ");
String answer = reader.nextLine();
if (answer.equalsIgnoreCase("y")) {
System.out.println("Enter a new name: ");
String newName = reader.nextLine();
animal.setName(newName);
}
System.out.println("Would you like to enter a new ID? Y/N: ");
answer = reader.nextLine();
if (answer.equalsIgnoreCase("y")) {
System.out.println("Enter a new ID: ");
int newID = inputValidator.readInt();
if(IDAlreadyExists(newID)){
System.out.println("This ID is already in use. Please enter a different one: ");
newID = readID();
}
animal.setID(newID);
}
System.out.println("Would you like to enter a new date of birth? Y/N: ");
answer = reader.nextLine();
if(answer.equalsIgnoreCase("y")){
System.out.println("Enter a new date of birth: ");
Date newDate = readDate();
animal.setDateOfBirth(newDate);
}
}
else{
System.out.println("Error, ID not found. This should never happen.");
}
}
public void printAllAnimals(){
for(Animal animal : fileArray){
System.out.println(animal);
}
}
public boolean IDAlreadyExists(int ID){
for(Animal animal: fileArray){
if(animal.getID() == ID){
return true;
}
}
return false;
}
public int readID(){
int ID = inputValidator.readInt();
while(IDAlreadyExists(ID) || ID < 0){
if(ID < 0){
System.out.println("The ID cannot be negative. Please enter a positive ID: ");
}
if(IDAlreadyExists(ID)){
System.out.println("This ID is already in use. Please enter a different one: ");
}
ID = inputValidator.readInt();
}
return ID;
}
public Date readDate() {
String date = "";
System.out.println("Enter day of birth:");
int day = inputValidator.readInt();
while (day < 1 || day > 31) {
System.out.println("Invalid number. Please enter a number between 1-31");
day = inputValidator.readInt();
}
if (day < 10) {
date += "0" + day + "/";
} else {
date += day + "/";
}
System.out.println("Enter month of birth:");
int month = inputValidator.readInt();
while (month < 1 || month > 12) {
System.out.println("Invalid number. Please enter a number between 1-12");
month = inputValidator.readInt();
}
if (month < 10) {
date += "0" + month + "/";
} else {
date += month + "/";
}
System.out.println("Enter year of birth:");
int year = inputValidator.readInt();
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
while(year < 1900 || year > currentYear){
System.out.println("Invalid number. Please enter a number between 1900 and " + currentYear);
year = inputValidator.readInt();
}
date += year + "";
Date dateOfBirth = new Date();
try {
dateOfBirth = dateFormatter.parse(date);
}
catch(Exception e){
System.out.println(e.getMessage());
}
return dateOfBirth;
}
}
</code></pre>
<p>InputValidator.java</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class InputValidator {
private Scanner reader;
public InputValidator(){
reader = new Scanner(System.in);
}
public int readInt(){
int input = 0;
boolean gotCorrect = false;
while(!gotCorrect) {
try {
input = Integer.parseInt(reader.nextLine());
gotCorrect = true;
} catch (Exception e) {
System.out.println("Please enter a valid number");
}
}
return input;
}
}
</code></pre>
<p>The text file where the information is stored has the source <code>src/animal.txt</code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T12:55:16.450",
"Id": "434604",
"Score": "0",
"body": "It's my personal opinion that this reads an awful lot like one of Oracle's Java certification questions. Can anyone with more recent experience suggest that the certification questions have moved in a different direction?"
}
] | [
{
"body": "<p><em>Unfortunately I don't have time to finish my answer right now, but here's what I think so far:</em></p>\n\n<h3>Main.java</h3>\n\n<p>If your whole program is built around reading and manipulating a single file, it's customary and useful to take the name of that file in as a parameter (i.e. read it from <code>args</code>) instead of hardcoding it. (In future versions you might replace the filename with, say, the connection information for the database.)</p>\n\n<h3>Animal.java</h3>\n\n<p>No real objections to the current code. This would be a good place to put a <code>Species</code> enum. (See AnimalHandler.java).</p>\n\n<h3>UserTextInterface.java</h3>\n\n<ul>\n<li>The only reason <code>processInput()</code> returns a boolean is to break out of the one-line while-loop in <code>run()</code>, but the while-loop in <code>run()</code> literally does nothing. It doesn't even call <code>processInput()</code> more than once, since <code>processInput()</code> will never return <code>true</code>. So just give <code>processInput()</code> a <code>void</code> return type and have <code>run()</code> call it normally. It's exactly the same behavior.</li>\n<li>In <code>processInput()</code>, the if-statement in the while-loop ends with an empty branch (<code>else { }</code>). This is unnecessary and should be removed.</li>\n</ul>\n\n<h3>AnimalHandler.java</h3>\n\n<ul>\n<li>A bit off-topic: this code loads all the data from your \"database\" (the file) into an in-program, in-memory structure (<code>fileArray</code>). This is fine for the current program, but since you say you want to use an online database in the future, I feel it's only fair to warn you that this pattern would not work well for that case. It would produce a very slow program. Ideally you would want some kind of database-interface class with useful methods like <code>findAnimal(int ID)</code>, <code>updateAnimal(Animal animal)</code>, etc., that could be then be used by an interact-with-users class. </li>\n<li><code>fileArray</code> is a bad name for your List object. Arrays and lists are not the same thing in Java, and <code>fileArray</code> sounds more like an array <em>of</em> files than an array of things <em>from</em> a file. </li>\n<li>You spend a lot of time searching for animals by ID by looping through <code>fileArray</code> and checking each ID individually. This will become increasingly inefficient as the list of animals grows longer. It would be far more efficient to replace the List with a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">Map</a>, using the IDs as the keys and the Animals as the values.</li>\n<li>Since the <code>addDog()</code> and <code>addCat()</code> methods are doing pretty much the same thing, you could combine them a more generic <code>addAnimal()</code> method that takes a <code>species</code> parameter. I think that a string would be good enough at present (you can capitalize or de-capitalize the first letter as needed), but you could also create a new <code>Species</code> <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow noreferrer\">enum</a> with useful properties. This will make the code easier to extend if you decides to add more animal types in the future (hamsters, goldfish, parrots, etc.).\n\n<ul>\n<li>Frankly, even the enum is not ideal, since you have to recompile the code every time you want to add a new species. It would be even better if you had a proper <code>Species</code> class and were able to load the species data from an external source as well (file, database, administrator input, etc.).</li>\n</ul></li>\n<li>In <code>readDate()</code>, instead of building the <code>date</code> string as you go, you can wait until the end and use <code>String.format()</code> to build the string from all your integers at once. With the right format string, this will also do all the zero-padding that you're currently doing with if-statements.\n<code>String date = String.format(\"%02d/%02d/%d\", day, month, year);</code>\n\n<ul>\n<li>Actually, I'm not 100% sure that <code>dateFormatter.parse()</code> even needs the zero-padding. Need to do a little more research on that.</li>\n</ul></li>\n<li>A bit off-topic again: I see that you have two separate but basically-identical <code>SimpleDateFormat</code> objects based on the pattern <code>\"dd/MM/yyyy\"</code>, one in this file and one in <code>FileHandler</code>. I just want to emphasize that this is a <strong>good</strong> thing. <code>AnimalHandler</code> does not know how <code>FileHandler</code> handles reading dates from or writing dates to the file, and it doesn't <em>need</em> to know that. You could change the pattern for one <code>SimpleDateFormat</code> and it wouldn't matter at all to the other one. Encapsulation is good.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T23:20:03.410",
"Id": "224068",
"ParentId": "224058",
"Score": "3"
}
},
{
"body": "<p>OOP considerations:</p>\n\n<p>Dog and Cat are both animals; You should have <code>Dog</code> and <code>Cat</code> classes which extend <code>Animal</code>.\nYou have basically three concerns (business logic) in your application: </p>\n\n<p>(1) Get input from command line, </p>\n\n<p>(2) Validate inputs and translate inputs to entity, </p>\n\n<p>(3) Apply CRUD operations to perform on entities.\nYou can create one interface for each of these.</p>\n\n<pre><code>interface CommandHandler {\n handleCommand(AddAnimalCommand command);\n handleCommand(UpdateAnimalCommand command);\n //...\n}\n</code></pre>\n\n<p>Validator (this keeps all your validation logic in one place):</p>\n\n<pre><code>//Return error message if not valid else return EMPTY_STRING (Don't ever return null!)\ninterface Validator {\n String validateId(int id);\n String validateDate(String date);\n}\n</code></pre>\n\n<p>DataStore (this provides flexibility of moving from file storage to other storage systems e.g. DB, Excel etc), you just create one more implementation class and use that:</p>\n\n<pre><code>interface DataStore {\n void save(Animal animal);\n Animal get(int id);\n void update(Animal animal);\n void delete(int id);\n}\n</code></pre>\n\n<p>There are few observations in your coding:</p>\n\n<p><code>readID()</code> could be simplified.</p>\n\n<pre><code> int readId(){\n while(true){\n int id = readInt();\n String err = validator.validate(id);\n if(validator.isEmpty()) return id;\n System.out.println(err);\n }\n }\n</code></pre>\n\n<p>Could you not take dateOfBirth in a specific format from user? Like '<em>Enter date of birth in year-month-day (for example 1990-03-10) format.</em>'?</p>\n\n<p>Remember to break the code into interfaces with clear functionality (one responsibility), implementing classes, helper classes, and methods which are not long and have meaningful names.\n<code>AnimalHandler</code> does not look a good name.\nI will advise to install SONAR in your IDE (better if you are using IntelliJ), it highlights bad coding practices, can sometimes report possibility of NullPointerException too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:14:45.393",
"Id": "434630",
"Score": "0",
"body": "What I did at first is have `Dog` and `Cat` extend `Animal`. But it made things more complicated, and I was advised against it on the /r/learnprogramming Discord server. The reasoning was that there are many more animals than dogs and cats, and it can spiral out of control."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T17:23:06.023",
"Id": "434632",
"Score": "0",
"body": "Having classes like Dog and Cat gives you an advantage of flexibility, you can handle different animals differently. However, in your current requirement scope this is not clear, so you can instead have `enum AnimalType { Dog, Cat }` or `Species` seems fine too, just make it enum."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:51:38.580",
"Id": "224104",
"ParentId": "224058",
"Score": "2"
}
},
{
"body": "<p><strong>Animal.java</strong></p>\n\n<ul>\n<li>I do not know which version of Java you are using, but consider version 8 as it is pretty much the industry standard now and use <code>LocalDate</code> instead of <code>Date</code></li>\n<li><code>species</code> seems like it should be an <code>Enum</code>, not a <code>String</code></li>\n</ul>\n\n<p><strong>InputValidator.java</strong></p>\n\n<ul>\n<li>Keep your scopes to smallest possible, why is <code>Scanner</code> an instance field?</li>\n<li>Do not forget to <code>close</code> your <code>Scanner</code></li>\n</ul>\n\n<pre><code>public class InputValidator {\n public int readInt() {\n Scanner sc = new Scanner(System.in);\n int input = 0;\n boolean gotCorrect = false;\n while (!gotCorrect) {\n try {\n input = Integer.parseInt(sc.nextLine());\n gotCorrect = true;\n } catch (Exception e) {\n System.out.println(\"Please enter a valid number\");\n }\n }\n sc.close();\n return input;\n }\n}\n</code></pre>\n\n<ul>\n<li>With all this said, I am not super convinced this should be a class, lets get back to this later</li>\n</ul>\n\n<p><strong>FileHandler.java</strong></p>\n\n<ul>\n<li>I will omit <code>save</code> and make comments on <code>load</code></li>\n<li>Again we are using <code>LocalDate</code> and keeping our scopes small</li>\n<li>Inform the user when an Animal can not be loaded, do not add it with just wrong date of birth</li>\n<li>Do not forget to close your <code>Closable</code>s</li>\n</ul>\n\n<pre><code>public class FileHandler {\n\n private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n\n public List<Animal> load(String filePath) {\n try (Scanner scanner = new Scanner(new File(filePath))) {\n List<Animal> contents = new ArrayList<>();\n while (scanner.hasNextLine()) {\n String[] parts = scanner.nextLine().split(\":\");\n try {\n LocalDate dateOfBirth = LocalDate.parse((parts[4]), dateFormatter);\n contents.add(new Animal(parts[0], Integer.parseInt(parts[1]), parts[2], parts[3], dateOfBirth));\n } catch (Exception e) {\n System.out.println(\"Animal: \" + parts[0] + \" could not be read!\");\n System.out.println(e.getMessage());\n }\n }\n return contents;\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return new ArrayList<>();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:16:05.490",
"Id": "224119",
"ParentId": "224058",
"Score": "2"
}
},
{
"body": "<p>I think this bit is worth refactoring:</p>\n\n<pre><code> public void printOptions(){\n System.out.println(\"Options:\");\n System.out.println(\"0. Quit\");\n System.out.println(\"1. Add a new dog\");\n System.out.println(\"2. Add a new cat\");\n System.out.println(\"3. Print all animals\");\n System.out.println(\"4. Delete an animal\");\n System.out.println(\"5. Update an animal\");\n }\n\n public boolean processInput(){\n int input = inputValidator.readInt();\n while(input != 0){\n if(input == 1){\n animalHandler.addDog();\n }\n else if(input == 2){\n animalHandler.addCat();\n }\n else if(input == 3){\n animalHandler.printAllAnimals();\n }\n else if(input == 4){\n animalHandler.removeAnimal();\n }\n else if(input == 5){\n animalHandler.updateAnimal();\n }\n else{\n\n }\n input = inputValidator.readInt();\n }\n return false;\n }\n}\n</code></pre>\n\n<p>Suppose your client comes to you and tells you they want to be able to do 10 more things with the data from the database. What you have now suffices for a small set of operations but is not scalable. Each new operation will require a print statement for the prompt and an addition to the <code>processInput</code>, making the function monstrous and difficult to manage.</p>\n\n<p>Though I don't know how the design would go, I would suggest creating an <code>Option</code> class hierarchy of some sort, where an <code>Option</code> has a <code>prompt</code>, a handler (maybe a class instance that it owns? Not sure), and a mechanism by which outside classes can \"select\" that option.</p>\n\n<p>I'm sure there's a better way to do this, though, but that's the best alternative I can think of at the moment.</p>\n\n<p>Edit: another issue with your approach is the reliance on magic numbers for the menu selections that the user inputs (e.g., the logic that 1 == \"Add new dog\"). There's a disconnect between the strings used to represent the menu options and the numbers you use to denote those options. If you rearrange the menu options, you'll have to very carefully review the code to ensure that nothing breaks. I'd recommend defining these using an enum instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T22:29:41.353",
"Id": "224124",
"ParentId": "224058",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224068",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T20:51:09.670",
"Id": "224058",
"Score": "3",
"Tags": [
"java",
"file",
"database"
],
"Title": "Java program to manage animal data and store them in text files"
} | 224058 |
<p>I would like to get some feedback on my completed code that finds and displays the articulation vertices in an undirected graph.</p>
<p>I included a test case within the code, it should (and does) print <code>c</code> as the only articulation vertex.</p>
<p>Also I would like to clarify my understanding on some things,</p>
<ol>
<li><p>This runs in <span class="math-container">\$\mathcal{O}(V+E)\$</span> time</p>
</li>
<li><p>In the final line of code I do, <code>low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])</code></p>
<p>Does it make a difference if I use the fixed discovered position as shown above, or the lowest reachable visited vertex position (<code>low_vis</code>), my own tests showed no difference and the same answer was returned (<code>c</code>).</p>
</li>
</ol>
<p>Thank you</p>
<pre><code>class vertex:
def __init__(self, key):
self.neighbours = {}
self.key = key
def add(self, key, edge):
self.neighbours[key] = edge
class graph:
def __init__(self):
self.root = {}
self.nbnodes = 0
self.curr = 0
def add(self, key1, key2, edge=0):
if key1 not in self.root:
self.root[key1] = vertex(key1)
self.nbnodes += 1
if key2 not in self.root:
self.root[key2] = vertex(key2)
self.nbnodes += 1
self.root[key1].add(key2, edge)
self.root[key2].add(key1, edge)
def cutver(self):
visited = set()
discovered = {}
low_vis = {}
parent = {}
result = []
for vertex in self.root:
if vertex not in visited:
parent[vertex] = -1
self._cutver(vertex, parent, visited, discovered, low_vis, result)
print(result)
def _cutver(self, vertex, parent, visited, discovered, low_vis, result):
visited.add(vertex)
discovered[vertex] = self.curr
low_vis[vertex] = self.curr
children = 0
self.curr += 1
for neighbour in self.root[vertex].neighbours:
if neighbour not in visited:
parent[neighbour] = vertex
children += 1
self._cutver(neighbour, parent, visited, discovered, low_vis, result)
low_vis[vertex] = min(low_vis[vertex], low_vis[neighbour])
if children > 1 and parent[vertex] == -1:
result.append(vertex)
if parent[vertex] != -1 and low_vis[neighbour] >= discovered[vertex]:
result.append(vertex)
elif neighbour != parent[vertex]:
low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])
if __name__ == '__main__':
a = graph()
A = 'A'
B = 'B'
C = 'C'
D = 'D'
E = 'E'
a.add(A,B)
a.add(A,C)
a.add(B,D)
a.add(D,C)
a.add(C,E)
a.cutver()
</code></pre>
| [] | [
{
"body": "<h1>PEP-8</h1>\n<pre><code>class vertex:\nclass graph:\n</code></pre>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> asks that you name these <code>Vertex</code> and <code>Graph</code>, with initial capital.</p>\n<h1>naming nodes</h1>\n<pre><code> self.key = key\n</code></pre>\n<p>Yes, you will be using this as a <code>dict</code> key.\nBut <code>name</code> would have been the more natural identifier for a node name.</p>\n<h1>unused attribute</h1>\n<p>Please delete this line:</p>\n<pre><code> self.nbnodes = 0\n</code></pre>\n<p>That quantity may be trivially obtained with <code>len(self.root)</code>,\nand in any event you never reference it.</p>\n<h1>edge weight</h1>\n<p>At first blush this appears to be a default edge ID of zero:</p>\n<pre><code>def add(self, key1, key2, edge=0):\n</code></pre>\n<p>Later it looks more like an edge weight, an attribute of the edge.\nIt would be helpful for a docstring to clarify this.\nOr just name it <code>edge_weight</code>.</p>\n<h1>API</h1>\n<p>Consider having <code>cutver()</code> print nothing,\nand instead <code>return</code> a result which the caller may print.</p>\n<p>Also, <code>_cutver()</code> feels a lot like a Fortran subroutine,\nas it has side effects on the <code>result</code> parameter,\nrather than <code>return</code>ing a result.</p>\n<h1>sentinel</h1>\n<p>You use this:</p>\n<pre><code> parent[vertex] = -1\n</code></pre>\n<p>without every verifying that a node name is not <code>-1</code>,\nor constraining each node name to be a <code>str</code>.\nThe usual convention would be to use <code>None</code> to represent this.</p>\n<h1>docstring</h1>\n<pre><code> self.curr = 0\n</code></pre>\n<p>This is absolutely not self-descriptive enough.\nUse a <code>"""docstring"""</code> or <code>#</code> comment to tell us what quantity it is measuring.</p>\n<h1>reference</h1>\n<p>In general <code>_cutver()</code> is obscure,\nwhich increases the difficulty of answering your two questions.\nIt cites no references and does not attempt to justify\nany of its algorithmic steps.\nPerhaps it correctly finds cut vertices,\nbut the text does not give us any reason to see why that is obviously true.\nIf the code tries to adhere to Hopcroft73 (with Tarjan, algorithm 447),\nthen choosing to omit identifiers like <code>lowpoint</code>\nis not helping the reader to see how the current implementation\ncorresponds to what Hopcroft describes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:21:14.963",
"Id": "224108",
"ParentId": "224063",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T22:08:02.140",
"Id": "224063",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"graph",
"depth-first-search"
],
"Title": "Find articulation points/ cut vertices in graph"
} | 224063 |
<p>This is my first time doing a code review so I expect a ton of criticism on this from all you professionals.</p>
<p><strong>What am I doing?</strong></p>
<p>I'm using python with flask to create a service for my web server. My web server has a login prompt for passing login info into the python service. The request is received as a JSON string element and is converted into a dictionary in python. Then I have my service validate that info to check for any issues with their submission. If any issues were present then I send back a 401 code letting the user know that their login failed. If validation was successful then the user is granted a session cookie and the service creates a thread that stores an object of the thread with the session and Instagram login instance. The user is also sent to the dashboard to control their instance.</p>
<p><strong>What do I need?</strong></p>
<p>I've never been code reviewed before so I really need someone to tear at this. I need to see if there are any issues regarding said code. The code works and there is no runtime issues present.</p>
<p>One of the main concerns is that on line 78 I'm making 2 json.loads executions and all I know is that one doesn't suffice.</p>
<p>Anyways let me know what I should improve.</p>
<pre class="lang-py prettyprint-override"><code>from flask import *
from flask_wtf.csrf import CSRFProtect
from flask_wtf.csrf import CSRFError
from InstagramAPI import InstagramAPI
from instasession import InstaSession
import threading
import json
import os
import time
import re
app = Flask(__name__)
app.secret_key = os.urandom(32)
csrf = CSRFProtect(app)
app.wtf_csrf_secret_key = os.urandom(32)
csrf.init_app(app)
activeSessions = list() # Active instagram sessions.
#CSRF Protection
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
return "Invalid CSRF token."
@app.route('/', methods=['GET'])
@app.route('/index', methods=['GET'])
def index():
if 'user' in session:
print("Loged In!")
return redirect(url_for("dashboard"))
else:
print("Not Loged In")
return render_template('index.html')
@app.route('/login', methods=['POST'])
def login():
print("GOT LOGIN REQUEST")
data = json.loads(request.data)
username = data["username"]
password = data["password"]
if validate_username(username) is False:
abort(401)
# TODO: Perform check on username to see if instance already exist so we can just resume their instance
# instead of creating a whole new instance.
# Perform Instagram Login
newLogin = InstagramAPI(username, password)
if newLogin.login():
print("Succesfull Login")
session['user'] = username # Store session cookie
# Give the user a thread for their session.
newThread = threading.Thread(target=process_action, args=(session['user'],))
newInstance = InstaSession(newThread, session['user'], newLogin)
newThread.start()
activeSessions.append( newInstance ) # Store Action Info
return "success"
else:
print("Login Failed")
abort(401)
#Called whenever the user wants to run a function or get information
@app.route('/action', methods=['POST'])
def action():
if 'user' in session:
if request.method == 'POST':
# Why do we need to use json.loads twice?!
requestedData = json.loads(json.loads(request.data))
if "method" in requestedData:
print(requestedData["method"])
if requestedData["method"] == "autolike":
print("Auto like Method")
update_actions(session['user'], requestedData)
return '{"method" : "auto-like-start"}'
elif requestedData["method"] == "stoplike":
print("Auto like Method")
update_actions(session['user'], requestedData)
return '{"method" : "auto-like-stop"}'
elif requestedData["method"] == "autocomment":
print("Auto Commenting")
elif requestedData["method"] == "getlikeslog":
instance = get_current_session( session['user'] )
if instance is not None:
return '{"updatelikes" : "'+str(instance.get_logs())+'"}'
else:
return "Invalid request!"
else:
return "Method does not exist"
else:
return "Request is missing method"
else:
return redirect(url_for("index"))
@app.route('/dashboard', methods=['GET'])
def dashboard():
if 'user' in session:
return render_template('dashboard.html')
else:
return redirect(url_for("index"))
@app.route('/logout', methods=['GET'])
def loutout():
if 'user' in session:
session.pop('user')
return "You Loged Out!"
else:
return redirect(url_for("index"))
def get_current_session( currentSession ):
time.sleep(1) #Why?
for i in range(len(activeSessions)):
if activeSessions[i].session == currentSession:
return activeSessions[i]
print("Could not find a session with users cookie")
return None
# Updates the variables for the threads.
def update_actions( currentSession, newAction ): # TODO: Use pythonic code format.
instance = get_current_session( currentSession )
if instance is not None:
instance.action = newAction
# Returns the subsession data for this cookie
def get_actions( currentSession ):
instance = get_current_session( currentSession )
if instance is not None:
return instance.action
# Threaded function that handles all instagram actions. Variables should be changed on the fly.
def process_action( session ):
instance = get_current_session(session)
isDone = False
action = instance.get_action()
while not isDone:
isNewAction = False
time.sleep(1)
action = instance.get_action()
if action is not None:
if "method" in action:
if action["method"] == "logout":
print("Stopping Instance")
instance.logout()
elif action["method"] == "autolike":
print("AUTO LIKE")
print("Tag:"+action["tag"])
instance.instagram.tagFeed(action["tag"])
lastJson = instance.instagram.LastJson
count = len(lastJson["items"])
for i in range(count):
if lastJson["items"][i]["has_liked"] is False:
if isNewAction:
break
postID = lastJson["items"][i]["id"]
instance.instagram.like(postID)
instance.set_logs(str(postID))
print("Liked Photo!" + str(postID))
for i in range(45):
time.sleep(1)
newAction = instance.get_action()
if action != newAction:
isNewAction = True
print("Message is different. Switching to new action")
break
# Performs validation on the username that way we don't get untrusted data.
def validate_username( username ):
try:
if len(username) > 30:
if not re.match(r'^[a-zA-Z0-9._]+$',username):
if username[0] == '.':
if username[len(username) - 1] == '.':
return True
except ValueError:
return False
</code></pre>
<p>This is the javascript for the dashboard</p>
<pre><code>var csrfToken = null
var logInterval = null
function DisplayMenu( menu ){
var menus = document.querySelectorAll(".submenu");
for(var i = 0; i < menus.length; i++){
if(menus[i].id == menu){
menus[i].style.display = "block";
} else {
menus[i].style.display = "none";
}
}
}
function ProccessResponse(response){
var jsonResponse = JSON.parse(response);
console.log(response.method);
if(jsonResponse.method == "auto-like-start"){
document.getElementById("like-start").disabled = true;
document.getElementById("like-stop").disabled = false;
} else if(jsonResponse.method == "auto-like-stop"){
document.getElementById("like-start").disabled = false;
document.getElementById("like-stop").disabled = true;
clearInterval(logInterval); // Stop logging.
logInterval = null;
} else if(jsonResponse.updatelikes) {
console.log("Got Update!");
var newEntry = document.getElementById("likes-log").value.concat( "Liked photo:" + jsonResponse.updatelikes + "\n" );
document.getElementById("likes-log").value = newEntry;
}
}
function SendRequest( method, endpoint, request ){
var xhttp = new XMLHttpRequest();
xhttp.open(method,endpoint,true);
xhttp.setRequestHeader("X-CSRFToken", csrfToken);
xhttp.send( JSON.stringify( request ) );
xhttp.onreadystatechange = function() {
if(xhttp.status == 200){
var response = xhttp.responseText;
console.log(response);
ProccessResponse(response);
} else {
console.log(xhttp.status);
}
}
}
async function LogLikes(){
if(!logInterval){
//SendRequest("GET","/action", '{"method" : "loglikes"}');
logInterval = setInterval(function() { SendRequest("POST","/action", '{"method" : "getlikeslog"}') }, 45000);
document.getElementById("likes-log").scrollTop = document.getElementById("likes-log").scrollHeight;
}
}
window.onload = function(){
var $ = function(id){ return document.getElementById(id); }
csrfToken = document.getElementsByTagName("meta")[0].content;
DisplayMenu("None"); // Hide everything Initally.
// Auto Liker Button
$("autolike-btn").addEventListener("click",function(){
DisplayMenu("autolike-menu");
})
// Auto Liker Tag
$("like-start").addEventListener("click",function(){
var tag = $("like-tag").value;
console.log(tag);
SendRequest("POST","/action", '{"method" : "autolike" , "tag" : "'+tag+'" }');
$("likes-log").value = "Starting Like Automation on tag: "+tag+"\n";
LogLikes();
})
$("like-stop").addEventListener("click",function(){
SendRequest("POST","/action", '{"method" : "stoplike"}');
$("likes-log").value = "Stopping Liking...";
})
// Auto Liker Button
$("autocomment-btn").addEventListener("click",function(){
DisplayMenu("autocomment-menu");
})
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T01:52:41.403",
"Id": "434565",
"Score": "1",
"body": "Do you have a sample record of what actually gets POSTed to `/action`? Alternatively, could you show us the form that leads to the POST to `/action` (maybe the `dashboard.html` template)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T03:10:52.680",
"Id": "434569",
"Score": "0",
"body": "I made an edit to this post. You can check out my .js code. The window.onload contains the \"like-start\" event listener that sends the json string to the server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T03:15:52.547",
"Id": "434570",
"Score": "1",
"body": "The `SendRequest()` function `JSON.stringify()`s the `request` parameter, but in `LogLikes()`, you're calling `SendRequest()` with a third argument that is already a string — `'{\"method\" : \"getlikeslog\"}'`. If you don't double-stringify, then you shouldn't have to double-decode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T04:02:51.050",
"Id": "434576",
"Score": "0",
"body": "Thanks for pointing that out I'll make that change. I just need someone to review my code in python and javascript and determine what kind of improvements I should make."
}
] | [
{
"body": "<p>I haven't written JavaScript or dealt with Flask for a couple years, but here are some suggestions for the Python code:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. In your case <code>process_action</code> is a good place to start pulling things apart.</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n\n<p>Assuming the above have been taken care of:</p>\n\n<ol>\n<li>Variable naming is incredibly important for maintainability. Unfortunately vacuous names like <code>data</code> are common, but I would recommend thinking about them and renaming them to something which is readable. In this case something like <code>request_parameters</code> might be appropriate.</li>\n<li>Having two routes to the main page is a bit confusing. I would suggest avoiding future headaches by having only a single canonical URL per page.</li>\n<li><a href=\"https://docs.python.org/3/library/http.html#http.HTTPStatus\" rel=\"nofollow noreferrer\">http.HTTPStatus</a> contains values for HTTP status codes, which is more readable than magic values.</li>\n<li>Initializing a variable with <code>list()</code> rather than <code>[]</code> is unusual. I don't expect it will actually make any practical difference, but it does stand out a bit.</li>\n<li>Rather than <code>print</code>ing I would recommend using <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> instead - it's much more flexible for when you want to move to more production-like log handling.</li>\n<li><a href=\"https://docs.python.org/3.5/library/json.html\" rel=\"nofollow noreferrer\"><code>json.dumps</code></a> is preferable to manual string building. It handles things like escaping for you, and also makes it easy for you to deal with Python <code>dict</code>s and <code>list</code>s until the very end.</li>\n<li><p>Try to aim for less nesting where possible. Returning early is one way to achieve this. For example,</p>\n\n<pre><code>if 'user' in session:\n [lots of indented code]\nelse:\n return redirect(url_for(\"index\"))\n</code></pre>\n\n<p>could instead be written as</p>\n\n<pre><code>if 'user' not in session:\n return redirect(url_for(\"index\"))\n[lots of dedented code]\n</code></pre>\n\n<p>. The same technique can be easily applied to <code>validate_username</code>.</p></li>\n<li><code>time.sleep</code> is not going to be accepted in production code. Not even for a millisecond. If for whatever reason things don't work when running with the breaks off, debug until it works with the breaks off.</li>\n<li>You have some magic values like <code>45</code> in your code. Since it's not obvious what they mean they should either be changed to refer to some third-party constant or be pulled out to a variable or constant clearly indicating what they are.</li>\n<li><code>username[len(username) - 1]</code> can be written <code>username[-1]</code>.</li>\n<li><p><code>validate_username</code> is either very buggy or extremely confusing. First, it returns either <code>True</code>, <code>False</code> or <code>None</code>, but a method like this should never rely on type coercion. Second, it returns <code>True</code> if a <em>bunch</em> of things are wrong with the username, <code>False</code> in case of <code>ValueError</code>, and <code>None</code> in every other case. Third, since</p>\n\n<pre><code>>>> None is False\nFalse\n</code></pre>\n\n<p>almost every weird username will be accepted as valid.</p></li>\n</ol>\n\n<p>In conclusion: like most Python code this could benefit from common language patterns and a thorough set of tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:44:28.570",
"Id": "434649",
"Score": "1",
"body": "Wow, this was a very in-depth examination of my code I'm really grateful that you took apart and busted it open. I can see so many things I need to improve now! I'll apply all the fixes you suggested. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T10:14:24.807",
"Id": "224084",
"ParentId": "224071",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224084",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T01:04:49.350",
"Id": "224071",
"Score": "4",
"Tags": [
"python",
"authentication",
"session",
"flask"
],
"Title": "Account automation through Python (with Flask) and javascript"
} | 224071 |
<p>I know this is <strong>horrible</strong> code. This program is for performing modeling, view and projection transformation. </p>
<p>The program reads input from <code>scene.txt</code> and outputs the <code>modeling transformation</code> in <code>stage1.txt</code>, <code>view transformation</code> in <code>stage2.txt</code>, <code>projection transformation</code> in <code>stage3.txt</code>. The files are added below.</p>
<p>I haven't utilized the functionalities of <code>C++</code> and the writing style is clumsy. I want to know how I could have written this same code with better <code>time</code>,<code>space complexity</code>, <code>data structure</code> and also with better elegance. </p>
<p>I have commented but someone pointed out that it was not enough. Where else should I be commenting? </p>
<blockquote>
<p><code>scene.txt</code></p>
</blockquote>
<pre><code>0.0 0.0 50.0
0.0 0.0 0.0
0.0 1.0 0.0
80.0 1.0 1.0 100.0
triangle
0.0 0.0 0.0
5.0 0.0 0.0
0.0 5.0 0.0
push
scale
2.0 2.0 2.0
triangle
0.0 0.0 0.0
5.0 0.0 0.0
0.0 5.0 0.0
translate
10.0 0.0 0.0
triangle
0.0 0.0 0.0
5.0 0.0 0.0
0.0 5.0 0.0
rotate
90.0 0.0 0.0 1.0
triangle
0.0 0.0 0.0
5.0 0.0 0.0
0.0 5.0 0.0
pop
triangle
0.0 0.0 0.0
20.0 0.0 0.0
0.0 20.0 0.0
end
</code></pre>
<blockquote>
<p><code>main.cpp</code></p>
</blockquote>
<pre><code>//
// Created by afsara on 7/11/19.
//
#include <iostream>
#include <stack>
#include <vector>
#include <cstdio>
#include <fstream>
#include <cmath>
#include <cstring>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const double PI = acos(-1.0);
const double EPS = 1e-4;
ifstream infile, infile2, infile3;
ofstream outfile, outfile2, outfile3;
int sz = 4;
stack<float (*)[10]> s;
stack<int> Size;
struct Point {
float x, y, z, w = 1;
Point() {}
};
struct Vector {
float x, y, z, w = 0;
Vector() {
x = x;
y = y;
z = z;
};
Vector(float vx, float vy, float vz) {
x = vx;
y = vy;
z = vz;
w = 0;
}
};
Vector eye(0, 0, 0), look(0, 0, 0), up(0, 0, 0);
float fovY, aspectRatio, near, far;
/* functions */
float (*matrixMultiplication(float firstMatrix[][10], float secondMatrix[][10],
int rowFirst,
int columnFirst, int rowSecond, int columnSecond))[10];
float (*makeIdentityMatrix(int identity_sz))[10];
void showstack(stack<float (*)[10]> s);
void insertToStack(float arr[][10]);
float (*makeTranslationMatrix(float transX, float transY, float transZ))[10];
float (*makeScalingMatrix(float scaleX, float scaleY, float scaleZ))[10];
inline double degToRad(double ang);
static inline bool isNearlyEqual(const double &a, const double &b);
float Cos(float angle);
float Sin(float angle);
float Tan(float angle);
Vector crossProduct(const Vector &vec1, const Vector &vec2);
float dotProduct(const Vector &vec1, const Vector &vec2);
Vector normalize(Vector a);
Vector multiply(Vector v, float scalar);
Vector add(Vector v1, Vector v2);
Vector subtract(Vector v1, Vector v2);
Vector rotateRod(Vector x, Vector rotateAxis, float rotateAngle);
void printMatrix(float (*matrix)[10]);
void printMatrix2(float (*matrix)[10]);
void printMatrix3(float (*matrix)[10]);
void print(float (*matrix)[10]);
void printTokens(vector<string> tokens[100], int line_num);
void readFromFile();
void readFromStage1File();
void readFromStage2File();
int main() {
float (*identityMatrix)[10] = makeIdentityMatrix(sz);
insertToStack(identityMatrix);
outfile.open("stage1.txt");
readFromFile();
outfile.close();
outfile2.open("stage2.txt");
readFromStage1File();
outfile2.close();
outfile3.open("stage3.txt");
readFromStage2File();
outfile3.close();
return 0;
}
inline double degToRad(double ang) {
return ang * PI / 180.0;
}
static inline bool isNearlyEqual(const double &a, const double &b) {
return abs(a - b) < EPS;
}
float Cos(float angle) {
float var = cos(degToRad(angle));
if (isNearlyEqual(var, 0)) var = 0;
return var;
}
float Sin(float angle) {
float var = sin(degToRad(angle));
if (isNearlyEqual(var, 0)) var = 0;
return var;
}
float Tan(float angle) {
float var = tan(degToRad(angle));
if (isNearlyEqual(var, 0)) var = 0;
return var;
}
Vector crossProduct(const Vector &vec1, const Vector &vec2) {
Vector res;
res.x = vec1.y * vec2.z - vec2.y * vec1.z;
res.y = vec1.z * vec2.x - vec2.z * vec1.x;
res.z = vec1.x * vec2.y - vec2.x * vec1.y;
return res;
}
float dotProduct(const Vector &vec1, const Vector &vec2) {
float res;
res += vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z;
if (isNearlyEqual(res, 0)) res = 0;
return res;
}
Vector normalize(Vector a) {
float val = sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
Vector p;
p.x = a.x / val;
p.y = a.y / val;
p.z = a.z / val;
//cout << "\nnormalizing\n[ " << p.x << " " << p.y << " " << p.z << " " << p.w << " ] \n";
return p;
}
Vector multiply(Vector v, float scalar) {
// cout << "scalar is " << scalar << endl;
v.x = v.x * scalar;
v.y = v.y * scalar;
v.z = v.z * scalar;
return v;
}
Vector add(Vector v1, Vector v2) {
Vector ret(0, 0, 0);
ret.x = v1.x + v2.x;
ret.y = v1.y + v2.y;
ret.z = v1.z + v2.z;
return ret;
}
Vector subtract(Vector v1, Vector v2) {
Vector ret;
ret.x = v1.x - v2.x;
ret.y = v1.y - v2.y;
ret.z = v1.z - v2.z;
return ret;
}
Vector rotateRod(Vector x, Vector rotateAxis, float rotateAngle) {
Vector temp1 = multiply(x, Cos(rotateAngle)); //cos(theta)*x ; x is a vector
//cout << "\ntemp1 " << temp1.x << " " << temp1.y << " " << temp1.z << endl;
Vector temp2 = crossProduct(rotateAxis, x); // a cross x
// cout << "a cross x : " << rotateAxis.x << " " << rotateAxis.y << " " << rotateAxis.z << " cross " << x.x << " "
// << x.y << " " << x.z << endl;
//cout << "\ntemp2 " << temp2.x << " " << temp2.y << " " << temp2.z << endl;
Vector temp3 = multiply(temp2, Sin(rotateAngle)); //sin(theta) * (a cross x)
//cout << "\ntemp3 " << temp3.x << " " << temp3.y << " " << temp3.z << endl;
Vector temp4 = add(temp1, temp3); // cos(theta)*x + sin(theta) * (a cross x)
cout << "\ntemp4 " << temp4.x << " " << temp4.y << " " << temp4.z << endl;
float temp5 = dotProduct(rotateAxis, x); // a dot x
//cout << "\ntemp5 " << temp5 << endl;
Vector temp6 = multiply(rotateAxis, temp5); // (a dot x)*a
//cout << "\ntemp6 " << temp6.x << " " << temp6.y << " " << temp6.z << endl;
Vector temp7 = multiply(temp6, (1 - Cos(rotateAngle))); // (1-cos(theta)) * (a dot x)*a
//cout << "\ntemp7 " << temp7.x << " " << temp7.y << " " << temp7.z << endl;
Vector finalR = add(temp4,
temp7); // cos(theta)*x + sin(theta) * (a cross x) + (1-cos(theta)) * (a dot x)*a
//cout << "\nfinal " << finalR.x << " " << finalR.y << " " << finalR.z << endl;
return finalR;
}
void printMatrix(float (*matrix)[10]) {
cout << "\n in print matrix \n";
for (int i = 0; i < sz - 1; ++i) {
for (int j = 0; j < sz - 1; ++j) {
cout << matrix[i][j] << " ";
outfile << setprecision(7) << fixed << matrix[j][i] << " ";
}
cout << endl;
outfile << endl;
}
outfile << endl;
}
void printMatrix2(float (*matrix)[10]) {
cout << "\n in print matrix 2\n";
for (int i = 0; i < sz - 1; ++i) {
for (int j = 0; j < sz - 1; ++j) {
cout << matrix[i][j] << " ";
outfile2 << setprecision(7) << fixed << matrix[j][i] << " ";
}
cout << endl;
outfile2 << endl;
}
outfile2 << endl;
}
void printMatrix3(float (*matrix)[10]) {
cout << "\n in print matrix 3\n";
for (int i = 0; i < sz - 1; ++i) {
for (int j = 0; j < sz - 1; ++j) {
cout << matrix[i][j] << " ";
outfile3 << setprecision(7) << fixed << matrix[j][i] << " ";
}
cout << endl;
outfile3 << endl;
}
cout<<endl;
outfile3 << endl;
}
void print(float (*matrix)[10]) {
cout << "\nprint in console\n";
for (int i = 0; i < sz; ++i) {
for (int j = 0; j < sz; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout<<endl;
}
float (*balance_W(float (*m)[10]))[10] {
float w1 = m[sz - 1][0];
float w2 = m[sz - 1][1];
float w3 = m[sz - 1][2];
for (int i = 0; i < sz; ++i) {
for (int j = 0; j < sz; ++j) {
if (j == 0) m[i][j] = m[i][j] / w1;
if (j == 1) m[i][j] = m[i][j] / w2;
if (j == 2) m[i][j] = m[i][j] / w3;
}
}
return m;
}
void printTokens(vector<string> tokens[100], int line_num) {
//printing the file content as a 2d array
for (int j = 0; j < line_num; ++j) {
for (int i = 0; i < tokens[j].size(); ++i) {
cout << j << " : " << i << " " << tokens[j][i] << " \n";
}
cout << endl;
}
}
void readFromFile() {
// open a file in read mode.
cout << "\n\n~~~~~~~~~~~~~~~~~~~~~~~~ Reading from the scene.txt file ~~~~~~~~~~~~~~~~~~~~~~~\n\n";
string line;
infile.open("scene.txt");
if (!infile.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
int line_num = 0;
vector<string> tokens[100]; // Create vector to hold the words
while (getline(infile, line)) {
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
while (ss >> buf)
tokens[line_num].push_back(buf);
line_num++;
}
//printTokens(tokens, line_num);
string command;
for (int i = 0; i < line_num; ++i) {
if (i == 0) {
eye.x = stof(tokens[i][0].c_str());
eye.y = stof(tokens[i][1].c_str());
eye.z = stof(tokens[i][2].c_str());
} else if (i == 1) {
look.x = stof(tokens[i][0].c_str());
look.y = stof(tokens[i][1].c_str());
look.z = stof(tokens[i][2].c_str());
} else if (i == 2) {
up.x = stof(tokens[i][0].c_str());
up.y = stof(tokens[i][1].c_str());
up.z = stof(tokens[i][2].c_str());
} else if (i == 3) {
fovY = stof(tokens[i][0].c_str());
aspectRatio = stof(tokens[i][1].c_str());
near = stof(tokens[i][2].c_str());
far = stof(tokens[i][3].c_str());
} else {
for (int itr = 0; itr < tokens[i].size(); ++itr) {
command = tokens[i][itr];
//start parsing commands
if (command == "triangle") {
//go to next line
i++;
cout << "found a triangle " << endl;
//input three points
struct Point firstPoint, secondPoint, thirdPoint;
firstPoint.x = stof(tokens[i][itr].c_str());
firstPoint.y = stof(tokens[i][itr + 1].c_str());
firstPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
secondPoint.x = stof(tokens[i][itr].c_str());
secondPoint.y = stof(tokens[i][itr + 1].c_str());
secondPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
thirdPoint.x = stof(tokens[i][itr].c_str());
thirdPoint.y = stof(tokens[i][itr + 1].c_str());
thirdPoint.z = stof(tokens[i][itr + 2].c_str());
float myMatrix[10][10];
vector<float> temp;
temp.push_back(firstPoint.x);
temp.push_back(secondPoint.x);
temp.push_back(thirdPoint.x);
temp.push_back(1);
temp.push_back(firstPoint.y);
temp.push_back(secondPoint.y);
temp.push_back(thirdPoint.y);
temp.push_back(1);
temp.push_back(firstPoint.z);
temp.push_back(secondPoint.z);
temp.push_back(thirdPoint.z);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
for (int j = 0; j < sz; ++j) {
for (int k = 0; k < sz; ++k) {
myMatrix[j][k] = temp.at(j * 4 + k);
}
}
/*cout << "\n\t\tABOUT TO MULTIPLY THE FOLLOWING\n\n";
print(s.top());
cout << endl;
print(myMatrix);
cout << "\n\n";*/
float (*resultant)[10];
resultant = matrixMultiplication(s.top(), myMatrix, sz, sz, sz, sz);
resultant = balance_W(resultant);
printMatrix(resultant); //T*I
print(resultant);
//showstack(s);
} else if (command == "scale") {
// input scaling factors
// generate the corresponding scaling matrix T
// S.push(product(S.top,T))
//go to next line
i++;
cout << "do scaling " << endl;
struct Point scaleFactor;
//parsing values
scaleFactor.x = stof(tokens[i][itr].c_str());
scaleFactor.y = stof(tokens[i][itr + 1].c_str());
scaleFactor.z = stof(tokens[i][itr + 2].c_str());
float (*scaleMatrix)[10] = new float[10][10];
scaleMatrix = makeScalingMatrix(scaleFactor.x, scaleFactor.y, scaleFactor.z);
//print(scaleMatrix);
float (*prev)[10];
float (*New)[10];
prev = s.top();
New = matrixMultiplication(prev, scaleMatrix, sz, sz, sz, sz);
s.push(New);
//showstack(s);
} else if (command == "translate") {
// input translation amounts
// generate the corresponding translation matrix T
// S.push(product(S.top,T))
//go to next line
i++;
cout << "do translate " << endl;
struct Point t;
//parsing values
t.x = stof(tokens[i][itr].c_str());
t.y = stof(tokens[i][itr + 1].c_str());
t.z = stof(tokens[i][itr + 2].c_str());
float (*T)[10] = new float[10][10];
T = makeTranslationMatrix(t.x, t.y, t.z);
//printMatrix(T);
float (*prev)[10];
float (*New)[10];
prev = s.top();
New = matrixMultiplication(prev, T, sz, sz, sz, sz);
s.push(New);
} else if (command == "rotate") {
// input rotation angle and axis
// generate the corresponding rotation matrix T
// S.push(product(S.top,T))
//go to next line
i++;
cout << "\t\tdo rotate " << endl;
struct Vector rotateAxis;
float rotateAngle;
//parsing values
rotateAngle = stof(tokens[i][itr].c_str());
//rotateAngle = degToRad(rotateAngle);
rotateAxis.x = stof(tokens[i][itr + 1].c_str());
rotateAxis.y = stof(tokens[i][itr + 2].c_str());
rotateAxis.z = stof(tokens[i][itr + 3].c_str());
rotateAxis = normalize(rotateAxis);
Vector c1, c2, c3;
Vector iHat(1, 0, 0), jHat(0, 1, 0), kHat(0, 0, 1);
c1 = rotateRod(iHat, rotateAxis, rotateAngle);
c2 = rotateRod(jHat, rotateAxis, rotateAngle);
c3 = rotateRod(kHat, rotateAxis, rotateAngle);
/*cout << "c1 : " << c1.x << " " << c1.y << " " << c1.z << " " << endl;
cout << "c2 : " << c2.x << " " << c2.y << " " << c2.z << " " << endl;
cout << "c3 : " << c3.x << " " << c3.y << " " << c3.z << " " << endl;*/
float R[10][10];
vector<float> temp;
temp.push_back(c1.x);
temp.push_back(c2.x);
temp.push_back(c3.x);
temp.push_back(0);
temp.push_back(c1.y);
temp.push_back(c2.y);
temp.push_back(c3.y);
temp.push_back(0);
temp.push_back(c1.z);
temp.push_back(c2.z);
temp.push_back(c3.z);
temp.push_back(0);
temp.push_back(0);
temp.push_back(0);
temp.push_back(0);
temp.push_back(1);
for (int j = 0; j < sz; j++) {
for (int k = 0; k < sz; k++) {
R[j][k] = temp.at(j * 4 + k);
}
}
cout << "printing rotation matrix" << endl;
print(R);
float (*prev)[10];
float (*New)[10];
prev = s.top();
New = matrixMultiplication(prev, R, sz, sz, sz, sz);
s.push(New);
} else if (command == "push") {
cout << "PUSH" << endl;
Size.push(s.size());
} else if (command == "pop") {
cout << "POP" << endl;
if (s.size() == 1) continue;
int l = Size.top();
Size.pop();
while (s.size() > l) {
s.pop();
}
} else if (command == "end") {
break;
}
}
}
}
infile.close();
}
void readFromStage1File() {
// open a file in read mode.
cout << "\n\n~~~~~~~~~~~~~~~~~~~~~~~~ Reading from the stage1.txt file ~~~~~~~~~~~~~~~~~~~~~~~\n\n";
string line;
infile2.open("stage1.txt");
if (!infile2.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
int line_num = 0;
vector<string> tokens[200]; // Create vector to hold the words
while (getline(infile2, line)) {
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
while (ss >> buf)
tokens[line_num].push_back(buf);
line_num++;
}
//printing the file content as a 2d array
//printTokens(tokens, line_num);
Vector l(0, 0, 0), r(0, 0, 0), u(0, 0, 0);
l = subtract(look, eye); //l = look - eye
l = normalize(l); //l.normalize()
r = crossProduct(l, up); //r = l X up
r = normalize(r); // r.normalize()
u = crossProduct(r, l); // u = r X l
//Apply the following translation T to move the eye/camera to origin.
float (*T)[10] = new float[10][10];
T = makeIdentityMatrix(sz);
T[0][sz - 1] = -eye.x;
T[1][sz - 1] = -eye.y;
T[2][sz - 1] = -eye.z;
T[3][sz - 1] = 1;
//Apply the following rotation R such that the l aligns with the -Z axis, r with X axis, and u with Y axis.
float (*R)[10] = new float[10][10];
vector<float> temp = {r.x, r.y, r.z, 0, u.x, u.y, u.z, 0, -l.x, -l.y, -l.z, 0, 0, 0, 0, 1};
for (int j = 0; j < sz; ++j) {
for (int k = 0; k < sz; ++k) {
R[j][k] = temp.at(j * 4 + k);
}
}
float (*V)[10] = new float[10][10];
V = matrixMultiplication(R, T, sz, sz, sz, sz);
//printMatrix2(V);
//V*matrix
int itr = 0;
for (int i = 0; i < line_num; i++) {
if (i == line_num - 1) {
cout << "breaking" << endl;
break;
};
if (tokens[i].size() == 0) { i++; }
//input three points
struct Point firstPoint, secondPoint, thirdPoint;
firstPoint.x = stof(tokens[i][itr].c_str());
firstPoint.y = stof(tokens[i][itr + 1].c_str());
firstPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
secondPoint.x = stof(tokens[i][itr].c_str());
secondPoint.y = stof(tokens[i][itr + 1].c_str());
secondPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
thirdPoint.x = stof(tokens[i][itr].c_str());
thirdPoint.y = stof(tokens[i][itr + 1].c_str());
thirdPoint.z = stof(tokens[i][itr + 2].c_str());
float myMatrix[10][10];
vector<float> temp;
temp.push_back(firstPoint.x);
temp.push_back(secondPoint.x);
temp.push_back(thirdPoint.x);
temp.push_back(1);
temp.push_back(firstPoint.y);
temp.push_back(secondPoint.y);
temp.push_back(thirdPoint.y);
temp.push_back(1);
temp.push_back(firstPoint.z);
temp.push_back(secondPoint.z);
temp.push_back(thirdPoint.z);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
for (int j = 0; j < sz; ++j) {
for (int k = 0; k < sz; ++k) {
myMatrix[j][k] = temp.at(j * 4 + k);
}
}
/*cout << "\t\tABOUT TO MULTIPLY THE FOLLOWING\n\n";
print(V);
cout << endl;
print(myMatrix);
cout << "\n\n";*/
float (*resultant)[10];
resultant = matrixMultiplication(V, myMatrix, sz, sz, sz, sz);
print(resultant);
printMatrix2(resultant);
}
infile2.close();
}
void readFromStage2File() {
// open a file in read mode.
cout << "\n\n~~~~~~~~~~~~~~~~~~~~~~~~ Reading from the stage2.txt file ~~~~~~~~~~~~~~~~~~~~~~~\n\n";
string line;
infile3.open("stage2.txt");
if (!infile3.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
int line_num = 0;
vector<string> tokens[200]; // Create vector to hold the words
while (getline(infile3, line)) {
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
while (ss >> buf)
tokens[line_num].push_back(buf);
line_num++;
}
//printing the file content as a 2d array
//printTokens(tokens, line_num);
float fovX = fovY * aspectRatio; //fovX = fovY * aspectRatio
float t = near * Tan(fovY / 2.0); //t = near * tan(fovY/2)
float div_r = near * Tan(fovX / 2.0); //r = near * tan(fovX/2)
float (*P)[10] = new float[10][10];
vector<float> temp = {near / div_r, 0, 0, 0, 0, near / t, 0, 0, 0, 0, (-(far + near) / (far - near)),
(-(2 * far * near) / (far - near)), 0, 0, -1, 0};
for (int j = 0; j < sz; ++j) {
for (int k = 0; k < sz; ++k) {
P[j][k] = temp.at(j * 4 + k);
}
}
print(P);
//P*matrix
int itr = 0;
for (int i = 0; i < line_num; i++) {
if (i == line_num - 1) {
cout << "breaking" << endl;
break;
};
if (tokens[i].size() == 0) { i++; }
//input three points
struct Point firstPoint, secondPoint, thirdPoint;
firstPoint.x = stof(tokens[i][itr].c_str());
firstPoint.y = stof(tokens[i][itr + 1].c_str());
firstPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
secondPoint.x = stof(tokens[i][itr].c_str());
secondPoint.y = stof(tokens[i][itr + 1].c_str());
secondPoint.z = stof(tokens[i][itr + 2].c_str());
i++;
thirdPoint.x = stof(tokens[i][itr].c_str());
thirdPoint.y = stof(tokens[i][itr + 1].c_str());
thirdPoint.z = stof(tokens[i][itr + 2].c_str());
float myMatrix[10][10];
vector<float> temp;
temp.push_back(firstPoint.x);
temp.push_back(secondPoint.x);
temp.push_back(thirdPoint.x);
temp.push_back(1);
temp.push_back(firstPoint.y);
temp.push_back(secondPoint.y);
temp.push_back(thirdPoint.y);
temp.push_back(1);
temp.push_back(firstPoint.z);
temp.push_back(secondPoint.z);
temp.push_back(thirdPoint.z);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
temp.push_back(1);
for (int j = 0; j < sz; ++j) {
for (int k = 0; k < sz; ++k) {
myMatrix[j][k] = temp.at(j * 4 + k);
}
}
/*cout << "\t\tABOUT TO MULTIPLY THE FOLLOWING\n\n";
cout << "printing Perspective matrix " << endl;
print(P);
cout << endl;
cout << "stage 2 matrix" << endl;
print(myMatrix);
cout << "\n\n";*/
float (*resultant)[10];
resultant = matrixMultiplication(P, myMatrix, sz, sz, sz, sz);
resultant = balance_W(resultant); //have to make w=1
//print(resultant);
printMatrix3(resultant); //T*I
}
}
float
(*matrixMultiplication(float firstMatrix[][10], float secondMatrix[][10], int rowFirst,
int columnFirst,
int rowSecond, int columnSecond))[10] {
//cout << "first matrix is :\n";
// print(firstMatrix);
//cout << "second matrix is :\n";
// print(secondMatrix);
float (*resultantMatrix)[10] = new float[10][10]();
int i, j, k;
// multiplying firstMatrix and secondMatrix and storing in array resultantMatrix.
for (i = 0; i < rowFirst; ++i) {
for (j = 0; j < columnSecond; ++j) {
for (k = 0; k < columnFirst; ++k) {
resultantMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
//printing
for (int l = 0; l < sz; ++l) {
for (int m = 0; m < sz; ++m) {
// cout << " [ " << l << "] [" << m << " ] " << resultantMatrix[l][m] << " ";
}
//cout << endl;
}
return resultantMatrix;
}
float (*makeIdentityMatrix(int identity_sz))[10] {
float (*identity)[10] = new float[10][10];
int row, col;
for (row = 0; row < identity_sz; row++) {
for (col = 0; col < identity_sz; col++) {
// Checking if row is equal to column
if (row == col) {
identity[row][col] = 1;
} else {
identity[row][col] = 0;
}
}
}
return identity;
}
void showstack(stack<float (*)[10]> s) {
cout << "\nprinting the full stack\n\n";
float (*temp)[10];
stack<float (*)[10]> tempStack;
tempStack = s;
while (!tempStack.empty()) {
temp = tempStack.top();
printMatrix(temp);
tempStack.pop();
}
}
void insertToStack(float (*arr)[10]) {
cout << "\n\ninserting to stack\n";
s.push(arr);
cout << "s.size() : " << s.size() << "\n\n";
}
float (*makeScalingMatrix(float scaleX, float scaleY, float scaleZ))[10] {
float (*myMatrix)[10] = new float[10][10];
for (int i = 0; i < sz; ++i) {
for (int j = 0; j < sz; ++j) {
if (i == j && i == 0) myMatrix[i][j] = scaleX;
else if (i == j && i == 1) myMatrix[i][j] = scaleY;
else if (i == j && i == 2) myMatrix[i][j] = scaleZ;
else if (i == j && i == 3) myMatrix[i][j] = 1;
else
myMatrix[i][j] = 0;
}
}
return myMatrix;
}
float (*makeTranslationMatrix(float transX, float transY, float transZ))[10] {
float (*myMatrix)[10] = new float[10][10];
for (int i = 0; i < sz; ++i) {
for (int j = 0; j < sz; ++j) {
if (i == j) {
myMatrix[i][j] = 1;
} else {
if (i == 0 && j == 3) myMatrix[i][j] = transX;
else if (i == 1 && j == 3) myMatrix[i][j] = transY;
else if (i == 2 && j == 3) myMatrix[i][j] = transZ;
else myMatrix[i][j] = 0;
}
}
}
return myMatrix;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T10:42:45.273",
"Id": "434597",
"Score": "2",
"body": "You should use classes to encapsulate all that global stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T11:31:07.150",
"Id": "434598",
"Score": "1",
"body": "`Where […] should I be commenting?` everywhere an educated guess at *what **is** this?* doesn't promise to be enough."
}
] | [
{
"body": "<p>General - it might be better to create a matrix class and your own vector class in a namespace.</p>\n\n<p><strong>Allow The Tools to Help You Improve the Code</strong><br>\nThere are compiler settings that can help you improve your code, these can be specific the the c++ compiler you are using or they can be common. A common c++ compiler switch is -Wall which indicates a errors and warnings should be reported. When I compiled this program there was an error reported as well as many warnings.</p>\n\n<p>1>modeler.cpp<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(145): warning C4244: 'initializing': conversion from 'double' to 'float', possible loss of data<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(151): warning C4244: 'initializing': conversion from 'double' to 'float', possible loss of data<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(157): warning C4244: 'initializing': conversion from 'double' to 'float', possible loss of data\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(337): warning C4018: '<': signed/unsigned mismatch<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(400): warning C4018: '<': signed/unsigned mismatch<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(628): warning C4018: '>': signed/unsigned mismatch<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(821): warning C4244: 'argument': conversion from 'double' to 'float', possible loss of data<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(822): warning C4244: 'argument': conversion from 'double' to 'float', possible loss of data<br>\n1>c:\\users\\pacmaninbw\\modeler\\modeler.cpp(178): error C4700: uninitialized local variable 'res' used<br>\n1>Done building project \"modeler.vcxproj\" -- FAILED.<br>\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========</p>\n\n<p>The error reported is in this function:</p>\n\n<pre><code>float dotProduct(const Vector &vec1, const Vector &vec2) {\n\n float res;\n\n res += vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z; // ERROR ON THIS LINE.\n if (isNearlyEqual(res, 0)) res = 0;\n\n return res;\n}\n</code></pre>\n\n<p>The variable <code>res</code> is not initialized prior to being used. The variable <code>res</code> is being used because the <code>+=</code> operator says add the following to this variable. There are 2 ways to correct this, either change the <code>+=</code> to <code>=</code> or assign zero in the declaration of <code>res</code>.</p>\n\n<pre><code> float res = 0;\n</code></pre>\n\n<p>In C++ none of the variables on the stack (local variables in functions and methods) are initialized by the compiler. A good practice is to initialize the variable in the declaration.</p>\n\n<p><em>Possible Floating Point Errors</em><br>\nAs you seem to be aware of with the <code>isNearlyEqual()</code> function due to the binary nature of computer data floating point numbers can't be completely represented on computers, there can always be some very small error. The error can be increased by switching back and forth between types, <code>int to double</code>, <code>double to int</code>, <code>float to double</code>, and <code>double to float</code>. This is why most financial institutions will use separate integers to represent dollars and cents.</p>\n\n<p>It might be better to choose one of the two types for everything, either stick with <code>double</code> or stick with <code>float</code>. I generally use just <code>double</code> because it provides greater precision. The only time that a <code>float</code> variable might be a good choice is if it is a member of a class or struct and space is an issue.</p>\n\n<p>When you do convert from one to the other use a static_cast to do the conversion, that will remove the warning messages and possibly improve accuracy.</p>\n\n<p>Here are two references on floating point numbers and related errors, the <a href=\"https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"noreferrer\">first</a> is why floating point numbers can be problems and the <a href=\"https://en.wikipedia.org/wiki/Floating_point_error_mitigation\" rel=\"noreferrer\">second</a> is on floating point error mitigation.</p>\n\n<p><em>signed/unsigned mismatch</em><br>\nIn the <code>for loops</code> where an integer value is being compared to <code>container.size()</code> there is a type mismatch, <code>container.size()</code> is declared as <code>size_t</code> which is currently defined as <code>unsigned int</code>. It might be better to define loop control variables as <code>size_t</code> when they will be compared with <code>container.size()</code>.</p>\n\n<p><strong>Avoid using \"using namespace std;\"</strong><br>\nNames spaces were invented to prevent collisions of class and function names from different libraries and modules. This code already introduces a struct/type that could conflict with the <code>std</code> names space <code>(struct Vector)</code>. It would be better to get into the habit of prefixing objects from different namespaces with the namespace so that others can maintain the code if necessary. You might also want to make your Vector struct a class and create a namespace for it. A better discussion of this can be found on <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stackoverflow.com</a>.</p>\n\n<p><strong>Using inline Function Declarations</strong><br>\nUsing <code>inline</code> in function declarations is generally obsolete. The <code>inline</code> declaration was created as an optimization in the early years of C++. Most modern C++ compilers will properly inline functions as necessary when compiling with -O3. There are times when inlining is not optimal due to cache restrictions and other reasons.</p>\n\n<p><strong>Debugging Code on Code Review</strong><br>\nIt is generally a good idea to remove debugging code before posting on Code Review, rather than just commenting it out. When you do comment out debugging code it might be better to comment out the for loops as well as the <code>cout</code> statements. This will improve the performance of the program. What might be even better is to move the debugging code that prints an entire matrix into a function where it can be called from multiple functions.</p>\n\n<pre><code>float\n(*matrixMultiplication(float firstMatrix[][10], float secondMatrix[][10], int rowFirst,\n int columnFirst,\n int rowSecond, int columnSecond))[10]{\n\n //cout << \"first matrix is :\\n\";\n // print(firstMatrix);\n\n //cout << \"second matrix is :\\n\";\n // print(secondMatrix);\n float(*resultantMatrix)[10] = new float[10][10]();\n int i, j, k;\n\n // multiplying firstMatrix and secondMatrix and storing in array resultantMatrix.\n for (i = 0; i < rowFirst; ++i) {\n for (j = 0; j < columnSecond; ++j) {\n for (k = 0; k < columnFirst; ++k) {\n resultantMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];\n }\n }\n }\n\n //printing\n for (int l = 0; l < sz; ++l) {\n for (int m = 0; m < sz; ++m) {\n // cout << \" [ \" << l << \"] [\" << m << \" ] \" << resultantMatrix[l][m] << \" \";\n }\n //cout << endl;\n }\n return resultantMatrix;\n}\n</code></pre>\n\n<p>For performance reasons it would be better to use <code>\"\\n\"</code> over <code>std::endl</code> especially in loops as shown above. <code>\"\\n\"</code> just inserts a new line, <code>std::endl</code> flushes the output after the new line which means it is making a system call and that really does slow things down.</p>\n\n<p><strong>Indentation</strong><br>\nThe code above is representative of all the code, a standard practice is to indent the inner loop of all nested loops. Indentation can be an indication of code complexity and can help a code author figure out where they need additional functions. Indentation also helps reviewers and maintainers of the code to read the code.</p>\n\n<p><strong>Code Complexity and Readability</strong><br>\nThe following code is a little too complex and readability could be improved:</p>\n\n<pre><code>float (*makeTranslationMatrix(float transX, float transY, float transZ))[10] {\n\n float (*myMatrix)[10] = new float[10][10];\n\n for (int i = 0; i < sz; ++i) {\n for (int j = 0; j < sz; ++j) {\n\n if (i == j) {\n myMatrix[i][j] = 1;\n\n } else {\n if (i == 0 && j == 3) myMatrix[i][j] = transX;\n else if (i == 1 && j == 3) myMatrix[i][j] = transY;\n else if (i == 2 && j == 3) myMatrix[i][j] = transZ;\n else myMatrix[i][j] = 0;\n }\n\n }\n }\n return myMatrix;\n}\n</code></pre>\n\n<p>In the <code>else</code> clause of the major if statement all of the subsidarary if statements could be made simpler by creating and outer if statement:</p>\n\n<pre><code> if (j == 3)\n {\n if (i == 0)\n {\n myMatrix[i][j] = transX;\n }\n else if (i == 1)\n {\n myMatrix[i][j] = transY;\n }\n else if (i == 2) \n {\n myMatrix[i][j] = transZ;\n }\n else\n {\n myMatrix[i][j] = 0;\n }\n }\n else\n {\n myMatrix[i][j] = 0;\n }\n</code></pre>\n\n<p>This might also improve performance by removing one comparison if the compiler hasn't already optimized it out.</p>\n\n<p>Note: For maintainability it might be better to always put braces <code>{}</code> after <code>if (condition)</code> and <code>else</code> so that maintainers can expand code as necessary without introducing new bugs.</p>\n\n<p>The numbers 0, 1, 2 and 3 aren't clear, it may be better to create symbolic constants with names that indicate what the actual condition is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:42:13.147",
"Id": "434642",
"Score": "0",
"body": "0,1,2,3 indicates the row positions. should i have used `define row0 0; define row1 1;` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:11:57.140",
"Id": "434645",
"Score": "0",
"body": "@afsara__ No, but some comments about why those particular positions are important might be good."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T14:54:58.030",
"Id": "224096",
"ParentId": "224085",
"Score": "5"
}
},
{
"body": "<p>I see some things that I think could help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. </p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error. Eliminating global variables where practical is always a good idea, and can be done here by moving them as local variables to the only place they're used, as with <code>infile</code> and/or pass them as parameters.</p>\n\n<h2>Use <code>constexpr</code> for values that could be computed at compile time</h2>\n\n<p>The values of <code>PI</code> and <code>EPS</code> could be declared <code>constexpr</code> or probably better would be <code>static constexpr</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#con5-use-constexpr-for-values-that-can-be-computed-at-compile-time\" rel=\"nofollow noreferrer\">Con.5</a>.</p>\n\n<h2>Be careful with signed and unsigned</h2>\n\n<p>In several places, the code compares an <code>int</code> <code>i</code> with <code>tokens[j].size()</code> or similar. However, <code>tokens[j].size()</code> is unsigned and <code>i</code> is signed. For consistency, it would be better to declare <code>i</code> as <code>std::size_t</code> which is the type returned by <code>size()</code>. </p>\n\n<h2>Eliminate unused parameters</h2>\n\n<p>The <code>rowSecond</code> parameter to <code>matrixMultiplication</code> is unused and should be deleted.</p>\n\n<h2>Don't define a default constructor that only initializes data members</h2>\n\n<p>The <code>Vector</code> constructor is currently this:</p>\n\n<pre><code>Vector() {\nx = x;\ny = y;\nz = z;\n};\n</code></pre>\n\n<p>Not only does this not make sense, better would be to use in-class member initializers and delete this constructor in favor of <code>Vector() = default;</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">C.45</a></p>\n\n<h2>Consider the user</h2>\n\n<p>Instead of having hardcoded filenames, it might be nice to allow the user to control the name and location of the input and output files. For this, it would make sense to use a command line argument and then pass the filename to the functions as needed.</p>\n\n<h2>Use better names</h2>\n\n<p>I would expect a function named <code>readFromFile</code> to read... something... from a file. No more and no less. However, what this function actually does is to read the file <em>and</em> perform some operation on that data <em>and</em> write that resulting data to yet another file. I'd suggest breaking each of those into its own function and then naming each piece more appropriately.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The <code>dotProduct()</code> function includes these lines:</p>\n\n<pre><code>float dotProduct(const Vector &vec1, const Vector &vec2) {\n float res;\n res += vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z;\n</code></pre>\n\n<p>The problem is that by using <code>+=</code> the code is using an uninitialized variable. Better would be to use <code>=</code>.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>This code has a number of inscrutable \"magic numbers,\" that is, unnamed constants such as 10, 100, 200, etc. Generally it's better to avoid that and give such constants meaningful names. That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of \"10\" and then trying to determine if this <em>particular</em> 10 is relevant to the desired change or if it is some other constant that happens to have the same value.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The various <code>printMatrix</code> routines are exactly alike except for the file they write to. That is a strong indicator they should instead be a single function with the <code>ostream</code> passed as a parameter. When you consolidate them, you will see that there's a subtle difference in the way one of them prints to the console.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>At the moment, the several calls to <code>new</code> have no corresponding calls to <code>delete</code> which is a memory leak. That should be fixed. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c31-all-resources-acquired-by-a-class-must-be-released-by-the-classs-destructor\" rel=\"nofollow noreferrer\">C.31</a></p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Define operations using operators</h2>\n\n<p>The code includes functions like this:</p>\n\n<pre><code>Vector add(Vector v1, Vector v2) {\n Vector ret(0, 0, 0);\n ret.x = v1.x + v2.x;\n ret.y = v1.y + v2.y;\n ret.z = v1.z + v2.z;\n return ret;\n}\n</code></pre>\n\n<p>This makes more sense to me expressed as an operator member function of <code>Vector</code>. First define <code>operator+=</code>:</p>\n\n<pre><code>Vector &operator+=(const Vector& other) {\n x += other.x;\n y += other.y;\n z += other.z;\n return *this;\n}\n</code></pre>\n\n<p>Then define a free standing functions using that function:</p>\n\n<pre><code>Vector operator+(Vector a, const Vector& b) {\n return a += b;\n}\n</code></pre>\n\n<p>Now instead of this:</p>\n\n<pre><code>Vector temp4 = add(temp1, temp3);\n</code></pre>\n\n<p>We can write this:</p>\n\n<pre><code>auto temp4 = temp1 + temp3;\n</code></pre>\n\n<p>And instead of </p>\n\n<pre><code>l = subtract(look, eye); //l = look - eye\n</code></pre>\n\n<p>We can simply write:</p>\n\n<pre><code>l = look - eye;\n</code></pre>\n\n<p>and render the comment completely redundant because the <em>code itself</em> is clear. This also allows considerable simplification elsewhere. For example the <code>rotateRod</code> function becomes this rather than the current 33 line function:</p>\n\n<pre><code>Vector rotateRod(Vector x, Vector rotateAxis, float rotateAngle) {\n auto ra{rotateAxis};\n rotateAxis *= rotateAxis.dotProduct(x) * (1 - Cos(rotateAngle)); \n return x*Cos(rotateAngle) + ra.cross(x)*Sin(rotateAngle) + rotateAxis;\n}\n</code></pre>\n\n<h2>Make better use of objects</h2>\n\n<p>Everywhere that something like <code>(float (*matrix)[10])</code> occurs is probably much better expressed as an object. I'd also suggest minimally using a <code>std::matrix<float, 10></code> rather than a raw array because the latter type is quite stupid and doesn't even know its own size.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:08:41.220",
"Id": "224118",
"ParentId": "224085",
"Score": "3"
}
},
{
"body": "<p>Lots of good comments already given.</p>\n\n<p>I'll just point out that you should most likely not be writing your own math primitives. It's easy to get wrong, it takes time away from actually creating what you're trying to create, you'll tear your hair out fixing hard to spot bugs and your code (contrary to what most people who write their own math primitives seem to think) will not be faster. Turns out, the people who write math libraries are experienced and have had much longer time than you to debug, design, test and optimize the libraries than you have.</p>\n\n<p>That said, there are two good reasons to write math primitives: you're doing it to learn the maths or libraries or functions you need are not available for your platform, licensing requirements, algorithms you need are missing etc.</p>\n\n<p>There are many good libraries out there, personally I like to use <a href=\"http://eigen.tuxfamily.org/index.php?title=Main_Page\" rel=\"noreferrer\">Eigen</a>. I have no affiliation with the project; I just like their API, they have good performance and don't need to deal with distributing libraries or linking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:27:27.900",
"Id": "224120",
"ParentId": "224085",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "224096",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T10:27:05.640",
"Id": "224085",
"Score": "2",
"Tags": [
"c++",
"performance",
"matrix",
"complexity",
"vectors"
],
"Title": "Modeling, view and projection transformation using vector and point in homogenous form"
} | 224085 |
<p>I am creating a database to store house points for our school running events. I would like to be able to tally all the points for the houses and it is working fine, however, I think it may be a bit verbose at this point.</p>
<p>Is there a simpler/better way with maybe more efficient code?</p>
<p>Races are stored in a <code>races</code> table (competitorID, raceID, time).</p>
<p>Student data is stored in a <code>competitor</code> table (competitorID, names, house).</p>
<p>The code will query the DB and bring back unique races, and then assign a point value based on their position (calculated by their race time).</p>
<pre><code>import sqlite3
conn = sqlite3.connect('house.db')
conn.row_factory = sqlite3.Row
# House Totals
blueTotal = 0
greenTotal = 0
redTotal = 0
yellowTotal = 0
# Assign points from 1st = 15 through to 10-Last being 1
def points():
global pointvalue
if count == 0:
pointvalue = 15
places()
if count == 1:
pointvalue = 12
places()
if count == 2:
pointvalue = 10
places()
if count == 3:
pointvalue = 8
places()
if count == 4:
pointvalue = 7
places()
if count == 5:
pointvalue = 6
places()
if count == 6:
pointvalue = 5
places()
if count == 7:
pointvalue = 4
places()
if count == 8:
pointvalue = 3
places()
if count == 9:
pointvalue = 2
places()
if count > 10:
pointvalue = 1
places()
#Add points to houses
def places():
global blueTotal, greenTotal, redTotal, yellowTotal, pointvalue
if competitors['house'] == "blueTotal":
blueTotal += pointvalue
if competitors['house'] == "redTotal":
redTotal += pointvalue
if competitors['house'] == "yellowTotal":
yellowTotal += pointvalue
if competitors['house'] == "greenTotal":
greenTotal += pointvalue
for x in range(1,50):
competitorDetails = conn.execute('SELECT firstname, surname, house '
'FROM race, competitor '
'WHERE competitor.competitorID = race.competitorID '
'AND race.raceID = ' + str(x))
count=0
for competitors in competitorDetails:
points()
count += 1
print("blueTotal " + str(blueTotal))
print("greenTotal " + str(greenTotal))
print("redTotal " + str(redTotal))
print("yellowTotal " + str(yellowTotal))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T14:14:17.453",
"Id": "434610",
"Score": "0",
"body": "I don't see any mention of the `time` being used, as you described in your preliminary text. You should update your SQL to include this. Also, much of this work can be done in SQL rather than Python. Can you explain why you're using Python for this instead?"
}
] | [
{
"body": "<h1>DRY</h1>\n<p>This <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">repetitive</a> code is an anti-pattern:</p>\n<pre><code>blueTotal = 0\ngreenTotal = 0\nredTotal = 0\nyellowTotal = 0\n</code></pre>\n<p>Please define</p>\n<pre><code>houses = 'blue green red yellow'.split()\n</code></pre>\n<p>and then you can use array access to perform "the same action" across all houses:</p>\n<pre><code>for house in houses:\n total[house] = 0\n</code></pre>\n<p>One could also assign <code>total = collections.defaultdict(int)</code>, but that would\nbe a horse of a different color.\n(<a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\">https://docs.python.org/3/library/collections.html#collections.defaultdict</a>)</p>\n<h1>global</h1>\n<p>The <code>global</code> keyword is usually not your friend,\nit leads to unfortunate coupling.\nHere, it is offering you a hint that you want to define a <code>class</code>,\nset totals to zero in the <code>__init__()</code> constructor,\nand then have <code>places()</code> access <code>self.total[]</code>.</p>\n<h1>arg passing</h1>\n<p>This is a bit crazy:</p>\n<pre><code> for competitors in competitorDetails:\n points()\n</code></pre>\n<p>Yes, you <em>can</em> treat <code>competitors</code> as an implicit argument\nby making it global, but there is absolutely no reason to,\nand the current code makes it extremely difficult for readers\nto understand what is going on. Please, please make <code>competitors</code>\nan explicit argument, passing it in with <code>points(competitors)</code>.</p>\n<h1>formatting</h1>\n<p>Clearly this works:</p>\n<pre><code>print("blueTotal " + str(blueTotal))\n</code></pre>\n<p>but the explicit call to <code>str</code> is slightly verbose.\nConsider re-phrasing such print statements in one of these ways:</p>\n<pre><code>print("blueTotal", blueTotal)\nprint(f'blueTotal {blueTotal}')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T14:07:43.097",
"Id": "434608",
"Score": "0",
"body": "Don't you mean \"a *house* of a different color\"? ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T14:24:24.970",
"Id": "434612",
"Score": "0",
"body": "It's an idiom that, among other places, shows up in Oz. It means \"quite a different thing\", and implicit init to zero for _all_ potential houses seemed quite different from OP's repetitive code. https://idioms.thefreedictionary.com/a+horse+of+a+different+color , https://oz.fandom.com/wiki/Horse_of_a_Different_Color"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:27:58.193",
"Id": "434748",
"Score": "1",
"body": "@J_H ... Woosh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:21:27.557",
"Id": "434756",
"Score": "0",
"body": "Why did you choose to say `houses = 'blue green red yellow'.split()` instead of `houses = ['blue', 'green', 'red', 'yellow']`? The second one seems more explicit to me..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:28:36.703",
"Id": "434758",
"Score": "0",
"body": "It's a concise and common idiom. For N items, I can choose to put N blanks between them, or 4*N punctuation characters, which can mean the difference between a one-line or multi-line expression. As N gets bigger, so does the relative advantage."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T13:56:22.327",
"Id": "224092",
"ParentId": "224089",
"Score": "7"
}
},
{
"body": "<p>Here are some hints on how to decrease the size of your code and make it more Pythonic.</p>\n\n<h3>Stack Ifs</h3>\n\n<p>Anytime you see stacked ifs, that are all basically the same, you should consider using a <a href=\"https://docs.python.org/3/library/stdtypes.html#mapping-types-dict\" rel=\"noreferrer\"><code>dict</code></a>. In the case here, the primary thing the ifs were doing was mapping a race place to points. So let's do that explicitly like:</p>\n\n<pre><code>pointvalues = { \n 0: 15,\n 1: 12,\n 2: 10,\n 3: 8,\n 4: 7,\n 5: 6,\n 6: 5,\n 7: 4,\n 8: 3,\n 9: 2,\n 10: 1,\n}\n</code></pre>\n\n<h3>Use a <a href=\"https://docs.python.org/3/library/stdtypes.html#mapping-types-dict\" rel=\"noreferrer\"><code>dict</code></a> for tracking like things</h3>\n\n<p>Instead of the specially named globals variables for tracking points, you can use a dict, and use your <em>house</em> names as keys to the <a href=\"https://docs.python.org/3/library/stdtypes.html#mapping-types-dict\" rel=\"noreferrer\"><code>dict</code></a> like:</p>\n\n<pre><code># House Totals\ntotals = dict(\n blueTotal=0,\n greenTotal=0,\n redTotal=0,\n yellowTotal=0,\n)\n</code></pre>\n\n<p>Or you might use <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.setdefault\" rel=\"noreferrer\"><code>setdefault</code></a> to save having to init the houses names at all.</p>\n\n<h3>Use <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a>:</h3>\n\n<p>Instead of explicitly counting loop iterations, you should use the builtin <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a> like:</p>\n\n<pre><code>for place, competitors in enumerate(competitorDetails):\n # Add points to houses\n totals[competitors['house']] += pointvalues.get(place, 0)\n</code></pre>\n\n<p>Also the above shows how to use the two <a href=\"https://docs.python.org/3/library/stdtypes.html#mapping-types-dict\" rel=\"noreferrer\"><code>dict</code></a>'s we built earlier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:49:00.620",
"Id": "434660",
"Score": "2",
"body": "A `dict` with consecutive integer keys starting at `0` is isomorphic to a `list`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:20:07.680",
"Id": "224098",
"ParentId": "224089",
"Score": "5"
}
},
{
"body": "<p>A few things no one has touched on yet...</p>\n\n<p><strong>points()</strong></p>\n\n<p>Your points values follow a pattern which can be easily modeled mathematically:</p>\n\n<pre><code># Assign points from 1st = 15 through to 10-Last being 1\ndef points():\n global pointvalue\n if count == 0:\n point_value = 15\n places()\n elif count < 3:\n point_value = 14 - 2 * count\n places()\n elif count < 11:\n point_value = 11 - count\n places()\n elif count > 10:\n point_value = 1\n places()\n</code></pre>\n\n<p>On my machine, this improvement made this section of the program about 2x faster.</p>\n\n<p><strong>if-elif</strong></p>\n\n<p>Since <code>competitors['house']</code> can only have one value, there is no sense in checking if it is all values with repetitive <code>if</code> statements. Instead, use an <code>if-elif</code> structure or perhaps <code>if-elif-elif-else</code>.</p>\n\n<pre><code># add points to houses\ndef places():\n global blue_total, green_total, red_total, yellow_total, point_value\n if competitors['house'] == \"blue_total\":\n blue_total += point_value\n elif competitors['house'] == \"red_total\":\n red_total += point_value\n elif competitors['house'] == \"yellow_total\":\n yellow_total += point_value\n elif competitors['house'] == \"green_total\":\n green_total += point_value\n</code></pre>\n\n<p><strong>Style:</strong></p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">Python's own style guide</a> dictates a convention for function and variable names: names should be lowercase, with words separated by underscores as necessary to improve readability.</p>\n\n<p>Therefore: <code>blueTotal</code> -> <code>blue_total</code> and <code>pointvalue</code> -> <code>point_value</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:47:30.093",
"Id": "224099",
"ParentId": "224089",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T13:33:57.953",
"Id": "224089",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"sqlite"
],
"Title": "School House Points (Python + SQLite)"
} | 224089 |
<p>Please refer to this <a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting&h_r=next-challenge&h_v=zen" rel="nofollow noreferrer">problem from Hackerrank</a></p>
<blockquote>
<p>HackerLand National Bank has a simple policy for warning clients about
possible fraudulent account activity. If the amount spent by a client
on a particular day is greater than or equal to the client's median
spending for a trailing number of days, they send the client a
notification about potential fraud. The bank doesn't send the client
any notifications until they have at least that trailing number of
prior days' transaction data.</p>
</blockquote>
<p>I have written the following code. However, the code is working for some of the test cases and is getting 'terminated due to timeout' for some. Can anyone please tell how can I improve the code?</p>
<pre><code>import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the activityNotifications function below.
static int activityNotifications(int[] expenditure, int d) {
//Delaring Variables
int iterations,itr,length,median,midDummy,midL,midR, midDummy2,i,i1,temp,count;
float mid,p,q;
length = expenditure.length;
iterations = length-d;
i=0;
i1=0;
itr=0;
count = 0;
int[] exSub = new int[d];
while(iterations>0)
{
// Enter the elements in the subarray
while(i1<d)
{
exSub[i1]=expenditure[i+i1];
//System.out.println(exSub[i1]);
i1++;
}
//Sort the exSub array
for(int k=0; k<(d-1); k++)
{
for(int j=k+1; j<d; j++)
{
if(exSub[j]<exSub[k])
{
temp = exSub[j];
exSub[j] = exSub[k];
exSub[k] = temp;
}
}
}
//Printing the exSub array in each iteration
for(int l = 0 ; l<d ; l++)
{
System.out.println(exSub[l]);
}
i1=0;
//For each iteration claculate the median
if(d%2 == 0) // even
{
midDummy = d/2;
p= (float)exSub[midDummy];
q= (float)exSub[midDummy-1];
mid = (p+q)/2;
//mid = (exSub[midDummy]+exSub [midDummy-1])/2;
//System.out.println(midDummy);
}
else // odd
{
midDummy2 =d/2;
mid=exSub[midDummy2];
//System.out.println(midDummy2);
}
if(expenditure[itr+d]>=2*mid)
{
count++;
}
itr++;
i++;
iterations--;
System.out.println("Mid:"+mid);
System.out.println("---------");
}
System.out.println("Count:"+count);
return count;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
int[] expenditure = new int[n];
String[] expenditureItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int expenditureItem = Integer.parseInt(expenditureItems[i]);
expenditure[i] = expenditureItem;
}
int result = activityNotifications(expenditure, d);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T18:19:15.720",
"Id": "434639",
"Score": "0",
"body": "Is it just a timeout or are there errors in the output as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:18:40.427",
"Id": "434745",
"Score": "0",
"body": "@pacmaninbw I think the code works fine for a small no. of data. For a large no. of data it shows timeout."
}
] | [
{
"body": "<h1>close</h1>\n\n<p>You had an opportunity to acquire (and then close) this resource\nusing <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resource</a></p>\n\n<pre><code>private static final Scanner scanner = new Scanner(System.in);\n</code></pre>\n\n<p>Similarly for this one:</p>\n\n<pre><code>new BufferedWriter(new FileWriter(System.getenv(\"OUTPUT_PATH\")));\n</code></pre>\n\n<h1>streaming input</h1>\n\n<p>You're reading 200,000 numbers here:</p>\n\n<pre><code> String[] expenditureItems = scanner.nextLine().split(\" \");\n</code></pre>\n\n<p>They won't fit in the lower levels of the cache hierarchy, they are spilling to RAM.\nConsider reading as you compute.\nYou never need much more than <code>d</code> numbers to be resident at once.</p>\n\n<h1>no-op</h1>\n\n<p>This doesn't appear to do anything for you. Consider deleting it.</p>\n\n<pre><code> scanner.skip(\"(\\r\\n|[\\n\\r\\u2028\\u2029\\u0085])?\");\n</code></pre>\n\n<h1>temp var</h1>\n\n<p>The compiler optimizes it away,\nbut needlessly introducing a temp variable makes your code harder to read:</p>\n\n<pre><code> int expenditureItem = Integer.parseInt(expenditureItems[i]);\n expenditure[i] = expenditureItem;\n</code></pre>\n\n<p>Just phrase it as:</p>\n\n<pre><code> expenditure[i] = Integer.parseInt(expenditureItems[i]);\n</code></pre>\n\n<p>Not sure why you wanted to allocate 200,000 strings and then 200,000 ints,\nwhen you could have streamed through them one string at a time.</p>\n\n<h1>Integer.toString</h1>\n\n<p>In addition to needless temp var,\nit seems you chose to define an inconvenient API:</p>\n\n<pre><code> int result = activityNotifications(expenditure, d);\n bufferedWriter.write(String.valueOf(result));\n</code></pre>\n\n<p>You might find it slightly more convenient to write the result\nif activityNotifications returned <code>Integer</code>.</p>\n\n<h1>API</h1>\n\n<p>You might have found it convenient to pass in two separate arrays,\none containing <code>d</code> entries and the other containing the <code>n - d</code>\nentries that you have to make decisions on.</p>\n\n<p>Ok, it appears you spend almost no time in <code>main</code>,\nrelative to what <code>activityNotifications</code> consumes.</p>\n\n<h1>sort</h1>\n\n<p>The pair of nested loops headed by</p>\n\n<pre><code> //Sort the exSub array\n</code></pre>\n\n<p>is quite insane.\nYou <em>know</em> <code>d</code> shall be \"large\".</p>\n\n<p>You have an opportunity to use <code>Arrays.sort()</code> with cost O(d log d),\nyet you went for the quadratic solution, O(d**2).</p>\n\n<h1>printing</h1>\n\n<p>I don't understand the comment \"Printing the exSub array in each iteration\".\nWhy would you want to spend time doing that?\nOnly the return value <code>count</code> is relevant for evaluating your submission.\nSimilarly for your debug print of <code>mid</code>.</p>\n\n<h1>algorithm - heap</h1>\n\n<p>You (re-)sort <code>d</code> elements <strong>every</strong> <strong>single</strong> <strong>time</strong>.\nEven though only a single value entered the <code>d</code>-day window,\nand a single value left.\nMaintain a <a href=\"https://en.wikipedia.org/wiki/Heap_(data_structure)\" rel=\"nofollow noreferrer\">heap</a>, at cost of O(log d) for each operation.</p>\n\n<h1>algorithm - counting values</h1>\n\n<p>Go back and read the problem.</p>\n\n<p>Are expenditures floats of arbitrary precision? No, they are integers.</p>\n\n<p>Can expenditures have arbitrary magnitudes as large as the U.S. debt?\nNo, only two hundred and one distinct values are allowed.</p>\n\n<p>Recall that a median value separates the low half from the high half of the values.\nMaintain 201 counts,\nand a circular FIFO list of daily expenditures\n(or continue using the giant <code>n</code>-entry input array,\nindexing it <code>d</code> behind today).\nIncrement a count corresponding to today's expenditure,\nand decrement a count for the day exiting the <code>d</code>-day window.\nIdentify the point at which the sum of the low counts\nmatches the sum of the high counts, that's your median.\nYou can do it in time proportional to 201 (<em>much</em> less than <code>d</code>),\nor you can choose to do it faster than that\nby maintaining cumulative sums\nand remembering what yesterday's median was.\nGood luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:09:06.127",
"Id": "434617",
"Score": "0",
"body": "The `main()` function is *given* by the HackerRank submission template."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:10:28.073",
"Id": "434618",
"Score": "0",
"body": "Wow! Not sure they're aiding the learning process, there. (Sorry, guess I mis-parsed \"I have written the following code.\")"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T15:01:09.067",
"Id": "224097",
"ParentId": "224090",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T13:34:47.007",
"Id": "224090",
"Score": "2",
"Tags": [
"java",
"time-limit-exceeded"
],
"Title": "Finding the number of times the code will generate an alert depending upon whether the transaction is fraudulent"
} | 224090 |
<p>Challenge from <a href="https://www.hackerrank.com/challenges/electronics-shop/problem" rel="nofollow noreferrer">Hacker Rank</a> -</p>
<blockquote>
<p>Monica wants to buy a keyboard and a USB drive from her favorite electronics store. The store has several models of each. Monica wants to spend as much as possible for the items, given her budget.</p>
<p>Given the price lists for the store's keyboards and USB drives, and Monica's budget, find and print the amount of money Monica will spend. If she doesn't have enough money to both a keyboard and a USB drive, print -1 instead. She will buy only the two required items.</p>
</blockquote>
<p>For example - with a budget of <strong>10</strong>, two keyboards costing <strong>3</strong>,<strong>1</strong> & finally three drives available costing <strong>5</strong>,<strong>2</strong>,<strong>8</strong>, the answer should be <strong>9</strong> as she is only able to purchase the keyboard for <strong>3</strong> and a drive for <strong>5</strong>.</p>
<p>I've attempted to solve this logically and with good performance in mind. I'm not sure if I should be happy with my solution. I would appreciate any feedback.</p>
<p>My solution (which works) or <a href="https://github.com/Webbarrr/HackerRank/tree/d1f2f244c975062acfddb14082de2c31c9f5a5ef/ElectronicsShop" rel="nofollow noreferrer">my GitHub repo</a> -</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace ElectronicsShop
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetMoneySpent(new int[] { 3, 1 }, new int[] { 5, 2, 8 }, 10));
Console.WriteLine(GetMoneySpent(new int[] { 5}, new int[] { 4 }, 5));
Console.ReadLine();
}
static int GetMoneySpent(int[] keyboards, int[] drives, int budget)
{
if (budget == 0)
return -1;
// sort the two arrays so the highest values are at the front
keyboards = SortArrayDescending(keyboards);
drives = SortArrayDescending(drives);
// delete any that are over our budget
var affordableKeyboards = GetAffordableItems(keyboards, budget);
var affordableDrives = GetAffordableItems(drives, budget);
// make a list to contain the combined totals
var combinedTotals = new List<int>();
foreach (var keyboard in keyboards)
{
foreach (var drive in drives)
{
combinedTotals.Add(keyboard + drive);
}
}
// sort the list & delete anything over budget
combinedTotals.Sort();
combinedTotals.Reverse();
combinedTotals.RemoveAll(n => n > budget);
return combinedTotals.Count == 0 ? -1 : combinedTotals[0];
}
static int[] SortArrayDescending(int[] array)
{
Array.Sort(array);
Array.Reverse(array);
return array;
}
static int[] GetAffordableItems(int[] array, int budget)
{
return array.Where(n => n < budget).ToArray();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T09:33:37.600",
"Id": "434694",
"Score": "6",
"body": "Regarding the sample in the problem description, if Monica buys items costing \\$3\\$ and \\$5 ,\\$ wouldn't that just be \\$8 ?\\$ I think you meant that she buys the keyboard for \\$1\\$ and the USB-drive for \\$8 ,\\$ yielding the total of \\$9 .\\$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:12:10.183",
"Id": "434698",
"Score": "0",
"body": "@Nat good spot! Yes you're right - I've fixed that now. Turns out I can't do basic Maths :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:11:19.963",
"Id": "434769",
"Score": "1",
"body": "Before going for good *code* you should go for a good *algorithm*. It seems your algorithm has $O(nk)$ runtime and memory. The problem can however be solved in $O(n\\log n+k\\log k)$ time with $O(n+k)$ memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:37:11.727",
"Id": "434781",
"Score": "0",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
}
] | [
{
"body": "<h3>General Guidelines</h3>\n\n<ul>\n<li>You have coded everything in a single class <code>Program</code>. Take advantage of the fact C# is an object oriented language. Create at least one custom class that defines this problem.</li>\n<li>Your current implementation is very strict and specific to 2 types of items. What if Monica needs to buy from <code>n</code> item types? It is up to you to decide the scope of your implementation, so what you have done is not wrong, but it is something to consider when building reusable code blocks. We can argue reusability of this exercise though.</li>\n<li>When providing a method for consumers to use, make sure to include a handful of unit tests. This is an excellent way to get to know the outcome given any input. In this case, you are providing us <code>GetMoneySpent</code>, but we have to write our own unit tests to verify correctness of this method.</li>\n</ul>\n\n<h3>Review</h3>\n\n<ul>\n<li>You are using <code>Array</code> for a problem where <code>IEnumerable</code> could have also been used. Prefer the latter because you don't want to depend on fixed sized collections. You are converting <code>ToArray()</code>, this overhead should not be required when working with <code>IEnumerable</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:21:53.117",
"Id": "434655",
"Score": "1",
"body": "In terms of your first point, you're 100% correct. I tend to fall into a bad habbit of writing procedural code when I'm doing these types of challenges. I really shouldn't, kind of defeats the purpose.\n\nI get what you mean for point 2, I guess I kinda limited it because it was for a one time use in this specific challenge. It's a good idea to look at reusability for exercises though.\n\nSorry about the lack of unit tests - I need to spend some more time improving my understanding of how they work, especially if I'm going to be posting stuff on code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:23:52.663",
"Id": "434656",
"Score": "1",
"body": "Well, it is tempting and easy to do it that way :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:50:52.587",
"Id": "224103",
"ParentId": "224100",
"Score": "7"
}
},
{
"body": "<h1>early pruning</h1>\n<p>This is very nice:</p>\n<pre><code> // delete any that are over our budget\n</code></pre>\n<p>Doing it <em>before</em> sorting can slightly speed the sorting operation.\nI say slightly because "items over budget" is determined by the input,\nand it will be some fraction <code>f</code> of an input item category,\nso the savings is O(f * n * log n).</p>\n<h1>early discard</h1>\n<p>This is a bigger deal.</p>\n<pre><code> // sort the list & delete anything over budget\n</code></pre>\n<p>For <code>k</code> keyboards and <code>d</code> drives, the sort does O(k * d * log k * d) work.\nDiscarding within this loop would be an even bigger win.</p>\n<h1>consistent idiom</h1>\n<p>It was a little odd that you used</p>\n<pre><code> combinedTotals.RemoveAll(n => n > budget);\n</code></pre>\n<p>and</p>\n<pre><code> array.Where(n => n < budget).ToArray();\n</code></pre>\n<p>to accomplish the same thing.\nThere's no speed difference but consider phrasing the same thing in the same way.</p>\n<h1>reversing</h1>\n<p>If you pass into <code>Sort</code> something that implements the <code>IComparer</code> interface,\nyou can change the comparison order and thus skip the <code>Reverse</code> step entirely.</p>\n<h1>arithmetic</h1>\n<p>Arbitrarily choose one of the categories as the driving category, perhaps keyboard.\nSort the drive prices, while leaving the keyboards in arbitrary order.\nNote the min drive price, and use that along with budget for immediately pruning infeasible keyboards.</p>\n<p>Loop over all surviving keyboards.\nTarget price is <code>budget - kb_price</code>.\nDo binary search over drives for the target,\nfinding largest feasible drive,\nand use that to update "best combo so far".\nNo need to sort them, you need only retain the "best" one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:10:21.383",
"Id": "434742",
"Score": "1",
"body": "The LINQ Where should be `array.Where(n => n <= budget)`. But your key point is made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T19:27:44.753",
"Id": "434917",
"Score": "1",
"body": "This answer has given me a lot to reflect upon. I mentioned further down to someone who quoted you, some of the things in terms of binary search & IComparer (the latter I've used very briefly) are things I've been researching today. I'm honestly looking forward to implementing what I've learned into future projects. Thank you"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:51:40.793",
"Id": "224105",
"ParentId": "224100",
"Score": "10"
}
},
{
"body": "<p>The good thing first:</p>\n\n<p>You divide and conquer the problem by creating some reasonable (and well named) methods. You could have gone all in by making methods for combining and final selection as well:</p>\n\n<pre><code> ...\n var combinedTotals = Combine(affordableKeyboards, affordableDrives);\n return SelectMaxBuy(combinedTotals, budget);\n}\n</code></pre>\n\n<p>But as shown below, dividing the code into such small methods can sometimes obscure more useful approaches. </p>\n\n<hr>\n\n<p>It must be a mind slip that you find the affordable keyboards and drives, but you forget about them and iterate over the full arrays of keyboards and drives:</p>\n\n<blockquote>\n<pre><code> // delete any that are over our budget\n var affordableKeyboards = GetAffordableItems(keyboards, budget);\n var affordableDrives = GetAffordableItems(drives, budget);\n\n // make a list to contain the combined totals\n var combinedTotals = new List<int>();\n\n foreach (var keyboard in keyboards)\n {\n foreach (var drive in drives)\n {\n combinedTotals.Add(keyboard + drive);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>I suppose that the loops should be:</p>\n\n<pre><code> foreach (var keyboard in affordableKeyboards)\n {\n foreach (var drive in affordableDrives)\n {\n combinedTotals.Add(keyboard + drive);\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Some optimizations:</p>\n\n<pre><code> return array.Where(n => n < budget).ToArray();\n</code></pre>\n\n<p><code>Where</code> has to iterate through the entire array, even if it is sorted.\nA better approach would have been to sort ascending first, then take untill <code>n > budget</code>, and then reverse:</p>\n\n<pre><code>array.OrderBy(n => n).TakeWhile(n => n <= budget).Reverse();\n</code></pre>\n\n<p>Making the almost same considerations with the combined totals:</p>\n\n<pre><code> int result = combinedTotals.OrderByDescending(n => n).FirstOrDefault(n => n <= budget);\n</code></pre>\n\n<p>Your entire method could be refined to this:</p>\n\n<pre><code>static int GetMoneySpent(int[] keyboards, int[] drives, int budget)\n{\n if (keyboards == null || keyboards.Length == 0 || drives == null || drives.Length == 0 || budget <= 0)\n return -1;\n\n keyboards = keyboards.OrderBy(n => n).TakeWhile(n => n <= budget).Reverse().ToArray();\n drives = drives.OrderBy(n => n).TakeWhile(n => n <= budget).Reverse().ToArray();\n\n // make a list to contain the combined totals\n var combinedTotals = new List<int>();\n\n foreach (var keyboard in keyboards)\n {\n foreach (var drive in drives)\n {\n combinedTotals.Add(keyboard + drive);\n }\n }\n\n int result = combinedTotals.OrderByDescending(n => n).FirstOrDefault(n => n <= budget);\n return result == 0 ? -1 : result;\n}\n</code></pre>\n\n<hr>\n\n<p>Just for the sport I made the below solution, that sorts the data sets in ascending order and iterate backwards to avoid reversing the data:</p>\n\n<pre><code>int GetMoneySpent(int[] keyboards, int[] drives, int budget)\n{\n if (keyboards == null || keyboards.Length == 0 || drives == null || drives.Length == 0 || budget <= 0)\n return -1;\n\n int result = -1; \n\n Array.Sort(keyboards);\n Array.Sort(drives);\n\n int istart = keyboards.Length - 1;\n while (istart >= 0 && keyboards[istart] > budget) istart--;\n int jstart = drives.Length - 1;\n while (jstart >= 0 && drives[jstart] > budget) jstart--;\n\n for (int i = istart; i >= 0; i--)\n {\n int keyboard = keyboards[i];\n\n for (int j = jstart; j >= 0; j--)\n {\n int drive = drives[j];\n\n int price = keyboard + drive;\n if (price < result)\n break;\n\n if (price > result && price <= budget)\n {\n result = price;\n }\n }\n }\n\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:20:13.443",
"Id": "434654",
"Score": "1",
"body": "Well that's embarassing. Definitely a slip of the brain in terms of forgetting to loop through the `affordableKeyboards` & `affordableDrives` arrays! Appreciate the feedback though, definite +1 from me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T06:25:05.783",
"Id": "434680",
"Score": "2",
"body": "@Webbarr: I think, most of us know the feeling. You're not the first and won't be the last :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:04:40.917",
"Id": "224111",
"ParentId": "224100",
"Score": "8"
}
},
{
"body": "<p>3 good answers already, but there's more!</p>\n\n<hr />\n\n<p>I don't like that you modify the array you are given. This sort of thing would need to be documented, and generally creates confusion for all. You don't need arrays as inputs, so you could take <code>IEnumerable</code>s instead without any added cost, which makes the code easier to reuse and communicates to the consumer that you aren't modifying anything. I'd consider making the parameter names a little more explicit:</p>\n\n<pre><code>public static int GetMoneySpent(IEnumerable<int> keyboardPrices, IEnumerable<int> drivePrices, int budget)\n</code></pre>\n\n<p>Your <code>SortArrayDescending</code> modifies the array given, and then proceeds to return it: this is how to really annoying people, because they will assume that because the method returns something that it won't be modifying the input.</p>\n\n<hr />\n\n<p>You've clearly thought about edge cases, which is good. You might consider some parameter validation (e.g. checking the <code>budget</code> makes sense, the arrays should not be <code>null</code>):</p>\n\n<pre><code>if (budget < 0)\n throw new ArgumentOutOfRangeException(nameof(budget), \"Budget must be non-negative\");\nif (keyboardPrices == null)\n throw new ArgumentNullException(nameof(keyboardPrices));\nif (drivePrices == null)\n throw new ArgumentNullException(nameof(drivePrices));\n</code></pre>\n\n<p>At the moment the program would print -1, which is sort of makes sense, but could easily be the first clue that something has gone wrong higher-up.</p>\n\n<hr />\n\n<p>As implied by J_H, you should discard before the sort. The following also clones the arrays immediately so we don't modify them:</p>\n\n<pre><code>// filter to within-budget items, sort the two arrays (ascending)\nkeyboards = keyboards.Where(k => k < budget).ToArray();\nArray.Sort(keyboards);\n\ndrives = drives.Where(d => d < budget).ToArray();\nArray.Sort(drives);\n</code></pre>\n\n<hr />\n\n<p>J_H has already described how you can get the optimal time complexity, but you can perform the loops at the end very simply, without needing nesting or binary search or any of that.</p>\n\n<p>You also don't need to record a list of all the candidates, just keep track of the current best, as Henrik Hansen has already demonstrated:</p>\n\n<pre><code>// maximum within budget price\nint max = -1;\n</code></pre>\n\n<p>If we start by looking at the most expensive keyboard and cheapest drive and simultaneously iterate through both, we can do this bit in linear time.</p>\n\n<pre><code>int ki = keyboards.Length - 1; // drive index\nint di = 0; // drive index\n\nwhile (ki >= 0 && di < drives.Length)\n{\n int candidate = keyboards[ki] + drives[di];\n if (candidate <= budget)\n {\n max = Math.Max(candidate, max);\n di++;\n }\n else\n {\n ki--;\n }\n}\n</code></pre>\n\n<p>Suppose we are looking at keyboard <code>ki</code> and drive <code>di</code>: <code>candidate</code> is the sum of their costs. If this candidate cost is no more than the budget, then it is a candidate for the max. We also know that we can check for a more pairing by looking at the next most expensive drive, <code>di + 1</code>. If instead the candidate was out of the budget, we know we can find a cheaper candidate by looking at the next cheapest keyboard <code>ki - 1</code>.</p>\n\n<p>Basically, we look at each keyboard in turn, and cycle through the drives until we find the most expensive one we can get away with. When we find the first drive that is too expensive, we move onto the next keyboard. We know that we don't want any drive cheaper than the last one we looked at, because that could only produce a cheaper pair, so we can continue our search starting from the same drive.</p>\n\n<p>At the end, we just return <code>max</code>: if we didn't find any candidates below budget, it will still be <code>-1</code>:</p>\n\n<pre><code>return max;\n</code></pre>\n\n<hr />\n\n<p>Concerning dfhwze's comment about buying more than 2 items: this process is essentially searching the <em>Pareto front</em>, which is done trivially and efficiently for 2 items, but becomes nightmarish for any more, so I would certainly forgive you for sticking to 2 lists ;)</p>\n\n<hr />\n\n<p>The above code all in one, with added inline documentation to make the purpose explicit (useful for the consumer, so that they know exactly what it is meant to do, and useful for the maintainer, so that they also know what it is meant to do):</p>\n\n<pre><code>/// <summary>\n/// Returns the maximum price of any pair of a keyboard and drive that is no more than the given budget.\n/// Returns -1 if no pair is within budget.\n/// </summary>\n/// <param name=\"keyboardPrices\">A list of prices of keyboards.</param>\n/// <param name=\"drivepricess\">A list of prices of drives.</param>\n/// <param name=\"budget\">The maximum budget. Must be non-negative</param>\npublic static int GetMoneySpent2(IEnumerable<int> keyboardPrices, IEnumerable<int> drivePrices, int budget)\n{\n if (budget < 0)\n throw new ArgumentOutOfRangeException(nameof(budget), \"Budget must be non-negative\");\n if (keyboardPrices == null)\n throw new ArgumentNullException(nameof(keyboardPrices));\n if (drivePrices == null)\n throw new ArgumentNullException(nameof(drivePrices));\n\n if (budget == 0)\n return -1;\n\n // filter to within-budget items, sort the two arrays (ascending)\n var keyboards = keyboardPrices.Where(k => k < budget).ToArray();\n Array.Sort(keyboards);\n\n var drives = drivePrices.Where(d => d < budget).ToArray();\n Array.Sort(drives);\n\n // maximum within budget price\n int max = -1;\n\n int ki = keyboards.Length - 1; // keyboard index\n int di = 0; // drive index\n\n while (ki >= 0 && di < drives.Length)\n {\n int candidate = keyboards[ki] + drives[di];\n if (candidate <= budget)\n {\n max = Math.Max(candidate, max);\n di++;\n }\n else\n {\n ki--;\n }\n }\n\n return max;\n}\n</code></pre>\n\n<hr />\n\n<p>J_H's solution (using a <code>BinarySearch</code>) could well be better in practise, because you only need to sort (and binary search) the shortest input: you can scan the other however you like. Implementation of that, since I too enjoy the sport:</p>\n\n<pre><code>/// <summary>\n/// Returns the maximum price of any pair of a keyboard and drive that is no more than the given budget.\n/// Returns -1 if no pair is within budget.\n/// </summary>\n/// <param name=\"keyboardPrices\">A list of prices of keyboards.</param>\n/// <param name=\"drivepricess\">A list of prices of drives.</param>\n/// <param name=\"budget\">The maximum budget. Must be non-negative</param>\npublic static int GetMoneySpent3(IEnumerable<int> keyboardPrices, IEnumerable<int> drivePrices, int budget)\n{\n if (budget < 0)\n throw new ArgumentOutOfRangeException(nameof(budget), \"Budget must be non-negative\");\n if (keyboardPrices == null)\n throw new ArgumentNullException(nameof(keyboardPrices));\n if (drivePrices == null)\n throw new ArgumentNullException(nameof(drivePrices));\n\n if (budget == 0)\n return -1;\n\n // filter to within-budget items\n var keyboards = keyboardPrices.Where(k => k < budget).ToArray();\n var drives = drivePrices.Where(d => d < budget).ToArray();\n\n // determine which list is shorter\n IReadOnlyList<int> longList;\n int[] shortList;\n\n if (keyboards.Length < drives.Length)\n {\n shortList = keyboards;\n longList = drives;\n }\n else\n {\n shortList = drives;\n longList = keyboards;\n }\n\n // special case of empty short-list\n if (shortList.Length == 0)\n return -1;\n\n // sort shortList, to facilitate binary search\n Array.Sort(shortList);\n\n // maximum within budget price\n int max = -1;\n\n foreach (var k in longList)\n {\n // filter faster\n if (k + shortList[0] > budget)\n continue;\n\n // find most expensive drive no more than budget - k\n int i = Array.BinarySearch(shortList, budget - k);\n i = i >= 0\n ? i // found\n : ~i - 1; // not found, consider next smallest\n\n // if such a drive exists, consider it a candidate\n if (i >= 0)\n {\n int candidate = k + shortList[i];\n max = Math.Max(max, candidate);\n }\n }\n\n return max;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T19:24:19.207",
"Id": "434916",
"Score": "1",
"body": "Now that's an answer! I'll be honest - quite a bit of that is over my head, but the exciting part of that is it's given me a lot of things to research & develop upon. I really appreciate the time you put into it, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T22:41:46.040",
"Id": "224125",
"ParentId": "224100",
"Score": "7"
}
},
{
"body": "<p>As others have pointed out, the code should be object oriented. It’s OK to start with procedural code as you have, but if you do, you should get in the habit of writing a quick test in your main entry point. Once you’ve written the first test, it can help you start seeing objects more clearly (and drive you to further unit tests.)</p>\n\n<p>For example: an ElectronicsShop would only have a catalog of items, but it has nothing to do with your spending habits. In your case, it would serve only as a data store for items. </p>\n\n<p>I’d really expect to see a Shopper class. The shopper would have both Money and a BuyingStrategy. The money could be a simple amount, but the strategy would be what you’re really working on. Finally, the strategy would expose a method Shop(Store, Items[], Budget). </p>\n\n<p>Inside Shop(), you’d retrieve the items from the store that meet your criteria: they’d be only keyboards and drives, and they’d be within budget. The shopper would add only eligible items to their comparison lists. Then comes time to evaluate them , so you’d add an Evaluate(Budget, ItemLists[]) method that would be called from within Shop(). Inside Evaluate() you can order results by price. But what happens when you get multiple answers that meet the same amount? A budget of 10 would be met by any of {9,1}, {1,9}, {6,4}, or even {5,5}! Which is more important, expensive drives or expensive keyboards? (In the real world, you’d go back to your product owner at this point and ask them about their priorities: “do you prefer the most expensive drive, the most expensive keyboard, or should it try to split the difference somehow?”) This might lead you to conclude that Evaluating is really the strategy, not Buying. </p>\n\n<p>I could go on, but I think I’ve made my point. Notice how once I’ve defined just a few relevant objects that the process I’m describing begins to mirror the real world act of shopping? And once you start down this path of viewing coding problems as models of real objects interacting in the real world, you’ll see the ease of defining objects and writing tests for them, and using them to recognize shortcomings in the specs and completing your specifications. (Pro tip: specifications are <em>always</em> incomplete.)</p>\n\n<p>Performance isn’t always the best starting point. Object oriented programming is less about finding the most mathematically efficient solution; it’s about building <em>understandable</em> components and proving that they meet your clients’ needs. Getting to the right answer is much more important than quickly getting to some answer that you can’t prove is correct. If performance is an issue after you’ve solved the problem, then start optimizing; but don’t start there. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T19:21:57.270",
"Id": "434914",
"Score": "1",
"body": "Thank you! I really appreciate your answer. It's given me quite a lot to think about (especially going back over this particular challenge) but also in my job today. I've definitely fallen into a nasty habbit of writing procedural code & releasing it, it's something I need to stop. Your answer just makes sense I guess. Again, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:32:55.893",
"Id": "224178",
"ParentId": "224100",
"Score": "3"
}
},
{
"body": "<p>I'd like to advocate for a more functional programming style. We all know object orientation can provide clarity over procedural programming, but if you can replace for loops and if statements with Select and Where? I'd say that's even better.</p>\n\n<p>Here's how:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int GetMoneySpent(int budget, int[] keyboards, int[] drives)\n{\n var affordableCombinations = keyboards\n .SelectMany(keyboard => drives\n .Select(drive => keyboard + drive))\n .Where(cost => cost <= budget);\n\n return affordableCombinations.Any()\n ? affordableCombinations.Max()\n : -1;\n}\n</code></pre>\n\n<hr>\n\n<p>Is this as efficient as your solution? Not in terms of CPU cycles, no. In terms of what the person reading the code must do, in order to understand the desired behavior? I'll argue yes.</p>\n\n<p>If you believe you'll see large performance gains by filtering out keyboards and drives that exceed the budget on their own, before adding any prices together, there's a concise way to do that with LINQ also:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int GetMoneySpent(int budget, int[] keyboards, int[] drives)\n{\n Func<int, bool> affordable = cost => cost < budget;\n\n var affordableCombinations = keyboards\n .Where(affordable)\n .SelectMany(keyboard => drives\n .Where(affordable)\n .Select(drive => keyboard + drive))\n .Where(affordable);\n\n return affordableCombinations.Any()\n ? affordableCombinations.Max()\n : -1;\n}\n</code></pre>\n\n<hr>\n\n<p>Is this as efficient as a solution involving manual iteration can be? Again, no. I think the approach in Henrik's answer is about the best you'll do. But this is easily readable, and probably efficient <em>enough</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T23:54:16.417",
"Id": "224515",
"ParentId": "224100",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224125",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T16:03:27.327",
"Id": "224100",
"Score": "11",
"Tags": [
"c#",
"programming-challenge",
"combinatorics"
],
"Title": "HackerRank: Electronics Shop"
} | 224100 |
<p>The problem statement: The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
<p>This code takes 9 seconds!, is there a better way?</p>
<pre><code>from time import time
def is_prime(number):
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
return False
return True
def calculate_largest(number):
# checking backwards to get the largest number first
for divisor in range(int(number ** 0.5) + 1, 0, -1):
if is_prime(divisor) and number % divisor == 0:
return divisor
if __name__ == '__main__':
time1 = time()
print(calculate_largest(600851475143))
print(time() - time1)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:21:44.087",
"Id": "434646",
"Score": "3",
"body": "That is not the most efficient solution. I suggest to check some [related questions](https://codereview.stackexchange.com/search?q=%5Bpython%5D+largest+prime+factor)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:05:25.983",
"Id": "434651",
"Score": "0",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:09:43.337",
"Id": "434653",
"Score": "0",
"body": "didn't know that, thanks for letting me know, anyway I want to mark it as answered or so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:51:40.320",
"Id": "434964",
"Score": "0",
"body": "@emadboctor If you want to mark the question as answered then you should upvote answers if they helped you. If you think on of the answers helped the most, then you should press the tick next to that answer, which marks it as the best answer."
}
] | [
{
"body": "<h1>order</h1>\n<p>You wrote:</p>\n<pre><code> if is_prime(divisor) and number % divisor == 0:\n</code></pre>\n<p>that is, <code>if A and B:</code>.</p>\n<p>But <code>B</code> is typically false and is quickly computed.\nPrefer <code>if B and A:</code></p>\n<h1>stride</h1>\n<p>Rather than</p>\n<pre><code> for divisor in range(int(number ** 0.5) + 1, 0, -1):\n</code></pre>\n<p>you might want to begin with an odd number and then use a stride of <code>-2</code>.\nYou needn't special case for when <code>number</code> is a power of two,\nsince the input clearly isn't.</p>\n<h1>sieve</h1>\n<p>Consider <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">sieving</a> for the solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:51:45.750",
"Id": "434650",
"Score": "2",
"body": "Yeah I don't think sieving is the way to go with this one. Whilst you can use similar fundamentals they achieve fundamentally different things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:06:47.057",
"Id": "434652",
"Score": "2",
"body": "Thanks, I edited the code and ran it again, time decreased dramatically (0.11 secs)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:14:36.357",
"Id": "434708",
"Score": "1",
"body": "Sieving is one of the easiest ways to speed up searching for small primes, and anyone can understand how it works. I think it's a fine way of speeding up this code.\n\nEDIT: I should note that the way to use a sieve in this case is to make a cache of primes, so you don't have to check every time if a number is prime."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:49:05.757",
"Id": "224114",
"ParentId": "224112",
"Score": "1"
}
},
{
"body": "<h2>Problems</h2>\n\n<p>There is one correcntness and two performance problems with your approach, both connected with running through the problem from the high numbers and down.</p>\n\n<p>For the correctness problem consider the number <code>91</code>, it has the factorization of <code>7*13</code>, but your approach would find <code>7</code> to be the largest, since <code>9 < 91**0.5 < 10 < 13</code>, but the correct one would be <code>13</code>. The reason we usually only need to consider primes up to the square-root of the target, is that whatever number is left when we have factorized it would be a prime number itself. This includes the number itself if we have found no prime factors.</p>\n\n<p>The first performance problem is that you have no cached data in <code>is_prime</code>, so you have to run over all of the numbers to check if it is a prime every time, this is as opposed to building up knowledge of the primes in the region, which would likely save you a lot of time, as you will likely need to test <code>is_prime</code> for a lot of numbers before you hit the right one.</p>\n\n<p>The second performance problem is that since you are running from above, you cannot make use of decreases to the target when you find smaller prime factors, which would have reduced the space you needed to look at.</p>\n\n<h2>Alternative</h2>\n\n<p>It is much simpler to write out the entire factorization, and then return the largest factor, than to try to go strictly after the last one.</p>\n\n<p>Another thing to notice is that primes will come before any other numbers that is a factor of that prime, so we can simply factorize from the lowest number and not try to remove non-primes, because we will already have factored out the parts those numbers would factor out, then they will never show up in the factorization.</p>\n\n<p>Note that if you want to do factorization for many numbers, you might want to construct the set of relevant prime numbers, while for a single use it is hard to eliminate a number faster than a single modulus operation.</p>\n\n<p>Here is an implementation of the above principles:</p>\n\n<pre><code>def factorize(target):\n factors = []\n while target % 2 == 0 and target > 1:\n factors.append(2)\n target = target // 2\n max_factor = target **0.5\n factor = 3\n while target > 1 and factor <= max_factor:\n while target % factor == 0 and target > 1:\n factors.append(factor)\n target = target // factor\n max_factor = target ** 0.5\n factor += 2\n if target > 1:\n factors.append(target)\n return factors\n\nprint(factorize(600851475143)[-1])\n</code></pre>\n\n<p>When I measure the time of the above code, it takes roughly <code>0.3ms</code> to run (a bit more for a single run and a bit less when I run it in a loop, about <code>0.35ms</code> vs <code>0.29ms</code> per run).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T03:09:10.803",
"Id": "435490",
"Score": "0",
"body": "In the nested `while` loop, shouldn't `target = target // 2` be `target = target // factor`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T06:44:59.783",
"Id": "435504",
"Score": "0",
"body": "@RootTwo That was indeed my intent, and I somehow ended up writing it wrong. I have corrected it now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:51:01.830",
"Id": "224148",
"ParentId": "224112",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T19:07:16.783",
"Id": "224112",
"Score": "0",
"Tags": [
"python",
"performance",
"programming-challenge",
"primes"
],
"Title": "Project Euler problem # 3 is this the most efficient approach in Python or can I do better?"
} | 224112 |
<p>This is the current <code>.htaccess</code> configuration for one of the website projects that I am working on, just as a learning exercise. This is working code and everything in it seems to be ok, My hosting company helped me set up a lot of these rules, While others where taken from various different blog posts. I'm looking to get feedback or reviews to see whether it is correct or whether it can be improved as I am still learning I don't expect it to be 100% accurate.</p>
<p>Some of the comments are just for my own understanding and learning purposes.
Is anything missing or incorrect? Should everything be inside an <code>IfModule</code>?</p>
<pre><code><IfModule mod_deflate.c>
SetOutputFilter DEFLATE
<IfModule mod_setenvif.c>
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# MSIE masquerades as Netscape, but it is fine
# BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
# the above regex won't work. You can use the following
# workaround to get the desired effect:
# Don't compress images
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
</IfModule>
<IfModule mod_headers.c>
# Make sure proxies don't deliver the wrong content
Header always set Content-Security-Policy: upgrade-insecure-requests
Header set Strict-Transport-Security "max-age=122112887284; includeSubDomains; preload"
Header append Vary User-Agent env=!dont-vary
Header always append X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options nosniff
Header set Access-Control-Allow-Origin "*"
IndexIgnore *.zip *.css *.php *.js *.pyt
Options -MultiViews -Indexes
</IfModule>
# I'm guessing the code I added below reffers to cache storage either locally or on host/server Please check this.
# Haven't set up any rules for Cache storage yet Add this...
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 6 hours"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/svg "access plus 1 year"
ExpiresByType image/ani "access plus 1 year"
ExpiresByType image/cur "access plus 1 year"
ExpiresByType text/css "access plus 6 months"
ExpiresByType image/html "access plus 4 hours"
ExpiresByType image/x-icon "access plus 2 year"
ExpiresByType application/pdf "access plus 2 months"
ExpiresByType text/javascript "access plus 2 hours"
</IfModule>
# Added from :: https://www.youtube.com/watch?v=FEflwAIlLmg
# Loading Ok with the Above code............
</IfModule>
# Prevent viewing of .htaccess file Same source as above
# <Files .htaccess> This part is throwing a server error...
# order allow, deny
# deny from all
# </Files>
</code></pre>
<p>The Above code block is my Old .htAccess file, I let my Hosting run out and they've deleted the whole entire project +2 others which was months worth of work and research.
I've now written out a new .htaccess file for which the code is included below. If anyone could review it for me & let me know if there are any mistakes, security issues, syntax errors or parts that could be optimized I would be hugely greatfull.</p>
<p>ServerSignature Off
DirectoryIndex coming-soon.html</p>
<pre><code> IndexIgnore *.bat *.css *.info *.zip *.js *.pyt *.txt *.py *.shtml
Options +FollowSymLinks -MultiViews -Indexes -ExecCGI
AddDefaultCharset utf-8
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml .txt .html .php .svg .shtml .py .pyt
<IfModule mod_headers.c>
# Make sure proxies don't deliver the wrong content
Header always set Content-Security-Policy: upgrade-insecure-requests
Header set Strict-Transport-Security "max-age=122112887284;
# includeSubDomains; preload"
Header append Vary User-Agent env=!dont-vary
Header always append X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options nosniff
# Header expect-CT: enforce, max-age=21600
# Header set Access-Control-Allow-Origin "*"
<FilesMatch "\.(ttf|otf|eot|woff|woff2|font.css|ico|webp)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
<filesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
#No access to the .htaccess und .htpasswd
<FilesMatch "(\.htaccess|\.htpasswd)">
Order deny,allow
Deny from all
</FilesMatch>
<files install.php>
Order allow,deny
Deny from all
</files>
<filesMatch "\\.(css)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\\.(js)$">
Header set Cache-Control "max-age=216000, private, must-revalidate"
</filesMatch>
<filesMatch "\\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
# No access to the readme.html
<files readme.html>
Order Allow,Deny
Deny from all
Satisfy all
</Files>
</IfModule>
<IfModule mod_setenvif.c>
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# MSIE masquerades as Netscape, but it is fine
# BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
# the above regex won't work. You can use the following
# workaround to get the desired effect:
# Don't compress images
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 6 hours"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/svg "access plus 1 year"
ExpiresByType image/ani "access plus 1 year"
ExpiresByType image/cur "access plus 1 year"
ExpiresByType text/css "access plus 6 months"
ExpiresByType image/html "access plus 4 hours"
ExpiresByType image/x-icon "access plus 2 year"
ExpiresByType application/pdf "access plus 2 months"
ExpiresByType text/javascript "access plus 3 hours"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (eval\() [NC,OR]
RewriteCond %{QUERY_STRING} (127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} ([a-z0-9]{2000,}) [NC,OR]
RewriteCond %{QUERY_STRING} (javascript:)(.*)(;) [NC,OR]
RewriteCond %{QUERY_STRING} (base64_encode)(.*)(\() [NC,OR]
RewriteCond %{QUERY_STRING} (GLOBALS|REQUEST)(=|\[|%) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)(.*)script(.*)(>|%3) [NC,OR]
RewriteCond %{QUERY_STRING} (\\|\.\.\.|\.\./|~|`|<|>|\|) [NC,OR]
RewriteCond %{QUERY_STRING} (boot\.ini|etc/passwd|self/environ) [NC,OR]
RewriteCond %{QUERY_STRING} (thumbs?(_editor|open)?|tim(thumb)?)\.php [NC,OR]
RewriteCond %{QUERY_STRING} (\'|\")(.*)(drop|insert|md5|select|union) [NC]
RewriteRule .* - [F]
</IfModule>
# 6G:[REQUEST METHOD]
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_METHOD} ^(connect|debug|move|put|trace|track) [NC]
RewriteRule .* - [F]
</IfModule>
# 6G:[REFERRERS]
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_REFERER} ([a-z0-9]{2000,}) [NC,OR]
RewriteCond %{HTTP_REFERER} (semalt.com|todaperfeita) [NC]
RewriteRule .* - [F]
</IfModule>
# 6G:[REQUEST STRINGS]
<IfModule mod_alias.c>
RedirectMatch 403 (?i)([a-z0-9]{2000,})
RedirectMatch 403 (?i)(https?|ftp|php):/
RedirectMatch 403 (?i)(base64_encode)(.*)(\()
RedirectMatch 403 (?i)(=\\\'|=\\%27|/\\\'/?)\.
RedirectMatch 403 (?i)/(\$(\&)?|\*|\"|\.|,|&|&amp;?)/?$
RedirectMatch 403 (?i)(\{0\}|\(/\(|\.\.\.|\+\+\+|\\\"\\\")
RedirectMatch 403 (?i)(~|`|<|>|:|;|,|%|\\|\{|\}|\[|\]|\|)
RedirectMatch 403 (?i)/(=|<span class="math-container">\$&|_mm|cgi-|muieblack)
RedirectMatch 403 (?i)(&pws=0|_vti_|\(null\)|\{\$</span>itemURL\}|echo(.*)kae|etc/passwd|eval\(|self/environ)
RedirectMatch 403 (?i)\.(aspx?|bash|bak?|cfg|cgi|dll|exe|git|hg|ini|jsp|log|mdb|out|sql|svn|swp|tar|rar|rdf)$
RedirectMatch 403 (?i)/(^$|(wp-)?config|mobiquo|phpinfo|shell|sqlpatch|thumb|thumb_editor|thumbopen|timthumb|webshell)\.php
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /coming-soon.html [NC,L,QSA]
</IfModule>
<IfModule mod_deflate.c>
# SetOutputFilter DEFLATE
</IfModule>
# MIME Types ...>[Some of these are redundant & will never be used in My Application Only include the ones you wish to use.]
<IfModule mod_mime.c>
# ::>>. Text/Plain Text
AddType text/plain .txt
AddType text/xml .xml
AddType text/xsl .xsl
AddType text/xsd .xsd
AddType text/css .css
AddType text/x-js .js4
AddType text/javascript .js3
AddType text/x-component .htc
AddType text/html .html .shtml .htm
AddType text/richtext .rtf .rtx
# ::>>. Images
AddType image/png .png
AddType image/bmp .bmp
AddType image/gif .gif
AddType image/x-icon .ico
AddType image/tiff .tif .tiff
AddType image/svg+xml .svg .svgz
AddType image/jpeg .jpg .jpeg .jpe
# ::>>. Audio
AddType audio/wav .wav
AddType audio/wma .wma
AddType video/avi .avi
AddType audio/ogg .ogg
AddType video/divx .divx
AddType video/mp4 .mp4 .m4v
AddType audio/mpeg .mp3 .m4a
AddType audio/midi .mid .midi
AddType audio/x-realaudio .ra .ram
# ::>>. Video
AddType video/quicktime .mov .qt
AddType video/mpeg .mpeg .mpg .mpe
AddType video/asf .asf .asx .wax .wmv .wmx
# ::>>. Applications
AddType application/zip .zip
AddType application/pdf .pdf
AddType application/x-tar .tar
AddType application/json .json
AddType application/java .class
AddType application/x-font-otf .otf
AddType application/font-woff .woff
AddType application/x-gzip .gz .gzip
AddType application/x-font-ttf .ttf .ttc
AddType application/x-javascript .js
AddType application/javascript .js2
AddType application/msword .doc .docx
AddType application/x-msdownload .exe
AddType application/vnd.ms-write .wri
AddType application/vnd.ms-access .mdb
AddType application/vnd.ms-project .mpp
AddType application/vnd.ms-opentype .otf
AddType application/vnd.ms-fontobject .eot
AddType application/x-shockwave-flash .swf
AddType application/vnd.ms-opentype .ttf .ttc
AddType application/vnd.oasis.opendocument.text .odt
AddType application/vnd.oasis.opendocument.chart .odc
AddType application/vnd.oasis.opendocument.formula .odf
AddType application/vnd.oasis.opendocument.graphics .odg
AddType application/vnd.oasis.opendocument.database .odb
AddType application/vnd.oasis.opendocument.presentation .odp
AddType application/vnd.oasis.opendocument.spreadsheet .ods
AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
</IfModule>
</code></pre>
<p>the backticks in the <code>RewriteCond</code> match seem to be messing up the syntax highlighting on Code review, but there's not much I can do about that.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:04:36.040",
"Id": "224115",
"Score": "3",
"Tags": [
"performance",
"security",
".htaccess"
],
"Title": ".htaccess file to enable compression, send security headers, and set cache expiration"
} | 224115 |
<h2>Introduction</h2>
<p>I've found a clever and fun thing to do after solving a n<sup>2</sup> × n<sup>2</sup> sudoku puzzle. I can take
a grid as such as this one and hard-code its indices as constraints to output other 4 × 4 latin squares in poly-time</p>
<p><a href="https://i.stack.imgur.com/aoLkZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aoLkZ.png" alt="enter image description here"></a></p>
<p>Now, I took each successive row and hardcoded as indices with successive print statements.</p>
<p>Indices constraints</p>
<pre><code>0123
3210
1032
2301
</code></pre>
<p>Working Code</p>
<pre><code>print('enter with [1,2,3...] brackets')
text = input()[1:-1].split(',')
print(text[0], text[1], text[2], text[3])
print(text[3], text[2], text[1], text[0])
print(text[1], text[0], text[3], text[2])
print(text[2], text[3], text[0], text[1])
</code></pre>
<h2>Question</h2>
<p>Being a novice at python I'm asking is there a better way of hardcoding the Sudoku's pattern with fewer lines of code?</p>
<p><em>Because it would be daunting to have to write larger constraints for larger latin squares.</em></p>
<p>I would appreciate it to keep it O(n) time because I have a desire to input integers besides just elements 1-4. But, 100-104 and so on..</p>
| [] | [
{
"body": "<ul>\n<li>Use <code>json</code> to simplify your input handling.</li>\n<li>You can use <code>str.format</code> to simplify all the <code>prints</code>.</li>\n<li>You don't handle incorrect data well. What if I enter 3 or 5 numbers?</li>\n<li>Your code doesn't run in <span class=\"math-container\">\\$O(n)\\$</span> time, it runs in <span class=\"math-container\">\\$O(n^2)\\$</span> time. I recommend that you ignore <span class=\"math-container\">\\$O\\$</span> and just get working code if you're a novice. After you get it working make it readable. Finally here you should time your code to see if you need to then optimize it.</li>\n<li>Use functions, they make your code easier to use.</li>\n</ul>\n\n<pre><code>import json\n\n\ndef handle_input(input_):\n try:\n data = json.loads(input_)\n except ValueError:\n raise ValueError('Invalid format.')\n\n if len(data) != 4:\n raise ValueError(f'Incorrect amount of numbers, got {len(data)} not 4.')\n return data\n\n\ndef main():\n print('Enter four numbers in brackets. E.g. [1, 2, 3, 4]')\n data = handle_input(input())\n print(\n '{0} {1} {2} {3}\\n'\n '{3} {2} {1} {0}\\n'\n '{1} {0} {3} {2}\\n'\n '{2} {3} {0} {1}\\n'\n .format(*data)\n )\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:14:47.587",
"Id": "434664",
"Score": "0",
"body": "Thank you, but should '{3} {2} {2} {0}\\n' be '{3} {2} {1} {0}\\n'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:24:17.190",
"Id": "434665",
"Score": "0",
"body": "@TravisWells You are correct, I have updated the answer to account for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:33:08.600",
"Id": "434668",
"Score": "0",
"body": "Also for some strange reason. I get an error. Try it and run it in the link below. You'll see. It seems to be fixed if you switch it 4 to a 5 (line 10). And again, I appreciate your answer. That should work. https://repl.it/repls/SquareLinearConferences"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:38:39.953",
"Id": "434670",
"Score": "1",
"body": "@TravisWells I accidentally used `!=` rather than `==`. The program told you what the problem was tho, so it shouldn't be a 'strange reason'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:39:50.800",
"Id": "434671",
"Score": "0",
"body": "yeah, I'm still a novice. I have to keep learning syntax errors. Just trying to be observant."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T21:40:16.057",
"Id": "224121",
"ParentId": "224116",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T20:30:24.370",
"Id": "224116",
"Score": "0",
"Tags": [
"python",
"sudoku"
],
"Title": "Python script takes input of four elements and outputs a valid 4 × 4 Sudoku grid in O(n) time, but only when given non-repeating elements"
} | 224116 |
<p>I want to populate columns of a dataframe (df) by iteratively looping over a list (A_list) generating a dictionary where the keys are the names of the desired columns of df (in the example below the new columns are 'C', 'D', and 'E')</p>
<pre><code>import pandas
def gen_data(key):
#THIS FUNCTION IS JUST AN EXAMPLE THE COLUMNS ARE NOT NECESSARILY RELATED OR USE THE KEY
data_dict = {'C':key+key, 'D':key, 'E':key+key+key}
return data_dict
A_list = ['a', 'b', 'c', 'd', 'f']
df = pandas.DataFrame({'A': ['a', 'b', 'c', 'd', 'f'], 'B': [1,2,3,3,2]})
for A_value in A_list:
data_dict = gen_data(A_value)
for data_key in data_dict:
df.loc[df.A == A_value, data_key] = data_dict[key]
</code></pre>
<p>So the result of this should be:</p>
<pre><code>df = pandas.DataFrame({'A': ['a', 'b', 'c', 'd', 'e','f'],
'B': [1,2,3,3,2,1],
'C': ['aa','bb','cc','dd',nan,'ff'],
'D': ['a', 'b', 'c', 'd', nan,'f'],
'E': ['aaa','bbb','ccc','ddd',nan,'fff']})
</code></pre>
<p>I feel that </p>
<pre><code>for data_key in data_dict:
df.loc[df.A == A_value, data_key] = data_dict[key]
</code></pre>
<p>is really inefficient if there are a lot of rows in df and I feel that there should be a way to remove the for loop in this code.</p>
<pre><code>for A_value in A_list:
data_dict = gen_data(A_value)
for data_key in data_dict:
df.loc[df.A == key, data_key] = data_dict[key]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:44:47.003",
"Id": "434672",
"Score": "0",
"body": "Since you're looking for a specific improvement in your code it belongs on Stack Overflow instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T16:49:57.917",
"Id": "435027",
"Score": "0",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
}
] | [
{
"body": "<p>Since there is an <code>e</code> missing in the input dataframe in col <code>A</code> provided by you, I have added it:</p>\n\n<pre><code>#input\nA_list = ['a', 'b', 'c', 'd', 'f']\ndf = pd.DataFrame({'A': ['a', 'b', 'c', 'd','e','f'], 'B': [1,2,3,3,2,1]})\n</code></pre>\n\n<hr>\n\n<p>You can start by joining the list you have:</p>\n\n<pre><code>pat='({})'.format('|'.join(A_list))\n#pat --> '(a|b|c|d|f)'\n</code></pre>\n\n<p>Then using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html\" rel=\"nofollow noreferrer\"><code>series.str.extract()</code></a> I am extracting the matching keys from the series based on the pattern we created.</p>\n\n<pre><code>s=df.A.str.extract(pat,expand=False) #expand=False returns a series for further assignment\nprint(s)\n</code></pre>\n\n<hr>\n\n<pre><code>0 a\n1 b\n2 c\n3 d\n4 NaN\n5 f\n</code></pre>\n\n<p>Once you have this series, you can decide what you want to do with it. For,example if I take your function:</p>\n\n<pre><code>def gen_data(key):\n #THIS FUNCTION IS JUST AN EXAMPLE THE COLUMNS ARE NOT NECESSARILY RELATED OR USE THE KEY \n data_dict = {'C':key*2, 'D':key, 'E':key*3}\n return data_dict\n</code></pre>\n\n<p>And do the below:</p>\n\n<pre><code>df.join(pd.DataFrame(s.apply(gen_data).values.tolist()))\n</code></pre>\n\n<p>We get the desired output:</p>\n\n<pre><code> A B C D E\n0 a 1 aa a aaa\n1 b 2 bb b bbb\n2 c 3 cc c ccc\n3 d 3 dd d ddd\n4 e 2 NaN NaN NaN\n5 f 1 ff f fff\n</code></pre>\n\n<p>However I personally <a href=\"https://stackoverflow.com/questions/54432583/when-should-i-ever-want-to-use-pandas-apply-in-my-code\">wouldn't</a> use apply unless mandatory, so here is another way using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html\" rel=\"nofollow noreferrer\"><code>df.assign()</code></a> where you can pass a dictionary of the extracted series and assign it to the dataframe:</p>\n\n<pre><code>df=df.assign(**{'C':s*2,'D':s,'E':s*3})\n</code></pre>\n\n<hr>\n\n<pre><code> A B C D E\n0 a 1 aa a aaa\n1 b 2 bb b bbb\n2 c 3 cc c ccc\n3 d 3 dd d ddd\n4 e 2 NaN NaN NaN\n5 f 1 ff f fff\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:54:12.500",
"Id": "434965",
"Score": "0",
"body": "Hey anky_91, Thank you for your reply. I really like the df.assign example you showed however my problem is that my \"gen_data\" is a bit complex requiring file io access so I won't be able to do any vectorization (i.e. {'C':s*2,'D':s,'E':s*3}) as per your example. However I have iteratively used assign with `df.loc[df.A == key] = df.loc[df.A == key].assign(**metric_dict)` and it now only take 1/3 the amount of time. is there a more efficient way of using assign?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T02:27:48.867",
"Id": "434968",
"Score": "1",
"body": "@kkawabat if vectorization isn't possible, you're doing it right IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T02:31:14.997",
"Id": "434969",
"Score": "0",
"body": "I've editted the submission to use `assign()` which seems to finish a bit faster. TY"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T06:37:39.693",
"Id": "224137",
"ParentId": "224126",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224137",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T23:19:46.057",
"Id": "224126",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Pandas updating/adding columns to rows incrementally using dictionary key values"
} | 224126 |
<p>Is there any room for improvement? Your feedback would be helpful.</p>
<p>Problem Statement:
The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
What is the value of this product? </p>
<pre><code>import operator
number = """\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450
"""
# Find the thirteen adjacent digits in the 1000-digit number that have
# the greatest product.
# What is the value of this product?
def partition(n):
"""returns a list of n series"""
list_of_nums = list(number)
all_partitions = []
while len(list_of_nums) != 0:
count = 0
temp = ''
while count <= n - 1:
try:
temp += list_of_nums[count]
count += 1
except IndexError:
return all_partitions
all_partitions.append(temp)
if len(list_of_nums) != 0:
del list_of_nums[0]
return all_partitions
def get_max(all_partitions):
"""returns the maximum product of n series"""
part_sum = []
for num in all_partitions:
tot = 1
for digit in num:
tot *= int(digit)
if tot != 0:
part_sum.append((num, tot))
return sorted(part_sum, key=operator.itemgetter(1), reverse=True)[0]
[1]
if __name__ == '__main__':
# Sanity check: sequence of length (4)
partitions1 = partition(4)
print(get_max(partitions1))
print()
# Result: sequence of length (13)
partitions2 = partition(13)
print(get_max(partitions2))
</code></pre>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li><code>number</code> and <code>n</code> could be <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">parameters</a> to this script. That way the whole thing would be reusable.</li>\n<li><p>You can use list comprehensions to partition your string:</p>\n\n<pre><code>>>> def partition(digits: str, length: int) -> List[str]:\n... return [digits[index:index + length] for index in range(len(digits) - length + 1)]\n... \n>>> partition(\"12345\", 3)\n['123', '234', '345']\n</code></pre></li>\n<li><p>Multiplying N random digits is going to be slower than checking whether any of the digits are zero. So your first pass could be to exclude any partitions which contain zero. If there are no partitions left afterwards the max is zero, and you've done no multiplications at all.</p>\n\n<pre><code>>>> partitions = partition(\"7316717653133062491\", 13)\n>>> nontrivial_partitions = [partition for partition in partitions if \"0\" not in partition]\n>>> nontrivial_partitions\n['7316717653133']\n</code></pre></li>\n<li>An optimization on the above is to immediately discard the next N - 1 digits as soon as you encounter a zero when generating partitions, since all of those partitions are also going to multiply to zero. Make sure you check for any zeros within those numbers as well to keep skipping.</li>\n<li>It looks like you have a newline at the end of <code>number</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T01:42:43.450",
"Id": "224128",
"ParentId": "224127",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T00:33:50.413",
"Id": "224127",
"Score": "2",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler Problem # 8 maximum product of sequences"
} | 224127 |
<p>I've been working on my first Python library which provides different utilities for a set of bioinformatics tools. I am looking for feedback on this module I made for parsing configurations needed for each tool run. </p>
<p>To give a little more context, users are prompted with a text box to edit the default parameters that a tool runs with given a list of different acceptable values that each option may take on.</p>
<p>config.py</p>
<pre><code># -*- coding: utf-8 -*-
"""
toolhelper.config
~~~~~~~~~~~~~~~~~
This module provides the needed functionality
for parsing and verifying user-inputted config files.
"""
import sys
import logging
PY2 = sys.version_info[0] == 2
if PY2:
import ConfigParser
else:
import configparser as ConfigParser
class Config(object):
"""This class implements config file parsing and validation.
Methods:
...
Attributes:
...
"""
def __init__(self, defaults,
value_map,
filename,
sections,
numericals=None,
allow_no_val=False):
self.defaults = defaults
self.value_map = value_map
self.filename = filename
self.sections = sections
self.numericals = numericals
self.settings = self._parse()
self.allow_no_val = allow_no_val
def _parse(self):
"""Builds dict from user-inputted config settings.
Returns:
Dictionary of config settings to be used for a tool run.
"""
config = ConfigParser.ConfigParser(allow_no_value=self.allow_no_val)
cfg = config.read(self.filename)
if not cfg:
msg = 'Config file not readable: Using default parameters.'
logging.error(msg)
return self.defaults
settings = {}
# Iterate over defaults keys to get each option to lookup
for option in self.defaults:
try:
input_val = _get_config_value(config, self.sections, option)
numerical = option in self.numericals.keys()
# Some of the tools allow for cases where the user can choose from
# many possible unlisted values for a specific option. This is assumed
# when option is in defauls by not value_map
in_value_map = option in self.value_map.keys()
in_defaults = option in self.defaults.keys()
# Might want to make this behavior more explicit.
if in_defaults and in_value_map and not numerical:
value = input_val
msg = 'Will check value for option: {} in specific tool.'.format(option)
logging.debug(msg)
else:
value = self._value_map_lookup(option, input_val, num=numerical)
except (InvalidValueError, InvalidOptionError):
msg = ('Invalid or missing entry for {}. Using default: '
' {}.'.format(option, self.defaults[option]))
logging.error(msg)
settings[option] = self.defaults[option]
else:
logging.debug('parameter %s = %s is valid.', option, value)
settings[option] = value
return settings
def _value_map_lookup(self, option, value, num=False):
"""Get value corresponding to the value argument in value_map.
Args:
value: A key to lookup in the value_map dict.
numerical: dictionary of numerical entries and their ranges.
Returns:
A value obtained from value_map that is suited for the tool's
logic. value_map is a map of user-inputted values to the values
that are needed by the tool.
value_map[option][value], or float(value) if num=True and the
value is not in value_map.
Raises:
InvalidValueError: Value is not found in value_map dictionary. The given
Value is invalid
"""
if value in self.value_map[option].keys():
return self.value_map[option][value]
elif num:
try:
float_val = float(value)
_check_range(float_val, self.numericals[option][0], self.numericals[option][1])
except ValueError:
raise InvalidValueError
else:
return float_val
else:
raise InvalidValueError
def _get_config_value(config, sections, option):
""" Fetches value from ConfigParser
A wrapper around ConfigParser.get(). This function checks
that the config has the given section/option before calling
config.get(). If the config does not have the option an
InvalidOptionError is raised.
Args:
config: A RawConfigParser instance.
sections: list of config sections to check for option.
option: The parameter name to look up in the config.
Returns:
Parameter value for corresponding section and option.
Raises:
InvalidOptionError: The config is missing the given option argument.
"""
for section in sections:
if config.has_option(section, option):
return ''.join(config.get(section, option).split()).lower()
raise InvalidOptionError
def _check_range(value, lower, upper):
"""Check if lower < value < upper or lower < value if upper is 'inf'
Args:
value: A number whose range is to be checked against the given range
lower: The lower limit on the range
upper: The upper limit on the range
Raises:
InvalidValueError: value not in range
"""
if upper == 'inf':
if value >= lower:
return
elif lower <= value <= upper:
return
raise ValueError
class InvalidValueError(Exception):
"""Exception class for invalid values
Exception for when the user enters a value that
is not a valid option. Raise this exception when the
user-inputted value in not in valid_options[key].
"""
class InvalidOptionError(Exception):
"""Exception class for invalid options
Exception for when the user gives an unexpected or invlaid
option. Raise this exception to handle user-inputted options
that do not belong in the config or needed options that are
missing.
"""
</code></pre>
<p>A config object is instantiated with:</p>
<ol>
<li>a dictionary that represents a tools default config parameters</li>
</ol>
<pre><code># Default configuration values for this tool. Equivalent to Default_Parameters.txt.
# When adding keys and values to this dictionary, make sure they are lower case and
# match the values to the values in the VALUE_MAP dict.
DEFAULTS = {
'counting method' : 'templates',
'productive only' : True,
'resolved only' : True,
'vj resolution' : 'gene',
'correction' : 'BY',
'alpha' : 0.05,
}
</code></pre>
<ol start="2">
<li>A value map dictionary which holds the acceptable values for each config option with each value mapped to what the tool needs to run internally.</li>
</ol>
<pre><code># A nested dict where the outer dictionary keys are all options, and each nested
# dictionary maps acceptable user-inputted values to the corresponding values
# needed for the tool internally.
# When adding entries to be sure all strings are lowercase and devoid of whitespace.
# Note this dict does not account for numerical entries
VALUE_MAP = {
'couting method' : {
'templates' : 'templates',
'rearrangement' : 'rearrangement'
},
'productive only' : {
'true' : 'productive',
'false' : 'nonproductive'
},
'resolved only' : {
'true' : True,
'false' : False
},
'vj resolution' : {
'gene' :'gene',
'family' : 'family',
'allele' : 'allele'
},
'correction' : {
'bh' : 'BH',
'bonferroni' : 'bonferroni',
'by' : 'BY',
'fdr' : 'fdr',
'none' : None,
}
}
</code></pre>
<ol start="3">
<li><p>The filename of the file where the user configuration lives for a specific tool run.</p></li>
<li><p>The sections in the configuration.</p></li>
</ol>
<pre><code>SECTIONS = ['union', 'significance']
</code></pre>
<ol start="5">
<li>Dictionary of configuration options that can take on a numerical value in a specific range.</li>
</ol>
<pre><code># configuaration settings that may be numerical
# keys: numerical options; values: tuples that embed accepted range.
NUMERICALS = {
'alpha' : (0, 1)
}
</code></pre>
<p>A tool will then make a config instance and grab the parsed and validation settings from the config.settings attribute.</p>
<pre><code> configuration = config.Config(settings.OUTPUT_DIR,
settings.DEFAULTS,
settings.VALUE_MAP,
settings.CONFIG_FILE,
settings.SECTIONS,
settings.NUMERICALS)
parameters = configuration.settings
</code></pre>
<p>Each tool initially had it's own configuration checking method with nested try-except blocks checking each config option and it was a total mess. I spent a lot of time trying to think how to best represent and validate the config data to hopefully minimize code complexity in each tool.</p>
| [] | [
{
"body": "<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place.</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere (I'm not sure whether they work with Python 2 though) and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n\n<p>Specific suggestions:</p>\n\n<ol>\n<li>Things like pulling out <code>self.numericals.keys()</code> should not happen within a loop. You never modify it, so the result will be the same every time. Better to get this value once.</li>\n<li><code>allow_no_val</code> should probably just be called <code>allow_no_value</code>, since that's what it's used as.</li>\n<li>If you put the bit about checking for the existence of the configuration file in a <code>main()</code> method the script would be easier to test. You could then pass a stream to <code>Config</code> - presumably <code>config.read</code> handles that just as well as a filename.</li>\n<li><code>__init__</code> running <code>_parse</code> is an antipattern. Typically <code>__init__</code> only does trivial things with its parameters, and relies on other methods to do the heavy lifting. Renaming <code>_parse</code> to <code>parse</code> would help in that case.</li>\n<li>Boolean parameters are a code smell. For example, in the case of <code>_value_map_lookup</code> it would be easier to read if there was a separate lookup method for numbers.</li>\n<li><p>Returning early and structuring the rest of the code accordingly can simplify some parts of the code. For example,</p>\n\n<pre><code>if value in self.value_map[option].keys():\n return self.value_map[option][value]\nelif num:\n try:\n float_val = float(value)\n _check_range(float_val, self.numericals[option][0], self.numericals[option][1])\n except ValueError:\n raise InvalidValueError\n else:\n return float_val\nelse:\n raise InvalidValueError\n</code></pre>\n\n<p>could be written as</p>\n\n<pre><code>if value in self.value_map[option].keys():\n return self.value_map[option][value]\n\nif not num:\n raise InvalidValueError\n\ntry:\n float_val = float(value)\n _check_range(float_val, self.numericals[option][0], self.numericals[option][1])\n return float_val\nexcept ValueError:\n raise InvalidValueError\n</code></pre></li>\n<li>Why does <code>_get_config_value</code> check for an option in <em>every</em> section and return the first one? That seems to make sections pointless, because they don't matter.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T02:25:51.580",
"Id": "224130",
"ParentId": "224129",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T01:46:11.353",
"Id": "224129",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Configuration parsing and verification utility for bioinformatics tools"
} | 224129 |
<p>I wrote this program recently to generate random passwords for myself. It works well but it's been a long time since I wrote any java and am just looking on ways to clean up the code. I'm also not sure how truly "random" the password generation is or if it is too excessive.</p>
<pre><code>import java.util.Random;
import java.util.Scanner;
final class RNG
{
final public static void main(String[] args)
{
System.out.print("This program generates between 1 and 100 RANDOM and SECURE passwords.\nPasswords are not stored in any way.\nWRITE DOWN YOUR NEW PASSWORDS!\nPassword length must be between 12 and 120.\n\n");
System.out.print("Please enter the length for your new password(s): ");
Scanner input = new Scanner(System.in);
if(input.hasNextLine())
{
System.out.print("Please enter the number of passwords you wish to create: ");
Scanner number = new Scanner(System.in);
RNG myPW = new RNG();
myPW.testLength(input, number);
}
}
final private void testLength(Scanner test, Scanner amount)
{
if(test.hasNextInt() && amount.hasNextInt())
{
int PWlength = test.nextInt();
int numberOfPW = amount.nextInt();
if ((PWlength >= 12 && PWlength <= 120) && numberOfPW > 0 && numberOfPW <= 100)
{
RNG myPW = new RNG();
myPW.PWGenerator(PWlength, numberOfPW);
}
if ((PWlength < 12 || PWlength > 120) && numberOfPW > 0 && numberOfPW <= 100)
{
System.out.println("ERROR! LENGTH OF PASSWORD MUST BE BETWEEN 12 AND 120\n");
restart();
}
if ((PWlength >= 12 && PWlength <= 120) && numberOfPW <= 0)
{
System.out.println("ERROR! NUMBER OF PASSWORDS YOU WISH TO GENERATE MUST BE GREATER THAN ZERO\n");
restart();
}
if ((PWlength >= 12 && PWlength <= 120) && numberOfPW > 100)
{
System.out.println("ERROR! NUMBER OF PASSWORDS YOU WISH TO GENERATE MUST BE LESS THAN OR EQUAL TO 100\n");
restart();
}
if((PWlength < 12 || PWlength > 120) && numberOfPW <= 0)
{
System.out.println("ERROR! LENGTH OF PASSWORD MUST BE BETWEEN 10 AND 120");
System.out.println("ERROR! NUMBER OF PASSWORDS YOU WISH TO GENERATE MUST BE GREATER THAN ZERO\n");
restart();
}
if((PWlength < 12 || PWlength > 120) && numberOfPW > 100)
{
System.out.println("ERROR! LENGTH OF PASSWORD MUST BE BETWEEN 10 AND 120");
System.out.println("ERROR! NUMBER OF PASSWORDS YOU WISH TO GENERATE MUST BE LESS THAN OR EQUAL TO 100\n");
restart();
}
}
if(!test.hasNextInt() && amount.hasNextInt())
{
System.out.println("ERROR! LENGTH OF PASSWORD IS NOT AN INTEGER. PLEASE TRY AGAIN.\n");
restart();
}
if(test.hasNextInt() && !amount.hasNextInt())
{
System.out.println("ERROR! NUMBER OF PASSWORDS IS NOT AN INTEGER. PLEASE TRY AGAIN.\n");
restart();
}
else
{
System.out.println("ERROR! LENGTH OF PASSWORD IS NOT AN INTEGER. PLEASE TRY AGAIN.");
System.out.println("ERROR! NUMBER OF PASSWORDS IS NOT AN INTEGER. PLEASE TRY AGAIN.\n");
restart();
}
}
final private void restart()
{
System.out.print("Please enter the length for your new password(s): ");
Scanner input = new Scanner(System.in);
if(input.hasNextLine())
{
System.out.print("Please enter the number of passwords you wish to create: ");
Scanner number = new Scanner(System.in);
RNG myPW = new RNG();
myPW.testLength(input, number);
}
}
final private void PWGenerator(int a, int b)
{
Random randomInt = new Random();
Random randomLetterU = new Random();
Random randomLetterL = new Random();
Random randomChar = new Random();
String[] alphabetUPPER = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
String[] alphabetlower = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String[] characters = {"!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", "?", "/", "<", ">"};
int selection;
int c;
int e = 1;
System.out.println();
while(e <= b)
{
System.out.print("Password #" + e + ": ");
int d = 1;
while(d <= a)
{
c = randomInt.nextInt(4);
if (c == 0)
{
selection = randomLetterU.nextInt(26);
System.out.print(alphabetUPPER[selection]);
d++;
}
if (c == 1)
{
selection = randomLetterL.nextInt(26);
System.out.print(alphabetlower[selection]);
d++;
}
if (c == 2)
{
System.out.print(randomInt.nextInt(10));
d++;
}
if (c == 3)
{
selection = randomChar.nextInt(18);
System.out.print(characters[selection]);
d++;
}
}
System.out.println("\n");
e++;
}
if(e > b)
{System.exit(0);}
}
}
</code></pre>
| [] | [
{
"body": "<h1> General </h1>\n\n<p><code>RNG</code> is a poor name for a class that generates passwords, not random numbers. <code>PasswordGenerator</code> would be better.</p>\n\n<p>In idiomatic Java, <code>{</code> are on the same line, not on a newline. <code>else</code> is on the same line as <code>}</code>. </p>\n\n<p>In idiomatic Java, method and variable names use camelCase. Avoid acronyms - they tend to make the code harder to read.</p>\n\n<p>Using <code>final</code> indicates to the reader that variables will not be reassigned.</p>\n\n<p>Your whitespace is inconsistent. In idiomatic Java, there is always whitespace between a control flow keyword (<code>if</code>, <code>while</code>) and the <code>(</code>.</p>\n\n<p>Resources that can be closed, such as <code>Scanner</code>, should always be closed, either in a <code>try-with-resources</code> or a <code>try-finally</code>. You also only need one scanner.</p>\n\n<p>ALL CAPS messages are hard to read. Use proper capitalization.</p>\n\n<h1>restart</h1>\n\n<p>This should be refactored - there's no reason to prompt the user here and also in <code>main()</code>. It would be cleaner to have two methods, each asking for one value and repeating until it is valid.</p>\n\n<h1>testLength</h1>\n\n<p>There's no reason to test every possible permutation of cases separately. Test each case once, and include the relevant error message for that case if it fails.</p>\n\n<h1>PWGenerator</h1>\n\n<p>You only need one <code>Random</code> instance. It should be passed around, for testing purposes.</p>\n\n<p><code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, and <code>e</code> are utterly meaningless. Try to use variable names that make it easier to understand what your code is doing.</p>\n\n<p>You can make password generation a little more compact if you keep a <code>String[][]</code>, rather than a <code>String[]</code>.</p>\n\n<p>You don't need the last <code>if</code> check - you can't exit the <code>while</code> loop until you're done generating passwords. Calling <code>System.exit(0)</code> explicitly is overkill - let the flow of the application end normally.</p>\n\n<p><code>for</code> loops might be more appropriate than the <code>while</code> loops. They better limit the scope of the counter variables.</p>\n\n<p><hr/>\nIf you make all these changes, your code might look more like:</p>\n\n<pre><code>final class PasswordGenerator {\n\n public static final void main(String[] args) {\n System.out.print(\"This program generates between 1 and 100 RANDOM and SECURE passwords.\\nPasswords are not stored in any way.\\nWRITE DOWN YOUR NEW PASSWORDS!\\nPassword length must be between 12 and 120.\\n\\n\");\n try (final Scanner input = new Scanner(System.in)) {\n new PasswordGenerator().generatePasswords(passwordLength(input), numberOfPasswords(input));\n }\n }\n\n private static int scanInt(final Scanner scanner) {\n while (!scanner.hasNextInt()) {\n System.out.print(\"Error! '\" + scanner.next() + \"' is not a number. Please try again: \");\n }\n return scanner.nextInt();\n }\n\n private static int passwordLength(final Scanner scanner) {\n System.out.print(\"Please enter the length for your new password(s): \");\n int passwordLength = scanInt(scanner);\n\n while (passwordLength < 12 || passwordLength > 120) {\n System.out.println(\"Error! Length of password mut be between 12 and 120\\n\");\n System.out.print(\"Please enter the length for your new password(s): \");\n passwordLength = scanInt(scanner);\n }\n\n return passwordLength;\n }\n\n private static int numberOfPasswords(final Scanner scanner) {\n System.out.print(\"Please enter the number of passwords you wish to create: \");\n int numberOfPasswords = scanInt(scanner);\n\n while (numberOfPasswords < 1 || numberOfPasswords > 100) {\n System.out.println(\"Error! Number of passwords must be between 1 and 100\\n\");\n System.out.print(\"Please enter the number of passwords you wish to create: \");\n numberOfPasswords = scanInt(scanner);\n }\n\n return numberOfPasswords;\n }\n\n private final void generatePasswords(final int desiredPasswordLength, final int desiredNumberOfPasswords) {\n final Random random = new Random();\n\n final String[][] passwordCharacters = {\n {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"},\n {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"},\n {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\" },\n {\"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"(\", \")\", \"-\", \"_\", \"+\", \"=\", \"?\", \"/\", \"<\", \">\"},\n };\n\n System.out.println();\n\n for (int passwordNumber = 1; passwordNumber <= desiredNumberOfPasswords; passwordNumber++) {\n System.out.print(\"Password #\" + passwordNumber + \": \");\n for (int currentPasswordLength = 0; currentPasswordLength < desiredPasswordLength; currentPasswordLength++) {\n final int characterType = random.nextInt(passwordCharacters.length);\n System.out.print(passwordCharacters[characterType][random.nextInt(passwordCharacters[characterType].length)]);\n }\n System.out.println(\"\\n\");\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:35:07.273",
"Id": "224162",
"ParentId": "224131",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T03:01:22.577",
"Id": "224131",
"Score": "4",
"Tags": [
"java",
"strings",
"random"
],
"Title": "Random password generator (Java)"
} | 224131 |
<p><a href="https://projecteuler.net/problem=9" rel="nofollow noreferrer">Project Euler #9, Pythagorean triplet</a> is</p>
<blockquote>
<p>A Pythagorean triplet is a set of three natural numbers <span class="math-container">\$a < b < c\$</span>
for which <span class="math-container">\$a^2 + b^2 = c^2\$</span>.</p>
<p>For example, <span class="math-container">\$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$</span>.</p>
<p>There exists exactly one Pythagorean triplet for which <span class="math-container">\$a + b + c = 1000\$</span>. Find the product <span class="math-container">\$a b c\$</span>.</p>
</blockquote>
<p>Here is my implementation in Python, awaiting your feedback.</p>
<pre><code>def get_triplet():
for c in range(2, 1000):
for b in range(2, c):
a = 1000 - c - b
if a ** 2 + b ** 2 == c ** 2:
return 'n1 = %s\nn2 = ' \
'%s\nn3 = %s\nproduct = %s' \
% (a, b, c, a * b * c)
if __name__ == '__main__':
print(get_triplet())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T05:53:31.230",
"Id": "434677",
"Score": "1",
"body": "Please ensure that your code is posted with the intended formatting. One way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T19:16:12.793",
"Id": "435042",
"Score": "0",
"body": "There is an answer invalidation issue that has happened because of edits to the indenting of the `return` line... but I believe the indent issue resulted from bad question formatting... more than bad code formatting. part of one answer has been invalidated, but the overall effect of keeping the edit is better than rolling it back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T19:26:17.503",
"Id": "435043",
"Score": "0",
"body": "@rolfl I apologize for that; I'm the one who proposed the indent formatting fix; I hadn't read any of the answers when I suggested that, in part b/c code indent issues have usually been the more \"obvious\" fixes. I'm hoping the answers that are referencing the indents can be updated, or if it's too much, then I suppose my fix may need a rollback and the question marked with something for others to avoid fixing the same issue over and over."
}
] | [
{
"body": "<h1>simplify a and fix search space</h1>\n<p>Given the nested for loop, your variable <code>a</code> can be decremented simpler:</p>\n<p>Moreover, your search space is far too large. Other authors have addressed his in more detail, but if you want to check every possible triplet from (1-1000), then you need to change your second for loop to:</p>\n<pre><code>def get_triplet():\n for c in range(2, 1000):\n a = 1000 - c - 1\n for b in range(1, c):\n a -= 1\n</code></pre>\n<h1>cut down on for loop size</h1>\n<p>You obviously can’t have a Pythagorean triple such that <span class=\"math-container\">\\$b=c\\$</span>, so you may simplify the first for loop to:</p>\n<pre><code>for c in range(2, 1000):\n</code></pre>\n<h1>return</h1>\n<p>First, you may consider printing directly from the function <code>get_triplets</code> cut down on one call of <code>return</code>. This is not good practice unless you are trying to optimize at all costs.</p>\n<p>However, your return may be better suited using <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f strings</code></a>, which are faster and newer (f for fast). Perhaps you could also not suddenly rename <code>a</code>,<code>b</code>,<code>c</code> to <code>n1</code>,<code>n2</code>,<code>n3</code>:</p>\n<pre><code>return f'a = {a}, b = {b}, c = {c}, product = {a*b*c}'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T08:44:51.233",
"Id": "434687",
"Score": "1",
"body": "I would also suggest not to suddenly rename _a_,_b_ and _c_ to _n1_,_n2_ and _n3_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T14:54:01.583",
"Id": "434728",
"Score": "0",
"body": "The way you modify the use of `a` does not seem simpler but rather more complicated. Now I have to look at two lines to understand what `a` is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T14:55:32.970",
"Id": "434729",
"Score": "2",
"body": "Furthermore, I don't see how printing from within `get_triplets` cuts down on a function call, and printing from within a function that finds this kind of data is generally not recommend and at the very least would require renaming the function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:23:01.873",
"Id": "434733",
"Score": "0",
"body": "@DreamConspiracy when we simplify a as shown above, the computer performs far fewer subtraction operations. Moreover, the author does not have to print from the function. It would be more reasonable for readability to return and then print, but if they print directly from the function, it eliminates one call of return"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:25:14.383",
"Id": "434734",
"Score": "0",
"body": "@dfhwze, that’s a good point. It’s been noted and added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:21:30.513",
"Id": "434757",
"Score": "1",
"body": "Your calculations seem off. If `c` is 2, `a` becomes 998, and then `b` starts at 2. Now `a+b+c = 1002`. As b increase, `c` decreases, maintaining 1002."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T23:19:01.963",
"Id": "434786",
"Score": "0",
"body": "@AJNeufeld. Correct, I assumed the author had his math straight. Thanks"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T05:23:06.713",
"Id": "224133",
"ParentId": "224132",
"Score": "5"
}
},
{
"body": "<p>Instead of returning a custom string, just return the values and leave the printing to the caller. This way it is at least feasible for this function to be used elsewhere.</p>\n\n<pre><code>def get_triplet():\n ...\n return a, b, c\n\nif __name__ == '__main__':\n a, b, c = get_triplet()\n print(f\"a = {a}, b = {b}, c = {c}, product = {a*b*c}\")\n</code></pre>\n\n<p>Here I also used an <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\"><code>f-string</code></a> (Python 3.6+) to make the formatting easier.</p>\n\n<p>You should also have a look at Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which recommends using a consistent number of spaces (preferably 4) as indentation. Your <code>return</code> line does not follow this practice. In addition, functions (and classes) should have only two newlines separating them.</p>\n\n<p>You should also think about adding a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a> to describe what the function does. The name <code>get_triplet</code> does not convey all the information (e.g. that they need to sum to a target value).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:56:58.747",
"Id": "224141",
"ParentId": "224132",
"Score": "8"
}
},
{
"body": "<p>Note that your code actually gives the wrong answer, it returns <code>a > b</code>.\nSince a and b are the two smaller variables, you should actually start looping over them in order, so it looks more like:</p>\n\n<pre><code>for a in range(1, 1000): # Don't know why you assumed a > 1 here\n for b in range(a + 1, 1000):\n c = 1000 - a - b\n</code></pre>\n\n<p>Also, it doesn't matter for this problem, but for future ones it's important to notice when you can break early to speed up loops:</p>\n\n<pre><code>c2 = a**2 + b**2\nif c2 == c ** 2:\n return a, b, c\nelif c2 > c ** 2:\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T12:30:05.810",
"Id": "434867",
"Score": "0",
"body": "Uhm, why is it better to loop starting from the smallest variable first? It seems to me that your version tests many more triples than OP's one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:35:47.490",
"Id": "434959",
"Score": "0",
"body": "@FedericoPoloni As I stated, OP's code actually gives the wrong result. The right triples, but in the wrong order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T02:21:23.907",
"Id": "434967",
"Score": "0",
"body": "@FedericoPoloni not to mention once you add the shortcut break in, my code does less checks than OPs, even if you include the shortcut with OPs method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T06:25:34.650",
"Id": "434987",
"Score": "0",
"body": "The wrong order seems irrelevant --- just rename `a` to `b` and vice versa. Also, you still haven't explained why in general it's a better idea to start looping from the smallest variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T22:37:09.883",
"Id": "435059",
"Score": "0",
"body": "@FedericoPoloni The smallest variable will go through the smallest number of iterations.\n\nIf a < c, you'd rather go through your outer loop a times than c times."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T12:09:35.303",
"Id": "224145",
"ParentId": "224132",
"Score": "11"
}
},
{
"body": "<h2>Search Space</h2>\n\n<p>Your search space is too large. Since <code>0 < a < b < c</code> and <code>a + b + c = 1000</code>, you can put hard limits on both <code>a</code> and <code>c</code>. The maximum <code>a</code> can be is <code>332</code>, since <code>333 + 334 + 335 > 1000</code>. Similarly, the minimum value <code>c</code> can be is <code>335</code>, since <code>332 + 333 + 334 < 1000</code>. As well, the maximum value <code>c</code> can have is <code>997</code> (<code>1 + 2 + 997 = 1000</code>).</p>\n\n<p>Based on the above, if you wish your outside loop to loop over <code>c</code> values, your first loop should be:</p>\n\n<pre><code>for c in range(335, 997 + 1):\n # ...\n</code></pre>\n\n<p>And the inner loop should be over <code>a</code> values:</p>\n\n<pre><code> for a in range(1, 332 + 1):\n b = 1000 - c - a\n # ...\n</code></pre>\n\n<p>But now that we’ve selected a <code>c</code> value, can tighten the limits on <code>a</code> even further. When <code>c</code> is <code>600</code>, then <code>a+b</code> must be <code>400</code>, and since <code>a < b</code> must hold, the maximum <code>a</code> can have is <code>400 / 2</code>. So:</p>\n\n<pre><code> for a in range(1, min(332, (1000 - c) // 2) + 1):\n b = 1000 - c - a\n # ...\n</code></pre>\n\n<p>Moreover, since we’ve selected a <code>c</code> value, we have established a maximum value for <code>b</code> as well, since <code>b < c</code> must hold. If <code>c</code> is <code>400</code>, then <code>b</code> can’t be larger than <code>399</code>, so <code>a</code> must be at least <code>1000 - 400 - 399 = 201</code>, establishing a lower limit for our inner loop:</p>\n\n<pre><code> for a in range(max(1, 1000 - c - (c - 1)), min(332, (1000 - c) // 2) + 1):\n b = 1000 - c - a\n # ...\n</code></pre>\n\n<h2>Geometry</h2>\n\n<p>As pointed out in a <a href=\"https://codereview.stackexchange.com/questions/224132/project-euler-problem-9-pythagorean-triplet/224164#comment434888_224164\">comment by @Peter Taylor</a> below, we can tighten the limits on <code>c</code> much further.</p>\n\n<p>First, triangles must be triangular. In every triangle, the length of any side must be less than the sum of the lengths of the other two sides. In particular, <span class=\"math-container\">\\$c < a + b\\$</span> must be true. Since <span class=\"math-container\">\\$a + b + c = 1000\\$</span>, we can conclude <span class=\"math-container\">\\$c < 1000 - c\\$</span>, or more simply, <span class=\"math-container\">\\$c < 500\\$</span>, establishing a much smaller upper limit.</p>\n\n<p>The smallest value <code>c</code> could obtain would be when <code>a</code> and <code>b</code> are at their largest. If we relax the conditions slightly, allowing <span class=\"math-container\">\\$a \\leq b\\$</span> and <span class=\"math-container\">\\$a, b, c, \\in \\Re\\$</span>; we have an isosceles right-angle triangle, <span class=\"math-container\">\\$a = b = c / \\sqrt 2\\$</span>. Then:</p>\n\n<p><span class=\"math-container\">\\$a + b + c = 1000\\$</span></p>\n\n<p><span class=\"math-container\">\\$c = 1000 \\sqrt 2 / (2 + \\sqrt 2) \\approx 414.2\\$</span></p>\n\n<p>giving us a larger lower limit.</p>\n\n<p>Thus, the range of the outer loop can be reduced to:</p>\n\n<pre><code>for c in range(413, 500):\n # ...\n</code></pre>\n\n<h2>Repeated Calculations</h2>\n\n<p>When searching for the Pythagorean triplet, you are calculating <code>c ** 2</code> each and every iteration of the inner loop. The value of <code>c</code> is constant during execution of the inner loop, so <code>c ** 2</code> is also constant. Since exponentiation is a relatively expensive operation, you should get a speed improvement by moving this calculation out of the inner loop:</p>\n\n<pre><code>for c in range(413, 500):\n c2 = c ** 2\n for a in range(max(1, 1000 - c - (c - 1)), min(332, (1000 - c) // 2) + 1):\n b = 1000 - c - a\n if a ** 2 + b ** 2 == c2:\n return a, b, c\n</code></pre>\n\n<p><code>1000 - c</code> is also repeated in the inner loop, so you could compute this outside the loop also; it should provide a slight performance improvement.</p>\n\n<hr>\n\n<p>See other answers for important PEP8, f-string, docstring, and return value improvements not duplicated here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T09:15:29.403",
"Id": "434847",
"Score": "2",
"body": "Since \"exponentiation is a relatively expensive operation\", wouldn't it be faster to also cache the squares in a first loop? There are a lot of repetitions at runtime of `a**2` and `b**2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T15:16:54.397",
"Id": "434885",
"Score": "0",
"body": "@OlivierGrégoire Don’t cache the squares in the first loop! That way leads to conditionals (`if not cached[n]: ...`) which will slow your whole code down more than you gain, and convolute your code. Cache the squares before the first loop. And don’t store the cached values in a dict; store them in a list (preferably an `array.array()`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T15:26:09.037",
"Id": "434888",
"Score": "1",
"body": "If you're going to analyse the ranges, you could also consider that at one extreme \\$a=1, b \\approx c \\approx 500\\$ and at the other extreme \\$a \\approx b \\approx c / \\sqrt 2\\$, so \\$c \\approx 1000 \\sqrt 2 / (2 + \\sqrt 2) \\approx 414\\$. Tidy that up a tiny bit and the range is greatly reduced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T15:46:40.657",
"Id": "434891",
"Score": "0",
"body": "@PeterTaylor Excellent points. I totally neglected to include \\$a^2 + b^2 = c^2\\$ in my range analysis. But due to the squares and/or right-triangle geometry, it greatly reduces the range limits of `c`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T16:16:09.320",
"Id": "434896",
"Score": "1",
"body": "@AJNeufeld Actually, I wrote \"in a first loop\", not \"in the first loop\". ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T19:38:47.830",
"Id": "434921",
"Score": "1",
"body": "3Blue1Brown has [a great video](https://youtu.be/QJYmyhnaaek) that includes techniques to reduce the search space to basically zero by directly generating the next triples from the previous one. I did something similar in [this answer](https://stackoverflow.com/a/8263898/992385) from 2011."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T17:12:20.763",
"Id": "224164",
"ParentId": "224132",
"Score": "17"
}
},
{
"body": "<p>If you want a solution that doesn't involve any coding, you can use the fact that Pythagorean triples <span class=\"math-container\">\\$a < b < c\\$</span> are of the form </p>\n\n<p><span class=\"math-container\">\\$a = 2pqr\\$</span></p>\n\n<p><span class=\"math-container\">\\$b = p(q^2 - r^2)\\$</span></p>\n\n<p><span class=\"math-container\">\\$c = p(q^2 + r^2)\\$</span></p>\n\n<p>or the same equations with <span class=\"math-container\">\\$a\\$</span> and <span class=\"math-container\">\\$b\\$</span> switched.</p>\n\n<p>Here <span class=\"math-container\">\\$p, q, r\\$</span> are positive integers, which are uniquely determined by the condition\n<span class=\"math-container\">\\$p = \\gcd(a, b, c)\\$</span>.</p>\n\n<p>This is known as Euclid's formula, a proof of which can be found in the <a href=\"https://en.wikipedia.org/wiki/Pythagorean_triple\" rel=\"nofollow noreferrer\">Wikipedia</a> article on Pythagorean triples. However, it may be more enlightening to prove this yourself, since all it requires is an understanding of the unique factorization of integers into products of powers of primes. The trick is to rewrite <span class=\"math-container\">\\$a^2+b^2=c^2\\$</span> as</p>\n\n<p><span class=\"math-container\">\\$a^2 = c^2-b^2 = (c+b)(c-b)\\$</span></p>\n\n<p>First suppose that <span class=\"math-container\">\\$\\gcd(a,b,c)=1\\$</span>. What are the possible common factors of <span class=\"math-container\">\\$c+b\\$</span> and <span class=\"math-container\">\\$c-b\\$</span>? Given that <span class=\"math-container\">\\$(c+b)(c-b) = a^2\\$</span> is a square, what does this imply?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T16:21:12.123",
"Id": "434897",
"Score": "0",
"body": "I might try doing another version that uses GCD, sounds cool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T09:17:35.997",
"Id": "434999",
"Score": "0",
"body": "Hi @Pieter, can you link to a source of these statements? Or show the derivation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T18:25:14.227",
"Id": "435036",
"Score": "0",
"body": "@RobAu I've edited my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T19:03:04.497",
"Id": "435039",
"Score": "0",
"body": "Thanks, this is really helpful"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T16:03:47.430",
"Id": "224225",
"ParentId": "224132",
"Score": "7"
}
},
{
"body": "<h1>Solution 1</h1>\n\n<p>You have two equations and three unknowns. Since three minus two is one, you should only require one search loop.</p>\n\n<p>a + b + c = 1000<br>\n=> c = 1000 - a - b</p>\n\n<p>a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup><br>\n=> a<sup>2</sup> + b<sup>2</sup> = (1000 - a - b)<sup>2</sup>\n=> a<sup>2</sup> + b<sup>2</sup> = 1000<sup>2</sup> - 2000a - 2000b + 2ab + a<sup>2</sup> + b<sup>2</sup><br>\n=> 0 = 1000000 - 2000a - 2000b + 2ab<br>\n=> 0 = 500000 - 1000a - 1000b + ab<br>\n=> 1000b - ab = 500000 - 1000a<br>\n=> (1000 - a)b = 1000(500 - a)<br>\n=> b = 1000(500 - a)/(1000 - a)<br></p>\n\n<p>We can now try various values of a in a loop and solve for b and c relative to a. These solutions will all fulfill a + b + c = 1000 and a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>. We just need to limit the actual solution to integral values of b (which will guarantee integral values of a and c because of the first equation), and stop the search once a >= b (which will guarantee a < b < c).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>S = 1000\n\na = 1\nwhile True:\n b = S * (S - 2 * a) / (2 * S - 2 * a)\n if a >= b:\n break\n elif b.is_integer():\n b = int(b)\n c = S - a - b\n\n print 'a = %s, b = %s, c = %s, a * b * c = %s' % (a, b, c, a * b * c)\n\n return a * b * c\n a += 1\n</code></pre>\n\n<h1>Solution 2</h1>\n\n<p>Using Euclid's Formula from Wikipedia, we can drastically reduce this search. Euclid's Formula tells us that:</p>\n\n<p>a = (m<sup>2</sup> - n<sup>2</sup>)/2<br>\nb = mn<br>\nc = (m<sup>2</sup> + n<sup>2</sup>)/2</p>\n\n<p>First we can constrain these to solutions that meet our requirements.</p>\n\n<p>a + b + c = 1000\n=> (m<sup>2</sup> - n<sup>2</sup>)/2 + mn + (m<sup>2</sup> + n<sup>2</sup>)/2 = 1000<br>\n=> m<sup>2</sup> + mn = 1000<br>\n=> mn = 1000 - m<sup>2</sup><br>\n=> n = 1000/m - m</p>\n\n<p>Plugging that back into the equations above, we get the following:</p>\n\n<p>a = (m<sup>2</sup> - n<sup>2</sup>)/2<br>\n=> a = (m<sup>2</sup> - (1000<sup>2</sup>/m<sup>2</sup> - 1000 - 1000 + m<sup>2</sup>))/2<br>\n=> a = (2000 - 1000000/m<sup>2</sup>)/2<br>\n=> a = 1000 - 500000/m<sup>2</sup></p>\n\n<p>b = mn<br>\n=> b = m(1000/m - m)<br>\n=> b = 1000 - m<sup>2</sup></p>\n\n<p>c = (m<sup>2</sup> + n<sup>2</sup>)/2<br>\n=> c = (m<sup>2</sup> + (1000<sup>2</sup>/m<sup>2</sup> - 1000 - 1000 + m<sup>2</sup>))/2<br>\n=> c = (2m<sup>2</sup> + 1000000/m<sup>2</sup> - 2000)/2<br>\n=> c = m<sup>2</sup> + 500000/m<sup>2</sup> - 1000</p>\n\n<p>Further, we can constrain the search to 0 < a < c.</p>\n\n<p>0 < a<br>\n=> 0 < 1000 - 500000/m<sup>2</sup><br>\n=> 500000/m<sup>2</sup> < 1000<br>\n=> 500000 < 1000m<sup>2</sup><br>\n=> 500 < m<sup>2</sup><br>\n=> sqrt(500) < m<br>\n=> 22.36068 < m</p>\n\n<p>a < c<br>\n=> 1000 - 500000/m<sup>2</sup> < m<sup>2</sup> + 500000/m<sup>2</sup> - 1000<br>\n=> 2000 < m<sup>2</sup> + 1000000/m<sup>2</sup><br>\n=> 2000m<sup>2</sup> < m<sup>4</sup> + 1000000<br>\n=> 0 < m<sup>4</sup> - 2000m<sup>2</sup> + 1000000<br>\n=> Quadradtic formula for m<sup>2</sup>, A=1, B=-2000, C=1000000<br>\n=> m<sup>2</sup> < (-(-2000) +/- sqrt((-2000)<sup>2</sup> - 4 * 1 * 1000000)) / (2 * 1)<br>\n=> m<sup>2</sup> < (2000 +/- sqrt(4000000 - 4000000)) / 2<br>\n=> m<sup>2</sup> < 2000 / 2<br>\n=> m<sup>2</sup> < 1000<br>\n=> m < sqrt(1000)<br>\n=> m < 31.62278</p>\n\n<p>So that means we only need to test integer values of m 23 to 31 (up to nine cases).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>S = 1000\n\nfor m in range(math.ceil(math.sqrt(S / 2)),\n math.floor(math.sqrt(S) + 1)):\n a = S - S ** 2 / (2 * m ** 2)\n if a.is_integer():\n a = int(a)\n b = S - m ** 2\n c = S - a - b\n\n print('a = %s, b = %s, c = %s, a * b * c = %s' %\n (min(a, b), max(a, b), c, a * b * c))\n\n return a * b * c\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T17:09:35.483",
"Id": "435029",
"Score": "0",
"body": "Great algorithmic answer. Consider changing the print to f strings or printing from the caller. What is the computational complexity of both algorithms you showed us?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T17:42:04.477",
"Id": "435032",
"Score": "1",
"body": "Thanks! If we say we're looking for a sum of S=1000, the first solution is O(S) and the second solution is O(sqrt(S)). And yeah, I'm not a fan of the print either and mostly just had it for debug purposes. I think the original question really only requires returning the product, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T17:47:06.560",
"Id": "435034",
"Score": "2",
"body": "m^2+mn = 1000 can be factored to m(m+n) = 1000, so m is a factor of 1000. So now we're looking for factors of 1000 between 23 and 26."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T17:58:00.557",
"Id": "435035",
"Score": "0",
"body": "That's an awesome point! Is there an algorithm for finding a factor within a range that doesn't require trying all values in that range? (Also note that the value of 26 was incorrect, and I updated my answer with the real upper limit of 31. Obviously it works for 1000, where the answer occurs at m=25, but for other values of S, like 90, it would not have always worked out.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-18T14:15:23.867",
"Id": "435338",
"Score": "1",
"body": "Euclid's formula actually includes a common factor, which is important. In this case, you can find values of m and n for which the common factor is 1 (although this isn't the least common factor), but for a Pythagorean triple like 9, 12, 15, there is no solution in integers of the form (m^2-n^2)/2, m*n, (m^2+n^2)/2, since 2*15 = 30 can't be written as the sum of two squares."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T21:34:59.620",
"Id": "224250",
"ParentId": "224132",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T03:36:36.567",
"Id": "224132",
"Score": "15",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler, problem # 9, Pythagorean triplet"
} | 224132 |
<p>I have written Pycharm plugin for integrating pycharm with <a href="https://github.com/pyflyby/pyflyby" rel="nofollow noreferrer">tidyimports</a>. I have followed steps mentioned in <a href="http://www.jetbrains.org/intellij/sdk/docs/tutorials/build_system/prerequisites.html#running-a-simple-gradle-based-intellij-platform-plugin" rel="nofollow noreferrer">Simple Pycharm Plugin Example</a>. </p>
<p>Below is the code that I have written, it works but I need this to be reviewed.</p>
<p>1.Tidy Import</p>
<pre><code>import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TidyImportAction extends AnAction
{
@Override
public void actionPerformed(AnActionEvent e)
{
Document document = e.getData(LangDataKeys.EDITOR).getDocument();
String source_code = document.getText();
source_code = source_code.replace("\"","\\\"");
String[] cmd = {
"/bin/sh",
"-c",
String.format("echo \"%s\" | tidy-imports", source_code)
};
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
String modified_source_code = "";
String pyflyby_output = "";
String s = "";
while ((s = stdInput.readLine()) != null) {
if (s.startsWith("[PYFLYBY]")){
if (s != null)
pyflyby_output += s + "\n";
} else {
if (s != null)
modified_source_code += s + "\n";
}
}
while ((s = stdError.readLine()) != null) {
if (s.startsWith("[PYFLYBY]")){
if (s != null)
pyflyby_output += s;
} else {
if (s != null)
modified_source_code += s;
}
}
Application application = ApplicationManager.getApplication();
String finalModified_source_code = modified_source_code;
application.runWriteAction(() -> {
document.setText(finalModified_source_code);
});
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
</code></pre>
<p>2.Hot Import</p>
<pre><code>import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.*;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.PyExpressionStatement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.uast.values.UBooleanConstant;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.jetbrains.python.*;
public class HotImportsAction extends AnAction {
Boolean hotimports_enabled = false;
public HotImportsAction() {
super("Enable HotImports");
System.out.println("Registering file watch");
// VirtualFileManager
VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileListener() {
@Override
public void contentsChanged(VirtualFileEvent event) {
VirtualFile virtual_file = event.getFile();
System.out.println("contentsChanged: " + virtual_file.toString());
if (virtual_file.toString().endsWith(".py") != true) {
return;
}
System.out.println("hotimports_enabled = " + hotimports_enabled.toString());
// do something
if (hotimports_enabled == true) {
System.out.println("File Changed: " + virtual_file.toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
String file_path = event.getFile().getPath();
run_tidyimports(file_path);
virtual_file.refresh(false, false);
}
}
});
}
public void actionPerformed(AnActionEvent event) {
Presentation presentation = event.getPresentation();
if (hotimports_enabled == true) {
presentation.setText("Enable HotImports");
hotimports_enabled = false;
} else {
run_tidyimports(event.getData(PlatformDataKeys.VIRTUAL_FILE).getPath());
presentation.setText("Disable HotImports");
hotimports_enabled = true;
}
PsiFile psi_file = event.getData(LangDataKeys.PSI_FILE);
// print_expressions(psi_file);
VirtualFile vFile = event.getData(PlatformDataKeys.VIRTUAL_FILE);
vFile.refresh(false, false);
}
public void print_expressions(PsiFile psi_file) {
ArrayList<String> knownExprs = new ArrayList<String>();
if (psi_file != null) {
psi_file.accept(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(PsiElement element) {
// System.out.println("PsiElement: " + element.toString());
if (element instanceof PyExpressionStatement) {
System.out.println("PyExpressionStatemt: " + element.toString() + " " + element.getText());
knownExprs.add(element.getText());
}
super.visitElement(element);
}
});
}
System.out.println("knownExpr: " + knownExprs.toString());
}
public static void run_tidyimports(String filePath) {
System.out.println("Running tidy-imports on " + filePath);
if (filePath == null || !filePath.endsWith(".py")) {
return;
}
String s = null;
try {
Process p = Runtime.getRuntime().exec("tidy-imports -r " + filePath);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
catch (Exception e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T10:42:24.170",
"Id": "457503",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<h1>General</h1>\n\n<p>In idiomatic Java, open curly braces belong on the same line, not a newline.</p>\n\n<p>In idiomatic Java, variable names use camelCase. Underscores are only used when naming constants.</p>\n\n<p>Classes not designed for extension should be marked as <code>final</code>. Variables that will not be reassigned should be marked as <code>final</code>. This clarifies the design intent of the author and makes it easier to read the code, because you have a compiler-enforced guarantee against change/extension.</p>\n\n<p>Curly braces should always be used, even when they're optional. They make it easier to read the code and harder to introduce bugs when modifying the code later.</p>\n\n<p>If you haven't read the excellent JavaWorld article on <code>Runtime.exec()</code>, you should. <a href=\"https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html\" rel=\"nofollow noreferrer\">https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html</a></p>\n\n<p>You may also consider using <code>ProcessBuilder</code>. It's a little easier to read and is more flexible. <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html</a></p>\n\n<p>If IntelliJ has some framework for logging, that may be preferable to writing directly to <code>System.out</code> and <code>System.err</code> (with <code>e.printStackTrace()</code>). This is doubly true if, as it appears, your <code>System.out</code> calls are intended for debugging purposes.</p>\n\n<h1>TidyImportAction</h1>\n\n<p>You should probably add a no-arg constructor so you can specify the action name.</p>\n\n<p><code>pyflyby_output</code> is built, but never used. As is, it should be removed.</p>\n\n<p><code>p</code> is a poor name for a variable. <code>process</code> would be better.</p>\n\n<p><code>p</code> can be defined inside the <code>try</code> block.</p>\n\n<p>Your <code>null</code> checks do nothing. If <code>s</code> was null, you'd break out of the <code>while</code> loop. If you somehow got past that, you'd get a <code>NullPointerException</code> when checking if it started with <code>[PYFLYBY]</code>.</p>\n\n<p>Modifying a <code>String</code> is expensive. Use the mutable <code>StringBuilder</code> instead. The compiler is probably doing this for you behind the scenes.</p>\n\n<p>There's no value to <code>finalModified_source_code</code>. Just use the <code>String</code> value.</p>\n\n<h1>HotImportsAction</h1>\n\n<p><code>hotimports_enabled</code> is a <code>Boolean</code> (object), but can never be null. You should prefer <code>boolean</code> (primitive). It's slightly more efficient, and also makes it clear that it cannot ever be null.</p>\n\n<p><code>hotimports_enabled</code> should be <code>private</code>, as it's not intended to be available outside <code>HotImportsAction</code>.</p>\n\n<p>Don't explicitly compare boolean values to <code>true</code> and <code>false</code>. Just use <code>if (whatever)</code>, not <code>if (whatever == true)</code>.</p>\n\n<p>Delete commented-out code. All of your non-code comments are really just visual noise and can also be removed.</p>\n\n<p>Guard clauses make your code less indented in general, and thus easier to read.</p>\n\n<p><code>actionPerformed</code> should be annotated with <code>@Override</code>.</p>\n\n<p><code>psi_file</code> is unused and should be removed. Likewise <code>print_expressions</code>.</p>\n\n<p>Catch the most specific exception you can. In particular, catch <code>IOException</code> instead of <code>Exception</code>.</p>\n\n<p><hr/>\nIf you were to make all of these changes, your code might look more like:</p>\n\n<pre><code>public final class TidyImportAction extends AnAction {\n\n public TidyImportAction() {\n super(\"Tidy Import\");\n }\n\n @Override\n public void actionPerformed(final AnActionEvent event) {\n final Document document = event.getData(LangDataKeys.EDITOR).getDocument();\n final String sourceCode = document.getText().replace(\"\\\"\",\"\\\\\\\"\");\n final String[] cmd = {\n \"/bin/sh\",\n \"-c\",\n String.format(\"echo \\\"%s\\\" | tidy-imports\", sourceCode)\n };\n\n try {\n final Process process = Runtime.getRuntime().exec(cmd);\n final BufferedReader standardInput = new BufferedReader(new InputStreamReader(process.getInputStream()));\n final BufferedReader standardError = new BufferedReader(new InputStreamReader(process.getErrorStream()));\n final StringBuilder modifiedSourceCode = new StringBuilder();\n\n String s = \"\";\n while ((s = standardInput.readLine()) != null) {\n if (!s.startsWith(\"[PYFLYBY]\")) {\n modifiedSourceCode.append(s).append(\"\\n\");\n }\n }\n\n while ((s = standardError.readLine()) != null) {\n if (!s.startsWith(\"[PYFLYBY]\")) {\n modifiedSourceCode.append(s);\n }\n }\n\n ApplicationManager.getApplication().runWriteAction(() -> {\n document.setText(modifiedSourceCode.toString());\n });\n\n\n } catch (final IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public final class HotImportsAction extends AnAction {\n\n private boolean hotImportsEnabled = false;\n\n public HotImportsAction() {\n super(\"Enable HotImports\");\n System.out.println(\"Registering file watch\");\n\n VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileListener() {\n @Override\n public void contentsChanged(final VirtualFileEvent event) {\n final VirtualFile virtualFile = event.getFile();\n System.out.println(\"contentsChanged: \" + virtualFile.toString());\n\n if (!virtualFile.toString().endsWith(\".py\")) {\n return;\n }\n\n System.out.println(\"hotImportsEnabled = \" + hotImportsEnabled);\n if (!hotImportsEnabled) {\n return;\n }\n\n System.out.println(\"File Changed: \" + virtualFile.toString());\n\n final DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n System.out.println(dateFormat.format(new Date()));\n\n final String filePath = event.getFile().getPath();\n\n runTidyImports(filePath);\n virtualFile.refresh(false, false);\n }\n });\n }\n\n @Override\n public void actionPerformed(final AnActionEvent event) {\n final Presentation presentation = event.getPresentation();\n if (hotImportsEnabled) {\n presentation.setText(\"Enable HotImports\");\n } else {\n runTidyImports(event.getData(PlatformDataKeys.VIRTUAL_FILE).getPath());\n presentation.setText(\"Disable HotImports\");\n }\n hotImportsEnabled = !hotImportsEnabled;\n\n event.getData(PlatformDataKeys.VIRTUAL_FILE).refresh(false, false);\n }\n\n public static void runTidyImports(final String filePath) {\n System.out.println(\"Running tidy-imports on \" + filePath);\n if (filePath == null || !filePath.endsWith(\".py\")) {\n return;\n }\n try {\n final Process p = Runtime.getRuntime().exec(\"tidy-imports -r \" + filePath);\n final BufferedReader standardInput = new BufferedReader(new InputStreamReader(p.getInputStream()));\n final BufferedReader standardError = new BufferedReader(new InputStreamReader(p.getErrorStream()));\n\n System.out.println(\"Here is the standard output of the command:\\n\");\n String s = null;\n while ((s = standardInput.readLine()) != null) {\n System.out.println(s);\n }\n System.out.println(\"Here is the standard error of the command (if any):\\n\");\n while ((s = standardError.readLine()) != null) {\n System.out.println(s);\n }\n } catch (final IOException e) {\n System.out.println(\"exception happened - here's what I know: \");\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T15:37:03.400",
"Id": "224223",
"ParentId": "224136",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T06:12:43.550",
"Id": "224136",
"Score": "4",
"Tags": [
"python",
"java",
"gradle"
],
"Title": "Pycharm plugin for imports cleaning"
} | 224136 |
<p>I have done some code-refactoring of <a href="https://codereview.stackexchange.com/questions/214390/my-blackjack-game-in-c-console">my console-based BlackJack in C#</a>. Finally found a better solution to solve Ace problems (double Aces should be value 22 and third Ace should be value 1).</p>
<p>I still find it hard to split the UI and the program logic although I have created a static Screen class for that. Secondly, I still can't figure out the purpose or need of having Hand class as suggested by some. Appreciate some code review in regards to design pattern or further code-refactoring of this version of my BlackJack. </p>
<p><strong>Links</strong></p>
<ul>
<li><a href="https://github.com/ngaisteve1/BlackJack" rel="nofollow noreferrer">Github repository</a></li>
<li><a href="https://youtu.be/PRRgxxvRnro" rel="nofollow noreferrer">Sample output of the program</a></li>
</ul>
<p><strong>Card class</strong></p>
<pre><code>using System;
using System.Collections.Generic;
public enum Suit
{
Diamonds, Clubs, Hearts, Spades
}
public enum Face
{
Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King
}
public class Card
{
public Suit Suit { get; }
public Face Face { get; }
public string FaceName { get; }
// set value is for Ace because Ace can have value 1 or 11.
public int Value { get; set; }
public char Symbol { get; }
public ConsoleColor CardColor { get; set; }
/// Initialize Value and Suit Symbol
public Card(Suit suit, Face face)
{
Suit = suit;
Face = face;
switch (Suit)
{
case Suit.Clubs:
Symbol = '♣';
CardColor = ConsoleColor.White;
break;
case Suit.Spades:
Symbol = '♠';
CardColor = ConsoleColor.White;
break;
case Suit.Diamonds:
Symbol = '♦';
CardColor = ConsoleColor.Red;
break;
case Suit.Hearts:
Symbol = '♥';
CardColor = ConsoleColor.Red;
break;
}
switch (Face)
{
case Face.Ten:
Value = 10;
FaceName = "10";
break;
case Face.Jack:
Value = 10;
FaceName = "J";
break;
case Face.Queen:
Value = 10;
FaceName = "Q";
break;
case Face.King:
Value = 10;
FaceName = "K";
break;
case Face.Ace:
Value = 11;
FaceName = "A";
break;
default:
Value = (int)face + 1;
FaceName = Value.ToString();
break;
}
}
public void PrintCardColor()
{
Utility.WriteLineInColor($"{this.Symbol}{this.FaceName}", this.CardColor);
}
public void PrintCard(Card _card)
{
Console.Write($"Drawn card is ");
Utility.WriteLineInColor($"{_card.Symbol}{_card.FaceName}", _card.CardColor);
}
}
</code></pre>
<p><strong>Deck class</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
public class Deck
{
// Field
private List<Card> deck;
public Deck()
{
/// Contruct a deck of 52 cards.
deck = new List<Card>(52);
InitializeColdDeck();
Shuffle();
Screen.PrintShufflingDeck();
}
private void InitializeColdDeck()
{
var suitAsList = Enum.GetValues(typeof(Suit)).Cast<Suit>().ToArray();
// Alternate way is below by LINQ. Functional programming.
// This way more concise and less prone to have error.
deck = suitAsList
.SelectMany(
suit => Enumerable.Range(0, 12),
(suit, rank) => new Card((Suit)suit, (Face)rank))
.ToList();
// Alternate way is below by using 2 for loops:
// This way seems more readable but prone to have error.
// for (int j = 0; j < 4; j++)
// for (int i = 0; i < 13; i++)
// deck.Add(new Card((Suit)j, (Face)i));
}
// Pick top card and remove it from the deck.
// Return: The top card of the deck
public Card DrawCard(Player person, bool test = false)
{
Card card;
if (test)
{
card = new Card(Suit.Clubs, Face.Ace);
}
else
{
card = deck[0];
}
if (person.GetHandValue() + card.Value == 21 && person.Hand.Count == 1)
// Check natural black jack immediately after received first 2 cards.
person.IsNaturalBlackJack = true;
else if (person.GetHandValue() + card.Value > 21 && card.Face == Face.Ace)
// person hand count is not used here because it could be double Aces in first two cards.
// only the first Aces is counted as 11 while the subsequent Aces will be 1
// if hand value is more than 21
card.Value = 1;
person.Hand.Add(card);
deck.Remove(card);
return card;
}
/// Randomize the order of the cards in the Deck using Fisher–Yates shuffle algorithm.
private void Shuffle()
{
Random rng = new Random();
int n = deck.Count;
// Each loop find a random card to insert into new card list object.
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
Card card = deck[k];
deck[k] = deck[n];
deck[n] = card;
}
}
public void ShowRemainingDeckCount()
{
Console.WriteLine("\nRemaining cards in the deck: " + GetRemainingDeckCount());
}
public int GetRemainingDeckCount()
{
return deck.Count;
}
}
</code></pre>
<p><strong>Player class</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Threading;
// This player class is designed specifically for BlackJack game
// Some property for Player is only for BlackJack game
public class Player
{
public string Name { get; set; }
public List<Card> Hand { get; set; }
public bool IsNaturalBlackJack { get; set; }
public bool IsBusted { get; set; } = false;
public int TotalWins { get; set; } = 0;
public static int TotalWinsCounter { get; private set; } = 0;
public int ChipsOnHand { get; set; } = 500;
public int ChipsOnBet { get; set; }
public bool Turn { get; set; } = true;
public Player(string Name = "Dealer")
{
this.Name = Name;
Hand = new List<Card>(5);
}
public int GetHandValue()
{
int value = 0;
foreach (Card card in Hand)
value += card.Value;
return value;
}
public void ShowHandValue()
{
Console.WriteLine($"{this.Name}'s hand value is: {this.GetHandValue()} ({this.Hand.Count} cards)");
}
public void ShowUpCards(bool isDealer = false)
{
Console.WriteLine($"\n{this.Name}'s hand has:");
if (isDealer)
{
Utility.WriteLineInColor($"{this.Hand[0].Symbol}{this.Hand[0].FaceName}", this.Hand[0].CardColor);
Utility.WriteLineInColor("<Hole Card>", ConsoleColor.Magenta);
Console.WriteLine($"{this.Name}'s Hand value is: {this.Hand[0].Value}");
}
else
{
foreach (var card in this.Hand)
card.PrintCardColor();
ShowHandValue();
}
}
public void AddWinCount()
{
this.TotalWins = ++TotalWinsCounter;
}
public void Hit(Deck deck)
{
Console.Write($"{this.Name} hits. ");
Utility.Sleep();
// Take a card from the deck and put into player's Hand.
//Card card = new Card(Suit.Hearts, Face.Ace); //deck.DrawCard();
Card card = deck.DrawCard(this);
// If there is any Ace in the Hand, change all the Ace's value to 1.
// if (this.GetHandValue() + card.Value > 21 && card.Face == Face.Ace)
// card.Value = 1;
//Hand.Add(card); // Background
card.PrintCardColor(); // UI
Utility.Sleep();
}
public void Stand()
{
Console.WriteLine($"{this.Name} stands."); // UI
Utility.Sleep();
this.ShowUpCards(); // UI
Utility.Sleep();
this.Turn = false;
}
public bool CanPlayerStand(bool isPlayerBusted)
{
// Player can stand without condition
if (!this.Name.Equals("Dealer"))
return true;
else if (isPlayerBusted) // for dealer to auto stand if player busted
return true;
return false;
}
public void ResetPlayerHand()
{
this.Hand = new List<Card>(5);
this.IsNaturalBlackJack = false;
this.IsBusted = false;
}
}
</code></pre>
<p><strong>Screen class</strong></p>
<pre><code>using System;
public static class Screen
{
public static void SplashScreen()
{
Console.Write("Loading");
Utility.printDotAnimation(20);
Console.Clear();
Console.Title = "Steve C# Console-Based BlackJack Game (Version 2)";
Console.Write("Steve C# Console-Based BlackJack Game ");
Utility.WriteInColor(" ♠ ", ConsoleColor.White);
Utility.WriteInColor(" ♥ ", ConsoleColor.Red);
Utility.WriteInColor(" ♣ ", ConsoleColor.White);
Utility.WriteInColor(" ♦ ", ConsoleColor.Red);
}
public static void PromptPlayerName()
{
Console.Write("\n\nEnter player's name: ");
}
public static void PrintShufflingDeck()
{
Console.Write("Shuffling cold deck");
Utility.printDotAnimation();
}
}
</code></pre>
<p><strong>Utility class</strong></p>
<pre><code>using System;
using System.Threading;
class Utility
{
public static void WriteLineInColor(string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
public static void WriteInColor(string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.Write(text);
Console.ResetColor();
}
public static void Sleep(int miliseconds = 1500)
{
Thread.Sleep(miliseconds);
}
public static void printDotAnimation(int timer = 10)
{
for (var x = 0; x < timer; x++)
{
Console.Write(".");
Thread.Sleep(100);
}
Console.WriteLine();
}
public static void Line()
{
Console.WriteLine("\n--------------------------------------------------");
}
}
</code></pre>
<p><strong>BlackJackGame class</strong></p>
<pre><code>using System;
using System.Threading;
public class BlackJackGame
{
private Deck deck;
public void Play()
{
bool continuePlay = true;
Screen.SplashScreen();
Screen.PromptPlayerName();
var player = new Player(Console.ReadLine());
var dealerComputer = new Player();
deck = new Deck();
while (continuePlay)
{
// Initialize screen and reset player and dealer's certain property
// for the new round.
Console.Clear();
player.ResetPlayerHand();
dealerComputer.ResetPlayerHand();
// Create a new deck if remaining cards are less than 20
if (deck.GetRemainingDeckCount() < 20)
deck = new Deck();
deck.ShowRemainingDeckCount();
// Show player bank roll
Console.WriteLine($"{player.Name} Chips Balance: {player.ChipsOnHand}");
if (player.ChipsOnHand <= 10)
{
Utility.WriteLineInColor("Insufficient chips in your account.", ConsoleColor.Red);
Utility.WriteLineInColor("Please reload your chips from the counter to continue to play.\n", ConsoleColor.Red);
continuePlay = false;
break;
}
// Get bet amount from player
Console.Write("Enter chips: ");
player.ChipsOnBet = Convert.ToInt16(Console.ReadLine());
// for brevity, no input validation here.
// Deal first two cards to player (Background)
deck.DrawCard(player);
deck.DrawCard(player);
// Show player's hand (UI)
player.ShowUpCards();
Utility.Sleep();
Utility.Line();
// Deal first two cards to dealer (Background)
deck.DrawCard(dealerComputer);
deck.DrawCard(dealerComputer);
// Show dealer's hand (UI)
dealerComputer.ShowUpCards(true);
Utility.Sleep();
Utility.Line();
// Check natural black jack
if (CheckNaturalBlackJack(player, dealerComputer) == false)
{
// If both also don't have natural black jack,
// then player's turn to continue.
// After player's turn, it will be dealer's turn.
TakeAction(player);
TakeAction(dealerComputer, player.IsBusted);
AnnounceWinnerForTheRound(player, dealerComputer);
}
Console.WriteLine("This round is over.");
Console.Write("\nPlay again? Y or N? ");
continuePlay = Console.ReadLine().ToUpper() == "Y" ? true : false;
// for brevity, no input validation
}
PrintEndGame(player, dealerComputer);
}
private void TakeAction(Player currentPlayer, bool isPlayerBusted = false)
{
string opt = "";
currentPlayer.Turn = true;
Console.WriteLine($"\n{currentPlayer.Name}'s turn. ");
while (currentPlayer.Turn)
{
if (currentPlayer.Name.Equals("Dealer"))
{
Utility.Sleep(2000); // faking thinking time.
// Mini A.I for dealer.
if (isPlayerBusted) // if player bust, dealer can stand to win
// break; // Dealer is required to still reveal hole card even though the player bust
opt = "S";
else
opt = currentPlayer.GetHandValue() <= 16 ? "H" : "S";
}
else
{
// Prompt player to enter Hit or Stand.
Console.Write("Hit (H) or Stand (S): ");
opt = Console.ReadLine();
}
switch (opt.ToUpper())
{
case "H":
currentPlayer.Hit(deck);
currentPlayer.ShowHandValue();
break;
case "S":
//if (currentPlayer.CanPlayerStand(isPlayerBusted))
currentPlayer.Stand();
break;
default:
Console.WriteLine("Invalid command.");
break;
}
CheckPlayerCard(currentPlayer);
}
Console.WriteLine($"{currentPlayer.Name}'s turn is over.");
Utility.Line();
Utility.Sleep();
}
private void CheckPlayerCard(Player _currentPlayer)
{
// If current player is busted, turn is over.
if (_currentPlayer.GetHandValue() > 21)
{
Utility.WriteLineInColor("Bust!", ConsoleColor.Red);
Utility.Sleep();
_currentPlayer.IsBusted = true;
_currentPlayer.Turn = false;
}
// If current player total card in hand is 5, turn is over.
else if (_currentPlayer.Hand.Count == 5)
{
Console.WriteLine($"{_currentPlayer.Name} got 5 cards in hand already.");
Utility.Sleep();
_currentPlayer.Turn = false;
}
}
private bool CheckNaturalBlackJack(Player _player, Player _dealer)
{
Console.WriteLine();
if (_dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine("Player and Dealer got natural BlackJack. Tie Game!");
_dealer.ShowUpCards();
return true;
}
else if (_dealer.IsNaturalBlackJack && !_player.IsNaturalBlackJack)
{
Console.WriteLine($"{_dealer.Name} got natural BlackJack. {_dealer.Name} won!");
_dealer.ShowUpCards();
_player.ChipsOnHand -= (int)Math.Floor(_player.ChipsOnBet * 1.5);
return true;
}
else if (!_dealer.IsNaturalBlackJack && _player.IsNaturalBlackJack)
{
Console.WriteLine($"{_player.Name} got natural BlackJack. {_player.Name} won!");
_player.AddWinCount();
_player.ChipsOnHand += (int)Math.Floor(_player.ChipsOnBet * 1.5);
return true;
}
// guard block
return false;
}
private void AnnounceWinnerForTheRound(Player _player, Player _dealer)
{
Console.WriteLine();
if (!_dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine($"{_dealer.Name} won.");
_dealer.AddWinCount();
_player.ChipsOnHand -= _player.ChipsOnBet;
}
else if (_dealer.IsBusted && !_player.IsBusted)
{
Console.WriteLine($"{_player.Name} won.");
_player.AddWinCount();
_player.ChipsOnHand += _player.ChipsOnBet;
}
else if (_dealer.IsBusted && _player.IsBusted)
{
Console.WriteLine("Tie game.");
}
else if (!_dealer.IsBusted && !_player.IsBusted)
if (_player.GetHandValue() > _dealer.GetHandValue())
{
Console.WriteLine($"{_player.Name} won.");
_player.AddWinCount();
_player.ChipsOnHand += _player.ChipsOnBet;
}
else if (_player.GetHandValue() < _dealer.GetHandValue())
{
Console.WriteLine($"{_dealer.Name} won.");
_dealer.AddWinCount();
_player.ChipsOnHand -= _player.ChipsOnBet;
}
else if (_player.GetHandValue() == _dealer.GetHandValue())
Console.WriteLine("Tie game.");
}
private void PrintEndGame(Player player, Player dealerComputer)
{
Console.WriteLine($"{player.Name} won {player.TotalWins} times.");
Console.WriteLine($"{dealerComputer.Name} won {dealerComputer.TotalWins} times.");
Console.WriteLine("Game over. Thank you for playing.");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T08:47:12.750",
"Id": "434688",
"Score": "0",
"body": "Is this a follow-up on https://codereview.stackexchange.com/questions/214390/my-blackjack-game-in-c-console? If so, I would edit both questions to link to each other. Also take advantage of the opportunity to format your code correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:09:08.770",
"Id": "434696",
"Score": "0",
"body": "Yes, that is the initial version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T05:31:19.180",
"Id": "434816",
"Score": "2",
"body": "Please don't edit the question to incorporate the suggestions. See [What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T05:59:10.073",
"Id": "434820",
"Score": "0",
"body": "Oh okay sure. Okay, I made some changes as suggested and updated in my github link of the original post."
}
] | [
{
"body": "<p>Your two main issues have not been resolved.</p>\n\n<hr>\n\n<h2>Separation of Concerns</h2>\n\n<blockquote>\n <p><em>I still find it hard to split the UI and the program logic although I have created a static Screen class for that.</em></p>\n</blockquote>\n\n<p>Even though you have tried to offset UI operations to a dedicated class <code>Screen</code>, your code is still full of mixed concerns logic (<strong>presentation vs application vs test</strong>). </p>\n\n<ul>\n<li><code>Card</code> has properties <code>FaceName</code>, <code>Symbol</code> used only at presentation layer. They might serve a purpose as default string representation, regardless how they get presented to the end user.</li>\n<li><code>Card</code> stores <code>CardColor</code>, which is definitely presentation logic.</li>\n<li><code>Card</code> has presentation layer methods <code>PrintCardColor</code> and <code>PrintCard</code>. They have no place in the application layer. In addition, <code>PrintCard</code> should be either static or have no argument.</li>\n<li><code>Deck</code> contains a method <code>DrawCard</code> which takes an argument <code>test</code>. This mixes test flow with normal application flow.</li>\n<li><code>Deck</code> has method <code>ShowRemainingDeckCount</code> which is presentation logic.</li>\n<li><code>Player</code> is even worse than the other classes. Some methods mix application with presentation logic in the body. Split application logic from methods <code>Hit</code> and <code>Stand</code>. </li>\n<li><code>Player</code> contains methods <code>ShowHandValue</code> and <code>ShowUpCards</code> which are presentation logic.</li>\n<li><code>BlackJackGame</code> also mixes presentation and application logic in <code>Play</code> making it impossible to use this class in other UIs.</li>\n</ul>\n\n<hr>\n\n<h2>Object-Oriented Design</h2>\n\n<blockquote>\n <p><em>I still can't figure out the purpose or need of having Hand class as suggested by some.</em></p>\n</blockquote>\n\n<p>Your current implementation requires you to do tricks and store way too much information on your existing classes.</p>\n\n<ul>\n<li><code>Card</code>'s property <code>FaceName</code> could be an extension method on enum <code>Face</code>.</li>\n<li><code>Player</code> really needs to be split into several classes: <code>Player</code>, <code>Hand</code>, <code>Bet</code>. I will explain below.</li>\n<li><code>Hand</code> should also store properties <code>IsNaturalBlackJack</code>, <code>GetHandValue</code> and <code>ChipsOnHand</code>. </li>\n<li>I would also place betting logic <code>IsBusted</code>, <code>ChipsOnBet</code>, <code>Turn</code>, <code>Bit</code>, <code>Stand</code> in a separate class <code>Bet</code>.</li>\n<li><code>BlackJackGame</code> can be further divided into <code>Round</code>s and a <code>Dealer</code>.</li>\n</ul>\n\n<p>By not having a class <code>Hand</code> you are required to do a trick with <code>Value</code> in <code>Card</code>. This is hand logic, not card. A Hand should provide the value used in a bet. A card can still have its own value, but this value is not of importance in the game, only as internal logic for the hand to calculates its own value.</p>\n\n<blockquote>\n<pre><code>// set value is for Ace because Ace can have value 1 or 11.\npublic int Value { get; set; }\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:21:20.363",
"Id": "434699",
"Score": "0",
"body": "Thanks a lot for the code review. Okay, I will try split the 'big' class into smaller classes. For the the presentation layer, I still yet to find some good example on it. Do you have any example on splitting application layer and presentation layer? If it is a web application, I could use MVC pattern, but in console, I have yet to find any."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T10:24:38.990",
"Id": "434701",
"Score": "3",
"body": "The most important thing is to remove all UI logic from the application layer. You don't want any Console references in Player, Card, Deck. What you could do for a console app, is to make extension methods on your application classes for printing their properties to the Console. This approach has the least impact on your current design. Another option is to create custom presentation classes and use mapping from application to presentation classes. This might be overkill for a simple console application though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T09:48:52.207",
"Id": "224140",
"ParentId": "224139",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "224140",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T07:55:03.537",
"Id": "224139",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"game",
"console"
],
"Title": "Console-based BlackJack in C# - Follow-Up"
} | 224139 |
<p>First of all I just started learning OOP.</p>
<p>My priority is to make safe code. I think my code is safe, because I use GD to make a copy of the uploaded image and I use an image proxy to make sure nobody can access the uploaded file directly and it's uploaded outside of the webroot. But if I was 100% sure that it's safe I was not posting it here haha. I'm not sure about the way I check the MIME type, and about the GD.</p>
<p>I made some tests and it works fine, but what do you guys think? Any suggestions are welcome. Also if you have any questions about the code just ask me in the comments.</p>
<p>Class Img:</p>
<pre><code>class Img
{
private static $folder, $file, $ext, $w, $h;
public static function upload($file, $new_size){
self::$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
list(self::$w, self::$h) = ($size = getimagesize($file["tmp_name"]));
if(!$size || !in_array(self::$ext, ['png', 'jpeg', 'jpg']))die(json_encode(['error' => 'Invalid file']));
if(filesize($file["tmp_name"]) > 2700000)die(json_encode(['error' => 'File is too big']));
self::$folder = dirname(__DIR__).'/../../uploads/profile/'.$_SESSION['user_folder'];
self::$file = $file["tmp_name"];
$_SESSION['avatar'] = ($name = mt_rand(100, 100000).'-'.time().'.'.self::$ext);
self::resize_image($name, $new_size, $new_size);
$user_id = $_SESSION['user_id'];
$conn = \lib\Db::instance();
$query = $conn->query("UPDATE users SET avatar = '{$name}' WHERE user_id = '{$user_id}'");
$conn = NULL;
die(json_encode(['avatar' => $_SESSION['avatar']]));
}
private static function resize_image($name, $width, $height){
if(self::$ext === 'jpeg')self::$ext = 'jpg';
if(self::$ext === 'jpg')$img = imagecreatefromjpeg(self::$file);
elseif(self::$ext === 'png')$img = imagecreatefrompng(self::$file);
$ratio = max($width/self::$w, $height/self::$h);
$x = (self::$w - $width/$ratio)/2;
self::$h = $height/$ratio;
self::$w = $width/$ratio;
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if(self::$ext === "png"):
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
endif;
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, self::$w, self::$h);
if(self::$ext === 'jpg')imagejpeg($new, self::$folder.$name);
elseif(self::$ext === 'png')imagepng($new, self::$folder.$name);
imagedestroy($new);
}
}
</code></pre>
<p>avatar_upload.php:</p>
<pre><code>require_once dirname(__DIR__).'/../../vendor/autoload.php';
if(!isset($_SESSION))session_start();
if($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_SESSION['user_id']))die(header('HTTP/1.1 404 Not Found'));
if(!empty($_FILES['avatar']['size']))\lib\Img::upload($_FILES["avatar"], 150);
</code></pre>
| [] | [
{
"body": "<ul>\n<li>Fight the urge to squeeze multiple \"things\" into one line. Your script will be easier to read and maintain with all declarations and constructs occupying their own rightful place. Spend the extra lines, you'll be happy you did a year from now.</li>\n<li>Use curly braces to encapsulate language constructs (e.g. if-else and foreach, etc.), this combined with appropriate tabbing will make your script easier to read and help to prevent mishaps when expressing conditional outcomes. Start but don't stop reading about coding standards here: <a href=\"https://blog.sideci.com/5-php-coding-standards-you-will-love-and-how-to-use-them-adf6a4855696\" rel=\"nofollow noreferrer\">https://blog.sideci.com/5-php-coding-standards-you-will-love-and-how-to-use-them-adf6a4855696</a></li>\n<li>Instead of murdering your script with <code>die()</code> calls, return a consistent data type no matter the outcome. In the future, you may change how you want to display/deliver the results. Finally, convert your returned array to json and echo.</li>\n<li>When writing variables into a query, you should be using a prepared statement with placeholders and bound variables.</li>\n<li>Avoid single-use and unnecessary variable declarations. If you have <code>$_SESSION['avatar']</code> then you don't need to declare <code>$name</code>.</li>\n<li>Starting your session is not a conditional thing. Do it early and do it every time.</li>\n<li>You might like to ask yourself why you've elected to write static methods. This is a topic worth investing some research time into. Start, but don't stop here: <a href=\"https://stackoverflow.com/q/33705976/2943403\">When should I use static methods?</a></li>\n</ul>\n\n<p>There is more to tell you, but I have run out of time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T21:53:15.390",
"Id": "434938",
"Score": "0",
"body": "You said that i should use prepared statements but is it because of the variable `$ext`? I mean, the variable `$user_id` is from a column with `AUTO_INCREMENT`, and the `$name` is made with the function `mt_rand()`, so i don't see other reason to use prepared statements. I only use it when there's user input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T22:48:41.893",
"Id": "434946",
"Score": "0",
"body": "I can't see the code where `$_SESSION['user_id']` is generated. If it is at all insecure, then it becomes a potential attack vector for this script. If it may possibly contain characters that will monkeywrench your query, then it becomes a potential point of breakage. Regardless of how stable/secure you believe the SESSION data is, I recommend consistently using prepared statements to write variables into your queries. If the `$_SESSION['user_id']` is an integer (and you are not going to use a prepared statement) you could use explicit casting (`(int)$_SESSION['user_id']`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T00:43:14.860",
"Id": "434962",
"Score": "0",
"body": "in the php.ini i had set sessions to `httponly` and `secure`. The user id is generated in the database with `AUTO_INCREMENT`, so i think it's safe. But i have a question, do you trust the value from the variable `$ext`? I meant, not to check the MIME type, but to use it in the name of the file and in the sql (which i did), I made a check with the function `in_array`, but i don't know if it's enough to trust."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T12:08:44.593",
"Id": "224215",
"ParentId": "224150",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:03:33.687",
"Id": "224150",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"security",
"validation",
"image"
],
"Title": "Upload image with GD library"
} | 224150 |
<p>I wrote this simple code for evaluating the π using Monte Carlo method. This is the serial version:</p>
<pre><code>long double compute_pi_serial(const long interval) {
srand(time(NULL));
double x, y;
int i, circle = 0;
for (i = 0; i < interval; i ++) {
x = (double)(rand() / (double) RAND_MAX);
y = (double)(rand() / (double) RAND_MAX);
if (pow(x,2) + pow(y, 2) <= 1.0) circle ++;
}
return (long double) circle / interval * 4.0;
}
</code></pre>
<p>After, I wrote a parallel version using <code>OpenMP</code> and this is the result:</p>
<pre><code>long double compute_pi_omp(const long interval) {
double x, y;
int i, circle = 0;
#pragma omp parallel private(x, y) num_threads(omp_get_max_threads())
{
srand(SEED);
#pragma omp for reduction(+:circle)
for ( i = 0; i < interval; i++ ) {
x = (double)(rand() / (double) RAND_MAX);
y = (double)(rand() / (double) RAND_MAX);
if ( pow(x, 2) + pow(y, 2) <= 1 ) circle++;
}
}
return (long double) circle / interval * 4.0;
}
</code></pre>
<p>This is an efficient method or there is a most efficient version always using <code>OpenMP</code>? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:01:43.930",
"Id": "434767",
"Score": "0",
"body": "Are you asking whether the Monte Carlo approach is efficient or the implementation with OpenMP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T23:16:03.613",
"Id": "434785",
"Score": "0",
"body": "@Ninetails My implementation in OpenMp"
}
] | [
{
"body": "<p><strong>Correctness issues</strong></p>\n\n<p>Correctness merits priority over efficiency. Important to get a correct answer, not a fast and wrong one. </p>\n\n<ul>\n<li>Poor use of mixing types</li>\n</ul>\n\n<p><code>long interval</code>, and <code>int i</code> lead to <em>undefined behavior</em> (UB) when <code>interval > INT_MAX</code>. Use same type.</p>\n\n<ul>\n<li>Small range</li>\n</ul>\n\n<p><code>long</code> may use 32-bit. Easy enough to run in less than 1 minute and exceed 2<sup>31</sup> - limiting how far we can test this code. Use <code>long long</code> or, use <code>unsigned long long</code>.</p>\n\n<ul>\n<li>Off-by-1</li>\n</ul>\n\n<p>Using <code>/ (double) RAND_MAX</code> may impart a small bias. Yet given the <em>slow convergence</em> of the Monte Carlo PI, I doubt any serious miscalculation.</p>\n\n<p>I'd expect the random values to be in the middle of each random range:</p>\n\n<pre><code>[0.5, 1.5, 2.5, ... RAND_MAX - 1.5, RAND_MAX - 0.5, RAND_MAX + 0.5]/(RAND_MAX + 1u)\n</code></pre>\n\n<p>Code has then distributed differently:</p>\n\n<pre><code>[0.0, 1.0/RAND_MAX, 2.0/RAND_MAX, ... 1.0]\n</code></pre>\n\n<p>A more significant bias occurs when <code>(int)(double) RAND_MAX != RAND_MAX</code> - select platforms with more precision in <code>RAND_MAX</code> than <code>double</code>.</p>\n\n<p>Note: to convert <code>RAND_MAX</code> plus 1 to <code>double</code>, code can use <code>(RAND_MAX/2 + 1)*2.0</code>. Works well when <code>RAND_MAX</code> is a <a href=\"http://mathworld.wolfram.com/MersenneNumber.html\" rel=\"nofollow noreferrer\">Mersenne Number</a> or and odd value. This avoids losing precision that <code>(double)RAND_MAX + 1.0</code> may incur.</p>\n\n<hr>\n\n<p><strong>Efficiency</strong></p>\n\n<ul>\n<li><code>pow()</code> vs <code>x*x</code></li>\n</ul>\n\n<p>A weak compiler may use a laborious function call seeing <code>pow(x,2)</code> and not the certainly more efficient <code>x*x</code> replacement. Of course the right answer is to use a smart compiler. Still, profiling a direct coding of <code>x*x</code> may prove worth-wild.</p>\n\n<ul>\n<li><em>fp</em> vs. <em>integer</em> </li>\n</ul>\n\n<p>I'd even consider an integer only approach. Something like the below.</p>\n\n<pre><code>// int2x twice as wide as int\nint2x limit = (int2x) RAND_MAX * RAND_MAX;\n...\n int2x x = rand();\n int2x y = rand();\n if (x*x + y*y <= limit) circle++;\n</code></pre>\n\n<ul>\n<li><code>double</code> vs. <code>long double</code></li>\n</ul>\n\n<p>Seriously doubt any calculation run within a day will benefit using the higher precision <code>long double</code>.</p>\n\n<pre><code>// return (long double) circle / interval * 4.0;\nreturn circle / interval * 4.0;\n</code></pre>\n\n<ul>\n<li>No comment on OP's major goal: Serial vs OMP - sorry.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T04:32:21.803",
"Id": "224267",
"ParentId": "224152",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224267",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T13:29:29.493",
"Id": "224152",
"Score": "4",
"Tags": [
"c",
"comparative-review",
"numerical-methods",
"openmp"
],
"Title": "Evaluating π using Monte Carlo methods - Serial vs OMP"
} | 224152 |
<p>Consider a struct:</p>
<pre class="lang-rust prettyprint-override"><code>struct RawData{
pub a: HashMap<String, String>,
pub b: HashMap<String, String>,
}
</code></pre>
<p>which should be converted in a struct with more concrete members:</p>
<pre class="lang-rust prettyprint-override"><code>struct EncodedData{
pub a: HashMap<String, MyStruct>,
pub b: HashMap<String, MyStruct>,
}
</code></pre>
<p>and there is a function which tries to parse <code>String</code> into <code>MyStruct</code> returning <code>Result<MyStruct, String></code></p>
<p>Now I am not happy with the working solution I found and think there must be a better solution:</p>
<pre class="lang-rust prettyprint-override"><code>fn convert(raw_data: RawData) -> Result<EncodedData, String> {
let a: Result<HashMap<String, MyStruct>, String> = raw_data
.a
.iter()
.map(|(k, v)| {
let v = parse(v.clone())?;
Ok((k.clone(), v))
})
.collect();
let a = a?;
let b: Result<HashMap<String, MyStruct>, String> = raw_data
.b
.iter()
.map(|(k, v)| {
let v = parse(v.clone())?;
Ok((k.clone(), v))
})
.collect();
let b = b?;
Ok(EncodedData { a, b })
}
</code></pre>
<p>Here is a complete working example:</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
#[macro_use]
extern crate maplit;
struct MyStruct {
code: String,
}
struct RawData {
pub a: HashMap<String, String>,
pub b: HashMap<String, String>,
}
struct EncodedData {
pub a: HashMap<String, MyStruct>,
pub b: HashMap<String, MyStruct>,
}
fn parse(code: String) -> Result<MyStruct, String> {
Ok(MyStruct { code })
}
fn convert(raw_data: RawData) -> Result<EncodedData, String> {
let a: Result<HashMap<String, MyStruct>, String> = raw_data
.a
.iter()
.map(|(k, v)| {
let v = parse(v.clone())?;
Ok((k.clone(), v))
})
.collect();
let a = a?;
let b: Result<HashMap<String, MyStruct>, String> = raw_data
.b
.iter()
.map(|(k, v)| {
let v = parse(v.clone())?;
Ok((k.clone(), v))
})
.collect();
let b = b?;
Ok(EncodedData { a, b })
}
fn main() {
let raw = RawData {
a: hashmap! {"a".to_string() => "b".to_string()},
b: hashmap! {"c".to_string() => "d".to_string()},
};
let _ = convert(raw);
}
</code></pre>
<p>with additional dependency:
<code>maplit = "^1.0.1"</code></p>
<p>Here I don't like:
1. the need of clone, because <code>into_iter()</code> is not allowed.
1. the second <code>let a = a?;</code> because otherwise the compiler could not infer the type.</p>
<p>Cargo clippy seems to be happy with that code. Are you?</p>
| [] | [
{
"body": "<blockquote>\n <ol>\n <li>the need of clone, because into_iter() is not allowed</li>\n </ol>\n</blockquote>\n\n<p>Well, into_iter() is allowed, and you can just use that and then you don't need clone.</p>\n\n<blockquote>\n <ol>\n <li>the second let a = a?; because otherwise the compiler could not infer the type.</li>\n </ol>\n</blockquote>\n\n<p>Yeah, Rust doesn't handle inferring the error type when using ? very nicely. </p>\n\n<p>The best strategy I've found so far is to move these things into reusable generic functions. For example:</p>\n\n<pre><code>fn map_hash_values<K: std::cmp::Eq + std::hash::Hash, V1, V2, E>(\n data: HashMap<K, V1>,\n f: impl Fn(V1) -> Result<V2, E>,\n) -> Result<HashMap<K, V2>, E> {\n data.into_iter().map(|(k, v)| Ok((k, f(v)?))).collect()\n}\n\nfn convert(raw_data: RawData) -> Result<EncodedData, String> {\n Ok(EncodedData {\n a: map_hash_values(raw_data.a, parse)?,\n b: map_hash_values(raw_data.b, parse)?,\n })\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T19:17:37.643",
"Id": "224170",
"ParentId": "224157",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T15:50:35.653",
"Id": "224157",
"Score": "-1",
"Tags": [
"rust"
],
"Title": "Trying to convert struct with hashmap member"
} | 224157 |
<p>As a followup to <a href="https://codereview.stackexchange.com/questions/223641/python-script-to-rename-images-based-on-descriptions-in-a-text-file">this</a> question, I removed the <code>Repository</code> class and do the copy in the <code>Folder</code> class.</p>
<p>Suppose I have the following image directories under the Pictures directory of a Windows user profile:</p>
<pre><code>C:\Users\Kiska\Pictures\Computers
- comp-amd-21343.jpg
- 12345.jpg
C:\Users\Kiska\Pictures\Cars
- car-random.jpg
- 54321.jpg
</code></pre>
<p>In each of those directories, they're are two images each. Notice that the names aren't reflective of what the images depicts.</p>
<p>My script will take a source directory, rename the images based on the folder name and the order in which it was renamed, and move it to a destination directory.</p>
<p>So the above images would be renamed:</p>
<pre><code>computers_1.jpg
computers_2.jpg
cars_1.jpg
cars_2.jpg
</code></pre>
<p><strong>Source.txt</strong>: </p>
<pre><code>Computers
Cars
</code></pre>
<p><strong>Folder.py:</strong></p>
<pre><code>import os
import shutil
class Folder:
def __init__(self, directory: str):
self._check_if_str_parameters_are_empty(parameter=directory, error_message="Directory cannot be empty")
self._directory = directory.strip()
def _check_if_str_parameters_are_empty(self, parameter, error_message):
if not parameter:
raise ValueError(error_message)
@property
def name(self) -> str:
return self._directory
def get_lst_of_files(self) -> list:
return os.listdir(self._directory)
def copy_files_with(self, extension: str, to_location: "Folder"):
if self == to_location:
raise ValueError("Source and Destination cannot be the same")
if "." in extension:
raise ValueError("Extension is incorrect type")
lst_of_images_in_source = os.listdir(self._directory)
number_of_images_in_source = len(lst_of_images_in_source)
print(f"Number of images: {number_of_images_in_source}")
if number_of_images_in_source:
number_of_images_in_destination = len(to_location.get_lst_of_files()) + 1
for number, image in enumerate(lst_of_images_in_source, start=number_of_images_in_destination):
source_image = os.path.join(self._directory, image)
destination_image = os.path.join(to_location.name,
self._construct_destination_string(self._get_base_name(str_to_split=self._directory),
number, extension))
print(f"{source_image} will be renamed to {destination_image}")
shutil.move(source_image, destination_image)
else:
print("No images to rename")
def _get_base_name(self, str_to_split: str) -> str:
return str_to_split.split("\\")[-1]
def _construct_destination_string(self, image_name: str, current_number: str, extension: str) -> str:
return "{0}_{1}.{2}".format(image_name.lower().replace(" ", "_"), current_number, extension)
def __eq__(self, other):
if isinstance(other, Folder):
return (self._directory) == (other._directory)
return NotImplemented
def __hash__(self):
return hash(self._directory)
</code></pre>
<p><strong>Main.py:</strong></p>
<pre><code>import os
from Folder import Folder
def main():
source_txt = "source.txt"
source_pictures = "{0}\\{1}".format(os.getenv("USERPROFILE"), "Pictures")
destination_pictures = None
extension = "jpg"
try:
if not destination_pictures:
raise ValueError("Please provide a valid destination path.")
if os.path.getsize(source_txt):
if os.path.exists(source_txt) and os.path.exists(destination_pictures):
with open(source_txt) as folder_reader:
for folder in folder_reader:
source_folder = os.path.join(source_pictures, folder)
if os.path.exists(source_folder):
source = Folder(directory=source_folder)
destination_folder = os.path.join(destination_pictures, folder)
os.makedirs(destination_folder, exist_ok=True)
destination = Folder(directory=destination_folder)
source.copy_files_with(extension=extension, to_location=destination)
else:
print(f"{folder} doesn't exist")
else:
print("Source file or Destination drive is missing")
else:
print("Source file is empty")
except(ValueError, OSError) as error:
print(error)
finally:
pass
if __name__ == '__main__':
main()
</code></pre>
<p>I removed all the custom validation because as pointed out in my previous question, it was unnecessary. </p>
<p><strong>Areas of concern</strong>:</p>
<ul>
<li><p>The <code>finally</code> block of the <code>try</code> statement has the <code>pass</code> under it. I handle the exceptions, and use the <code>with</code> statement to read the file, so I don't really know what should go there.</p></li>
<li><p>I use type hinting, but I should also use docstrings and comments, but I didn't add them to save space. </p></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T19:03:49.690",
"Id": "434760",
"Score": "0",
"body": "Am I understanding your code correctly? Are you basically copying all files from `src/{name}/*` to `dst/{name}_{i}`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T20:53:09.470",
"Id": "434766",
"Score": "0",
"body": "@Peilonrayz - Not all the files in Pictures, just the ones specified in the text file, it gets renamed and placed in the equivalent destination folder."
}
] | [
{
"body": "<p>I'm in a rush so this is half baked :(</p>\n\n<ul>\n<li>It's best if you provide everything, currently your code isn't PEP 8 compliant due to you removing the docstrings. Some people may moan at you for this.</li>\n<li>You should prefer guard statements over <code>if</code> <code>else</code> statements when possible. You can easily change <code>if os.path.getsize(source_txt)</code> to use a <code>not</code> which would reduce the amount of indentation and reduce the complexity to read.</li>\n<li>You seem to have half baked error handling and I wouldn't be surprised if you're duplicating errors you can get from <code>open</code> and <code>pathlib</code>.</li>\n<li>I don't think you need a <code>Folder</code> class. If you use <code>pathlib</code> then everything you need should be fairly simple. I'm probably missing a couple of features but I think what you want is as simple as the below code.</li>\n</ul>\n\n<pre><code>from pathlib import Path\n\n\ndef main(source, src, dst, extensions):\n src = Path(src)\n dst = Path(dst)\n with open(source) as folders:\n for folder_name in folders:\n for i, file in enumerate(\n file\n for file in (src / folder_name).iterdir()\n if file.suffix in extensions\n ):\n shutil.move(file, dst / f'{folder_name}_{i}{file.suffix}')\n\n\nif __name__ == '__main__':\n try:\n main(\n \"source.txt\",\n \"{0}\\\\{1}\".format(os.getenv(\"USERPROFILE\"), \"Pictures\"),\n None,\n (\".jpg\",),\n )\n except Exception as e:\n print(e)\n raise SystemExit(1) from None\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T19:32:10.090",
"Id": "224171",
"ParentId": "224159",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T16:18:24.890",
"Id": "224159",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Rename and move images to a destination directory based on a text file"
} | 224159 |
<p>I have <code>$fruits_arr</code>:</p>
<pre><code>Array
(
[0] => Array
(
[id] => 213
[fruit] => banana
)
[1] => Array
(
[id] => 438
[fruit] => apple
)
[2] => Array
(
[id] => 154
[fruit] => peach
)
)
</code></pre>
<p>And <code>$ids_arr</code>:</p>
<pre><code>Array (
[0] => 213
[1] => 154
)
</code></pre>
<p>I want to recreate <code>$fruits_arr</code> to have only array items where <code>id</code> is equal to a value from <code>$ids_arr</code>. I also want to maintain the index/array order of <code>$fruits_arr</code>. </p>
<p>I'm using the following:</p>
<pre><code>$selected_fruits = array();
foreach( $fruits_arr as $fruit ) :
if ( in_array( $fruit['id'], $ids_arr ) ) :
$selected_fruits[] = $fruit;
endif;
endforeach;
print_r( $selected_fruits );
</code></pre>
<p>It seems to work but I am wondering if there is a shorter, better way to accomplish this in the latest PHP version. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T07:55:44.727",
"Id": "434833",
"Score": "0",
"body": "To give you the best advice, tell us where this array is being generated / how you are generating it. If it is necessary to filter this data, there is a better array structure to pursue. Is this a query's result set? If so, are you using mysqli? pdo? Are your ids unique within the `$fruits_arr` array? `in_array()` is not an efficient means to filter your data."
}
] | [
{
"body": "<p>Only thing you can use besides the foreach loop, it is <code>array_filter</code>:</p>\n\n<pre><code>$selected_fruits = array_filter($fruits_arr, function($fruit) use($ids_arr) {\n return in_array( $fruit['id'], $ids_arr );\n});\n</code></pre>\n\n<p>looks shorter and uses native functions</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T08:06:46.593",
"Id": "434835",
"Score": "0",
"body": "`ARRAY_FILTER_USE_BOTH` is entirely unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T16:42:29.573",
"Id": "434900",
"Score": "0",
"body": "yeap u are right"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:48:07.510",
"Id": "224168",
"ParentId": "224167",
"Score": "2"
}
},
{
"body": "<p>There's nothing wrong with your foreach loop, but you can use a slightly different syntax:</p>\n\n<pre><code>$selected_fruits = [];\n\nforeach ($fruits as $fruit) {\n if (in_array($fruit[\"id\"], $selected_ids)) {\n $selected_fruits[] = $fruit;\n }\n}\n\nprint_r($selected_fruits);\n</code></pre>\n\n<p>I've changed <code>$fruits_arr</code> to <code>$fruits</code>, and <code>$ids_arr</code> to <code>$selected_ids</code>. A variable name should describe the meaning or purpose of the data or resource a variable contains. And you should be consistent about your choices. For instance, why don't the arrays <code>$selected_fruits</code> and <code>$fruit</code> have the <code>_arr</code> post-fix in your code? They are arrays as well. </p>\n\n<p>There's no difference in the way the code above works, when compared with your code, but it is actually shorter than when <code>array_filter()</code> is used. <em>Shorter code</em> is, however, never a hallmark of <em>better code</em>. I think readability, and simply code that makes sense, are far more important. Using a rather complex function like <code>array_filter()</code> here is, in my eyes, overkill. </p>\n\n<p>As far as I can tell the syntax, as used in this answer, is used more often than the syntax in your question. For the <code>[]</code> array declaration you need PHP 5.4 or higher.</p>\n\n<p>You also wrote: </p>\n\n<blockquote>\n <p>I also want to maintain the index/array order of $fruits_arr. </p>\n</blockquote>\n\n<p>It is not completely clear what this means. If you actually want to maintain the same indexes you have to do a bit more. The code would then look like this:</p>\n\n<pre><code>$selected_fruits = [];\n\nforeach ($fruits as $index => $fruit) {\n if (in_array($fruit[\"id\"], $selected_ids)) {\n $selected_fruits[$index] = $fruit;\n }\n}\n\nprint_r($selected_fruits);\n</code></pre>\n\n<p>This would make the indexes of <code>$selected_fruits</code> equal to those of <code>$fruits_arr</code>.</p>\n\n<p>It is clear that both <code>foreach</code> loops, used in the code segments above, will have to walk the whole <code>$fruits</code> array to find all selected fruits. If the <code>$fruits</code> array becomes very long, compared to the number of selected fruits, this will not be very efficient. One of the reasons for this is the way that you've defined the <code>$fruits_arr</code>. The keys in this array don't do much. If I assume that the fruit ids in this array are unique, then it would be very helpful if the <code>$fruits_arr</code> keys actually were those fruit ids. I can redefine your <code>$fruits_arr</code> to achieve this, with this code:</p>\n\n<pre><code>$fruits_arr = array_combine(array_column($fruits_arr, \"id\"), $fruits_arr);\n</code></pre>\n\n<p>Now the <code>$fruits_arr</code> looks like this:</p>\n\n<pre><code>Array\n(\n [213] => Array\n (\n [id] => 213\n [fruit] => banana\n )\n\n [438] => Array\n (\n [id] => 438\n [fruit] => apple\n )\n\n [154] => Array\n (\n [id] => 154\n [fruit] => peach\n )\n)\n</code></pre>\n\n<p>It would, of course, be better to have done this right from the start, so you don't have to manipulate <code>$fruits_arr</code> to get those useful keys. Given this new array you can now do:</p>\n\n<pre><code>$selected_fruits = [];\n\nforeach ($selected_ids as $fruit_id) {\n $selected_fruits[] = $fruits[$fruit_id];\n}\n\nprint_r($selected_fruits);\n</code></pre>\n\n<p>This code only walks over the shorter <code>$selected_ids</code> array. It also doesn't contain the <code>in_array()</code> function anymore, because I assumed that all selected fruits are present in the fruits array. It wouldn't be a selection otherwise. </p>\n\n<p>Finally, the code above can be shortened to:</p>\n\n<pre><code>$selected_fruits = array_intersect_key($fruits, array_flip($selected_ids));\n\nprint_r($selected_fruits);\n</code></pre>\n\n<p>This is the shortest and most efficient version I can think of.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T08:21:45.060",
"Id": "434839",
"Score": "0",
"body": "Don't use combine(), see my snippet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T08:33:50.553",
"Id": "434841",
"Score": "0",
"body": "And flip the selected ids"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T09:21:27.183",
"Id": "434848",
"Score": "0",
"body": "I agree that `combine()` should not be used, it's better to create the array in the correct form from the start. And you're right about the `array_intersect_key()`, I'll correct that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T08:03:07.907",
"Id": "224202",
"ParentId": "224167",
"Score": "1"
}
},
{
"body": "<p>The best performing techniques for filtering arrays employ key-based comparisons. </p>\n\n<p>To prepare your posted data structures for such a technique will require both arrays to have there ids copied to the first level keys.</p>\n\n<p>Once both arrays have id values for keys, you can filter by comparison.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/VsXt5\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$fruits_arr = [\n ['id' => 213, 'fruit' => 'banana'],\n ['id' => 438, 'fruit' => 'apple'],\n ['id' => 154, 'fruit' => 'peach']\n];\n$ids_arr = [213, 154];\n\nvar_export(array_intersect_key(array_column($fruits_arr, null, \"id\"), array_flip($ids_arr)));\n</code></pre>\n\n<p>This is theoretic efficiency, because more effort is required simply to prepare. It would be better if you could declare these data structures in the necessary structure.</p>\n\n<p>All of the above assumes your ids are unique, if not your data will lose values with duplicated ids.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T08:21:09.057",
"Id": "224205",
"ParentId": "224167",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T18:08:11.457",
"Id": "224167",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "PHP recreate array if it contains certain values"
} | 224167 |
<p>I am trying to implement throttle function in vanilla JavaScript. I have seen other implementations on the web, but the way I have implemented it is more understandable for myself. I was wondering if any of you experts can take a look and let me know if I am missing some thing. It seems to be working fine but I am not sure the way I handle it is the correct.</p>
<p>HTML: </p>
<pre><code><html>
<head>
</head>
<body>
<div id='move'>
</div>
<div id='result'>
</div>
</body>
</code></pre>
<p>JS:</p>
<pre><code>var area;
var result;
function init() {
area = document.querySelector('#move');
area.addEventListener('mousemove', trottle);
result = document.querySelector('#result');
}
function updateResult(event) {
let xCordinate = event.clientX;
let yCordinate = event.clientY;
result.textContent = `${xCordinate} , ${yCordinate}`;
}
function trottle(event) {
updateResult(event);
let element = event.target
element.removeEventListener('mousemove', trottle);
setTimeout(function() {
element.addEventListener('mousemove', trottle);
}, 2000)
}
init();
</code></pre>
| [] | [
{
"body": "<p>Overall the code appears easy to read, and does what you say it does.</p>\n\n<p><strong>General comments:</strong></p>\n\n<ul>\n<li><p>The name of the throttle function is misspelled (trottle versus throttle). Not a show stopper, but does make it harder to read.</p></li>\n<li><p>I see a number of ECMA script language features being used, but the old <code>function() { ... }</code> style is being used for the callback in <code>setTimeout</code>. Consider using the more concise \"<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow function expression</a>\" (e.g. lambda expression) syntax instead:</p>\n\n<pre><code>setTimeout(() => element.addEventListener('mousemove', throttle), 2000);\n</code></pre></li>\n</ul>\n\n<p><strong>Code reusability and variable scope</strong></p>\n\n<ul>\n<li><p>Two global variables are being declared, and really should not exist in the global scope. Consider using an Immediately Invoked Function Expression (IIFE) to hide them:</p>\n\n<pre><code>(() => {\n let area;\n let result;\n\n ...\n})();\n</code></pre>\n\n<p>Or you can use a build tool like Grunt to automatically wrap this script in an IIFE.</p></li>\n<li><p>Other events are just as \"spammy\" as the mousemove event. The \"scroll\" event is just as bad, and this could be useful for that as well. Consider parameterizing the event that is being throttled.</p></li>\n<li><p>Same thing with the <code>updateResult</code> function. It could be parameterized as a callback function.</p></li>\n<li><p>Parameterizing the frequency of the throttling would be easy, and a good idea as well.</p></li>\n<li><p>The CSS selectors used to target the element whose events are being throttled is the last thing that needs to be parameterized in order to make this truly reusable.</p></li>\n</ul>\n\n<p>Given this, a function signature like the following would probably allow you to fix all the issues, including leaking variables to the global scope:</p>\n\n<pre><code>function throttleEvent(element, eventName, frequency, callback) {\n ...\n}\n</code></pre>\n\n<p>And would be used like this:</p>\n\n<pre><code>let area = document.querySelector(\"#move\");\nlet result = document.querySelector('#result');\nlet updateResult = (event) => {\n result.textContent = `${event.clientX} , ${event.clientY}`;\n};\n\nthrottleEvent(area, \"mousemove\", 2000, updateResult);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-18T12:22:29.433",
"Id": "224402",
"ParentId": "224173",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T20:13:22.430",
"Id": "224173",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Throttle implementation using pure JavaScript adding and removing event listener"
} | 224173 |
<p>I am fooling around with hooks in React and I'm stumbling against decisions that I need to make regarding implementation. Below is the code for the custom useForm hook which can be used to hook up forms to validation using Yub schema's.</p>
<p>Currently you can pass a callback function to the useForm that gets called when all the values are valid but this is where I'm not 100% sure what the best approach would be. Callback pattern or a promise or something I have not thought of?</p>
<p>I use flow for type annotations and I would love you guys to give me some feedback. Please do bash it!</p>
<pre><code>import { useState } from 'react'
import { mapYubValidationSchemaErrors } from '@domain/helpers'
type YubValidationSchema = any
function useForm(validationSchema: YubValidationSchema, callback: () => void) {
const [values, setValues] = useState({})
const [errors, setErrors] = useState({})
async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {
event.preventDefault()
try {
await validationSchema.validate(values, { abortEarly: false })
callback()
} catch (errorResult) {
setErrors(
mapYubValidationSchemaErrors(errorResult.inner),
)
}
}
function handleChange(event: SyntheticInputEvent<HTMLInputElement>) {
event.persist()
const newValues = {
...values,
[event.target.name]: event.target.value,
}
setValues(newValues)
}
return {
values,
errors,
handleSubmit,
handleChange,
}
}
export default useForm
</code></pre>
<p>The code to use it can be as follows</p>
<pre><code>function onValidated() {
// Do something
}
const {
errors,
handleChange,
handleSubmit,
} = useForm(validationSchema, onValidated)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T20:30:50.303",
"Id": "224174",
"Score": "1",
"Tags": [
"validation",
"react.js",
"typescript",
"callback"
],
"Title": "React.js hook to validate a form on submission"
} | 224174 |
<p>I created a simple quiz in HTML/CSS and plain Javascript. There are three questions with two options each, so there are eight possible combinations of answers, and therefore results. You can only pick one option per question.</p>
<p>This is how I am currently assigning a result to each combination in Javascript. The input is done through HTML.</p>
<pre><code>function GetResult(){
var result;
var inputs = document.getElementsByTagName('input');
for(var i = 0, i < inputs.length, i++){
if(inputs[i].checked){
result = result + inputs[i].value;
}}
if(result == 'NaturalHistoricalRelaxed'){
//result A
}
if(result == 'NaturalHistoricalFast'){
//result B
}
if(result == 'NaturalModernRelaxed'){
//result C
}
if(result == 'NaturalModernFast'){
//result D
}
if(result == 'UrbanHistoricalRelaxed'){
//result E
}
if(result == 'UrbanHistoricalFast'){
//result F
}
if(result == 'UrbanModernRelaxed'){
//result G
}
if(result == 'UrbanModernFast'){
//result H
}
}
</code></pre>
<p>My question is, is there a better way of assigning each result to each combination?</p>
<p>I know that many people would tell me to use a Javascript library, but I don't want to, so please do not write answers like that.</p>
| [] | [
{
"body": "<p>I am not familiar enough with JavaScript to write out the code while I am travelling, but I can at least describe a simple algorithm to do so generally in a faster and slightly simpler way. I here assume that you have access to the raw results and don't need to re-interpret them from the collected string.</p>\n\n<p>For each answer we assign a 0 or 1 to the result, and then join them together as a bit mask, by shifting each answer by the 0-indexed numbering of the question it is an answer to. You can then construct an array of all the possible results, \nand when you want to know which result a response corresponds to, you can just construct an integer from the above bit mask and use it as an index for the array's result you want. If you have unique results for every response, then this is about as good as you can do (remember you can put a function in the array and call it if you want to do the compilation lazily). If you can construct the results from some kind of pattern, then you can find the right indexes by filtering the indexes with and based bit masked (with not applied to the result if you want the ones which have 0's in those masks).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T19:38:37.630",
"Id": "435219",
"Score": "0",
"body": "You are describing a 'nominal' value. I like solutions that use existing structs to store 'complex' data. Unfortunately, I am out of votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T19:16:19.323",
"Id": "477488",
"Score": "0",
"body": "Is it just me, or are bit masks not very developer friendly when it comes to readability and debugging? I get that they are very good for performance, but would a simple dictionary not suffice in this case, and be much easier to use? Or am I just too much of a simple web developer to understand their benefit?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T07:32:55.477",
"Id": "224200",
"ParentId": "224175",
"Score": "3"
}
},
{
"body": "<p>when you have many if condition with one case value, you can use switch case syntax</p>\n\n<pre><code>switch (result) {\n case 'NaturalHistoricalRelaxed':\n //result A;\n break;\n case 'NaturalHistoricalFast':\n //result B;\n break;\n case 'NaturalModernRelaxed':\n //result C;\n break;\n case 'NaturalModernFast':\n //result D;\n break;\n case 'UrbanHistoricalRelaxed':\n //result E;\n break;\n case 'UrbanHistoricalFast':\n //result F;\n break;\n case 'UrbanModernRelaxed':\n //result G;\n break;\n case 'UrbanModernFast':\n //result H;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T14:58:59.933",
"Id": "477452",
"Score": "4",
"body": "This is an example of why best practice in general questions are off-topic. Since we don't know what `//result A` is we don't know if your switch or a dictionary / object would be better. Take `{'NaturalHistoricalRelaxed': 'result A'}[result]`. Since I don't know if your advice is good or bad I'm hesitant to upvote it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T15:12:16.420",
"Id": "477458",
"Score": "0",
"body": "It was very thought-provoking, I didn't look at it that way.\nbut i know, if we have many if for one unique value, it will be better replace to switch case, may be it is not true"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T05:16:55.827",
"Id": "243248",
"ParentId": "224175",
"Score": "1"
}
},
{
"body": "<p>I'm not sure I understand your code entirely. What is happening inside each conditional? What doe you mean by \"assigning each result to each combination\"? I'll assume you are trying to select a certain value based on a combination of answers, cause that makes the most sense to me.</p>\n\n<p>First off, the result string could be composed in a cleaner way with modern javascript (imo). I would probably go for something like this, mostly because I find it to be more readable:</p>\n\n<pre><code>const checkedInputs = document.querySelectorAll('input:checked');\nconst answerKey = Array.from(checkedInputs, input => input.value).join('');\n</code></pre>\n\n<p>To then select the desired value based on this key, it would probably be cleaner to work with a dictionary. Something like this:</p>\n\n<pre><code>const resultDictionary = {\n NaturalHistoricalRelaxed: 'result A',\n NaturalHistoricalFast: 'result B'\n // ...\n}\n\nconst result = resultDictionary[answerKey];\n</code></pre>\n\n<p>No ugly chain of conditionals, and much easier to maintain if you have to change something. You could even pull in that dictionary from a JSON file or an API or something, and make the code work on multiple quizes that way.</p>\n\n<p>I hope I interpreted your question correctly and my answer makes sense. Feel free to ask if you want me to elaborate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T22:40:15.027",
"Id": "477516",
"Score": "0",
"body": "Please don't answer off-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T22:57:08.057",
"Id": "477517",
"Score": "0",
"body": "Really @Peilonrayz? An open question with +1 score and two prior answers and you choose to downvote just me? How am I supposed to know this is off topic (according to you)? Perhaps you should close the question then, in stead off slapping people on the wrist that try to be helpful... Way to build a community!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T23:06:34.240",
"Id": "477518",
"Score": "0",
"body": "The question is +3/-2 and has 4 close votes attached to it. I can appreciate that you can't see this. Additionally my comment on Mehrdad's answer said this is an off-topic question. Additionally if anything I targeted Mehrdad, as I systematically edited, commented and voted on all of their posts. Again I can appreciate that you didn't know this. But I'd appreciate it if you didn't accuse me of nonsense based on nothing more than a hunch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T23:35:51.757",
"Id": "477520",
"Score": "0",
"body": "You are probably right, I shouldn't have lashed out like that. Please accept my apologies @Peilonrayz, it's just that it's the second time I get slapped on the wrist in as many answers, and this time I really don't see how the question is off topic (perhaps you care to explain). I get the feeling things have changed around here, and I'm not sure I like the patrolling vibe I get..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T23:44:53.350",
"Id": "477521",
"Score": "0",
"body": "It's ok Pevara. I could have made my initial comment better too, to avoid a needless confrontation. I am sorry. I can understand that it's not nice to feel like you're being policed. In this case the question is missing context to give an accurate answer, for example it's impossible for me to know which of your answer or Mehrdad's answer is better for the OP. We have made this off-topic as we have had problems with OPs becoming hostile to answerers that just want to help but weren't given all the information."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T19:07:19.670",
"Id": "243277",
"ParentId": "224175",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:15:19.910",
"Id": "224175",
"Score": "1",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Showing a unique result based on options selected"
} | 224175 |
<p>To improve my knowledge I am trying to make a <code>bool</code> class from scratch, or derivative of. I am using MinGW g++11 compiler on a Windows 7 laptop. </p>
<pre><code>#include <iostream>
#include <bitset>
class Zeroth{
uint8_t* MEM = nullptr;
public:
const static uint8_t NullSet; // if data is declared sttic it is shared acros all instances, const means it can not be changed
const static uint8_t UnitSet;
/*
the idea is that instead copying integers i can define a constant shared memories [ generated on a fly or in a header ]
and then just store memory of the value that is pointed to
so if object is present: point to memory of UnitSet
if object isn't present: point to memory of NullSet
therefore i have 1 8 bit space instanced and deleted with every value, but all those spaces point to the same constant memories
*/
Zeroth():MEM(new uint8_t){ this->MEM = (uint8_t*)&Zeroth::NullSet; }
Zeroth(int VAL):MEM(new uint8_t) {
this->MEM = (uint8_t*)( VAL&0x1 ? &Zeroth::UnitSet : &Zeroth::NullSet );
}
~Zeroth(){ delete MEM; }
const bool isPresent() const {
return (int)&Zeroth::UnitSet == (int)&(*this->MEM);
}
const bool isNotPresent() const {
return (int)&Zeroth::NullSet == (int)&(*this->MEM);
}
friend std::ostream& operator<<( std::ostream& os, const Zeroth& data );
};
std::ostream& operator<<( std::ostream& os, const Zeroth &data ){
return os << ( data.isPresent() ? 'T' : 'F');
}
const uint8_t Zeroth::NullSet = 0;
const uint8_t Zeroth::UnitSet = 1;
int main(){
Zeroth Az(3);
std::cout << Az << std::endl;
std::cout << Az.isPresent() << std::endl;
std::cout << Az.isNotPresent() << std::endl;
Zeroth Bz;
std::cout << Bz << std::endl;
std::cout << Bz.isPresent() << std::endl;
std::cout << Bz.isNotPresent() << std::endl;
return 0;
}
</code></pre>
<p>And result is :</p>
<pre><code>CD: F:\cppDMmods
Current directory: F:\cppDMmods
g++ -Wno-unused-variable -O2 F:\cppDMmods\test.cpp -o F:\cppDMmods\test.exe
Process started (PID=4296) >>>
<<< Process finished (PID=4296). (Exit code 0)
IF: "Exists" != "Exists" goto NOEXE
test.exe
Process started (PID=5516) >>>
T // Az printout
1 // Az "presence" :> aka true
0 // Az "negated presence" :> aka !true
F // Bz printout
0 // Bz "presence"
1 // Bz "negated presence"
<<< Process finished (PID=5516). (Exit code 0)
cmd /c del test.exe
Process started (PID=6124) >>>
<<< Process finished (PID=6124). (Exit code 0)
NO EXE FILE TO DELETE
================ READY ================
</code></pre>
<p>I am worried that due to my presumed lack of knowledge there might be some memory leaks, massive future bugs and etc.<br>
Any suggestions, recommendations and pointed out issues are welcomed.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:32:33.190",
"Id": "434771",
"Score": "1",
"body": "The size of a pointer to an `uint8_t` should be either 32bit or 64bit and is therefore heavier than if you'd use the value itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:35:25.923",
"Id": "434772",
"Score": "0",
"body": "Are you talking about `MEM` member ? How can i declare an 34 bit ( by defining an `uint64_t` ? ) , and what are possible issues that could rise if i don't change the size of the pointer ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:49:34.370",
"Id": "434774",
"Score": "1",
"body": "The pointer has the right size, C++ will take care of this. What I was trying to say is that \"instead copying integers i [...] just store memory [address] of the value\" (from your code) increases the memory footprint (see yourself in this online example: http://cpp.sh/2xmm)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:03:09.453",
"Id": "434776",
"Score": "0",
"body": "So , i am guessing the same thing arises if i try to store `address of` instead of `pointer`? Which makes sense since size of an address is tied to OS bit size... and since we push the elements on the registry the variable is destroyed once it exits the scope. So `bool a = true` expands to `bool a = new bool(1)` ?"
}
] | [
{
"body": "<p>I'm sorry to be so straightforward: <strong>This is madness!</strong> Your code seems to indicate a sincere lack of several language features.</p>\n\n<h2>Pointer to const</h2>\n\n<p>You define <code>MEM</code> to be of type <code>uint8_t*</code>, but it actually points to values of <code>const uint8_t</code>. To account for this difference you cast the <code>const</code> away in both constructors. If you'd ever (accidentally) write to the memory <code>MEM</code> points to, <a href=\"https://stackoverflow.com/q/25209838\">undefined behavior</a> might ensue. So it should be at least of type <code>uint8_t const *</code>.</p>\n\n<h2>Memory leak in constructor</h2>\n\n<p>As you have suspected, your code leaks memory. Both constructors assign <code>new uint8_t</code> to <code>MEM</code> before overwriting it directly afterwards. Now there is no way to reference the values created on the heap with <code>new</code>. Both allocations are not necessary since <code>MEM</code> always points to one of the two static variables. Therefore you should also not try to delete them once <code>Zeroth</code> goes out of scope.</p>\n\n<p>Since we are at the constructor: why do you accept an 32bit integer as argument when all you care about is one bit and all your internal values are stored in an <code>uint8_t</code>? I also find it unintuitive to treat all the even numbers as false, and all the odd ones as true (this is basically a consequence of your bit mask). Often all values except 0 are treated as truthy values (exempt of this rule are exit codes, where 0 is usually seen as success).</p>\n\n<h2>isPresent/isNotPresent</h2>\n\n<p>Those functions do not even compile on a 64bit platform, since the completely unnecessary cast to <code>int</code> narrows the bidwidth of the pointer type from 64bit to 32bit. Apart from that, there is a whole lot of other weird things going on here.</p>\n\n<p>Let's try to break this down:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>(int)&(*this->MEM)\n</code></pre>\n\n<p><code>this->MEM</code> is a pointer. You then for whatever reason decided to dereference (<code>*this->MEM</code>) it to get the value it's pointing to. After that, you take the address of the value (<code>&(*this->MEM)</code>), which should be the same as <code>this->MEM</code>. And if all of this weren't enough, you then try to cram the address into an <code>int</code> (<code>(int)&(*this->MEM)</code>).</p>\n\n<p>Same procedure for the value you try to compare it with:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>(int)&Zeroth::UnitSet\n</code></pre>\n\n<p>You have the value <code>Zeroth::UnitSet</code>, take the address of it <code>&Zeroth::UnitSet</code> and then try to cram this address into a 32bit integer.</p>\n\n<p>You get the same effect using</p>\n\n<pre><code>bool isPresent() const { return &Zeroth::UnitSet == this->MEM; }\nbool isNotPresent() const { return &Zeroth::NullSet == this->MEM; }\n</code></pre>\n\n<p>without all this madness.</p>\n\n<h2>Memory footprint</h2>\n\n<p>The internal state of your class is represented by a pointer to a const <code>uint8_t</code>. As I have already tried to tell you in the comments, the size of the pointer is 32bit or 64bit depending on which type of architecture your compiler tries to target. This 4 to 8 times larger than the 8bit you would need to store the value. If you stick with the value, there are far less possibilities to shoot yourself in the foot.</p>\n\n<pre><code>class ZerothVal {\n\npublic:\n ZerothVal() = default; // see https://en.cppreference.com/w/cpp/language/default_constructor\n\n ZerothVal(uint8_t VAL) {\n val = (VAL & 0x1 ? ZerothVal::UnitSet : ZerothVal::NullSet);\n }\n\n bool isPresent() const { return val == ZerothVal::UnitSet; }\n bool isNotPresent() const { return val == ZerothVal::NullSet; }\n\n friend std::ostream& operator<<(std::ostream& os, const ZerothVal& data);\n\nprivate:\n const uint8_t NullSet = 0;\n const uint8_t UnitSet = 1;\n\n uint8_t val = ZerothVal::NullSet;\n};\n\nstd::ostream& operator<<(std::ostream& os, const ZerothVal& data) {\n return os << (data.isPresent() ? 'T' : 'F');\n}\n</code></pre>\n\n<h2>Operator support</h2>\n\n<p>Since you'd like to implement some kind of bool value, I'd highly recommend implementing the <a href=\"https://www.artima.com/cppsource/safebool.html\" rel=\"nofollow noreferrer\">Safe Bool Idiom</a>. For you that would mean that you have to implement <code>operator bool()</code> for your class (see <a href=\"https://stackoverflow.com/a/4600316\">this SO post</a> for an explanation).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T11:53:25.270",
"Id": "434863",
"Score": "0",
"body": "This is madness i tell you! Madness!! :D Don't apologise for straightforwardness and bluntness ...that is why i am here for. Operator overloading will come after i stop shooting myself in the foot. It does compile on 64 bit OS ( i am currently on it ), but this could be IDE /compiler difference. Why did you remove static ? Ok i get that all that memory , but the idea is to use shared members so each class don't have to initialise them ? Does const in this manner do the similar action ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T12:03:00.673",
"Id": "434865",
"Score": "0",
"body": "There are 32bit and 64bit versions of Cygwin, so it depends on which version you've got. I removed `static` because IMHO it does not buy you anything here. Until you have serious indications that there will be a problem in your application, you should stick with the simplest possible implementation. Then if there is a problem, measure carefully and then and only then look at the results and think about optimization."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T11:31:15.863",
"Id": "224213",
"ParentId": "224176",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "224213",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:19:25.207",
"Id": "224176",
"Score": "1",
"Tags": [
"c++",
"c++11",
"reinventing-the-wheel",
"memory-management"
],
"Title": "Boolean class using shared referenced memory"
} | 224176 |
<p>I wrote this function to count the syllables in a word using Python to complete an exercise.</p>
<p>The exercise's text is:</p>
<blockquote>
<p>Return the number of syllables in the given word, according to this
rule: Each contiguous sequence of one or more vowels is a syllable,
with the following exception: a lone "e" at the end of a word is not
considered a syllable unless the word has no other syllables. You
should consider y a vowel.</p>
</blockquote>
<p>I also disagree with the text because using the given instructions the syllable count for the word "example" are 2 and should be 3.</p>
<p>But, as discussed in the comments, the exercise text is the one that I implemented and would like to get suggestions and improvements for.</p>
<pre><code>def count_syllables(word):
word = word.lower()
counter = 0
is_previous_vowel = False
for index, value in enumerate(word):
if value in ["a", "e", "i", "o", "u", "y"]:
if index == len(word) - 1:
if value == "e":
if counter == 0:
counter += 1
else:
counter += 1
else:
if is_previous_vowel == True:
counter += 1
is_previous_vowel = False
break
is_previous_vowel = True
else:
if is_previous_vowel == True:
counter += 1
is_previous_vowel = False
print ("In \"{}\" I count {} syllables".format(word, counter))
count_syllables("coding")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:45:24.253",
"Id": "434773",
"Score": "0",
"body": "You could possibly try bit masking. Using `ord` function you can convert any character to its 8 bit integer representation. Then you could write instead of *`for`* an *`while loop`* till end character is found (`0x00`), where your counter would then be `counter += 1 if (ord(word[i]) & 97 == 97 else 0`. You can see what integer representations of your vowel letters are by going into console and just `list(map(ord, 'aeiouy'))`. With while loop you can save in speed by not assigning length of string. GKeyWords: Bitwise operators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:02:15.357",
"Id": "434775",
"Score": "1",
"body": "I also disagree with the text, although for the different reasons. There are plenty of words in which successive vowels form distinct syllables; there are plenty of (mostly borrowed) words in which final `e` forms a syllable; treatment of `y` is too simplistic (say, `beyond`). However I am curious how did you come up with 4 syllables in `example`. Nevertheless, the problem statement is what has to be implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:18:37.423",
"Id": "434777",
"Score": "0",
"body": "@vnp Horrible typo! 3 and not 4 syllables for example, obviously.\nI also see that the exercise track was written in this way for simplification.\nIndeed the Code Review should be mainly code related so I will consider as good answer the one that improves my code and just follow the given exercise track.\nObviously if a great coder comes with a complete solution working for real English that would simply be awesome for me and other people on the planet, I guess :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:23:15.933",
"Id": "434778",
"Score": "0",
"body": "So you just want someone to do the example instead of you ? Smart. \nYou are missing the main question. The code works so you have no major bugs. There is of course optimisation and readability/speed improvement, but since you've changed your question a bunch of times ( i don't mind that ), it is unclear what are you expecting to get from Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:28:37.553",
"Id": "434779",
"Score": "1",
"body": "@Danilo\nWhat do you mean by \"instead of me\"?\nI already did a complete and working version of the code, as you can read in the post.\nAll I am looking for is improvements / more efficient / more elegant version of it.\nThis is the main idea behind this site, no?\nOn the other side, while discussing with vpn, seemed obvious that also the text of the exercise would not obtain 100% correctness in English.\nI just think it would be nice bonus if we can get a 100% working version in English but it is not the aim of this question, only focused on given code improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:33:52.853",
"Id": "434780",
"Score": "0",
"body": "@Pitto this \" I will consider as good answer the one that improves my code and just follow the given exercise track.\" sentence gives off a feeling of delegating work. I might be wrong. So what is the aim of the question ? Improve code, make it efficient and elegant? So in short readable , faster and simple code ? If that is so perhaps you could add that to the question so you don't get a bunch of iterations of your own code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:38:59.200",
"Id": "434782",
"Score": "0",
"body": "@Danilo Forgive me if my clarity is not top notch but English is not my main language. The work I had to do is already done so what am I delegating? This website is code review and people post their code to... Get reviews. I tried to explain better what I will consider a good result so if someone decides to give it a try already knows better what I'd be looking for and what could probably be useful for next readers. Here's how to ask a good question: https://codereview.meta.stackexchange.com/questions/1954/checklist-for-how-to-write-a-good-code-review-question I don't think mine is terrible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T22:40:17.643",
"Id": "434783",
"Score": "0",
"body": "If I came here to ask this question is because I want to learn more and better Python and because I hope to contribute to write a good count syllable function that might be useful for other in future, that's all."
}
] | [
{
"body": "<p>As a good practice to promote code reuse, the function should <code>return</code> a numeric result. The <code>print()</code> should be done by the caller.</p>\n\n<p>Constantly referring to <code>is_previous_vowel</code> is tedious. There are a couple of solutions you could use involving <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a>. In particular, <code>groupby()</code> and <code>zip_longest()</code> could be useful.</p>\n\n<p>Ultimately, the simplest solution is to use a <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regular expression</a> to declare what you are looking for: one or more consecutive vowels (<code>'[aeiouy]+'</code>), but not an <code>e</code> at the end (<code>'(?!e$)</code>).</p>\n\n<pre><code>import re\n\ndef count_syllables(word):\n return len(\n re.findall('(?!e$)[aeiouy]+', word, re.I) +\n re.findall('^[^aeiouy]*e$', word, re.I)\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T07:50:09.197",
"Id": "434832",
"Score": "0",
"body": "This is a masterpiece"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T23:20:24.220",
"Id": "224180",
"ParentId": "224177",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "224180",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-14T21:35:54.980",
"Id": "224177",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python function to count syllables in a word"
} | 224177 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.