body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>We currently have two legacy systems: the Consumer and the Worker. These systems are massively complex in ways that are not important to this review, but it is enough to say that a large-scale re-development of these systems is not currently possible.</p>
<p>The Consumer communicates with the Worker via http request/response. The request/response nature of this setup is critical and non-negotiable; this is really the whole purpose of this review. There is no opportunity to use (for example) notifications or events to solve this problem. The Worker's task of processing the request may be long (or longish) running, and returns a response when complete. </p>
<p>So the current state could not be simpler:</p>
<pre><code>1. Consumer sends a request to the Worker via POST
2. Worker receives the request and does the necessary work
3. Worker returns a response to the Consumer
</code></pre>
<p>Now, the problem: the actual work that the Worker does has resource constraints, and allowing an unlimited number of "jobs" to be processed concurrently is problematic. What we need to do is introduce a way to queue up requests and feed them to the Worker in a measured, predictable way.</p>
<p>Our solution is to introduce a "Queue Service" in between the Consumer and the Worker. This will be a physical, singular service that acts as a pass-through, with its only other responsibility being to manage the Worker's load. </p>
<p>The actual implementation of the queuing mechanism is not important for this question, but a few important requirements:</p>
<pre><code>1. The Queue Service will consist of custom code to queue, prioritize and feed the work to the Worker (out-of-box solutions like Gateways are not viable options).
2. The Queue Service will be asynchronous to avoid thread starvation when there are many http requests in flight.
</code></pre>
<p>So the desired state would be:</p>
<pre><code>1. Consumer sends a request to the Queue Service via POST
2. Queue Service receives the request
3. Queue Service sends a request to the Worker via POST (immediately or delayed depending on the state of the queue)
4. Worker receives the request and does the necessary work
5. Worker returns a response to the Queue Service
6. Queue Service returns a response to the Consumer
</code></pre>
<p>To be clear, the idea is that the request remains active even if the work gets put into queue and has to wait.</p>
<p>In the code below, I am trying to prove that this is possible by signaling using the TaskCompletionSource construct. There are all kinds of shortcuts/simplifications in this code--the main question is whether this technique is viable to keep the request alive until a separate process signals its completion (and provides a result). </p>
<pre><code>[TestFixture]
public class ValidateAsyncContinuation
{
[Test]
public async Task RunAsync()
{
//start this as a background task (fire and forget)
PretendQueueReader.StartProcessing();
var sw = Stopwatch.StartNew();
const int feedDelayInMs = 1;
const int numToProcess = 1000;
var tasks = new List<Task>();
//this simulates x number of requests sent via http and waiting for a response, spaced out by a 1ms delay
for (var x = 0; x < numToProcess; x++)
{
var x1 = x; //to avoid "access to modified closure" warning
var task = Task.Run(async () =>
{
await PretendController.Post(new Request($"request {x1}"), x1);
Debug.WriteLine($"Completed {x1}.");
});
tasks.Add(task);
Thread.Sleep(feedDelayInMs);
}
await Task.WhenAll(tasks);
Debug.WriteLine($"took {sw.ElapsedMilliseconds}ms");
PretendQueueReader.Stop();
}
}
//background process that periodically tells the PretendQueue to check to see if there is work to be done
public static class PretendQueueReader
{
private static bool _stop;
public static async Task StartProcessing()
{
while (!_stop)
{
await PretendQueue.ProcessQueue();
await Task.Delay(1); //run every 1ms. Not having any delay spikes the CPU.
}
}
public static void Stop()
{
_stop = true;
}
}
public static class PretendController
{
//the controller passes the request along to the queue and waits for a response
public static async Task<Response> Post(Request request, int index)
{
return await PretendQueue.QueueRequest(request, index);
}
}
public static class PretendQueue
{
private static readonly Queue<RequestCompletion> Queue = new Queue<RequestCompletion>();
private static int _inProcess;
private const int MaxConcurrent = 100;
private static readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1,1);
public static async Task<Response> QueueRequest(Request request, int index)
{
var responseSignal = new TaskCompletionSource<Response>();
//lock the queue when accessing and release when complete.
await SemaphoreSlim.WaitAsync();
try
{
Queue.Enqueue(new RequestCompletion(request, responseSignal));
Debug.WriteLine($"Queuing Request #{index}: {_inProcess} requests are in process and {Queue.Count} requests are in queue.");
}
finally
{
SemaphoreSlim.Release();
}
return await responseSignal.Task;
}
public static async Task ProcessQueue()
{
RequestCompletion requestCompletion;
//lock the queue when accessing and release when complete.
await SemaphoreSlim.WaitAsync();
try
{
if (Queue.Count == 0 || _inProcess >= MaxConcurrent) return;
Debug.WriteLine($"DE-Queuing a Request: {_inProcess} requests are in process and {Queue.Count} requests are in queue.");
requestCompletion = Queue.Dequeue();
}
finally
{
SemaphoreSlim.Release();
}
//fire and forget
Run(requestCompletion.Request, requestCompletion.ResponseCompletionSource);
}
private static async Task<Response> Run(Request request, TaskCompletionSource<Response> responseSignal)
{
await SemaphoreSlim.WaitAsync();
_inProcess++;
SemaphoreSlim.Release();
//Fire and forget.
PretendWorker.ProcessAndSignal(request, responseSignal);
var response = await responseSignal.Task;
await SemaphoreSlim.WaitAsync();
_inProcess--;
SemaphoreSlim.Release();
return response;
}
}
public static class PretendWorker
{
public static async Task ProcessAndSignal(Request request, TaskCompletionSource<Response> responseCompletionSource)
{
var start = DateTime.Now;
//this simulates the call to the worker (taking 2 seconds)
await Task.Delay(TimeSpan.FromSeconds(2));
responseCompletionSource.SetResult(new Response(start, DateTime.Now));
}
}
public class RequestCompletion
{
public RequestCompletion(Request request, TaskCompletionSource<Response> responseCompletionSource)
{
Request = request;
ResponseCompletionSource = responseCompletionSource;
}
public Request Request { get; }
public TaskCompletionSource<Response> ResponseCompletionSource { get; }
}
public class Request
{
public Request(string name)
{
Name = name;
}
public string Name { get; }
}
public class Response
{
public Response(DateTime startedTime, DateTime completedTime)
{
StartedTime = startedTime;
CompletedTime = completedTime;
}
public DateTime StartedTime { get; }
public DateTime CompletedTime { get; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:24:59.713",
"Id": "423188",
"Score": "1",
"body": "I would be concerned over timeouts. Http servers usually have timeouts/request have timeouts/clients have timeouts. They are all usually customizable so you would need to make sure they are all accounted for. Just having a quest pending doesn't stop say iis from timing out your request. Packages like SignalR are designed to keep a long running connection with fall backs. Might be worth checking if you can use that possibly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:30:51.950",
"Id": "423189",
"Score": "0",
"body": "@CharlesNRice timeouts are indeed a consideration that we will need mitigate carefully."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T20:46:38.653",
"Id": "217986",
"Score": "2",
"Tags": [
"c#",
"asynchronous",
"async-await"
],
"Title": "Putting a Queue Between HTTP Request/Response"
} | 217986 |
<p>I am trying to extract the ip address of my machine when connected to multiple wireless networks. The motivation here is then I can make a socket connection on that ip when I have two networks that have the same default gateway. I am hoping that there is either a way to greatly improve the code or replace it with some functionality that does what I am doing in a more robust cleaner way. In particular, the part that worries me most is using the MAX_OFFSET to ensure that the code does not return the next ip address. </p>
<pre><code>import os
import subprocess
if os.name == "nt":
WIRELESS_ADAPTER0 = b"Wi-Fi:"
WIRELESS_ADAPTER1 = b"Wi-Fi 2"
COMMAND = "ipconfig"
IPV4_LINE = b"IPv4"
IPV6_LINE = b"IPv6"
IP_INDEX = -1
MAX_OFFSET = 5
else:
WIRELESS_ADAPTER0 = b"wlan0"
WIRELESS_ADAPTER1 = b"wlan1"
COMMAND = "ifconfig"
IPV4_LINE = b"inet"
IPV6_LINE = b"inet6"
IP_INDEX = 1
MAX_OFFSET = 7
def get_ip(all_lines, start_index):
try:
search_lines = list(filter(lambda x: (IPV4_LINE in x) or (IPV6_LINE in x), all_lines[start_index:start_index+MAX_OFFSET]))
return search_lines[0].split()[IP_INDEX]
except IndexError:
pass
all_lines = subprocess.check_output(COMMAND).split(b"\n")
for i in range(len(all_lines)):
if WIRELESS_ADAPTER0 in all_lines[i]:
ip0 = get_ip(all_lines, i)
if WIRELESS_ADAPTER1 in all_lines[i]:
ip1 = get_ip(all_lines, i)
</code></pre>
<p>I have included some sample output from ipconfig below:</p>
<pre class="lang-none prettyprint-override"><code> Wireless LAN adapter Wi-Fi 2:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . : lan
Ethernet adapter Ethernet 5:
Connection-specific DNS Suffix . : enceptacorp.local
Link-local IPv6 Address . . . . . : fe80::80f0:901c:f4d3:1c6%5
IPv4 Address. . . . . . . . . . . : 192.168.128.226
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.128.1
</code></pre>
<p>The reason I use MAX_OFFSET is to make sure that I don't get the next ip address down (i.e. the IP for Ethernet 5, when Wi-Fi 2 is disconnected). I have also noticed that sometimes when first connecting to the router, I won't get assigned an IPv4 Address right away, and that is why I have included IPv4 and IPv6. If anyone can comment on whether I will always get an IPv6 address (and thus can ignore IPv4), that would be useful to know. Is there a better way to get the IP address of a particular network interface? Or even just a command like ipconfig that returns more concise/consistent/cleaner output? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:00:47.593",
"Id": "421932",
"Score": "0",
"body": "Which operating systems do you expect your code to work on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:07:02.930",
"Id": "421933",
"Score": "0",
"body": "Windows 10 and Linux. Specifically, I will be running it on a Windows laptop and a raspberry pi running posix. I have tested it on both and it seems to work for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:09:23.220",
"Id": "421934",
"Score": "0",
"body": "I'm not convinced that it will work on Linux. The second line of `ifconfig` output for each interface is ` inet addr:1.2.3.4 Bcast:1.2.3.255 Mask:255.255.255.0`. So, it would get `addr:1.2.3.4` as the IP address."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:20:31.603",
"Id": "421935",
"Score": "0",
"body": "Hmm, I have `inet 192.168.128.105 netmask 255.255.255.0 broadcast 192.168.128.255`, no addr"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T20:57:50.433",
"Id": "217987",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"parsing",
"ip-address"
],
"Title": "Extract the IP address from the output of ipconfig when connected to multiple wireless networks"
} | 217987 |
<p>Python 3.7.0</p>
<pre><code>from sys import argv
class Version:
def __init__(self, ver_str):
if type(ver_str) != 'string':
ver_list = ver_str.split('.')
self.Major = int(ver_list[0])
self.Minor = int(ver_list[1])
self.Patch = int(ver_list[2])
self.Build = int(ver_list[3])
def __repr__(self):
return "{}.{}.{}.{}".format(self.Major, self.Minor, self.Patch, self.Build)
def __lt__(self, other):
if other.Major != self.Major:
return self.Major < other.Major
elif other.Minor != self.Minor:
return self.Minor < other.Minor
elif other.Patch != self.Patch:
return self.Patch < other.Patch
else:
return self.Build < other.Build
def __gt__(self, other):
if other.Major != self.Major:
return self.Major > other.Major
elif other.Minor != self.Minor:
return self.Minor > other.Minor
elif other.Patch != self.Patch:
return self.Patch > other.Patch
else:
return self.Build > other.Build
def printme(self):
print("{}.{}.{}.{}".format(self.Major, self.Minor, self.Patch, self.Build))
def main(argv):
validate_args(argv)
ver_1 = Version(argv[1])
ver_2 = Version(argv[2])
op = argv[3]
if op == '<':
print("{} < {}: {}".format(ver_1, ver_2, ver_1 < ver_2))
elif op == '>':
print("{} > {}: {}".format(ver_1, ver_2, ver_1 > ver_2))
else:
print("Incorrect operator")
exit(-1)
def validate_args(argv):
no_of_args = len(argv)
if no_of_args != 4:
print("USAGE: {} 1.1.1.1 2.2.2.2 '<' or '>'".format(argv[0]))
exit(-1)
if (len(argv[1].split('.')) != 4) or (len(argv[2].split('.')) != 4):
print("USAGE: {} 1.1.1.1 2.2.2.2. '<' or '>' IMPROPER VERSION FORMAT".format(argv[0]))
exit(-1)
if argv[3] != '>' and argv[3] != '<':
print("USAGE: {} 1.1.1.1 2.2.2.2. '<' or '>' IMPROPER OPERATOR".format(argv[0]))
exit(-1)
if __name__ == '__main__':
main(argv)
</code></pre>
| [] | [
{
"body": "<p>First of all, have you looked at <code>LooseVersion</code> and/or <code>StrictVersion</code> from <a href=\"https://docs.python.org/3.7/distutils/apiref.html#module-distutils.version\" rel=\"nofollow noreferrer\"><code>distutils.version</code></a>? They might already provide you with exactly what you need.</p>\n\n<hr>\n\n<p>General “PEP-8” Comments:</p>\n\n<p>You should have a blank line after your import, after <code>class Version</code>, and after the <code>def __repr__(self)</code> method. The blank-lines inside of <code>__lt__</code> and <code>__gt__</code> functions before the <code>else:</code> clause are inconsistent.</p>\n\n<p>Your class and methods could benefit from <code>\"\"\"doc strings\"\"\"</code>.</p>\n\n<p>The class members <code>Major</code>, <code>Minor</code>, <code>Patch</code> and <code>Build</code> should all be lower case. Only class names should begin with capital letters. Since the members should be private to the class, they should also be prefixed with an underscore.</p>\n\n<hr>\n\n<p>The constructor will silently fail if <code>type(ver_str) != 'string'</code> is ever <code>False</code>, and then the instance becomes useless, as the members which are required in every other method of the class become reference errors. There is no need to check if <code>ver_str</code> is a string; just try to split it, and convert the parts to integers. If you haven’t passed in a string, the split or conversion to integers will cause an exception. (You could add a check that the split produces exactly 4 parts, to reject a version such as \"1.2.3.4.5.6\".)</p>\n\n<p>Fortunately (as noted by @200_success in the comments), <code>type(ver_str)</code> will never equal <code>'string'</code>, because <code>type(...)</code> doesn't return strings; it returns types. The code only works because the test inverts the condition, and reads <code>!=</code> when the intention is for the type to <code>==</code> a string. The correct test would be closer to <code>if isinstance(ver_str, str):</code>, but again explicit type checking is an anti-pattern.</p>\n\n<p>Without the explicit type checking, and using a more functional approach, the constructor could be written as a one line method. As a side-effect of the deconstruction assignment, the version string must contain exactly 4 parts or an exception will be raised.</p>\n\n<pre><code>def __init__(self, ver_str):\n self.Major, self.Minor, self.Patch, self.Build = map(int, ver_str.split('.'))\n</code></pre>\n\n<hr>\n\n<p><code>printme()</code> is unused and could be deleted. If you don’t wish to delete it, at least name it using snake_case to make it more readable: <code>print_me()</code>. You could write the function as simply <code>print(repr(self))</code> to avoid duplicating code.</p>\n\n<hr>\n\n<p><code>__repr__(self)</code> should actually return a string like <code>Version(\"1.2.3.4\")</code>, not the string <code>\"1.2.3.4\"</code> to conform to the <code>repr()</code> contract. What you have written would make a great <code>__str__(self)</code> method though, and you could then implement <code>__repr__(self)</code> using the <code>str()</code> method.</p>\n\n<hr>\n\n<p>Inside <code>def main(...):</code>, you are using <code>argv</code>. This is a different <code>argv</code>, shadowing the one you import from <code>sys</code> using <code>from sys import argv</code>.</p>\n\n<p>You should avoid shadowing the imported name, by using:</p>\n\n<pre><code>import sys\n\n# ....\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n\n<hr>\n\n<p>There is no need to <code>exit(-1)</code> from <code>main()</code>, since the program will terminate anyway immediately. <code>exit()</code> will terminate the Python interpreter, which can be unexpected, and can cause resources to not be properly closed. A unit test framework will abruptly terminate, preventing recording of the test results, and preventing other unit tests from running. In short, don’t ever use <code>exit()</code>. Ever.</p>\n\n<hr>\n\n<p>Since you are explicitly writing for Python 3.7.0, you can use f-strings. This means you can replace many of your <code>.format(...)</code> calls with a more compact, readable representation where the substitution location and value are combined. Ie:</p>\n\n<pre><code> print(\"{} < {}: {}\".format(ver_1, ver_2, ver_1 < ver_2))\n</code></pre>\n\n<p>could become simply:</p>\n\n<pre><code> print(f\"{ver_1} < {ver_2}: {ver_1 < ver_2}\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:26:44.370",
"Id": "423057",
"Score": "2",
"body": "The `type(ver_str)` check is even more bizarre, when you consider that `type('1.2.3.4') == 'string'` if `False`. I have no idea what that check in the initializer is intended to accomplish."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:33:07.570",
"Id": "423059",
"Score": "0",
"body": "@200_success Wow. I knew the explicit type-checking was bad, but I totally missed that it was outright wrong."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T05:41:31.903",
"Id": "218995",
"ParentId": "217992",
"Score": "6"
}
},
{
"body": "<p>Python tuples already sort the way you want to, so you can replace your class with just a thin wrapper around the built-in <code>tuple</code> class. You only need a constructor that can parse a string of the form <code>\"3.1.0.2\"</code> into a tuple of ints and a nice representation as a version string:</p>\n\n<pre><code>class VersionTuple(tuple):\n def __new__(cls, s):\n return super().__new__(cls, map(int, s.split(\".\")))\n\n def __repr__(self):\n return \".\".join(map(str, self))\n</code></pre>\n\n<p>Note that this does not restrict the number of arguments to include a major, minor, patch and build version. If you want that, you can instead inherit from a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>collections.namedtuple</code></a>:</p>\n\n<pre><code>from collections import namedtuple\n\nclass VersionTuple(namedtuple(\"VersionTuple\", \"major minor patch build\")):\n def __new__(cls, s):\n return super().__new__(cls, *map(int, s.split(\".\")))\n\n def __repr__(self):\n return \".\".join(map(str, self))\n</code></pre>\n\n<hr>\n\n<p>Both work the same way with respect to comparisons (you even get the equality operator for free):</p>\n\n<pre><code>VersionTuple(\"3.1.0.0\") < VersionTuple(\"3.1.2.0\")\n# True\nVersionTuple(\"1.0.0.0\") > VersionTuple(\"3.1.2.0\")\n# False\nVersionTuple(\"1.0.0.0\") == VersionTuple(\"1.0.0.0\")\n# True\n</code></pre>\n\n<p>And printing:</p>\n\n<pre><code>print(VersionTuple(\"3.6.3.0\"))\n# 3.6.3.0\n</code></pre>\n\n<p>While the latter allows you to also access the individual parts:</p>\n\n<pre><code>VersionTuple(\"3.6.3.0\").patch\n# 3\n</code></pre>\n\n<p>It also raises a <code>TypeError</code> if the version string does not contain four parts:</p>\n\n<pre><code>VersionTuple(\"3.6.3\")\n# ...\n# TypeError: __new__() missing 1 required positional argument: 'build'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:36:30.800",
"Id": "219025",
"ParentId": "217992",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "218995",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:21:25.600",
"Id": "217992",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Compare two version numbers in the form Major.Minor.Patch.Build to see if one is less than or greater than the other"
} | 217992 |
<p>This is what I've come up with for a class that handles parsing AWS Textract output. So far it only gets the AWS Textract output into a .txt file.</p>
<pre><code>import json
import logging as log
import os
import sys
import subprocess
import time
log.basicConfig(
format='%(asctime)s [%(levelname)s]: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=log.DEBUG,
handlers=[
log.StreamHandler(),
log.FileHandler('{}.log'.format(__name__))
]
)
class InitialParser:
def __init__(self, filename, s3_bucket, version=1):
self.filename = filename
self.s3_bucket = s3_bucket
self.version = version
self.file = None
self.filepath = None
self.data = None
self.output_filename = self.filename.replace('.pdf', '.txt')
def run(self):
log.info('Running initial parser on file {}'.format(self.filename))
if self.run_textract():
log.info('Textract process successful')
else:
log.info('Textract process failed, exiting')
sys.exit(0)
def load_file_data(self):
self.filepath = os.path.join(os.getcwd(), '../extracted/{}'.format(filename))
try:
with open(self.filepath, 'r') as file:
self.file = file
self.data = json.load(file)
except FileNotFoundError as e:
log.error('Could not find parsing file: {}'.format(e))
def run_textract(self):
"""
Runs AWS Textract commands on the given document and sends the output
to a .txt file.
@param s3_bucket: the S3 Bucket where the document is located.
"""
job_id = ''
# note: adding "Version":<str> to the AWS object below breaks the command
aws_object = json.dumps({"S3Object":{"Bucket":self.s3_bucket,"Name":self.filename}}).replace(' ', '') # can't have any spaces lol picky AWS CLI
start_textract_command = "aws textract start-document-text-detection --document-location '{}'".format(aws_object)
get_textract_output_command = 'aws textract get-document-text-detection --job-id '
try:
job_id = '"{}"'.format(json.loads(subprocess.check_output([start_textract_command], shell=True, stderr=subprocess.STDOUT).decode('utf-8'))['JobId'])
except subprocess.CalledProcessError as e:
if 'InvalidS3ObjectException' in e.output.decode('utf-8'):
log.error('InvalidS3ObjectException (could not fetch object metadata from S3).\n Check the document name, AWS CLI configuration region (run `aws configure list`), permissions, and the S3 Bucket name & region.')
elif 'ProvisionedThroughputExceededException' in e.output.decode('utf-8'):
log.error('ProvisionedThroughputExceededException (provisioned rate exceeded). You\'re doing that too much.')
else:
log.error('Starting Textract failed. Error: {}'.format(e.output.decode('utf-8')))
time.sleep(10) # wait for Textract to do its' thing
if job_id != '':
try:
subprocess.call(['touch {}'.format(self.output_filename)], shell=True)
subprocess.call(['{} > {}'.format(get_textract_output_command+job_id, self.output_filename)], shell=True, stderr=subprocess.STDOUT)
return True
except subprocess.CalledProcessError as e:
log.error(e.output)
else:
return False
if __name__ == '__main__':
initial_parser = InitialParser(
filename='test1.pdf',
s3_bucket='test-bucket',
)
initial_parser.run()
</code></pre>
<p>I'd like a better way of handling the wait period for Textract to finish other than waiting 10 seconds, and it may take longer than that in some instances.</p>
<p>I do know that the output file will have <code>"JobStatus": "IN PROGRESS"</code> so I could repeatedly search the output .txt file for "SUCCEEDED", but that could be slow if the file has 40,000+ lines when it's actually done (it will)</p>
| [] | [
{
"body": "<pre><code>aws_object = json.dumps({\"S3Object\":{\"Bucket\":self.s3_bucket,\"Name\":self.filename}}).replace(' ', '') # can't have any spaces lol picky AWS CLI\nstart_textract_command = \"aws textract start-document-text-detection --document-location '{}'\".format(aws_object)\n</code></pre>\n\n<p>This is not AWS which is picky, rather you’re not building the command line properly. If you provide a single string and start your <code>subprocess</code> using <code>shell=True</code>, each space will mark a new argument. Instead, you’d be better off building a list of arguments and let <code>subprocess</code> quote them properly:</p>\n\n<pre><code>start_textract_command = ['aws', 'textract', 'start-document-text-detection', '--document-location', json.dumps(…)]\n</code></pre>\n\n<p>and then just run <code>subprocess.check_output(start_textract_command, stderr=subprocess.STDOUT)</code>.</p>\n\n<p>Speaking of which, instead of using the <a href=\"https://docs.python.org/3/library/subprocess.html#older-high-level-api\" rel=\"nofollow noreferrer\">older high level API</a>, you should switch to <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"nofollow noreferrer\"><code>subprocess.run</code></a>:</p>\n\n<pre><code>process = subprocess.run(start_textract_command, capture_output=True, encoding='utf-8')\ntry:\n process.check_returncode()\nexcept CalledProcessError:\n if 'InvalidS3ObjectException' in process.stderr:\n …\nelse:\n job_id = json.loads(process.stdout)['JobId']\n with open(self.output_filename, 'wb') as output_file:\n process = subprocess.run(['aws', 'textract', 'get-document-text-detection', '--job-id', str(job_id)], stdout=output_file, stderr=subprocess.PIPE)\n if process.returncode:\n log.error(process.stderr.decode('utf-8'))\n</code></pre>\n\n<hr>\n\n<p>Now for the <code>time.sleep</code> part, <a href=\"https://docs.aws.amazon.com/textract/latest/dg/how-it-works.html\" rel=\"nofollow noreferrer\">AWS Textract provides two modes of operations</a>: synchronous and asynchronous. You can start by using the synchronous <a href=\"https://docs.aws.amazon.com/textract/latest/dg/API_DetectDocumentText.html\" rel=\"nofollow noreferrer\"><code>detect-document-text</code></a> operation if it fits your need and you won't have to deal with the timing at all.</p>\n\n<p>Otherwise, if you need to stick to <a href=\"https://docs.aws.amazon.com/textract/latest/dg/API_StartDocumentTextDetection.html\" rel=\"nofollow noreferrer\"><code>start-document-text-detection</code></a>, the completion of the process is published as a notification. I’m not at all versed in how SNS works but they have <a href=\"https://docs.aws.amazon.com/sns/latest/dg/sns-tutorials.html\" rel=\"nofollow noreferrer\">a tutorial to get you started on using Amazon SNS</a> so you can create a channel, specify it in your textract job and wait for the completion event.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:07:23.880",
"Id": "422990",
"Score": "0",
"body": "thanks for the tips, this really cleans up the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:56:06.850",
"Id": "423013",
"Score": "0",
"body": "just wanted to add that the `capture_output` arg for `subprocess.run` does not exist in Python 3.6.X and using `stdout=subprocess.PIPE` will accomplish the same thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:31:28.537",
"Id": "423058",
"Score": "0",
"body": "@star_trac You should also add `stderr=PIPE`, to account for the error case as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:48:15.013",
"Id": "219011",
"ParentId": "217993",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:36:09.797",
"Id": "217993",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"amazon-web-services"
],
"Title": "Running AWS commands works ok, but the code seems messy and I don't like the time.sleep bit"
} | 217993 |
<p>I am implementing a method to find the median of an unsorted array using a counting sort. I would happily go for a median of medians or selection algorithm for better performance but they are essentially sorting the array (or partially sorting the array if I choose to go for minHeap) which I am not in favor of.</p>
<pre><code>int getRange(int *array, int count)
{
int i, max = 0;
for(i = 0; i < count; i++)
{
if(array[i] > max)
{
max = array[i];
}
}
return max;
}
int countFreq(int *array, int size_array, int item)
{
int i, freq = 0;
for(i = 0; i < size_array; i++)
{
if(array[i] == item)
freq++;
}
return freq;
}
int median(int *array, int count)
{
int range = getRange(array, count);
int i, mid_index, addition = 0;
//Yes I can use calloc here
int *freq = (int *)malloc(sizeof(int) * range + 1);
memset(freq, 0, sizeof(int)* range + 1);
for(i = 0; i < range + 1; i++)
{
//Count i in array and insert at freq[i]
freq[i] = countFreq(array, count, i);
}
if(count % 2 == 0)
{
mid_index = count / 2;
}
else
{
mid_index = count / 2 + 1;
}
for(i = 0; i < range + 1; i++)
{
addition += freq[i];
if(addition >= mid_index)
{
break;
}
}
free(freq);
return i;
}
</code></pre>
<p>I followed <a href="https://qr.ae/TWp52Y" rel="noreferrer">this</a> answer to implement using C! Certainly, I want to improve upon this or maybe a better algorithm that doesn't sort the array! For me, this algorithm has some problems</p>
<ol>
<li><p>What if there are just 2 elements say {10, 10000}, this will still go on for creating an array of size 10000 which essentially has zeros in it except at the last index! </p></li>
<li><p>I find it hard to digest the performance of this algorithm with larger arrays to sort, for now, this is O(n<sup>3</sup>) as far as I can think of.</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T07:35:30.687",
"Id": "422947",
"Score": "0",
"body": "There are two reasons I see to reject quickselect: 1) code/algorithmic complexity 2) O(n) memory *or* modification of the input. If the input can be inspected more than once, there are a number of procedures promising O(nlogn) time using little (additional) memory. So you want a *code review* of your *counting sort & median determination* code, and no suggestions modifying input or using substantial additional memory? How about O(nlogn) time, O(logn) space?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T16:29:01.000",
"Id": "423042",
"Score": "0",
"body": "I would surely enjoy an algorithm with O(nlog(n)) but considering the input array I am not very much in favor of using an auxiliary space O(n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:55:29.687",
"Id": "423272",
"Score": "0",
"body": "Just to keep a note, I was just mad at this, and how can such a simple problem does not have any efficient solution. Torben's Median Algorithm works charm, the main property of this algorithm is, \"Bigger the array gets, better the algorithm becomes\"! It dosen't sort the array. For odd number of elements, it returns the middle and for even it returns n/2 highest value. There is a slight improvement of this on github for even sized arrays to return actual median! Obviously it's better with O(log(N))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T05:42:26.473",
"Id": "423290",
"Score": "0",
"body": "What *is* `Torben's Median Algorithm`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:37:53.213",
"Id": "423335",
"Score": "0",
"body": "You can find the source code here http://ndevilla.free.fr/median/median/src/torben.c"
}
] | [
{
"body": "<p>If we never modify the elements of <code>array</code>, then it should be passed as a pointer to const: <code>int const *array</code>.</p>\n\n<p>The frequency counts can be unsigned, and ought to be able to represent any size of input array (that suggests that <code>count</code> should be a <code>size_t</code>).</p>\n\n<p>We absolutely <em>must</em> test that the return value of <code>malloc()</code> (and family) is not null before trying to dereference it (including passing it to <code>memset()</code>). Additionally, it's not necessary or desirable to cast it to the target type:</p>\n\n<pre><code>size_t *freq = calloc(sizeof *freq, range + 1);\nif (!freq) {\n fputs(\"Memory allocation failed!\\n\", stderr);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>The algorithm has undefined behaviour if any element in the array is less than zero. We need to find the minimum as well as maximum value, or perhaps change the input to be an unsigned type.</p>\n\n<p>The counting is strange, with the nested loop. Normally, we'd loop just once, incrementing the index for each element we look at - something like this:</p>\n\n<pre><code>for (int i = 0; i < count; ++i) {\n ++freq[array[i]];\n}\n</code></pre>\n\n<p>To avoid excessive temporary memory use for the count array, we could use a multi-pass approach.</p>\n\n<ul>\n<li>Divide the range [min,max] into into (say) 256 buckets.</li>\n<li>Count the inputs into those buckets.</li>\n<li>Identify the median bucket. Call that <em>M</em>.</li>\n<li>Now divide the range represented by <em>M</em> into buckets.</li>\n<li>Make another pass over the inputs, counting values within <em>M</em> into these new buckets (discarding values not in <em>M</em>).</li>\n<li>Repeat until the bucket size is 1.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T16:32:10.193",
"Id": "423045",
"Score": "0",
"body": "Wow! This significantly reduces the time required! Is that O(n)? I used Torben's method earlier which is O(log(N)) but this is even faster and much faster indeed! Can you throw some light on time complexity? I just changed the way to create a frequency array, did not incorporate any changes related to excessive temporary memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:14:40.120",
"Id": "423052",
"Score": "1",
"body": "You should be able to reason about the complexity yourself - it looks to me that it should be O(_n_) in time and O(max) in space. The multi-pass approach trades time for space: O(_n_ log _n_) and O(1) respectively."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:13:46.260",
"Id": "219013",
"ParentId": "217994",
"Score": "7"
}
},
{
"body": "<p>I like @toby-speight's answer (and have up-voted). He's reviewed your code. \nHere's the result of scratching my head for an hour while driving home FWIW.<br>\nOne up-side is it should deal with all ints.<br>\nTemporary (working) storage requirement is O(1).<br>\nTime complexity obviously a lot worse - I estimate ~O(nlog n) but haven't put too much thought into it.\nE&OE.</p>\n\n<pre><code>/* THE APPROACH\n * ************\n * This is not exactly a code review, but an algorithm suggestion\n * Based on trading off between\n * (i) O(n) intermediate storage (for counts) and\n * (ii) reducing storage at the cost of increasing time-complexity\n * Obviously I'm going down rabbit hole (ii) (given points 1 & 2 following your code)\n * Thought process something like this...\n * - Not allowed to sort\n * - Can't keep counts\n * - How to search?\n * - Need max and min entries, costing 1 pass over the array (count n)\n * - Worst-case search is binary \"chop\", costing O(log n) PASSES (O(n log n) (hope I've got that thumb-thuck right;-)\n * - Improvement maybe possible... let's see how we go\n * - Note adopted definition: median of 1,2,3,4 (even number of data points) is (2+3)/2\n*/\n\n#include <iostream>\n#include <vector>\n#include <climits>\n\nsize_t nPasses = 0;\n\nvoid FindMinMax(const std::vector<int>& rgint, int& min, int& max)\n{\n min = max = rgint[0];\n for (auto i : rgint)\n {\n if (i < min) \n min = i;\n else if (i > max) \n max = i;\n }\n}\n\nstruct DataPointInfo\n{\n double Value{};\n int low{};\n int high{};\n int nearestBelow = INT_MIN;\n int nearestAbove = INT_MAX;\n size_t countBelow = 0;\n size_t countEqual = 0;\n size_t countAbove = 0;\n};\n\nvoid AboveBelow(const std::vector<int>& rgint, DataPointInfo* pguess)\n{\n pguess->countAbove = pguess->countBelow = pguess->countEqual = 0;\n pguess->nearestBelow = INT_MIN;\n pguess->nearestAbove = INT_MAX;\n for (auto i : rgint)\n {\n if (pguess->Value > i)\n {\n pguess->countBelow++;\n if (i > pguess->nearestBelow) \n pguess->nearestBelow = i;\n }\n else if (pguess->Value < i)\n {\n pguess->countAbove++;\n if (i < pguess->nearestAbove) \n pguess->nearestAbove = i;\n }\n else pguess->countEqual++;\n }\n}\n\ndouble FindMedian(const std::vector<int>& rgint)\n{\n int min, max;\n FindMinMax(rgint, min, max);\n nPasses++;\n DataPointInfo dpi{ (static_cast<double>(min) + max) / 2, min, max };\n do\n {\n AboveBelow(rgint, &dpi);\n nPasses++;\n if (dpi.countBelow <= dpi.countAbove + dpi.countEqual && dpi.countBelow + dpi.countEqual >= dpi.countAbove) \n return dpi.countEqual > 0 ? dpi.Value : (static_cast<double>(dpi.nearestBelow) + dpi.nearestAbove) / 2; // found\n if (dpi.countBelow < dpi.countAbove) // must be \"to the right\"\n dpi.low = dpi.nearestAbove;\n else // must be \"to the left\"\n dpi.high = dpi.nearestBelow;\n dpi.Value = (static_cast<double>(dpi.low) + dpi.high) / 2;\n } while (true);\n}\n\nint main()\n{\n const std::vector<int> testData{ 1,2,3,8,3,2,3,5,0,1,2,7,6,5,4,2,3,4,5,9 };\n double median = FindMedian(testData);\n std::cout << median << \" found in \" << nPasses << \" passes over the dataset\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:20:58.637",
"Id": "423117",
"Score": "0",
"body": "(Nits: 1) in `AboveBelow()`, you take advantage of `pguess->Value > i` excluding `< i`: in `FindMinMax()`, initialise `min` & `max` to the first element of `rgint` to do the same. 2) in `AboveBelow()`, `tol` id unused 3) `<climits>` 4) whence `round()`?) In `FindMedian`, I'd expect `below <= above + equal && above <= below + equal` to cause less problems (median of [1, 2, 3])."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:25:04.200",
"Id": "423230",
"Score": "0",
"body": "Thanks @greybeard. Keen eye and points well made - except for 3)... How/why should <climits> (not) be used? (Not doubting, in need of educating;-) All others items accepted and code updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:17:39.337",
"Id": "423239",
"Score": "0",
"body": "I'm no expert in C++ standards. The online environment I used to tinker with the code presented complained about `INT_MIN`/`MAX` without `<climits>` - way back when those appeared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:38:53.227",
"Id": "423336",
"Score": "0",
"body": "I tried it with random array and I feel it gets stuck in an infinite loop for some inputs. I'll figure out the cases and will post it here"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T21:39:22.537",
"Id": "219048",
"ParentId": "217994",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219013",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T23:38:58.413",
"Id": "217994",
"Score": "6",
"Tags": [
"algorithm",
"c",
"statistics"
],
"Title": "Finding median from unsorted array with duplicate elements without sorting it"
} | 217994 |
<p>I have the following <code>DAOParent</code> class that I use to put connect/disconnect code in one place. Each <code>DAO</code> class in the application is an <code>EJB</code> that extends <code>DAOParent</code> (note that I don't use <code>JPA</code>):</p>
<pre><code>public class DAOParent {
private InitialContext context = null;
private DataSource ds = null;
private Connection conn = null;
protected Connection getConnFromPool(String pool) throws DAOException {
try {
context = new InitialContext();
ds = (DataSource)context.lookup(pool);
conn = ds.getConnection();
return conn;
}
catch (NamingException e) {
throw new DAOException(e.getMessage());
}
catch (SQLException e) {
throw new DAOException(e.getMessage());
}
}
protected void releaseConn() {
try {
if (conn != null)
conn.close();
}
catch (SQLException e) {}
try {
if (context != null)
context.close();
}
catch (NamingException e) {}
}
}
</code></pre>
<p>And the <code>DAO</code> class:</p>
<pre><code>@Stateless
public class DAOChild extends DAOParent {
public void someMethod() throws DAOException {
Connection conn = getConnFromPool("some/jndi/path");
try {
// use the connection
}
finally {
releaseConn();
}
}
}
</code></pre>
<p>The <code>DAOChild</code> class is then injected in an <code>EJB</code> to access the data.</p>
<p>Questions: (1) is there a problem with this approach? (2) If I have <code>DAOChild1</code> and <code>DAOChild2</code> injected in the same <code>EJB</code>, is there a conflict in the connection lookup?</p>
<p>I run this on Wildfly 14 application server/container.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T02:41:17.857",
"Id": "218991",
"Score": "2",
"Tags": [
"java"
],
"Title": "Having single DAO parent class in an EJB application"
} | 218991 |
<p>I have answered a Question in Stackoverflow <a href="https://stackoverflow.com/questions/55804715/homework-c-problem-involving-arrays-pointers-and-functions">link</a>.</p>
<blockquote>
<p>a) Create a function called resize that can be used to increase the
size of integer arrays dynamically. The function takes three
parameters. The first parameter is the original array, the second
parameter is the size of this array, and the third parameter is the
size of the larger array to be created by this function. Make sure
that you allocate memory from the heap inside this function. After
allocating memory for the second array the function must copy the
elements from the first array into the larger array. Finally, the
function must return a pointer to the new array.</p>
<p>b. In main, allocate an array on the heap that is just large enough to
store the integers 5, 7, 3, and 1.</p>
<p>c. Resize the array to store 10 integers by calling the resize
function created in step a. Remove the old (smaller) array from the
heap. Add the numbers 4, 2, and 8 to the end of the new array.</p>
<p>d. Write a sort function that sorts any integer array in increasing
order.</p>
<p>e. Use the sort function to sort the array of numbers in c above.
Display the sorted numbers.</p>
</blockquote>
<p>Is there a Dangling pointer issue.</p>
<pre><code>#include <array>
#include <iostream>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
//Bubble Sort
bool sort(int arr[], int size)
{
for( int i = 0; i< size -1; i++)
{
for( int j = 0; j < size - i -1; j++)
{
//descending order
if(arr[j]<arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
return true;
}
void Print(int Array[], int nSize)
{
for( int i = 0; i < nSize; i++)
{
std::cout<<" "<<Array[i];
}
std::cout<<"\n";
}
void Resize( int *&Array, const int& nSizeOld, const int& nSize )
{
int * newArray = new int[nSize];
//Copy Elements of the Array
for(int i = 0; i< nSize; i++)
{
newArray[i] = Array[i];
}
delete[] Array;
//Assign ptr of Prev to new Array
Array = newArray;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int kNewSize = 10, kSize = 5;
int *pMyArray = new int[kSize];
//Set Values
for( int i = 0; i< kSize; ++i )
{
pMyArray[i] = i * 5;
}
Resize( pMyArray, kSize, kNewSize );
//Set Values
for( int i = kSize; i< kNewSize; ++i )
{
pMyArray[i] = i * 10;
}
Print(pMyArray, kNewSize);
sort(pMyArray, kNewSize);
Print(pMyArray, kNewSize);
if( pMyArray!=NULL )
{
delete[] pMyArray;
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:56:39.903",
"Id": "422978",
"Score": "1",
"body": "As Roland Illig points out below, in C++ there's no need to implement your own low level memory management for this when you can just use `std::vector` instead. That said, if you _do_ need/want to implement your own low level array resizing, you should be using [`std::realloc()`](https://en.cppreference.com/w/cpp/memory/c/realloc). The reference page I linked to even provides some (to my inexpert eye) decent example code."
}
] | [
{
"body": "<p>If you had tagged this code as C, it would have been acceptable. Since you tagged it as C++, it's horrible.</p>\n\n<p>Instead of writing your own <code>swap</code> function, there's already <code>std::swap</code> in <code><algorithm></code>.</p>\n\n<p>Instead of writing bubble sort yourself, just use <code>std::sort</code>, also from <code><algorithm></code>.</p>\n\n<p>Instead of using arrays and resizing them yourself, just use <code>std::vector<int></code>, from <code><vector></code>.</p>\n\n<p>After applying these transformations, you cannot have a dangling pointer anymore since your code is completely pointer-free.</p>\n\n<p>As part of an exercise for learning the basic operations on memory management, it's ok to write code like this, but never ever use such code in production. In production the code should look like this:</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <vector>\n\nvoid Print(const std::vector<int> &nums)\n{\n for(int num : nums)\n {\n std::cout << \" \" << num;\n }\n std::cout << \"\\n\";\n}\n\nint main()\n{\n std::vector<int> nums { 5, 7, 3, 1 };\n\n // There's probably a more elegant way to add the elements to the vector.\n nums.push_back(4);\n nums.push_back(2);\n nums.push_back(8);\n\n std::sort(nums.begin(), nums.end());\n\n Print(nums);\n}\n</code></pre>\n\n<p>By the way, your original code doesn't have any dangling pointer as well. Well done.</p>\n\n<p>You don't need the <code>!= NULL</code> check before the <code>delete[]</code> since that pointer cannot be null. In modern C++ (since C++11 I think) you would also write <code>nullptr</code> instead of <code>NULL</code>. The reason is that historically <code>NULL</code> had not been guaranteed to be of pointer type.</p>\n\n<p>Have a look at <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/algorithm</a> for more algorithms that you shouldn't implement yourself in C++.</p>\n\n<p>I would have liked to write the <code>push_back</code> block in a shorter way, as well as the <code>Print</code> function. I'm sure there's a more elegant way, I just don't know it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:45:49.750",
"Id": "422975",
"Score": "0",
"body": "I would just stream char-literals instead of length-one string-literals. And [cppreference.com](https://en.cppreference.com/w/cpp/algorithm) is inho a better reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T18:33:10.867",
"Id": "423068",
"Score": "0",
"body": "@Deduplicator I changed the link, thanks for the hint. Regarding the single characters: shouldn't the compiler produce exactly the same code for these two variants by detecting the length 1 string? I thought this was possible in C++. I like code that is as uniform as possible, and using string literals for anything string-like seems simple and nice to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T19:15:26.177",
"Id": "423076",
"Score": "0",
"body": "The compiler could in theory inline enough layers to get the same code in the end using whole-program-analysis, necessary due to virtual functions called. I doubt it though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:57:22.840",
"Id": "423254",
"Score": "0",
"body": "\"You don't need the != NULL check before the delete[] since that pointer cannot be null\" The behaviour is identical anyway, as the `delete` and `delete[]` operators are both defined to be null safe (in which case they do nothing)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T06:19:55.017",
"Id": "218996",
"ParentId": "218994",
"Score": "18"
}
},
{
"body": "<p>The code is obviously wrong: your compiler should have warmed you that <code>Resize()</code> never uses its <code>nSizeOld</code> parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T06:58:01.290",
"Id": "422942",
"Score": "1",
"body": "That's a funny concept of \"wrong\"... Anyway, it was probably a typo, since it actually is needed; the question was edited accordingly. This answer is superfluous now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T07:09:11.763",
"Id": "422946",
"Score": "2",
"body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 2 → 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T08:11:49.060",
"Id": "422951",
"Score": "4",
"body": "If we follow those rules literally, to correct [what seems to me] a simple typo, OP should ask a completely new question with the fix. Seems kind of ridiculous for such a trivial matter... If every question followed that rule verbatim this site would me a mess. I'm not saying your comment isn't correct or helpful, but it should be precisely that, a comment, so that OP can fix the [irrelevant] issue and move on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:10:42.113",
"Id": "423050",
"Score": "2",
"body": "While your answer is correct and you made a good observation I'd contend that this type of error (a trivial bug) was not what the OP wanted to ask (it would, after all, be OT), so that it does not warrant an answer. I'd have written a comment and waited for the correction. You should imo reinstate the corrected version of the question and delete (or preface as obsolete) your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:17:31.733",
"Id": "423053",
"Score": "1",
"body": "@PeterA.Schneider As per the rules in the [help/on-topic], all aspects of the code are open to critique. This out-of-bounds memory access bug (which may or may not have been apparent to the author) is absolutely fair game for a Code Review answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T06:37:04.427",
"Id": "218997",
"ParentId": "218994",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Your code is too low-level. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p3-express-intent\" rel=\"nofollow noreferrer\">It expresses implementation details instead of intent.</a> That's why your code looks like \"C with <code>cout</code>s instead of <code>printf</code> and <code>new</code>/<code>delete</code> instead of <code>malloc</code>/<code>free</code>\" instead of C++.</p></li>\n<li><p><a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\"><strong>Roland Illig</strong></a> has already told you that you should use <code>std::swap</code> instead of building a new one from scratch. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p13-use-support-libraries-as-appropriate\" rel=\"nofollow noreferrer\">You should use existing libraries, especially the standard library, whenever possible.</a></p>\n\n<p>That said, your own implementation of <code>swap</code> is also questionable. This is C++, not C. We have <em>references</em>. Using <em>pointers</em> makes the code less readable, and puts burden on the user of the function. So you should change it to:</p>\n\n<pre>\nvoid swap(int& x, int& y)\n{\n int temp = x;\n x = y;\n y = temp;\n}\n</pre>\n\n<p>And the calls to it can be changed from <code>swap(&foo, &bar)</code> to <code>swap(foo, bar)</code>. Still, <code>std::swap</code> is preferable.</p></li>\n<li><p>Again, <a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\"><strong>Roland Illig</strong></a> has already told you that you should use the <code>std::sort</code> instead of building a new bubble sort from scratch. <code>std::sort</code> typically uses <a href=\"https://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">quicksort</a>, which has <span class=\"math-container\">\\$O(n \\log n)\\$</span> time complexity; whereas bubble sort has <span class=\"math-container\">\\$O(n^2)\\$</span> time complexity. It should be obvious that <code>std::sort</code> is much more efficient.</p></li>\n<li><p>Your parameter lists are <em>so</em> C-ish. (pointer, size) parameter pairs are everywhere. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f24-use-a-spant-or-a-span_pt-to-designate-a-half-open-sequence\" rel=\"nofollow noreferrer\">They are error-prone.</a> Consider using spans. (Spans are currently not available in the standard library; consider using the one from <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#gsl-guidelines-support-library\" rel=\"nofollow noreferrer\">GSL</a>)</p>\n\n<p>You even have parameter lists like <code>(int*& Array, const int& nSizeOld, const int& nSize)</code>. Don't pass by const reference for builtin types. Just pass by value, as in <code>int nSizeOld</code>, <code>int nSize</code>. And letting a pointer denote an array with sizes littered everywhere holds a great welcome party for errors. </p></li>\n<li><p>Don't use <code>_tmain</code> and <code>_TCHAR</code>. They are not portable. (Strictly speaking, they are not proper C++.) <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#p2-write-in-iso-standard-c\" rel=\"nofollow noreferrer\">You should write in ISO standard C++.</a> Use <code>main</code> and <code>char</code> instead.</p>\n\n<pre>\n// Correct prototype of the main function\nint main(int argc, char* argv[])\n{\n // ...\n}\n</pre></li>\n<li><p>Don't make such liberal use of \"naked\" <code>new</code>s and <code>delete</code>s. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly\" rel=\"nofollow noreferrer\">Explicit calls to <code>new</code>s and <code>delete</code>s are very error prone.</a> <code>std::vector</code>s should be preferred from the beginning.</p></li>\n<li><p>You have four <code>for</code> loops in total. The first three use <code>i++</code>, whereas the last one uses <code>++i</code>. Please consistently use <code>++i</code>.</p></li>\n</ol>\n\n<p>As a conclusion: you should refactor your code to express intent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:00:03.340",
"Id": "423729",
"Score": "0",
"body": "Thanks for the Review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T02:12:15.867",
"Id": "219225",
"ParentId": "218994",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "218996",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T05:33:11.237",
"Id": "218994",
"Score": "6",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "Array Dynamic resize in heap"
} | 218994 |
<p>My TableView consists of four cells (for blacklisting categories) with a boolean property (indicated with a checkmark) and another cell with a <code>UISwitch</code> embedded in it. My current controller is as follows:</p>
<pre><code>class TableViewController: UITableViewController {
var blacklisted = Set<Category>()
var flags = Set<String>()
@IBAction func toggle(_ sender: UISwitch) {
if (sender.isOn) {
print("if")
} else {
print("else")
}
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
self.dismiss(animated: true)
}
@IBAction func done(_ sender: UIBarButtonItem) {
ViewController.allowed = ViewController.allowed.subtracting(blacklisted)
ViewController.flags = ViewController.flags.union(flags)
print(ViewController.allowed)
print(ViewController.flags)
self.dismiss(animated: true)
}
var states = [PastState.UNSELECTED, PastState.UNSELECTED, PastState.UNSELECTED, PastState.UNSELECTED]
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath.section != 0) {
return
}
tableView.cellForRow(at: indexPath)?.accessoryType
= (states[indexPath.row] == PastState.SELECTED)
? .none
: .checkmark
switch (indexPath.row) {
case 0:
TableViewController.toggleItem(if: states[0], set: &flags, with: "nsfw")
break
case 1:
TableViewController.toggleItem(if: states[1], set: &flags, with: "religious", "political")
break
case 2:
TableViewController.toggleItem(if: states[2], set: &blacklisted, with: Category.Programming)
break
case 3:
TableViewController.toggleItem(if: states[3], set: &blacklisted, with: Category.Dark)
break
default: break
}
states[indexPath.row] = (states[indexPath.row] == PastState.SELECTED)
? PastState.UNSELECTED
: PastState.SELECTED
}
static func toggleItem<T: Hashable>(`if` state: PastState, set: inout Set<T>, with items: T...) {
if (state == PastState.UNSELECTED) {
for item in items {
set.insert(item)
}
} else {
for item in items {
set.remove(item)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
</code></pre>
<p>I've been told the code is <em>spaghetti code</em> and to separate the model, but I'm not quite too sure how.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T10:58:41.543",
"Id": "422968",
"Score": "0",
"body": "Could you make your question more specific?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T03:55:08.883",
"Id": "423577",
"Score": "0",
"body": "Richard, btw, if you’re new to Swift, consider a linter/formatter. See https://nshipster.com/swift-format/. I like [SwiftLint](https://github.com/realm/SwiftLint), which I integrate directly into Xcode (warnings show up right in Xcode, simplifying resolution). And [this is my `.swiftlint.yml`](https://gist.github.com/robertmryan/985cc48837d579c7268d11407f418a6a) that I use to tailor it to my personal programing needs, but you should feel free to tweak to your personal preferences. But tools like this can be especially helpful if you’re new to Swift and want to follow established conventions."
}
] | [
{
"body": "<p>There are quite a few issues here:</p>\n\n<ul>\n<li><p>In <code>switch</code> statement, you don’t need/want <code>break</code> statements. Unlike C languages, Swift <code>switch</code> statements don’t <code>fallthrough</code> by default. To use <code>break</code> where it is not needed is very unswifty.</p></li>\n<li><p>I’d make <code>toggleItem</code> an instance method.</p></li>\n<li><p>The properties of the <code>ViewController</code> should not be <code>static</code>.</p></li>\n<li><p>This table view controller should not be reaching into <code>ViewController</code> to update its properties, which tightly couples these two classes. We should strive for far looser coupling in our code.</p>\n\n<p>Admittedly, because <code>ViewController</code> is presenting <code>TableViewController</code>, the presenting view controller might go ahead and update properties in the presented view controller, in order to pass data to down the chain. But <code>TableViewController</code> should never be reaching back up the chain. That makes them too tightly coupled and only allows <code>TableViewController</code> to be called from that one view controller, whereas as your app grows, you might want to call it from elsewhere.</p>\n\n<p>The typical solution to achieve loose coupling is the delegate-protocol pattern. Presented view controllers should not updating properties in the presenting view controller, but rather it should only communicate back via its protocol. This allows us to use this presented view controller from wherever we want.</p></li>\n<li><p>If you’re going to have an early exit in <code>didSelectRowAt</code> (if section ≠ 0), all things being equal, you should prefer <code>guard</code> over <code>if</code>, as it makes the intent more clear (you see <code>guard</code> keyword and you immediately know “oh, this is an early exit for some edge case”). The compiler will also warn us if we accidentally forget to call <code>return</code>.</p></li>\n<li><p>In <code>if</code> statements, the use of parentheses around the test clause feels a bit unswifty. Consider:</p>\n\n<pre><code>if (state == PastState.UNSELECTED) {\n ... \n} else {\n ... \n}\n</code></pre>\n\n<p>Instead, I’d suggest:</p>\n\n<pre><code>if state == PastState.UNSELECTED {\n ... \n} else {\n ... \n}\n</code></pre></li>\n<li><p>In the case of an enumeration, I’d favor <code>switch</code> over <code>if</code>. Thus, instead of the above, I’d suggest:</p>\n\n<pre><code>switch state {\ncase PastState.UNSELECTED:\n ...\n\ncase PastState.SELECTED:\n ...\n}\n</code></pre>\n\n<p>This ensures that the test is exhaustive. It makes it easier to reason about the code at a glance. Plus, if you, for example, later add a <code>.NOTDETERMINED</code> enumeration, the compiler can warn you of all of the non-exhaustive <code>switch</code> statements, but if you use <code>if</code>-<code>else</code>, you have to manually pour through all of your code looking for this yourself.</p></li>\n<li><p>Because <code>PastState</code> is an enumeration, you can eliminate all of those redundant references to the enumeration name. E.g., using the previous example, you can say:</p>\n\n<pre><code>switch state {\ncase .UNSELECTED:\n ...\n\ncase .SELECTED:\n ...\n}\n</code></pre></li>\n<li><p>In your enumerations, you should use camelCase (start with lower case letter, only capitalize start of new word within the case name):</p>\n\n<pre><code>switch state {\ncase .unselected:\n ...\n\ncase .selected:\n ...\n}\n</code></pre>\n\n<p>Alternatively, just retire this enumeration altogether and just use a <code>[Bool]</code> property. Or, as shown at the end of this answer, if you use a view model, you might refactor this out completely.</p></li>\n<li><p>The <code>blacklisted</code> property is using an enumeration, which is good. But <code>flags</code> is using strings with values buried in the code. They both should be enumerations.</p></li>\n<li><p>The <code>done</code> method is subtracting <code>blacklisted</code> from the <code>ViewController</code>’s <code>allowed</code>. But what if you unselected a blacklisted item and needed to add it back to the <code>allowed</code>? The existing code won’t do that.</p>\n\n<p>The same issue applies for <code>ViewController.flags</code>, where you’re adding <code>flags</code>. But what if one was removed?</p></li>\n<li><p>You are setting the <code>accessoryView</code> based upon which flags/blacklisted values exist in these sets and toggle this based upon selecting a row. But you then have this <code>UISwitch</code>, too. You’d generally use either a <code>UISwitch</code> or the <code>accessoryView</code>, but not both. Pick one or the other. (In my demo, I’m going to retire <code>UISwitch</code>.)</p></li>\n<li><p>The references to <code>self.dismiss(...)</code> can be simplified to just <code>dismiss(...)</code>.</p></li>\n<li><p>The <code>didSelectRowAt</code> is:</p>\n\n<ul>\n<li>toggling the <code>indicatorView</code> based upon the old <code>state</code>;</li>\n<li>updating the <code>blacklist</code>/<code>flags</code> properties; and</li>\n<li>toggling the <code>state</code>.<br /> </li>\n</ul>\n\n<p>I would suggest that you simply want to toggle the state and then reload that row. Not only does it make this less fragile (you don’t have three different operations that you need to carefully coordinate), but it affords the opportunity to animate the change of the <code>indicatorView</code>.</p></li>\n<li><p>I would suggest grouping your view controller methods into extensions. For example, I find it nice to put <code>UITableViewDataSource</code> methods in one extension, <code>UITableViewDelegate</code> methods in another, <code>@IBAction</code> methods in another, etc. This makes it easy to visually identify/find relevant methods. This also allows you to collapse sections (e.g. <kbd>⌘</kbd>+<kbd>option</kbd>+<kbd>◀︎</kbd>) sections that you’re not currently working on, making it easy to focus on the work at hand. This, combined with use of the <code>MARK: -</code> designator makes navigation through your view controller easier.</p></li>\n<li><p>You’ve got an enumeration called <code>PastState</code>. But this is not the “past state”, but rather the current state as updated as the user proceeds with selecting/unselecting various options. So I might rename that <code>SelectedState</code> or something like that.</p>\n\n<p>Likewise, I might give <code>TableViewController</code> a name that indicates its purpose. E.g. maybe <code>AllowedContentViewController</code>.</p></li>\n<li><p>I find it confusing that the main view controller uses <code>allowed</code>, but the <code>TableViewController</code> uses <code>blacklisted</code> (which is presumably an inverted set of the aforementioned). I’d suggest using the same model in both view controllers. If <code>TableViewController</code> wants to invert it as part of its determination of what’s checked and what’s not, then it should do that.</p></li>\n<li><p>The most radical change I’m going to suggest is that you should completely remove the business logic from the view controller. The view controller should be handling the interface with the UIKit controls (the table view, the buttons, etc.), but all the logic about which <code>flags</code> and <code>Category</code> values is represented by which row, how you toggle them, etc., doesn’t belong here. You often put it in what I will call a “view model” (though this entity goes by different names)</p>\n\n<p>The virtue of this is two fold. First the view controller suddenly becomes something very concise and easy to understand. Second, when you get around to writing unit tests, you want to be able to test your business logic without worrying about UIKit stuff (which should be part of the UI tests, not the unit tests).</p></li>\n</ul>\n\n<p>So, pulling this all together, we end up with a view controller like this:</p>\n\n<pre><code>class AllowedContentViewController: UITableViewController {\n\n // properties set by presenting view controller\n\n weak var delegate: AllowedContentViewControllerDelegate?\n var allowed: Set<Category>!\n var flags: Set<Flag>!\n\n // properties used by this view controller\n\n private var viewModel: AllowedContentViewModel!\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n viewModel = AllowedContentViewModel(allowed: allowed, flags: flags)\n }\n\n}\n\n// MARK: - Actions\n\nextension AllowedContentViewController {\n @IBAction func cancel(_ sender: UIBarButtonItem) {\n dismiss(animated: true)\n }\n\n @IBAction func done(_ sender: UIBarButtonItem) {\n delegate?.allowedContentViewController(self, didUpdateAllowed: viewModel.allowed, flags: viewModel.flags)\n dismiss(animated: true)\n }\n}\n\n// MARK: - UITableViewDataSource\n\nextension AllowedContentViewController {\n // you didn't provide the following two, so I'll take a guess what that looked like\n\n override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return viewModel.numberOfRows()\n }\n\n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: \"Cell\", for: indexPath)\n\n cell.textLabel?.text = viewModel.text(for: indexPath.row)\n cell.accessoryType = viewModel.isSelected(row: indexPath.row) ? .checkmark : .none\n\n return cell\n }\n}\n\n// MARK: - UITableViewDelegate\n\nextension AllowedContentViewController {\n override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n guard indexPath.section == 0 else {\n return\n }\n\n viewModel.toggle(row: indexPath.row)\n tableView.reloadRows(at: [indexPath], with: .fade)\n }\n}\n</code></pre>\n\n<p>That references a protocol to which our presenting view controller will conform:</p>\n\n<pre><code>protocol AllowedContentViewControllerDelegate: class {\n func allowedContentViewController(_ viewController: AllowedContentViewController, didUpdateAllowed allowed: Set<Category>, flags: Set<Flag>)\n}\n</code></pre>\n\n<p>The presenting view controller would then do something like so:</p>\n\n<pre><code>class ViewController: UIViewController {\n\n var allowed = Set<Category>()\n var flags = Set<Flag>()\n\n override func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n if let destination = (segue.destination as? UINavigationController)?.topViewController as? AllowedContentViewController {\n destination.flags = flags\n destination.allowed = allowed\n destination.delegate = self\n }\n }\n}\n\nextension ViewController: AllowedContentViewControllerDelegate {\n func allowedContentViewController(_ viewController: AllowedContentViewController, didUpdateAllowed allowed: Set<Category>, flags: Set<Flag>) {\n self.allowed = allowed\n self.flags = flags\n }\n}\n</code></pre>\n\n<p>I obviously made an assumption here of how you presented this <code>AllowedContentViewController</code> (namely that you must have embedded it in a <code>UINavigationController</code>, based upon the presence of <code>dismiss</code> but that you also had <code>@IBAction</code>s with <code>UIBarButton</code>). Clearly, adjust the <code>prepare(for:sender:)</code> according to how you actually presented this table view controller.</p>\n\n<p>Anyway, above, the presenting view controller is responsible for passing data to this presented <code>AllowedContentViewController</code> and for responding to <code>AllowedContentViewControllerDelegate</code> delegate method that supplies the updated user preferences for what is allowed and what isn’t. This gets the <code>AllowedContentViewController</code> from ever having to reach into <code>ViewController</code> to retrieve/update properties itself. Now <code>AllowedContentViewController</code> can be used in any context you want.</p>\n\n<p>Finally, our view model has all the business logic that used to be in the <code>TableViewController</code>:</p>\n\n<pre><code>struct AllowedContentViewModel {\n var allowed: Set<Category>\n var flags: Set<Flag>\n\n func numberOfRows() -> Int {\n return 4\n }\n\n func isSelected(row: Int) -> Bool {\n switch row {\n case 0: return flags.contains(.nsfw)\n case 1: return flags.contains(.religious) && flags.contains(.political)\n case 2: return !allowed.contains(.programming)\n case 3: return !allowed.contains(.dark)\n default: fatalError(\"Unexpected row number\")\n }\n }\n\n private mutating func select(row: Int) {\n switch row {\n case 0: flags.insert(.nsfw)\n case 1: flags.insert(.religious); flags.insert(.political)\n case 2: allowed.remove(.programming)\n case 3: allowed.remove(.dark)\n default: fatalError(\"Unexpected row number\")\n }\n }\n\n private mutating func unselect(row: Int) {\n switch row {\n case 0: flags.remove(.nsfw)\n case 1: flags.remove(.religious); flags.remove(.political)\n case 2: allowed.insert(.programming)\n case 3: allowed.insert(.dark)\n default: fatalError(\"Unexpected row number\")\n }\n }\n\n mutating func toggle(row: Int) {\n if isSelected(row: row) {\n unselect(row: row)\n } else {\n select(row: row)\n }\n }\n\n func text(for row: Int) -> String {\n switch row {\n case 0: return NSLocalizedString(\"NSFW\", comment: \"Label\")\n case 1: return NSLocalizedString(\"Religious/political\", comment: \"Label\")\n case 2: return NSLocalizedString(\"Blacklisted Programming\", comment: \"Label\")\n case 3: return NSLocalizedString(\"Blacklisted Dark\", comment: \"Label\")\n default: fatalError(\"Unexpected row number\")\n }\n }\n}\n</code></pre>\n\n<p>We can, if we want, then write unit tests for this view model. For example:</p>\n\n<pre><code>class AllowedContentViewModelTests: XCTestCase {\n\n func testDefaultState() {\n let viewModel = AllowedContentViewModel(allowed: [], flags: [])\n\n XCTAssert(!viewModel.isSelected(row: 0))\n XCTAssert(!viewModel.isSelected(row: 1))\n XCTAssert(viewModel.isSelected(row: 2))\n XCTAssert(viewModel.isSelected(row: 3))\n }\n\n func testTogglingNsfw() {\n var viewModel = AllowedContentViewModel(allowed: [], flags: [.nsfw])\n\n XCTAssert(viewModel.isSelected(row: 0))\n\n viewModel.toggle(row: 0)\n\n XCTAssert(!viewModel.isSelected(row: 0))\n }\n\n}\n</code></pre>\n\n<p>See example at <a href=\"https://github.com/robertmryan/RefactoredViewController\" rel=\"nofollow noreferrer\">https://github.com/robertmryan/RefactoredViewController</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:10:53.987",
"Id": "219284",
"ParentId": "219002",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T08:33:05.943",
"Id": "219002",
"Score": "2",
"Tags": [
"swift",
"controller",
"user-interface"
],
"Title": "Table View Controller class in Swift"
} | 219002 |
<p>I'm a beginner when it comes to path finding, so I decided to write an as simple as possible (to me) A* algorithm to learn.</p>
<p>I looked up on internet the general idea and found some pseudo-code that I translated in Python.</p>
<p>What I'm most interested in is if I'm missing some edge case or not (I wrote tests for the situations I could come up with and it works), and about optimizations.</p>
<p>Specifically, I don't really like going through the <code>nodes</code> list basically two times at every cycle.</p>
<p>Limitations:</p>
<ul>
<li><p>it only checks four directions instead of eight. Maybe in the future I'll use this for a game with a grid, pac-man like, movement so I excluded diagonal direction.</p></li>
<li><p>The <code>found_in_list</code> part looks very clumsy to me, but I could not find a nicer way of skipping to the next node.</p></li>
</ul>
<p>I think it could be simpler, but I couldn't find how.</p>
<pre><code>from collections import defaultdict
class Node():
def __init__(self, position=None, parent=None):
if not position:
raise Exception("Position must be specified")
self.position = position
self.parent = parent
if (parent is None):
self.distance_from_start = 0
else:
self.distance_from_start = parent.distance_from_start + 1
self.distance_from_target = 0
self.cost = 0
def __eq__(self, other):
return self.position == other.position
def get_squared_distance(first, second):
squared_x_distance = (first.position[0] - second.position[0]) ** 2
squared_y_distance = (first.position[1] - second.position[1]) ** 2
return squared_x_distance + squared_y_distance
def get_path_from_node(node):
path = []
while node is not None:
path.append(node.position)
node = node.parent
return path[::-1]
def is_invalid_position(maze, node):
if (node.position[0] >= len(maze[0])):
return True
if (node.position[1] >= len(maze)):
return True
if (node.position[0] < 0):
return True
if (node.position[1] < 0):
return True
if (maze[node.position[1]][node.position[0]] != 0):
return True
return False
def astar(maze, start_position, end_position):
start_node = Node(start_position)
end_node = Node(end_position)
nodes = [start_node]
visited_nodes = defaultdict(bool)
while len(nodes) > 0:
current_index = 0
for index in range(len(nodes)):
if nodes[index].cost < nodes[current_index].cost:
current_index = index
current_node = nodes[current_index]
visited_nodes[current_node.position] = True
nodes.pop(current_index)
if current_node == end_node:
return get_path_from_node(current_node)
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
new_node = Node(node_position, current_node)
if (is_invalid_position(maze, new_node)):
continue
if (visited_nodes[new_node.position]):
continue
new_node.distance_from_target = get_squared_distance(new_node, end_node)
new_node.cost = new_node.distance_from_start + new_node.distance_from_target
found_in_list = False
for node in nodes:
if new_node == node and new_node.distance_from_start > node.distance_from_start:
found_in_list = True
break
if (found_in_list):
continue
nodes.append(new_node)
return []
</code></pre>
<p>EDIT: an example usage</p>
<pre><code>def main():
maze = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = (0, 0)
end = (7, 6)
path = astar(maze, start, end)
print(path)
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:05:15.210",
"Id": "422969",
"Score": "1",
"body": "`return []`? Is this finished and tested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:25:01.230",
"Id": "422971",
"Score": "0",
"body": "If there is no path the `while len(nodes) > 0:` will end, and return an empty path. If there is a path, it will `return get_path_from_node(current_node)`. You could say it's better to return `None` in that case instead of `[]` but other than that I don't see the problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:29:10.750",
"Id": "422972",
"Score": "0",
"body": "I overlooked the early return. My bad."
}
] | [
{
"body": "<p>Instead of a visited_nodes list you can replace it with a position to node dictionary. That way you can get the old node with <code>node = known_nodes[node_position]</code> (if not present create new one). Then you can add a boolean <code>seen</code> to the node and use that to bail out the inner loop.</p>\n\n<p>Keeping the list mostly sorted using a heap helps, though you still need to look for the updated nodes in the array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T11:38:38.157",
"Id": "219010",
"ParentId": "219006",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code>def is_invalid_position(maze, node):\n</code></pre>\n</blockquote>\n\n<p>Why <code>node</code>? The only things used by this method are <code>maze</code> and <code>node.position</code>, so to me it would make more sense to take those as parameters.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> found_in_list = False\n for node in nodes:\n if new_node == node and new_node.distance_from_start > node.distance_from_start:\n found_in_list = True\n break\n\n if (found_in_list):\n continue\n nodes.append(new_node)\n</code></pre>\n</blockquote>\n\n<p>Surely if you find a shorter route to the same position you want to <em>replace</em> the previous node, not just append a new one to the list?</p>\n\n<p>Well, actually it's better to use <code>dict</code> from position to <code>Node</code> and then to update the existing node, for a simple reason:</p>\n\n<blockquote>\n<pre><code> new_node = Node(node_position, current_node)\n if (is_invalid_position(maze, new_node)):\n continue\n\n if (visited_nodes[new_node.position]):\n continue\n\n new_node.distance_from_target = get_squared_distance(new_node, end_node)\n new_node.cost = new_node.distance_from_start + new_node.distance_from_target\n</code></pre>\n</blockquote>\n\n<p>calculates <code>get_squared_distance</code> every time the node is seen. The heuristic shouldn't change, and could potentially be a lot more expensive, so it makes sense to calculate it only the first time and then to essentially cache it in the node.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> while len(nodes) > 0:\n ...\n\n if current_node == end_node:\n return get_path_from_node(current_node)\n\n ...\n\n return []\n</code></pre>\n</blockquote>\n\n<p>As evidenced by the comments on the question, a comment in the code along the lines of \"No route exists\" to explain the sentinel return value would help.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> current_index = 0\n for index in range(len(nodes)):\n if nodes[index].cost < nodes[current_index].cost:\n current_index = index\n</code></pre>\n</blockquote>\n\n<p>is horribly slow. Since the graph is unweighted you can implement a very nice heap using an array of <code>set</code>. You'll probably have to implement <code>__hash__</code>, but I expect that best practices call for doing that whenever you implement <code>__eq__</code> anyway.</p>\n\n<hr>\n\n<p>To me this looks too tightly composed. A* is a graph algorithm for general graphs. This implementation hard-codes a grid graph for which A* is unnecessary: you can find the shortest path by just changing one coordinate in single steps until it matches, and then changing the other in the same way.</p>\n\n<p>It's also inconsistently OO. If <code>Node</code> is worthy of a class, surely <code>Maze</code> is too? I would prefer to see an implementation which works for a general graph and an implementation of a grid graph with its neighbourhood rules and heuristic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:19:19.297",
"Id": "422982",
"Score": "0",
"body": "Thank you for your suggestions. I don't understand what you mean by `you can find the shortest path by just changing one coordinate in single steps until it matches, and then changing the other in the same way`. Do you mean moving horizontally until the start `x` is the same as the target `x` and doing the same with the `y`? But that way you wouldn't get the shortest path, and you wouldn't be able to go around obstacles, so I'm not sure why you say A* is unnecessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:28:32.620",
"Id": "422985",
"Score": "0",
"body": "Ok, I realized just now that you're right and the shortest path is moving the x and then the y because I confined the movement to just up/down/right/left. The point about obstacles still stands though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:39:50.840",
"Id": "422996",
"Score": "0",
"body": "Ah, `maze` does slightly more than I thought."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:02:54.290",
"Id": "219012",
"ParentId": "219006",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T09:52:33.663",
"Id": "219006",
"Score": "4",
"Tags": [
"python",
"algorithm",
"a-star"
],
"Title": "A* algorithm as simple as possible"
} | 219006 |
<p>I've stumbled across some UI (React.js) code that I've worked out to have a time complexity of <code>O(n^4)</code> (I hope that's right, if not please do correct me). I was interested in how one might go about optimising something like this.</p>
<p>I know that <code>for()</code> loops do perform slightly better than <code>array.forEach()</code> and I'd assume <code>const</code> uses a bit less memory than <code>let</code> due to not needing to support re-allocation. </p>
<p>Would using functional operators like <code>map</code> and <code>filter</code> improve performance?</p>
<p>I'd be really interested to see some suggestions to this, and maybe the ideal optimisation for it?</p>
<p>The code:</p>
<pre><code>animate () {
let movingScreens = {}
if (this.animationsDisabled()) {
movingScreens = {}
} else {
for (let i in scrollAnimationDefs.movingScreens) {
if (i !== 'appsTop' && i !== 'appsBottom') movingScreens[i] = scrollAnimationDefs.movingScreens[i]
}
}
for (let shape in movingScreens) {
if (movingScreens[shape].scrolls) {
for (let scroll of movingScreens[shape].scrolls) {
const from = scroll.from * this.scrollMax
const to = scroll.to * this.scrollMax
if (from <= this.scrollTop && to >= this.scrollTop) {
const styles = scroll.styles(
(this.scrollTop - from) / (to - from)
)
for (let style in styles) {
let newStyle = styles[style]
const els = scrollAnimationDefs.movingScreens[shape].els.map(
ref => {
if (ref === 'screen1IfContainer') return this.animations.screen1IfContainer.current.container.current
return this.animations[ref].current
}
)
for (const i in els) {
if (els[i]) {
els[i].style[style] = newStyle
}
}
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:02:32.657",
"Id": "423000",
"Score": "0",
"body": "Please tell us, what does this code do? See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:26:55.477",
"Id": "423006",
"Score": "2",
"body": "Your title is too generic. It should reflect what your code does, not what you want out of the review."
}
] | [
{
"body": "<h2>Style and code</h2>\n\n<ul>\n<li>There are several places where you should use <code>const</code> rather than <code>let</code>. Mainly inside the for loops.</li>\n<li>The second <code>movingScreens = {}</code> is redundant.</li>\n<li>Avoid nesting loops too deeply. Use a function to avoid this.</li>\n<li>Don't use <code>for...in</code> as you need to be sure you are not getting properties higher up the prototype chain. Use <code>Object.keys</code> to get the keys and iterate them with a <code>for...of</code></li>\n<li>Avoid long lines by using alias to reference object paths or long names.</li>\n<li>The naming is confusing, you have <code>shapes</code>, <code>screens</code>, <code>scrollScreens</code> that seam to be interchangeable</li>\n<li>Is this a typo or a really bad name and reference <code>this.animations.screen1IfContainer.current.container.current</code></li>\n</ul>\n\n<h2>Avoid iterating again</h2>\n\n<p>You build the object <code>movingScreens</code> then you iterate it again. Would be better to process the items instead of building the object <code>movingScreens</code>.</p>\n\n<p>You use <code>Array.map</code> to create an array of elements, then you iterate that array again. Process the elements as you iterate the first time.</p>\n\n<h2>Rewrite</h2>\n\n<ul>\n<li>Removed the object <code>movingScreens</code> processing the shapes in the first loop.</li>\n<li>Added function <code>scrollScreen</code> to process a (<code>screen</code>, <code>shape</code>, or <code>scroll</code> I can not be sure).</li>\n<li>Used aliases to reference long names and paths. <code>currentCont</code>, and <code>screens</code></li>\n<li>All variables are now <code>const</code></li>\n<li>Used <code>Object.keys</code> for safer key iteration.</li>\n</ul>\n\n<p>As there is no way for me to test this code, nor do I have a context (what is what), it may contain typos or logic errors.</p>\n\n<pre><code>animate() {\n const currentCont = this.animations.screen1IfContainer.current.container.current;\n const scrollScreen = shape => {\n for (const scroll of shape.scrolls) {\n const from = scroll.from * this.scrollMax;\n const to = scroll.to * this.scrollMax;\n if (from <= this.scrollTop && to >= this.scrollTop) {\n const styles = scroll.styles((this.scrollTop - from) / (to - from));\n for (const style of Object.keys(styles)) {\n for(const ref of shape.els) {\n const el = ref === 'screen1IfContainer' ? \n currentCont : this.animations[ref].current;\n if (el) { el.style[style] = styles[style] }\n }\n }\n }\n }\n }\n if (!this.animationsDisabled()) {\n const screens = scrollAnimationDefs.movingScreens;\n for (const key of Object.keys(screens)) {\n if (key !== 'appsTop' && key !== 'appsBottom' && screens[key].scrolls) {\n scrollScreen(screens[key]);\n }\n }\n }\n}\n</code></pre>\n\n<h2>Questions</h2>\n\n<blockquote>\n <p><span class=\"math-container\">\\$O(n^4)\\$</span> (I hope that's right, if not please do correct me)</p>\n</blockquote>\n\n<p>You have not defined <code>n</code> thus its is meaningless to define the complexity.</p>\n\n<blockquote>\n <p>Would using functional operators like map and filter improve performance?\n I'd be really interested to see some suggestions to this, and maybe the ideal optimisation for it?</p>\n</blockquote>\n\n<p>As this is animation these points can not be answered. The slow point is the moving of pixels, this is highly dependent on the device it is running on. The JS code is but a fraction of the workload, you can optimize it till the cows come home and it may not make a spec of difference on the performance of the animation.</p>\n\n<p>Any optimization would require the full animation to see when and where the many GPU state changes, compositing, and what not can be optimized.</p>\n\n<h2>Update</h2>\n\n<p>I forgot this line in your question.</p>\n\n<blockquote>\n <p>I'd assume const uses a bit less memory than let due to not needing to support re-allocation</p>\n</blockquote>\n\n<p>If <code>const</code> uses less memory that would be up to the JS engine. I would not use it as a criteria as when to use <code>const</code> or not.</p>\n\n<ul>\n<li>We use <code>const</code> to protect against accidental mutation.</li>\n<li>We use <code>let</code> and <code>const</code> to avoid accidentally redefining a variable.</li>\n<li>We use <code>const</code> (as with <code>let</code>) to scope the variable to a block. A block is code between <code>{</code> and <code>}</code> The exception is when a variable is defined in a <code>for</code>, <code>do</code>, or <code>while</code> loop as a <code>const</code> or <code>let</code> it is scoped to the loop block, not to the current block. eg <code>{ /*current block a is not in scope */ for(const a of b) { /* a is in scope loop block*/ } }</code></li>\n<li>We use <code>const</code> to give meaning to constants that are otherwise just numbers or strings in your source code. eg <code>const unit = 1;</code></li>\n<li><p>Currently chrome, FF, edge give <code>const</code>, <code>let</code>, and <code>var</code> have a slight performance benefit over literals. eg <code>1 + 1</code> is a little slower than <code>one + one</code> with <code>one</code> defined as <code>const one = 1;</code> </p>\n\n<p>Do not rely on this to remain true as engines are constantly changing. The benefit is <strong>very</strong> small and only an advantage under very specific conditions.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:34:06.067",
"Id": "423022",
"Score": "0",
"body": "\"_There are several places where you should use const rather than let. Mainly inside the for loops_\" I know the presumed reason but the OP might not. You should explain the advantages (and possible disadvantages as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T16:15:57.743",
"Id": "423037",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Was going to address OP's comment about `const` and forgot. Added some more words on the matter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:25:52.927",
"Id": "219023",
"ParentId": "219008",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219023",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T10:20:18.803",
"Id": "219008",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "Suggestions for optimising this front end code"
} | 219008 |
<p>I have this counting sort for byte values running in linear time with respect to array length:</p>
<p><strong><code>Arrays.java</code></strong></p>
<pre><code>package net.coderodde.util;
import java.util.Random;
/**
* This class contains static methods for sorting {@code byte} arrays.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 24, 2019)
*/
public final class Arrays {
/**
* Sorts the given {@code byte} array in its entirety.
*
* @param arrays the array to sort.
*/
public static void sort(byte[] arrays) {
sort(arrays, 0, arrays.length);
}
/**
* Sorts the given {@code byte} array omitting first {@code fromIndex}
* array components starting from beginning, and omitting last
* {@code array.length - toIndex} array components from the ending.
*
* @param array the array holding the target range.
* @param fromIndex the starting index of the target range.
* @param toIndex one position to the right from the last element
* belonging to the target range.
*/
public static void sort(byte[] array, int fromIndex, int toIndex) {
rangeCheck(array.length, fromIndex, toIndex);
int[] bucketCounters = new int[256];
for (int index = fromIndex; index < toIndex; index++) {
bucketCounters[Byte.toUnsignedInt(array[index])]++;
}
int index = fromIndex;
// Insert the negative values first:
for (int bucketIndex = 128; bucketIndex != 256; bucketIndex++) {
java.util.Arrays.fill(array,
index,
index += bucketCounters[bucketIndex],
(byte) bucketIndex);
}
// Insert the positive values next:
for (int bucketIndex = 0; bucketIndex != 128; bucketIndex++) {
java.util.Arrays.fill(array,
index,
index += bucketCounters[bucketIndex],
(byte) bucketIndex);
}
}
/**
* Checks that {@code fromIndex} and {@code toIndex} are in
* the range and throws an exception if they aren't.
*/
private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException(
"fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
if (fromIndex < 0) {
throw new ArrayIndexOutOfBoundsException(fromIndex);
}
if (toIndex > arrayLength) {
throw new ArrayIndexOutOfBoundsException(toIndex);
}
}
public static void main(String[] args) {
warmup();
benchmark();
}
private static final int LENGTH = 50_000_000;
private static final void warmup() {
runBenchmark(false);
}
private static final void benchmark() {
runBenchmark(true);
}
private static final void runBenchmark(boolean output) {
long seed = System.currentTimeMillis();
Random random = new Random();
byte[] array1 = createRandomByteArray(LENGTH, random);
byte[] array2 = array1.clone();
byte[] array3 = array1.clone();
if (output) {
System.out.println("seed = " + seed);
}
long startTime = System.nanoTime();
java.util.Arrays.sort(array1);
long endTime = System.nanoTime();
if (output) {
System.out.println("java.util.Arrays.sort(byte[]) in " +
(endTime - startTime) / 1e6 +
" milliseconds.");
}
startTime = System.nanoTime();
java.util.Arrays.parallelSort(array2);
endTime = System.nanoTime();
if (output) {
System.out.println("java.util.Arrays.parallelSort(byte[]) in " +
(endTime - startTime) / 1e6 +
" milliseconds.");
}
startTime = System.nanoTime();
net.coderodde.util.Arrays.sort(array3);
endTime = System.nanoTime();
if (output) {
System.out.println("net.coderodde.Arrays.sort(byte[]) in " +
(endTime - startTime) / 1e6 +
" milliseconds.");
System.out.println("Algorithms agree: " +
(java.util.Arrays.equals(array1, array2) &&
java.util.Arrays.equals(array1, array3)));
}
}
private static final byte[] createRandomByteArray(int length,
Random random) {
byte[] array = new byte[length];
for (int i = 0; i < length; i++) {
array[i] = (byte) random.nextInt();
}
return array;
}
}
</code></pre>
<p><strong>Typical output</strong></p>
<pre class="lang-none prettyprint-override"><code>seed = 1556112137029
java.util.Arrays.sort(byte[]) in 67.6446 milliseconds.
java.util.Arrays.parallelSort(byte[]) in 210.0057 milliseconds.
net.coderodde.Arrays.sort(byte[]) in 46.6332 milliseconds.
Algorithms agree: true
</code></pre>
| [] | [
{
"body": "<p>I find the big points covered well:</p>\n\n<ul>\n<li>class and methods have one clear, documented purpose</li>\n<li>the API follows the well-known <code>java.util.Arrays</code><br>\n(if not to the point of documenting <code>RuntimeException</code>s thrown)</li>\n</ul>\n\n<hr>\n\n<p>I'd try to get rid of <em>magic literals</em> and <em>code replication</em>:<br>\nsize <code>counts = new int[Byte.MAX_VALUE-Byte.MIN_VALUE+1]</code> (or <code>1<<Byte.SIZE</code>?), use</p>\n\n<pre><code>for (int bucket = Byte.MIN_VALUE ; bucket <= Byte.MAX_VALUE; bucket++)\n Arrays.fill(array,\n index, \n index += counts[Byte.toUnsignedInt((byte) bucket)], \n (byte) bucket);\n</code></pre>\n\n<p>I found it interesting to ogle the RTE source code I use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T17:12:01.790",
"Id": "235120",
"ParentId": "219018",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "235120",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:24:43.787",
"Id": "219018",
"Score": "2",
"Tags": [
"java",
"array",
"sorting"
],
"Title": "Efficient counting sort for large byte arrays in Java"
} | 219018 |
<p>I have a login dialog working in vue js with typescript.</p>
<p>I want to trigger the open via a button on page, but also by toggling a value in the vuex store.</p>
<p>It is working by 2 watchers:</p>
<ol>
<li>Watching the local visible state persists the state to the store on every change</li>
<li>Watching the store state then toggles the local visible flag.</li>
</ol>
<p>The result is the button can open the modal, click outside the modal closes. But i can trigger the modal to be opened from the router now too from elsewhere in the app via vuex.</p>
<p>But... now i have to have 2 watchers running all the time. Is there a better way?</p>
<pre><code><template>
<div>
<el-button v-if="!authenticated" @click="visible = true">Login</el-button>
<el-dialog :visible.sync="visible" title="Login or Register">
<el-tabs v-model="activeTab">
<el-tab-pane label="Login" name="login">
<login-form></login-form>
</el-tab-pane>
<el-tab-pane label="Register" name="register">
<register-form></register-form>
</el-tab-pane>
</el-tabs>
</el-dialog>
</div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { AuthenticationModule } from '@/store/modules/authentication';
import LoginForm from '@/views/forms/LoginForm.vue';
import RegisterForm from '@/views/forms/RegisterForm.vue';
@Component({
components: {
LoginForm,
RegisterForm,
},
})
export default class AppHeaderLogin extends Vue {
private visible: boolean = false;
private activeTab: string = 'login';
get authenticated() {
return AuthenticationModule.authenticated;
}
get loginPrompt() {
return AuthenticationModule.prompt.login;
}
@Watch('loginPrompt')
onLoginPromptChange(value: boolean) {
if (value !== this.visible) {
this.visible = value;
}
}
@Watch('visible')
onVisibleChange(value: boolean) {
// Do stuff with the watcher here.
AuthenticationModule.TOGGLE_PROMPT_LOGIN(value);
}
}
</script>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:29:55.423",
"Id": "219019",
"Score": "1",
"Tags": [
"typescript",
"vue.js"
],
"Title": "vuejs vuex element-ui used to toggle a login dialog but req"
} | 219019 |
<p>I tried to search and read for 10-12 hours on how to have a secure session, and this is the <em>(simplified version of the)</em> code that I came up with. <em>(found no good book or article with complete guide about PHP Sessions, each had something and missed something else)</em></p>
<p>Could you kindly please check if I have taken the necessary steps or if I've made a mistake somewhere?</p>
<p><em>Additional Info: <code>PHP 7.3.x</code> will be used, Webserver is <code>nginx</code> on <code>Ubuntu 18.04</code>, will have a maximum of ~500 visitors per second, usually ~50-100, sessions are written on disk (default of PHP)</em></p>
<pre><code>function secure_session_start($domain, $ip, $useragent)
{
// Change PHPSESSID for better security, remove this if set in php.ini
session_name('app_session');
// Secure session_set_cookie_params
session_set_cookie_params(0, '/', $domain, true, true);
// Don't show any output if session_start fails, die immediately (will add log_error later)
@session_start() or die();
// Keep session alive (as suggested by comment on https://www.php.net/manual/en/function.session-start.php#121209)
$_SESSION['time'] = time();
// Hash Useragent to be safe from storing malicious useragent text as session data on server
$useragent_hash = hash('sha256', $useragent);
// Make sure we have a canary set
if ( ! isset($_SESSION['canary']))
{
// Regenerate & delete old session as well
session_regenerate_id(true);
$_SESSION['canary'] = [
'birth' => time(),
'ip' => $ip,
'useragent_hash' => $useragent_hash
];
}
// Regenerate session ID every 5 minutes:
if ($_SESSION['canary']['birth'] < time() - 300)
{
// Regenerate & delete old session as well
session_regenerate_id(true);
$_SESSION['canary']['birth'] = time();
}
// If user is logged in, log out user if IP or Useragent is changed (this is intentional, I know users behind load-balancers etc will have issues)
if (isset($_SESSION['username']) && ($_SESSION['canary']['ip'] !== $ip OR $_SESSION['canary']['useragent_hash'] !== $useragent_hash))
{
// Destroy cookie
setcookie (session_name(), "", time() - 3600, '/', $domain, true, true);
// Destroy session
session_unset();
session_destroy();
// Redirect (avoid loop by checcking ip_browser_changed)
if( ! isset($_GET['ip_browser_changed']))
{
header('Location: '.URL.'login/?ip_browser_changed');
exit('IP Address or Browser has been changed, please login again!');
}
}
}
</code></pre>
<p>Then I will simply do <code>secure_session_start()</code> in my code after validating user IP Address with <code>filter_var($ip, FILTER_VALIDATE_IP)</code></p>
<p><strong>Edit:</strong> I've always relied on PHP Frameworks and their Auth library to handle the sessions etc for me and never worried about them, this time because of too many visitors, I had to skip using frameworks.</p>
<p>I have to make sure users are kept logged in with secure sessions as long as their Browser or IP hasn't changed. Now I'm trying to learn how to securely add the <code>Remember Me</code> feature, just needed to make sure I'm on the right track (with your help)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:14:48.127",
"Id": "423003",
"Score": "0",
"body": "Wow, 500 v/s is a lot. I don't think your 'keep session alive' action makes much sense. You never use `$_SESSION['time']` anywhere. You would normally keep a session alive (after browser closes) by setting the first parameter of [session_set_cookie_params()](https://www.php.net/manual/en/function.session-set-cookie-params.php) to something other than zero. I would also use a cookie token, instead of a canary, but that's another matter. You haven't told us what it is you want to do with this code, can you add that? What are your goals?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:19:15.290",
"Id": "423004",
"Score": "0",
"body": "@KIKOSoftware 500 is the peak, it will be around 50-100 most of the time. about the `$_SESSION['time']` I read it here: https://www.php.net/manual/en/function.session-start.php#121209 , so the comment is wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:21:02.500",
"Id": "423056",
"Score": "0",
"body": "OK, I don't know is that comment is right or wrong. It's just an unlucky choice to put a time in the session and to say that that will keep it alive. Better to use something like `$_SESSION['dummy'] = random_bytes(25);`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:38:34.193",
"Id": "423182",
"Score": "1",
"body": "I think [How to Create Bulletproof Sessions](https://blog.teamtreehouse.com/how-to-create-bulletproof-sessions) will give you a better idea of how to write a session manager. I strongly advice you not to mix session handling and user authetication in one single function."
}
] | [
{
"body": "<ul>\n<li><p>As an overarching rule, I never write scripts with the \"stfu operator\" (<code>@</code>). It looks like you plan to refine the session starting line, so I won't dwell.</p></li>\n<li><p>You are calling <code>time()</code> 5 separate times in your function. Because there is no benefit in recording their differences in terms of microseconds, I recommend that you call <code>time()</code> once, and cache the value in a variable/constant to be used in all processes in the custom function.</p></li>\n<li><p>I tend to never use <code>OR</code> or <code>AND</code> in my php conditions (only in my SQL) as a matter of consistency. This also prevents unintended hiccups regarding <a href=\"https://stackoverflow.com/q/5998309/2943403\">precedence</a>. Separately, I never use <code>or die()</code> in my scripts ...trying not to dwell.</p></li>\n<li><p>Because you are generating a hash for non-cryptographic use, you may enjoy the advice/discussions about performance comparisons between different hash generators: <a href=\"https://stackoverflow.com/q/3665247/2943403\">Fastest hash for non-cryptographic uses?</a></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T00:20:16.850",
"Id": "219054",
"ParentId": "219021",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:45:04.567",
"Id": "219021",
"Score": "4",
"Tags": [
"php",
"security",
"session"
],
"Title": "Secure session handling in PHP"
} | 219021 |
<p>I am Learning Javascript, after doing Java development for 2 years. I am doing a module on udemy which had a coding challenge which I completed and it works but wanted to get it reviewed to find out best practices and how the code can be improved and optimised.</p>
<p>Here is the Challenge:</p>
<blockquote>
<p>CODING CHALLENGE</p>
<p>Suppose that you're working in a small town administration, and you're in charge of two town elements:</p>
<ol>
<li>Parks</li>
<li>Streets</li>
</ol>
<p>It's a very small town, so right now there are only 3 parks and 4 streets. All parks and streets have a name and a build year.</p>
<p>At an end-of-year meeting, your boss wants a final report with the following:</p>
<ol>
<li>Tree density of each park in the town (forumla: number of trees/park area) √</li>
<li>Average age of all of the town's parks (forumla: sum of all ages/number of parks) √</li>
<li>The name of the park that has more than 1000 trees √</li>
<li>Total and average length of the town's streets √</li>
<li>Size classification of all streets: tiny/small/normal/big/huge. If the size is unknown, the default is normal √</li>
</ol>
<p>All the report data should be printed to the console. √</p>
<p>HINT: Use some of the ES6 features: classes, subclasses, template strings, default parameters, maps, arrow functions, destructuring, etc.</p>
</blockquote>
<p>My code is:</p>
<pre><code>class NameAndBuildYear {
constructor(name, buildYear) {
this.name = name;
this.buildYear = buildYear;
}
}
class Park extends NameAndBuildYear {
constructor(name, buildYear, numOfTrees, parkArea) {
super(name, buildYear);
this.numOfTrees = numOfTrees;
this.parkArea = parkArea;
}
calculateTreeDensity() {
return this.numOfTrees / this.parkArea
}
calculateAgeOfTree() {
let age = new Date().getFullYear() - this.buildYear;
return age;
}
}
class Street extends NameAndBuildYear {
constructor(name, buildYear, streetLength, size = 'normal') {
super(name, buildYear);
this.streetLength = streetLength;
this.size = size;
}
}
let mordernPark = new Park('Mordern Park', 1909, 100, 0.2);
let tootingPark = new Park('Tooting Park', 1950, 1000, 0.4);
let balhamPark = new Park('Balham Park', 1800, 600, 2.9);
let parkArray = [mordernPark, tootingPark, balhamPark];
function calculateAverageAgeOfPark() {
var sumAge = 0;
parkArray.forEach((element) => {
sumAge += element.calculateAgeOfTree();
});
console.log(`The Average age of the the towns park is ${Math.round(sumAge / parkArray.length)} years`);
}
function calculateTreeDensityOfEachPark() {
for (const cur of parkArray) {
console.log(`The Tree Desnity of ${cur.name} is the density is ${Math.round(cur.calculateTreeDensity())} per square km`);
}
}
calculateTreeDensityOfEachPark();
calculateAverageAgeOfPark();
let numberOfTreesMap = new Map();
numberOfTreesMap.set(mordernPark.name, mordernPark.numOfTrees);
numberOfTreesMap.set(tootingPark.name, tootingPark.numOfTrees);
numberOfTreesMap.set(balhamPark.name, balhamPark.numOfTrees);
for (let [key, value] of numberOfTreesMap.entries()) {
if (value >= 1000) {
console.log(`${key}: has a ${value} trees`);
}
}
const faylandAvenue = new Street('Fayland Avenue', 1982, 200);
const tootingBroadWay = new Street('Tooting Broadway', 1908, 1000, 'huge');
const penworthamRoad = new Street('Penwortham Road', 1950, 300, 'big');
const mertonRoad = new Street('Merton Road', 1932, 100, 'small');
let streetMap = new Map();
streetMap.set(faylandAvenue.name, faylandAvenue.streetLength);
streetMap.set(tootingBroadWay.name, tootingBroadWay.streetLength);
streetMap.set(penworthamRoad.name, penworthamRoad.streetLength);
streetMap.set(mertonRoad.name, mertonRoad.streetLength);
function calculateTotalAndAverageStreetLength() {
let totalStreetLength = 0;
for (let [key, value] of numberOfTreesMap.entries()) {
totalStreetLength += value;
}
console.log(`The total length of the town's streets is ${totalStreetLength} meters and the average length is ${totalStreetLength / streetMap.size} meters`);
}
calculateTotalAndAverageStreetLength();
let streetArray = [faylandAvenue, tootingBroadWay, penworthamRoad, mertonRoad];
streetArray.forEach((element) => {
console.log(`The size of ${element.name} is ${element.size}`);
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:49:42.047",
"Id": "423012",
"Score": "1",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:03:25.467",
"Id": "423014",
"Score": "0",
"body": "@TobySpeight No the edit is fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:12:05.270",
"Id": "423086",
"Score": "0",
"body": "I edited the challenge so that it is easier readable. Since it is human-readable text, in should not be formatted like code."
}
] | [
{
"body": "<h1>Java to JavaScript</h1>\n<p>From Java to JavaScript is one of that hardest ways to move into JS. Appart from a similar C style syntax they are very different.</p>\n<h2>Some things to know</h2>\n<ul>\n<li><p>Javascript does not have classes, interfaces, or classical inheritance.\nThe <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class\" rel=\"nofollow noreferrer\">class syntax</a> is just an alternative way of defining <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects\" rel=\"nofollow noreferrer\">objects</a>.</p>\n<p>The class syntax has some serious problems (no way to define private properties (new syntax is on the way) and encourages poor encapsulation styles) and should be avoided until it has stabilized.</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this\" rel=\"nofollow noreferrer\"><code>this</code></a> is not the same as Javas <code>this</code> be careful when and how you use it.</p>\n</li>\n<li><p>Objects do not have private properties. Encapsulation is via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"nofollow noreferrer\">closure</a>. However properties can be protected via the using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\">Object</a> properties and functions.</p>\n</li>\n<li><p>Javascript Objects <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain\" rel=\"nofollow noreferrer\">inherit via a prototype chain</a>. All objects have Object at the top of the prototype chain.</p>\n</li>\n<li><p>Apart from the <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Primitive\" rel=\"nofollow noreferrer\">primitives</a> <code>boolean</code>, <code>undefined</code>, <code>null</code>, <code>number</code>, <code>string</code> and <code>symbol</code>, all else are objects (and the primitives can be objects to).</p>\n</li>\n<li><p>Javascript can be run in two modes. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\">strict mode</a> is the preferred mode.</p>\n</li>\n</ul>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">MDN main javascript page</a> is a good reference, use it if you need any more information regarding this answer. I will add extra links only if not at MDN</p>\n<h2>The code</h2>\n<p>The code is a mess.</p>\n<ul>\n<li><p>The following variables should all be declared using the keyword <code>const</code> instead of <code>let</code>: <code>mordernPark</code>, <code>tootingPark</code>, <code>balhamPark</code>, <code>parkArray</code>, <code>numberOfTreesMap</code>, <code>streetMap</code>, and <code>streetArray</code> I may have missed some.</p>\n</li>\n<li><p>Define variables and constants in one place. Do create them as you need them.</p>\n</li>\n<li><p>You define functions for some parts of the report yet in others you just have inline code. Ideally you create a function for each part, and group them all in one object. (see example. The object <code>report</code> has all the functions)</p>\n</li>\n<li><p>Good names should try to be under 20 characters long and contain no more than two distinct words. from <a href=\"https://hilton.org.uk/presentations/naming-guidelines\" rel=\"nofollow noreferrer\">Naming guidelines for professional programmers</a></p>\n<p>An example is the name <code>calculateTotalAndAverageStreetLength</code> is way to verbose. If you add this to an object called report you can name it <code>report.streetLengths</code></p>\n</li>\n<li><p>Keep names meaningful. Don't add type to the name. eg <code>parkArray.forEach((element) => {</code> should be <code>parks.forEach(park => {</code></p>\n</li>\n<li><p>Rather than send all report text hard coded to the console, have the functions push them to an array and return that array. You can then send that array where you need.</p>\n</li>\n<li><p>Use getters and setters when getting or setting calculated properties.</p>\n</li>\n<li><p>You have a super class <code>NameAndBuildYear</code> to hold the name and build year, yet you do not define a function to get the age in that object, rather you put it in the parks object. It should be with the <code>NameAndBuildYear</code> object.</p>\n</li>\n<li><p>Don't over complicate the code. You have named variables for each street, and array for all the streets and a map of streets by street name. Yet the street object holds the name already, why duplicate the names so many times?</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Keeping a similar structure (and still using the class syntax (cringe...)) the rewrite uses the above points to make your code more manageable.</p>\n<p>I have renamed the main class to Assets as it seams more fitting.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nclass Asset {\n constructor(name, built) {\n this.name = name;\n this.built = built;\n }\n get age() { return new Date().getFullYear() - this.built }\n}\nclass Park extends Asset {\n constructor(name, built, trees, area) {\n super(name, built);\n this.trees = trees;\n this.area = area;\n }\n get density() { return this.trees / this.area }\n}\nclass Street extends Asset {\n constructor(name, built, length, size = 'normal') {\n super(name, built);\n this.length = length;\n this.size = size;\n }\n}\nconst parks = [\n new Park('Mordern Park', 1909, 100, 0.2),\n new Park('Tooting Park', 1950, 1000, 0.4),\n new Park('Balham Park', 1800, 600, 2.9),\n];\nconst streets = [\n new Street('Fayland Avenue', 1982, 200),\n new Street('Tooting Broadway', 1908, 1000, 'huge'), \n new Street('Penwortham Road', 1950, 300, 'big'),\n new Street('Merton Road', 1932, 100, 'small'),\n];\n\nconst report = {\n create() {\n return [\n ...report.parkAges(),\n ...report.treeDensities(),\n ...report.manyTrees(),\n ...report.streetLengths(),\n ...report.streetSizes(),\n ];\n },\n parkAges() {\n var meanAge = parks.reduce((sum,park) => sum + park.age, 0) / parks.length;\n return [`Parks have an average age of ${Math.round(meanAge)} years`];\n },\n treeDensities() { \n return parks.map(park => `${park.name} has ${park.density} trees per square km`);\n },\n manyTrees() { \n return parks\n .filter(park => park.trees > 1000)\n .map(park => `${park.name}: has a ${park.trees} trees`);\n },\n streetLengths() {\n const total = streets.reduce((sum, street) => sum + street.length, 0);;\n return [\n `The total length of the town's streets is ${total} meters`,\n `The average length is ${Math.round(total / streets.length)} meters`\n ];\n },\n streetSizes() { \n return streets.map(street => `${street.name} is ${street.size}`);\n }\n}\n// to output to console\n// console.log(report.create());\n\n\n// For example only\nlogArray(report.create());\n\nfunction log(textContent) {\n reportDisplay.appendChild(Object.assign(document.createElement(\"div\"),{textContent}));\n}\nfunction logArray(array) { array.forEach(log) }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"reportDisplay\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Example</h2>\n<p>The following example is what I would call JS pure and takes a lot of care to protect via encapsulation the data and functions of the object <code>assets</code>.</p>\n<p>It is a little far from ideal, it is mostly to show some alternative style OO JavaScript for those that come from more strict class typed languages like Java.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst assets = (() => {\n const types = Object.freeze({\n park: \"park\",\n road: \"road\",\n street: \"road\",\n parks: \"park\",\n streets: \"road\", \n });\n const currentYear = new Date().getFullYear();\n const assetTypes = {\n [types.road](length, size = \"normal\") {\n return {\n get length() { return length },\n get size() { return size },\n };\n },\n [types.park](trees, area) {\n return {\n get manyTrees() { return trees > 1000 },\n get density() { return Number((trees / area).toFixed(1)) }\n };\n },\n create(type, name, year, ...data) {\n return Object.freeze({\n get age() { return currentYear - year },\n get name() { return name },\n ...assetTypes[type](...data), \n });\n },\n }; \n const assets = {[types.road]: new Map(), [types.park]: new Map()};\n const API = Object.freeze({\n types,\n each(type, cb) { for(const asset of assets[type].values()) { cb(asset) } },\n addAsset(type, name, ...data) { \n assets[type].set(\n name, \n assetTypes.create(type, name, ...data)\n );\n },\n get totalStreetLength() {\n var total = 0;\n API.each(types.road, road => total += road.length);\n return total;\n },\n get meanStreetLength() { return API.totalStreetLength / assets[types.road].size },\n get meanParkAge() {\n var total = 0;\n API.each(types.park, park => total += park.age);\n return Math.round(total / assets[types.park].size);\n },\n report() {\n const report = [];\n API.each(types.parks, park => report.push(`${park.name} has ${park.density} trees per km squared.`));\n report.push(`The average age of all parks is ${API.meanParkAge}years.`);\n API.each(types.parks, park => park.manyTrees && (report.push(`${park.name} has more than 1000 trees.`)));\n report.push(`The total street length is ${API.totalStreetLength}m.`);\n report.push(`The average street length is ${API.meanStreetLength}m.`);\n API.each(types.streets, street => report.push(`${street.name} has a size clasification of ${street.size}`));\n return report;\n }\n });\n return API;\n})();\n\nconst smallTown = assets;\nconst types = assets.types;\nsmallTown.addAsset(types.park, 'Mordern Park', 1909, 100, 0.2);\nsmallTown.addAsset(types.park, 'Tooting Park', 1950, 1010, 0.4);\nsmallTown.addAsset(types.park, 'Balham Park', 1800, 100, 2.9);\nsmallTown.addAsset(types.street, 'Fayland Avenue', 1982, 200);\nsmallTown.addAsset(types.street, 'Tooting Broadway', 1908, 1000, 'huge');\nsmallTown.addAsset(types.street, 'Penwortham Road', 1950, 300, 'big');\nsmallTown.addAsset(types.street, 'Merton Road', 1932, 100, 'small');\n\n\nlogArray(smallTown.report())\nfunction log(textContent) {\n reportDisplay.appendChild(Object.assign(document.createElement(\"div\"),{textContent}));\n}\nfunction logArray(array) { array.forEach(log) }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"reportDisplay\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:58:23.480",
"Id": "423153",
"Score": "0",
"body": "fantastic answer, honestly learnt so much from it. I am more familiar with your second example but I think the first example looks a lot cleaner"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T19:34:21.523",
"Id": "219043",
"ParentId": "219024",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "219043",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:30:01.220",
"Id": "219024",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"programming-challenge"
],
"Title": "Create a town administration report"
} | 219024 |
<p>I've created a heavily problematic code that works.</p>
<p>Summary: It looks through a folder structure, for png files and tries to replicate this structure in Photoshop. Files are mapped layers and Folders to Groups. I am using <code>comtypes</code> to access Photoshop and create the groups and layers.</p>
<p>The issue I faced with, is that you can't access Photoshop Layer Objects directly (instead you have to go through the whole structure). E.g. to access</p>
<pre><code>new
|
-- folder
|-- sub_folder
|-- random_file
</code></pre>
<p>in order to access the random_file, you have to access new, then folder, then <code>sub_folder</code>!</p>
<p>The following code works and it was developed through an intense mental state of concentration (and some trial and error). I believe it's horrendous though! As I am trying to learn how to be a better programmer and learn from the best, I though to ask your help: Can somebody guide me in order to re-factor this beast? What can I do better and what's the way to go with?</p>
<pre class="lang-py prettyprint-override"><code># Algorithm (?):
# ---------
# Starting from given top folder structure .
# traverse downwards and create
# photoshop groups named as the folders
# import all the png files under this
# as linked layers and name them accordingly
# traverse another layer deeper
# and do the same
# Import layers from Misc as Background and Shadow
os.chdir(ROOT_PATH + '/Misc')
import_all_pngs_as_layers(new_doc, new_doc, ROOT_PATH + '/Misc')
os.chdir(ROOT_PATH) # Revert the working path
duplicate = False
subdir = False
for root, dd, ff in os.walk('.'):
path = root.split(os.sep)
if not os.path.basename(root) == '.': # ignore parent
if os.path.dirname(root).replace(".\\", "") in IGNORED_DIRS:
pass
elif not os.path.dirname(root) == '.' and not os.path.dirname(
root).replace(".\\", "") in IGNORED_DIRS:
# print('I am a subdir {} of the dir {}'.format(
# os.path.basename(root),
# os.path.dirname(root).replace(".\\", "")))
create_group_named(
new_doc, os.path.basename(root),
new_doc.LayerSets(os.path.dirname(root).replace(".\\", "")))
elif not os.path.basename(root) in IGNORED_DIRS:
# print("Create TOP LEVEL layer group named",
# os.path.basename(root))
create_group_named(
new_doc,
os.path.basename(root)) # Create a group named 'subdir'
if len(ff) > 1:
for filename in ff:
if filename.endswith('.png'):
for item in GROUPED_LAYERS:
# print(item)
# print(item in filename)
if item in filename:
# print(
# 'lets create a group {} and put the layer{} under it in folder {}'
# .format(item, filename, os.path.basename(root)))
os.chdir(os.path.realpath(root))
try:
new_doc.LayerSets(
os.path.basename(root)).LayerSets(item)
except:
ng = create_group_named(
new_doc, item,
new_doc.LayerSets(os.path.basename(root)))
create_layer_from_file(
new_doc, filename, ng,
os.path.realpath(filename))
else:
# print(new_doc.LayerSets(os.path.basename(root)))
create_layer_from_file(
new_doc, filename,
new_doc.LayerSets(
os.path.basename(root)).LayerSets(item),
os.path.realpath(filename))
duplicate = True
os.chdir(ROOT_PATH)
if duplicate:
pass
duplicate = False
else:
os.chdir(os.path.realpath(root))
# print('Rest files import as layers {} under {}'.format(
# filename, os.path.basename(root)))
if os.path.basename(
root) in IGNORED_DIRS or os.path.dirname(
root).replace(".\\", "") in IGNORED_DIRS:
pass
elif not os.path.dirname(root) == '.':
# print('layer {} on main group {} on group {}'
# .format(filename, os.path.dirname(root).replace(".\\",""), os.path.basename(root)))
create_layer_from_file(
new_doc, filename,
new_doc.LayerSets(
os.path.dirname(root).replace(
".\\", "")).LayerSets(
os.path.basename(root)),
os.path.realpath(filename))
else:
create_layer_from_file(
new_doc, filename,
new_doc.LayerSets[os.path.basename(root)],
os.path.realpath(filename))
os.chdir(ROOT_PATH)
else:
pass
</code></pre>
<p>For completeness here's the rest of the program:</p>
<pre class="lang-py prettyprint-override"><code>import comtypes.client as ct
psApp = ct.CreateObject('Photoshop.Application')
new_doc = psApp.Documents.Add(600, 800, 72, "new-psb-test", 2, 1, 1)
# they are ignored as those are the directories on the root level
# and I explicitly import them and their layers before the loop
IGNORED_DIRS = ['Misc', 'Wheel_Merged']
# If the files (inside the group/folder Accessories)
# include the following in their names then they need to be
# sub- grouped under that name: e.g. Grille_01, 22_Grille, Grille0 all need to be
# layers under the Group named Grille
GROUPED_LAYERS = ['Body_Side', 'Grille']
def create_group_named(doc, layer_set, under=''):
""" Create a New LayerSet (aka Group) in the Photoshop
document (doc).
Args:
doc (obj): The Photoshop Document Instance
under (obj): The Group Object Instance
(e.g. if you want a subgroup under Lights then give that
object as a under name)
layer_set (str): The name of the new Layer Set
Returns:
new_layer_set (obj): The LayerSet (Group) Object
"""
if not under: # add a top level group
new_layer_set = doc.layerSets.Add()
else: # add subgroup
new_layer_set = under.LayerSets.Add()
new_layer_set.name = layer_set
return new_layer_set
def paste_file_as_linked_layer(path):
""" Import a file as a photoshop (smart) linked layer
Args:
path(str): The exact path of the image including extension
Returns:
whatever execute action returns (TBC)
"""
idPlc = psApp.charIDToTypeID("Plc ")
desc11 = ct.CreateObject("Photoshop.ActionDescriptor")
idIdnt = psApp.charIDToTypeID("Idnt")
desc11.putInteger(idIdnt, 2)
# Open the file (path)
idnull = psApp.charIDToTypeID("null")
desc11.putPath(idnull, path)
# set its type as a linked payer
idLnkd = psApp.charIDToTypeID("Lnkd")
desc11.putBoolean(idLnkd, True)
idFTcs = psApp.charIDToTypeID("FTcs")
idQCSt = psApp.charIDToTypeID("QCSt")
idQcsa = psApp.charIDToTypeID("Qcsa")
desc11.putEnumerated(idFTcs, idQCSt, idQcsa)
idOfst = psApp.charIDToTypeID("Ofst")
desc12 = ct.CreateObject('Photoshop.ActionDescriptor')
idHrzn = psApp.charIDToTypeID("Hrzn")
idRlt = psApp.charIDToTypeID("#Rlt")
desc12.putUnitDouble(idHrzn, idRlt, 0)
idVrtc = psApp.charIDToTypeID("Vrtc")
idRlt = psApp.charIDToTypeID("#Rlt")
desc12.putUnitDouble(idVrtc, idRlt, 0)
idOfst = psApp.charIDToTypeID("Ofst")
# put the object in an offset space of 0,0
desc11.putObject(idOfst, idOfst, desc12)
# 'return' of the function
# is the placement of the linked layer
f = psApp.executeAction(idPlc, desc11, 3)
def create_layer_from_file(doc, layer_name, layer_set, path):
""" Create new Layer from File nested under a LayerSet
Args:
doc (obj): The working Photoshop file
layer_name (str): The given name for the Layer
layer_set (obj): the LayerSet object that the Layer is nested under
path (str): the full Path of the file (including the extension)
Returns:
"""
psApp.activeDocument = doc
layer = layer_set.artLayers.Add()
layer.name = layer_name # Rename Layer
doc.activeLayer = layer # Select Layer
paste_file_as_linked_layer(os.path.realpath(path).replace('\\', '/'))
return layer
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:19:24.207",
"Id": "423202",
"Score": "1",
"body": "@wizofe your code is __not__ horrible, sure there's some formatting that would improve readability, and [`argparse`](https://docs.python.org/2/library/argparse.html#type) would allow for extending into a full command line utility, aside from those nits it's looking okay for the most part. In particular, those `if os.path.basename(...).replace(...` lines maybe easier to debug later if it where a convenience function. As for accessing `random_file` within `sub_folder`, if ya don't like nesting, maybe try an intermediate structure to organize things the way ya like, eg. `pandas`, `dict`, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:55:25.637",
"Id": "423315",
"Score": "2",
"body": "@S0AndS0: That sounds like the start of a nice answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:51:16.907",
"Id": "423320",
"Score": "0",
"body": "Thanks @S0AndS0. Indeed I need to use `argparse` as I did in a similar tool I developed after this :) \n\nCan you give me examples for the terms:\n- 'convenience function': How I can implement one for the `if os.path.basename(...).replace(...)`?\n- My big trouble was to create such an 'intermediate structure' for my pre-existing folder structure/schema. An example on that would be very awesome (I am happy to see one both using `pandas` and a `dict` Thanks again :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:07:35.537",
"Id": "423551",
"Score": "1",
"body": "@Graipher some may call it _foreshadowing_ ;-)... @wizofe most welcome and I'm glad that it seems to be helping so far, one thing my answer here does __not__ cover, searching and accessing some `random_file` object, is something that I kinda covered over on [math.stack](https://math.stackexchange.com/a/3171877/657433). Though there'd be _**some**_ modification I believe the resulting code maybe shorter than what's demonstrated there. Hint `first_to_compute` would instead contain a search `str`ing or `list`, maybe _`walk`ing_ in a _`yield`ing_ fashion; bonus points for readable recursiveness."
}
] | [
{
"body": "<p>I spent <em>sometime</em> with the <a href=\"https://codereview.stackexchange.com/q/219028/197446\"><code>code</code></a> you've currently posted @wizofe, I'm not sure if it'll ever be the same again...</p>\n<blockquote>\n<p>Side note; I heard it rumored that the character limits are <em>just a bit</em> more relaxed than on other sub-stacks... or in other-words this may get a bit verbose, or in other-other-words it could be <em>another one of those posts</em> so a snack and drink is a solid choice.</p>\n</blockquote>\n<h3><code>utils_photoshop/__init__.py</code></h3>\n<blockquote>\n<p>I didn't have insight as to how you where organizing code so I'm making up file and directory names for later <em>pseudo-<code>import</code>ing</em>.</p>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\nimport comtypes.client as ct\n\n\n__license__ = """\nSee selection from author of question: https://codereview.stackexchange.com/q/219028/197446\n"""\n\n\n## Note from S0AndS0; repeated `new_doc` __will__ cause all manor of headaches\n#def import_all_pngs_as_layers(new_doc, new_doc, path):\ndef import_all_pngs_as_layers(new_doc, path):\n """\n # Warning: this function is missing from current version of the posted question\n """\n pass\n\n\ndef create_named_group(doc, layer_set, under = ''):\n """\n Create a New LayerSet (aka Group) in the Photoshop document (doc).\n\n ## Arguments\n\n - doc (obj): The Photoshop Document Instance\n - under (obj): The Group Object Instance\n (e.g. if you want a subgroup under Lights then give that\n object as a under name)\n - layer_set (str): The name of the new Layer Set\n\n ## Returns: new_layer_set (obj): The LayerSet (Group) Object\n """\n if not under: # add a top level group\n new_layer_set = doc.layerSets.Add()\n else: # add subgroup\n new_layer_set = under.LayerSets.Add()\n\n new_layer_set.name = layer_set\n return new_layer_set\n\n\ndef paste_file_as_linked_layer(path, psApp):\n """\n Import a file as a Photoshop (smart) linked layer\n\n ## Arguments\n\n - path (str): The exact path of the image including extension\n - psApp (object): an instance of `ct.CreateObject('Photoshop.Application')`\n\n ## Returns: whatever execute action returns (TBC)\n """\n idPlc = psApp.charIDToTypeID('Plc ')\n\n desc11 = ct.CreateObject('Photoshop.ActionDescriptor')\n idIdnt = psApp.charIDToTypeID('Idnt')\n desc11.putInteger(idIdnt, 2)\n\n # Open the file (path)\n idnull = psApp.charIDToTypeID('null')\n desc11.putPath(idnull, path)\n\n # set its type as a linked payer\n idLnkd = psApp.charIDToTypeID('Lnkd')\n desc11.putBoolean(idLnkd, True)\n\n idFTcs = psApp.charIDToTypeID('FTcs')\n idQCSt = psApp.charIDToTypeID('QCSt')\n idQcsa = psApp.charIDToTypeID('Qcsa')\n desc11.putEnumerated(idFTcs, idQCSt, idQcsa)\n\n idOfst = psApp.charIDToTypeID('Ofst')\n desc12 = ct.CreateObject('Photoshop.ActionDescriptor')\n idHrzn = psApp.charIDToTypeID('Hrzn')\n idRlt = psApp.charIDToTypeID('#Rlt')\n desc12.putUnitDouble(idHrzn, idRlt, 0)\n idVrtc = psApp.charIDToTypeID('Vrtc')\n idRlt = psApp.charIDToTypeID('#Rlt')\n desc12.putUnitDouble(idVrtc, idRlt, 0)\n idOfst = psApp.charIDToTypeID('Ofst')\n # put the object in an offset space of 0,0\n desc11.putObject(idOfst, idOfst, desc12)\n\n # _`return`_ of this function is placement of the linked layer\n f = psApp.executeAction(idPlc, desc11, 3)\n\n\ndef create_layer_from_file(doc, layer_name, layer_set, path, psApp):\n """\n Create new Layer from File nested under a LayerSet\n\n ## Arguments\n\n - doc (obj): The working Photoshop file\n - layer_name (str): The given name for the Layer\n - layer_set (obj): the LayerSet object that the Layer is nested under\n - path (str): the full Path of the file (including the extension)\n - psApp (object): an instance of `ct.CreateObject('Photoshop.Application')`\n\n ## Returns: `layer`, an instance of `layer_set.artLayers.Add()`\n """\n psApp.activeDocument = doc\n layer = layer_set.artLayers.Add()\n layer.name = layer_name # Rename Layer\n doc.activeLayer = layer # Select Layer\n\n paste_file_as_linked_layer(os.path.realpath(path).replace('\\\\', '/'), psApp)\n\n return layer\n\n\ndef scrubbed_dirname(path):\n """\n ## Returns: path with any `.\\\\` removed\n """\n ## Note from S0AndS0; careful with writing code like this,\n ## it can _spaghettify_ a code-base to incomprehensible levels.\n ## Generally this is a sign that there is something that could\n ## be done better with whatever is using functions like these.\n ## Or in other-words, consider Ctrl^f "scrubbed_dirname" to be\n ## a _highlighter_ for places that code may be getting _hairy_.\n ## However, this is a balance of what is worth the time as well\n ## as how far feature-creep plans to take this project.\n return os.path.dirname(path).replace('.\\\\', '')\n\n\ndef notice(msg, verbosity = 0, *f_list, **f_kwargs):\n """\n Prints formatted notices if `--verbosity` is greater than `0`\n\n ## Arguments\n\n - msg (str): The string to print, possibly with formatting\n - f_list (list): A list of arguments to pass to `format()`\n - f_kwargs (dict): Key word arguments to pass to `format()`\n\n ## Returns: None\n """\n ## Note from S0AndS0; when ya get to the point that adding\n ## checks for other levels of verbosity, or maybe are considering\n ## passing something like `v_threshold` and `v_current`, it might\n ## be better to look for libraries that better express such intent.\n if verbosity <= 0:\n return\n\n if f_list and f_kwargs:\n print(msg.format(*f_list, **f_kwargs))\n elif f_list:\n print(msg.format(*f_list))\n elif f_kwargs:\n print(msg.format(**f_kwargs))\n else:\n print(msg)\n</code></pre>\n<p>As noted the <code>import_all_pngs_as_layers</code> function was missing from your question, not sure what it's <em>special sauce</em> is but that's okay as my internal parser is more tolerant than Python's. If this omission was intentional I'd advise editing in a real <code>__license__</code> reference that expresses your views on edits, use, etc. instead of keeping the <em>herbs-n-spices</em> a secret.</p>\n<p>The <code>paste_file_as_linked_layer</code> and <code>create_layer_from_file</code> functions received edits to allow for passing about <code>psApp</code>, I get that this is not ideal but more on that later.</p>\n<p>The <code>scrubbed_dirname</code> is the convenience function that I commented about earlier, and much like the above code's comment-block states, this is something to be very careful with! These kinds of functions can be much like tribbles, one or two isn't too bad but given time and feature-creep maneuvering through a code-base can become a slog.</p>\n<p>The <code>notice</code> function is another example of a convenience function that replaces the commented <code>print()</code> statements with something that outputs conditionally. But like the commented block states, it's probably a good idea to look into a library if there's more features wanted out of something like that. I didn't because I'm not about to assume you'll want to (if allowed) <em><code>pip install something</code></em> just to use my suggestions, that and <code>notice</code>'ll show some <em>fancy</em> argument passing in the next code block.</p>\n<p>I may have messed-up your documentation styling @wizofe (mainly because I use MarkDown just about everywhere), so my apologies on that point. And except for otherwise commented within the code-blocks you've done very well in dividing up portions of the problem space into manageable chunks. Not a whole lot of <em>ground-breaking</em> I can do in other-words.</p>\n<hr />\n<h3><code>png_to_photoshop.py</code></h3>\n<blockquote>\n<p>Much like some of those <em>pocket monsters</em>, pressing <kbd>b</kbd> will cancel this <em>evolution</em>...</p>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\nimport sys\nimport argparse\nimport comtypes.client as ct\nimport warnings\n\nfrom textwrap import dedent\nfrom utils_photoshop import (\n create_layer_from_file,\n create_named_group,\n import_all_pngs_as_layers,\n notice,\n paste_file_as_linked_layer,\n scrubbed_dirname)\n\n\n#\n# _Boilerplate stuff_\n#\n__description__ = """\nThis script recursively traverses folder structure starting with given path and creates;\n\n- Photoshop groups named as each sub-directory, within which are\n\n - all the png files linked to layers and name accordingly\n\n> Sub-directories are treated similarly if found\n"""\n\n__license__ = """\nSee selection from author of question: https://codereview.stackexchange.com/q/219028/197446\n"""\n\n__examples__ = """\nAdd PNG files from: /home/bill/Pictures/funny-cats/\n\n png_to_photoshop.py --basedir /home/bill/Pictures/funny-cats/\\\\\n --img_ext png\\\\\n --misc_dir YarnCollection\\\\\n --ignored_dirs YarnCollection Unicorns\\\\\n --layers_group costumed surprised adorbs\\\\\n --verbosity 9000\n"""\n\n__author__ = ('wizofe', 'https://codereview.stackexchange.com/users/199289/wizofe')\n\n## Note to editors, please add yourself to the following\n__editors__ = [\n ('S0AndS0', 'https://codereview.stackexchange.com/users/197446/s0ands0'),\n]\n\n## Note from S0AndS0; you will usually see the reverse of the following\n## at the bottom of files that maybe run or imported, in this case I am\n## being explicit as to how this file may be used without modification.\nif __name__ != '__main__':\n raise NotImplementedError("Try running as a script, eg. python file-name.py --help")\n\n\n#\n# Parse the command line arguments into an `args_dict`\n#\nparser = argparse.ArgumentParser(description = __description__, epilog = __examples__, allow_abbrev = False)\n## Example of adding command-line argument\n# parser.add_argument('--foo', default = 'Fooed', type = str, help = 'Foo is defaulted to -> %(default)s')\n\nparser.add_argument('--about', action = 'store_true', help = 'Prints info about this script and exits')\nparser.add_argument('--license', action = 'store_true', help = 'Prints script license and exits')\n\nparser.add_argument('--verbosity',\n type = int,\n default = 0,\n help = "How verbose to be during execution, default %(default)s")\n\nparser.add_argument('--img_ext',\n default = 'png',\n help = "Image extension to import into Photoshop with this script, default %(default)s")\n\nparser.add_argument('--base_dir',\n required = True,\n help = 'Base directory to recursively parse for PNG files into Photoshop layers')\n\nparser.add_argument('--misc_dir',\n required = True,\n help = 'Base directory to recursively parse for PNG files into Photoshop layers')\n\nparser.add_argument('--ignored_dirs',\n nargs='+',\n default = ['Misc', 'Wheel_Merged'],\n help = "List of sub-directory names to ignore while _walking_ base_dir, default %(default)s")\n\n## Note from S0AndS0; ya may want to play with the following `help`\n## to get output of `script-name.py --help` looking more acceptable.\nparser.add_argument('--layers_group',\n nargs='+',\n default = ['Body_Side', 'Grille'],\n help = textwrap.dedent("""\n List of association names between file names, and Photoshop sub-groups, default %(default)s.\n\n For example "{name}_01, 22_{name}, {name}0" could be grouped to "{name}",\n via something like...\n\n script-name.py --layers_group {name}\n """.format(name = 'Grille')))\n\nargs_dict = vars(parser.parse_args())\n\n\n#\n# Ways to prematurely exit from script, note `--help` takes care of itself\n#\nif args_dict['license']:\n print(__license__)\n sys.exit()\n\n\nif args_dict['about']:\n message = """\n This script and related code was brought to you by\n\n Author: {name} of {url}\n """.format(name = __author__[0], url = __author__[1])\n\n if __editors__:\n message += '\\n\\n\\tand...\\n'\n for name, url in __editors__:\n message += "\\t{name} -> {url}".format(**{'name': name, 'url': url})\n\n print(dedent(message))\n sys.exit()\n\n\n## Note from S0AndS0; I moved the following two assignments and\n## modified the `paste_file_as_linked_layer` and `create_layer_from_file`\n## functions to pass `psApp` about, because I figure a future self\n## or reader will want to customize it a bit more. This is less than\n## ideal, so see the posted notes for some thoughts on the future.\npsApp = ct.CreateObject('Photoshop.Application')\nnew_doc = psApp.Documents.Add(600, 800, 72, 'new-psb-test', 2, 1, 1)\n\n# Import layers from Misc as Background and Shadow\nmisc_path = os.path.join(args_dict['base_dir'], args_dict['misc_dir'])\nos.chdir(misc_path)\nimport_all_pngs_as_layers(new_doc = new_doc, path = misc_path)\nos.chdir(args_dict['base_dir']) # Revert the working path\n\nduplicate = False\nsubdir = False\nimg_ext = ".{ext}".format(ext = args_dict['img_ext'])\n\n\nfor root, dd, ff in os.walk(args_dict['base_dir']):\n ## Note from S0AndS0; where is `path` being used?\n ## Or is this _zombie_/_vestigial_ code?\n path = root.split(os.sep)\n\n root_dir_basename = os.path.basename(root)\n if root_dir_basename == '.': # ignore parent\n pass\n\n if scrubbed_dirname(root) in args_dict['ignored_dirs']:\n pass\n\n if not os.path.dirname(root) == '.' and not scrubbed_dirname(root) in args_dict['ignored_dirs']:\n notice(msg = "I am a subdir {} of the dir {}",\n verbosity = args_dict['verbosity'],\n root_dir_basename,\n scrubbed_dirname(root))\n create_named_group(\n doc = new_doc,\n layer_set = root_dir_basename,\n under = new_doc.LayerSets(scrubbed_dirname(root)))\n elif not root_dir_basename in args_dict['ignored_dirs']:\n notice(msg = "Creating TOP LEVEL layer group {name}",\n verbosity = args_dict['verbosity'],\n name = root_dir_basename)\n create_named_group(\n doc = new_doc,\n layer_set = root_dir_basename)\n else: # Uncaught state!\n warnings.warn("\\n".join([\n 'How did I get here?',\n "\\tWhat did you give me?",\n "\\t... uh-oh, I think I will pass on these questions and current state with...",\n "\\troot_dir_basename -> {path}".format(path = root_dir_basename),\n ]))\n pass\n\n ## Note from S0AndS0; the following might be better if higher\n ## up in the execution stack of for loop, unless there is a\n ## reason to have `create_named_group` fire on empty `ff`\n if len(ff) <= 0:\n pass\n\n for filename in ff:\n if not filename.endswith(img_ext):\n pass\n\n for item in args_dict['layers_group']:\n notice(msg = "{item} in {filename}",\n verbosity = args_dict['verbosity'],\n item = item,\n filename = filename)\n if item in filename:\n notice(msg = "Creating group {group} to place layer {layer} within folder {folder}",\n verbosity = args_dict['verbosity'],\n group = item,\n layer = filename,\n folder = root_dir_basename)\n os.chdir(os.path.realpath(root))\n\n try:\n new_doc.LayerSets(root_dir_basename).LayerSets(item)\n except:\n named_group = create_named_group(\n doc = new_doc,\n layer_set = item,\n under = new_doc.LayerSets(root_dir_basename))\n create_layer_from_file(\n doc = new_doc,\n layer_name = filename,\n layer_set = named_group,\n path = os.path.realpath(filename),\n psApp = psApp)\n else:\n notice(msg = new_doc.LayerSets(root_dir_basename), verbosity = args_dict['verbosity'])\n create_layer_from_file(\n doc = new_doc,\n layer_name = filename,\n layer_set = new_doc.LayerSets(root_dir_basename).LayerSets(item),\n path = os.path.realpath(filename),\n psApp = psApp)\n\n duplicate = True\n os.chdir(args_dict['base_dir'])\n\n if duplicate:\n duplicate = False\n pass\n\n if root_dir_basename in args_dict['ignored_dirs'] or scrubbed_dirname(root) in args_dict['ignored_dirs']:\n pass\n\n os.chdir(os.path.realpath(root))\n notice(msg = "Resting files imported as layers {layer} under {folder}",\n verbosity = args_dict['verbosity'],\n layer = filename,\n folder = root_dir_basename)\n\n if not os.path.dirname(root) == '.':\n notice(msg = "layer {layer} on main group {m_group} on group {group}",\n verbosity = args_dict['verbosity'],\n layer = filename,\n m_group = os.path.dirname(root).replace('.\\\\', ''),\n group = root_dir_basename)\n create_layer_from_file(\n doc = new_doc,\n layer_name = filename,\n layer_set = new_doc.LayerSets(scrubbed_dirname(root)).LayerSets(root_dir_basename),\n path = os.path.realpath(filename),\n psApp = psApp)\n else:\n create_layer_from_file(\n doc = new_doc,\n layer_name = filename,\n layer_set = new_doc.LayerSets[root_dir_basename],\n path = os.path.realpath(filename),\n psApp = psApp)\n\n os.chdir(args_dict['base_dir'])\n</code></pre>\n<p>There'll be somethings that'll likely look familiar in the above code block, and some things that are <em><code>diff</code>erent</em>; I'll encourage readers to pull-out interesting bits and try'em in <em>scriptlets</em> because as it is neither the question's code nor what I've so far posted will function.</p>\n<p>If there are questions on why I've written some-thing some-way, feel free to ask in the comments. Basically all I've added so far is some <code>argparse</code> tricks and re-factored your code to be a little less <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\"><em><code>cyclomaticly complex</code></em></a> (it's still a bit high as it is), really you where on the <em>right track</em> @wizofe with using <code>pass</code> often and I've just tried to follow along with it.</p>\n<blockquote>\n<p>The observant readers may also be noting my use of quotes, while Python doesn't care one way or another on <em><code>'some string'</code></em> vs <em><code>"some string"</code></em>, I personally find it easier to read <em>moons later</em> when there's consistent use that means something about the contents. In this case single-quotes don't have anything <em>fancy</em> going on where as double quotes may have formatting stuffed in somewhere.</p>\n</blockquote>\n<hr />\n<p>Moving on to what could be further improved, and on track with what I was commenting earlier about and intermediate structure for organizing some of this. Some of these <code>for</code> loops might be easier to expand upon as <a href=\"https://wiki.python.org/moin/Iterator\" rel=\"nofollow noreferrer\"><code>Iterator</code>s</a>, eg...</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\nimport sys\nimport argparse\nimport comtypes.client as ct\nimport warnings\n\nfrom textwrap import dedent\nfrom utils_photoshop import (\n create_layer_from_file,\n create_named_group,\n import_all_pngs_as_layers,\n notice,\n paste_file_as_linked_layer,\n scrubbed_dirname)\n\nfrom collections import Iterator\n\n\nclass DirWalker_PhotoshopRanger(Dict, Iterator):\n """\n DirWalker_PhotoshopRanger is a hybrid class between a `dict`ionary and `Iterator`\n\n After modifications your _mileage_ may be improved\n """\n\n def __init__(base_dir, misc_dir, layers_group, ignored_dirs, verbosity = 0, **kwargs):\n super(DirWalker_PhotoshopRanger, self).__init__(**kwargs)\n self.update({\n 'base_dir': base_dir,\n 'misc_dir': misc_dir,\n 'layers_group': layers_group,\n 'ignored_dirs': ignored_dirs,\n 'verbosity': verbosity},\n 'dir_steps': os.walk(base_dir),\n 'duplicate': False,\n 'subdir': False,\n 'grouped_layers': {},\n 'psApp': ct.CreateObject('Photoshop.Application'),\n 'misc_path': os.path.join(base_dir, misc_dir))\n\n os.chdir(self['misc_path'])\n self.update(new_doc = self['psApp'].Documents.Add(600, 800, 72, 'new-psb-test', 2, 1, 1))\n self.update(misc_layers = import_all_pngs_as_layers(new_doc = self['new_doc'], path = self['misc_path']))\n # Revert the working path\n os.chdir(self['base_dir'])\n\n self.update()\n\n def __iter__(self):\n return self\n\n def next(self):\n try:\n root, dd, ff = self['dir_steps'].next()\n except (StopIteration):\n self.throw(GeneratorExit)\n\n if scrubbed_dirname(root) in self['ignored_dirs']:\n pass\n\n root_dir_basename = os.path.basename(root)\n if root_dir_basename == '.': # ignore parent\n pass\n\n ## ... do more stuff before returning `self`\n\n return self\n\n #\n # Python 2/3 compatibility stuff\n #\n\n def throw(self, type = None, traceback = None):\n raise StopIteration\n\n __next__ = next\n</code></pre>\n<p>... which may give ya the controls to <em>flatten</em> things into <em><code>categories</code></em> (first sub-directory name, or similar) via something like <em><code>self['categories'].update(hash_path: container_object)</code></em> or <em><code>self['categories'].append(container_object)</code></em></p>\n<p>In the future you might want to consider pulling some of the functions from <code>utils_photoshop/__init__.py</code> into the <code>DirWalker_PhotoshopRanger</code> <code>class</code>. Namely those that I modified to pass <code>psApp</code> about, instead maybe hav'em use <code>self['psApp']</code>.</p>\n<p>Incorporating portions of pre-existing code from the main <code>for</code> loop into the suggested <em>iterator</em> will require a little editing, eg. <em><code>...doc = new_doc,...</code></em> would become <em><code>...doc = self['new_doc'],...</code></em>, and later maybe removed if things like the <code>create_layer_from_file</code> function are pulled into the <code>class</code>. That last state might begin to look something like...</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\n## ... other import and initialization stuff\n\nclass DirWalker_PhotoshopRanger(Dict, Iterator):\n\n # ... things like __init__ above\n\n def create_named_group(self, layer_set, under = ''):\n """\n Create a New LayerSet (aka Group) in the Photoshop document (self['new_doc']).\n\n ## Arguments\n\n - layer_set (str): The name of the new Layer Set\n - under (obj): The Group Object Instance, optional\n\n ## Returns: new_layer_set (obj): The LayerSet (Group) Object\n """\n if not under: # add a top level group\n new_layer_set = self['new_doc'].layerSets.Add()\n else: # add subgroup\n new_layer_set = under.LayerSets.Add()\n\n new_layer_set.name = layer_set\n return new_layer_set\n\n def next(self):\n try:\n root, dd, ff = self['dir_steps'].next()\n except (StopIteration):\n self.throw(GeneratorExit)\n\n root_dir_basename = os.path.basename(root)\n if root_dir_basename == '.': # ignore parent\n pass\n\n if scrubbed_dirname(root) in self['ignored_dirs']:\n pass\n\n if not os.path.dirname(root) == '.' and not scrubbed_dirname(root) in self['ignored_dirs']:\n notice(msg = "Searching sub-directory {subdir} of the directory {directory}",\n verbosity = self['verbosity'],\n subdir = oot_dir_basename,\n directory = scrubbed_dirname(root))\n self.create_named_group(\n layer_set = root_dir_basename,\n under = self['new_doc'].LayerSets(scrubbed_dirname(root)))\n\n ## ... do more stuff before returning `self`\n\n return self\n\n ## ... other class stuff\n\n\nif __name__ == __main__:\n import argparse\n\n #\n # Parse the command line arguments into an `args_dict`\n #\n parser = argparse.ArgumentParser(description = __description__, epilog = __examples__, allow_abbrev = False)\n # parser.add_argument('--foo', default = 'Fooed', type = str, help = "Foo is defaulted to -> %(default)s")\n\n ## ... more argparsy goodness\n\n args_dict = vars(parser.parse_args())\n\n\n #\n # Initialize the DirWalker\n #\n f_line = ".-.".join('_' for _ in range(9))\n dir_walker = DirWalker_PhotoshopRanger(**args_dict)\n\n for i, state in enumerate(dir_walker):\n notice(msg = "{f_line}\\n{count}".format(f_line = f_line, count = i),\n verbosity = 9001)\n for k, v in state.items():\n notice(msg = "{key} -> {value}".format(key = k, value = v),\n verbosity = 9002)\n\n notice(msg = "{f_line}".format(f_line = f_line), verbosity = 9001)\n</code></pre>\n<p>If written carefully these structures can be very performant on memory use and other system resources. Though yet again I'll warn that a code-base can get <em>hairy</em> with'em, in different ways than with convenience functions, but with very similar effect. Additionally it maybe of use to know that functions that use <code>yield</code> operate very similarly to iterators, and be called <em><code>generators</code></em>, eg...</p>\n<pre class=\"lang-py prettyprint-override\"><code>def range_summinator(start, end):\n increment = 1\n if end < start:\n increment = -1\n\n while start != end:\n start += increment\n\n yield start\n\n\nr = range_summinator(0, 2)\nr.next() # -> 1\nr.next() # -> 2\nr.next()\n# Traceback (most recent call last):\n# File "<stdin>", line 1, in <module>\n# StopIteration\n</code></pre>\n<p>Okay I think this is a good pausing point to mull things over, and perhaps find bugs within my own suggestions, gotta say it was kinda a challenge without testing it in it's entirety. I may update this as thoughts percolate, and if comments/questions are posted.</p>\n<hr />\n<p>Resources useful in writing (and maybe expanding upon) above are not limited to the following;</p>\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/43786174/how-to-pass-and-parse-a-list-of-strings-from-command-line-with-argparse-argument\">how-to-pass-and-parse-a-list-of-strings-from-command-line-with-argparse-argument</a> Q&A from StackOverflow</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/7427101/simple-argparse-example-wanted-1-argument-3-results\">simple-argparse-example-wanted-1-argument-3-results</a> Q&A from StackOverflow</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/3891804/raise-warning-in-python-without-interrupting-program\">raise-warning-in-python-without-interrupting-program</a> Q&A from StackOverflow</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/73663/terminating-a-python-script\">terminating-a-python-script</a> Q&A from StackOverflow</p>\n</li>\n<li><p><a href=\"https://docs.python.org/2/library/textwrap.html#textwrap.dedent\" rel=\"nofollow noreferrer\"><code>textwrap.dedent</code></a> Python documentation</p>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/argparse.html#prog\" rel=\"nofollow noreferrer\"><code>argparse</code></a> Python documentation</p>\n</li>\n<li><p><a href=\"https://wiki.python.org/moin/Iterator\" rel=\"nofollow noreferrer\"><code>Iterator</code></a> Python documentation</p>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/warnings.html\" rel=\"nofollow noreferrer\"><code>warnings</code></a> Python documentation</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T07:50:00.693",
"Id": "219239",
"ParentId": "219028",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219239",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:41:04.373",
"Id": "219028",
"Score": "5",
"Tags": [
"python",
"image",
"file-system"
],
"Title": "Find png files in folder structure and map them to Photoshop groups and layers"
} | 219028 |
<p>I have 3 types of coins: Gold, Silver, Copper.<br>
1 silver = 100 copper.<br>
1 gold = 100 silver. </p>
<p>My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is: </p>
<pre><code>def api_wallet_translate_gold(value):
"""Translate a value into string of money"""
if value >= 10000: # Gold
return ("{0} gold, {1} silver and {2} copper."
.format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
elif value >= 100: # Silver
return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
else: # Copper
return "{0} copper.".format(str(value)[-2:])
</code></pre>
<p>It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it. </p>
<p>Note: We never know how many gold digits we have, it could be 999999 to 1</p>
| [] | [
{
"body": "<p>It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.</p>\n\n<p>You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"noreferrer\"><code>divmod()</code></a>. After than it's a matter of deciding how you want to format the resulting dict:</p>\n\n<pre><code>coins = [\n (\"gold\", 100 * 100),\n (\"silver\", 100), \n (\"copper\", 1)\n]\n\ndef translate_coins(value, coins):\n res = {}\n for coin, v in coins:\n res[coin], value = divmod(value, v)\n return res \n\ntranslate_coins(1013323, coins)\n</code></pre>\n\n<p>Result: </p>\n\n<pre><code>{'gold': 101, 'silver': 33, 'copper': 23}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:08:41.117",
"Id": "423048",
"Score": "0",
"body": "This is almost perfect @MarkM, though the `def translate_coins(value, coins):` line combined with `res[coin], value = divmod(value, v)`, could have the `value`s (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a `dict` for `coins` instead of a list of tuples?... Then `for coin, quantity in coins.items():` could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:13:49.157",
"Id": "423051",
"Score": "2",
"body": "Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:46:31.280",
"Id": "423061",
"Score": "0",
"body": "After further testing I see what you're doing, clever @MarkM, really clever there with reassigning `value`... though I don't envy debugging such mutations, it __does__ totally make sense in this context to mutate... I also now see your wisdom in using a `list` of `tuples`, and retract my previous question in regards to using a `dict` as input to the `translate_coins` function; that would have made code far _hairier_ than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:58:36.090",
"Id": "219031",
"ParentId": "219029",
"Score": "9"
}
},
{
"body": "<p>That was a nice little break from work, tks for asking this question :-)\nI think this is a good use case for an object/class vs. a method.</p>\n\n<p>I would create a Currency class, which then allows you to either print it, or access its attributes independently...</p>\n\n<pre><code>class Currency(object):\n\n COPPER_CONVERSION_MAP = {\n 'copper': 1,\n 'gold': 100 * 100,\n 'silver': 100\n }\n gold = 0\n silver = 0\n copper = 0\n\n def __init__(self, copper=0, silver=0, gold=0):\n # convert all inputs into copper\n self.copper = (\n copper +\n silver * self.COPPER_CONVERSION_MAP['silver'] +\n gold * self.COPPER_CONVERSION_MAP['gold']\n )\n self.break_currency()\n\n def break_currency(self):\n for coin_type in ['gold', 'silver']:\n coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])\n setattr(self, coin_type, coins)\n self.copper = coppers\n\n def __str__(self):\n return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)\n</code></pre>\n\n<p>You can then consume like so:</p>\n\n<pre><code>>>> c = Currency(copper=653751735176)\n>>> str(c)\n'65,375,173 gold, 51 silver and 76 copper'\n>>> c.copper\n76\n>>> c.silver\n51\n>>> c.gold\n65375173\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T03:14:36.147",
"Id": "423112",
"Score": "0",
"body": "Welcome to Code Review. Now that you have created `Currency` and can compare both approaches and executions (including [MarkM's](https://codereview.stackexchange.com/a/219031) thereof: What is your assessment of the relative merits?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:11:18.960",
"Id": "219056",
"ParentId": "219029",
"Score": "3"
}
},
{
"body": "<p>Yet another possibility is to use a <code>namedtuple</code> to hold the coins.</p>\n\n<pre><code>from collections import namedtuple\n\nclass Currency(namedtuple(\"Currency\", \"gold silver copper\")):\n\n def __new__(cls, copper):\n gold, copper = divmod(copper, 10000)\n silver, copper = divmod(copper, 100)\n return super().__new__(cls, gold, silver, copper)\n\n def __str__(self):\n return \"{} gold, {} silver, {} copper\".format(*self)\n\nc = Currency(1234567)\n\nprint(c)\n</code></pre>\n\n<p>Here, I’ve hard-coded the conversion, but this could easily be adapted to variable exchange rate between gold, silver and copper coins, similar to other answers.</p>\n\n<p>The benefit of the named tuple is the individual coin counts are accessible:</p>\n\n<pre><code>print(c.gold, c.silver, c.copper)\n</code></pre>\n\n<p>Since we now have a class for the <code>Currency</code> object, it would be possible to add basic arithmetic operators, so operations can be concisely expressed, if desired.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:37:49.913",
"Id": "219078",
"ParentId": "219029",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219031",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:46:46.173",
"Id": "219029",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"formatting"
],
"Title": "Split coins into combinations of different denominations"
} | 219029 |
<p>I just want to confirm that I am versioning my "versionable" fields correctly, and that there isn't another, better way to do this.</p>
<p>I have a table <code>event</code>, a record of an event in time. It has some fields that I want to be invariant, like it's ID and event series it is associated with. It also has some fields that I want to be editable, like the date or the description. The other issue is that I have foreign keys on the auto_increment ids of both tables, which is why I think I need two tables and not just one, or? But I also want to keep the history of the variant fields, So I created two tables:</p>
<h2>invariant</h2>
<pre><code>id int
series int
active boolean
</code></pre>
<p>and</p>
<h2>variant</h2>
<pre><code>eventID int //foreign key to the invariant ID field
id int //this table needs its own id which serves as a foreign key on another table
date Date
description varchar(255)
active boolean
</code></pre>
<p>When an edit is made to the variant fields, I am switching the active Boolean on existing rows with the same eventID to false. then when I insert my new version, I can get the just latest version on the invariant - variant join by specifying <code>where active=true</code>. </p>
<p>If/when I want to delete the event entirely, I am setting active to false in the invariant table.</p>
<p>As I said at the top, I just want to confirm that this is an optimal solution for the specified requirements, or if there are better ways or things I am not understanding</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:49:47.313",
"Id": "423062",
"Score": "0",
"body": "Why do you need the active column on the invariant table? Sounds like the value can be retrieved based on the variant table"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:55:42.890",
"Id": "423063",
"Score": "0",
"body": "_\"and event series it is associated with\"_ Are you sure the event series is invariant? You mentioned you can delete events."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T18:07:04.667",
"Id": "423064",
"Score": "0",
"body": "@dustytrash I think the language I've used is confusing you. I am using the active field in both tables to \"delete\" records without actually removing them from the database. Does that make sense? To your other question, yes eventSeries is invariant. It is used among other things to ensure that different clients can't see or edit other clients events"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:31:26.217",
"Id": "423089",
"Score": "0",
"body": "Why am I getting down voted on this?"
}
] | [
{
"body": "<p>Do not use an 'active' column as a way of joining a table.</p>\n\n<blockquote>\n <p>The other issue is that I have foreign keys on the auto_increment ids\n of both tables</p>\n</blockquote>\n\n<p>I'm assuming you mean the invariant & variant tables both have PrimaryKeys which are auto_incremented. If so, this is fine. Most tables have an auto incremented primary key.</p>\n\n<p>You could put all the columns onto the variant table (which is where they belong) and have an audit table. The audit table would contain the old value(s) & new value(s) along with the changed date.</p>\n\n<p>If you wish to continue with your unique versioning system, I would still remove the active indicator on both tables, and instead sort by latest date to find the current. If no rows exist on invariant, either variant is 'inactive' or should be deleted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T18:02:21.347",
"Id": "219038",
"ParentId": "219032",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219038",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T16:36:22.420",
"Id": "219032",
"Score": "0",
"Tags": [
"sql",
"mysql"
],
"Title": "Saving row versions in MySQL"
} | 219032 |
<p>I have solved the jug problem with 3 jugs:</p>
<blockquote>
<p>For jugs size A, B and C find the minimum number of steps to reach D, where D < max (A,B,C)</p>
</blockquote>
<p>My Python 3 code is below. I am wondering if there are other ways, faster ways or more efficiency ways to compute the answer.</p>
<pre><code>"""
Solving the "how many moves to get solution d for jugs size a, ,b, c
"""
"""Function make move"""
#Create list of visited solutions
listPrevSolutions = []
#Create correspnding list of number of steps to reach solution
listTotalSteps = []
list_index_steps = []
def MoveWater (jugMax,
jugState,
targetVol,
runningTotal,
previousSteps,
listLength):
global list_index_steps
noNewSolutionAdded = 1
listPosition = listLength
jugA_max = jugMax[0]
jugB_max = jugMax[1]
jugC_max = jugMax [2]
jugA_state = jugState[0]
jugB_state = jugState[1]
jugC_state = jugState[2]
if jugA_state == targetVol or jugB_state == targetVol or jugC_state == targetVol:
print ("Target achieved in 1 step. Fill up a jug")
return True
#Move 1: move from A into B (if room) AND (if not state doesn't exist)
if jugA_state !=0:
if jugB_state < jugB_max:
#Empty A into B if room
if jugB_state + jugA_state <= jugB_max:
new_jugA_state, new_jugB_state = 0, jugB_state + jugA_state
else: #Empty as much of A into B
new_jugA_state, new_jugB_state = (jugA_state - (jugB_max-jugB_state)), jugB_max
new_jugC_state = jugC_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 2: move from A into C (if room) AND (if not state doesn't exist)
if jugA_state !=0:
if jugC_state < jugC_max:
#Empty A into C if room
if jugC_state + jugA_state <= jugC_max:
new_jugA_state, new_jugC_state = 0, jugC_state+ jugA_state
else: #Empty as much of A into C
new_jugA_state, new_jugC_state = (jugA_state - (jugC_max-jugC_state)), jugC_max
new_jugB_state = jugB_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 3: move from B into A (if room) AND (if not state doesn't exist)
if jugB_state !=0:
if jugA_state < jugA_max:
#Empty B into A if room
if jugA_state + jugB_state <= jugA_max:
new_jugB_state, new_jugA_state = 0, jugA_state + jugB_state
else: #Empty as much of B into A
totalToMove = jugA_max - jugA_state
new_jugA_state, new_jugB_state = jugA_max, jugB_state - totalToMove
new_jugC_state = jugC_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 4: move from B into C (if room) AND (if not state doesn't exist)
if jugB_state !=0:
if jugC_state < jugC_max:
#Empty B into C if room
if jugC_state + jugB_state <= jugC_max:
new_jugB_state, new_jugC_state = 0, jugC_state + jugB_state
else: #Empty as much of B into C
new_jugB_state, new_jugC_state = (jugB_state - jugC_max), jugC_max
new_jugA_state = jugA_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 5: move from C into B (if room) AND (if not state doesn't exist)
if jugC_state !=0:
if jugB_state < jugB_max:
#Empty C into B if room
if jugC_state + jugB_state <= jugB_max:
new_jugC_state, new_jugB_state = 0, jugB_state + jugC_state
else: #Empty as much of C into B
totalToMove = jugB_max - jugB_state
new_jugB_state, new_jugC_state = jugB_max, jugC_state - totalToMove
new_jugA_state = jugA_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 6: move from C into A (if room) AND (if not state doesn't exist)
if jugC_state !=0:
if jugA_state < jugA_max:
#Empty C into A if room
if jugA_state + jugC_state <= jugA_max:
new_jugC_state, new_jugA_state = 0, jugA_state + jugC_state
else: #Empty as much of C into A
totalToMove = jugA_max - jugA_state
new_jugA_state, new_jugC_state = jugA_max, jugC_state - totalToMove
new_jugB_state = jugB_state
if [new_jugA_state,new_jugB_state,new_jugC_state] not in listPrevSolutions:
listPrevSolutions.append([new_jugA_state,new_jugB_state,new_jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if new_jugA_state == targetVol or new_jugB_state == targetVol or new_jugC_state == targetVol:
print (targetVol,"ml reached in", runningTotal+1,"steps")
print_Steps_Taken(previousSteps + [listPosition-1])
return True
#Move 7 - Empty A
if jugA_state != 0:
if jugB_state != 0 or jugC_state !=0:
if [0,jugB_state,jugC_state] not in listPrevSolutions:
listPrevSolutions.append([0,jugB_state,jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
#Move 8 - Empty B
if jugB_state != 0:
if jugA_state != 0 or jugC_state !=0:
if [jugA_state,0,jugC_state] not in listPrevSolutions:
listPrevSolutions.append([jugA_state,0,jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
#Move 9 - Empty C
if jugC_state != 0:
if jugB_state != 0 or jugA_state !=0:
if [jugA_state,jugB_state,0] not in listPrevSolutions:
listPrevSolutions.append([jugA_state,jugB_state,0])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
#Move 10 - Fill A
if jugA_state!=jugA_max:
if jugB_state != jugB_max or jugC_state!=jugC_max:
if [jugA_max,jugB_state,jugC_state] not in listPrevSolutions:
listPrevSolutions.append([jugA_max,jugB_state,jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
#Move 11 - Fill B
if jugB_state!=jugB_max:
if jugA_state!=jugA_max or jugC_state!=jugC_max:
if [jugA_state,jugB_max,jugC_state] not in listPrevSolutions:
listPrevSolutions.append([jugA_state,jugB_max,jugC_state])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
#Move 12 - Fill C
if jugC_state!=jugC_max:
if jugA_state != jugA_max or jugB_state!=jugB_max:
if [jugA_state,jugB_state,jugC_max] not in listPrevSolutions:
listPrevSolutions.append([jugA_state,jugB_state,jugC_max])
listTotalSteps.append(runningTotal+1)
list_index_steps.append(previousSteps + [listPosition])
listPosition +=1
noNewSolutionAdded = 0
if noNewSolutionAdded == 1 and listPrevSolutions.index(jugState) == len(listPrevSolutions) - 1:
print ("No new possible solutions")
return True
return False
def print_Steps_Taken(previousSteps):
for index in previousSteps:
print (listPrevSolutions[index])
def setjugVolumes():
#Set jug sizes (a,b,c) and target volume (d)
a = int(input("Please enter volume of largest jug: "))
b = int(input("Please enter volume of second largest jug: "))
c = int(input("Please enter volume of third largest jug: "))
jugsMax = [a,b,c]
targetVol = int(input("Please enter target volume: "))
return jugsMax, targetVol
def possibleStartStates():
#Set jug states
# (full, empty, empty), (full, full empty),
#(empty, full, empty), (empty, full, full),
#(empty, empty, full) ,(full, empty, full),
startStates = [
[5,0,0], [5,3,0],
[0,3,0], [0, 3,1],
[0,0,1], [5,0,1]]
return startStates
if __name__ == "__main__":
jugMax, targetVol = setjugVolumes()
#Get all possible start states - add featur later and run for loop for ALL possible
#...states. Add this feature later
jugA_max = jugMax[0]
jugB_max = jugMax[1]
jugC_Max = jugMax[2]
#Add first state to list with runningTotal
listPrevSolutions.append([jugA_max, 0,0])
listTotalSteps.append(1)
listPrevSolutions.append([0, jugB_max,0])
listTotalSteps.append(1)
listPrevSolutions.append([0, 0,jugC_Max])
listTotalSteps.append(1)
listPrevSolutions.append([jugA_max, jugB_max,0])
listTotalSteps.append(2)
listPrevSolutions.append([jugA_max, 0,jugC_Max])
listTotalSteps.append(2)
listPrevSolutions.append([0, jugB_max,jugC_Max])
listTotalSteps.append(2)
list_index_steps.append ([0])
list_index_steps.append ([1])
list_index_steps.append ([2])
list_index_steps.append ([3])
list_index_steps.append ([4])
list_index_steps.append ([5])
#Now run the function
counter = 0
for item in listPrevSolutions:
jugState = item
runningTotal = listTotalSteps[counter]
previousSteps = list_index_steps[counter]
listLength = len(listPrevSolutions)
x = MoveWater(jugMax,
jugState,
targetVol,
runningTotal,
previousSteps,
listLength)
counter +=1
if x == True:
break
</code></pre>
<hr>
<p>Follow-up question: <a href="https://codereview.stackexchange.com/q/219211/100620">Solve the jug problem for n jugs</a></p>
| [] | [
{
"body": "<p>You’ve got too much code.</p>\n\n<p>Not too much code to review - we can review a lot of code. You’ve written too much code for this problem. You’ve enumerated all the possible states, and hard coded variable names for all the possible states and constraints. You’ve got <code>jugA_state</code>, <code>jugB_state</code> and <code>jugC_state</code> for the current volumes of the 3 jugs and <code>jugA_max</code>, <code>jugB_max</code> and <code>jugC_max</code> (and sometimes <code>jugC_Max</code>!) for the capacities of the 3 jugs. If you have to solve a 4 jug problem, your amount of code is going to skyrocket. Never mind a 5 jug problem!</p>\n\n<p>Instead, you should number the jugs 0, 1 and 2, and used indexing for the capacities and current volumes. You can use a tuple for the capacities, since it is fixed for the duration of the problem.</p>\n\n<pre><code>capacities = (5, 3, 1)\nvolumes = [5, 0, 0]\n</code></pre>\n\n<p>Moving water from one jug into any other jug can be done by one function:</p>\n\n<pre><code>def pour(from:int, to:int, volumes:list, capacities:tuple) -> list:\n transfer = min(volumes[from], capacities[to] - volumes[to])\n if transfer > 0:\n volumes = volumes[:] # Copy the current state (volumes)\n volumes[from] -= transfer\n volumes[to] += transfer\n return volumes # Return the new state (volumes)\n return None\n</code></pre>\n\n<p>Pouring from each jug to every other jug is a simple double iteration:</p>\n\n<pre><code>for from in range(num_jugs):\n for to in range(num_jugs):\n if from != to:\n new_volumes = pour(from, to, volumes, capacities)\n if new_volumes:\n # Valid pour - next, check if this is a new state, record move, etc.\n</code></pre>\n\n<p>The “empty a jug” and “fill a jug” moves are simpler; only a single iteration is required.</p>\n\n<p>Checking if any jug has reached the target volume is easy. Just use the <code>any()</code> function with a generator expression:</p>\n\n<pre><code>if any(volume == target_volume for volume in volumes):\n print(\"Target volume reached\")\n</code></pre>\n\n<hr>\n\n<p>More advanced:</p>\n\n<p>Testing if a new state is contained within a list of already visited states. You are using <code>[...] in listPreviousSolutions</code>. Instead of testing for containment in a <code>list</code>, which is an <span class=\"math-container\">\\$O(N)\\$</span> search, you could use containment in a <code>set</code>, which is an <span class=\"math-container\">\\$O(1)\\$</span> lookup. But since your states are themselves lists, which are mutable, you must first convert them into a <code>tuple</code>, which is immutable, and so is hashable which is required for sets.</p>\n\n<pre><code>previousStates = set()\n\n#...\n\nnew_state = ...\nnew_state = tuple(new_state)\nif new_state not in previousStates:\n previousStates.add(new_state)\n # ... etc ...\n</code></pre>\n\n<hr>\n\n<p>General PEP-8 comments.</p>\n\n<p>Use consistent naming. You’ve used <code>mixedCase</code> for some variables (<code>targetVol</code>), <code>snake_case</code> for others (<code>list_index_steps</code>), and even a combination of the two (<code>jugA_max</code>). <code>snake_case</code> is recommended by the PEP-8 standard.</p>\n\n<p>Similar for function names. You’ve use <code>CamelCase</code> (<code>MoveWater</code>) , <code>mixedCase</code> (<code>possibleStartStates</code>) and a mashup of <code>mixedCase</code> and <code>snake_case</code> (<code>print_Steps_Taken</code>). You’ve also inconsistently capitalized when using <code>mixedCase</code> (<code>setjugVolumes</code> ... the <code>j</code> should have been capitalized). Again, be consistent. I believe PEP-8 recommends <code>mixedCase</code> for function names.</p>\n\n<p>Spaces. Put a space around operators, like <code>!=</code> and <code>+=</code>. Put a space after commas in lists and function calls. Do not put a space before the <code>(</code> in function calls (<code>list_index_steps.append ([5])</code>).</p>\n\n<p>Use a checker like <code>pylint</code> to validate your code against the PEP-8 standards, checking for these and other coding guidelines.</p>\n\n<hr>\n\n<p>Don’t use an integer to represent a boolean state, and avoid negations in variable names. So instead of:</p>\n\n<pre><code>noNewSolutionsAdded = 1\n\n# ...\n\nif ... :\n noNewSolutionsAdded = 0\n\n# ...\n\nif noNewSolutionsAdded == 1 and ...:\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>solutions_added = False\n\n# ...\n\nif ...:\n solutions_added = True\n\n# ...\n\nif not solutions_added and ...:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T10:25:13.383",
"Id": "423162",
"Score": "0",
"body": "Really good answer! But PEP-8 recommends `snake_case` for function and variable names. ☺️"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:22:15.600",
"Id": "423203",
"Score": "0",
"body": "Thanks. I will work on v2 now :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:40:31.180",
"Id": "219072",
"ParentId": "219033",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "219072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:06:30.560",
"Id": "219033",
"Score": "6",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Jug problem - 3 jugs"
} | 219033 |
<p>I have worked on a SFML Game/Game-Engine Project for 2 months now and am looking for some feedback in terms of...</p>
<ul>
<li>Is this a valid approach for a Game class?</li>
<li>Are there any glaring C++ coding practice mistakes?</li>
</ul>
<p>The following code is from my Game class which is the main organizational unit of the Game/Engine. I use a Scene(State) approach, meaning that every Scene/Screen in the Game is a closed of unit with it's Entities being updated from the Game class.</p>
<p>Game.h</p>
<pre><code>#ifndef GAME_H
#define GAME_H
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <string>
#include <vector>
#include <map>
#include "../game/Entity.h"
#include "../game/FpsCounter.h"
#include "../game/EScene.h"
#include "../game/Scene.h"
#include "../game/InputHandler.h"
#include "../game/WindowStyle.h"
#include "../menu/VBox.h"
#include "../menu/HBox.h"
#include "../menu/ButtonMenu.h"
#include "../animation/TranslateAnimation.h"
namespace ProjectSpace
{
/**
* @brief Core class of the Game. Contains main Game-Loop and Event-Loop.
*/
class Game
{
public:
/**
* @brief Constructs a Game detecting the monitor's resolution automatically.
*
* @param[in] windowTitle Title of the Game's window.
*/
Game(std::string windowTitle, WindowStyle style = DEFAULT);
/**
* @brief Constructs a Game.
*
* @param[in] screenWidth Width of the Game's window.
* @param[in] screenHeight Height of the Game's window.
* @param[in] windowTitle Title of the Game's window.
*/
Game(unsigned int screenWidth, unsigned int screenHeight, std::string windowTitle, WindowStyle style = DEFAULT);
/**
* @brief Destroys every Scene of the Game.
*/
~Game();
/**
* @brief Starts the Game/Game-Loop.
*/
void start();
/**
* @brief Sets the current scene.
*
* @param[in] scene The scene
*/
void setCurrentScene(EScene scene);
private:
/**
* @brief Helper function for initializing everything before starting the Game. Creates all Sprites and stuff...
*/
void init();
sf::RenderWindow window; // Window of the Game.
FpsCounter fpsCounter; // Fps Counter of the Game.
InputHandler inputHandler; // InputHandler for input Actions that are always available in the game (Not Scene dependant).
VBox menu;
std::map<EScene, Scene*> scenes; // All Scenes of the Game.
Scene* currentScene; // Scene that is currently active (is drawn and updated).
TranslateAnimation* menuForward;
TranslateAnimation* menuBackward;
ButtonMenu* buttonMenu;
float windowWidth;
float windowHeight;
};
}
#endif
</code></pre>
<p>Game.cpp</p>
<pre><code>#include "Game.h"
#include <SFML/System/Clock.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/VideoMode.hpp>
#include "../menu/TextBox.h"
#include "../animation/FadeAnimation.h"
#include "../menu/Button.h"
#include "../menu/ButtonMenu.h"
#include "InputHandler.h"
#include "Scene.h"
#include "Factory.h"
namespace ProjectSpace
{
Game::Game(std::string windowTitle, WindowStyle style)
: window{sf::VideoMode{sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height}, windowTitle, style},
fpsCounter{"rsrc/fonts/arial.ttf"}, currentScene{nullptr}, windowWidth{(float)sf::VideoMode::getDesktopMode().width},
windowHeight{(float)sf::VideoMode::getDesktopMode().height}
{
window.setFramerateLimit(60);
init();
}
Game::Game(unsigned int screenWidth, unsigned int screenHeight, std::string windowTitle, WindowStyle style)
: window{sf::VideoMode{screenWidth, screenHeight}, windowTitle, style}, fpsCounter{"rsrc/fonts/arial.ttf"},
currentScene{nullptr}
{
// Makes sure that not more than 60 Frames per Second are calculated. Save Ressources.
window.setFramerateLimit(60);
init();
}
Game::~Game()
{
for (auto const& p : scenes)
{
delete p.second;
}
}
void Game::start()
{
sf::Clock clock{};
// This is main Game-Loop
while (window.isOpen())
{
// At the start of each iteration "clock.restart()" will return the time that the last iteration took.
// This is so that all objects of the current iteration know how much time has passed since the last frame.
sf::Time time = clock.restart();
float frameTime = time.asSeconds();
// std::cout << "frameTime: " << frameTime << std::endl;
// This is the Event-Loop (Hier muessen wir nochmal gucken, was wir damit anstellen koennen. Ist wohl ziemlich wichtig in SFML.)
sf::Event event;
while (window.pollEvent(event))
{
// For example by pressing the Close-Button on a Window, a Closed Event is created.
if (event.type == sf::Event::Closed)
{
window.close();
}
}
currentScene->update(time);
inputHandler.update(time);
fpsCounter.update(time);
menu.update(time);
menuForward->update(time);
menuBackward->update(time);
buttonMenu->update(time);
// Default way of drawing stuff in SFML. Clear the window, draw you'r stuff and then display it.
window.clear();
window.draw(*currentScene);
window.draw(fpsCounter);
window.draw(menu);
window.display();
}
}
void Game::setCurrentScene(EScene scene)
{
if (scenes.count(scene) == 0)
{
std::cout << "@Game::setCurrentScene(): Given scene is not known to Game." << std::endl;
return;
}
currentScene = scenes[scene];
}
void Game::init()
{
// Creating Levels
scenes[EScene::DEBUG] = Factory::CREATE_DEBUG_SCENE(window);
scenes[EScene::LEVEL_ONE] = Factory::CREATE_DEBUG_SCENE_2(window);
currentScene = scenes[EScene::DEBUG];
// Creating Menu
Button* btn = new Button{[this]()
{
window.close();
}, window, "EXIT"};
Button* btn2 = new Button{[this]()
{
window.close();
}, window, "EXIT"};
Button* btn3 = new Button{[this]()
{
setCurrentScene(EScene::DEBUG);
}, window, "Debug Level"};
Button* btn4 = new Button{[this]()
{
setCurrentScene(EScene::LEVEL_ONE);
}, window, "Level 1"};
menu.addMenuElements({btn, btn2, btn3, btn4});
menu.setPosition(-10, 50);
menu.setSpacing(5);
buttonMenu = new ButtonMenu{{btn, btn2, btn3, btn4}, &inputHandler};
menuForward = new TranslateAnimation{&menu, sf::Vector2f{-250, 50}, sf::Vector2f{-10, 50}, 0.5f};
menuBackward = new TranslateAnimation{&menu, sf::Vector2f{-10, 50}, sf::Vector2f{-250, 50}, 0.5f};
// Setting up input handler
inputHandler.add([this]()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
menuBackward->stop();
menuForward->start();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))
{
menuForward->stop();
menuBackward->start();
}
});
}
}
</code></pre>
<p>GitHub Repo: <a href="https://github.com/Dante3085/ProjectSpace/tree/bb79a0861a508ed06ffc05b94129b31fd756a1f5" rel="nofollow noreferrer">https://github.com/Dante3085/ProjectSpace</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:34:37.753",
"Id": "423586",
"Score": "0",
"body": "Why did you check in all the binaries?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:13:10.023",
"Id": "423606",
"Score": "0",
"body": "@yuri I put SFML and mingw in there because I work on multiple systems and with 2 other guys, so that they just have to clone the repo for it to compile and run on windows.\n\nAs for any other weird looking things in the repository, it's inexperience on my part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T10:05:38.417",
"Id": "423611",
"Score": "0",
"body": "What about the build artifacts? Do they need to be checked in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:24:19.823",
"Id": "423618",
"Score": "0",
"body": "@yuri Definetly not. You're certainly right. I've put *.o in the gitignore a few days ago, so object files don't get commited anymore, but I am not shure how to erase them from origin-repo on github. I've made that mistake long before I had a gitignore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:37:28.940",
"Id": "423621",
"Score": "0",
"body": "You can remove them with [git rm](https://git-scm.com/docs/git-rm) and then commit that. Ideally you would make a new repo that never includes any artifacts or binaries and instead distribute those in some other form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T16:43:07.917",
"Id": "423636",
"Score": "0",
"body": "@yuri That worked. Thank you for you'r Feedback. I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:31:42.880",
"Id": "423655",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/92980/discussion-between-sparda-dante3085-and-yuri)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:19:56.950",
"Id": "219034",
"Score": "4",
"Tags": [
"c++",
"game",
"sfml"
],
"Title": "Central class for SFML game engine"
} | 219034 |
<p>I am making a project just for fun that employs the 3DES algorithm in Java. I was wondering if my algorithm looks secure. Is there any advice or feedback you could give me? Do I need to include an IV? Am I transferring the salt successfully?</p>
<p>My code can encrypt a file using the Triple DES algorithm.</p>
<pre><code>// author @Alex Matheakis
public static void main(String[] args) throws Exception {
// file to be encrypted
Scanner inputScanner = new Scanner(System.in);
System.out.println("Enter filename");
String filename = inputScanner.nextLine();
FileInputStream inputFile = new FileInputStream("C:\\Documents\\Encryptor\\" + filename + ".txt");
// encrypted file
FileOutputStream outputFile = new FileOutputStream("C:\\Documents\\Encryptor\\encryptedfile.des");
// password to encrypt the file
String passKey = "password";
byte[] salt = new byte[8];
Random r = new Random();
r.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(passKey.toCharArray());
SecretKeyFactory secretKeyFactory = SecretKeyFactory
.getInstance("PBEWithSHA1AndDESede");
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 99999);
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
outputFile.write(salt);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inputFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outputFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outputFile.write(output);
inputFile.close();
outputFile.flush();
outputFile.close();
inputScanner.close();
System.out.println("File has been Encrypted.");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:29:49.770",
"Id": "423069",
"Score": "7",
"body": "[3DES is effectively broken and retired](https://www.cryptomathic.com/news-events/blog/3des-is-officially-being-retired), so your code is \"insecure\" in terms of the cipher strength."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:14:34.180",
"Id": "423134",
"Score": "2",
"body": "@BenjaminUrquhart It's not optimal and it is being officially retired, but it's not \"effectively broken\". The main issue is the small block size (limiting the amount you can encrypt with any given key, depending on block mode), and vulnerability to linear cryptanalysis (which is only an issue after on the order of a terabyte of known-plaintext is encrypted)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:59:02.200",
"Id": "423199",
"Score": "0",
"body": "@forest fair enough, I did make that assumption."
}
] | [
{
"body": "<p>It's kind of secure, but it uses older algorithms.</p>\n\n<p>Although Benjamin correctly identifies 3DES, I would not call 3 key triple DES \"broken\". It still delivers a security of about 112 bits which nobody sane will try and break.</p>\n\n<p>There is a chance that somebody would try and break your password though, and the shown password is clearly not random enough as it only contains 12 lowercase characters from a 26 character alphabet, which translates in 4.7 * 12 = 56 bits of entropy (each <em>fully random</em> letter delivers about 4.7 bits of entropy, 5.7 if upper and lowercase are randomly mixed). It may be that the relatively high number of iterations (99,999 iterations) will save you, but you're only supplying the 3DES key with half the entropy it requires to obtain the 112 bit security, so that's not enough.</p>\n\n<p>The derivation method is probably secure, but it likely also performs too many operations which may just benefit an adversary. You are much better off with a more modern key derivation method such as Argon2. Likewise, we generally try and use authenticated encryption nowadays instead of the underlying CBC mode encryption. Problem is that there is no such prebuild solution directly available from the Java API, so you'd have to implement a copy of a protocol yourself or use a good library. Fernet would e.g. give you a more modern format.</p>\n\n<p>You may want to include a version number to your encrypted messages so you can upgrade your algorithms or iteration count / salt size (etc.) at a later date. That way you can recognize older ciphertext, decrypt it, re-encrypt it with the newer protocol or keys and finally securely erase the old ciphertext. Or you could add additional encryption by encrypting it again using a different key derived from the password (a bit harder to do and to decrypt, but certainly possible).</p>\n\n<p>SHA-1 has been broken, but not enough for it to become a problem for PBE. Of course you should still try and avoid old algorithms such as 3DES and SHA-1 and replace them with new ones such as AES and SHA-256.</p>\n\n<p>Oh, almost forgot. Triple DES has a block size of 64 bits / 8 bytes, which is deemed pretty small nowadays. You could lose some confidentiality when encrypting large files with it in CBC mode because blocks may start to repeat (you might lose much more confidentiality with other modes of operation).</p>\n\n<hr>\n\n<p>The idea of the password consisting of characters is that you can clear a char array, while you cannot do the same thing for a <code>String</code>. If you supply the password as a string then you lose this ability.</p>\n\n<p>Do you know that there is a <code>CipherInputStream</code> and <code>CipherOutputStream</code> that can be put in front of a <code>FileInputStream</code> or <code>FileOutputStream</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:02:48.637",
"Id": "423176",
"Score": "0",
"body": "Great advice with the password I did not realise that thanks. I have also looked further into SHA-1 but I believe it will be okay for now, it's more secure than MD5 at least. I am having trouble trying to implement CipherInputStream and CipherOutputStream though is there any chance you could help me please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:33:06.980",
"Id": "423190",
"Score": "1",
"body": "Probably, but please ask on StackOverflow (check for dupes first). I've got some things to take care of today, so I might not be as responsive. There are other good programmers there though (kelalaka is of great help, jbtule etc.)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T21:09:11.313",
"Id": "424651",
"Score": "0",
"body": "sorry just had a thought about what block mode this code uses. Could you please let me know how you know it's ECB mode when it is not mentioned in the code? @Maarten Bodewes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T21:14:44.817",
"Id": "424653",
"Score": "1",
"body": "I mentioned CBC, not ECB. Actually, my search on the internet page only showed one \"ECB\" mentioned and that's in your comment (probably now 3 :P). I mentioned CBC mode, and that's described e.g. [here](https://openjdk.java.net/jeps/121) and, probably more authoritative, [here](https://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJCEProvider)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T12:18:22.137",
"Id": "424745",
"Score": "0",
"body": "Great thank you @Maarten I have one last question sorry, since it encrypts with CBC mode surely I should include reading/writing the IV within my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T15:19:33.157",
"Id": "424909",
"Score": "1",
"body": "Well, yes, but as long as your salt is random for each encryption (preferably reencryption of the same file) then your key is unique. In that case your key / IV combination is of course also unique *even* if the IV is static. What you need to do in your code is to store the salt with the ciphertext, but you need to do that anyway to be able to decrypt. OpenSSL uses a similar format and doesn't store the IV either."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T18:10:42.923",
"Id": "219040",
"ParentId": "219039",
"Score": "18"
}
},
{
"body": "<p>No, it's not secure.</p>\n\n<p>Your code is using <code>Random</code> instead of <code>SecureRandom</code>, which limits the entropy of the salt to 48 bits.</p>\n\n<p>In addition, as an auditor I would immediately reject any \"security code\" that is implemented directly in the <code>main</code> method. To demonstrate that you understand the building blocks of a cipher, your code has to be structured into manageable methods that make the relation between the basic ingredients as clear as possible. The code should explain how the encryption works, without overwhelming the reader with needless technical details. Keeping track of 5 variables in your head is already difficult.</p>\n\n<p>The outermost method should be <code>encrypt(InputStream in, OutputStream out, Key key, Random rnd)</code>. Only if you provide this kind of API can you write useful unit tests to demonstrate that the encryption code works for at least a few select examples.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T19:23:05.400",
"Id": "423077",
"Score": "1",
"body": "Hmm, good catch about the `Random`. Although random required for a salt is kind of in between; you just don't want salt values never to repeat, but otherwise they don't need much security. Still `SecureRandom` should definitely be used here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:20:33.443",
"Id": "423088",
"Score": "5",
"body": "Why `File`? Why not `InputStream` and `OutputStream`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T22:27:37.247",
"Id": "423094",
"Score": "0",
"body": "Hmm, for an outward facing interface function I would deem `File` an acceptable parameter - but the actual encryption should always take place on streams or buffers. Note that with `File` you are stuck to the file system, but you could e.g. switch to memory mapped I/O and encrypting / decrypting `ByteBuffer`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T03:55:40.787",
"Id": "423115",
"Score": "1",
"body": "I chose to use `File` because it's closest to the current code and makes testing possible. It's not the most flexible or most elegant choice. I just wanted something a little more expressive than `main(String...)`. It's correct that the encryption code should not force the plaintext to be written to disk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:25:06.353",
"Id": "423181",
"Score": "0",
"body": "Thank you Roland, I changed mine to SecureRandom now. I am also attempting to implement my code to the 5 methods you mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:11:51.280",
"Id": "429268",
"Score": "0",
"body": "@RolandIllig Testing on a file when the function accepts streams would be trivial. You'd just need to create `FileReader` and `FileWriter` objects from it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:03:56.073",
"Id": "429277",
"Score": "0",
"body": "@jpmc26 I hope you meant `FileInputStream` instead of `FileReader`, as well as `FileOutputStream` instead of `FileWriter`, since the Java encryption API works on byte arrays rather than character arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:07:31.780",
"Id": "429278",
"Score": "0",
"body": "Sure. I haven't used Java in a long time. =) Sorry for the mistake. But the point remains the same: there's no need to tie an encryption function specifically to disk reading and writing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:10:02.233",
"Id": "429281",
"Score": "0",
"body": "I changed the API from using `File` to using `InputStream` and `OutputStream`."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T19:13:59.263",
"Id": "219041",
"ParentId": "219039",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "219040",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:18:58.677",
"Id": "219039",
"Score": "12",
"Tags": [
"java",
"security",
"cryptography"
],
"Title": "Employing 3DES algorithm in Java"
} | 219039 |
<p>I've made a little implementation of an undirected graph, using FIFO lists, for one of my homeworks. Never really knew how to write a proper FIFO data structure, so I would be glad to see some opinion of yours.</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
class Graph
{
class Node
{
struct adj
{
int data;
adj* next;
};
adj* head;
adj* tail;
int num;
public:
Node();
Node(const Node&);
Node& operator=(const Node&);
bool is_empty();
bool is_leaf();
void push(int);
int pop();
void print();
~Node();
};
int num_nodes;
Node* nodes;
public:
Graph(int);
Graph(ifstream&);
Graph(const Graph&);
void add_edge(int, int);
Node& operator[](int);
void print();
~Graph();
};
Graph::Node::Node()
{
head=NULL;
tail=NULL;
num=0;
}
Graph::Node::Node(const Node& F)
{
head=NULL;
tail=NULL;
num=0;
adj* tmp=F.head;
while(tmp)
{
push(tmp->data);
tmp=tmp->next;
}
}
Graph::Node& Graph::Node::operator=(const Node& F)
{
if(this!=&F)
{
head=NULL;
tail=NULL;
num=0;
adj* tmp=F.head;
while(tmp)
{
push(tmp->data);
tmp=tmp->next;
}
}
return *this;
}
bool Graph::Node::is_empty()
{
return head==NULL;
}
bool Graph::Node::is_leaf()
{
return num==1;
}
void Graph::Node::push(int value)
{
adj* tmp=new adj;
tmp->data=value;
tmp->next=NULL;
if(is_empty())
{
head=tmp;
}
else
{
tail->next=tmp;
}
tail=tmp;
num++;
}
int Graph::Node::pop()
{
if(!is_empty())
{
adj* tmp=head;
head=head->next;
int value=tmp->data;
delete tmp;
num--;
return value;
}
else
{
return -1;
}
}
void Graph::Node::print()
{
adj*tmp=head;
while(tmp)
{
cout<<tmp->data<<" ";
tmp=tmp->next;
}
cout<<endl;
}
Graph::Node::~Node()
{
while(!is_empty())
{
pop();
}
}
Graph::Graph(int num_nodes)
{
this->num_nodes=num_nodes;
nodes=new Node[num_nodes+1];
}
Graph::Graph(ifstream& f)
{
f>>num_nodes;
nodes=new Node[num_nodes+1];
int start, end;
while(f>>start>>end)
{
add_edge(start, end);
}
}
Graph::Graph(const Graph& G)
{
num_nodes=G.num_nodes;
nodes=new Node[num_nodes+1];
for(int i=1; i<=num_nodes; i++)
{
nodes[i]=G.nodes[i];
}
}
void Graph::add_edge(int start, int end)
{
nodes[start].push(end);
if(start!=end)
{
nodes[end].push(start);
}
}
Graph::Node& Graph::operator[](int i)
{
return nodes[i];
}
void Graph::print()
{
for(int i=1; i<=num_nodes; i++)
{
nodes[i].print();
}
cout<<endl;
}
Graph::~Graph()
{
delete[] nodes;
}
int main()
{
ifstream f("graph.txt");
Graph G(f);
G.print();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:23:01.200",
"Id": "423241",
"Score": "0",
"body": "You seem to be correct with that guess :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:54:11.217",
"Id": "423368",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:03:33.350",
"Id": "423370",
"Score": "0",
"body": "Oh, understood."
}
] | [
{
"body": "<p>Add spaces to improve readability:</p>\n\n<pre><code>head = NULL;\nwhile (tmp)\nif (this != &F)\n</code></pre>\n\n<p>Member functions that do not change any of the class members should be declared with the <code>const</code> specifier:</p>\n\n<pre><code>bool is_empty() const;\nbool is_leaf() const;\n</code></pre>\n\n<p>Some of your <code>while</code> loops could be rewritten as <code>for</code> loops. For example, the loop in the <code>Node</code> copy constructor could be rewritten as</p>\n\n<pre><code>for (adj* tmp = F.head; tmp != NULL; tmp = tmp->next)\n push(tmp->data);\n</code></pre>\n\n<p>Should a <code>pop</code> with an empty list be tolerated? Currently you silently ignore the problem by returning a -1. Would throwing an exception (to report the error) be better? Or at least a <code>std::assert(false);</code> before the return, so you can detect the problem in a debug build. Also, you don't need the <code>else</code> there, since the body of the <code>if</code> will return.</p>\n\n<p>You have no error checking. In particular, <code>add_edge</code> will happily try to add an edge to a node that doesn't exist, resulting in Undefined Behavior and (if you're lucky) a crash. (The same applies to <code>Graph::operator[]</code>. You could add an assert check, or an <code>at</code> method that would check the bounds, similar to how <code>std::vector</code> operates.)</p>\n\n<p>Your <code>Graph</code> copy constructor does not copy <code>nodes[0]</code>.</p>\n\n<p>Why are you using raw memory for Graph's <code>nodes</code>? You should use <code>std::vector</code> or some form of smart pointer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:05:16.100",
"Id": "423340",
"Score": "0",
"body": "I'm very thankful for your comment. Now I have added spaces, rewritten the while loops. I initially used exception handling but then removed it. Now I re-added it. There is still something I really don't understand. First, I start my indexes by 1, so that's why I'm not copying `nodes[0]`, since it doesn't store any valuable data, just an empty list. The other thing, I thought the `~Node` destructor frees up the allocated memory. Also, why should I delete the `this` object if I want to copy it? \n\nPS: I haven't learnt to use the STLs so that's why I didn't included them in my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:56:33.167",
"Id": "423381",
"Score": "0",
"body": "@BalogSzilárd I completely missed `~Node` since it isn't near the constructors. It would probably make sense to locate the destructor next to the constructors, since what they do is related. The assignment operator sets `head` to NULL, and doesn't free up any of the `adj` objects that are currently stored in `this`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T15:09:42.777",
"Id": "423395",
"Score": "0",
"body": "OMG now I completely understand . Should I explicitly call the destructor as `this->~Node()` or just simply type the right code to do it? I'm completely grateful for your time and for your help. I thought it would be a good idea to write the destructors at the end of that list since it is the last thing a function executes, but it seems its not the case. Anyways, big thanks! Have a great day!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:49:48.380",
"Id": "423422",
"Score": "0",
"body": "@BalogSzilárd Don't call the destructor. Since duplicating code is not a good idea, you can put what the destructor does into a (private) function (`cleanup` or something like that), then call that from the destructor and the copy assignment operator. Then maybe just do the memory handling that `pop` does, without having to track or return a value (or have multiple redundant checks for empty)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:19:32.280",
"Id": "219132",
"ParentId": "219044",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219132",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:13:01.650",
"Id": "219044",
"Score": "2",
"Tags": [
"c++",
"linked-list",
"graph",
"homework"
],
"Title": "Graph implementation using FIFO lists"
} | 219044 |
<blockquote>
<p><strong>Problem 1 - Matrix powers in R</strong></p>
<p>R does not have a built-in command for taking matrix powers. </p>
<p>Write a function <code>matrixpower()</code> with two arguments mat and k that will
take integer powers k of a matrix mat.</p>
</blockquote>
<p><strong>My attempted solution.</strong></p>
<pre><code>matrixMul <- function(mat1, mat2)
{
rows <- nrow(mat1)
cols <- ncol(mat2)
if(rows == cols)
{
matOut <- matrix(nrow = rows, ncol = cols) # empty matrix
for (i in 1:rows)
{
for(j in 1:cols)
{
vec1 <- mat1[i,]
vec2 <- mat2[,j]
mult1 <- vec1 * vec2
matOut[i,j] <- sum(mult1)
}
}
return(matOut)
}
else
{
return (matrix( rep( 0, len=25), nrow = 5))
}
}
matrixpower<-function(mat1, k)
{
pow1 <- abs(k)
rows <- nrow(mat1)
cols <- ncol(mat1)
matOut <- diag(1, rows, cols)
if(pow1 == 0)
{
return(matout)
}
if (pow1 == 1)
{
matOut <- mat1
}
if(pow1 > 1)
{
for (i in 1:pow1)
{
matOut <- matrixMul(matOut, mat1)
}
}
if(k < 0)
{
matOut <- solve(matOut)
}
return (matOut)
}
mat1 <- matrix(c(1,2,3,4), nrow = 2, ncol=2)
pow1 <- matrixpower(mat1, -2)
pow1
</code></pre>
<p>I have a few questions here.</p>
<ol>
<li>Is there any room for improvement in this code?</li>
<li>Does this problem ask for manual implementation of multiplication? Or, should the use of <code>%*%</code> suffice?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:42:24.863",
"Id": "423131",
"Score": "1",
"body": "In case you're more interested in the result than in the exercise of writing the function yourself, check out `matrixcalc::matrix.power()` or https://stats.stackexchange.com/questions/4320/compute-the-power-of-a-matrix-in-r/187477"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:16:01.757",
"Id": "423179",
"Score": "0",
"body": "I think you can assume that the matrix multiplication operator is allowed in your solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:48:30.597",
"Id": "423269",
"Score": "0",
"body": "Not the fastest solution (would be what Jorge suggested) but a good candidate for the use of a recursion."
}
] | [
{
"body": "<p>It would be more efficient to use binary exponentiation.</p>\n\n<p>Suppose that you want to raise an n by n matrix to the <span class=\"math-container\">\\$k^{th}\\$</span> power.</p>\n\n<p>The current method requires that you do a normal matrix multiplication <span class=\"math-container\">\\$k-1\\$</span> times.</p>\n\n<p>This of course has complexity <span class=\"math-container\">\\$k\\$</span> multiplied by <span class=\"math-container\">\\$f(n)\\$</span>, Where <span class=\"math-container\">\\$f(n)\\$</span> is the complexity of a matrix multiplication ( This is usually <span class=\"math-container\">\\$n^ 3\\$</span> unless you write some fancy shmancy code that no one writes)</p>\n\n<p>If you use binary exponentiation you reduce the number of multiplications to <span class=\"math-container\">\\$log(k)\\$</span>. Specifically the number of multiplications is the ceiling of <span class=\"math-container\">\\$log_2(k)\\$</span> plus the number of 1 bits in the binary representation of <span class=\"math-container\">\\$k\\$</span>.</p>\n\n<p>This is of course much more efficient for large values of <span class=\"math-container\">\\$k\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:35:32.247",
"Id": "423119",
"Score": "0",
"body": "Welcome to Code! Can you [edit](https://codereview.stackexchange.com/posts/219059/edit) your answer to give an explanation of why binary exponentiation would be more efficient? If there is documentation that supports this claim then feel free to [cite any such sources](https://codereview.stackexchange.com/help/referencing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:40:05.907",
"Id": "423120",
"Score": "2",
"body": "Done !!!!!!!!!!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:18:17.617",
"Id": "423125",
"Score": "0",
"body": "Thanks for showing me how to use math mode !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:20:15.167",
"Id": "423126",
"Score": "1",
"body": "yeah - for more info see the [LaTeX section of the formatting page](https://codereview.stackexchange.com/editing-help#latex)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:46:31.387",
"Id": "423268",
"Score": "0",
"body": "See https://stackoverflow.com/a/40901360/1201032 for a simple implementation."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:45:27.710",
"Id": "219059",
"ParentId": "219045",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:47:41.307",
"Id": "219045",
"Score": "5",
"Tags": [
"matrix",
"r"
],
"Title": "Manually writing a function matrixpower() in R"
} | 219045 |
<p>Trying to set up express server that will authenticate a user's Google email before proceeding.</p>
<p>The code below works, but is there any way to make it more elegant?</p>
<p>The whole <code>new Promise</code> thing feels clunky.</p>
<p>Still wrapping my head around async functions. All the <code>googleapis</code> functions are async, so I feel there's a better way.</p>
<p>I wanted to "wrap" the whole <code>getEmail</code> inside the <code>app.get('/oauth2callback'...</code> but I'm confused by how to "bubble up" a response from several levels of nested async calls so that the <code>app.get</code> call can send the final <code>res</code> to client (if that makes any sense.)</p>
<pre><code>const { google } = require('googleapis');
const express = require('express');
const oauth2Client = new google.auth.OAuth2(
oauthID, oauthSecret, // from google dev console
"http://localhost:3000/oauth2callback" //callback URL
);
async function getEmail(auth, code) {
const { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens);
return new Promise((resolve) => {
google.people('v1').people.get(
{ auth: auth, resourceName: 'people/me', personFields: 'emailAddresses' },
(err, res) => {
if (err) { resolve(err) }
email = res.data.emailAddresses && res.data.emailAddresses.length && res.data.emailAddresses[0].value
resolve(email);
}
)
});
}
const app = express();
app.get('/', async (req, res) => {
const URL = await oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
});
res.send(`<a href="${URL}">login</a>`);
});
app.get('/oauth2callback', (req, res) => {
getEmail(oauth2Client, req.query.code)
.then(r => res.send('••Your Google email is: ' + r))
.catch(e => res.send('••Error: ' + e))
})
app.listen(3000)
</code></pre>
<p>UPDATE: A few hours later, here's what I came up with:</p>
<pre><code>const authURL = auth.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
});
//...
app.get('/oauth2callback', (req, res) => {
auth.getToken(req.query.code)
.then(r => {
auth.setCredentials(r.tokens)
google.people('v1').people.get(
{ auth: auth, resourceName: 'people/me', personFields: 'emailAddresses' }
)
.then(r => {
email = r.data.emailAddresses && r.data.emailAddresses.length && r.data.emailAddresses[0].value;
res.json({email: email})
})
.catch(e => res.send('••Error in people: ' + e))
})
.catch(e => {
res.send(`Problem logging in, <a href="${authURL}">try again</a>`)
})
})
</code></pre>
<p>This works, too ... but is it "better"?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T14:08:54.350",
"Id": "423477",
"Score": "0",
"body": "can you use [`await` inside `getEmail(auth, code) {}` for the `get()` request instead of creating a promise](https://javascript.info/async-await#await) ? If you use several times `await`, the function execution is stopped until receiving the callback?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T21:32:43.777",
"Id": "219047",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"express.js",
"oauth"
],
"Title": "Node/Express authenticate Google email address"
} | 219047 |
<p><strong>Description:</strong></p>
<p>I am working on a classifier which categorizes the text based on some criteria, at present, it is a map of category and list of words if any of the words appear in the text, a category is assigned to it. The text can have multiple categories. The number of categories can be more than 100.</p>
<p><strong>Problem:</strong></p>
<p>There is a need to make this design as flexible as possible so that new classifier can be just plugged in.</p>
<p><strong>Code:</strong></p>
<pre><code>from collections import defaultdict
import string
import re
def createIndex(my_dict):
index = defaultdict(list);
for category, words in my_dict.items():
for word in words:
index[word.lower()].append(category)
return index
class Document(object):
def __init__(self, category, text):
self.category = category
self._text = text.strip().translate(str.maketrans('', '', string.punctuation))
self._paragraphs = []
def parse(self):
paragraphs = re.split('\n\n', self._text)
for para in paragraphs:
self._paragraphs.append(Paragraph(para))
def paragraphs(self):
return self._paragraphs
class Paragraph(object):
def __init__(self, text):
self.number = None
self._text = text
def words(self):
return self._text.split()
def text(self):
return self._text
def __str__(self):
return self._text
class ClassifiedText(object):
def __init__(self, text, categories):
self.text = text
self.categories = categories
def __str__(self):
return self.text + '->' + str(self.categories)
def __repr__(self):
return self.text + '->' + str(self.categories)
class UncassifiedText(object):
def __init__(self, text):
self.text = text
self.weight = 0
self.words = []
self.category = None
def __str__(self):
return self.text + '[Unclassified]'
def __repr__(self):
return self.text + '[Unclassified]'
class WeightedClassifiedText(object):
def __init__(self, text, weight, category, words):
self.text = text
self.weight = weight
self.words = words
self.category = category
def __str__(self):
return self.text + '[' + str(self.weight) + ']'
def __repr__(self):
return self.text + '[' + str(self.weight) + ']'
class CategoryClassifier(object):
def classify(self, text):
raise NotImplementedError('subclasses must override classifier()!')
class TimeClassifier(CategoryClassifier):
def __init__(self):
self.index = createIndex(wordsByCategory)
self._key = 'time'
self._label = 'Time'
def classify(self, paragraph):
count = 0
matched_words = set()
for word in paragraph.words():
if 'time' in self.index[word.lower()]:
matched_words.add(word)
count += 1
if count > 0:
return WeightedClassifiedText(
paragraph.text(), count, 'Time', list(matched_words))
else:
return UncassifiedText(paragraph.text())
class MoodClassifier(CategoryClassifier):
def __init__(self):
self.index = createIndex(wordsByCategory)
self._key = 'mood'
self._label = 'Mood'
def classify(self, paragraph):
count = 0
matched_words = set()
for word in paragraph.words():
if 'mood' in self.index[word.lower()]:
matched_words.add(word)
count += 1
if count > 0:
return WeightedClassifiedText(
paragraph.text(), count, 'Mood', list(matched_words))
else:
return UncassifiedText(paragraph.text())
class DayClassifier(CategoryClassifier):
def __init__(self):
self.index = createIndex(wordsByCategory)
self._key = 'day'
self._label = 'Day'
def classify(self, paragraph):
count = 0
matched_words = set()
for word in paragraph.words():
if self._key in self.index[word.lower()]:
matched_words.add(word)
count += 1
if count > 0:
return WeightedClassifiedText(
paragraph.text(), count, self._label, list(matched_words))
else:
return UncassifiedText(paragraph.text())
class LocationClassifier(CategoryClassifier):
def __init__(self):
self.index = createIndex(wordsByCategory)
self._key = 'location'
self._label = 'Location'
def classify(self, paragraph):
count = 0
matched_words = set()
for word in paragraph.words():
if 'location' in self.index[word.lower()]:
matched_words.add(word)
count += 1
if count > 0:
return WeightedClassifiedText(
paragraph.text(), count, 'Location', list(matched_words))
else:
return UncassifiedText(paragraph.text())
wordsByCategory = {
'time': ['monday', 'noon', 'morning'],
'location': ['Here', 'Near', 'City', 'London', 'desk', 'office', 'home'],
'mood': ['Happy', 'Excited', 'smiling', 'smiled', 'sick'],
'day': ['sunday', 'monday', 'Friday']
}
raw_text = """
Friday brings joy and happiness. We get together
and have fun in our London office.
Monday is normally boring and makes me sick.
Everyone is busy in meetings and no fun.
She looked and smiled at me again, I am thinking
to have coffee with her.
"""
document = Document('Contract', raw_text)
document.parse()
#print(document.paragraphs[0])
#print(ManualClassifier(','.join(texts[0])).classify())
classfiers = [
TimeClassifier(),
MoodClassifier(),
DayClassifier(),
LocationClassifier()
]
for text in document.paragraphs():
result = list(map(lambda x: x.classify(text), classfiers))
categories = list(filter(
lambda x: x is not None, list(map(lambda x: x.category, result))))
print(text, categories)
</code></pre>
<p>It works as expected and to add a new classifier I just have to create a class and add it to the list of classifier and it works. But I feel lack of object-oriented design and I am new to Python as well so I am not sure if I am doing it the "Python" way.</p>
<p><strong>Misc:</strong></p>
<p>In the future I need to introduce the ML-based classifiers as well and then for a given text I need to decide on the category decided by the ML vs Manual classification. For the same reason, I have added <code>weight</code> in the <code>ClassifiedText</code>.</p>
| [] | [
{
"body": "<p>It is indeed not so object oriented, but there's something to work with.</p>\n\n<p>First things first : <code>UncassifiedText</code> -> <code>UnclassifiedText</code> right?</p>\n\n<p>If we look at all your classifiers, we can see pretty quickly that they are <strong>all</strong> the same except for the <code>key</code> and the <code>label</code>. There's another difference where only the <code>DayClassifier</code> actually uses the variables <code>key</code> and <code>label</code>.</p>\n\n<p>Instead of having all these duplicated, why not just use : </p>\n\n<pre><code>class Classifier():\n def __init__(self, key, label):\n self.index = createIndex(wordsByCategory)\n self._key = key\n self._label = label\n\n def classify(self, paragraph):\n count = 0\n matched_words = set()\n for word in paragraph.words():\n if self._key in self.index[word.lower()]:\n matched_words.add(word)\n count += 1 \n if count > 0:\n return WeightedClassifiedText(\n paragraph.text(), count, self._label, list(matched_words))\n else:\n return UncassifiedText(paragraph.text()) \n</code></pre>\n\n<p>Then : </p>\n\n<pre><code>classifiers = [\n Classifier(\"day\", \"Day\"),\n Classifier(\"mood\", \"Mood\"),\n ....\n]\n</code></pre>\n\n<p>With only this change, you've removed all the duplication in your code, that's already pretty damn good OOP. But we can do a little better. </p>\n\n<p>One thing that strikes me as not very OOP is the global usage of <code>wordsByCategory</code> and the whole mechanic behind it, we could make if much simpler. As a matter of fact <code>createIndex</code> is bloated. You create an index for every word in the dictionary, but your classifier only uses some of them. You could make this much simpler with something like this :</p>\n\n<pre><code>class ClassifierV2():\n def __init__(self, key, label, words):\n self.words = words\n self._key = key\n self._label = label\n\n def classify(self, paragraph):\n count = 0\n matched_words = set()\n for word in paragraph.words():\n # Notice the difference here, we don't need to track if we have the right category\n # it's the only one possible.\n if word in self.words:\n matched_words.add(word)\n count += 1 \n if count > 0:\n return WeightedClassifiedText(\n paragraph.text(), count, self._label, list(matched_words))\n else:\n return UncassifiedText(paragraph.text()) \n\nClassifierV2(\"day\", \"Day\", ['sunday', 'monday', 'Friday'])\n</code></pre>\n\n<p>Here's a minor thing, if your label is always the key with a capitalized first letter, you should consider doing this instead in the constructor : </p>\n\n<pre><code>class ClassifierV2():\n def __init__(self, label, words):\n self.words = words\n self._key = label.lower()\n self._label = label\n\nClassifierV2(\"Day\", ['sunday', 'monday', 'Friday'])\n</code></pre>\n\n<p>The goal would be that, if you want to add a new classifier, you wouldn't need to touch your code back. How could we achieve this? I think a classifiers configuration file is in order. Configuration files can seem scary at first, but we'll keep it <em>very</em> simple : </p>\n\n<p><strong>classifiers.json</strong> (I'm being dead honest I'm not sure what's the proper syntax for .json files I never hand write them lol, but that's got to be pretty close to it)</p>\n\n<pre><code>{\n 'time': ['monday', 'noon', 'morning'],\n 'location': ['Here', 'Near', 'City', 'London', 'desk', 'office', 'home'],\n 'mood': ['Happy', 'Excited', 'smiling', 'smiled', 'sick'],\n 'day': ['sunday', 'monday', 'Friday']\n}\n</code></pre>\n\n<p>Once we have this, if you want to add a new classifier, you add a new line to your json file, anyone can do this. You can then load your <code>wordDictionary</code> with the <code>json</code> package. And feed each <code>key:value</code> pair to a new instance of the <code>ClassifierV2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T23:55:22.950",
"Id": "225495",
"ParentId": "219050",
"Score": "3"
}
},
{
"body": "<p>Apart from the above mentioned points (which I mainly agree with), my OCD doesn't let me skip the first thing that I spotted:</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#id17\" rel=\"nofollow noreferrer\"><strong>Use 4 spaces per indentation level.</strong></a></p>\n\n<blockquote>\n <p>When the conditional part of an if-statement is long enough to require\n that it be written across multiple lines, it's worth noting that the\n combination of a two character keyword (i.e. if), plus a single space,\n plus an opening parenthesis creates a natural 4-space indent for the\n subsequent lines of the multiline conditional. This can produce a\n visual conflict with the indented suite of code nested inside the\n if-statement, which would also naturally be indented to 4 spaces. This\n PEP takes no explicit position on how (or whether) to further visually\n distinguish such conditional lines from the nested suite inside the\n if-statement.</p>\n</blockquote>\n\n<p>More, <a href=\"https://www.python.org/dev/peps/pep-0008/#id21\" rel=\"nofollow noreferrer\"><strong>Surround top-level function and class definitions with two blank lines.</strong></a>. So, instead of:</p>\n\n<pre><code>class B(A):\n # ...\n\nclass C(A):\n # ...\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>class B(A):\n # ...\n\n\nclass C(A):\n # ...\n</code></pre>\n\n<p>You can read more about the subject at the above metnioned links.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T14:04:56.737",
"Id": "225584",
"ParentId": "219050",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T21:53:52.743",
"Id": "219050",
"Score": "7",
"Tags": [
"python",
"object-oriented",
"natural-language-processing"
],
"Title": "Document classfier"
} | 219050 |
<p><strong>What I'm trying to do:</strong> implement the Vigenère cipher in Ruby. I already have a working version, but I want to make sure it is efficient and well-designed.</p>
<pre class="lang-rb prettyprint-override"><code>module Crypto
# Vigenère cipher encryption and decryption abstraction
module Vigenere
LETTERS = ('a'..'z').to_a.freeze
private_constant :LETTERS
module_function
# Encrypts a string
#
# @param string [String] the string that will be encrypted
# @param key [String] the key that will be used to encrypt the string
#
# @return [String] the encrypted string
def encrypt(string:, key:)
key = make_key(length: string.length, key: key)
string.length.times.map { |i|
p = LETTERS.find_index(string[i])
k = LETTERS.find_index(key[i])
LETTERS[(p + k) % 26]
}.join
end
# Decrypts an encrypted string
#
# @param string [String] the encrypted string that will be decrypted
# @param key [String] the key that will be used to decrypt the string
#
# @return [String] the decrypted string
def decrypt(string:, key:)
key = make_key(length: string.length, key: key)
string.length.times.map { |i|
c = LETTERS.find_index(string[i])
k = LETTERS.find_index(key[i])
LETTERS[(c - k + 26) % 26]
}.join
end
# Repeats a word until it matches a certain length
#
# @param length [Integer] the length of the word being encrypted/decrypted
# @param key [String] the word that will be repeated
#
# @return [String] the word in its new form
def make_key(length:, key:)
i = 0
length.times do
i = 0 if i == key.length
break if key.length == length
key << key[i]
i += 1
end
key
end
private_class_method :make_key
end
end
</code></pre>
<p>I do have some specific questions:</p>
<p><strong>1. <code>private_class_method</code></strong></p>
<p>This is the best way I found to define a private method in a module, but it feels weird to me. Isn't there a better way to do that? My first implementation was this:</p>
<pre class="lang-rb prettyprint-override"><code>module Crypto
class Vigenere
class << self
def encrypt # ...
def decrypt # ...
private
def make_key # ...
end
end
end
</code></pre>
<p>which was fine for me. But then I read <a href="https://github.com/rubocop-hq/ruby-style-guide#modules-vs-classes" rel="noreferrer">this</a> rule on the Ruby Style Guide repository. So I switched to using <code>module</code>, but it doesn't feel right to use private methods in this structure. Am I wrong?</p>
<p><strong>2. reseting a counter (index)</strong></p>
<p>Take a look at this snippet of code:</p>
<pre class="lang-rb prettyprint-override"><code>def make_key(length:, key:)
i = 0
length.times do
i = 0 if i == key.length
break if key.length == length
key << key[i]
i += 1
end
key
end
</code></pre>
<p>Defining a counter (<code>i</code>) and manually incrementing it... looks awkward, doesn't it (at least in the Ruby world)? Is there a better way to do this?</p>
<p><strong>3. valid multi-line block with curly braces?</strong></p>
<p>Now take a look at this snippet:</p>
<pre class="lang-rb prettyprint-override"><code>string.length.times.map { |i|
p = LETTERS.find_index(string[i])
k = LETTERS.find_index(key[i])
LETTERS[(p + k) % 26]
}.join
</code></pre>
<p>I know most Ruby developers tend to use curly braces only for one-line blocks and <code>do-end</code> for multi-line blocks, but this time it seems okay using curly braces with a multi-line block, since I'm chaining <code>#join</code> right after. What would you do:</p>
<p><em>1. use do-end, store it in a variable and invoke #join after that</em></p>
<pre class="lang-rb prettyprint-override"><code>new_letters = string.length.times.map do |i|
p = LETTERS.find_index(string[i])
k = LETTERS.find_index(key[i])
LETTERS[(p + k) % 26]
end
new_letters.join
</code></pre>
<p><em>2. what I did (use curly braces even with multi-line block and chain #join)</em></p>
<p>And of course, if you have any other observations, please share.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T00:39:10.217",
"Id": "423097",
"Score": "2",
"body": "If you take the time to spell Vigenère correctly then that's enough for me to tell that the code is going to be all right :)"
}
] | [
{
"body": "<p>The code is rather clear, so consider the following to be nitpicks.</p>\n\n<hr>\n\n<p>I'd say that you are generating a new <em>key stream</em> from the key. I'd certainly not reuse the <code>key</code> variable.</p>\n\n<hr>\n\n<p>The first <code>i = 0</code> before the loop seems spurious.</p>\n\n<p>Using <code>i</code> as a counter is well understood, and I'd not worry overly much on the style of it. You are probably the only one who cares if it is really Ruby-esk; developers down the line will understand it.</p>\n\n<p>What I wonder though is that you run your loop <code>length</code> times, but there is a <code>break</code> that seems to trigger before that. That's not all too clear to me.</p>\n\n<p>I wonder what happens if you supply it an \"empty\" key string. Some guard statements may be in order.</p>\n\n<hr>\n\n<p>Same for the curly braces. It's clear as it is, choose whatever you want. Personally I slightly favor the braces.</p>\n\n<hr>\n\n<p>You could consider creating a <code>mod</code> function, however since <code>%</code> is already the modulus, which will never return a negative value if the right value is positive, it seems to me that removing the <code>+ 26</code> is probably the only thing you need to change (during decryption).</p>\n\n<p>Instead of using 26 as unexplained magic value, you should get the size of the <code>LETTERS</code> range instead. That way you can also expand your ciphertext later.</p>\n\n<hr>\n\n<p>I've got no opinion on the <code>private_class_method</code> as I'm not a Ruby developer (I'm specialized in knowing many languages / constructs and of course applied crypto).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T02:38:50.687",
"Id": "423110",
"Score": "0",
"body": "Thanks, that's really helpful! Sadly, I don't have enough reputation to upvote your answer. :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T00:34:08.380",
"Id": "219055",
"ParentId": "219053",
"Score": "4"
}
},
{
"body": "<p>Looping using <code>string.length.times.map { |i| … }</code> and <code>length.times do …</code> is OK, but slightly on the awkward side. I recommend adhering to the convention of writing same-line blocks using <code>{}</code> and line-spanning blocks using <code>do … end</code>.</p>\n\n<p>To extend the key, you can use the string multiplication operator. (Note that extending the key longer than necessary doesn't do much harm.)</p>\n\n<p>You can also factor out more of the commonality between the <code>encrypt</code> and <code>decrypt</code> functions.</p>\n\n<p>Instead of searching the <code>LETTERS</code> array, I recommend performing arithmetic on ASCII codes.</p>\n\n<pre><code>module Crypto\n module Vigenere\n module_function\n def encrypt(plaintext, key) \n vigenere(plaintext, key) { |p, k| (p + k) % 26 }\n end\n\n def decrypt(ciphertext, key) \n vigenere(ciphertext, key) { |c, k| (c - k + 26) % 26 }\n end\n\n # Implementation of Vigenere cipher. The combiner block accepts\n # one character from the text and the corresponding character from\n # the key (encoded as a=0, b=1, ..., z=25), and returns the\n # result using the same numerical scheme.\n def vigenere(text, key, &combiner)\n a = 'a'.ord\n ext_key = key * (text.length / key.length + 1)\n text.chars.zip(ext_key.chars).collect do |t, k|\n (a + combiner.call(t.ord - a, k.ord - a)).chr\n end.join\n end\n private_class_method :vigenere\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:09:18.987",
"Id": "219064",
"ParentId": "219053",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219055",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T23:32:57.763",
"Id": "219053",
"Score": "5",
"Tags": [
"ruby",
"vigenere-cipher"
],
"Title": "Vigenère cipher in Ruby"
} | 219053 |
<p>I was reading Introduction to Computation and Programming using Python and there in an exercise, we had to write a function which would tell us if a given word is a palindrome or not, <strong>recursively</strong>. </p>
<p>This is the code which I wrote:</p>
<pre><code>word = input()
def isPalindrome(x):
if len(x) > 1:
if x[0] == x[-1] and isPalindrome(x[1:-1]):
return('The word is Plaindrome.')
else:
return('It is not.')
else:
return(True) #As this is a base case.
print(isPalindrome(word))
</code></pre>
<p>This seems to work for all the words I pass into it except <strong>uiouioiu</strong>.
<code>isPalindrome(uiouioiu)</code> returns <code>The word is Palindrome</code>.</p>
<p>Could someone explain what is happening?</p>
<p><strong>EDIT 1</strong>: If I modify the code to:</p>
<pre><code>word = input()
def isPalindrome(x):
if len(x) > 1:
if x[0] == x[-1] and isPalindrome(x[1:-1]):
return(True)
else:
return(False)
else:
return(True) #As this is a base case.
print(isPalindrome(word))
</code></pre>
<p><code>isPalindrome(uiouioiu)</code> returns <code>False</code> as expected. Why is this happening?</p>
| [] | [
{
"body": "<p>The reason it doesn't work is that \"It is not\" is converted into True, so when you analyze \n\"uiouioiu\" the process eventually has to check the middle part \"ui\", the problem is that the answer \"It is not\" is then interpreted as True.</p>\n\n<p>The same behaviour should also be obtained when testing the word \"abca\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:41:26.640",
"Id": "423099",
"Score": "0",
"body": "Hi. Thanks for the answer. Could you please explain what do you mean by \" `It is not`is converted into True\" ? `It is not == True` evaluates to `False`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:42:07.787",
"Id": "423100",
"Score": "0",
"body": "Check instead something like if('It is not'): do something"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:42:52.030",
"Id": "423101",
"Score": "0",
"body": "Put the argument 'It is not' inside an if statement and check if it does what it is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:44:01.363",
"Id": "423102",
"Score": "0",
"body": "For example if 'it is not':\n print(\"hola\\n\");"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:45:00.927",
"Id": "423103",
"Score": "0",
"body": "The idea is that non empty strings turn into True when you put them inside an if"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:47:55.443",
"Id": "423105",
"Score": "0",
"body": "I don't know, I don't use python, but that is the way it works with c++ also. It probably has to do with the fact that == first checks if the two variables have the same type or something? Or maybe == checks if the two things are exactly the same. I don't know to be honest, but i do know that if you use a non empty string in an if statement it will interpret it as True."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:49:25.133",
"Id": "423106",
"Score": "0",
"body": "Thanks for the answer! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:49:36.217",
"Id": "423107",
"Score": "0",
"body": "Glad to help !!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T02:16:33.000",
"Id": "423108",
"Score": "2",
"body": "@RahulJ The concept you are looking for is called \"truthiness\" or \"truthyness\" and it is not limited to Python. See [this blog post](https://blog.jrheard.com/truthiness-and-short-circuit-evaluation-in-python) for an explanation. Be aware that similar (but different) rules exist in other languages, and it's the job of the programmer to know these rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T03:09:02.270",
"Id": "423111",
"Score": "0",
"body": "I don't think it's the job of the programmer to be honest. I'm sick of \"programmers\" being held to such high standards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T03:26:59.027",
"Id": "423113",
"Score": "5",
"body": "Please do not answer off-topic questions."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:36:36.273",
"Id": "219058",
"ParentId": "219057",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T01:29:02.607",
"Id": "219057",
"Score": "-1",
"Tags": [
"python",
"palindrome"
],
"Title": "Why does my function think that \"uiouioiu\"is a plaindrome?"
} | 219057 |
<p>I am trying to implement a function <code>groupWeeks(dates)</code> using <code>reduce</code> that allows me to group an array of objects <code>{ date: '2019-03-11', count: 8 }</code> by weeks.</p>
<p>The following code works fine. Is there a way to refactor it? It seems to me that my solution is unnecessarily complex. Please ignore <code>Date.prototype.getWeekNumber</code> and <code>getWeekStart(date)</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const dates = [
{ date: '2019-02-24', count: 10 },
{ date: '2019-02-25', count: 11 },
{ date: '2019-02-26', count: 12 },
{ date: '2019-03-09', count: 8 },
{ date: '2019-03-10', count: 7 },
{ date: '2019-03-11', count: 6 },
{ date: '2019-04-14', count: 3 },
{ date: '2019-04-15', count: 2 },
{ date: '2019-04-16', count: 4 },
{ date: '2019-04-22', count: 5 }
];
/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* @param int dowOffset
* @return int
*/
Date.prototype.getWeek = function(dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */
dowOffset = typeof dowOffset == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(), 0, 1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = day >= 0 ? day : day + 7;
var daynum =
Math.floor(
(this.getTime() -
newYear.getTime() -
(this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) /
86400000
) + 1;
var weeknum;
//if the year starts before the middle of a week
if (day < 4) {
weeknum = Math.floor((daynum + day - 1) / 7) + 1;
if (weeknum > 52) {
nYear = new Date(this.getFullYear() + 1, 0, 1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
} else {
weeknum = Math.floor((daynum + day - 1) / 7);
}
return weeknum;
};
function getWeekStart(date) {
var offset = new Date(date).getDay();
return new Date(new Date(date) - offset * 24 * 60 * 60 * 1000)
.toISOString()
.slice(0, 10);
}
function groupWeeks(dates) {
const groupsByWeekNumber = dates.reduce(function(acc, item) {
const today = new Date(item.date);
const weekNumber = today.getWeek();
// check if the week number exists
if (typeof acc[weekNumber] === 'undefined') {
acc[weekNumber] = [];
}
acc[weekNumber].push(item);
return acc;
}, []);
return groupsByWeekNumber.map(function(group) {
return {
weekStart: getWeekStart(group[0].date),
count: group.reduce(function(acc, item) {
return acc + item.count;
}, 0)
};
});
}
console.log(groupWeeks(dates));</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>You said to ignore <code>getWeekStart()</code>, but I'm afraid I can't do that. It appears that the intention of <code>getWeekStart()</code> is to take a date string (in YYYY-MM-DD form) and find the Sunday that starts the week (in YYYY-MM-DD form). However, depending on the time zone in which the code is executed, it may actually find the Monday, or possibly a Saturday instead.</p>\n\n<p>The problem is that</p>\n\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters\" rel=\"nofollow noreferrer\"><code>new Date(\"<em>YYYY</em>-<em>MM</em>-<em>DD</em>\")</code></a> interprets the date as a UTC timestamp:</p>\n\n<blockquote>\n <p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that <strong>date-only strings (e.g. \"1970-01-01\") are treated as UTC, not local</strong>.</p>\n</blockquote></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay\" rel=\"nofollow noreferrer\"><code><em>date</em>.getDay()</code></a> returns the day of the week for the specified date <strong>according to local time</strong>, where 0 represents Sunday.</p></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString\" rel=\"nofollow noreferrer\"><code><em>date</em>.toISOString()</code></a> works in UTC:</p>\n\n<blockquote>\n <p>The <code>toISOString()</code> method returns a string in simplified extended ISO format (<a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a>), which is always 24 or 27 characters long (<code>YYYY-MM-DDTHH:mm:ss.sssZ</code> or <code>±YYYYYY-MM-DDTHH:mm:ss.sssZ</code>, respectively). <strong>The timezone is always zero UTC offset</strong>, as denoted by the suffix \"Z\".</p>\n</blockquote></li>\n</ul>\n\n<p>For the code to be reliably correct, you must work consistently in UTC — in other words, call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay\" rel=\"nofollow noreferrer\"><code><em>date</em>.getUTCDay()</code></a> instead.</p>\n\n<p>Furthermore, I'd rename <code>getWeekStart()</code> to <code>weekStart()</code>. The \"get\" prefix implies that you are fetching something that already exists. However, you are actually computing something, so the prefix is superfluous, perhaps even misleading.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:42:01.767",
"Id": "423130",
"Score": "0",
"body": "I really appreciate looking into details. I did not realize it could be a problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:23:12.847",
"Id": "219076",
"ParentId": "219061",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219076",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T02:22:37.033",
"Id": "219061",
"Score": "3",
"Tags": [
"javascript",
"datetime",
"functional-programming"
],
"Title": "Grouping dates by weeks using reduce()"
} | 219061 |
<p>I am building a simple login page which will check for username before navigating to another screen and here is how I am doing the binding now. I would like to know if I am doing it right and if I am not, what is the recommended way of doing the binding. Moreover, I creating the UI programmatically.</p>
<p><strong>ViewModel.swift</strong></p>
<pre><code>// Inputs
private let usernameSubject = PublishSubject<String>()
private let nextButtonDidTapSubject = PublishSubject<Void>()
// Outputs
private let validUsernameSubject = PublishSubject<Bool>()
private let invalidUsernameSubject = PublishSubject<String>()
// MARK: - Init
init() {
input = Input(username: usernameSubject.asObserver(),
nextButtonDidTap: nextButtonDidTapSubject.asObserver())
output = Output(validUsername: validUsernameSubject.asObservable(),
invalidUsername: invalidUsernameSubject.asObservable())
nextButtonDidTapSubject
.withLatestFrom(usernameSubject.asObservable())
.subscribe(onNext: { [unowned self] text in
if text.count >= self.minUsernameLength {
self.validUsernameSubject.onNext(true)
} else {
let message = text.count > 0 ?
"Please enter a valid username" :
"Please enter a username"
self.invalidUsernameSubject.onNext(message)
}
})
.disposed(by: disposeBag)
}
</code></pre>
<p><strong>ViewController.swift</strong></p>
<pre><code>private func configureBinding() {
loginLandingView.usernameTextField.rx.text.orEmpty
.subscribe(viewModel.input.username)
.disposed(by: disposeBag)
loginLandingView.nextButton.rx.tap
.subscribe(viewModel.input.nextButtonDidTap)
.disposed(by: disposeBag)
viewModel.output.validUsername
.subscribe(onNext: { [unowned self] _ in
print("Valid username - Navigate...")
self.navigate()
})
.disposed(by: disposeBag)
viewModel.output.invalidUsername
.subscribe(onNext: { [unowned self] message in
self.showAlert(with: message)
})
.disposed(by: disposeBag)
}
</code></pre>
| [] | [
{
"body": "<p>I do not recommend this approach. There are entirely too many subjects and they are completely unnecessary. Too much boilerplate.</p>\n\n<p>I recommend a more functional approach:</p>\n\n<p>The view controller would contain something like this:</p>\n\n<pre><code>// assign viewModel before presenting.\nvar viewModel: (LoginInputs) -> LoginOutputs = { _ in fatalError(\"assign before view is loaded.\") }\n\n// called from viewDidLoad()\nprivate func configureBinding() {\n\n let inputs = LoginInputs(\n username: loginLandingView.usernameTextField.rx.text.orEmpty.asObservable(),\n loginTrigger: loginLandingView.nextButton.rx.tap.asObservable()\n )\n\n let outputs = viewModel(inputs)\n\n outputs.navigateTrigger\n .subscribe(onNext: { [unowned self] in\n self.navigate()\n })\n .disposed(by: disposeBag)\n\n outputs.invalid\n .subscribe(onNext: { [unowned self] message in\n self.showAlert(with: message)\n })\n .disposed(by: disposeBag)\n}\n</code></pre>\n\n<p>And the view model would look like:</p>\n\n<pre><code>struct LoginInputs {\n let username: Observable<String>\n let loginTrigger: Observable<Void>\n}\n\nstruct LoginOutputs {\n let navigateTrigger: Observable<Void>\n let invalid: Observable<String>\n}\n\nfunc loginViewModel(minUsernameLength: Int) -> (_ inputs: LoginInputs) -> LoginOutputs {\n return { inputs in\n let usernameEntered = inputs.loginTrigger\n .withLatestFrom(inputs.username)\n\n let navigateTrigger = usernameEntered\n .filter { minUsernameLength <= $0.count }\n .map { _ in }\n let usernameTooShort = usernameEntered\n .filter { 1 <= $0.count && $0.count < minUsernameLength }\n .map { _ in \"Please enter a valid username\" }\n let usernameEmpty = usernameEntered\n .filter { $0.isEmpty }\n .map { _ in \"Please enter a username\" }\n\n return LoginOutputs(\n navigateTrigger: navigateTrigger,\n invalid: Observable.merge(usernameTooShort, usernameEmpty)\n )\n }\n}\n</code></pre>\n\n<p>The code that presents the view controller would look something like:</p>\n\n<pre><code>let controller = LoginViewController() \ncontroller.viewModel = loginViewModel(minUsernameLength: 8) // or whatever the minimum is.\n// show the view controller\n</code></pre>\n\n<p>The above will maximize the testability of your code. You can test the view model by simply calling the function and pushing data into it. You can test the view controller by assigning a viewModel function that pushes test data.</p>\n\n<p>The above will also establish a strong separation between your logic (in the view model) and your effects (in the view controller.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T02:41:30.410",
"Id": "423284",
"Score": "0",
"body": "Thank you for the recommended approach. Highly appreciate it as I am still learning how to integrate RxSwift with MVVM. As for the last piece of your code regarding the presentation of view controller, wouldn't it be better/cleaner if I am defining the minUsernameLength inside the viewModel since it is unlikely to change **OR** it is meant for ease of testing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:25:25.723",
"Id": "423331",
"Score": "0",
"body": "That's up to you. I defined it outside the view model because it looked like you were doing the same from the code sample you presented. You could put a `let minUsernameLength = 8` just before the `let usernameEntered` line if you would prefer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T00:41:32.027",
"Id": "219141",
"ParentId": "219062",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T02:55:50.540",
"Id": "219062",
"Score": "3",
"Tags": [
"validation",
"swift",
"authentication",
"mvvm",
"rx-swift"
],
"Title": "Login page using RxSwift in MVVM"
} | 219062 |
<p>I am self-learning js and came across this problem(#3) from the <a href="https://projecteuler.net/problem=3" rel="noreferrer">Euler Project</a></p>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<p><strong>Logic:</strong></p>
<ul>
<li><p>Have an array <code>primes</code> to store all the prime numbers less than <code>number</code></p></li>
<li><p>Loop through the odd numbers only below <code>number</code> to check for primes using <code>i</code></p></li>
<li><p>Check if <code>i</code> is divisible by any of the elements already in <code>primes</code>.</p>
<ul>
<li>If yes, <code>isPrime = false</code> and break the for loop for <code>j</code> by <code>j=primesLength</code></li>
<li>If not, <code>isPrime = true</code></li>
</ul></li>
<li><p>If <code>isPrime == true</code> then add <code>i</code> to the array <code>primes</code> and check if <code>number%i == 0</code></p>
<ul>
<li>If <code>number%i == 0%</code> update the value of <code>factor</code> as <code>factor = i</code></li>
</ul></li>
<li><p>Return <code>factor</code> after looping through all the numbers below <code>number</code></p></li>
</ul>
<p><strong>My code:</strong></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 problem3(number){
let factor = 1;
let primes = [2]; //array to store prime numbers
for(let i=3; i<number; i=i+2){ //Increment i by 2 to loop through only odd numbers
let isPrime = true;
let primesLength= primes.length;
for(let j=0; j< primesLength; j++){
if(i%primes[j]==0){
isPrime = false;
j=primesLength; //to break the for loop
}
}
if(isPrime == true){
primes.push(i);
if(number%i == 0){
factor = i;
}
}
}
return factor;
}
console.log(problem3(600851475143));</code></pre>
</div>
</div>
</p>
<p>It is working perfectly for small numbers, but is <strike>quite</strike> very slow for 600851475143. What should I change in this code to make the computation faster?</p>
<p>Edit: <a href="https://codereview.stackexchange.com/q/219099/199363">Updated code based on feedback</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:16:09.557",
"Id": "423180",
"Score": "6",
"body": "\"`//to break the for loop`\" Doesn't Javascript have a `break`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:18:37.187",
"Id": "423326",
"Score": "0",
"body": "@Arthur yeah. I'm new to this, and forgot what exactly the word was. It was later pointed out in an answer (now deleted) here, after which I have updated my code. Thanks for pointing out though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:33:34.443",
"Id": "423333",
"Score": "1",
"body": "No worries. Knowing that any scope runs until the end is a known aesthetic goal when coding, and people who try to achieve that would probably also do something exactly like that. So I don't think it's that bad, really. And it's not like a single assignment rather than a break would tax the processor much, and a clever compiler might even optimise it away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T15:57:38.967",
"Id": "532062",
"Score": "0",
"body": "[Here's the fastest solution for JavaScript](https://github.com/vitaly-t/prime-lib/blob/main/src/prime-factors.ts). It will solve this for 600851475143 in just `0.00001s`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T16:29:27.663",
"Id": "532066",
"Score": "0",
"body": "When doing tasks like this, it may be helpful to know what the correct result will be. https://www.wolframalpha.com/input/?i=What+is+the+largest+prime+factor+of+the+number+600851475143%3F"
}
] | [
{
"body": "<p>There are <a href=\"/search?q=600851475143+is%3Aquestion\">many questions about Project Euler 3</a> on this site already. The trick is to <a href=\"/a/48185/9357\">pick an algorithm</a> that…</p>\n\n<ul>\n<li>Reduces <code>n</code> whenever you find a factor, so that you don't need to consider factors anywhere near as large as 600851475143</li>\n<li>Only finds prime factors, and never composite factors, so that you never need to explicitly test for primality.</li>\n</ul>\n\n<p>Your algorithm suffers on both criteria: the outer <code>for</code> loop goes all the way up to 600851475143 (which is ridiculous, because even if you optimistically assume that it takes one nanosecond per loop, that would be 5 minutes), and you're testing each of those numbers for primality (which is incredibly computationally expensive).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:38:49.463",
"Id": "423146",
"Score": "0",
"body": "The \"pick an algorithm\" link never explains this explicitly; when you start from low numbers you don't need to check the divisors for primality since the divisors of any composite number would already have been divided out. Even if the original number was divisible by 15, it would already have been divided by 3 and 5."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:43:29.703",
"Id": "423148",
"Score": "3",
"body": "@JollyJoker I kind of mentioned it, without giving away the spoiler: \"Bonus question: in the example above, do we still need to test 19 for primality? Why or why not?\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:43:50.310",
"Id": "423149",
"Score": "0",
"body": "Now I feel like writing a code golfed recursive version, but don't have time..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:48:04.350",
"Id": "423150",
"Score": "0",
"body": "You also test every odd number without explanation, while a naive implementation would test the divisors for primality first. Well, some prefer complete answers, some want the asker to think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:50:46.670",
"Id": "423223",
"Score": "1",
"body": "Integer division is still very slow compared to other operations, like multiplication. And even on modern x86 CPUs, isn't fully pipelined. (A new division can't start every clock cycle. Like 1 per 6 cycles on Skylake for 32-bit division, or 1 per 21 to 83 cycles for 64-bit division: https://agner.org/optimize). 1ns is only 4 clocks on a 4GHz CPU. But if we're being very optimistic, `divsd` (scalar `double` floating point) has 1 per 4-clock throughput on Skylake, so maybe we could come close if we come up with a way to check if the result of that is an exact integer in only a couple uops."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:19:44.247",
"Id": "219066",
"ParentId": "219063",
"Score": "18"
}
},
{
"body": "<p>The first problem is that you are trying to find all prime numbers under number. The number of prime numbers under x is approximately x/ln(x) which is around 22153972243.4 for our specific value of x</p>\n\n<p>This is way too big ! So even if you where capable of obtaining each of these prime numbers in constant time it would take too much time.</p>\n\n<p>This tells us this approach is most likely unfixable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:48:07.490",
"Id": "219069",
"ParentId": "219063",
"Score": "1"
}
},
{
"body": "<p>You already skip all even numbers.<br/>\nFor the same reason, create code that skips:</p>\n\n<ol>\n<li>every 3rd #</li>\n<li>every 5th #</li>\n<li>every 7th ... 11th ... 13th, maybe ...</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:02:06.387",
"Id": "423248",
"Score": "2",
"body": "That sort of stepping can get complicated quickly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:34:48.053",
"Id": "423251",
"Score": "2",
"body": "@1201ProgramAlarm The best way would probably be to keep track of the previous primes and for each new prime, make sure it isn't a multiple of any previous prime. This is useful for generating the infinite sequence of primes (I think of it as an infinite sieve of Eratosthenes), but unless the number is big enough that taking it *modulus* a small number is too slow, it's best just to find the one modulus instead of finding many smaller ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T05:44:49.563",
"Id": "423291",
"Score": "1",
"body": "@1201ProgramAlarm It is, however, how a basic sieve works. You assume all numbers are prime (an array of true) and mark of all multiples of two as composite, then all multiples of three, then all multiples of the next number that is still true."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:28:33.870",
"Id": "219106",
"ParentId": "219063",
"Score": "1"
}
},
{
"body": "<p>For starters, you only need to check odd numbers (potential primes) below <code>√X</code>.</p>\n<p>If <code>A * B == X</code>, then:</p>\n<ul>\n<li>Either <code>A == B</code> and <code>X</code> is a perfect square, so the largest prime dividing <code>A</code> is the largest prime factor,</li>\n<li>Or one of <code>A</code> and <code>B</code> is less than the other, and thus less than <code>√X</code>.</li>\n</ul>\n<p>Without loss of generality, say <code>A</code> is less than <code>B</code>. Then <code>B</code> would be greater than <code>√X</code>, but the largest prime factor in <code>A</code> or <code>B</code> would be the largest prime factor of <code>X</code>.</p>\n<p>So, you can start testing <code>B</code>, and just like <code>X</code>, you need to test only numbers less than <code>√B</code>, and when testing <code>A</code> only those less than <code>√A</code>.</p>\n<p>You can keep a list of numbers that divide <code>X</code>, I would always try to find a factor of the largest number that divides <code>X</code>:</p>\n<ul>\n<li>If it is prime, it is the largest prime factor.</li>\n<li>But if you do find a factor of the largest, get rid of it and replace it with its two factors. Then once again, find the largest factor and prove it is prime or composite.</li>\n</ul>\n<p>I would also start your loop for finding a factor "from the bottom," not from the top, to play the odds.</p>\n<p>⅓ of all numbers are divisible by 3, ⅕ divisible by 5, etc. You can divide by 2 as many times as possible before beginning. Then keep track of the largest odd number you have tried (prime or not, that will include all primes), so once they fail, you don't need to try them again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:57:18.903",
"Id": "219114",
"ParentId": "219063",
"Score": "4"
}
},
{
"body": "<p>This answer is not so much for academic purposes, but rather to show how this can be done real fast, using an existing library. However, <a href=\"https://github.com/vitaly-t/prime-lib/blob/main/src/prime-factors.ts\" rel=\"nofollow noreferrer\">the function source code</a> can be easily reused also.</p>\n<p>Using <a href=\"https://github.com/vitaly-t/prime-lib\" rel=\"nofollow noreferrer\">prime-lib</a> library (I'm the author):</p>\n<pre class=\"lang-js prettyprint-override\"><code>import {primeFactors} from 'prime-lib';\n\nconst allFactors = primeFactors(600851475143); // takes ~0.00001s\n//=> [71, 839, 1471, 6857]\n\nconst maxPrime = allFactors.reduce((c, i) => Math.max(c, i));\n//=> 6857\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T16:20:02.713",
"Id": "269647",
"ParentId": "219063",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219066",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T03:35:52.790",
"Id": "219063",
"Score": "11",
"Tags": [
"javascript",
"beginner",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "A faster way to compute the largest prime factor"
} | 219063 |
<p>I implemented a recursive depth-first traversal, with all three traversal modes in this function. Is this the most succinct way to write the code?</p>
<pre><code>/**
* Node
*/
public class Node {
private int value;
Node left;
Node right;
public Node(int value) {
this.setValue(value);
left = null;
right = null;
}
/**
* @return the value
*/
public int getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
</code></pre>
<pre><code>/**
* Depth-First Traversal (Recursion)
* @param root root of node-tree to be traversed
*/
public void dftRecursion(Node root) {
if (root == null) {
return;
}
switch (tMode) { // traversal mode
case IN_ORDER:
dftRecursion(root.left);
System.out.print(root.getValue() + " ");
dftRecursion(root.right);
break;
case PRE_ORDER:
System.out.print(root.getValue() + " ");
dftRecursion(root.left);
dftRecursion(root.right);
break;
case POST_ORDER:
dftRecursion(root.left);
dftRecursion(root.right);
System.out.print(root.getValue() + " ");
break;
default:
throw new IllegalArgumentException("Mode value:" + tMode);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:17:13.293",
"Id": "423124",
"Score": "0",
"body": "What is `tMode`? Please ensure that your code is posted with the proper context."
}
] | [
{
"body": "<p>To answer your question exactly and with very little value: <strong>no</strong>. All those println's and traversal modes add unnecessary length to your code.</p>\n\n<p>But lets get down to business... shortness is not always he most desirable feature of source code. Your choice of providing accessors for <code>value</code> but not for the <code>left</code> and <code>right</code> subtrees is questionable. Be consistent with how you expose and manipulate your fields.</p>\n\n<p>You left out the context of <code>dtfRecursion</code>. Defining the traversal mode outside the traversal algorithm is odd. You could implment the traversal modes as separate classes. This would free you from the need to check the correctness of the <code>tMode</code>. Also you wouldn't need to worry about someone changing <code>tMode</code> during traversal (not that you do it now, eh).</p>\n\n<p>It seems that you're just doing this for the sake of writing the algorithm but to make this review more useful, I'll point out that instead of hardcoding the println's you could pass a <code>Consumer<Integer></code> to the traversal method and implement whatever you want to do with the values in that. And you could implement <code>Node</code> as a parameterized class to allow storage of types other than just integers.</p>\n\n<p><code>Node</code> is also a bit generic name for a class that is highly specific in it's implementation. <code>BinaryTreeNode</code> might be better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:57:28.233",
"Id": "219079",
"ParentId": "219067",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:31:34.057",
"Id": "219067",
"Score": "1",
"Tags": [
"java",
"recursion",
"interview-questions",
"tree"
],
"Title": "Depth-first traversal implementation in Java (by recursion)"
} | 219067 |
<p>I've wroted this function because I was getting trouble using <code>toLocaleString()</code> in google-apps-script, and after some refactorings I got to a working code:</p>
<pre><code>function neat(numToFormat,prefThousands, prefDecimals) {
var thousandSep = prefThousands == undefined ? "." : prefThousands;
var decimalSep = prefDecimals == undefined ? "," : prefDecimals;
function parseInput(numToFormat) {
var isNumber = typeof(numToFormat) == 'number';
var numberToFixed;
if(isNumber){
numberToFixed = numToFormat.toFixed(2);
} else {
//replacing "," for parseFloat precision
if(numToFormat.indexOf(",") >-1){
numToFormat = numToFormat.replace(",",".");
}
numberToFixed = parseFloat(numToFormat).toFixed(2);
}
return numberToFixed;
}
function placeThousands(wholesPart){
/* To add thousands separators.
* it iterates throught the
* number in chunks of len 3.
* adding a the setted prefered thousand separator.
* just needed if wholesPart.length >=4
*
*/
var wholesLength = wholesPart.length;
var wholesModulo = wholesLength % 3;
//benefits from the mod equaling the slice end size needed
//and if mod == 0 fstChunk = ""
var fstChunk = wholesPart.slice(0,wholesModulo);
var placed =wholesModulo !=0 ? fstChunk+thousandSep : fstChunk;
for (var i=wholesModulo;i<wholesLength;i+=3) {
var nextLoop = i+3;
if(nextLoop<wholesLength) {
var sliceBy = wholesPart.slice(i,nextLoop);
placed += sliceBy +thousandSep;
} else {
sliceBy = wholesPart.slice(i,wholesLength);
placed += sliceBy;
}
}
return placed;
}
var numberToFixed = parseInput(numToFormat);
var decimalPart = numberToFixed.slice(-3).replace('.',decimalSep);
var wholesPart = numberToFixed.slice(0,(numberToFixed.length - 3));
var needThousands = wholesPart.length >=4;
var neat = needThousands ? placeThousands(wholesPart) + decimalPart : wholesPart + decimalPart;
if(numberToFixed>= 9007199254740991){
neat= "This number is too big, neatnumbers can't handle it";
} else if(neat == "NaN") {
neat= "neatnumbers only deals with numbers";
}
return neat;
}
</code></pre>
<p>It's restricted to 9007199254740991 because calling <code>parseFloat()</code> even on integers bigger than that is imprecise.</p>
<p>Speed is not an issue, I coded solo, so commenting is somewhat distressing since I'm afraid to restate the code.
But I'm open for criticizing on any aspects.</p>
| [] | [
{
"body": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a> to automatically assign a value if none is given.</p>\n\n<pre><code>function neat(numToFormat, thousandSep = \".\", decimalSep = \",\")\n</code></pre>\n\n<p>You should start by checking if the input is valid, instead of doing it at the end. It would also be better to throw an error, since it's not easy to tell from the result if the formatting succeeded or not.</p>\n\n<pre><code>if (typeof numToFormat == 'number') {\n if(Number.isNaN(numToFormat) || !Number.isFinite(numToFormat)) {\n throw new Error(\"Invalid number\");\n }\n}\nelse if(typeof numToFormat == 'string') {\n if(!/^\\d+((,|\\.)\\d+)?$/.test(numToFormat)) {\n throw new Error(\"Invalid string\");\n }\n}\nelse {\n throw new Error(\"Can only use number or string\");\n}\n</code></pre>\n\n<p>It's not <code>parseFloat()</code> which is imprecise, but the numbers themselves. JavaScript uses IEEE 754, which is 64-bit floating point numbers, with 53 bits used for precision. The number you are testing against is the highest safe integer, which is 2^53-1 and can be gotten from <code>Number.MAX_SAFE_INTEGER</code>. But your result could still be imprecise with numbers this large, since you are not only using integers but also 2 decimal places.</p>\n\n<p>With string inputs you can get around this by not converting it to a number at all. Since the result is also a string, you can keep it a string all the way through. For number inputs you can only work with the precision you've been given. Any imprecision should be handled by the code calling this function beforehand.</p>\n\n<p>You will need to update your <code>parseInput</code> function to avoid <code>parseFloat</code>. Just cut of any extra decimals, or add them if they are missing. If you want to round the number it gets a bit harder, but it's still possible.</p>\n\n<p>Your <code>placeThousands</code> function can be done a little simpler. There are several ways to do it, but I would cut the string into an array of chunks and then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>join</code></a> them together. I would also make it easier to change the chunk size by putting it in a variable.</p>\n\n<pre><code>const chunkSize = 3;\nlet chunks = [];\nlet start = wholesPart.length % chunkSize;\nif(start != 0) {\n chunks.push(wholesPart.slice(0, start));\n}\nfor(let i = start; i < wholesPart.length; i+= chunkSize) {\n chunks.push(wholesPart.slice(i, i + chunkSize));\n}\nreturn chunks.join(thousandSep)\n</code></pre>\n\n<p>When I saw <code>fstChunk</code> the first thing I thought was 'fast chunk', but I guess it's supposed to be 'first chunk'. There is no reason make things less clear just to save 2 characters.</p>\n\n<p>You don't need to check the length of <code>wholesPart</code>, <code>placeThousands</code> can handle short strings.</p>\n\n<pre><code>return placeThousands(wholesPart) + decimalPart;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T00:03:36.500",
"Id": "423274",
"Score": "0",
"body": "Thank you @Kruga, unfortunatelly, Default parameters and Number.MAX_SAFE_INTEGER don't work on google-apps-script, but the other points are valid and welcomed. `fstChunk` really is bad :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:30:09.620",
"Id": "219105",
"ParentId": "219068",
"Score": "4"
}
},
{
"body": "<h2>Style and code</h2>\n<ul>\n<li><p>For max integer value use <code>Number.MAX_SAFE_INTEGER</code></p>\n</li>\n<li><p>Use <code>===</code> rather than <code>==</code> and <code>!==</code> rather than <code>!=</code></p>\n</li>\n<li><p><code>typeof</code> is not a function. <code>typeof(numToFormat) == 'number';</code> can be written <code>typeof numToFormat === "number";</code></p>\n</li>\n<li><p>Use <code>isNaN(number)</code> to determine if a variable is <em>"Not a Number"</em></p>\n</li>\n<li><p>Use <code>Number(val)</code> to convert to a number rather than <code>parseFloat(val)</code></p>\n</li>\n<li><p>If you are going to exit on <code>NaN</code> or out of range do it early rather than after you process everything.</p>\n</li>\n<li><p>If a variable is not going to change define it as a constant with <code>const</code></p>\n</li>\n<li><p><code>neat</code> is a rather ambiguous name for the function. Maybe <code>formatNumber</code> would be better</p>\n</li>\n<li><p>Spaces between operators make the code more readable. <code>nextLoop = i+3;</code> as <code>nextLoop = i + 3;</code></p>\n</li>\n<li><p>Space between <code>if</code> and <code>(</code> also <code>for (</code> , <code>while (</code> and other tokens followed by <code>(</code>. And space between <code>) {</code></p>\n</li>\n</ul>\n<h2>Logic</h2>\n<p>The whole thing feels over complicated. For values under 1000 all you do is maybe replace the decimal point. For other values you need only handle the thousands separator.</p>\n<p>There is also the issues of negative numbers. You don't return a string saying No can do. The value you return will have a 1000 separator in the wrong place if the number length is divisible by 3 eg <code>neat(-100)</code> returns <code>"-.100,00"</code></p>\n<h2>Rewrite</h2>\n<ul>\n<li><p>The rewrite fixes the negative number problem.</p>\n</li>\n<li><p>I added a places variable so that the number of decimal places can be set.</p>\n</li>\n<li><p>Uses default parameters to define defaults for (new <code>places</code> arg), <code>thousandSep</code> and <code>decimalSep</code></p>\n</li>\n<li><p>Rather than return error string I return the number argument. It is likely that if the value overflows or is not a number the calling code will not check if the result is one of the error strings. This way what goes in will still have meaning when it comes out.</p>\n</li>\n</ul>\n<p>Code</p>\n<pre><code>function formatNumber(number, thousandSep = ",", decimalSep = ".", places = 2) {\n if (isNaN(number)) { return number }\n var result = number < 0 ? "-" : "";\n number = Math.abs(number);\n if (number >= Number.MAX_SAFE_INTEGER) { return result + number.toFixed(places) }\n \n var place = Math.ceil(Math.log10(number));\n\n if (place < 3) { \n return result + number.toFixed(places).replace(".", decimalSep);\n }\n\n while (place--) {\n result += number / 10 ** place % 10 | 0;\n if (place > 0 && place % 3 === 0) { result += thousandSep }\n }\n \n return result + decimalSep + number.toFixed(places).split(".")[1];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T00:31:57.643",
"Id": "423276",
"Score": "0",
"body": "Thank you @Blindman67, negative numbers really escaped me. Didn't test them at all. I liked the reasoning of returning always a number."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:11:35.860",
"Id": "219131",
"ParentId": "219068",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:33:02.303",
"Id": "219068",
"Score": "3",
"Tags": [
"javascript",
"formatting",
"google-apps-script"
],
"Title": "Function to format numbers with thousand separators and decimals"
} | 219068 |
<p>I have a scenario in which I call many APIs throughout my application lifecycle. </p>
<p>In case the server sends me a 503 response code, it will also send a lockdown object which has a timestamp associated in one of the fields. The reason of this being that I have to block further calls to the server till the timestamp expires. </p>
<p>My solution consists of a retrofit client coupled with an okhttp Interceptor </p>
<p>Here are the steps of execution: </p>
<p>Interceptor (Sentinel) intercepts the request
Interceptor checks a global exception value which is held by an object class (Singelton - LockDownManager ) returns a true or false based on the current timestamp. The LockDownManager is also responsible for memoizing the exception, incase the server is still locked down it helps in rethrowing the same exception. </p>
<p>below is my implementation, I am only including the relevant parts from Sentinel: </p>
<pre><code> class Sentinel : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
// Check with global counter if request can be executed
val canClientMakeRequest = LockDownManager.isServerAvailable()
if (!canClientMakeRequest) {
throw LockDownManager.ex as HttpStatusDetailedException
} else {
// Mark exception null
LockDownManager.ex = null
}
//....... Continue execution
// Response received
// Check if response contains 503 object
// Done by checkIfHasToMemoize(...)
}
</code></pre>
<p>Here is how exception is memoized and parsed: </p>
<pre><code>fun checkIfHasToMemoize(resp: Response) {
// Parse response and derive errorObj - excluded
val errorObj = httpResult.httpError
if (errorObj != null) {
val detailedException =
HttpStatusDetailedException(httpStatusCode, "Unexpected HTTP(S) result:" +
" $result", errorObj)
// Set LockDown -> isServerAvailable
if (detailedException.httpCode == 503 && null != LockDownManager.ex)
LockDownManager.ex = detailedException
throw detailedException
}
</code></pre>
<p>Finally here is my singleton Manager: </p>
<pre><code>object LockDownManager {
@Volatile
var ex: HttpStatusDetailedException? = null
fun isServerAvailable(): Boolean {
if (ex == null) {
return true
}
val serverAvailableTimestamp = ex?.blockUntil ?: 0L
if (serverAvailableTimestamp == 0L) {
return true
}
val c = Calendar.getInstance()
c.timeZone = TimeZone.getTimeZone("UTC")
val currentTime = c.timeInMillis
return currentTime > serverAvailableTimestamp
}
}
</code></pre>
<p>This is a multithreaded environment and more than the semantics of my variable names I am concerned about the veracity of thread safety. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:50:48.750",
"Id": "423151",
"Score": "0",
"body": "Do you get a performance issue if you *don't* memoize the exceptions? Exceptions that are created at one place and thrown in another are generally less useful as they reuse the same stacktrace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:49:47.363",
"Id": "423197",
"Score": "0",
"body": "Memoization is by design, I am rethrowing the memoized exception because there is no chance for the client to connect back to the server and get a new exception - think of it in a way like caging the client and rethrowing the same exception on each retry within the specified time."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:49:44.210",
"Id": "219070",
"Score": "1",
"Tags": [
"multithreading",
"error-handling",
"api",
"kotlin",
"client"
],
"Title": "Temporarily block API calls when server sends a 503 response"
} | 219070 |
<p>I am trying to find out quantiles for each column on the table for various firms using spark 1.6</p>
<p>I have around 5000 entries in firm_list and 300 entries in <code>attr_lst</code>. Number of records in table is around 200000.</p>
<p>I am using 10 executors each with 16gb memory.</p>
<p>Currently it is taking around 1 second for each quantile calculation and 2 mins for whole transformation. with this pace, it will run around 10000 Mins for 5000 firms.</p>
<p>Please let me know how can I optimize the performance.</p>
<pre><code>from __future__ import print_function
from src.utils import sql_service, apa_constant as constant,file_io_service
from pyspark.sql.functions import monotonicallyIncreasingId
from pyspark.sql.functions import lit,col,broadcast
from pyspark.ml.feature import Bucketizer
from pyspark.ml import Pipeline
from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType,DoubleType
from pyspark.sql.types import *
from pyspark.ml.feature import *
from concurrent.futures import *
from functools import reduce
from pyspark.sql import DataFrame
import pyspark
import numpy as np
def generate_quantile_reports(spark_context,hive_context,log,attribute_type,**kwargs):
sql = """describe {}.apa_all_attrs_consortium""".format(kwargs['sem_db'])
op = hive_context.sql(sql)
res = op.withColumn("ordinal_position",monotonicallyIncreasingId())
res.registerTempTable('attribs')
attr_lst = hive_context.sql("""select col_name from attribs where ordinal_position > 24 AND col_name not like '%vehicle%' AND col_name not like'%cluster_num%' AND col_name not like '%value_seg%' order by ordinal_position""").collect()
sql = """select distinct firm_id, firm_name from {}.apa_all_attrs_consortium where ud_rep = 1 and lower(channel) not in ('ria','clearing') order by firm_id limit 5 """.format(kwargs['sem_db'])
dat = hive_context.sql(sql)
firm_list = dat.collect()
sql = """select entity_id, cast(firm_id as double), %s from %s.apa_all_attrs_consortium where ud_rep = 1 and lower(channel) not in ('ria','clearing') cluster by entity_id""" % (", ".join("cast(" + str(attr.col_name) + " as double)" for attr in attr_lst), kwargs['sem_db'])
df = hive_context.sql(sql)
qrtl_list = []
df.cache()
df.count()
counter = 0
for (fm,fnm) in firm_list:
df2 = df[df.firm_id == fm]
df2 = df2.replace(0, np.nan)
df_main = df2.drop('firm_id')
counter += 1
colNames = []
quartileList = []
bucketizerList = []
for var in attr_lst:
colNames.append(var.col_name)
jdf = df2._jdf
bindt = spark_context._jvm.com.dstsystems.apa.util.DFQuantileFunction.approxQuantile(jdf,colNames,[0.0,0.25,0.5,0.75,1.0],0.0)
for i in range(len(bindt)):
quartile = sorted(list(set(list(bindt[i]))))
quartile = [-float("inf")] + quartile
quartile.insert(len(quartile),float("inf"))
quartile.insert(len(quartile),float("NaN"))
df_main = df_main.filter(df_main[colNames[i]].isNotNull())
bucketizerList.append(Bucketizer().setInputCol(colNames[i]).setOutputCol("{}_quantile".format(colNames[i])).setSplits(quartile))
path = " {}/tmpPqtDir/apa_team_broker_quartiles".format(kwargs['semzone_path'])
qrtl_list.append(Pipeline(stages=bucketizerList).fit(df_main).transform(df_main))
finalDF = reduce(DataFrame.unionAll, qrtl_list)
finalDF.repartition(200).write.mode("overwrite").option("header","true").parquet(path)
df.unpersist()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:30:46.733",
"Id": "423129",
"Score": "0",
"body": "Welcome to Code Review! The indentation of your code is broken. You can paste your code from an editor and then either use [\"code fences\"](https://meta.stackexchange.com/a/322000/312087) or select it and press Ctrl+K to have it formatted for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:43:37.867",
"Id": "423307",
"Score": "0",
"body": "@AlexV : Thanks for the suggestion, corrected the indentation."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:24:07.560",
"Id": "219071",
"Score": "2",
"Tags": [
"python",
"apache-spark"
],
"Title": "Quantiles calculation in Pyspark MLib"
} | 219071 |
<p>Today, I decided to implement <code>std::any</code> using the <a href="https://en.cppreference.com/w/cpp/header/any" rel="noreferrer">cppreference page</a>. I've never actually used <code>std::any</code> before and after seeing the implementation first hand... I don't think I'll start now! I'm not entirely sure what this class is actually meant for. I'm not even sure why I implemented this in the first place...</p>
<p>Anyway, here's the code:</p>
<pre><code>#include <memory>
#include <utility>
#include <typeinfo>
namespace mystd {
template <typename T>
struct is_in_place_type : std::false_type {};
template <typename T>
struct is_in_place_type<std::in_place_type_t<T>> : std::true_type {};
class any {
template <typename ValueType>
friend const ValueType *any_cast(const any *) noexcept;
template <typename ValueType>
friend ValueType *any_cast(any *) noexcept;
public:
// constructors
constexpr any() noexcept = default;
any(const any &other) {
if (other.instance) {
instance = other.instance->clone();
}
}
any(any &&other) noexcept
: instance(std::move(other.instance)) {}
template <typename ValueType, typename = std::enable_if_t<
!std::is_same_v<std::decay_t<ValueType>, any> &&
!is_in_place_type<std::decay_t<ValueType>>::value &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
any(ValueType &&value) {
static_assert(std::is_copy_constructible_v<std::decay_t<ValueType>>, "program is ill-formed");
emplace<std::decay_t<ValueType>>(std::forward<ValueType>(value));
}
template <typename ValueType, typename... Args, typename = std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
explicit any(std::in_place_type_t<ValueType>, Args &&... args) {
emplace<std::decay_t<ValueType>>(std::forward<Args>(args)...);
}
template <typename ValueType, typename List, typename... Args, typename = std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<List> &, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>
>>
explicit any(std::in_place_type_t<ValueType>, std::initializer_list<List> list, Args &&... args) {
emplace<std::decay_t<ValueType>>(list, std::forward<Args>(args)...);
}
// assignment operators
any &operator=(const any &rhs) {
any(rhs).swap(*this);
return *this;
}
any &operator=(any &&rhs) noexcept {
any(std::move(rhs)).swap(*this);
return *this;
}
template <typename ValueType>
std::enable_if_t<
!std::is_same_v<std::decay_t<ValueType>, any> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
any &
>
operator=(ValueType &&rhs) {
any(std::forward<ValueType>(rhs)).swap(*this);
return *this;
}
// modifiers
template <typename ValueType, typename... Args>
std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
std::decay_t<ValueType> &
>
emplace(Args &&... args) {
auto new_inst = std::make_unique<storage_impl<std::decay_t<ValueType>>>(std::forward<Args>(args)...);
std::decay_t<ValueType> &value = new_inst->value;
instance = std::move(new_inst);
return value;
}
template <typename ValueType, typename List, typename... Args>
std::enable_if_t<
std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<List> &, Args...> &&
std::is_copy_constructible_v<std::decay_t<ValueType>>,
std::decay_t<ValueType> &
>
emplace(std::initializer_list<List> list, Args &&... args) {
auto new_inst = std::make_unique<storage_impl<std::decay_t<ValueType>>>(list, std::forward<Args>(args)...);
std::decay_t<ValueType> &value = new_inst->value;
instance = std::move(new_inst);
return value;
}
void reset() noexcept {
instance.reset();
}
void swap(any &other) noexcept {
std::swap(instance, other.instance);
}
// observers
bool has_value() const noexcept {
return static_cast<bool>(instance);
}
const std::type_info &type() const noexcept {
return instance ? instance->type() : typeid(void);
}
private:
struct storage_base;
std::unique_ptr<storage_base> instance;
struct storage_base {
virtual ~storage_base() = default;
virtual const std::type_info &type() const noexcept = 0;
virtual std::unique_ptr<storage_base> clone() const = 0;
};
template <typename ValueType>
struct storage_impl final : public storage_base {
template <typename... Args>
storage_impl(Args &&... args)
: value(std::forward<Args>(args)...) {}
const std::type_info &type() const noexcept override {
return typeid(ValueType);
}
std::unique_ptr<storage_base> clone() const override {
return std::make_unique<storage_impl<ValueType>>(value);
}
ValueType value;
};
};
} // mystd
template <>
void std::swap(mystd::any &lhs, mystd::any &rhs) noexcept {
lhs.swap(rhs);
}
namespace mystd {
class bad_any_cast : public std::exception {
public:
const char *what() const noexcept {
return "bad any cast";
}
};
// C++20
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
// any_cast
template <typename ValueType>
ValueType any_cast(const any &anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, const value_type_cvref &>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(*value);
} else {
throw bad_any_cast();
}
}
template <typename ValueType>
ValueType any_cast(any &anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, value_type_cvref &>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(*value);
} else {
throw bad_any_cast();
}
}
template <typename ValueType>
ValueType any_cast(any &&anything) {
using value_type_cvref = remove_cvref_t<ValueType>;
static_assert(std::is_constructible_v<ValueType, value_type_cvref>, "program is ill-formed");
if (auto *value = any_cast<value_type_cvref>(&anything)) {
return static_cast<ValueType>(std::move(*value));
} else {
throw bad_any_cast();
}
}
template <typename ValueType>
const ValueType *any_cast(const any *anything) noexcept {
if (!anything) return nullptr;
auto *storage = dynamic_cast<any::storage_impl<ValueType> *>(anything->instance.get());
if (!storage) return nullptr;
return &storage->value;
}
template <typename ValueType>
ValueType *any_cast(any *anything) noexcept {
return const_cast<ValueType *>(any_cast<ValueType>(static_cast<const any *>(anything)));
}
// make_any
template <typename ValueType, typename... Args>
any make_any(Args &&... args) {
return any(std::in_place_type<ValueType>, std::forward<Args>(args)...);
}
template <typename ValueType, typename List, typename... Args>
any make_any(std::initializer_list<List> list, Args &&... args) {
return any(std::in_place_type<ValueType>, list, std::forward<Args>(args)...);
}
} // mystd
</code></pre>
<p>I'm thinking about doing this in C++11 without rigorously adhering to the standard and without RTTI. Maybe another day...</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:07:21.270",
"Id": "423140",
"Score": "4",
"body": "There's nothing much to say except it's excellent. As to why use `std::any`, I'd say it's rarely useful, because if you know the possible type values you'd use `std::variant`, and if not you'll be embarrassed to cast it back to a usable value / pointer. Besides, C++ programmers are used to avoid RTTI and Java-like hierarchies under a very abstract `Object` type. Nonetheless it can find a use in evolutive / pluggable / distributed programs, where different components can try and recognize what a `std::any` really is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T12:20:40.910",
"Id": "530083",
"Score": "0",
"body": "In `any_cast` of a pointer, you check if the pointer is null before `dynamic_cast`, and then again after. But `dynamic_cast<T>(nullptr)` just gives back a null pointer of type `T` (https://en.cppreference.com/w/cpp/language/dynamic_cast item 2), so these two checks can be merged.\n\nIs there a reason to keep them separate, such as clarity or optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T21:09:23.250",
"Id": "530132",
"Score": "1",
"body": "@Riley I’m not checking `anything` and casting `anything`. I’m checking `anything` and casting `anything->storage`. If either of the null checks are removed then I’d be dereferencing a null pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T18:37:58.303",
"Id": "530247",
"Score": "0",
"body": "Oh understood thanks!"
}
] | [
{
"body": "<p>Your implementation is excellent! I can hardly find any problems. I was amazed how simple a conforming implementation of <code>any</code> can be. And I wholeheartedly agree with <a href=\"https://codereview.stackexchange.com/users/157553/papagaga\"><strong>@papagaga</strong></a>'s <a href=\"https://codereview.stackexchange.com/questions/219075/implementation-of-stdany#comment423140_219075\">comment</a>.</p>\n\n<p>Here's my two cents. I use the <a href=\"https://timsong-cpp.github.io/cppwp/n4659/\" rel=\"nofollow noreferrer\">N4659</a>, the C++17 final draft, as a reference.</p>\n\n<h2>Non-conformance (priority: high)</h2>\n\n<ol>\n<li><p><a href=\"http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0551r3.pdf\" rel=\"nofollow noreferrer\">Thou Shalt Not Specialize <code>std::swap</code></a>. Instead, you should overload <code>swap</code> to be found by ADL. See <a href=\"https://stackoverflow.com/questions/11562/how-to-overload-stdswap#comment-5729583\">How to overload <code>std::swap()</code></a> on Stack Overflow. </p>\n\n<pre><code>class any {\npublic:\n // ...\n friend void swap(any& lhs, any& rhs)\n {\n lhs.swap(rhs);\n }\n};\n</code></pre></li>\n<li><p><a href=\"https://timsong-cpp.github.io/cppwp/n4659/any.bad_any_cast#2\" rel=\"nofollow noreferrer\">[any.bad_any_cast]/2</a> specifies that <code>bad_any_cast</code> should derive from <code>std::bad_cast</code>. Your implementation fails to do this.</p></li>\n</ol>\n\n<h2>Other suggestions (priority: low)</h2>\n\n<ol>\n<li><p><a href=\"https://timsong-cpp.github.io/cppwp/n4659/any.class#3\" rel=\"nofollow noreferrer\">[any.class]/3</a> says:</p>\n\n<blockquote>\n <p>Implementations should avoid the use of dynamically allocated memory\n for a small contained value. [ <em>Example</em>: where the object constructed\n is holding only an <code>int</code>. — <em>end example</em> ]\n Such small-object optimization shall only be applied to types <code>T</code> for \n which <code>is_nothrow_move_constructible_v<T></code> is <code>true</code>.</p>\n</blockquote>\n\n<p>Clearly, you did not implement this optimization.</p></li>\n<li><p>Initially I thought, \"where is your destructor?\" Then I realized that the synthesized destructor is equivalent to <code>reset()</code>. I recommend you explicitly default this to reduce confusion since you implemented the rest of the Big Five.</p>\n\n<pre><code>~any() = default;\n</code></pre></li>\n<li><p>The following <code>static_assert</code> on line 40 is unnecessary:</p>\n\n<pre><code>static_assert(std::is_copy_constructible_v<std::decay_t<ValueType>>, \"program is ill-formed\");\n</code></pre>\n\n<p>because this constructor does not participate in overload resolution unless <code>std::is_copy_constructible_v<std::decay_t<ValueType>></code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T04:45:14.410",
"Id": "423453",
"Score": "2",
"body": "I was hoping for a review that mentioned nonconformance! Specializing the swap template felt a bit weird. I overloaded swap in the past but I guess just I forgot this time. The cppreference page does say that bad_any_cast derives from bad_cast so my fault for not reading carefully. I've never implemented SBO before so I wasn't sure how to do it. I do remember explicitly defaulting the destructor at some point but I guess I deleted it when reordering things (oops). I knew the static_assert was redundant but the cppreference page mentions \"program is ill-formed\" so I did it anyway! Great review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T04:47:53.810",
"Id": "423454",
"Score": "0",
"body": "@Kerndog73 Thank you! Hope you don't liberally forget things in the future ;-) About SBO: it's not that hard. You can just specialize the template for types that meet some criteria (e.g., `sizeof(T)` is less than some threshold) and implement it accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T04:31:40.340",
"Id": "219233",
"ParentId": "219075",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "219233",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:23:12.443",
"Id": "219075",
"Score": "19",
"Tags": [
"c++",
"reinventing-the-wheel",
"template-meta-programming",
"c++17",
"variant-type"
],
"Title": "Implementation of std::any"
} | 219075 |
<p>I'm learning how to write code in Python. This code makes an .ini that saves different cycles adding one new operation to the previous cycle. It starts at 1;1, saves that it has run 1 cycle and will start cycle 2 next time. So, next is 1;2 followed by 2;2. Next cycle is 3, so it will go up to three: 1;3, 2;3, 3;3, etc. until 7;7 is reached. After that it switches to fullcycles. Hope this explains it well enough.</p>
<p>The challenge is to make this code work with as least as code as possible.</p>
<pre><code>import os, configparser, webbrowser
chakras = [['root', '1', 'https://www.youtube.com/watch?v=JTqktSAmG30'],
['sacral', '2', 'https://www.youtube.com/watch?v=VRGs0GiR-QY'],
['solar', '3', 'https://www.youtube.com/watch?v=Pz47Fv_TQDU'],
['heart', '4', 'https://www.youtube.com/watch?v=tDWoIAITBiY'],
['throat', '5', 'www.youtube.com/watch?v=QwzSOF9GEHo'],
['thirdeye', '6', 'https://www.youtube.com/watch?v=IpbXlN2duKk'],
['crown', '7', 'https://www.youtube.com/watch?v=7ZpUUXNQW1E']]
def OpenChakraLinkPlusSaveNext():
config = configparser.ConfigParser()
config.read('Chakras.ini')
config.sections()
try:
chakracycle = int(config['Chakras']['chakracycle'])
trainingcycle = int(config['Chakras']['trainingcycle'])
fullchakracycle = int(config['Chakras']['fullchakracycle'])
except KeyError:
config = configparser.ConfigParser()
config['Chakras'] = {'chakracycle': 1,
'trainingcycle': 1,
'fullchakracycle': 0}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
config = configparser.ConfigParser()
config.read('Chakras.ini')
config.sections()
chakracycle = int(config['Chakras']['chakracycle'])
trainingcycle = int(config['Chakras']['trainingcycle'])
fullchakracycle = int(config['Chakras']['fullchakracycle'])
### Debugging which cycle is saved now.
## print(chakracycle)
## print(trainingcycle)
## print(fullchakracycle)
for chakra in chakras:
if int(chakra[1]) == chakracycle:
### Debugging which chakra is going to be loaded.
##print(chakra[0])
webbrowser.open(chakra[2])
if fullchakracycle == 0:
if chakracycle >= 7 and trainingcycle == chakracycle:
config['Chakras'] = {'chakracycle': 1,
'trainingcycle': 0,
'fullchakracycle': int(fullchakracycle) + 1}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
elif trainingcycle == chakracycle:
config['Chakras'] = {'chakracycle': 1,
'trainingcycle': int(trainingcycle) + 1,
'fullchakracycle': 0}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
elif trainingcycle != chakracycle:
config['Chakras'] = {'chakracycle': int(chakracycle) + 1,
'trainingcycle': int(trainingcycle),
'fullchakracycle': 0}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
elif fullchakracycle != 0:
if chakracycle >= 7:
config['Chakras'] = {'chakracycle': 1,
'trainingcycle': 0,
'fullchakracycle': int(fullchakracycle) + 1}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
else:
config['Chakras'] = {'chakracycle': int(chakracycle) + 1,
'trainingcycle': 0,
'fullchakracycle': int(fullchakracycle)}
with open('Chakras.ini', 'w') as configfile:
config.write(configfile)
### Debugging which cycle will be saved.
## print(chakracycle)
## print(trainingcycle)
## print(fullchakracycle)
OpenChakraLinkPlusSaveNext()
</code></pre>
| [] | [
{
"body": "<p><code>OpenChakraLinkPlusSaveNext()</code> is a <em>very</em> long function, with its logic for incrementing, loading, and saving state scattered and duplicated all over the place. Functions should adhere to the Single Responsibility Principle, and do one thing only.</p>\n\n<p>Another problem is that the implementation is strongly tied to <code>configparser</code>. As a result, you need to put <code>int()</code> casts all over the place, because <code>configparser</code> only deals with strings.</p>\n\n<h2>Counting</h2>\n\n<p>Start by focusing on the core functionality and the main challenge of the code, which is how to increment the counters.</p>\n\n<p>I suggest defining a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>namedtuple</code></a> with three fields: <code>fullchakracycle</code>, <code>trainingcycle</code>, and <code>chakra</code>. Note that I've written the fields in reverse order, because <code>fullchakracycle</code> acts as the \"most significant\" field if you wanted to compare two states. I've also renamed <code>chakracycle</code> to <code>chakra</code>, since I consider it just a counter and not a cycle counter.</p>\n\n<pre><code>from collections import namedtuple\n\nclass ChakraState(namedtuple('ChakraState', 'fullchakracycle trainingcycle chakra')):\n def next(self):\n if self.fullchakracycle or \\\n self.trainingcycle == self.chakra == 7:\n return ChakraState(\n self.fullchakracycle + (self.chakra == 7),\n 0,\n self.chakra % 7 + 1\n )\n else:\n return ChakraState(\n 0,\n self.trainingcycle + (self.chakra == self.trainingcycle),\n self.chakra % self.trainingcycle + 1\n )\n</code></pre>\n\n<p>You can easily write a short script to verify that it increments correctly:</p>\n\n<pre><code>state = ChakraState(0, 1, 1)\nfor _ in range(50):\n print(state)\n state = state.next()\n</code></pre>\n\n<p>The output should look like:</p>\n\n<pre><code>ChakraState(fullchakracycle=0, trainingcycle=1, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=2, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=2, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=3, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=3, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=3, chakra=3)\nChakraState(fullchakracycle=0, trainingcycle=4, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=4, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=4, chakra=3)\nChakraState(fullchakracycle=0, trainingcycle=4, chakra=4)\nChakraState(fullchakracycle=0, trainingcycle=5, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=5, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=5, chakra=3)\nChakraState(fullchakracycle=0, trainingcycle=5, chakra=4)\nChakraState(fullchakracycle=0, trainingcycle=5, chakra=5)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=3)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=4)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=5)\nChakraState(fullchakracycle=0, trainingcycle=6, chakra=6)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=1)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=2)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=3)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=4)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=5)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=6)\nChakraState(fullchakracycle=0, trainingcycle=7, chakra=7)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=1)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=2)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=3)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=4)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=5)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=6)\nChakraState(fullchakracycle=1, trainingcycle=0, chakra=7)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=1)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=2)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=3)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=4)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=5)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=6)\nChakraState(fullchakracycle=2, trainingcycle=0, chakra=7)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=1)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=2)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=3)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=4)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=5)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=6)\nChakraState(fullchakracycle=3, trainingcycle=0, chakra=7)\nChakraState(fullchakracycle=4, trainingcycle=0, chakra=1)\n</code></pre>\n\n<h2>Suggested solution</h2>\n\n<p>Then, we can go on to add support for loading and saving the state in <code>Chakras.ini</code>. I've chosen to write the <code>load()</code> and <code>save()</code> methods within the <code>ChakraState</code> class.</p>\n\n<p><code>chakras</code> is a \"constant\", so I'd name it using <code>ALL_CAPS</code>. Since only the URLs matter, I've dropped the name and number fields.</p>\n\n<pre><code>from collections import namedtuple\nimport configparser\nimport webbrowser\n\nCHAKRAS = [\n 'https://www.youtube.com/watch?v=JTqktSAmG30', # root\n 'https://www.youtube.com/watch?v=VRGs0GiR-QY', # sacral\n 'https://www.youtube.com/watch?v=Pz47Fv_TQDU', # solar\n 'https://www.youtube.com/watch?v=tDWoIAITBiY', # heart\n 'https://www.youtube.com/watch?v=QwzSOF9GEHo', # throat\n 'https://www.youtube.com/watch?v=IpbXlN2duKk', # thirdeye\n 'https://www.youtube.com/watch?v=7ZpUUXNQW1E', # crown\n]\n\nclass ChakraState(namedtuple('ChakraState', 'fullchakracycle trainingcycle chakra')):\n def next(self):\n if self.fullchakracycle or \\\n self.trainingcycle == self.chakra == len(CHAKRAS):\n return ChakraState(\n self.fullchakracycle + (self.chakra == len(CHAKRAS)),\n 0,\n self.chakra % len(CHAKRAS) + 1\n )\n else:\n return ChakraState(\n 0,\n self.trainingcycle + (self.chakra == self.trainingcycle),\n self.chakra % self.trainingcycle + 1\n )\n\n @classmethod\n def load(cls, filename):\n config = configparser.ConfigParser()\n config.read(filename)\n try:\n return cls(**{k: int(v) for k, v in config['Chakras'].items()})\n except KeyError:\n return cls(0, 1, 1)\n\n def save(self, filename):\n config = configparser.ConfigParser()\n config['Chakras'] = self._asdict()\n with open(filename, 'w') as f:\n config.write(f)\n\ndef open_chakra_link_and_save_next():\n state = ChakraState.load('Chakras.ini')\n webbrowser.open(CHAKRAS[state.chakra - 1])\n state.next().save('Chakras.ini')\n\nif __name__ == '__main__':\n open_chakra_link_and_save_next()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:39:48.670",
"Id": "423173",
"Score": "2",
"body": "nice solution. In python 3.7, [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses) might be easier than `namedtuple`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-31T19:35:22.943",
"Id": "437393",
"Score": "0",
"body": "Wow Thanks, man I'm sorry I couldn't take the time to respond and figure out how well written your script is. I still haven't tried it out, but thanks in advance man, this is literally what I've asked for!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:41:44.413",
"Id": "219087",
"ParentId": "219077",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:25:28.897",
"Id": "219077",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"windows",
"configuration"
],
"Title": "Opening YouTube videos according to chakra cycles"
} | 219077 |
<p>I have a power shell script that when run will prompt the user to:</p>
<ol>
<li>Select a folder location</li>
<li>select a file name</li>
<li>enter credentials</li>
</ol>
<p>This then exports those credentials in a xml file. Although this requires 3 prompts to the user before is complete. Looking to find if there is a better way to approach this. For example, having a single prompt for the user. </p>
<pre><code>###########################################################
# Create a file containing encrypted credentials
###########################################################
clear
Function Get-Folder($initialDirectory)
{
#User selected folder location
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$path = New-Object System.Windows.Forms.FolderBrowserDialog
$path.Description = "Select a folder"
$path.rootfolder = "MyComputer"
if($path.ShowDialog() -eq "OK")
{
$location += $path.SelectedPath
}
#User selected file name
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'File Name'
$msg = 'Please enter your file name'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
#Open prompt for user to enter credentials and export to xml file
Get-Credential | Export-Clixml "$location\Credentials-$text.xml"
}
Get-Folder
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Instead of letting the user (1) choose a folder and (2) choose a file name, you can just present the user with a <strong>Save File Dialog</strong>. It also warns the user if he tries to overwrite an existing file.</p></li>\n<li><p>If the user cancels one of your dialogs, you should cancel the script rather than continue with invalid data.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>$dialog = New-Object System.Windows.Forms.SaveFileDialog\n$dialog.FileName = \"Credentials.xml\"\n$dialog.Filter = \"XML files (*.xml)|*.xml|All files|*.*\"\n\nif ($dialog.ShowDialog() -ne \"OK\")\n{\n exit\n}\n\n...\n\nGet-Credential | Export-Clixml $dialog.FileName\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:34:22.120",
"Id": "219107",
"ParentId": "219081",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:16:45.393",
"Id": "219081",
"Score": "3",
"Tags": [
"powershell"
],
"Title": "Powershell script to save user credentials in a xml file"
} | 219081 |
<p>A list of objects needs to be grouped. </p>
<p>The list is iterated and checked with other objects in the same list except itself. The method People.isAttributeEqual() checks if two objects can be grouped.</p>
<p>The list returns a list of two unique objects with the same attributes.</p>
<p>I am trying to optimize the method People.groupSimilar(). All other details given here are just snippets.</p>
<p>The code below works but looks clunky and non optimized. Is there a way to optimize and use lambda instead?</p>
<pre><code>public class People
{
private String name;
private String age;
private String address;
public People(final String name, final String age, final String address)
{
this.name = name;
this.age = age;
this.address = address;
}
public boolean isAttributeEqual(final People dupPeop)
{
return this.address.equals(dupPeop.address) && this.age.equals(dupPeop.age) && this.name.equals(dupPeop.name);
}
public static void main(final String[] args)
{
List<People> asList = Arrays.asList(new People("Sri", "28", "TN"), new People("Sri", "28", "TN"), new People("Sri", "28", "TN"),
new People("Pri", "28", "TN"));
List<People> groupSimilar = groupSimilar(asList);
}
public static List<People> groupSimilar(final List<People> people)
{
List<People> duplicatePeople = new ArrayList<>(people);
for (Iterator<People> iterator = duplicatePeople.iterator(); iterator.hasNext();)
{
People people2 = iterator.next();
for (People orignalPeople : people)
{
if (!orignalPeople.equals(people2) && orignalPeople.isAttributeEqual(people2))
{
iterator.remove();
people2 = iterator.next();
}
}
}
return duplicatePeople;
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code>public class People\n</code></pre>\n</blockquote>\n\n<p>The class is named <code>People</code>, but it should probably be called <code>Person</code>. Every instance of the class is another Person, not another People.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>private String name;\nprivate String age;\nprivate String address;\n</code></pre>\n</blockquote>\n\n<p>It might be worth to consider splitting up the <code>name</code> attribute into a <code>firstName</code> and <code>lastName</code>, because otherwise it could be difficult to compare two peoples' last names, for example.</p>\n\n<p>Representing <code>age</code> as a <code>String</code> is not the best fit. Age is usually a whole number, i.e. an integer, so it would be better to use <code>int</code> instead. Then you could also more easily compare ages by e.g. calculating the age difference between two people. <code>String</code>s should be used for things that are actual text or at least sequences of characters.</p>\n\n<p>Even better than having an <code>age</code> attribute at all could be to have a <code>dateOfBirth</code> instead, represented by the Java type <code>Date</code>. Age is just an implicit attribute of a person that could change any day, and so instead of saving it in a variable you can calculate it from the date of birth and the current date whenever you need.</p>\n\n<p>I'd say that representing <code>address</code> as a <code>String</code> is fine, but could be worth getting its own class with <code>street</code>, <code>zipCode</code> etc., then saving a reference to an <code>Address</code> inside the <code>Person</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public boolean isAttributeEqual(final People dupPeop)\n</code></pre>\n</blockquote>\n\n<p><code>isAttributeEqual</code> does not tell you which attribute it checks. The singular name implies that one attribute is being checked, but what the method actually does is compare all attributes. There is a convention for that in Java, which is to override the <code>equals</code> method which the class inherits from <code>Object</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>List<People> asList = Arrays.asList(new People(\"Sri\", \"28\", \"TN\"), new People(\"Sri\", \"28\", \"TN\"), new People(\"Sri\", \"28\", \"TN\"),\n new People(\"Pri\", \"28\", \"TN\"));\n\nList<People> groupSimilar = groupSimilar(asList);\n</code></pre>\n</blockquote>\n\n<p>It can be more readable if a variable name states what it contains, independently from how it came to be. <code>asList</code> is the operation that creates the list, but that will not be relevant anymore if you use the variable later on in the code. So, assuming the rename of the class that I recommended earlier, you could have something like this:</p>\n\n<pre><code>List<Person> persons\n</code></pre>\n\n<p>or</p>\n\n<pre><code>List<Person> people\n</code></pre>\n\n<p>Similarly, <code>groupSimilar</code> groups similar people, but the result is a list of similar people:</p>\n\n<pre><code>List<Person> similarPeople = groupSimilar(people);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>List<Person> similarlyGroupedPeople = groupSimilar(people);\n</code></pre>\n\n<p>Also, it seems to me that what <code>groupSimilar</code> does is to find the people that are duplicated in the same list, rather than actually grouping similar people, so I would rename the variable and the method to this:</p>\n\n<pre><code>List<Person> duplicates = findDuplicates(people);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public static List<People> groupSimilar(final List<People> people)\n {\n List<People> duplicatePeople = new ArrayList<>(people);\n for (Iterator<People> iterator = duplicatePeople.iterator(); iterator.hasNext();)\n {\n People people2 = iterator.next();\n for (People orignalPeople : people)\n {\n if (!orignalPeople.equals(people2) && orignalPeople.isAttributeEqual(people2))\n {\n iterator.remove();\n people2 = iterator.next();\n }\n }\n }\n return duplicatePeople;\n }\n</code></pre>\n</blockquote>\n\n<p>Rather than manually controlling the iterator, i.e. checking <code>hasNext()</code> and advancing it with <code>next()</code>, I would use a simple for-each loop for the outer loop, just like your inner loop already is.</p>\n\n<p>Since you are using the default implementation for <code>equals</code> which is inherited from <code>Object</code>, it is equivalent to a reference equality check, which can be done on reference types using the <code>==</code> operator (<code>!=</code> for reference inequality).</p>\n\n<p>So, assuming that you replaced your <code>isAttributeEqual</code> with an overriding implementation of <code>equals</code>, and use <code>==</code>/<code>!=</code> instead of the default <code>equals</code>, I would rewrite the method like this:</p>\n\n<pre><code>public static List<People> findDuplicates(final List<People> people) {\n List<People> duplicates = new ArrayList<>();\n\n for (Person person : people) {\n for (Person person2 : people) {\n if (person != person2 && person.equals(person2) {\n duplicates.add(person);\n }\n }\n }\n\n return duplicates;\n}\n</code></pre>\n\n<p>The code also becomes, in my view, more easily understandable by only adding the people that are verified as duplicates, rather than declaring all as duplicates and removing those that are not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:59:41.940",
"Id": "219088",
"ParentId": "219082",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:30:36.623",
"Id": "219082",
"Score": "0",
"Tags": [
"java",
"performance",
"iteration"
],
"Title": "Grouping objects that have the same attributes"
} | 219082 |
<p>I've got a class that is like a facade, like an engine for my application which is responsible for fetching data from url and summing it.</p>
<p>I have got problem with proper names for my methods. </p>
<ol>
<li><code>executeNBPParserEngine</code> is like method that connects everything to one. It gots <code>if</code> and <code>else</code> statement. If statement checks if the given day is included in current year (data from current year is stored in different page than from previous years). If yes, then it opens connection to the given site (data from current year is stored in different page than from previous years), fetch some data and sum it in sumOfSellingRate and sumOfBuyingRate.</li>
</ol>
<p>The class looks like this. I do not know if every method here is named properly. Maybe I should create some more methods to shorten it more?</p>
<pre><code>import conditionchecker.ConditionChecker;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.System.in;
class NBPParserEngine {
public static final String KOD_WALUTY = "kod_waluty";
private ConditionChecker conditionChecker;
private DataFetcher dataFetcher;
private Scanner scanner;
private float buyingRate;
private float sellingRate;
private float sumOfBuyingRate = 0;
private float sumOfSellingRate = 0;
NBPParserEngine(ConditionChecker conditionChecker, DataFetcher dataFetcher) {
this.conditionChecker = conditionChecker;
this.dataFetcher = dataFetcher;
scanner = new Scanner(in);
}
void executeNBPParserEngine() {
String startDateString = "2013-01-28";
String endDateString = "2013-01-31";
List<LocalDate> daysBetweenFirstAndSecondDate = findDaysBetweenFirstAndSecondDate(startDateString, endDateString);
for (LocalDate iteratedDay : daysBetweenFirstAndSecondDate) {
if (conditionChecker.checkIfGivenDayIsIncludedInCurrentYear(iteratedDay))
try {
String DIR_SOURCE = "http://www.nbp.pl/kursy/xml/dir.txt";
String line = dataFetcher.findLineWithGivenDate(String.valueOf(iteratedDay), DIR_SOURCE);
sumBuyingAndSellingRate(line);
} catch (IOException | SAXException | ParserConfigurationException e) {
e.printStackTrace();
}
else {
try {
String iteratedDayString = iteratedDay.toString();
String[] iteratedStringArray = iteratedDayString.split("-");
String DIR_SOURCE = "http://www.nbp.pl/kursy/xml/dir" + iteratedStringArray[0] + ".txt";
String line = dataFetcher.findLineWithGivenDate(String.valueOf(iteratedDay), DIR_SOURCE);
sumBuyingAndSellingRate(line);
} catch (IOException | SAXException | ParserConfigurationException e) {
e.printStackTrace();
}
}
}
}
void sumBuyingAndSellingRate(String line) throws ParserConfigurationException, SAXException, IOException {
String URL_SOURCE = "http://www.nbp.pl/kursy/xml/" + line + ".xml";
Document doc = dataFetcher.getXML(URL_SOURCE);
NodeList nList = doc.getElementsByTagName("pozycja");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.getElementsByTagName(KOD_WALUTY).item(0).getTextContent().equals("USD")) {
buyingRate = getBuyingRateFromDOM(eElement);
sellingRate = getSellingRateFromDOM(eElement);
}
}
}
sumOfBuyingRate += buyingRate;
sumOfSellingRate += sellingRate;
}
public float getSellingRateFromDOM(Element eElement) {
return Float.parseFloat(eElement
.getElementsByTagName("kurs_sprzedazy")
.item(0)
.getTextContent().replaceAll(",", "."));
}
float getBuyingRateFromDOM(Element eElement) {
return Float.parseFloat((eElement
.getElementsByTagName("kurs_kupna")
.item(0)
.getTextContent().replaceAll(",", ".")));
}
public List<LocalDate> findDaysBetweenFirstAndSecondDate(String startDateString, String endDateString) {
LocalDate startDate = LocalDate.parse(startDateString);
LocalDate endDate = LocalDate.parse(endDateString);
Stream<LocalDate> dates = startDate.datesUntil(endDate.plusDays(1));
return dates.collect(Collectors.toList());
}
}
</code></pre>
| [] | [
{
"body": "<h2>Naming Convention</h2>\n\n<hr>\n\n<p>To answer I think your method names are unnecessarily long and overly descriptive.</p>\n\n<p><em>executeNbpParserEngine</em> is a little more readable then <em>executeNBPParserEngine</em> as it doesn't hide Parse.\nWhen working with acronyms:\nOne should take into account if the abbreviation is well known such as XML, HTTP, JSON.\nif the abbreviation is at the end ex. <em>executeParserEngineFromNBP</em> then it is even more readable.\n<a href=\"https://stackoverflow.com/questions/2236807/java-naming-convention-with-acronyms\">read more here</a></p>\n\n<p>I.e When I read the function name <strong><em>findDaysBetweenFirstAndSecondDate</em></strong>\nIt's difficult to read.\nYour function name should work with your arguments name and return type to give a more accurate description.</p>\n\n<h2>Code review:</h2>\n\n<hr>\n\n<p>1: Initialise the Scanner Object in line as it will improve Maintainability if you need multiple constructors in the future.</p>\n\n<pre><code>private Scanner scanner = new Scanner(in); \n</code></pre>\n\n<p>2: Switch <em>executeNBPParserEngine</em> to <em>executeNbpParserEngine</em> it a bit cleaner\n3: <em>findDaysBetweenFirstAndSecondDate</em> to <em>getDaysBetween</em></p>\n\n<p>Also, you do not have to declare a variable just run collect on the return from LocalDate: datesUntil.</p>\n\n<pre><code>public List<LocalDate> getDaysBetween(String startDateString, String endDateString) {\n LocalDate startDate = LocalDate.parse(startDateString);\n LocalDate endDate = LocalDate.parse(endDateString);\n return startDate.datesUntil(endDate.plusDays(1)).collect(Collectors.toList());\n}\n</code></pre>\n\n<p>4: Combine <em>getSellingRateFromDOM</em> && <em>getBuyingRateFromDOM</em> as they are too similar.\nchange to </p>\n\n<pre><code> float getFieldFromDOM(Element eElement,String tag) {\nreturn Float.parseFloat((eElement\n .getElementsByTagName(tag)\n .item(0)\n .getTextContent().replaceAll(\",\", \".\")));\n</code></pre>\n\n<p>}</p>\n\n<p>Also, add final strings that contain tag ex.kurs_kupna</p>\n\n<pre><code>private final String BUY_RATE_TAG = \"kurs_kupna\";\nprivate final String SELL_RATE_TAG = \"kurs_sprzedazy\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:19:21.337",
"Id": "423796",
"Score": "0",
"body": "The last thing I want to ask is `sumBuyingAndSellingRate` is invalid name, as this method looks like this now: https://pastebin.com/EENPupFJ It is very similiar, but I sum `buyingRate` and add to list `sellingRate` as I need to calculate later standard deviation. What is the proper name for it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:22:35.847",
"Id": "219381",
"ParentId": "219084",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219381",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:16:42.147",
"Id": "219084",
"Score": "1",
"Tags": [
"java",
"dom",
"url"
],
"Title": "Summing buying and selling rate fetched from the web txt"
} | 219084 |
<p><strong>Context:</strong></p>
<p>I'm building a React app using Ramda as a helper library for functional programming.</p>
<p>Users can import contacts into the app. These contacts can be <a href="https://en.wikipedia.org/wiki/VCard" rel="nofollow noreferrer">vCards</a>.</p>
<p>I've written a function that:</p>
<ol>
<li>Removes duplicates,</li>
<li>Removes companies,</li>
<li>Transforms the vcards data into contacts the React app understands.</li>
</ol>
<p>The apps contacts look like this:</p>
<pre><code>{
firstName: 'Bob',
lastName: 'Mueller',
company: 'X-Enterprises',
position: 'CEO',
contactDetails: 'Cell phone: 555-55-5555 Email: bob.mueller@XE.com',
conversationTopics: 'We talked about politics.'
city: 'New York'
}
</code></pre>
<p>So an empty contact looks like this:</p>
<pre><code>const emptyContact = {
firstName: '',
lastName: '',
company: '',
position: '',
contactDetails: '',
conversationTopics: ''
city: ''
}
</code></pre>
<p>I will give you the fixtures with which I test my function in the end, because they are very long. But here is the test that I wrote to test my function:</p>
<pre><code>describe('createVCardContacts()', async assert => {
assert({
given: 'an array of vcard contacts',
should: 'return an array of valid contacts',
actual: createVCardContacts(vCardData),
expected: parsedVCardData,
});
});
</code></pre>
<p>Valid contacts here means no duplicates and no companies.</p>
<p><strong>Function:</strong></p>
<p>So, here is the <code>createVCardContacts</code> function:</p>
<pre><code>import * as R from 'ramda';
import * as RA from 'ramda-adjunct';
import * as R_ from 'ramda-extension';
// VCard data always has its value at index 3 and can either be
// an array or a value
const getDataFromVCard = R.pipe(
R.ifElse(
R.pipe(
R.head,
R_.isArray
),
R.head,
R.identity
),
R.nth(3)
);
export const nGetter = R.pipe(
getDataFromVCard,
R.takeWhile(R.complement(R.isEmpty))
);
export const orgGetter = R.pipe(
getDataFromVCard,
R.replace(';', '')
);
export const bdayGetter = R.pipe(
getDataFromVCard,
R.concat('Birthday: ')
);
export const titleGetter = getDataFromVCard;
export const noteGetter = getDataFromVCard;
export const adrGetter = R.pipe(
getDataFromVCard,
R.nth(3)
);
export const telGetter = R.pipe(
getDataFromVCard,
R.concat('Cell phone: ')
);
export const emailGetter = R.pipe(
getDataFromVCard,
R.concat('Email: ')
);
const vCardEvolveObject = {
n: nGetter,
org: orgGetter,
bday: bdayGetter,
title: titleGetter,
note: noteGetter,
adr: adrGetter,
tel: telGetter,
email: emailGetter,
};
export const createVCardContacts = R.pipe(
// Remove duplicates by name
R.uniqBy(R.prop('n')),
// Remove companies
R.reject(
R.both(
R.both(R.has('fn'), R.has('org')),
R.converge(R.equals, [
R.pipe(
R.prop('fn'),
R.nth(3)
),
R.pipe(
R.prop('org'),
R.nth(3),
R.replace(';', '')
),
])
)
),
R.map(
R.pipe(
// Only pick relevant keys, if present
R.pick(R.keys(vCardEvolveObject)),
// Transform object to only contain strings
R.evolve(vCardEvolveObject),
// Add contact details key
R.assoc('contactDetails', ''),
// Build information for contact details from bday, phone, and email
R.mapObjIndexed((val, key, obj) =>
key === 'contactDetails'
? R.trim(
R.replace(
/undefined/g,
'',
`${R.prop('bday')(obj)} ${R.prop('tel')(obj)} ${R.prop('email')(
obj
)}`
)
)
: val
),
// Get first and last name
R.converge(R.assoc('lastName'), [
R.pipe(
R.prop('n'),
R.head
),
R.identity,
]),
R.converge(R.assoc('firstName'), [
R.pipe(
R.prop('n'),
R.drop(1),
R.reduce((acc, val) => R.trim(`${acc} ${val}`), '')
),
R.identity,
]),
// Remove irrelevant keys
R.dissoc('n'),
R.dissoc('bday'),
R.dissoc('tel'),
R.dissoc('email'),
// Rename relevant keys
RA.renameKeys({
org: 'company',
adr: 'city',
title: 'position',
note: 'conversationTopics',
})
)
),
R.merge(emptyContact)
);
</code></pre>
<p>Here is why I post this question on code review:</p>
<ol>
<li>The function is super long meaning it looks a little bit like spaghetti code. </li>
<li>I'm new to functional programming and maybe I'm doing wrong things here.</li>
</ol>
<p>If you could have a look at it and maybe improve it, make it more readable and / or performant, and teach me I would be super grateful! Thank you very much.</p>
<p><strong>Fixtures:</strong></p>
<pre><code>export const vCardData = [
{
version: ['version', {}, 'text', '3.0'],
prodid: ['prodid', {}, 'text', '-//Apple Inc.//iOS 10.2//EN'],
n: ['n', {}, 'text', ['Mueller', 'Alex', '', '', '']],
fn: ['fn', {}, 'text', 'Alex Mueller'],
tel: ['tel', { type: ['cell', 'voice', 'pref'] }, 'text', '+555-5555-55'],
rev: ['rev', {}, 'text', '2018-03-01T08:05:33Z'],
},
{
version: ['version', {}, 'text', '3.0'],
prodid: ['prodid', {}, 'text', '-//Apple Inc.//iOS 11.1.2//EN'],
n: ['n', {}, 'text', ['Mueller', 'Alex', '', '', '']],
fn: ['fn', {}, 'text', 'Alex Mueller'],
tel: ['tel', { type: ['cell', 'voice', 'pref'] }, 'text', '+555-5555-55'],
rev: ['rev', {}, 'text', '2018-02-14T16:01:30Z'],
},
{
version: ['version', {}, 'text', '3.0'],
prodid: ['prodid', {}, 'text', '-//Apple Inc.//Mac OS X 10.14//EN'],
n: ['n', {}, 'text', ['', '', '', '', '']],
fn: ['fn', {}, 'text', 'Apple GmbH'],
org: ['org', {}, 'text', 'Apple GmbH;'],
url: [
'url',
{ group: 'item1', type: 'pref' },
'text',
'http://www.apple.com/de/',
],
xAbLabel: ['xAbLabel', { group: 'item1' }, 'text', '_$!<HomePage>!$_'],
xAbShowAs: ['xAbShowAs', {}, 'text', 'COMPANY'],
rev: ['rev', {}, 'text', '2019-02-28T21:07:48Z'],
},
{
version: ['version', {}, 'text', '3.0'],
prodid: ['prodid', {}, 'text', '-//Apple Inc.//Mac OS X 10.14//EN'],
n: ['n', {}, 'text', ['Howenstedt', 'Jan', '', '', '']],
fn: ['fn', {}, 'text', 'Jan Howenstedt'],
rev: ['rev', {}, 'text', '2019-02-28T21:07:48Z'],
},
{
version: ['version', {}, 'text', '3.0'],
prodid: ['prodid', {}, 'text', '-//Apple Inc.//iOS 12.1.4//EN'],
n: ['n', {}, 'text', ['Vesoc', 'Mark', '', '', '']],
fn: ['fn', {}, 'text', 'Mark Vesoc'],
tel: [
['tel', { type: ['cell', 'voice', 'pref'] }, 'text', '+49 173 5555555'],
['tel', { type: ['work', 'voice'] }, 'text', '0241 8943850'],
],
bday: ['bday', { value: 'date' }, 'date', '1991-06-26'],
xSocialprofile: [
'xSocialprofile',
{ type: 'whatsapp', xBundleidentifiers: 'net.whatsapp.WhatsApp' },
'text',
'x-a',
],
pple: ['pple', {}, 'text', '%E2%80%AD+49%20173%205555555%E2%80%AC'],
rev: ['rev', {}, 'text', '2019-04-23T11:57:59Z'],
},
{
version: ['version', {}, 'text', '3.0'],
n: ['n', {}, 'text', ['Chapoupis', 'Nik', '', '', '']],
fn: ['fn', {}, 'text', 'Nik Chapoupis'],
org: ['org', {}, 'text', 'Ordersome;'],
bday: ['bday', { value: 'date' }, 'date', '1990-03-14'],
title: ['title', {}, 'text', 'CEO'],
note: ['note', {}, 'text', 'Looks for Designers'],
adr: [
[
'adr',
{ group: 'item1', type: ['home', 'pref'] },
'text',
['', '', 'Engelbertstraße 33', 'Aachen', '', '52078', 'Germany'],
],
[
'adr',
{ group: 'item2', type: 'work' },
'text',
['', '', 'Jülicherstraße\\n72a', 'Aachen', '', '52070', 'Germany'],
],
],
xAbadr: [
['xAbadr', { group: 'item1' }, 'text', 'de'],
['xAbadr', { group: 'item2' }, 'text', 'de'],
],
tel: [
['tel', { type: ['cell', 'pref', 'voice'] }, 'text', '+49 1578 5555555'],
['tel', { type: ['work', 'voice'] }, 'text', '0241 8943850'],
],
url: [
'url',
{ group: 'item3', type: 'pref' },
'text',
'http://ordersome.de',
],
xAblabel: [
['xAblabel', { group: 'item3' }, 'text', '_$!<HomePage>!$_'],
['xAblabel', { group: 'item4' }, 'text', '_$!<Anniversary>!$_'],
],
impp: [
'impp',
{ xServiceType: 'Facebook', type: ['facebook', 'pref'] },
'text',
'xmpp:Hello%20World',
],
email: [
[
'email',
{ type: ['home', 'pref', 'internet'] },
'text',
'nikolas@gmail.com',
],
[
'email',
{ type: ['work', 'internet'] },
'text',
'nikolaschapoupis@gmail.com',
],
],
xAbdate: [
'xAbdate',
{ group: 'item4', type: 'pref' },
'text',
'2017-10-11',
],
xSocialprofile: [
'xSocialprofile',
{ xUser: 'twitter.com/nikolas_chap', type: 'twitter' },
'text',
'http://twitter',
],
'com/nikolasChap': [
'com/nikolasChap',
{ group: 'com/twitter' },
'text',
null,
],
prodid: [
'prodid',
{},
'text',
'-//Apple Inc.//iCloud Web Address Book 1906B32//EN',
],
rev: ['rev', {}, 'text', '2019-04-23T04:58:28Z'],
},
];
export const parsedVCardData = [
{
city: '',
company: '',
contactDetails: 'Cell phone: +555-5555-55',
conversationTopics: '',
firstName: 'Alex',
lastName: 'Mueller',
position: '',
},
{
city: '',
company: '',
contactDetails: '',
conversationTopics: '',
firstName: 'Jan',
lastName: 'Howenstedt',
position: '',
},
{
city: '',
company: '',
contactDetails: 'Birthday: 1991-06-26 Cell phone: +49 173 5555555',
conversationTopics: '',
firstName: 'Mark',
lastName: 'Vesoc',
position: '',
},
{
city: 'Aachen',
company: 'Ordersome',
contactDetails:
'Birthday: 1990-03-14 Cell phone: +49 1578 5555555 Email: nikolas@gmail.com',
conversationTopics: 'Looks for Designers',
firstName: 'Nik',
lastName: 'Chapoupis',
position: 'CEO',
},
];
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T22:32:01.967",
"Id": "423442",
"Score": "0",
"body": "https://www.rubypigeon.com/posts/avoid-mutation-functional-style-in-ruby/"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T08:25:37.820",
"Id": "219085",
"Score": "1",
"Tags": [
"javascript",
"functional-programming",
"ramda.js"
],
"Title": "Transform vcards into contacts using functional programming in JavaScript"
} | 219085 |
<p>For learning purposes, I've written an iterative version of a recursive algorithm for generating the set of permutations for a given set of unique integers. </p>
<p>Can I make any improvements to increase readability and performance? </p>
<p>I've also read in various sources that when transforming a recursive algorithm into an iterative one, the stack data-structure is often used to 'substitute' the call stack used in the recursive case. I'm not using a <code>std::stack</code> here but could I have used one to simplify my implementation? </p>
<pre><code>using std::vector;
vector<vector<int>> permutations(vector<int> integers) {
vector<vector<int>> curr_perms;
if (integers.size() <= 1) {
curr_perms.push_back(integers);
return curr_perms;
}
size_t sz = integers.size();
vector<vector<int>> next_perms;
// initialise with the one permutation of the last single element
vector<int> t = { integers[sz - 1] };
curr_perms.emplace_back(t);
// backwards iterating a sequence of at least two elements
for (int i = sz - 2; i >= 0; --i) {
auto first = integers[i];
for (const auto &s : curr_perms) {
for (auto j = 0U; j < s.size() + 1; ++j) {
vector<int> p(s.begin(), s.end()); // make a copy
p.insert(p.begin() + j, first); // shuffle in 'first' element
next_perms.push_back(std::move(p)); // and add this as a new permutation
}
}
// permutations found in this iteration are the input for the next
std::swap(next_perms, curr_perms); // <-- is this needlessly copying all the elements?
next_perms.clear();
}
return curr_perms;
}
</code></pre>
| [] | [
{
"body": "<p>As often, the recursive algorithm is readable and beautiful, but not very efficient: stack consumption can be overwhelming, memory allocations are plentiful, and you're forced to compute the whole set of permutations at once.</p>\n\n<p>When you mechanically translate the recursive algorithm into its iterative form, you often lose most of its beauty and readability, without gaining much on the front of performance: you just emulate with a data structure what the compiler would have done. It might be useful sometimes but you can generally assume that the compiler will do a better job than yourself.</p>\n\n<p>Hence I would recommend looking into two alternative approaches:</p>\n\n<ul>\n<li><p>the first is to do it the standard library way, and provide a <code>std::next_permutation</code> function which return the next permutation in the lexicographical order (see for instance my answer to <a href=\"https://codereview.stackexchange.com/questions/217939/compute-all-the-permutations-for-a-given-vector-of-integers\">this question</a>). It can be improved upon though, with <a href=\"https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm\" rel=\"nofollow noreferrer\">the SJT algorithm</a>, and that would be an exercise of choice;</p></li>\n<li><p>the second is to keep the general, incremental reasoning of the recursive algorithm, but use the additional knowledge you get in the iterative form: indeed, on the contrary to the recursive form, you know upfront how many permutations you'll return in the end, and thus can avoid all but one allocation.</p></li>\n</ul>\n\n<p>For instance:</p>\n\n<pre><code>#include <vector>\n\nstd::vector<std::vector<int>> permutations_set(const std::vector<int>& set) {\n\n if (set.empty()) return {};\n\n auto current = std::begin(set);\n\n // the unique memory allocation\n std::vector<std::vector<int>> permutations(factorial(set.size()), {*current});\n\n for (++current; current != std::end(set); ++current) {\n std::size_t offset = 0; // offset plays the central role here; you could say it replaces the stack\n for (auto& permutation : permutations) {\n const auto initial_size = permutation.size();\n permutation.insert(std::next(std::begin(permutation), offset), *current); \n if (offset++ == initial_size) offset = 0;\n }\n }\n\n return permutations; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T01:15:15.270",
"Id": "423446",
"Score": "0",
"body": "When you say 'you just emulate with a data structure what the compiler would have done', does that mean that you don't have to care about stack overflows anymore from deeply recursive call stacks when using a modern compiler? Can a compiler always transform a recursive algorithm into iterative form? That sounds pretty advanced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T05:51:31.360",
"Id": "423457",
"Score": "0",
"body": "@yorztif: you can configure recursion depth on compilers, and it is limited only by memory availability. But what I meant is that the compiler build an execution stack to execute the program. Execution contexts are then pushed / popped. That's what you also do when translating from recursive to iterative with a stack. Some compilers are able to translate some forms of recursion ( tail recursion) but I'm not sure C++ compilers do it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:00:04.057",
"Id": "219173",
"ParentId": "219089",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T09:05:50.637",
"Id": "219089",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"c++11",
"reinventing-the-wheel",
"combinatorics"
],
"Title": "Iterative version of a permutations algorithm"
} | 219089 |
<p>I'm a newcomer to Java (I primarily do C# ) and I have to say that they have made I/O handling much more difficult than it should have been. I am accustomed to the scenario where when I need keyboard input in a class of my application I simply call <code>Console.Readline()</code> and does the job. In Java, I must create a Scanner object in order to perform these operations and when input is needed in methods of different classes things get more complicated. So what I thought was creating an Input class where all keyboard inputs are handled there. </p>
<pre><code>import java.time.* ;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class Input
{
private static Scanner scan = new Scanner(System.in);
public static void UseEnterAsDelimiter()
{
scan.useDelimiter(System.getProperty("line.separator"));
}
public static int IntInRange(int min , int max, String InvalidMsg )
{
int value;
while(true)
{
while (!scan.hasNextInt())
{
System.out.println("Expected an Integer. Please type again.");
scan.next();
}
value = scan.nextInt();
if( value >= min && value <= max)
return value;
else
{
System.out.println(InvalidMsg);
}
}
}
public static int Int()
{
int value;
while (true)
{
while (!scan.hasNextInt())
{
System.out.println("Expected an Integer. Please type again.");
scan.next();
}
value = scan.nextInt();
return value;
}
}
public static String String()
{
return scan.next();
}
public static String StringNoEmpty()
{
String value;
while(true)
{
value = scan.next();
if ( !value.isEmpty())
return value;
else
System.out.println("Input cannot be blank. Please type again.");
}
}
public static LocalDate Date()
{
LocalDate value;
while(true)
{
try
{
String input = scan.next();
if( input.isEmpty())
System.out.println("Field cannot be empty.");
else
{
value = LocalDate.parse(input);
return value;
}
}
catch(DateTimeParseException e)
{
System.out.println("Date was not given in a correct format , please type it again.");
}
}
}
public static LocalTime Time()
{
LocalTime value;
while(true)
{
try
{
String input = scan.next();
if( input.isEmpty())
System.out.println("Field cannot be empty.");
else
{
value = LocalTime.parse(input);
return value;
}
}
catch(DateTimeParseException e)
{
System.out.println("Time was not given in a correct format , please type it again.");
}
}
}
public static void CloseScanner()
{
scan.close();
}
}
</code></pre>
<p>My question is if it's considered good practice to use a static Scanner and if it is what can I do to make this class better. I'm looking for improvement here, this class does what's expected but I don't know if it's the correct way.</p>
| [] | [
{
"body": "<p>Since it always operates on System.in, which is static, it's fine to have a static class. You could name it \"SystemInput\" to make the purpose clearer and make the class final with private constructor to make a point that it's not to be instantiated.</p>\n\n<p>Your naming convention is uncommon to Java. Methods should start ith lower case letter.</p>\n\n<p>The class is essentially just a big chunk of utility methods. To maintain the single responsibility principle, you could split them into their own classes that operate on a given Scanner. Maybe implement a common typed interface... You're just doing procedural programming with a global variable now.</p>\n\n<p>Using the wildcard in imports is a bit bad practise. It becomes hard to tell what you actually need. It's also a sign that your class might have too many responsibilities if you have to resort to \"just gimme everything\".</p>\n\n<p>What kind of projects do you usually do? (Ok, this is purely anecdotal, but) I've been programming Java for about 20 years and while I've parsed command line parameters quite often and read data piped from other commands I don't remember ever reading input from console interactively after leaving the university \"Introduction to Java\" course.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:09:36.580",
"Id": "423177",
"Score": "1",
"body": "Well I'm a 1st year undergraduate. I say that I'm primarily doing C# cause I've been in touch with it since I was 13 and during these 6 years I've advanced in a point where I'm very fluent with it. But let's go to your answer : I'm aware of the single responsibility principle, but I don't understand why I'm violating it. All class methods are basically used for user input. I'm assuming that you mean that the class handles many Data Types (int, String etc.). I would do the interfaces if was writing for enterprise, wouldn't be difficult but we haven't even done it in class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:28:54.750",
"Id": "423205",
"Score": "0",
"body": "Regarding the imports, if you're using eclipse as your IDE, you can press ctrl-shift-O to organize imports which will remove unused imports and only show the actual used ones."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:23:36.933",
"Id": "219097",
"ParentId": "219090",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>My question is if it's considered good practice to use a static\n Scanner and if it is what can I do to make this class better. I'm\n looking for improvement here, this class does what's expected but I\n don't know if it's the correct way.</p>\n</blockquote>\n\n<p>This depends on what you are building. This kind of static design might be ok for smaller utilities. For anything bigger it will come around to kick you sooner or later.</p>\n\n<p>Your class is not really a class but a collection of utilities. Which again might be ok. Problem is with the <code>Scanner</code> which in your case is globally shared. Everybody who uses your class gets coupled to this global state.</p>\n\n<p>Consider the below code:</p>\n\n<pre><code>public class BMI {\n public double value() {\n double weightInKg = (double) Input.Int();\n double heightInM = (double) Input.Int();\n Input.CloseScanner();\n return weightInKg / (heightInM * heightInM);\n }\n}\n</code></pre>\n\n<p>Since this uses globally shared state I just broke your code for all clients. Every piece of code depending on <code>Input</code> class will fail because I closed the scanner.</p>\n\n<p>If I would now tried to write a unit test I would not be able to. Not without some dirty hacks. This code is coupled to Input and this dependency cannot be broken.</p>\n\n<p>This is where Software Development principles such as <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> come to into play.</p>\n\n<p><strong>Single Responsibility Principle:</strong></p>\n\n<p>Class should have a single reason to change. Your input class is responsible for everything regarding reading from console. That is a lot of reasons for change. From changing of date format to adding a new operations. Every such need causes change in this class and has potential to break something.</p>\n\n<p><strong>Open Closed Principle:</strong></p>\n\n<p>You want to be able to extend you program without touching existing code. If I wanted to read double for example I would have to change Input class. I should be able to just create snother class</p>\n\n<p><strong>Liskov Substitution Principle:</strong></p>\n\n<p>There is no substitution possible for Input. You cannot create other implementations of static utilities.</p>\n\n<p><strong>Interface Segregation Principle:</strong></p>\n\n<p>You want interfaces of your objects to be small so that object do not have to depend on things they do not use. Any class accessing <code>Input</code> has access to everything even though it just needs to read integers.</p>\n\n<p><strong>Dependency Inversion Principle:</strong></p>\n\n<p>Dependencies of your objects should be configurable. So that you can achieve easier reuse and testability. You cannot invert static dependency. It is there and you can't do anything about it.</p>\n\n<p>There are many approaches how to make your code SOLID. Here is one example again with BMI class to show how client would use the code:</p>\n\n<pre><code>public class BMI {\n\n private final DoubleProvider weightInKg;\n private final DoubleProvider heightInM;\n\n public BMI(DoubleProvider weightInKg, DoubleProvider heightInM) {\n this.weightInKg = weightInKg;\n this.heightInM = heightInM;\n }\n\n public double value() {\n final double weight = weightInKg.doubleValue();\n final double height = heightInM.doubleValue();\n return weight / (height * height);\n }\n}\n\npublic class Input implements DoubleProvider, IntProvider {\n\n private final Scanner scanner;\n\n public Input(Scanner scanner) {\n this.scanner = scanner;\n }\n\n @Override\n public double doubleValue() {\n ...\n }\n\n @Override\n public int intValue() {\n ...\n }\n\n ...\n\n}\n</code></pre>\n\n<p>Most notable change are the dependencies. My BMI class no longer depends on details of Input. It can read from console, file, network... anything as long as it implements DoubleProvider interface.</p>\n\n<p>Nothing prevents me from testing both BMI and Input. Dependencies are configurable via constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T18:00:34.427",
"Id": "423224",
"Score": "0",
"body": "Your example made me understand a lot of things on how Java works, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T08:10:08.563",
"Id": "423309",
"Score": "0",
"body": "@NickDelta Almost nothing what Januson wrote has to do with Java, it all applies to C# (or almost any other language) in the same way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T08:47:11.070",
"Id": "423311",
"Score": "1",
"body": "@RoToRa Yes, I'm aware of that,I was just convinced that I had to close the Scanner but eventually if I do that anywhere in the project, all other Scanners will fail after that. That's why I said it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:29:55.290",
"Id": "219121",
"ParentId": "219090",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T09:06:07.987",
"Id": "219090",
"Score": "1",
"Tags": [
"java",
"beginner",
"validation",
"io"
],
"Title": "Input class in Java"
} | 219090 |
<p>I'm creating a <em>debug-view</em> for my <a href="https://codereview.stackexchange.com/questions/208332/adjusting-business-logic-conveniently-through-json-and-expression-trees">expression-trees</a>. They <em>record</em> each operation automatically in a tree that I am transforming into <code>string</code> so that I can see the exact evaluation of expressions.</p>
<hr>
<h3>Tree(Node)</h3>
<p>This tree is represented by the <code>TreeNode</code>. It stores the <code>Value</code> of the current node and its children.</p>
<pre><code>[PublicAPI]
[DebuggerDisplay(DebuggerDisplayString.DefaultNoQuotes)]
public class TreeNode<T> : List<TreeNode<T>>
{
public TreeNode(T value, IEnumerable<TreeNode<T>> children)
: base(children)
{
Value = value;
}
public TreeNode(T value)
: this(value, Enumerable.Empty<TreeNode<T>>()) { }
private string DebuggerDisplay => this.ToDebuggerDisplayString(b =>
{
b.DisplayValue(x => x.Value);
b.DisplayValue(x => x.Count);
});
[NotNull]
public static TreeNode<T> Empty => new TreeNode<T>(default);
[CanBeNull]
public T Value { get; set; }
public static implicit operator T(TreeNode<T> node) => node.Value;
public static implicit operator TreeNode<T>(T value) => new TreeNode<T>(value);
}
public static class TreeNode
{
public static TreeNode<T> Create<T>(T value) => new TreeNode<T>(value);
}
public static class TreeNodeExtensions
{
public static (TreeNode<T> Parent, TreeNode<T> Child) Append<T>(this TreeNode<T> parent, T value)
{
var child = new TreeNode<T>(value);
parent.Add(child);
return (parent, child);
}
}
</code></pre>
<h3>Test data</h3>
<p>This <em>node</em> when created like this:</p>
<pre><code>var root = TreeNode.Create((Person)("John", "Doe"));
root.Append(("Sam", "Doe")).Child.Append(("Tom", "Doe")).Parent.Append(("Juliet", "Doe"));
root.Append(("Vanessa", "Doe"));
</code></pre>
<p>based on this test model:</p>
<blockquote>
<pre><code>[DebuggerDisplay(DebuggerDisplayString.DefaultNoQuotes)]
public class Person
{
private string DebuggerDisplay => this.ToDebuggerDisplayString(b =>
{
b.DisplayValue(x => x.FirstName);
});
public string FirstName { get; set; }
public string LastName { get; set; }
private object ToDump() => $"{LastName}, {FirstName}";
public static implicit operator Person((string FirstName, string LastName) p) => new Person
{
FirstName = p.FirstName,
LastName = p.LastName
};
}
</code></pre>
</blockquote>
<h3>Usage example</h3>
<p>needs to be renderd as <em>something</em>. This <em>something</em> is currently a <code>string</code>:</p>
<pre><code>var renderer = new StringTreeNodeRenderer();
renderer.Render(root, (p, d) => $"ln: {p.LastName}{Environment.NewLine}fn: {p.FirstName} ({d})").Dump("Service");
</code></pre>
<blockquote>
<pre><code>ln: Doe
fn: John (0)
ln: Doe
fn: Sam (1)
ln: Doe
fn: Tom (2)
ln: Doe
fn: Juliet (2)
ln: Doe
fn: Vanessa (1)
</code></pre>
</blockquote>
<h3>Renderer</h3>
<p>The utility that does that is implemented recursively. For DI purposes I use an interface here and in case I should have other renderers later (like json or html). The <em>default</em> <code>StringTreeNodeRenderer</code> calls the <code>RenderValueCallback</code> for each value, indents it appropriately and then turns everything into a single <code>string</code>.</p>
<pre><code>public delegate string RenderValueCallback<T>(T value, int depth);
public interface ITreeNodeRenderer<TResult>
{
TResult Render<TValue>(TreeNode<TValue> root, RenderValueCallback<TValue> renderValue);
}
public abstract class TreeNodeRenderer<TResult> : ITreeNodeRenderer<TResult>
{
public abstract TResult Render<TValue>(TreeNode<TValue> root, RenderValueCallback<TValue> renderValue);
}
public class StringTreeNodeRenderer : ITreeNodeRenderer<string>
{
public int IndentWidth { get; set; } = 3;
public string Render<TValue>(TreeNode<TValue> root, RenderValueCallback<TValue> renderValue)
{
var nodeViews = Render(root, 0, renderValue);
var indentedNodeViews = nodeViews.Select(nv => nv.Value.IndentLines(IndentWidth * nv.Depth));
return string.Join(Environment.NewLine, indentedNodeViews);
}
private IEnumerable<TreeNodeView> Render<T>(TreeNode<T> root, int depth, RenderValueCallback<T> renderValue)
{
yield return new TreeNodeView
{
Value = renderValue(root, depth),
Depth = depth
};
var views =
from node in root
from view in Render(node, depth + 1, renderValue)
select view;
foreach (var view in views)
{
yield return view;
}
}
}
</code></pre>
<h3>Helpers</h3>
<p>The renderer is using two helper extensions. One for indenting all lines in a <code>string</code> an one for trimming a <code>StringBuilder</code>.</p>
<pre><code>public static class StringExtensions
{
public static string IndentLines(this string value, int indentWidth, char indentCharacter = ' ', Encoding encoding = default)
{
var output = new StringBuilder();
using (var valueStream = new MemoryStream((encoding ?? Encoding.UTF8).GetBytes(value)))
using (var valueReader = new StreamReader(valueStream))
{
while (valueReader.ReadLine() is var line && line != null)
{
output
.Append(new string(indentCharacter, indentWidth))
.AppendLine(line);
}
}
return
output
.TrimEnd(Environment.NewLine)
.ToString();
}
}
public static class StringBuilderExtensions
{
public static StringBuilder TrimEnd(this StringBuilder stringBuilder, string value)
{
var startIndex = stringBuilder.Length - value.Length;
for (int i = startIndex, j = 0; j < value.Length; i++, j++)
{
if (!stringBuilder[i].Equals(value[j]))
{
return stringBuilder;
}
}
return
stringBuilder
.Remove(startIndex, value.Length)
.TrimEnd(value);
}
}
</code></pre>
<p><em>(The debugger utilities I use here are part of my <a href="https://github.com/he-dev/reusable/tree/dev/Reusable.Core/src/Diagnostics" rel="noreferrer">Diagnostics</a> tools.)</em></p>
<hr>
<h3>Questions</h3>
<p>My main questions are: </p>
<ul>
<li>Is everything properly separated and encapsulated?</li>
<li>Is it extendable?</li>
<li>Is it easy to use?</li>
</ul>
| [] | [
{
"body": "<p>I would change the following things to your API:</p>\n\n<ul>\n<li>let tree items know their parent and children -> easier navigation</li>\n<li>encapsulate the children -> better integrity</li>\n</ul>\n\n<p>As for the rendering, it can be done more lightweight.</p>\n\n<p>sample code:</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic class Program\n{\n public static void Main()\n {\n var root = TreeNode.Create(new Person(\"John\", \"Doe\"))\n .Add(new Person(\"Sam\", \"Doe\"))\n .Add(new Person(\"Tom\", \"Doe\"))\n .Parent.Add(new Person(\"Juliet\", \"Doe\"))\n .Root.Add(new Person(\"Vanessa\", \"Doe\"))\n .Root;\n\n var rendered = Render(root, (p, d) => \n string.Format(\"ln: {0}{3}fn: {1} ({2})\", p.LastName, p.FirstName, d, Environment.NewLine));\n\n Console.Write(rendered);\n }\n\n private static string Render<T>(TreeNode<T> tree, Func<T, int, string> layout) \n {\n var builder = new StringBuilder();\n var indent = new Stack<string>();\n var depth = 0;\n\n RenderTree(builder, tree, depth, layout, indent);\n\n return builder.ToString();\n }\n\n private static void RenderTree<T>(StringBuilder builder, TreeNode<T> tree, int depth, Func<T, int, string> layout, Stack<string> indent) {\n\n Render(builder, tree.Value, depth, layout, indent);\n\n indent.Push(\"\\t\");\n depth++;\n\n foreach (var child in tree.Children) {\n RenderTree(builder, child, depth, layout, indent);\n }\n\n indent.Pop();\n }\n\n private static void Render<T>(StringBuilder builder, T element, int depth, Func<T, int, string> layout, Stack<string> indent) {\n\n var textLines = layout(element, depth).Split(new[] {Environment.NewLine }, StringSplitOptions.None);\n var textIndent = string.Join(string.Empty, indent);\n\n foreach (var textLine in textLines) {\n builder.AppendLine(string.Format(\"{0}{1}\", textIndent, textLine));\n }\n }\n\n public class TreeNode<T>\n {\n private List<TreeNode<T>> children = new List<TreeNode<T>>();\n\n public TreeNode(T value)\n {\n Value = value;\n }\n\n public static TreeNode<T> Empty { get { return new TreeNode<T>(default(T)); }}\n\n public T Value { get; set; }\n\n public IEnumerable<TreeNode<T>> Children { get { return children.ToArray(); }}\n\n public TreeNode<T> Parent { get; private set; }\n\n public TreeNode<T> Root { get { return Parent == null ? this : Parent.Root; }}\n\n public static implicit operator T(TreeNode<T> node) { return node.Value; }\n\n public static implicit operator TreeNode<T>(T value) { return new TreeNode<T>(value); }\n\n public TreeNode<T> Add(TreeNode<T> child) {\n // TODO check null, check family (is self, ancestor, descendant, or child of other parent) ..\n children.Add(child);\n child.Parent = this;\n return child;\n }\n\n public TreeNode<T> Remove(TreeNode<T> child) {\n // TODO check null, check family (is child) ..\n if (children.Contains(child)) {\n children.Remove(child);\n child.Parent = null;\n }\n return child;\n }\n }\n\n public static class TreeNode\n {\n public static TreeNode<T> Create<T>(T value) { return new TreeNode<T>(value); }\n }\n\n public class Person\n {\n public string FirstName { get; set; }\n\n public string LastName { get; set; }\n\n public Person(string firstName, string lastName) {\n FirstName = firstName;\n LastName = lastName;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T09:14:30.783",
"Id": "425950",
"Score": "0",
"body": "These are some interesting ideas! Cool :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T09:18:45.393",
"Id": "425951",
"Score": "1",
"body": "Hi man, glad you like the ideas. You can build an even better API by creating generic tree walkers. Your renderer could use a tree walker in depth-first (https://en.wikipedia.org/wiki/Depth-first_search) order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T09:23:47.570",
"Id": "425952",
"Score": "1",
"body": "I knew I might be reinventing the wheel. Implementing a well known method sounds reasonable. I'll give it a try."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T09:10:32.673",
"Id": "220454",
"ParentId": "219092",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220454",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T09:46:39.240",
"Id": "219092",
"Score": "6",
"Tags": [
"c#",
"strings",
"recursion",
"tree"
],
"Title": "Rendering tree of nodes as string"
} | 219092 |
<p>First of all, I know there is huge amount of information about KMP on the internet but many examples are just the code without any explanation. So I've decided to implement it on my own.</p>
<p>Secondly, I am going to use this algorithm to search for a pattern in a numerical string.</p>
<p>I wrapped all the stuff in class <code>KMP</code>.</p>
<h1>CODE</h1>
<h2>KMP.h</h2>
<pre><code>#ifndef KMP_H
#define KMP_H
#include <cstddef>
#include <vector>
class KMP
{
protected :
std::vector< size_t > found_positions;
public :
KMP() :
found_positions( 0 )
{ }
void build_failure_vector( const std::vector< float >& pattern,
std::vector< int >& failure_vector );
void search_for_pattern( const std::vector< float >& pattern,
const std::vector< float >& sample );
typedef typename std::vector< size_t >::const_iterator position_iterator;
inline position_iterator cbegin() const noexcept { return found_positions.cbegin(); }
inline position_iterator cend() const noexcept { return found_positions.cend(); }
};
#endif
</code></pre>
<h2>KMP.cpp</h2>
<pre><code>#include "KMP.h"
void KMP::build_failure_vector( const std::vector< float >& pattern,
std::vector< int >& failure_vector )
{
//extra space for the case when all occurencies are required
failure_vector.resize( pattern.size() + 1 );
//set -1 as an indicator of the beginning of a pattern
failure_vector[ 0 ] = -1;
//in the case of a mismatch we don't shift text index back
//but instead we check if we could proceed from a proper suffix of the pattern
//it is the pattern index which indicates the position of a potential match
int continue_from;
for( size_t i = 1; i < failure_vector.size(); i++ )
{
//if a mismatch was at index i
//we check if the beginning of a pattern has been reached or
//the previous pattern character (at i-1) matches
//some failure character
//start from the failure at the previous pattern index
continue_from = failure_vector[ i-1 ];
while( (continue_from >= 0) &&
(pattern[ continue_from ] != pattern[ i-1 ] ) )
{
continue_from = failure_vector[ continue_from ];
}
//if in the above while loop we found that
//pattern[ i-1 ] == pattern[ continue_from ] for some continue_from index
//then we should check if the current main text character mathes pattern[ continue_from + 1 ]
failure_vector[ i ] = continue_from + 1;
}
}
void KMP::search_for_pattern( const std::vector< float >& pattern,
const std::vector< float >& sample )
{
//prepare failure function
std::vector< int > failure_vector;
build_failure_vector( pattern, failure_vector );
//position in the main text
size_t sample_pos = 0;
//must be of type int because may be equal to -1
int pattern_pos = 0;
while( sample_pos < sample.size() )
{
//check next character in the main text
//only if the next potential match is the beginning of the pattern
//or there is a match
if( (pattern_pos < 0) ||
(sample[ sample_pos ] == pattern[ pattern_pos ]) )
{
sample_pos++;
//if pattern_pos was -1 then it becomes 0
//i.e. we start from the beginning
pattern_pos++;
if( pattern_pos == pattern.size() )
{
//complete match occured
found_positions.push_back( sample_pos - pattern_pos );
//the last position in failure_vector
//says what we should continue from after complete match
pattern_pos = failure_vector[ pattern_pos ];
}
}
//if there was a mismatch
else
{
//what next character of the pattern is a potential match
pattern_pos = failure_vector[ pattern_pos ];
}
}
}
</code></pre>
<h1>Usage</h1>
<p>Usage is straightforward. For example, </p>
<blockquote>
<p>Sample vector: [ 3, 1, 3, 1, 3, 2, 0, 1, 3, 1, 3, ]</p>
<p>Pattern vector: [ 3, 1, 3, ]</p>
<p>Failure vector: [ -1, 0, 0, 1, ]</p>
<p>Pattern found positions vector: [ 0, 2, 8, ]</p>
</blockquote>
| [] | [
{
"body": "<p><strong>Let the Compiler do the Optimization</strong><br>\nC++ compilers have become very good at optimization, especially when they are compiled -O3. The compiler will handle optimizations such as inlining functions automatically, there is no need for the <code>inline</code> specification preceding functions in header files. See this <a href=\"https://stackoverflow.com/questions/1759300/when-should-i-write-the-keyword-inline-for-a-function-method\">stack overflow question</a>.</p>\n\n<p>It isn't apparent that the functions <code>cbegin()</code> and <code>cend()</code> are ever used in the code.</p>\n\n<p><strong>Including Unnecessary Header Files</strong><br>\nThe code compiles properly without including <code>cstddef</code>. Including unnecessary header files may introduce symbol collisions, it also slows down compile times because the code in the include file needs to compiled as well.</p>\n\n<p><strong>Over Commenting</strong><br>\nIt is obvious that commenting the solution is one of the main goals, and that is a good goal, however, there is such a thing as over commenting code. As code ages there will be changes to it to fix bugs or for optimization and comments require extra work to make sure they continue to represent the code. It is best to use variable and function names that are self documenting to make the code clearer. If the algorithm need commenting, it might be better to put a block comment at the top of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T04:22:35.170",
"Id": "423286",
"Score": "0",
"body": "Oh, `cbegin()` and `cend()` are used in the usage stage. I just omitted `main()`. They are for iterating over found positions. BTW. What's wrong with inlining functions in header files? I am using `YouCompleteMe` plugin and without `cstddef` header it complained that `size_t` was unknown type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:16:16.087",
"Id": "423324",
"Score": "0",
"body": "@LRDPRDX Since `main()` wasn't included and no link was provided to all source code I could only review what was here, therefore the cstddef header is not necessary nor is cbegin and cend. I've added a link to stack overflow about why you shouldn't use the inline keyword any more. If you look at my first question on code review you'll find that I did use it as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T01:12:03.100",
"Id": "423445",
"Score": "0",
"body": "@LRDPRDX & pacmaninbw: Functions defined in the class are automatically inline. This has little to do with optimization."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:11:55.037",
"Id": "219104",
"ParentId": "219095",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T10:45:17.980",
"Id": "219095",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"search"
],
"Title": "Knuth-Morris-Pratt algorithm in C++"
} | 219095 |
<p>Just implemented this <a href="https://en.wikipedia.org/wiki/Kalman_filter" rel="nofollow noreferrer">Kalman Filter</a> in Python + Numpy keeping the Wikipedia notation </p>
<p>It's a pretty straightforward implementation of the original algorithm, the goals were</p>
<ul>
<li><p>develop skills related to <strong>implementing a scientific paper</strong> </p></li>
<li><p>keep it readable (so I have used private methods for intermediate results) </p></li>
</ul>
<p>It includes a simple test case </p>
<pre class="lang-py prettyprint-override"><code>
import numpy as np
"""
Kalman Filter in plain Python + Numpy
Filter State
- x = Updated State
- P = Updated State Uncertainty
- x_pred = Predicted State
- P_pred = Predicted State Uncertainty
Models
- F = Prediction Model
- H = Observation Model (Maps from State Space to Observation Space)
- B = Evolved Forcing Term
- Q = Evolution Noise
- R = Observation Noise
"""
class KF:
def __init__(self, x, P, F, B, H, Q, R):
# Init
self.x = x
self.x_pred = x
# Initial State Uncertainty
self.P = P
self.P_pred = P
# Prediction Model
self.F = F
# Observation Model
self.H = H
# Process Noise
self.Q = Q
# Observation Noise
self.R = R
def predict(self, u):
self.x_pred = F.dot(x) + B.dot(u)
self.P_pred = F.dot(P.dot(np.transpose(F))) + Q
def __innovation(self, y):
return y - self.H.dot(self.x_pred)
def __S(self):
return self.R + self.H.dot(self.P_pred.dot(np.transpose(self.H)))
def __K(self):
return self.P_pred.dot(np.transpose(self.H).dot(np.linalg.inv(self.__S())))
def __I(self, A):
if(A.shape[0] != A.shape[1]):
raise ValueError("[Identity] Not Square")
return np.identity(A.shape[0])
def update(self, y):
self.x = self.x_pred + self.__K().dot(self.__innovation(y))
temp = self.__K().dot(self.H)
self.P = (self.__I(temp) - temp).dot(self.P_pred.dot(np.transpose(self.__I(temp) - temp))) + self.__K().dot(self.R.dot(np.transpose(self.__K())))
def to_str(self):
return "x \n" + np.array2string(self.x) + "\n P \n" + np.array2string(self.P) + "\n x_pred \n" + np.array2string(self.x_pred) + "\n P_pred \n" + np.array2string(self.P_pred)
F = np.array([[1,0], [0,1]])
P = np.array([[1,0], [0,1]])
B = np.array([[1,0], [0,1]])
H = np.array([[1,0], [0,1]])
Q = np.array([[1,0], [0,1]])
R = np.array([[1,0], [0,1]])
x = np.array([[1], [0]])
y = np.array([[3], [5]])
u = np.array([[0], [0]])
kf = KF(x, P, F, B, H, Q, R)
kf.predict(u)
kf.update(y)
print("State = " + kf.to_str())
</code></pre>
<p>Output </p>
<pre><code>State = x
[[2.33333333]
[6.66666667]]
P
[[0.66666667 0. ]
[0. 0.66666667]]
x_pred
[[1.]
[0.]]
P_pred
[[2. 0.]
[0. 2.]]
</code></pre>
<p>Validation with <a href="https://filterpy.readthedocs.io/en/latest/" rel="nofollow noreferrer">Filterpy</a> as suggested by @AlexV </p>
<pre class="lang-py prettyprint-override"><code>from filterpy.kalman import KalmanFilter
my_filter = KalmanFilter(dim_x=2, dim_z=2)
my_filter.x = x # initial state (location and velocity)
my_filter.F = F
my_filter.H = H # Measurement function
my_filter.P = P # covariance matrix
my_filter.R = R # state uncertainty
my_filter.Q = Q
my_filter.predict()
my_filter.update(y)
print(np.array2string(my_filter.x))
</code></pre>
<p>Output </p>
<pre><code>[[2.33333333]
[6.66666667]]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:07:41.603",
"Id": "423200",
"Score": "1",
"body": "I assume you did this for the learning experience, but I would nevertheless like to bring [filterpy](https://pypi.org/project/filterpy/) to your attention. You could use it as reference to test against, but that depends on how much you trust the other implementation ;-)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:28:31.313",
"Id": "219098",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "N-D Kalman Filter in Python + Numpy"
} | 219098 |
<p>I came up with this code after implementing the feedback given by <a href="https://codereview.stackexchange.com/users/9357/200-success">@200_success</a>. The previous one (<a href="https://codereview.stackexchange.com/questions/219063/a-faster-way-to-compute-the-largest-prime-factor">A faster way to compute the largest prime factor</a>) tested my patience, but still failed to give the answer on time. This one is an improvement as it gives the answer without much delay.</p>
<p><strong>The question</strong> (Euler project problem #3)</p>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<p><strong>Logic:</strong></p>
<p>Keep dividing the number <code>n</code> by all the factors, starting from the smallest one. The value of <code>n</code> left in the end will be the largest prime factor of the original value of <code>n</code>.</p>
<p><strong>My code:</strong></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 problem3(n){
for(let i=2; i<n; i++){
if(n%i === 0)n = n/i;
}
return n;
}
console.log(problem3(600851475143));</code></pre>
</div>
</div>
</p>
<p><strong>Improvement:</strong></p>
<ul>
<li><p>No need to loop through all the numbers below <code>n</code></p></li>
<li><p>Remove the nested <code>for</code> loops, replacing them by only one</p></li>
<li><p>No need to check if a number is prime or not</p></li>
</ul>
<p><strong>My question:</strong> Even though it is a lot better*, but still, how can it be improved further?</p>
<p><BR>
<Sub>* Really, it's a lot than the previous one as it used to be so slow that I never saw the output for 600851475143</sub></p>
| [] | [
{
"body": "<p>It's buggy. Consider input <code>8</code>.</p>\n\n<hr>\n\n<p>Also, consider an input which is a very large prime. E.g. <code>2147483647</code>. Your current code would take about 2147483645 trial divisions. It's possible to do it with only 46340 trial divisions while keeping the code very simple. Can you see how?</p>\n\n<blockquote class=\"spoiler\">\n <p> Hint: 46340 is the square root, rounded down.</p>\n</blockquote>\n\n<p>And that's easily optimised to 23171. Can you see how?</p>\n\n<blockquote class=\"spoiler\">\n <p> Hint: only one prime is even.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:59:27.343",
"Id": "219102",
"ParentId": "219099",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:33:58.840",
"Id": "219099",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"programming-challenge",
"primes"
],
"Title": "A faster way to compute largest prime factor (Again, but a lot better)"
} | 219099 |
<p>I'm working through Paul Graham's "ANSI Common Lisp". In Chapter 6 (p105), he introduces the idea of utility functions. He points out these are core to bottom-up programming and reusability. He observes that for such utility functions in lisp and fp "it's easier to abstract out the general when you can pass the specific as a function argument".</p>
<p>The example below is given in the book (my own code for discussion will follow after this example).</p>
<blockquote>
<pre class="lang-lisp prettyprint-override"><code>
(defun most (fn lst)
"What's the el of a list with highest score, according to provided
scoring fn?"
(if (null lst)
(values nil nil)
(let* ((wins (car lst)) ; 'wins' is 'winning element'
(max (funcall fn wins))) ; 'max' is 'winning score'
(dolist (obj (cdr lst))
(let ((score (funcall fn obj)))
(when (> score max)
(setf wins obj
max score))))
(values wins max))))
</code></pre>
</blockquote>
<p>which runs as</p>
<pre class="lang-lisp prettyprint-override"><code>> (most #'length '((a b) (a b c) (a)))
(A B C) ;
3
</code></pre>
<p>So, <code>most</code> above is effectively mapping the given list using the function argument then simply applying an arithmetic max to find the winner (though it does it in a slightly more efficient way than I just described).</p>
<p>I recalled a previous example where a comparator function was passed as an argument, allowing choice between <code>></code> or <code><</code>, for example. So, I added an second function argument to the above function as below (the only change is that the function arg has been added and then the single line where I've added a new comment).</p>
<pre class="lang-lisp prettyprint-override"><code>(defun utmost (> fn lst) ; note '>' is name of a variable!
"Same as most above but with extra function argument allowing e.g. < or >"
(if (null lst)
(values nil nil)
(let* ((wins (car lst)) ; 'wins' is 'winning element'
(max (funcall fn wins))) ; 'max' is 'winning score'
(dolist (obj (cdr lst))
(let ((score (funcall fn obj)))
(when (funcall > score max) ; <- I replaced '>' with 'funcall >'
(setf wins obj
max score))))
(values wins max))))
</code></pre>
<p>which can be run as:</p>
<pre><code>> (utmost #'< #'length '((a b) (a b c) (a)))
(A) ;
1
</code></pre>
<p>Above, we passed <code><</code> as the new fn param, so 'utmost' has taken the form of returning the element of the given list of '<em>least</em>' ('length') this time.</p>
<p><strong>Questions</strong></p>
<p>Given that this is my first attempt at 'designing' a function that takes more than one function parameter, I'm wondering if I'm on the right track at all.</p>
<p>Obviously the name 'utmost' is not very good ('extremal', 'outlier'? - don't like the latter).</p>
<p>I wonder if the more you abstract out and so the more general a function becomes, the harder it becomes to name it? :)</p>
<p>If I wanted to parameterise 'lowest' or 'highest' I feel there should be a better way to do it, because passing <code>></code> or <code><</code> doesn't seem as intuitive as being able to state you want the lowest or highest.</p>
<p>Are there any design errors or misconceptions worth pointing out in the above? </p>
<p>Are there some better examples of functions which use multiple function arguments worth making a part of ones toolkit?</p>
| [] | [
{
"body": "<p>I agree that this generalization is not particularly useful: to abstract a part of a program to a functional parameter is meaningful when you can reuse that program with a class of different functions, not with two operators like <code><</code> and <code>></code>. For this, it is sufficient to define a boolean parameter:</p>\n\n<pre><code>(defun most (fn lst &key lowest) \n \"What's the el of a list with highest or lowest score, according to provided\nscoring fn?\"\n (if (null lst)\n (values nil nil) \n (let* ((wins (car lst)) ; 'wins' is 'winning element'\n (val (funcall fn wins)) ; 'max' is 'winning score'\n (comparison (if lowest #'< #'>))) ; highest or lowest ?\n (dolist (obj (cdr lst)) \n (let ((score (funcall fn obj)))\n (when (funcall comparison score val)\n (setf wins obj\n val score))))\n (values wins val))))\n\nCL-USER> (most #'length '((a b) (a b a c) (a)))\n(A B A C)\n4\nCL-USER> (most #'length '((a b) (a b a c) (a)) :lowest t)\n(A)\n1\n</code></pre>\n\n<p>More, I think that in this case one possibility of generalization could be not on the comparison itself, but on the functional parameter applied to the results, that it the maximum (for which the comparison is used). In fact the Paul Graham's function is the optimization of the following simpler (and less efficient!) function:</p>\n\n<pre><code>(defun most (fn lst)\n (let ((val (reduce #'max lst :key fn)))\n (values (find val lst :key fn) val)))\n</code></pre>\n\n<p>Abstracting on the function #'max:</p>\n\n<pre><code>(defun most (fn op lst)\n (let ((val (reduce op lst :key fn)))\n (values (find val lst :key fn) val)))\n</code></pre>\n\n<p>Making it a little more efficient:</p>\n\n<pre><code>(defun most (fn op lst)\n (let* ((vals (mapcar fn lst))\n (val (reduce op vals))\n (wins (position val vals)))\n (values (when wins (nth wins lst)) val)))\n</code></pre>\n\n<p>But I think that even this generalization is not particularly useful, even if it could have a little more sense:</p>\n\n<pre><code>CL-USER> (most #'length #'max '((a b) (a b a c) (a)))\n(A B A C)\n4\nCL-USER> (most #'length #'min '((a b) (a b a c) (a)))\n(A)\n1\nCL-USER> (defun avg (a b) (/ (+ a b) 2))\nAVG\nCL-USER> (most #'length #'avg '((a b) (a b a c) (a)))\n(A B)\n2\nCL-USER> (most #'length #'+ '((a b) (a b a c) (a)))\nNIL\n7\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T17:08:19.160",
"Id": "465386",
"Score": "0",
"body": "I would personally (probably) have created a \"cmp\" variable, possibly defaulting to #'> (or #'<, depending on), but I guess there's always the option of tweaking your scoring function to be commensurate with the ordering you want."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:52:45.077",
"Id": "219299",
"ParentId": "219101",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T11:44:17.013",
"Id": "219101",
"Score": "3",
"Tags": [
"beginner",
"functional-programming",
"common-lisp"
],
"Title": "Utmost function that takes a comparator function"
} | 219101 |
<p>We gave an option for user to Upload the image</p>
<p>Image is uploading fine, but its not adding any <strong>img src tag</strong> for that uploaded image.... Is this is acceptable to upload image without using any img tag ? will it lead to any problems 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>$(document).ready(function() {
// dont have a webserver so im using base64string instead
var maskedImageUrla = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAAEWCAYAAABiyvLjAAAACXBIWXMAAC4jAAAuIwF4pT92AAAF+mlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDIgNzkuMTYwOTI0LCAyMDE3LzA3LzEzLTAxOjA2OjM5ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTAxLTE5VDE4OjExOjMwKzA1OjMwIiB4bXA6TWV0YWRhdGFEYXRlPSIyMDE5LTAxLTE5VDE4OjExOjMwKzA1OjMwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAxOS0wMS0xOVQxODoxMTozMCswNTozMCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpjNzlhOWNlMi1jZmM4LTI3NDQtOWQ5YS0wN2RkNGI0Y2YzNGQiIHhtcE1NOkRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDozYjhkZGNiMS04MjQ4LTM4NDAtYmY1OC1jN2VhMTYyOTYyMGUiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo5NGVkMjU4ZC0zMzhiLTljNDMtOTYyOS1jMmM1MmRiMzE2NGUiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiBwaG90b3Nob3A6SUNDUHJvZmlsZT0ic1JHQiBJRUM2MTk2Ni0yLjEiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjk0ZWQyNThkLTMzOGItOWM0My05NjI5LWMyYzUyZGIzMTY0ZSIgc3RFdnQ6d2hlbj0iMjAxOS0wMS0xOVQxODoxMTozMCswNTozMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTggKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpjNzlhOWNlMi1jZmM4LTI3NDQtOWQ5YS0wN2RkNGI0Y2YzNGQiIHN0RXZ0OndoZW49IjIwMTktMDEtMTlUMTg6MTE6MzArMDU6MzAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCBDQyAyMDE4IChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz62EfeeAAATzUlEQVR4nO3df5BdZX3H8Xfu7OxsQ4zbEGOMMYQQQ4ghhB9BCIj8DKAQiTqAETH8qIkMSgMtGIMylMFIMThoGbCCoYBSobVKpYIi5WdApR2IURkGEWkaI41pTNNM2El3+8d3L7nc3Lv33HvPOd/nOefzmtnR3b33nC9J9rPf85znPM+ooaEhREZwEXDj8P//E2CXYy2SoYp3ARKsCcCDwE1Az/DHNNeKJFMKA2nkGOBXwIK6r89wqEVyojCQep8BHgXGNfjerJxrkRz1eBcgwRgH3M2e3UCtA3OqRRwoDARsLOBRYHKL183NvhTxMkp3E0rvEODHQH+C1+4C9gIGsixIfGjMoNxOBJ4kWRCAdZJzMqtGXCkMyuts7NZhX5vvOzyDWiQACoNyOh8bLOzk739eyrVIIBQG5bMMuK2L989PqxAJiwYQy+UTwNdSOM7ewJYUjiMBUWdQHotJJwgAjk3pOBIQhUE5zAfuTPF4J6R4LAmEwqD4pgD3k+7f9fEpHksCoTGDYhsN/ASYncGx3w5szOC44kSdQbGtIZsgAHUHhaMwKK7PAmdmePyTMjy2ONBlQjGdAvwg43NsAN6R8TkkRwqD4pkGPAeMyeFc+wMv5HAeyYEuE4qlB7iXfIIARl77QCKjMCiWa7BHkvPyoRzPJRnTZUJxHAE8lfM5B4G3AptzPq9kQJ1BMfRhTyHmrQKc4XBeyYDCoBiuBaY6nVuXCgWhy4T4HQ087nj+AexSYatjDZICdQZx6yPdB5A60Quc5lyDpEBhELeV+F0e1NKlQgHoMiFeE4H/IIzl7ncCbwG2excinVNnEK8VhBEEYJcrp3gXId1RGMRpIrY7ckg+4l2AdEdhEKeQuoKq02i8P6NEQmEQnxC7ArC7Clk+Mi0ZUxjEZznhdQVVH/cuQDqnuwlxGQ/8J/ZbOFR6rDlS6gzispywgwDgPO8CpDPqDOLRj3UFo53raGUTtgLSLu9CpD3qDOKxnPCDAGyAc6F3EdI+dQZxGIN1BWO9C0noIbRganTUGcThYuIJArBl1Kd5FyHtURiErxebZBSTCrDUuwhpj8IgfAuIqyuoOh97ZkEioTAI31neBXRoPHCOdxGSnAYQw9YH/JHw5xY0sw44yLsISUadQdjeR7xBADAHONa7CElGYRC2WC8Rai33LkCS0WVCuHqB/yHuzgBsb4X9gRe9C5GRqTMI1wLiDwKwf2OXeRchrSkMwrXIu4AULQEmeBchI1MYhKkCfNC7iBT1obGD4GnMIEzeG6NkYSuwD7DNuQ5pQp1BmE73LiAD/cAy7yKkOXUGYfo5MNu7iAxsAvbF9lmQwKgzCM8EihkEYGsdnO9dhDSmMAjPMd4FZGwleoApSAqD8BznXUDGJgEXehche9KYQXiKOl5QayOwHxo7CIo6g7D0AbO8i8jBJOAT3kXIGykMwjKX8vydrEBjB0Epyz+8WBziXUCOJmJrO0ogFAZhOcC7gJytwCYjSQAUBmEp+sBhvXHAFd5FiNHdhLD8nvI93bcDeCd2h0EcqTMIx1jKFwRgu0Rd7V2EKAxCUoZbis0sAWZ6F1F2CoNwlDkMeoBV3kWUncIgHO/yLsDZGWglZVcKg3CoTYYvo3+TbvQHHw6Fgc3A1CPOTnRrMRz/hW1JVnavYrcatTxaztQZhCPGzVWzMAG4yruIMlJnEIZe4DXvIgIygA2oauOVHKkzCEO/dwGB6QVWexdRNgqDMPR7FxCghcBp3kWUicIgDP3eBQTqq9h0ZcmBwiAM/d4FBGoqtoCq5EBhEIZ+7wIC9hdoDkYuFAZhUCvcXC9wk3cRZaAwCIPmGIzseGCxdxFFpzAIg/4eWluNLqcypX+EYVBn0NpE4HrvIopMYRCGV70LiMSF2CWDZEBhEIYN3gVE5OtowDUTCoMwKAySmwZc411EEelBpTCMA/7gXUREBoF3A894F1IkCoNwvIbdU5dk1gMHA7u8CykKXSaEQ5cK7ZkNfNa7iCJRGITjZe8CIrQSmONdRFEoDMKhzqB9vcA30eVVKhQG4VAYdGY2uruQih7vApxVsDX3JmMz3CZjI/tvxqa+9gEfH37t3wE7hz8GsD0CAf6IjW5vG/76BuB5YFObtfy2w/8GsScbvwes9S4kZmW4mzAOW4J7Lrbq7jR2B8A4Ru6OBus+b6eT2gasw4LhF9jo93qah8QpwA/aOL680UvAQcB270JiVbQwqGADSkcD7wWOwH7oQ7INeBYLip+zOySmDH8unftbYKl3EbEqQhjMBE4ETsK254r1oZ/NaN+ENJwKPOBdRIxiDIN+7If//VhrPdG1GgnNRuBAYIt3IbGJJQzGYNt2fxRr/UVG8l1gkXcRsQk9DGYAn8L239OTatKOpdgYgiQUahgsAJZjlwEindgBHIrdzZEEQgqD0cC5WAjMcK5FiuFZ7OnGAec6ohBCGEzGLgWWEe+dAAnX32D/vqQFzzCYDFwHnI2mRUu2Tge+711E6DzCoAJcDKxCg4KSjy3Y7EQ9/zGCvMNgFrAGODzPk4pgzy28Fy2G0lRe7XkPcDXwHAqCIqh/ZiMG87HLUmkij85gLnAn9qipFMNO7InOGC3CJiVJnSzDoAdbluoqNEAo4diGrZ34knchockqDKYBd6NLAgnTs8CRWIcjw7L4jX0u9iiugkBCNRf4qncRoUk7DK7EVgTSLUMJ3YXYLy4ZluZlwnXA5WkdTCQHO7Dpyuu9CwlBWp2BgkBiNBr4J7TVO5BOGFyLgkDiNR34Nrrj1fUfwKVoVxuJ3wJsenypdTNmcD5wW4q1iHg7C7jHuwgvnYbBicCDqLWSYtmBzT9Y512Ih07CYAbwb9i6hCJF8xIwjxIuqNrub/Z+bKMPBYEU1TRKOqDY7n/w3dgflkiRnQhc711E3toJgz9HC5RKeVyKDZKXRtIxg7nAz9BGrVIuA9gOTQ97F5KHJGEwGnvwSJcHUkabsTsML3oXkrUklwnXoCCQ8hqPDZoXfuXuVp3BIdhtRJGyexi7ZCjsHgytOoObc6lCJHzHAzd6F5GlkcLgHLRAiUitZdhdhkJqdpnQC/wa2+hERHYbxBZVvc+7kLQ16wzOR0Eg0kiFgq7v2agz6AV+A0zKvxyRaGzGVlkuzC5NjTqDM1EQiLRSuFuOjcJgee5ViMRpNrZsWq93IWmoD4O52NwCEUnmeGz/0OjVh8F5LlWIxG0x8GXvIrpVO4BYAX4HTPArRyRqK4AvehfRqdrOYD4KApFurMK6hCjVhsGpblWIFMcabLXl6NSGgRYuEeleL3aHIbpJSdUxg4nYeIGIpGMbcBQRbd1W7QwWulYhUjxjse0EpnsXklQ1DE5wrUKkmCZhsxSjmNFbDYPorm9EIjEd6xD6netoadTQ0FAv8Jp3ISIF91PgOGzXpiBVgKneRYiUwOEE/hxDBZjiXYRISSwA7iTQ3ZrUGYjk60wC3b28AuzjXYRIySwBvu5dRL0KNuFIRPJ1IYGttlxBax2KePk0sNq7iKoKkUyIECmoS7Fdy9wpDET8XTn84WrU0NDQ/xHorQ6RkrkMuMHr5KOGEu7JLiK5uAT4iseJFQYi4fkkcEveJ61Q4F1lRSJ1M3BR3ietAJvyPqmItHQTdusxNxXglTxPKCKJ3UiOuz5XsL3iBvM6oYi0ZTVweR4nqoaBbi2KhOs64DNZn6QC/Dbrk4hI11aR8cSkCvBylicQkdRcA1yd1cEVBiJx+TxwbRYHHjU0NDQa+N8sDi4imflr4Io0D1jBFmjckOZBRSRzl2OTk1Ib/K8e6N/TOqCI5GYZtqZiTxoHq4bBT9I4mIjkbjHwj6Sw6nI1DJ7o9kAi4mYhcD8wupuDVDde7QX+u9uDiYirp4FTga2dvLnaGQwAD6RUkIj4OAJ4FJjQyZtrRyLvTaUcEfE0B3icDjZHGlWztkkv8AdgTHp1iYiTV7Dd1V9M+obazmAAuCPtikTExRSsQ5ib9A31ExbWpFmNiLiaiI0hHJvkxfVh8Azwy5QLEhE/Y4EHgQ+3emGjqYxBbgopIh3rBb5Ni3UVRzVYHHk88DtSmuIoIkH5K+CqRt9o1BlsBv4h03JExMvnga/R4Ge/UWcAMB94MuOiRMTPfcBZwM7qF5qFAdgo5DE5FCUiPp4ATmd4+vJIYaDuQKT41gMnAxtHWhhhLXBrPvWIiJPZwFNA/0idAUA/8GtgXA5FiYiffVotmbQV2xVWRIprC/BKkvXT7gIeybYWEXH0GCRfTHEpsCu7WkTE0VOQPAxeAL6QXS0i4mgtjHxrsV4f8AtgKtqbUaQoBoG9gJ3t/FDvBC5AQSBSJOsYnoXY7g/2I+hyQaRIXl8ZvZPf8iuB21MrRUQ8vT7LuJ0xg1o92DrtC9KqSERc7Mvw5sudhgHYHguPAoelU5OI5GwLsHf1k24GA3dgGzYkXn1VRILyWO0n3d4Z2AwcB2zq8jgikr+naj9J4zbhBiwQtmL3LEUkDk/XftLNmEEjr5HCbrAikou9sMt9IP0JRB9I+Xgiko311AQBpB8GDwB/lvIxRSR9D9d/IYupxbcCn8zguCKSnn+t/0LaYwa1lqDt2kRCtTc2z+B1WT50dDvwfuquS0TE3TrqggCyfwLxX4Ajse2hRSQMP2z0xTweR14HHAw8lMO5RKS1Hzf6YpZjBvUqwCrg8rxOKCJ7GATeRIPL9zwXKhkErgAWAdtzPK+I7PY0TcbxPFYt+i522fC8w7lFyq7p5brXEmYvAvOAe5zOL1JWP2r2jTzHDJq5FLgOWzBFRLIzgI0XDDT6ZgiLm94AHIrNlRaR7DxGkyCAMMIA7Pbjodhiq9qsRSQbD470zVDCACyxVgIHUrcCi4ikYo+Hk2qFMGbQzNnA9cBk70JECmA78GZGWIAopM6g3t8D7wRWoHkJIt36Pi1WIgs5DMB2evkisB9wC1pWTaRT97d6QciXCY3MBlZj+zUMEn6YiYRij0eW68X2w7QeOBlbov0F51pEYvEMLYIA4guDqgewuw7nofkJIq18L8mLYrtMaOZo4BLgg8QbcCJZORh4ttWLihIGVZOw9RcvAsY51yISgleBtyZ5YdF+i24EPge8DfgosNa3HBF330n6wqKFQdUA8C3gKGxs4Ra0FqOU0z8nfWHRLhNGMgY4Bxt0PNy5FpE8DGCzDncmeXGZwqDWdOBjwIeBWc61iGTlPtrY5aysYVBrKrAQ+0M7luJeOkn5XAB8I+mLFQZvNBZ4HxYMp2GXFiKxeguwOemLFQbN9QDHYLMdTwTmulYj0p4ngPe08wYtNdbcLuz57+oz4P3YZcQJWDjMdKlKJJl7232DOoPOjQeOwG5fzsfuUPS5ViRiBoG3A5vaeZPCID09wBwsIOZh4TATDUhK/h7ALm/bojDI1mhsrOEwbI3H2ditTHUQkqWPYIsDtUVh4GMKFgqzgHcN/+9sdPdCurcVexah6SrIzSgMwjKR3cGwPzADmIaFhwZ7JYkvAX/ZyRsVBvGYhAXD1OGPfYc/nz78vUZjE1oNqnz2A17q5I0Kg2KoYKtIT6n52Gf4a1OHPx/rVZzk5iHgpE7frDAoj9HsDorJWGcxFesuZmC3Suups4jLImxj444oDKSqj92XIdOwdrN6GTIVCxMJ1ybgHXSxI5kGpaRqJ/DL4Y9GJmLzJmYCBwz/72xsvEL83UyXWxOqM5BujWX3HZCDsIlXc9EYRZ4Gsa5gYzcHURhIVqYBh2CLcR6Gzcjs9yyowL4DfKjbgygMJE8zsOc4jsKeCJ3hW05hnITdSeiKwkA89WOhcAK2S5aeBG3fy9idoa4pDCQkE7HHw08CzkDjDklcBtyQxoEUBhKqCrY5zgewzXGmulYTpl3Ycwgtt05LQmEgsZiF7YVxLjZpSuAubGHfVCgMJEbzsR+CxZT7UuIoUtwoSGEgMesFzgQ+Rfn2wliPbRCUGs07l5gNYK3yu7HFY26ng+f4I3VT2gdUZyBFMx5YDnya4i4WswMbONye5kHVGUjRbAZWYtNzV2Ir/xTNHaQcBKDOQIpvDNYlrKA4ncJBwLq0D6owkLIYB1wFXEzcHfHTwJFZHDjmPxSRdmwBLsF+q6Z2O85B6gOHVeoMpKyWAauJa9GWLcDbyOiOiToDKatbsEVanvYupA3Xk+GtU3UGUnYV4GrgSu9CWtiOdQWp30WoUmcgZTcIfA57IGqHcy0juYEMgwDUGYjUmgP8CJjgXUidnVhXsDXLk6gzENltHTa1+WXnOup9hRwmT6kzENnTZOBxwlhDYQDbXn1z1idSZyCypw3Ae4BXvAvB7npkHgSgzkBkJNOBn2FrJnj84tyFbZPX1RLoSakzEGnuReBPsTsOHr5BTkEACgORJC5wOOcgsCrPEyoMRFq7A7g153PeRc53NTRmIJLMaOA5bBwhDwcAz+d0LkCdgUhSO7DVmfNwDzkHASgMRNrxU2wCUNZyHSuo0mWCSHvGAr/BFkvJwn3YcxK5U2cg0p5t2INNWXHpCkCdgUgnerHuYFLKx/0hcHLKx0xMnYFI+waAazI4rltXAOoMRDrVB/ye9LZ3ewJ7HsKNOgORzuzEpgun5doUj9URdQYinZsJ/CqF4zwDzEvhOF1RZyDSueexQb9uuXcFoM5ApFvzgSe7eP9abGt1d+oMRLqzFvhSB+8bxBY4/Vi65XROnYFI9yrAbcCSNt6zHXhTJtV0SJ2BSPcGgfOApSRbzvwR4MAsC+qEOgORdI3FOoRFwGHYzs+D2NoEjwBrsDkFwfl/5WWoxWSgy5cAAAAASUVORK5CYII=";
// maskedImage one
var mask1 = $(".container").mask({
maskImageUrl: maskedImageUrla,
onMaskImageCreate: function(img) {
// add your style to the img example below
img.css({
"left": 105,
"top": 5
})
}
});
fileupa1.onchange = function() {
mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
};
}); // end of document ready
// jq plugin for mask
(function($) {
var JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString() + JQmasks.length,
x: 0, // image start position
y: 0, // image start position
onImageCreate: function(img) {},
onMaskImageCreate: function(div) {}
}, options);
var container = {};
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
initImage = false,
startX = settings.x,
startY = settings.y,
div,
obj = $(this);
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
};
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset();
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0;
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id === id)
el.item.enable();
else el.item.disable();
});
prevX = pos.x;
prevY = pos.y;
return $(item);
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
};
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (draggable && $(canvas).attr("active") === "true") {
var pos = container.mousePosition(evt);
var x = settings.x + pos.x - prevX;
var y = settings.y + pos.y - prevY;
if (x === settings.x && y === settings.y)
return; // position has not changed
settings.x = x;
settings.y = y;
prevX = pos.x;
prevY = pos.y;
container.updateStyle();
}
};
container.updateStyle = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = "source-over";
if (initImage || !image) {
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function() {
if (settings.onImageCreate)
settings.onImageCreate(image);
canvas.width = image.width * settings.scale;
canvas.height = image.height * settings.scale;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({
"width": image.width,
"height": image.height
});
};
} else {
context.drawImage(image, 0, 0, image.width, image.height);
}
if (initImage || !img) {
img = new Image();
img.src = settings.imageUrl || "";
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
settings.x = settings.x === 0 && initImage === true ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y === 0 && initImage === true ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
} else {
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
}
};
// change the draggable image
container.loadImage = function(imageUrl) {
if (img)
img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle();
};
container.createCanvas = function() {
if (canvas)
canvas.remove();
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
div.append(canvas);
div.find("canvas").hover(container.selected);
div.find("canvas").on('touchstart mousedown', container.selected);
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === true) return;
event.handled = true;
JQmasks.forEach(function(item) {
item.item.disable();
});
});
div.find("canvas").bind("dragover", container.onDragOver);
};
// change the masked Image
container.loadMaskImage = function(imageUrl, from) {
if (div)
div.remove();
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
});
container.createCanvas();
obj.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({
item: container,
id: settings.id
});
return container;
};
}(jQuery));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
border: 1px solid #DDDDDD;
display: flex;
background: red;
}
.container canvas {
display: block;
}
.masked-img {
overflow: hidden;
margin-left: 10px;
position: relative;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
image 1
<input id="fileupa1" type="file" >
<div class="container">
</div></code></pre>
</div>
</div>
</p>
<p>Here is <a href="https://codepen.io/kidsdial/pen/LvXqNb" rel="nofollow noreferrer">Codepen</a> & <a href="https://jsfiddle.net/mf5p6rh3/" rel="nofollow noreferrer">Fiddle</a></p>
<p>Please let me know if you need more information....</p>
<p>Thanks in Advance....</p>
| [] | [
{
"body": "<p>I would try to:</p>\n\n<p>1) Avoid <code>(function($) {})</code></p>\n\n<p>2) Use several <strong>non-abstract</strong> objects to handle your logic. <strong>Abstract</strong> objects are much harder to read and understand, I find them harder to refactor and to use inheritance.</p>\n\n<p>You can write <code>vanilla Javascript</code>, <code>CoffeeScript</code> or ES6 using <code>classes</code>.</p>\n\n<blockquote>\n <h1><a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming#Class-based_vs_prototype-based\" rel=\"nofollow noreferrer\">Class-based vs prototype-based</a></h1>\n \n <p>In <strong>class-based</strong> languages the classes are defined beforehand and the objects are instantiated based on the classes. If two objects apple and orange are instantiated from the class Fruit, they are inherently fruits and it is guaranteed that you may handle them in the same way; e.g. a programmer can expect the existence of the same attributes such as color or sugar content or is ripe.</p>\n \n <p>In <strong>prototype-based</strong> languages the objects are the primary entities. No classes even exist. The prototype of an object is just another object to which the object is linked. Every object has one prototype link (and only one). New objects can be created based on already existing objects chosen as their prototype. You may call two different objects apple and orange a fruit, if the object fruit exists, and both apple and orange have fruit as their prototype. The idea of the fruit class doesn't exist explicitly, but as the equivalence class of the objects sharing the same prototype. The attributes and methods of the prototype are delegated to all the objects of the equivalence class defined by this prototype. The attributes and methods owned individually by the object may not be shared by other objects of the same equivalence class; e.g. the attributes sugar content may be unexpectedly not present in apple. Only single inheritance can be implemented through the prototype. </p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:52:20.293",
"Id": "423537",
"Score": "0",
"body": "Well, thanks a lot for reply in weekend, but what to do with img tag ? Is that required? Can we zoom the uploaded image without using img tag ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:37:48.407",
"Id": "423547",
"Score": "0",
"body": "@vickeycolors sorry but discussions about troubleshooting should be done on `Stackoverflow`. Your question on stackoverflow is too complex to be answered. You need to break down your problem into steps and figure out which is the code breaking your functionality and build a [**minimal**, complete, reproducible example](https://stackoverflow.com/help/mcve). Your example is not **minimal** on stackoverflow and many users will prioritize other questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:44:53.123",
"Id": "423549",
"Score": "0",
"body": "@vickeycolors My point is, if you would be following the `Class-based` pattern instead of the `prototype-based` pattern, write high-quality code, maybe with unit tests, you could have code like [in this question](https://codereview.stackexchange.com/questions/219232/ruby-version-rotate-linked-list-to-the-right-by-k-places#comment423464_219232) which is easier to read and mantain. You can easily take the `def rotate` method from those classes and get your answer on StackOverflow. Unluckily `95%` of questions on SO are not about issues but code quality"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T09:52:16.610",
"Id": "219243",
"ParentId": "219103",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:43:00.193",
"Id": "219103",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html5",
"canvas"
],
"Title": "Upload image without src attribute"
} | 219103 |
<p>I have the following kotlin function that takes in a string "value", then attempts to parse "value" as both a LocalDateTime and an Int. It returns a Pair of the parsed value of "value" and an enum that specifies which of the three types it was determined to be.</p>
<pre><code>enum class RangeValueType{
Int,
Date,
String
}
fun parseValue(value: String): Pair<RangeValueType, Any> {
val rangeDate: LocalDateTime
val rangeInt: Int
//try date first
try {
//ISO_LOCAL_DATE_TIME e.g. 2011-12-03T10:15:30 for Dec. 3rd, 2011 & 10:15 30 sec.
//can't use basic date b/c e.g. 20111203 is indistinguishable from an int.
rangeDate = LocalDateTime.parse(value)
//it parsed to a date, so return the date
return Pair(RangeValueType.Date, rangeDate)
}catch (dtpe: DateTimeParseException) {
//not a date
}
//try number next
try{
rangeInt = value.toInt()
//it parsed to an int, so return the int
return Pair(RangeValueType.Int, rangeInt)
}catch (nfe: NumberFormatException)
{
//not an int
}
//not date or int, must be a string
return Pair(RangeValueType.String, value)
}
</code></pre>
<p>My principal concern is that I am using caught exceptions as a means of flow control, which I understand to generally be a Bad Idea. I know C# has a "TryParse" method for exactly this kind of case, but I wasn't able to find anything for Kotlin / Java. </p>
<p>Is there a better way to parse the values into their proper types?</p>
| [] | [
{
"body": "<p>(Disclamer: I only know Kotlin theoretically)</p>\n\n<p>You can avoid the second <code>try</code>/<code>catch</code> by using <code>String.toIntOrNull</code> instead of <code>String.toInt</code>.</p>\n\n<p>And by extracting the <code>LocalDateTime</code> conversion into a separate function, that also returns <code>null</code> when it fails (which also would help fulfill the single responsibility principle), you could then use a functional approach with the <a href=\"https://kotlinlang.org/docs/reference/null-safety.html#safe-calls\" rel=\"nofollow noreferrer\">safe call operator (<code>?.</code>)</a>, the <a href=\"https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator\" rel=\"nofollow noreferrer\">Elvis operator (<code>?:</code>)</a> and the <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html\" rel=\"nofollow noreferrer\"><code>run</code> extension method</a>:</p>\n\n<pre><code>enum class RangeValueType {\n INT,\n DATE,\n STRING\n}\n\nfun parseLocalDateTime(value: String): LocalDateTime? {\n try {\n return LocalDateTime.parse(value)\n } catch (dtpe: DateTimeParseException) {\n return null;\n }\n}\n\nfun parseValue(value: String): Pair<RangeValueType, Any> {\n return parseLocalDateTime(value)?.run { Pair(RangeValueType.DATE, this) } ?:\n value.toIntOrNull()?.run { Pair(RangeValueType.INT, this) } ?: \n value.run { Pair(RangeValueType.STRING, this) } \n}\n</code></pre>\n\n<p><a href=\"https://pl.kotl.in/zS84_1uVa\" rel=\"nofollow noreferrer\">Runable version</a> </p>\n\n<p>(NB: enum constants should be written all capitalized so they are not confused with types.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:48:56.090",
"Id": "219159",
"ParentId": "219108",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:52:55.587",
"Id": "219108",
"Score": "2",
"Tags": [
"parsing",
"datetime",
"integer",
"kotlin"
],
"Title": "Determine if a String can be parsed to LocalDateTime or Int"
} | 219108 |
<p>My goal is to calculate the length of each strongly connected component (<a href="https://en.wikipedia.org/wiki/Strongly_connected_component" rel="nofollow noreferrer">SCC</a>)</p>
<p>I have an input that looks like this:</p>
<pre><code>[['1', '2'],
['1', '2'],
['1', '5'],
['1', '6'],
['1', '7'],
['1', '3'],
['1', '8'],
['1', '4'],
['2', '47646'],
['2', '47647'],
['2', '13019']...
</code></pre>
<p>where lists inside big list means edge and elements of inside lists mean first and second vertex respectively.</p>
<p>Here is my code:</p>
<pre><code>#1.Create reverse graph: changing directions of the directed graph
#a)
df_reverse = [None] * len(df)
for i in range(len(df)):
df_reverse[i] = [int(df[i][1])]
df_reverse[i].append(int(df[i][0]))
#b) Sort the array according to df_reverse[i][0]
df_reverse = sorted(df_reverse,reverse = True)
#2. Run DFS-loop on reversed Graph:
t = 0 # for finishing lines: how many nodes are processed so far
s = None # current source vertex
explored = []
finish_time = {}
def DFS(graph,node):
explored.append(node)
global s
leader = s
print('Node:',node)
print('Leader:',leader)
#index = [ind for ind,vertex in enumerate(df_reverse) if vertex[0] == node]
for second_vert in graph:
print('Second_vert:',second_vert)
print('Second_vert[0] == node:',second_vert[0] == node)
if second_vert[0] == node:
print('second_vert[1] not in explored :',second_vert[1] not in explored)
if second_vert[1] not in explored:
print('---------------------------------')
print('NEXT ITERATION OF THE INNER LOOP')
print('-------------------------------------')
DFS(graph,second_vert[1])
global t
print('t was:',t)
t+= 1
print('t is :',t)
print('Index:',index)
finish_time[node] = t
print('LEADER TO THE NODE ',node,' IS ASSIGNED!')
print('-------------------------------------------')
#Nodes starts from n to 1
for i in range(max(df_reverse[0]),0,-1):
if i not in explored:
s = i
DFS(df_reverse,i)
#mapping finishing time to nodes
for ind,val in enumerate(df_reverse):
df_reverse[ind][0] = finish_time[df_reverse[ind][0]]
df_reverse[ind][1] = finish_time[df_reverse[ind][1]]
#3. Run DFS-loop on Graph with original directions(but with labeled finishing times):
df_reversed_back = [None] * len(df_reverse)
for i in range(len(df_reverse)):
df_reversed_back[i] = [int(df_reverse[i][1])]
df_reversed_back[i].append(int(df_reverse[i][0]))
#b) Sort the array according to df_reverse[i][0]
df_reversed_back = sorted(df_reversed_back,reverse = True)
all_components = []
SSC = []
explored= []
#c)modification of DFS
def DFS_2_Path(graph,node):
#global SSC
global all_components
explored.append(node)
print('Node:',node)
#index = [ind for ind,vertex in enumerate(df_reverse) if vertex[0] == node]
for second_vert in graph:
print('Second_vert:',second_vert)
print('Second_vert[0] == node:',second_vert[0] == node)
if second_vert[0] == node:
print('second_vert[1] not in explored :',second_vert[1] not in explored)
if second_vert[1] not in explored:
print('SSC was:',SSC)
SSC.append(second_vert[1])
print('SSC is:',SSC)
print('---------------------------------')
print('NEXT ITERATION OF THE INNER LOOP')
print('-------------------------------------')
DFS_2_Path(graph,second_vert[1])
if second_vert[1] in explored and len(SSC)> 0: #check if second vert is not explored and if it's not a new SSC
print('SSC was:',SSC)
SSC.append(second_vert[1])
print('SSC is:',SSC)
all_components.append(SSC[:])
print('All_components is :',all_components)
SSC[:] = []
print('All_components was:',all_components)
for i in range(max(df_reversed_back[0]),0,-1):
if i not in explored:
s = i
DFS_2_Path(df_reversed_back,i)
</code></pre>
<p>The problem is, that my code is very slow. I would appreciate any improvements and suggestions.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:26:34.660",
"Id": "423204",
"Score": "0",
"body": "Welcome to Code Review! Your code does not seem to be *complete* (i.e. runnable). Would it be correct to assume that the presented input is in `df`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:33:10.770",
"Id": "423243",
"Score": "0",
"body": "Do you need to use your own implementation? If not, there is the [networkx](https://networkx.github.io/) graph library, which also conviniently features a [SCC implementation](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.strongly_connected_components.html)."
}
] | [
{
"body": "<p>The debug logging is not going to help performance. You should really remove debugging code (and commented out code) before you ask for code review.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>df_reverse = [None] * len(df)\nfor i in range(len(df)):\n df_reverse[i] = [int(df[i][1])]\n df_reverse[i].append(int(df[i][0]))\n</code></pre>\n</blockquote>\n\n<p>is hard to read and understand.</p>\n\n<pre><code>def reversed_edge:\n return [int(edge[1]), int(edge[0])]\n\n\ndf_reverse = [reversed_edge(edge) for edge in df]\n</code></pre>\n\n<p>is clearer (although neither makes clear why the input isn't already using <code>int</code>s). And the meaning of <code>df</code> in <code>df_reverse</code> is opaque to me.</p>\n\n<hr>\n\n<p><code>DFS</code> contains two lines of code which just assign to unused variables, and some commented out code. Removing those, we get</p>\n\n<blockquote>\n<pre><code>def DFS(graph,node):\n explored.append(node)\n for second_vert in graph:\n if second_vert[0] == node:\n if second_vert[1] not in explored:\n DFS(graph,second_vert[1])\n\n global t\n t+= 1\n finish_time[node] = t\n</code></pre>\n</blockquote>\n\n<p>There are two red flags here:</p>\n\n<ol>\n<li><blockquote>\n<pre><code> for second_vert in graph:\n if second_vert[0] == node:\n</code></pre>\n</blockquote>\n\n<p><code>graph</code> (which is really <code>df_reverse</code>) is going to be filtered for every node in the graph, which means that it's using the wrong data structure. It should be a <code>dict</code>. This is almost certainly a major cause of the performance problem.</p></li>\n<li><p><code>t</code> and <code>finish_time</code> are defined in the same global scope, but only one of them is declared <code>global</code> here. That may or may not be a bug, but it's certainly confusing.</p></li>\n</ol>\n\n<hr>\n\n<p>As for the rest of the code, I can't understand what it's doing without some more helpful comments. Comments indicating that the following section of code implements step <code>#1.a)</code> are useless without an initial comment indicating the resource which the code follows. But since it's apparently doing two DFSs I rather hope that it's possible to refactor the code so that (a) it only implements DFS once, and calls it twice; (b) it does so with clearer scopes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:48:42.963",
"Id": "219112",
"ParentId": "219109",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219112",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T14:54:59.073",
"Id": "219109",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"graph"
],
"Title": "Strongly connected component in graph"
} | 219109 |
<p>I wrote this Javascript snippet for a Polymer fronted, it works without issues.</p>
<p>The only thing that it accomplishes is changing an icon's orientation whenever a user is clicking on any expandable-item (expandable-item is a specific Tag name).</p>
<p>Imagine a classic Operating System's folder tree display and the + or - icon that shows if a specific folder is expandable or not.</p>
<p>When the user clicks, the clicked expandable-item tag receives the expanded attribute.</p>
<p>The user can click on several expandable-item and all of them must remain opened or closed according to the user clicks and, clearly, also the icons related to the items must change accordingly.</p>
<p>Are there any ways that you could suggest to make it more efficient and/or shorter?</p>
<pre><code>var expandedItems = this.shadowRoot.querySelectorAll('expandable-item');
for (var i = 0; i < expandedItems.length; ++i) {
if (expandedItems[i].hasAttribute("expanded")){
expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-down");
} else {
expandedItems[i].getElementsByClassName("expandable-icon")[0].setAttribute("icon", "arrow:chevron-open-right");
}
}
</code></pre>
<p>Thanks for your suggestions.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:31:59.943",
"Id": "423208",
"Score": "3",
"body": "What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Also: Is `expandable-item` a tag name and/or a class name? If you are able to include sample HTML that might be helpful. Also, when does the JavaScript above get run?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T16:15:47.493",
"Id": "423212",
"Score": "2",
"body": "To make this a good question, you should include the context for this code. Are you doing anything else besides just toggling an icon? Normally, some other functionality goes along with expansion/contraction, and we could give you more proper advice if we could see the related code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:54:56.427",
"Id": "423246",
"Score": "0",
"body": "Thanks @SᴀᴍOnᴇᴌᴀ and 200_success, I perfectly get your point!\nI hope the question is better now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:58:31.647",
"Id": "423247",
"Score": "1",
"body": "Well, I don't see any change to the title so, it doesn't look better to me. Also, the text added does not answer my question regarding `expandable-item` being a class name, tag name or both..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:48:11.453",
"Id": "423299",
"Score": "0",
"body": "I applied other changes, @SᴀᴍOnᴇᴌᴀ.\nThanks again for your input and patience."
}
] | [
{
"body": "<p>Search online for <a href=\"https://www.google.com/search?ei=PkfDXLWRJdLa-gTcto7oCA&q=queryselectorall+vs+getelementsbytagname&oq=queryselectorall+vs+getelementsbytagname&gs_l=psy-ab.3..0l2j0i5i30l2.1762.4223..4480...3.0..0.61.447.8......0....1..gws-wiz.......0i71j35i304i39j0i13i10i30j0i13j0i13i5i30j35i39j0i7i30j0i7i5i30j0i7i30i19j0i7i5i30i19.TvVU3Y8HInU\" rel=\"nofollow noreferrer\">\"<em>queryselectorall vs getelementsbytagname</em>\"</a> and you will likely see results like <a href=\"https://stackoverflow.com/q/18247289/1575353\">this SO post from August 2013</a> and <a href=\"https://humanwhocodes.com/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/\" rel=\"nofollow noreferrer\">this post from September 2010</a>. After reading those one can posit that using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName\" rel=\"nofollow noreferrer\"><code>Element.getElementsByTagName()</code></a> instead of <code>querySelectorAll()</code> would be quicker, since the selector appears to merely find elements by tag name. Be aware that method returns a Live <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\">HTMLCollection</a> so you would need to put the elements into an array before iterating over them. There are some nice tools in <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> to do this, like using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">the spread syntax</a> or calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\"><code>Array.from()</code></a>.</p>\n\n<hr>\n\n<p>If you keep the <code>for</code> loop, you could consider using a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> (also standard with <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a>) in order to eliminate the accessing array elements with bracket notation.</p>\n\n<hr>\n\n<p>I am not able to find references to those attributes <code>icon=\"arrow:chevron-open-down\"</code> and <code>icon=\"arrow:chevron-open-right\"</code> but if those could be handled in CSS then you could eliminate the whole JS iteration block. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:56:52.437",
"Id": "423687",
"Score": "0",
"body": "Precious fuel for my refactoring.\nThanks for your kind help :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:13:45.037",
"Id": "219200",
"ParentId": "219110",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219200",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:13:07.483",
"Id": "219110",
"Score": "1",
"Tags": [
"javascript",
"iteration",
"polymer"
],
"Title": "Check if a web element has a specific property and apply changes to the DOM according to the property's existence"
} | 219110 |
<p>I'm trying to identify which cells in Column C in a spreadsheet of data are dates and if they are, then check if that date is older than 2 years old. If the second condition is met then the below code should copy the entire row from sheet "<em>DUP_ALL</em>" to a new sheet (Archive) and then delete the copied row from the "<em>DUP_ALL</em>" sheet.</p>
<p>I believe it works but I was wondering if there are any better ways to optimise my code.</p>
<p>Is it more efficient to stay in the first loop and copy and delete the rows at the same time or is it better to copy all the rows, then loop through a second time deleting all the rows that meet the same criteria.</p>
<p>I tried doing a copy and then delete in the same for loop to begin with but it kept producing an error "<em>Run Time 1004: Method 'Range' of Object '_worksheet' failed</em>"</p>
<p>Any help with optimising the below is greatly appreciated</p>
<pre><code>Sub TestArchive()
Dim sh As Worksheet, lr As Long, rng As Range, sh2 As Worksheet, lr2 As Long, c As Range
Set sh = Sheets("DUP_ALL") 'Edit sheet name
Set sh2 = Sheets("Archive") 'Edit Sheet name
lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
Set rng = sh.Range("C2:C" & lr)
For Each c In rng
If IsDate(c.Value) Then
If c.Value < Date - 456 Then
lr2 = sh2.Cells(Rows.Count, 1).End(xlUp).Row + 1
c.EntireRow.Copy sh2.Range("A" & lr2)
End If
End If
Next
For Each c In rng
If IsDate(c.Value) Then
If c.Value < Date - 456 Then
lr1 = sh.Cells(Rows.Count, 1).End(xlUp).Row + 1
c.EntireRow.Delete sh.Range("A" & lr1)
End If
End If
Next
End Sub
</code></pre>
| [] | [
{
"body": "<p>I've found that if you are deleting rows in a range you need to create a <code>for loop</code> that starts at the bottom and works your way up. When you are using the <code>for each loop</code> and try deleting an item out of that range and keep looping it destroys the reference to that range. The next iteration will throw an error.</p>\n\n<p>Here's an example, (I'm just pulling this out of my head and haven't tested it, but it should get you in the right direction)</p>\n\n<pre><code>...\ndim sh1Rows as integer \ndim myCell as range \n\nsh1Rows = sh.[\"A1\"].end(xlDown).row\n\nfor i = sh1Rows to 1 step -1\n set myCell = sh[\"A1\"].offset(0,i)\n if IsDate(myCell.value) and myCell.value < Date - 456 Then\n sh2.cells(1,sh2.[\"A1\"].end(xlDown) +1).entirerow = myCell.entirerow.value\n myCell.entirerow.delete\n end if\nnext\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T22:15:21.877",
"Id": "219534",
"ParentId": "219111",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219534",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:24:48.823",
"Id": "219111",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "VBA Copy and Delete Rows loop optimisation"
} | 219111 |
<p>My macro is cobbled together using some code from Ron DeBruin and various other sources and it currently works but I am sure it is not as efficient or bulletproof as possible. Currently it updates the Weekly or Monthly Dashboard tabs and saves them as a PDF then emails them to the correct subcontractor as well as their manager. Any thoughts on how to make it more efficient or reduce potential errors?</p>
<pre><code>Sub BulkSendReports()
Dim FileName As String
Dim TitleName As String
Dim FileLocation As String
Dim i As Integer
Dim Email As String
Dim SDLEmail As String
Dim Name As String
Dim pf1 As PivotField
Dim pf2 As PivotField
Dim pf3 As PivotField
Dim pf4 As PivotField
Dim IIF_Band As String
Dim Email_Subject As String
Email_Subject = ThisWorkbook.Worksheets("Report Controls").Range("C5").Value
Dim Email_Body As String
Email_Body = ThisWorkbook.Worksheets("Report Controls").Range("C7").Value
Dim Agent_Count As Integer
Agent_Count = ThisWorkbook.Worksheets("Background Data").Range("A" & Rows.Count).End(xlUp).Row - 1
Application.ScreenUpdating = False
For i = 1 To Agent_Count
Application.StatusBar = "Generating Dashboard for..." & Name
Worksheets("Dashboard").Activate
ThisWorkbook.Worksheets("Dashboard").Range("B6").Value = ThisWorkbook.Worksheets("Background Data").Range("C1").Offset(i, 0)
Set pf1 = ActiveSheet.PivotTables("PivotTable3").PivotFields("IIF Band")
Set pf2 = ActiveSheet.PivotTables("PivotTable5").PivotFields("IIF Band")
Set pf3 = ActiveSheet.PivotTables("PivotTable6").PivotFields("IIF Band")
Set pf4 = ActiveSheet.PivotTables("PivotTable7").PivotFields("IIF Band")
IIF_Band = ActiveWorkbook.Worksheets("Calculations").Range("D13").Value
pf1.ClearAllFilters
pf1.CurrentPage = IIF_Band
pf2.ClearAllFilters
pf2.CurrentPage = IIF_Band
pf3.ClearAllFilters
pf3.CurrentPage = IIF_Band
pf4.ClearAllFilters
pf4.CurrentPage = IIF_Band
TitleName = ActiveWorkbook.Worksheets("Calculations").Range("D11").Value
FileLocation = "C:\Users\ARP021\Documents\RSuite\" & TitleName & ".pdf"
Email = ThisWorkbook.Worksheets("Background Data").Range("B1").Offset(i, 0)
SDLEmail = ThisWorkbook.Worksheets("Background Data").Range("H1").Offset(i, 0)
Name = ThisWorkbook.Worksheets("Background Data").Range("A1").Offset(i, 0)
If ActiveWindow.SelectedSheets.Count > 1 Then
MsgBox "There is more then one sheet selected," & vbNewLine & _
"be aware that every selected sheet will be published"
End If
FileName = RDB_Create_PDF(Source:=ActiveSheet, _
FixedFilePathName:=FileLocation, _
OverwriteIfFileExist:=True, _
OpenPDFAfterPublish:=False)
If FileName <> "" Then
RDB_Mail_PDF_Outlook FileNamePDF:=FileName, _
StrTo:=Email, _
StrCC:="", _
StrBCC:=SDLEmail, _
StrSubject:=Email_Subject, _
Signature:=True, _
Send:=False, _
StrBody:="Hello " & Name & ",<br><br>" & Email_Body
Else
MsgBox "Not possible to create the PDF, possible reasons:" & vbNewLine & _
"Microsoft Add-in is not installed" & vbNewLine & _
"You Canceled the GetSaveAsFilename dialog" & vbNewLine & _
"The path to Save the file in arg 2 is not correct" & vbNewLine & _
"You didn't want to overwrite the existing PDF if it exist"
End If
Next i
ThisWorkbook.Worksheets("Report Controls").Range("C7").Value = "Enter Email body text here (exluding greetings)."
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub
Function RDB_Create_PDF(Source As Object, FixedFilePathName As String, _
OverwriteIfFileExist As Boolean, OpenPDFAfterPublish As Boolean) As String
Dim FileFormatstr As String
Dim Fname As Variant
If FixedFilePathName = "" Then
FileFormatstr = "PDF Files (*.pdf), *.pdf"
Fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
Title:="Create PDF")
If Fname = False Then Exit Function
Else
Fname = FixedFilePathName
End If
If OverwriteIfFileExist = False Then
If Dir(Fname) <> "" Then Exit Function
End If
On Error Resume Next
Source.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=OpenPDFAfterPublish
On Error GoTo 0
If Dir(Fname) <> "" Then RDB_Create_PDF = Fname
End Function
Function RDB_Mail_PDF_Outlook(FileNamePDF As String, StrTo As String, _
StrCC As String, StrBCC As String, StrSubject As String, _
Signature As Boolean, Send As Boolean, StrBody As String)
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
If Signature = True Then .Display
.To = StrTo
.CC = StrCC
.BCC = StrBCC
.Subject = StrSubject
.HTMLBody = StrBody & "<br>" & .HTMLBody
.Attachments.Add FileNamePDF
If Send = True Then
.Display
Else
.Display
End If
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Function
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T15:49:10.507",
"Id": "219113",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Update Dashboard tabs to compare subcontractor to peers then email performance summary"
} | 219113 |
<p>I am working on a <a href="https://www.hackerrank.com/challenges/computer-game" rel="nofollow noreferrer">coding challenge from the Hackerrank site</a>. Given two equal-length arrays of integers, with values from 2 to 10<sup>9</sup>, find the maximum number of times we can remove a pair (A<sub>i</sub>, B<sub>j</sub>) where A<sub>i</sub> and B<sub>j</sub> are not co-prime.</p>
<p>The programming language of my choice is Python2.
Hackerrank has <a href="https://www.hackerrank.com/environment" rel="nofollow noreferrer">timeout of 10 secs</a> for the Python2 submissions and it is noteworthy that Hackerrank doesn't provide the <code>numpy</code> package for the standard challenges.</p>
<p>My current approach is to reduce this problem to well-known Max-Flow problem and solve it using the <a href="https://cp-algorithms.com/graph/dinic.html" rel="nofollow noreferrer">Dinic algorithm</a>.</p>
<p>My Python code:</p>
<pre><code># -*- coding: utf-8 -*-
#!/bin/python
from collections import *
def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
# precompute prime numbers smaller than sqrt(10**9)
prime_gen = gen_primes()
primes = [next(prime_gen) for _ in xrange(3500)]
# enhanced trial division method using precomputed prime numbers
def trial_division(n):
a = set()
while n % 2 == 0:
a.add(2)
n /= 2
i = 1
f = primes[i]
while f * f <= n:
if n % f == 0:
a.add(f)
n /= f
else:
i += 1
f = primes[i]
if n != 1:
a.add(n)
return a
def bfs(graph, cap_edges, level, s, t):
queue = deque()
queue.append(s)
level[s] = 1
while queue:
u = queue.popleft()
for v, eid, _ in graph[u]:
if level[v] == 0 and cap_edges[eid] > 0:
level[v] = level[u] + 1
queue.append(v)
return level[t] > 0
def dfs(graph, ptr, cap_edges, level, u, s, t):
if u == t:
return 1
adj = graph[u]
ind = ptr[u]
i = ind
n = len(adj)
while i < n:
v, eid, eid_b = adj[i]
ptr[u] = i
i += 1
if (level[v] == level[u] + 1) and cap_edges[eid] > 0:
f = dfs(graph, ptr, cap_edges, level, v, s, t)
if f > 0:
cap_edges[eid] -= 1
cap_edges[eid_b] += 1
return f
return 0
# solve the max-flow problem using the Dinic algorithm
def max_flow(graph, cap_edges, s, t):
n = len(graph)
level = [0] * n
ptr = [0] * n
flow = 0
while bfs(graph, cap_edges, level, s, t):
f = dfs(graph, ptr, cap_edges, level, s, s, t)
while f > 0:
flow += f
f = dfs(graph, ptr, cap_edges, level, s, s, t)
level = [0] * n
ptr = [0] * n
return flow
def computer_game(n, A, B):
start_node = 0
end_node = 1
graph = defaultdict(list)
cap_edges = []
node_count = 2
edges_count = 0
prime_nodes_map = {}
for value in A:
current_node = node_count
graph[start_node].append((current_node, edges_count, edges_count+1))
cap_edges.append(1)
graph[current_node].append((start_node, edges_count+1, edges_count))
cap_edges.append(0)
edges_count += 2
node_count += 1
factors = trial_division(value)
for p in factors:
if p not in prime_nodes_map:
prime_nodes_map[p] = node_count
node_count += 1
p_node = prime_nodes_map[p]
graph[current_node].append((p_node, edges_count, edges_count+1))
cap_edges.append(1)
graph[p_node].append((current_node, edges_count+1, edges_count))
cap_edges.append(0)
edges_count += 2
for value in B:
current_node = node_count
graph[current_node].append((end_node, edges_count, edges_count+1))
cap_edges.append(1)
graph[end_node].append((current_node, edges_count+1, edges_count))
cap_edges.append(0)
edges_count += 2
node_count += 1
factors = trial_division(value)
for p in factors:
if p not in prime_nodes_map:
prime_nodes_map[p] = node_count
node_count += 1
p_node = prime_nodes_map[p]
graph[p_node].append((current_node, edges_count, edges_count+1))
cap_edges.append(1)
graph[current_node].append((p_node, edges_count+1, edges_count))
cap_edges.append(0)
edges_count += 2
result = max_flow(graph, cap_edges, start_node, end_node)
print(result)
if __name__ == '__main__':
n = int(raw_input())
a = map(int, raw_input().rstrip().split())
b = map(int, raw_input().rstrip().split())
computer_game(n, a, b)
</code></pre>
<p>This Python code gets timeout for the last 2 biggest test instances, but I know in fact that I am using the right algorithm because I submitted a C++ solution implementing <strong>the exact same algorithm</strong>, which passes all the test cases with flying colors.</p>
<p>So my question is, can my Python code above be optimized any further?
Did I miss some obvious optimizations?
At this point I am wondering if this challenge can be solved with Python at all...</p>
<p>Here is a large test-case pair which causes timeout:
<a href="https://gist.githubusercontent.com/bmktuwien/1b5a2db3a0c2803da9d5c886b295b92e/raw/ba53ebbd4c03a2c0895ddb892bc46e7492c63cb8/input.txt" rel="nofollow noreferrer">input.txt</a>
<a href="https://gist.githubusercontent.com/bmktuwien/c5c2a04b8f0397f234ad742c4155f34c/raw/ae274c04430c5a3056a3f5883e01108175d557bb/output.txt" rel="nofollow noreferrer">output.txt</a></p>
<p>For the comparison, here is my C++ solution which passes all test cases:</p>
<blockquote>
<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
using namespace std;
struct Entry {
int node;
int eid;
int eid_r; };
vector<int> gen_primes(int n) {
vector<int> result;
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++) {
if (prime[p]) {
for (int i=p*2; i<=n; i += p)
prime[i] = false;
}
}
for (int p=2; p<=n; p++) {
if (prime[p]) {
result.push_back(p);
}
}
return result; }
vector<int> factorization(int n, const vector<int>& primes) {
vector<int> a;
if (!(n&1)) {
a.push_back(2);
n >>= 1;
while (!(n&1)) {
n >>= 1;
}
}
int i = 1;
int f = primes[i];
while (f*f <= n) {
if (n % f == 0) {
a.push_back(f);
n /= f;
while (n % f == 0) {
n /= f;
}
}
f = primes[i++];
}
if (n != 1) {
a.push_back(n);
}
return a; }
bool bfs(const vector<vector<Entry>> &graph,
vector<int>& cap_edges, vector<int>& level, int s, int t) {
queue<int> q;
q.push(s);
level[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (const Entry &e : graph[u]) {
if ((level[e.node] == 0) && (cap_edges[e.eid] > 0)) {
level[e.node] = level[u] + 1;
q.push(e.node);
}
}
}
return level[t] > 0; }
int dfs(const vector<vector<Entry>> &graph,
vector<int>& ptr, vector<int>& cap_edges, vector<int>& level,
int u, int s, int t) {
if (u == t) {
return 1;
}
for (int i = ptr[u]; i < graph[u].size(); i++) {
const Entry& e = graph[u][i];
ptr[u] = i;
if ((level[e.node] == level[u]+1) && (cap_edges[e.eid] > 0)) {
int f = dfs(graph, ptr, cap_edges, level, e.node, s, t);
if (f > 0) {
cap_edges[e.eid] -= f;
cap_edges[e.eid_r] += f;
return f;
}
}
}
return 0; }
int max_flow(const vector<vector<Entry>> &graph, vector<int>&
cap_edges,
int s, int t) {
int n = graph.size();
vector<int> level(n, 0);
vector<int> ptr(n, 0);
int flow = 0;
while (bfs(graph, cap_edges, level, s, t)) {
int f;
do {
f = dfs(graph, ptr, cap_edges, level, s, s, t);
flow += f;
} while(f > 0);
fill(level.begin(), level.end(), 0);
fill(ptr.begin(), ptr.end(), 0);
}
return flow; }
void solve(int n, const vector<int>& A, const vector<int>& B) {
vector<int> primes = gen_primes(32000);
int start_node = 0;
int end_node = 1;
vector<vector<Entry>> graph(310000);
vector<int> cap_edges;
int node_count = 2;
int edge_count = 0;
map<int, int> prime_nodes_map;
for (int value : A) {
int current_node = node_count;
graph[start_node].push_back({current_node, edge_count, edge_count+1});
cap_edges.push_back(1);
graph[current_node].push_back({start_node, edge_count+1, edge_count});
cap_edges.push_back(0);
edge_count += 2;
node_count += 1;
vector<int> prime_factors = factorization(value, primes);
for (int p : prime_factors) {
auto it = prime_nodes_map.find(p);
if (it == prime_nodes_map.end()) {
prime_nodes_map[p] = node_count;
node_count += 1;
}
int p_node = prime_nodes_map[p];
graph[current_node].push_back({p_node, edge_count, edge_count+1});
cap_edges.push_back(1);
graph[p_node].push_back({current_node, edge_count+1, edge_count});
cap_edges.push_back(0);
edge_count += 2;
}
}
for (int value : B) {
int current_node = node_count;
graph[current_node].push_back({end_node, edge_count, edge_count+1});
cap_edges.push_back(1);
graph[end_node].push_back({current_node, edge_count+1, edge_count});
cap_edges.push_back(0);
edge_count += 2;
node_count += 1;
vector<int> prime_factors = factorization(value, primes);
for (int p : prime_factors) {
auto it = prime_nodes_map.find(p);
if (it == prime_nodes_map.end()) {
prime_nodes_map[p] = node_count;
node_count += 1;
}
int p_node = prime_nodes_map[p];
graph[p_node].push_back({current_node, edge_count, edge_count+1});
cap_edges.push_back(1);
graph[current_node].push_back({p_node, edge_count+1, edge_count});
cap_edges.push_back(0);
edge_count += 2;
}
}
cout << max_flow(graph, cap_edges, start_node, end_node) << endl; }
int main(int argc, char **argv) {
int n;
cin >> n;
vector<int> a;
for (int i = 0; i < n; i++) {
int val;
cin >> val;
a.push_back(val);
}
vector<int> b;
for (int i = 0; i < n; i++) {
int val;
cin >> val;
b.push_back(val);
}
solve(n, a, b);
}
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:49:11.253",
"Id": "423222",
"Score": "2",
"body": "I don't think it's unreasonable for the same algorithm to run in over 5 times the equivalent in C/C++. A quick glance at [Julia's benchmarks](https://julialang.org/benchmarks/) shows this to be true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T18:06:40.970",
"Id": "423225",
"Score": "0",
"body": "@Peilonrayz Thank you for your comment. Funny you mention factor 5, because thats exactly the factor between c++ timeout (2 secs) and python timeout (10 secs) on Hackerrank. But in my case, the python code is ca. 10 times slower than c++ equivalent. Thats why I asked the question in the first place to learn how to improve the code further to reach at least factor 5..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:54:38.670",
"Id": "423245",
"Score": "0",
"body": "Have you tried caching the results of your `trial_division` function? And checking the cache inside your `n` loop? It seems likely that you would see some hits, but I'm not sure how many."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:15:25.180",
"Id": "423249",
"Score": "0",
"body": "@AustinHastings Yes, I tried to memoize the `trial_division` function but the hits were negligible since the input data are uniformly random generated between 2 and 10^9..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:46:56.250",
"Id": "423253",
"Score": "0",
"body": "I was hoping you would get memo hits on smaller values of `n`. Too bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:36:17.510",
"Id": "423403",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
}
] | [
{
"body": "<p>It's not clear to me why <code>gen_primes()</code> is so complicated. The C++ version, which is a straight sieve, is much clearer.</p>\n\n<hr>\n\n<p>There's one red flag in <code>trial_division</code>: <code>/=</code> is floating point division. Averaging timing runs would obviously be better, but even on a single timing run changing the two <code>/=</code> to <code>//=</code> drops the run time from 20.5 secs to 16.2 secs.</p>\n\n<p>The iteration in <code>trial_division</code> is also unidiomatic. Replacing it with a <code>for</code> loop:</p>\n\n<pre><code>def trial_division(n):\n a = set()\n\n while n % 2 == 0:\n a.add(2)\n n //= 2\n\n for p in primes:\n if p * p > n:\n break\n\n while n % p == 0:\n a.add(p)\n n //= p\n\n if n != 1:\n a.add(n)\n\n return a\n</code></pre>\n\n<p>the time drops to 12.5 secs.</p>\n\n<p>Profiling with <code>python -m cProfile cr219119.py <cr219119.in</code> shows that <code>trial_division</code> is still by far the bottleneck. The expensive operations are the multiplication and division, and the division is a problem, but we can remove the multiplication with</p>\n\n<pre><code>primesWithSquares = [(p, p*p) for p in primes]\n</code></pre>\n\n<p>and changing the loop to</p>\n\n<pre><code> for p, p2 in primesWithSquares:\n if p2 > n:\n break\n\n while n % p == 0:\n a.add(p)\n n //= p\n</code></pre>\n\n<p>to get down to 10.8 secs.</p>\n\n<p>Finally, using the same trick as the C++ code of doubling up the tests to use a list rather than a set:</p>\n\n<pre><code>def trial_division(n):\n a = []\n\n if n & 1 == 0:\n a.append(2)\n n //= 2\n while n & 1 == 0:\n n //= 2\n\n for p, p2 in primesWithSquares:\n if p2 > n:\n break\n\n if n % p == 0:\n a.append(p)\n n //= p\n while n % p == 0:\n n //= p\n\n if n != 1:\n a.append(n)\n\n return a\n</code></pre>\n\n<p>I get a running time of 9.4 secs.</p>\n\n<hr>\n\n<p>As far as the rest of the code goes, I find it severely lacking in comments. A lot of the names are quite good (<code>trial_division</code> and <code>computer_game</code> are the worst exceptions), but I had to reverse engineer the code to figure out what <code>prime_nodes_map</code> was about and I still don't fully understand the <code>graph</code> data structure. There also seems to be a lot of potential to factor out some of the code involved in the graph construction. Perhaps (untested)</p>\n\n<pre><code>def add_edge(u, v, direction):\n graph[u].append((v, edges_count, edges_count+1))\n cap_edges.append(direction)\n graph[v].append((u, edges_count+1, edges_count))\n cap_edges.append(1 - direction)\n edges_count += 2\n\ndef new_node():\n node_count += 1\n return node_count - 1\n\ndef add_half_graph(values, end_node, direction):\n for value in values:\n current_node = new_node()\n\n add_edge(end_node, current_node, direction)\n\n for p in trial_division(value):\n if p not in prime_nodes_map:\n prime_nodes_map[p] = new_node()\n\n add_edge(current_node, prime_nodes_map[p], direction)\n\nadd_half_graph(A, start_node, 1)\nadd_half_graph(B, end_node, 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:49:41.747",
"Id": "423337",
"Score": "0",
"body": "Interesting. I always assumed something like `a/b`, for `a` and `b` being integers, would use an integer division in Python 2 since the result is type `int`, but the [dis documentation](https://docs.python.org/2/library/dis.html#opcode-BINARY_DIVIDE) says it's actually a different op from `//`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:55:48.790",
"Id": "423338",
"Score": "0",
"body": "@AlexV, I should confess that I profiled with Python3, making minor tweaks, because I don't have Python2 on this machine. I may have put my foot in it with the divisions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T15:46:15.237",
"Id": "423398",
"Score": "0",
"body": "@PeterTaylor Thank you so much for your in depth review! Really appreciate it. If I may make some comments about your points: As someone already mentioned, the `/` operator is an integer division in Python 2 if you don't import `__future__.division` (which I didn't). But the caching of the squared prime numbers saves indeed lots of time (about 4 secs on my machine). It never occurred to me that multiplication could be such a performance killer, especially if the results are less than 10^9. Anyway thank you so much and I will try to resubmit the solution with cached prime-squares..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T15:56:39.320",
"Id": "423399",
"Score": "0",
"body": "fyi: I just resubmitted the revised code with cached squared prime numbers but the last 2 test-cases still time out... But I think I'm getting closer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:37:40.370",
"Id": "423487",
"Score": "0",
"body": "(Untested and knowing Python likely to be wrong) Given that for each `while n % p == 0: n //= p` you're effectively performing the same calculation twice, if you change it to one `divmod` you may get a performance increase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:52:18.313",
"Id": "423560",
"Score": "0",
"body": "@Peilonrayz, good suggestion, but in practice it seems to be much slower."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:00:54.057",
"Id": "219174",
"ParentId": "219117",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219174",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T16:53:40.223",
"Id": "219117",
"Score": "7",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"primes",
"graph"
],
"Title": "Hackerrank: Computer Game (max-flow problem with integer factorization)"
} | 219117 |
<p>I need to write an OCaml program that return all possible zip of two lists together while preserving the order of the element in each list. For example, if we zip the lists [1;2] and [3;4], we get [[1;2;3;4];[1;3;4;2];[3;1;2;4];[1;3;2;4];[3;1;4;2];[3;4;1;2]].</p>
<p>My naïve approach is to append each element in the first list one by one into the second list while making sure that the order of elements in the first list is preserved when inserted into the second list. Please show me the simple recursive structure.</p>
<p>Here are my codes :</p>
<pre><code>let rec insert item list =
match list with
|[]-> [[item]]
|x::xs-> (item::list)::(List.map (fun y-> x::y) (insert item xs))
let breakIntoTwo list item=
let rec helper acc ll itemm=
match ll with
|[]->(acc,[])
|x::xs -> if x= itemm then (acc,ll)
else helper (acc@[x]) xs itemm
in helper [] list item
let rec insertl item list nextItem=
match breakIntoTwo list nextItem with
|(a,b) -> List.map (fun y -> y@b) (insert item a)
let rec insertll item listoflists nextItem=
match listoflists with
|[]-> []
|x::xs-> (insertl item x nextItem) @ (insertll item xs nextItem)
let rec zip list1 list2=
match list1 with
|[]-> [list2]
|[a]-> insert a list2
|x::xs::xss -> insertll x (zip (xs::xss) list2) xs
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:00:27.703",
"Id": "219118",
"Score": "2",
"Tags": [
"combinatorics",
"ocaml"
],
"Title": "Interleave two lists, preserving the order of elements in their original list"
} | 219118 |
<p><strong>The task</strong></p>
<blockquote>
<p>Given a linked list and a positive integer k, rotate the list to the
right by k places.</p>
<p>For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it
should become 3 -> 5 -> 7 -> 7.</p>
<p>Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should
become 3 -> 4 -> 5 -> 1 -> 2.</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>class LinkedNode {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
const n4 = new LinkedNode(5);
const n3 = new LinkedNode(3, n4);
const n2 = new LinkedNode(7, n3);
const n1 = new LinkedNode(7, n2);
let n = n1;
const rotate = (l, k) => {
let p = l;
const first = l;
let last;
let res;
let i = 0;
while(p) {
i++;
if (!p.next) { last = p; }
p = p.next;
}
const size = i;
if (!(k % size)) { return l; }
const aim = size - (k % size) - 1;
p = l;
i = 0;
while (p) {
if (i++ === aim) {
res = p.next;
p.next = null;
last.next = first;
return res;
}
p = p.next;
}
};
n = rotate(n, 0);
while (n) {
console.log(n.value);
n = n.next;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T21:22:32.953",
"Id": "423250",
"Score": "1",
"body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
}
] | [
{
"body": "<p>Start by renaming your variables.\n'p', 'n', 'n4' etc are all examples of a bad/no naming standards.</p>\n\n<p>I don't see any value in creating extra variables, especially when the new variable does not have a meaningful name. I'd suggest trying to reduce the number of declared variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:02:15.360",
"Id": "423237",
"Score": "0",
"body": "Hmm.... `p` is \"pointer\". I thought it's generally known. `i` stands for \"index\". I think this is common as well. The same for `k`. However `n`, `n1`, `n2` etc. are \"nodes\". I could have written it like this but that would mean too much repetition: `node`, `node1`, `node2`, `node3`, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:46:31.140",
"Id": "423366",
"Score": "0",
"body": "@thadeuszlay don't shorten names to reduce repetition. That's silly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T18:41:09.660",
"Id": "219125",
"ParentId": "219119",
"Score": "0"
}
},
{
"body": "<p>You started to write a class, but then stopped. You should continue. There are three things that are potentially <span class=\"math-container\">\\$O(n)\\$</span> in this problem: </p>\n\n<ol>\n<li>You need to know the length of the list.</li>\n<li>You need to know the last node of the list.</li>\n<li>You need to know the <code>k-1</code>th node of the list.</li>\n</ol>\n\n<p>Two of those obviously go together, so you could justify writing a helper method that returns them both. The third one is arbitrary enough that there's not really any way to speed it up.</p>\n\n<p>If you are in some kind of timed environment, you'll definitely want to wrap the list in a class and cache the <code>last</code> pointer and the <code>size</code> of the list.\nIf you do that, you can quickly compute <code>k % size</code> and then find #3, which will be <span class=\"math-container\">\\$O(n)\\$</span>. </p>\n\n<p>If I were trying to write challenges for a timed competition, I would include a large list and <code>k = 2 * n - 1</code>.</p>\n\n<p>I see several obvious methods in your code, including a more sophisticated constructor that could take an array (perhaps an outer <code>LinkedList</code> class), the <code>length</code> operation, the <code>get_last</code> operation, the <code>get_item</code> operation, the <code>print</code> or perhaps <code>map</code> operation, and obviously missing is the <code>compare</code> operation.</p>\n\n<p>You should probably check for <code>k == 0</code> before finding the last item. I can easily see a <code>time-limit-exceeded</code> trap being to construct a huge list, then do a <code>rotate</code> with <code>k=0</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:34:28.743",
"Id": "219130",
"ParentId": "219119",
"Score": "1"
}
},
{
"body": "<p>There are a few places that you could have simplified.</p>\n\n<ul>\n<li><p>To count items and loop to find the end you can use <code>while(p.next) { p = p.next, i++ }</code> with <code>p</code> after the loop holding the tail.</p></li>\n<li><p><code>%</code> is calculated before <code>+</code> and <code>-</code> so <code>size - (k % size) - 1</code> is the same as <code>size - k % size - 1</code></p></li>\n<li><p>The last <code>while</code> can reuse <code>i</code> and count <code>i</code> down to zero to find the new tail, cutting the list after the <code>while</code> loop. Avoiding the need <code>for if(i++ === aim)</code> and the variable <code>aim</code></p></li>\n<li><p>The creation of the variable <code>size</code> could be avoided by using <code>i</code> instead</p></li>\n</ul>\n\n<h2>Two alternatives</h2>\n\n<p>I assume that the rotation is never left. Eg the rotate value is negative.</p>\n\n<p>First constructing the list can be simplified as</p>\n\n<pre><code>const node = (value, next) => ({value, next});\nconst head = node(0, node(1, node(2, node(3, node(4, node(5, node(6)))))));\n</code></pre>\n\n<p><strong>Note:</strong> I do not use <code>null</code> see second example below for why. However <code>null</code> as you have used it is semantically correct.</p>\n\n<h3>Example A</h3>\n\n<p>Avoiding having to count the items if no rotation there is an early exit. Apart from that the function uses the same logic you have used to rotate the list.</p>\n\n<pre><code>function rotateList(node, rotate) {\n var tail = node, n = node, count = 1;\n if (rotate > 0) {\n while (n.next) { n = n.next, count ++ }\n if (rotate % count) {\n count -= rotate % count + 1;\n while (count--) { tail = tail.next }\n n.next = node;\n node = tail.next;\n tail.next = undefined;\n }\n }\n return node;\n}\n</code></pre>\n\n<h3>Example B</h3>\n\n<p>Just for fun the next version cuts the list using destructuring. Note that the right side has two values and the left, three. <code>tail.next</code> will automatically be assigned <code>undefined</code>. If I used <code>null</code> I would need the right side to be <code>[node, tail.next, null];</code></p>\n\n<pre><code>function rotateList(node, rotate) {\n var tail = node, n = node, count = 1;\n while (n.next) { n = n.next, count ++ }\n if (rotate % count) {\n count -= rotate % count + 1;\n while (count--) { tail = tail.next }\n [n.next, node, tail.next] = [node, tail.next];\n }\n return node;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T12:04:14.173",
"Id": "426056",
"Score": "0",
"body": "could the algorithm benefit from having both a next and previous pointer? e.g. for huge linked lists, right-rotating 10000000 times might correspond to left-rotating 3 times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T13:56:52.560",
"Id": "426065",
"Score": "0",
"body": "@dfhwze The question indicates that the list is a single linked list not a double linked list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T08:25:44.153",
"Id": "219242",
"ParentId": "219119",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219242",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:06:29.140",
"Id": "219119",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"linked-list",
"ecmascript-6"
],
"Title": "Rotate a linked list to the right by k places"
} | 219119 |
<p>My questions are:</p>
<ol>
<li>How can I improve my implementation of the FSM model?</li>
<li>Should Finite State Machines have functionality for Adding and Removing states from table? (Since I can only be in one state at a time I feel like there's no need for me to store the states when I can just call SetState(state)).</li>
<li>Am I doing the transitions right with SetState(state)? (I feel like I can just handle the transitions inside each States update method. Maybe there's a better way but I'm not sure.)</li>
</ol>
<p>Below is the code that I have these questions about.</p>
<hr>
<h2>Diagram </h2>
<p><img src="https://i.imgur.com/mjXQbMx.png" alt="AI FSM Diagram"></p>
<h2>State Module:</h2>
<pre><code>local State = {}
State.__index = State
function State:New()
local newState = {
Init = function() print("Init ran") end,
Update = function() print("Updating") end,
Enter = function() print("Entering") end,
Exit = function() print("Exiting") end,
}
setmetatable(newState, self)
print("Created new state")
return newState
end
return State
</code></pre>
<h2>StateMachine Module:</h2>
<pre><code>local ReplicatedStorage = game:GetService("ReplicatedStorage")
local State = require(ReplicatedStorage:WaitForChild("State"))
local StateMachine = {}
StateMachine.__index = StateMachine
function StateMachine:Create()
local machine = {}
machine.initState = State:New()
machine.currentState = machine.initState
machine.currentState.Init()
setmetatable(machine, self)
return machine
end
function StateMachine:Update()
if self.currentState ~= nil then
self.currentState:Update()
end
end
function StateMachine:SetState(state)
assert(state ~= nil, "Cannot set a nil state.")
self.currentState:Exit()
self.currentState = state
self.currentState.Init()
self.currentState.Enter()
end
return StateMachine
</code></pre>
<p>Here's the way I'm using my version of a FSM.</p>
<p>Example:</p>
<pre><code>newZombie.stateMachine = StateMachine:Create()
newZombie.idleState = State:New()
newZombie.idleState.Init = function()
print("idle state init")
end
newZombie.idleState.Enter = function()
print("idle state enter!")
end
newZombie.idleState.Update = function()
print("idle state updating!")
if not newZombie.target then
print("Getting target")
newZombie.target = newZombie:GetNearestTarget()
end
if newZombie.zombieTarget then
print("Found target")
newZombie.stateMachine:SetState(newZombie.chaseState)
end
end
newZombie.chaseState = State:New()
newZombie.chaseState.Init = function()
print("chaseState init")
end
newZombie.chaseState.Enter = function()
print("chaseState enter")
end
newZombie.chaseState.Update = function()
print("chaseState updating!")
if newZombie.target then
local direction = (newZombie.target.Position - newZombie.rootPart.Position).Unit * 0.5
local distanceToTarget = (newZombie.target.Position - newZombie.rootPart.Position).magnitude
local MAX_ATTACK_RADIUS = 4
local ray = Ray.new(newZombie.rootPart.Position, (newZombie.target.Position - newZombie.rootPart.Position).Unit * 500)
local ignoreList = {}
for i, v in pairs(ZombiesServerFolder:GetChildren()) do
table.insert(ignoreList, v)
end
local hit, position, normal = Workspace:FindPartOnRayWithIgnoreList(ray, ignoreList)
if not hit.Parent:FindFirstChild("Humanoid") then
print("Walk Path")
end
if distanceToTarget >= MAX_ATTACK_RADIUS then
newZombie.rootPart.CFrame = newZombie.rootPart.CFrame + direction
else
newZombie.stateMachine:SetState(newZombie.attackState)
end
else
newZombie.stateMachine:SetState(newZombie.idleState)
end
end
newZombie.attackState = State:New()
newZombie.attackState.Init = function()
print("attackState init")
end
newZombie.attackState.Enter = function()
print("attackState enter")
end
newZombie.attackState.Update = function()
print("attackState updating!")
if newZombie.target then
local distanceToTarget = (newZombie.target.Position - newZombie.rootPart.Position).magnitude
local MAX_ATTACK_RADIUS = 4
if distanceToTarget >= MAX_ATTACK_RADIUS then
newZombie.stateMachine:SetState(newZombie.chaseState)
end
end
end
----------------------------------------------------
---- STARTING STATE ----
----------------------------------------------------
newZombie.stateMachine:SetState(newZombie.idleState)
----------------------------------------------------
</code></pre>
<p>Also in the NPC update function I'm updating the state machines current state update function.</p>
<pre><code>if self.stateMachine then
self.stateMachine:Update()
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T17:32:30.627",
"Id": "426342",
"Score": "0",
"body": "Shouldn't there be another state between Idle and Chase? Or is 'Find target' guaranteed to deliver the target? In what state should your machine be while it's trying to find the target, you think? It's hardly idle when it's actually on the hunt."
}
] | [
{
"body": "<blockquote>\n <p><em>Am I doing the transitions right with SetState(state)? (I feel like I\n can just handle the transitions inside each States update method.\n Maybe there's a better way but I'm not sure.)</em></p>\n</blockquote>\n\n<p>You allow a state to change the state of its parent state machine. For instance:</p>\n\n<blockquote>\n<pre><code>newZombie.attackState.Update = function()\n ..\n if distanceToTarget >= MAX_ATTACK_RADIUS then \n newZombie.stateMachine:SetState(newZombie.chaseState)\n end\n ..\nend\n</code></pre>\n</blockquote>\n\n<p>Because of this, there is a potential problem with your state transition flow. Nothing prevents a state to change the state of the machine while in Init/Enter/Exit.</p>\n\n<blockquote>\n<pre><code>function StateMachine:SetState(state)\n assert(state ~= nil, \"Cannot set a nil state.\")\n self.currentState:Exit()\n self.currentState = state\n self.currentState.Init()\n self.currentState.Enter()\nend\n</code></pre>\n</blockquote>\n\n<p>For example, if <code>stateB</code> starts a state transition to <code>stateC</code> while in <code>stateA</code> in <code>Enter</code>, the following could happen:</p>\n\n<ul>\n<li>stateA.Exit (ok)</li>\n<li>stateB.Init (ok)</li>\n<li>stateB.Enter (ok)</li>\n<li>stateB.Exit (fishy because in transition, but consistent)</li>\n<li>stateC.Init (fishy because in transition, but consistent)</li>\n<li>stateC.Enter (fishy because in transition, but consistent)</li>\n<li>stateB.Exit (<strong>wrong</strong>, the previous active state gets exited after the current state is activacted)</li>\n</ul>\n\n<p>You can fix this by either: </p>\n\n<ol>\n<li>blocking new state transitions while transitioning</li>\n<li>allowing states to immediately transition to other states while in transition, but then you need to make sure the order of Exit/Init/Enter remains consistent</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T17:15:58.390",
"Id": "220651",
"ParentId": "219120",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:06:29.660",
"Id": "219120",
"Score": "3",
"Tags": [
"state-machine",
"lua"
],
"Title": "Finite state machine for chasing and attacking a target"
} | 219120 |
<p>I have an import macro, which creates ID by concatenating cells, then I compare using VLOOKUP with another sheet if any duplicate found.</p>
<p>It's running very slowly, so I want to know better ways to optimize this code, because once finished, I will need to add another "for" for to handle duplicates found and compare dates. </p>
<p>It's one of my first macros in VBA, so I'm sure there are a lot of ways to improve the performance.</p>
<pre><code>Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim slr As Long
Dim dlr As Long
Dim Tlr As Long
Set wb1 = ActiveWorkbook
FileToOpen = Application.GetOpenFilename _
(Title:="Select import file", _
FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
slr = wb2.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
wb2.Worksheets("Sheet1").Range("A8:S" & slr).Copy _
wb1.Worksheets("INPUT_DATA").Range("A2")
End If
wb2.Close savechanges:=False
dlr = wb1.Worksheets("INPUT_DATA").Cells(Rows.Count, 1).End(xlUp).Row
wb1.Worksheets("INPUT_DATA").Range("A2:S" & dlr).ClearFormats
For cell = 2 To dlr
Cells(cell, 20).Formula = "=CONCAT(RC[-19], ""__"",RC[-18])"
Next
'check duplicate values before import to TOTAL_DATA
Tlr = wb1.Worksheets("TOTAL_DATA").Cells(Rows.Count, 1).End(xlUp).Row
countMatch = 0
countUnmatch = 0
For cell = 2 To dlr
Cells(cell, 21).Formula = "=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), ""No"", ""Yes"")"
If Cells(cell, 21).Value = "Yes" Then
Cells(cell, 20).Font.Color = vbRed
countMatch = countMatch + 1
Else
Range("A" & cell, "T" & cell).Cut Destination:=wb1.Worksheets("TOTAL_DATA").Range("A" & Tlr + 1)
Tlr = Tlr + 1
countUnmatch = countUnmatch + 1
End If
Next cell
If countMatch > 0 Then
MsgBox "Found duplicates!!" & vbCr & "Number of duplicates : " & countMatch & _
vbCr & "Duplicate items were keep at INPUT_DATA" & vbCr & _
"Loaded succesfully : " & countUnmatch & " items", vbExclamation
Else
MsgBox "Loaded succesfully : " & countUnmatch & " items"
End If
End Sub
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T05:52:18.820",
"Id": "423292",
"Score": "0",
"body": "Thanks @200_success for you edit, next question i'll try to do much better! ;)"
}
] | [
{
"body": "<p>This is not a full answer, but it should lead you to the right way:</p>\n\n<pre><code>Option Explicit\nSub ImportData()\n\n Dim wb2 As Workbook\n Dim ws1 As Worksheet 'you can also reference sheets\n Dim ws2 As Worksheet\n Dim slr As Long\n Dim dlr As Long\n Dim Tlr As Long\n Dim arrData 'working with arrays is always better\n Dim i As Long\n Dim DictDuplicates As New Scripting.Dictionary 'You need Microsoft Scripting Runtime for this to work\n\n 'I'm gonna assume you don't have/want formulas on the INPUT_DATA so it will be all values.\n With ThisWorkbook 'always better ThisWorkbook if its the same containing the code\n Set ws1 = .Sheets(\"INPUT_DATA\")\n Set ws2 = .Sheets(\"TOTAL_DATA\")\n End With\n\n 'Lets Store the lookup data in a dictionary so you can check it later\n With ws2\n dlr = .Cells(.Rows.Count, 30).End(xlUp).Row\n For i = 2 To dlr ' I'm assuming the data has headers, if not, change 2 for 1\n 'This may throw an error if your data is duplicated on that sheet\n DictDuplicates.Add .Cells(i, 30), i 'store the value and it's position for later needs\n Next i\n End With\n\n\n FileToOpen = Application.GetOpenFilename _\n (Title:=\"Select import file\", _\n FileFilter:=\"Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm\")\n\n If FileToOpen = False Then\n MsgBox \"No File Specified.\", vbExclamation, \"ERROR\"\n Exit Sub\n Else\n Set wb2 = Workbooks.Open(Filename:=FileToOpen, ReadOnly:=True) 'since you are not writting, open it on ReadOnly to avoid problems\n With wb2.Worksheets(\"Sheet1\")\n slr = .Cells(.Rows.Count, 1).End(xlUp).Row 'You didn't qualified the Rows.Count\n arrData = .Range(\"A8:S\" & slr).Value\n End With\n wb2.Close savechanges:=False\n End If\n\n 'Now you can work on the array\n For i = 2 To UBound(arrData) ' I'm assuming the data copied has headers, if not, change 2 for 1\n If DictDuplicates.Exists(arrData(i, 1) & \"\"\"__\"\"\" & arrData(i, 2)) Then\n 'If the concatenated data exists on the dictionary\n Else\n 'If it doesn't\n\n End If\n Next i\n With ws1\n .Range(.Cells(1, 1), .Cells(UBound(arrData), UBound(arrData, 2))).Value = arrData 'paste the array to the worksheet\n End With\n\nEnd Sub\n</code></pre>\n\n<p>Think of using arrays/dictionaries when working with large amounts of data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T12:00:12.823",
"Id": "219634",
"ParentId": "219122",
"Score": "0"
}
},
{
"body": "<p>This should be twice as fast:</p>\n\n<pre><code>dlr = wb1.Worksheets(\"INPUT_DATA\").Cells(Rows.Count, 1).End(xlUp).Row\nwb1.Worksheets(\"INPUT_DATA\").Range(\"A2:S\" & dlr).ClearFormats\n\n'check duplicate values before import to TOTAL_DATA\n Tlr = wb1.Worksheets(\"TOTAL_DATA\").Cells(Rows.Count, 1).End(xlUp).Row\n countMatch = 0\n countUnmatch = 0\n\nFor cell = 2 To dlr\n Cells(cell, 20).Formula = \"=CONCAT(RC[-19], \"\"__\"\",RC[-18])\"\n\n Cells(cell, 21).Formula = \"=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), \"\"No\"\", \"\"Yes\"\")\"\n If Cells(cell, 21).Value = \"Yes\" Then\n Cells(cell, 20).Font.Color = vbRed\n countMatch = countMatch + 1\n Else\n Range(\"A\" & cell, \"T\" & cell).Cut Destination:=wb1.Worksheets(\"TOTAL_DATA\").Range(\"A\" & Tlr + 1)\n Tlr = Tlr + 1\n countUnmatch = countUnmatch + 1\n End If\nNext cell\n</code></pre>\n\n<p>Because in here we <strong>loop only once</strong> from <code>2 to dlr</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T14:18:31.277",
"Id": "219641",
"ParentId": "219122",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T17:37:35.740",
"Id": "219122",
"Score": "3",
"Tags": [
"performance",
"beginner",
"vba",
"excel",
"join"
],
"Title": "VBA code to import data, doing lookups to detect duplicates"
} | 219122 |
<p>Edit: New version at <a href="https://codereview.stackexchange.com/questions/221361/python-3-tkinter-calculator-follow-up">Python 3 Tkinter Calculator - follow-up</a></p>
<p>New status: I´ve refactored the code trying to follow the recommendations from the guys who answered this question. The new version is on the link above. </p>
<p>I'm a beginner developer and I chose Python as my initial language to learn. This is my very first project: a calculator using Tkinter for GUI.</p>
<p>I've tried to apply some OOP and modules approach, as an attempt to make it like a real job, instead of simply putting it all on a single file or procedural mode.</p>
<p>I need some feedback about module naming and organization, class naming and organization, PEP-8 style, and structure in general.</p>
<h3>Module: window.py</h3>
<p>This should be the main module, but I´m facing some circular import issue that I can't figure why yet.</p>
<pre><code>import tkinter as tk
import frame_display
import frame_botoes
root = tk.Tk()
root.geometry("640x640")
visor = frame_display.DisplayContainer(root)
numeros = frame_botoes.ButtonsContainer(root)
root.mainloop()
</code></pre>
<h3>Module: calculadora.py</h3>
<p>I made some sort of workaround and the programs runs here:</p>
<pre><code>agregator = ""
result = ""
def pressNumber(num):
global agregator
global result
agregator = agregator + str(num)
result = agregator
window.visor.updateTextDisplay(result)
def pressEqual():
try:
global agregator
total = str(eval(agregator))
window.visor.updateTextDisplay(total)
agregator = ""
except ZeroDivisionError:
window.visor.updateTextDisplay("Erro: Divisão por zero")
agregator = ""
except:
window.visor.updateTextDisplay("Error")
agregator = ""
def pressClear():
global agregator
agregator = ""
window.visor.updateTextDisplay("Clear")
import window
</code></pre>
<p>I tried to use separate modules and classes as an attempt to use good practices.</p>
<h3>Module: frame_display.py</h3>
<pre><code>import tkinter as tk
from tkinter import Frame
from tkinter import StringVar
class DisplayContainer(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.parent = root
self.configure(bg="cyan", height=5)
self.text_display = StringVar()
# Layout DisplayContainer
self.grid(row=0 , column=0 , sticky="nwe")
self.parent.columnconfigure(0, weight=1)
# Call DisplayContainer widgets creation
self.createWidgets()
# Create widgets for DisplayContainer
def createWidgets(self):
self.label_display = tk.Label(self)
self.label_display.configure(textvariable=self.text_display)
self.label_display["font"] = 15
self.label_display["bg"] = "#bebebe"
self.label_display["relief"] = "groove"
self.label_display["bd"] = 5
self.label_display["height"] = 5
# Layout widgets for DisplayContainer
self.label_display.grid(row=0 , column=0 , sticky="nswe")
self.columnconfigure(0, weight=1)
def updateTextDisplay(self, text):
self.text_display.set(text)
</code></pre>
<h3>Module: frame_botoes.py</h3>
<pre><code>import tkinter as tk
from tkinter import Frame
import calculadora
class ButtonsContainer(Frame):
def __init__(self , root):
Frame.__init__(self, root)
self.parent = root
self.configure(bg="yellow")
self.parent.bind("<Key>", self.keyHandler)
self.parent.bind("<Return>", self.returnKeyHandler)
# Layout ButtonsContainer
self.grid(row=1 , column=0 , sticky ="nsew")
self.parent.rowconfigure(1, weight=1)
self.parent.columnconfigure(0, weight=1)
# Call ButtonsContainer widgets creation
self.createWidgets()
# Create widgets for ButtonsContainer
def createWidgets(self):
button_padx = 15
button_pady = 15
self.button_1 = tk.Button(self, text="1", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(1))
self.button_2 = tk.Button(self, text="2", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(2))
self.button_3 = tk.Button(self, text="3", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(3))
self.button_4 = tk.Button(self, text="4", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(4))
self.button_5 = tk.Button(self, text="5", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(5))
self.button_6 = tk.Button(self, text="6", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(6))
self.button_7 = tk.Button(self, text="7", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(7))
self.button_8 = tk.Button(self, text="8", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(8))
self.button_9 = tk.Button(self, text="9", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(9))
self.button_0 = tk.Button(self, text="0", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(0))
self.button_open_parens = tk.Button(self, text="(", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("("))
self.button_close_parens = tk.Button(self, text=")", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(")"))
self.button_dot = tk.Button(self, text=".", padx= button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("."))
self.button_plus = tk.Button(self, text="+", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("+"))
self.button_minus = tk.Button(self, text="-", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("-"))
self.button_multiply = tk.Button(self, text="*", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("*"))
self.button_divide = tk.Button(self, text="/", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber("/"))
self.button_equal = tk.Button(self, text="=", padx=button_padx, pady=button_pady, command=calculadora.pressEqual)
self.button_clear = tk.Button(self, text="CLEAR", padx=button_padx, pady=button_pady, command=calculadora.pressClear)
# Layout widgets for ButtonsContainer
self.button_1.grid(row=0, column=0, sticky="nswe")
self.button_2.grid(row=0, column=1, sticky="nswe")
self.button_3.grid(row=0, column = 2, sticky="nswe")
self.button_4.grid(row=1, column=0, sticky="nswe")
self.button_5.grid(row=1, column=1, sticky="nswe")
self.button_6.grid(row=1, column=2, sticky="nswe")
self.button_7.grid(row=2, column=0, sticky="nswe")
self.button_8.grid(row=2, column=1, sticky="nswe")
self.button_9.grid(row=2, column=2, sticky="nswe")
self.button_open_parens.grid(row=3, column=0, sticky="nswe")
self.button_close_parens.grid(row=3, column=2, sticky="nswe")
self.button_0.grid(row=3, column=1, sticky="nswe")
self.button_dot.grid(row=4, column=2, sticky="nswe")
self.button_plus.grid(row=0 , column=3, sticky="nswe")
self.button_minus.grid(row=1 , column=3, sticky="nswe")
self.button_multiply.grid(row=2 , column=3, sticky="nswe")
self.button_divide.grid(row=3 , column=3, sticky="nswe")
self.button_equal.grid(row=4 , column=3, sticky="nswe")
self.button_clear.grid(row=4 , columnspan=2, sticky="nswe")
for x in range(0,5):
self.rowconfigure(x, weight=1)
for i in range(0, 4):
self.columnconfigure(i, weight=1)
#Bind keyboard events
def keyHandler(self, event):
calculadora.pressNumber(event.char)
#Bind Return key
def returnKeyHandler(self, event):
calculadora.pressEqual()
</code></pre>
| [] | [
{
"body": "<p>Disclaimer: you should not be using <code>eval</code> that said I am not going to be removing it from the code as you can work out the correct options on your own. I will be reviewing the overall code issues. Just know <code>eval</code> is evil! :D</p>\n\n<p>Ok so quick answer to fix the main problem is to add a new argument to all functions in <code>calculadora.py</code> lets call this argument <code>window</code> because we are passing the the root window to each function.</p>\n\n<p>Then you need to build the root window as a class with class attributes. This way your functions in calculadora can actually update the the fields.</p>\n\n<p>Once we changed those 2 parts we need to pass that window to those functions from the <code>frame_botoes.py</code> buttons so we will update those buttons as well.</p>\n\n<p>Updated <code>window.py</code>:</p>\n\n<p>import tkinter as tk\nimport frame_display\nimport frame_botoes</p>\n\n<pre><code>class Main(tk.Tk):\n def __init__(self):\n super().__init__()\n self.geometry(\"640x640\")\n self.visor = frame_display.DisplayContainer(self)\n self.numeros = frame_botoes.ButtonsContainer(self)\n\nMain().mainloop()\n</code></pre>\n\n<p>Updated <code>calculadora.py</code>:</p>\n\n<pre><code>agregator = \"\"\nresult = \"\"\n\n\ndef pressNumber(num, window):\n global agregator\n global result\n agregator = agregator + str(num)\n result = agregator\n window.visor.updateTextDisplay(result)\n\n\ndef pressEqual(window):\n try:\n global agregator\n total = str(eval(agregator))\n window.visor.updateTextDisplay(total)\n agregator = \"\"\n except ZeroDivisionError:\n window.visor.updateTextDisplay(\"Erro: Divisão por zero\")\n agregator = \"\"\n except:\n window.visor.updateTextDisplay(\"Error\")\n agregator = \"\"\n\ndef pressClear(window):\n global agregator\n agregator = \"\"\n window.visor.updateTextDisplay(\"Clear\")\n</code></pre>\n\n<p>Updated <code>frame_botoes.py</code>:</p>\n\n<pre><code>import tkinter as tk\nfrom tkinter import Frame\nimport calculadora\n\n\nclass ButtonsContainer(Frame):\n\n def __init__(self , root):\n Frame.__init__(self, root)\n self.parent = root\n self.configure(bg=\"yellow\")\n self.parent.bind(\"<Key>\", self.keyHandler)\n self.parent.bind(\"<Return>\", self.returnKeyHandler)\n\n\n # Layout ButtonsContainer\n self.grid(row=1 , column=0 , sticky =\"nsew\")\n self.parent.rowconfigure(1, weight=1)\n self.parent.columnconfigure(0, weight=1)\n\n # Call ButtonsContainer widgets creation\n self.createWidgets()\n\n\n # Create widgets for ButtonsContainer\n def createWidgets(self):\n\n button_padx = 15\n button_pady = 15\n\n self.button_1 = tk.Button(self, text=\"1\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(1, self.parent))\n self.button_2 = tk.Button(self, text=\"2\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(2, self.parent))\n self.button_3 = tk.Button(self, text=\"3\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(3, self.parent))\n self.button_4 = tk.Button(self, text=\"4\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(4, self.parent))\n self.button_5 = tk.Button(self, text=\"5\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(5, self.parent))\n self.button_6 = tk.Button(self, text=\"6\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(6, self.parent))\n self.button_7 = tk.Button(self, text=\"7\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(7, self.parent))\n self.button_8 = tk.Button(self, text=\"8\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(8, self.parent))\n self.button_9 = tk.Button(self, text=\"9\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(9, self.parent))\n self.button_0 = tk.Button(self, text=\"0\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(0, self.parent))\n\n self.button_open_parens = tk.Button(self, text=\"(\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\"(\", self.parent))\n self.button_close_parens = tk.Button(self, text=\")\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\")\", self.parent))\n\n\n self.button_dot = tk.Button(self, text=\".\", padx= button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\".\", self.parent))\n self.button_plus = tk.Button(self, text=\"+\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\"+\", self.parent))\n self.button_minus = tk.Button(self, text=\"-\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\"-\", self.parent))\n self.button_multiply = tk.Button(self, text=\"*\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\"*\", self.parent))\n self.button_divide = tk.Button(self, text=\"/\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(\"/\", self.parent))\n self.button_equal = tk.Button(self, text=\"=\", padx=button_padx, pady=button_pady, command=calculadora.pressEqual(self.parent))\n self.button_clear = tk.Button(self, text=\"CLEAR\", padx=button_padx, pady=button_pady, command=calculadora.pressClear(self.parent))\n\n # Layout widgets for ButtonsContainer\n self.button_1.grid(row=0, column=0, sticky=\"nswe\")\n self.button_2.grid(row=0, column=1, sticky=\"nswe\")\n self.button_3.grid(row=0, column = 2, sticky=\"nswe\")\n self.button_4.grid(row=1, column=0, sticky=\"nswe\")\n self.button_5.grid(row=1, column=1, sticky=\"nswe\")\n self.button_6.grid(row=1, column=2, sticky=\"nswe\")\n self.button_7.grid(row=2, column=0, sticky=\"nswe\")\n self.button_8.grid(row=2, column=1, sticky=\"nswe\")\n self.button_9.grid(row=2, column=2, sticky=\"nswe\")\n\n self.button_open_parens.grid(row=3, column=0, sticky=\"nswe\")\n self.button_close_parens.grid(row=3, column=2, sticky=\"nswe\")\n\n self.button_0.grid(row=3, column=1, sticky=\"nswe\")\n self.button_dot.grid(row=4, column=2, sticky=\"nswe\")\n self.button_plus.grid(row=0 , column=3, sticky=\"nswe\")\n self.button_minus.grid(row=1 , column=3, sticky=\"nswe\")\n self.button_multiply.grid(row=2 , column=3, sticky=\"nswe\")\n self.button_divide.grid(row=3 , column=3, sticky=\"nswe\")\n\n self.button_equal.grid(row=4 , column=3, sticky=\"nswe\")\n self.button_clear.grid(row=4 , columnspan=2, sticky=\"nswe\")\n\n for x in range(0,5):\n self.rowconfigure(x, weight=1)\n\n for i in range(0, 4):\n self.columnconfigure(i, weight=1)\n\n #Bind keyboard events\n def keyHandler(self, event):\n calculadora.pressNumber(event.char, self.parent)\n\n #Bind Return key\n def returnKeyHandler(self, event):\n calculadora.pressEqual()\n</code></pre>\n\n<p>Now that the quick fix is dealt with its time to go in depth as to the other formatting issues and PEP8 changes we should make.</p>\n\n<p>I will keep each one of your files separate but honestly I do not think it is necessary to separate the main window file from the frame data.</p>\n\n<p>1st: I would like to address is PEP8 standards. Personally I think you should use CamelCase for Class names and lowercase_with_underscores for functions/methods.</p>\n\n<p>2nd: Lets look at your buttons in <code>frame_botoes</code>. You should probably be generating your buttons with loops so we can keep the code short and clean. I have 2 examples here. One uses simple counting for the layout and the other uses a list with grid values for placement.</p>\n\n<p>3rd: We should avoid using <code>global</code> so lets convert your calculadora functions into a class that we use with class attribute to manage the <code>aggregator</code>.</p>\n\n<p>4th: You only need <code>self.</code> prefix for a variable that will be changed later in the class outside of the method it is generated in. So for all your buttons we can remove this prefix. At the same time we don't need to name them as we are generating them from a loop. Naming doesn't help us here as the layout is simple enough and we are not changing the buttons later.</p>\n\n<p>5th: We do not need <code>from tkinter import Frame</code> as you are already using <code>import tkinter as tk</code> so we can simply call <code>tk.Frame</code> or any other widget for that matter where it is needed.</p>\n\n<p>With some general clean up and the things I mentioned above here is your modified code:</p>\n\n<p>New <code>window.py</code>:</p>\n\n<pre><code>import tkinter as tk\nimport frame_display\nimport frame_botoes\n\n\nclass Main(tk.Tk):\n def __init__(self):\n super().__init__()\n self.geometry(\"640x640\")\n self.columnconfigure(0, weight=1)\n self.rowconfigure(1, weight=1)\n self.visor = frame_display.DisplayContainer().grid(row=0, column=0, sticky=\"new\")\n self.numeros = frame_botoes.ButtonsContainer().grid(row=1, column=0, sticky=\"nsew\")\n\nMain().mainloop()\n</code></pre>\n\n<p>New <code>calculadora.py</code>:</p>\n\n<pre><code>class Press:\n def __init__(self, master):\n self.master = master\n self.aggregator = ''\n\n def num(self, n):\n self.aggregator += str(n)\n self.master.visor.update_text_display(self.aggregator)\n\n def equal(self, _):\n try:\n total = str(eval(self.aggregator))\n self.aggregator = ''\n self.master.visor.text_display.set(total)\n except ZeroDivisionError:\n self.master.visor.text_display.set(\"Error: Divisão por zero\")\n except:\n self.master.visor.text_display.set(\"Unexpected error\")\n raise\n\n def clear(self):\n self.master.visor.text_display.set(\"Clear\")\n</code></pre>\n\n<p>New <code>frame_display.py</code>:</p>\n\n<pre><code>import tkinter as tk\n\n\nclass DisplayContainer(tk.Frame):\n def __init__(self):\n super().__init__()\n self.configure(bg=\"cyan\", height=5)\n self.columnconfigure(0, weight=1)\n self.txt = tk.StringVar()\n\n label_display = tk.Label(self, textvariable=self.txt, font=15, bg=\"#bebebe\", relief=\"groove\", bd=5, height=5)\n label_display.grid(row=0, column=0, sticky=\"nsew\")\n\n def update_text_display(self, text):\n self.text_display.set(text)\n</code></pre>\n\n<p>New <code>frame_botoes.py</code>:</p>\n\n<pre><code>import tkinter as tk\nimport calculadora\n\n\nclass ButtonsContainer(tk.Frame):\n def __init__(self):\n super().__init__()\n self.configure(bg=\"yellow\")\n self.screen = calculadora.Press(self.master)\n self.master.bind(\"<Key>\", self.key_handler)\n self.master.bind(\"<Return>\", self.screen.equal)\n for x in range(0, 5):\n self.rowconfigure(x, weight=1)\n if x < 4:\n self.columnconfigure(x, weight=1)\n\n pad = 15\n r = 0\n c = 0\n for i in range(10):\n if i == 0:\n tk.Button(self, text=i, padx=pad, pady=pad,\n command=lambda n=i: self.screen.num(n)).grid(row=3, column=1, sticky=\"nswe\")\n else:\n tk.Button(self, text=i, padx=pad, pady=pad,\n command=lambda n=i: self.screen.num(n)).grid(row=r, column=c, sticky=\"nswe\")\n if c == 2:\n c = 0\n r += 1\n else:\n c += 1\n\n for i in [[\"-\", 1, 3], [\"*\", 2, 3], [\"/\", 3, 3], [\"(\", 3, 0],\n [\")\", 3, 2], [\".\", 4, 2], [\"+\", 0, 3], [\"=\", 4, 3], [\"CLEAR\", 4, 0]]:\n if i[0] == 'CLEAR':\n tk.Button(self, text=i[0], padx=pad, pady=pad,\n command=self.screen.clear).grid(row=i[1], column=i[2], columnspan=2, sticky=\"nsew\")\n elif i[0] == '=':\n tk.Button(self, text=i[0], padx=pad, pady=pad,\n command=self.screen.equal).grid(row=i[1], column=i[2], sticky=\"nsew\")\n else:\n tk.Button(self, text=i[0], padx=pad, pady=pad,\n command=lambda v=i[0]: self.screen.num(v)).grid(row=i[1], column=i[2], sticky=\"nsew\")\n\n def key_handler(self, event):\n self.screen.num(event.char)\n</code></pre>\n\n<p>If you have any questions let me know :D</p>\n\n<p>Just for fun here is how I would have build this calc.\nIts a small enough program I think most if not all is fine in a single class. Also by placing everything in a single class we can avoid a lot of the back and forth going on and keep our code simple. By doing this we took your roughly 180+ lines of code and reduced them to around 80+ lines of code.</p>\n\n<p>My example:</p>\n\n<pre><code>import tkinter as tk\n\n\nclass Main(tk.Tk):\n def __init__(self):\n super().__init__()\n self.geometry(\"640x640\")\n self.columnconfigure(0, weight=1)\n self.rowconfigure(1, weight=1)\n self.aggregator = ''\n self.txt = tk.StringVar()\n self.bind(\"<Key>\", self.key_handler)\n self.bind(\"<Return>\", self.equal)\n\n dis_frame = tk.Frame(self)\n dis_frame.grid(row=0, column=0, sticky=\"new\")\n btn_frame = tk.Frame(self)\n btn_frame.grid(row=1, column=0, sticky=\"nsew\")\n\n dis_frame.configure(bg=\"cyan\", height=5)\n dis_frame.columnconfigure(0, weight=1)\n\n for x in range(0, 5):\n btn_frame.rowconfigure(x, weight=1)\n if x < 4:\n btn_frame.columnconfigure(x, weight=1)\n\n self.display = tk.Label(dis_frame, textvariable=self.txt, font=15,\n bg=\"#bebebe\", relief=\"groove\", bd=5, height=5)\n self.display.grid(row=0, column=0, sticky=\"nsew\")\n\n pad = 15\n r = 0\n c = 0\n for i in range(10):\n if i == 0:\n tk.Button(btn_frame, text=i, padx=pad, pady=pad,\n command=lambda n=i: self.num(n)).grid(row=3, column=1, sticky=\"nswe\")\n else:\n tk.Button(btn_frame, text=i, padx=pad, pady=pad,\n command=lambda n=i: self.num(n)).grid(row=r, column=c, sticky=\"nswe\")\n if c == 2:\n c = 0\n r += 1\n else:\n c += 1\n\n for i in [[\"-\", 1, 3], [\"*\", 2, 3], [\"/\", 3, 3], [\"(\", 3, 0],\n [\")\", 3, 2], [\".\", 4, 2], [\"+\", 0, 3], [\"=\", 4, 3], [\"CLEAR\", 4, 0]]:\n if i[0] == 'CLEAR':\n tk.Button(btn_frame, text=i[0], padx=pad, pady=pad,\n command=self.clear).grid(row=i[1], column=i[2], columnspan=2, sticky=\"nsew\")\n elif i[0] == '=':\n tk.Button(btn_frame, text=i[0], padx=pad, pady=pad,\n command=self.equal).grid(row=i[1], column=i[2], sticky=\"nsew\")\n else:\n tk.Button(btn_frame, text=i[0], padx=pad, pady=pad,\n command=lambda v=i[0]: self.num(v)).grid(row=i[1], column=i[2], sticky=\"nsew\")\n\n def key_handler(self, event):\n self.num(event.char)\n\n def num(self, n):\n self.aggregator += str(n)\n self.txt.set(self.aggregator)\n\n def equal(self, event=None):\n try:\n total = str(eval(self.aggregator))\n self.txt.set(total)\n self.aggregator = total\n except ZeroDivisionError:\n self.txt.set(\"Error: Divisão por zero\")\n except:\n self.txt.set(\"Unexpected error\")\n raise\n\n def clear(self):\n self.txt.set(\"Clear\")\n self.aggregator = ''\n\nMain().mainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:24:01.187",
"Id": "424813",
"Score": "0",
"body": "wow, didn´t know about eval being problematic... it seemed so convenient, as the user could make expressions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:26:32.880",
"Id": "424814",
"Score": "0",
"body": "I really wanted to put some 'put things separated' approach, but now I realized that it turned to be a back and forth circular code..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T20:44:48.573",
"Id": "424824",
"Score": "1",
"body": "@BrunoLemos it is super convenient and that is why it is evil :D It can make your code vulnerable to attack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:41:15.603",
"Id": "424889",
"Score": "0",
"body": "oh, I see... some kind of injection, isn´t it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T13:54:51.073",
"Id": "424890",
"Score": "1",
"body": "@BrunoLemos yes it is vulnerable to injection, it is also slow compared to better methods and it can make debugging issue difficult."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:11:53.030",
"Id": "424892",
"Score": "0",
"body": "I see that I should join the display and buttons frames in one single module, as well as the window and main code in another one. It would be better this way? Like: widgets module (with display and buttons frames) and main module (with calculator logic class and tk window class)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:25:34.223",
"Id": "424898",
"Score": "1",
"body": "@BrunoLemos it doesnt hurt to have the display separate. You may want to keep them separate just in case you want to make a transforming calculator. Like switching between normal and scientific mode. If you have no need to move the display or other widgets later then the extra frame is not needed but doesnt really cause any issues here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T18:38:57.827",
"Id": "424954",
"Score": "0",
"body": "Is a good option to structure my frame classes by separating creation, arrangement and key binding in separate functions? Like: def create_widgets(), def arrange_widgets and def bind_keys() ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T19:43:42.877",
"Id": "424960",
"Score": "1",
"body": "@BrunoLemos You don't want to over write your code. If there is not a good reason to build a function all you are doing is adding unwanted complexity. Just try to keep things short and readable. the PEP8 guidelines is something you should read. It will provide some good references."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:35:24.240",
"Id": "428031",
"Score": "0",
"body": "I refactored the code. Should I open a new topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T19:03:43.217",
"Id": "428035",
"Score": "1",
"body": "@BrunoLemos I would. By changing the code you end up changing what the review would look like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:35:56.807",
"Id": "429210",
"Score": "0",
"body": "It would be bad send you this new version? https://codereview.stackexchange.com/questions/221361/python-3-tkinter-calculator-follow-up"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:21:35.473",
"Id": "219194",
"ParentId": "219124",
"Score": "4"
}
},
{
"body": "<p>Welcome to CodeReview! And welcome to coding! Publishing and reviewing your code is\none of the best ways to get better at coding. And we're going to make you better, no matter how much it hurts. ;-)</p>\n\n<p>First, congratulations! You've written a fair amount of code in a single project, and you managed to produce a somewhat complex app, with graphics, alternative input, event handling, etc. This is a pretty ambitious first project.</p>\n\n<p>I have some suggestions about the organization and structure, and the coding style.</p>\n\n<h2>Organization and Structure</h2>\n\n<h3>Modules</h3>\n\n<p>You have too many modules. A good starting rule for breaking code into different modules is this: always put everything in one file. By the time you need to break that\nrule, you'll know what and how and when to break it. For now, you don't need to break it -- just put everything into <code>calculadora.py</code>.</p>\n\n<p>On a side note, the fact that you were importing a module at the <em>bottom</em> of one of\nyour files instead of at the top is a sign that you should merge the modules together if possible. Needing to do that kind of thing should set off your internal alarms\nthat something is wrong.</p>\n\n<h3>Functions</h3>\n\n<p>There are three good reasons to create a function: (1) to standardize operations that you perform more than one time; (2) to \"abstract away\" low-level operations to a separate layer; (3) to isolate a valuable operation for re-use.</p>\n\n<p>Reason #3 is generally rare. But you aren't doing enough of #1 and #2. Consider this:</p>\n\n<pre><code>root = tk.Tk()\nroot.geometry(\"640x640\")\nvisor = frame_display.DisplayContainer(root)\nnumeros = frame_botoes.ButtonsContainer(root)\nroot.mainloop()\n</code></pre>\n\n<p>The first four lines of that block \"create the application\". The fifth line \"runs the application\". You might put that in a class, if you have learned classes yet. Otherwise, just put that into two functions:</p>\n\n<pre><code>app = create_application()\nrun_application(app)\n</code></pre>\n\n<p>Or consider this code:</p>\n\n<pre><code>self.button_1 = tk.Button(self, text=\"1\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(1))\nself.button_2 = tk.Button(self, text=\"2\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(2))\nself.button_3 = tk.Button(self, text=\"3\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(3))\nself.button_4 = tk.Button(self, text=\"4\", padx=button_padx, pady=button_pady, command=lambda: calculadora.pressNumber(4))\n</code></pre>\n\n<p>There are more lines of this (5..0), but these four are enough to make the point: this is a repeated operation and could be a function!</p>\n\n<p>What's more, these lines appear lower down:</p>\n\n<pre><code>self.button_1.grid(row=0, column=0, sticky=\"nswe\")\nself.button_2.grid(row=0, column=1, sticky=\"nswe\")\nself.button_3.grid(row=0, column = 2, sticky=\"nswe\")\nself.button_4.grid(row=1, column=0, sticky=\"nswe\")\n</code></pre>\n\n<p>These lines are \"in parallel\" with the button creation lines above. So they could be part of the same method. Let's try:</p>\n\n<pre><code>def make_button(self, text, row, column):\n new_button = tk.Button(self, text=text, padx=self.BUTTON_PADX, pady=self.BUTTON_PADY,\n command=lambda: press_button(text))\n new_button.grid(row=row, column=column, sticky=self.BUTTON_STICKY)\n self.buttons.append(new_button)\n</code></pre>\n\n<p>Then you could replace a lot of that text with something like:</p>\n\n<pre><code>self.make_button('1', 0, 0)\nself.make_button('2', 0, 1)\nself.make_button('3', 0, 2)\nself.make_button('4', 1, 0)\nself.make_button('5', 1, 1)\n</code></pre>\n\n<h3>Pro-tip: Visual Organization</h3>\n\n<p>When you're writing code, it's important to communicate to the <em>next guy</em>\nwhat you are trying to do. Sometimes the next guy is \"future you\" who will be reading this a year from now. Sometimes the next guy is another junior developer that will take over your project when you get promoted. But there's almost always going to be a \"next guy\" and your code is really written for him or her, more than for the compiler.</p>\n\n<p>One trick you can use is to visually organize things. Then you will write code that \"decodes\" the visual organization. It's worth spending 15 minutes to make life easy for yourself, or for the next guy. Things like putting configuration into a docstring and parsing the string instead of putting 10 different values in separate quotation marks.</p>\n\n<p>You could do something like this:</p>\n\n<pre><code>button_layout = \"\"\"\n 1 2 3 +\n 4 5 6 -\n 7 8 9 *\n ( 0 ) /\n CCC . =\n\"\"\".strip('\\n').splitlines()\n\nfor row, line in enumerate(button_layout):\n extra_col = 0\n\n for col, ch in enumerate(line.split()):\n if ch == 'CCC':\n self.make_clear_button(row, col)\n extra_col = 1\n else:\n self.make_button(ch, row, col + extra_col)\n\nself.num_rows = row + 1\nself.num_cols = col + 1\n</code></pre>\n\n<p>This would let you visually arrange the keys in different shapes, and the code would \"figure out\" where to put the buttons, and how many rows and columns were present.</p>\n\n<p>Note that doing this provides <em>absolutely no value</em> to your program. The buttons are going to be created no matter what. But it lets you explore different shapes for the window just by moving characters around, and it lets the \"next guy\" see and understand how the buttons are arranged in a way that 30+ lines of <code>row=3, col=0 ... row=4, col=2</code> just cannot do.</p>\n\n<h2>Coding Style</h2>\n\n<h3>PEP-8</h3>\n\n<p>The official Python coding style document is <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. You may have learned a different style from reading code written in Java or some other language. But you're going to be considered \"out of spec\" if you deviate from PEP-8.</p>\n\n<p>That said, PEP-8 contains a lot of good advice for beginning coders. It's a fairly well-reasoned document, with just a few things that are totally wrong (IMO). But I\nignore those things in favor of having a common standard, and you should too. Conform!</p>\n\n<p>To quickly summarize:</p>\n\n<ul>\n<li><p>Use <code>snake_case</code> for all names except classes. Classes are <code>PascalCase</code> just like every other language.</p></li>\n<li><p>Use <code>ALL_CAPS</code> for \"constants\". If a class or object has an all-caps attribute,\nthen it's a class constant or an object constant. If a module has an all-caps variable at the top, it's a module constant. This despite the fact of <code>math.pi</code> and <code>math.e</code> and <code>math.tau</code>. \"Do as we say, not as we do.\" :-)</p></li>\n</ul>\n\n<h3>Importing names</h3>\n\n<p>You can import names from a module using <code>from module import name</code>. Or you can import a module and refer to <code>module.name</code> instead. You should choose the style based on\nclarity and frequency of use.</p>\n\n<p>For some reason, you do this:</p>\n\n<pre><code>from tkinter import Frame\nfrom tkinter import StringVar\n</code></pre>\n\n<p>Then you make use of <code>Frame</code> and <code>StringVar</code> 4 + 1 times, respectively. On the other hand, you <em>don't</em> import <code>Button</code> but refer to <code>tk.Button</code> 25 times!</p>\n\n<p>I suggest that your default should be to not import any names explicitly, and to prefer to spell out the <code>module.name</code> form. It's okay to abbreviate the module name, which you do (<code>tkinter</code> -> <code>tk</code>):</p>\n\n<pre><code>import tkinter as tk\n\nclass DisplayContainer(tk.Frame):\n def __init__(...):\n ...\n self.text_display = tk.StringVar()\n</code></pre>\n\n<p>Then if you find yourself repeating <code>tk.Button</code> 25 times (which you should not: see\nthe note about functions above) you can do an additional import of that one name. Or you could just stash it in a local variable if every occurrence is within the same\nfunction:</p>\n\n<pre><code>button = tk.Button\nthis = button(...)\nthat = button(...)\nanother = button(...)\n</code></pre>\n\n<h3>Comments</h3>\n\n<p>If your comment says in English (or Portuguese!) the same thing the code says in Python, delete the comment. Don't do this:</p>\n\n<pre><code># Call ButtonsContainer widgets creation\nself.createWidgets()\n</code></pre>\n\n<p>Comments should explain:</p>\n\n<ul>\n<li><p>Details that come from the problem domain</p>\n\n<pre><code># Per tax code, deduction does not apply if children > 12 yrs old\n</code></pre></li>\n<li><p>Code constructs that are particularly dense or complex (particularly: nested comprehensions in Python)</p>\n\n<pre><code># Flatten list-of-lists, ignoring short names.\nall_planets = [planet for sublist in planets for planet in sublist if len(planet) < 6]\n</code></pre></li>\n<li><p>Things that are not obvious from the code, including side effects.</p>\n\n<pre><code># Note: this call flushes stdout\n</code></pre></li>\n<li><p>Things that are missing.</p>\n\n<pre><code># Note: NOT calling end_row() here!\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:41:58.493",
"Id": "424903",
"Score": "0",
"body": "thanks!!! I´ll refactor my code best as possible. Some tips are still a bit hard for me, as the button layout block you suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:44:30.337",
"Id": "424904",
"Score": "0",
"body": "Is a good option to structure my frame classes by separating creation, arrangement and key binding in separate functions? Like: def create_widgets(), def arrange_widgets and def bind_keys() ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:50:55.143",
"Id": "424980",
"Score": "1",
"body": "@BrunoLemos I would say no, because separating `create_widgets` and `arrange_widgets` doesn't provide much value. Do you *need* to have creation and arrangement separate? I don't thing so. But doing that means you have two functions, each of which probably has 25 lines, since I think there are 25 buttons? That means 50 lines of code and the information about buttons is in two different locations (button labels and callbacks are in one function, button positioning is in a different function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T22:52:52.287",
"Id": "424981",
"Score": "2",
"body": "@BrunoLemos (cont'd) I think it makes more sense to have one function that does \"everything for a button\", and call that function 25 times. Then you have 30-ish lines of code (5 lines of function plus 25 calls) and all the information about a given button is in one place - the call to the function where the parameters are all in line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T19:09:30.540",
"Id": "427006",
"Score": "0",
"body": "can you talk more about \" to \"abstract away\" low-level operations to a separate layer\"? I didn´t get this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T19:13:20.167",
"Id": "427008",
"Score": "0",
"body": "I didn´t understand the \"self.num_rows = row + 1\" and \"self.num_cols = col + 1\" at the button layout part... are they outside the first for loop? Could you explain the entire process of this part?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T21:26:50.050",
"Id": "427035",
"Score": "1",
"body": "@BrunoLemos Suppose you have a function that opens a file, processes the contents, and closes the file. You could call `open()` directly, or you could \"abstract away\" the low-level open call and write a function named `read_data()` that would return the data. Sometimes it makes sense to have a \"simple\" function like `read_data` so that you can write code like `read_data(); process_data(); write_data()` instead of mixing the abstraction levels like `f = open(); data = read(f); process_data(data); write_data()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T21:30:44.547",
"Id": "427037",
"Score": "1",
"body": "`self.num_rows` (&cols) are counts, which are 1-based. So they are 1 higher than the highest value returned by `enumerate`, which is 0-based. Thus, if you `enumerate(['a', 'b'])` you will get `(0, 'a')` and `(1, 'b')`, but the `num_items` should be *two* rather than *one*. So I added one outside the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:38:03.103",
"Id": "429212",
"Score": "0",
"body": "Could you take a look at the new version? https://codereview.stackexchange.com/questions/221361/python-3-tkinter-calculator-follow-up"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T03:34:22.993",
"Id": "219229",
"ParentId": "219124",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T18:23:24.053",
"Id": "219124",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"calculator",
"tkinter"
],
"Title": "Calculator in Python 3 using Tkinter"
} | 219124 |
<p>I wrote a macro that is taking 20+ minutes to run on other computers, but when I run it on mine it only takes 5 mins. It is a larger macro and I am new to the VBA coding world. I was wondering if I could condense it down so that it can run faster not only for my computer but other computers too. </p>
<p>The purpose of my macro is to take multiple sheets in one workbook and consolidate them into one sheet in the same workbook that I titled as "Consolidated". A problem with the Excel file is that some columns are left blank or the title of the columns are different from other sheets that I am copying and pasting to the master sheet, so I added an <code>iferror</code> to sheets that have blank cells so that I can use the end down function in the final part of the macro where I copy each column from each sheet into the master consolidation sheet. If you need to explain better please let me know.</p>
<pre><code>Sub Macro1()
Dim i As Integer
Dim r As Long, c As Long
Application.ScreenUpdating = False
Sheets("CIP Summary").Select
Sheets.Add
ActiveSheet.Name = "Consolidated"
ActiveCell.FormulaR1C1 = "Company"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Location"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Store"
Range("D1").Select
ActiveCell.FormulaR1C1 = "RCT/Voucher"
Range("E1").Select
ActiveCell.FormulaR1C1 = "Vendor"
Range("F1").Select
ActiveCell.FormulaR1C1 = "Vendor Name"
Range("G1").Select
ActiveCell.FormulaR1C1 = "Date"
Range("H1").Select
ActiveCell.FormulaR1C1 = "Reference"
Range("I1").Select
ActiveCell.FormulaR1C1 = "Amount"
Range("J1").Select
ActiveCell.FormulaR1C1 = "Period"
Range("K1").Select
ActiveCell.FormulaR1C1 = "JE"
Range("L1").Select
ActiveCell.FormulaR1C1 = "Project"
Range("M1").Select
ActiveCell.FormulaR1C1 = "Expected Open Date"
Range("N1").Select
ActiveCell.FormulaR1C1 = "Comment"
Range("N1").Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.Font.Bold = True
For i = 15 To Worksheets.Count
For c = 1 To 14
For r = 5 To 1000
If IsError(Sheets(i).Cells(r, c)) Then
Sheets(i).Cells(r, c).Value = "N/A"
ElseIf Sheets(i).Cells(r, c) = "" Then
Sheets(i).Cells(r, c).Value = "N/A"
End If
Next r
Next c
Next i
Dim xWs As Worksheet
Dim Rng As Range
Dim lastRow As String
Dim myPath As String
'company
Sheets(15).Select
Set Cell = Range("A1:N4").Find("Company", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("A1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("Company", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'location
Sheets(15).Select
Set Cell = Range("A1:N4").Find("location", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("B1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("location", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'Store
Sheets(15).Select
Set Cell = Range("A1:N4").Find("store", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("C1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("store", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'RCT
Sheets(15).Select
Set Cell = Range("A1:N4").Find("RCT", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("D1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("RCT", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'Vendor
Sheets(15).Select
Set Cell = Range("A1:N4").Find("Vendor", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("E1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("Vendor", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'Vendor Name
Sheets(15).Select
Set Cell = Range("A1:N4").Find("Vendor Name", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("F1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("Vendor Name", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'Date
Sheets(15).Select
Set Cell = Range("A1:N4").Find("date", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("g1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("date", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'Reference
Sheets(15).Select
Set Cell = Range("A1:N4").Find("reference", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("H1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("reference", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'amount
Sheets(15).Select
Set Cell = Range("A1:N4").Find("amount", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("I1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("amount", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'period
Sheets(15).Select
Set Cell = Range("A1:N4").Find("period", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("J1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("period", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'JE
Sheets(15).Select
Set Cell = Range("A1:N4").Find("JE", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("K1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("JE", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'project
Sheets(15).Select
Set Cell = Range("A1:N4").Find("Project", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("L1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("project", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'expected open date
Sheets(15).Select
Set Cell = Range("A1:N4").Find("expected", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("M1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("expected", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
'comment
Sheets(15).Select
Set Cell = Range("A1:N4").Find("comment", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Range("N1").Select
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlDown)).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
For i = 16 To Worksheets.Count
Sheets(i).Select
Set Cell = Range("A1:N5").Find("comment", LookAt:=xlPart)
Cell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy
Worksheets("Consolidated").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:26:22.393",
"Id": "423231",
"Score": "2",
"body": "You told us what you would like us to do, but not what the purpose of your code is. Please [edit] your title to summarize what your code is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:29:47.770",
"Id": "423233",
"Score": "0",
"body": "Thanks @MathieuGuindon ! i will correct now !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:37:01.583",
"Id": "423234",
"Score": "0",
"body": "Thanks for updating - I mostly meant that for the title though =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:38:04.070",
"Id": "423235",
"Score": "0",
"body": "[This SO Q&A](https://stackoverflow.com/q/10714251/1188513) should help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:22:43.103",
"Id": "423240",
"Score": "2",
"body": "My 30 second glance (don't have time for a review at the moment) - your three biggest issues are: Active/Select (should not use), iterating through Excel objects instead of arrays (this will give the biggest time saving), and repeated loops (DRY- Don't Repeat Yourself)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:29:47.437",
"Id": "423242",
"Score": "0",
"body": "@AJD thank you for the response, im fairly new to vba world of excel so i need help as far as understanding looping, repeating looping and iterating through excel objects instead of arrays. my background is accounting so i not sure how to go through this process without any guidance, please any direct help will help me understand this more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T20:54:21.630",
"Id": "423244",
"Score": "0",
"body": "Here are a couple of other quick hits for you: repeating the advice from @AJD above, look at [this link](https://stackoverflow.com/a/10717999/4717755), then look over [these tips](https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/), especially #5."
}
] | [
{
"body": "<p>This code provides a large number of rookie errors. I suspect, looking at the code, is that it was initially developed from a recorded macro (or two).</p>\n\n<p>In summary, the issues to be addressed are:</p>\n\n<ul>\n<li>No <code>Option Explicit</code> - you use <code>Cell</code> as a variable in the code which\nhas not been declared</li>\n<li>Variable names have no real meaning</li>\n<li>You Select/Activate and do not use qualified names</li>\n<li>You have sections of code that is very repetitive</li>\n<li>You have loops that reference Excel objects, meaning that the VBA\nengine keeps switching to the Excel engine and back again - very\nexpensive</li>\n<li>Remember to turn <code>ScreenUpdating</code> back on!</li>\n</ul>\n\n<h2>Option Explicit</h2>\n\n<p>Always use <code>Option Explicit</code>. This helps avoid typos (<code>r1</code> instead of <code>rl</code>, anyone?) which leads to undeclared variables using default values, which in turn leads to strange results that are hard to track down. In addition, it help enforce strong type discipline and enables the debugger to provide more meaningful error messages (relatively speaking!).</p>\n\n<h2>Meaningful variable names</h2>\n\n<p>Using meaningful variable names results in code that requires less comments and is easer to maintain. Some examples:</p>\n\n<ul>\n<li><code>r</code> could mean anything, but <code>rowCounter</code> provides a visual clue that\nthis is used as a counter or in a loop.</li>\n<li><code>i</code> is a standard loop iterator, but what are we iterating?\n<code>worksheetCounter</code> is similarly self-documenting.</li>\n<li><code>c</code> could be <code>columnCounter</code></li>\n<li><code>Cell</code> has the double danger of being a reserved word and an object\nin Excel. Using this as a variable name can lead to confusion.\nPerhaps <code>sourceToCopy</code> is more meaningful in this context?</li>\n</ul>\n\n<h2>Avoiding Select and Active[thingys]</h2>\n\n<p>As noted in the comments, this StackOverflow answer provides some good guidance on avoiding select: <a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba/10717999#10717999\">https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba/10717999#10717999</a>. </p>\n\n<p>Selecting things slows the code down by forcing screen updates that are not necessary. <code>Select</code> in itself is not otherwise dangerous in code - just unnecessary and slow.</p>\n\n<p>Using the Active Book/Sheet/Cell, however is very dangerous in code. In addition, every time you use an unqualified range, you are implicitly using the active range object (book, sheet, cell). As a coder, you have very little control over what is active - you could be running other code that switches the active thing. The user could be doing things and switching while the code is running. Excel itself could for some unknown reason jump to another [thing] and make it active.</p>\n\n<h2>Don't repeat yourself (DRY)</h2>\n\n<p>I am lazy programmer. If I have to write the same code twice, I think it is too much work and I can address the repetition in two ways: in a loop or in a routine (with parameters!).</p>\n\n<p>You have globs of code where the code is simple a cut and paste of previous stuff. If you ever wanted to adjust the code, you now have to do it in umpteen places and \"London to a brick\", you would miss one piece of repeated code and spend ages trying to figure out why you are getting bad results (or even worse, getting bad results and believing they are good).</p>\n\n<h2>Excel objects versus VBA objects</h2>\n\n<p>I don't want to get too technical here, there are others who can explain this much better than me. I think of this simply as having two object engines. There is a VBA engine and an Excel engine. VBA code uses the VBA engine, and the Excel specific objects (cells, sheets, workbooks, application formulas to name a few) use the Excel engine. </p>\n\n<p>This is all fine and good, except that to switch between the two engines takes computing time and effort. And a relatively large amount of it. So in a loop like below, the system will switch engines 10,000 times (and that is without the effort to do calculations)</p>\n\n<pre><code>For myIterator = 1 to 5000\n Debug.Print myWB.Range(\"A\" & CStr(myIterator)).Value\nnext myIterator\n</code></pre>\n\n<p>Whereas ...</p>\n\n<pre><code>myValues = myWB.Range(\"A1:A5000\").Value ' myValues is a Variant type\nFor myIterator = 1 to 5000\n Debug.Print myValues(myIterator,1) \n ' two dimensional array because this is how the values are converted.\nnext myIterator\n</code></pre>\n\n<p>...is much more switch friendly.</p>\n\n<h2>What does this mean?</h2>\n\n<p>Here is a look at your code with the above points addressed.</p>\n\n<pre><code>Option Explicit\n\nSub ConsolidateData() ' more meaningful name\n\n Application.ScreenUpdating = False ' Use proper indenting.\n\n Dim consolidatedWorksheet As Worksheet\n Set consolidatedWorksheet = ThisWorkbook.Worksheets.Add(Before:=ThisWorkbook.Worksheets(\"CIP Summary\")) ' assign the sheet so it can be qualified.\n consolidatedWorksheet.Name = \"Consolidated\" ' no longer working with ActiveSheet\n\n Dim titles As Variant 'Now we use an array to set the cell values. In one hit.\n titles = Array(\"Company\", \"Location\", \"Store\", \"RCT/Voucher\", \"Vendor\", \"Vendor Name\", \"Date\", \"Reference\", \"Reference\", \"Amount\", \"Period\", \"JE\", \"Project\", \"Expected Open Date\", \"Comment\")\n With consolidatedWorksheet.Range(\"A1:N1\")\n .Value = titles\n .Font.Bold = True\n End With\n\n Dim sheetIterator As Long ' always use long these days.\n Dim rowIterator As Long, columnIterator As Long\n Dim sheetContents As Variant\n\n 'Cleanse the data\n ' using an array to save switching the engine nearly 14,000 * 2 times. Now we only switch a few times.\n For sheetIterator = 15 To Worksheets.Count ' 15 is a magic number - will it always be right?\n With ThisWorkbook.Sheets(sheetIterator) ' set up the array\n sheetContents = .Range(.Cells(5, 1), .Cells(1000, 14))\n End With\n For columnIterator = 1 To 14\n For rowIterator = 5 To 1000\n If VarType(sheetContents(rowIterator, columnIterator)) = vbError Or sheetContents(rowIterator, columnIterator) = \"\" Then\n sheetContents(rowIterator, columnIterator) = \"N/A\"\n End If\n Next rowIterator\n Next columnIterator\n ' replace the values in case there have been changes\n With ThisWorkbook.Sheets(sheetIterator) ' set up the array\n .Range(.Cells(5, 1), .Cells(1000, 14)) = sheetContents\n End With\n Next sheetIterator\n\n''''company\n''' *** This code forms the thinking for the repetitive routine.\n''' Dim firstCompany As Range\n''' Dim allData As Range\n''' With ThisWorkbook.Sheets(15) ' magic number\n''' Set firstCompany = .Range(\"A1:N4\").Find(\"Company\", LookAt:=xlPart).Offset(1, 0)\n''' Set allData = .Range(firstCompany, firstCompany.End(xlDown))\n''' End With\n''' With ThisWorkbook.Worksheets(\"Consolidated\")\n''' ' the use of the Cells method will open up to making a generic routine\n''' .Range(.Cells(1, 2), .Cells(1, 2)).Value = allData.Value\n''' ' set the values instead of copying cells. But you could adjust this to copy and paste if you wanted.\n''' End With\n'''\n''' Dim pasteTarget As Range\n''' For sheetIterator = 16 To Worksheets.Count\n''' With ThisWorkbook.Sheets(sheetIterator)\n''' Set firstCompany = .Range(\"A1:N5\").Find(\"Company\", LookAt:=xlPart).Offset(1, 0)\n''' Set allData = .Range(firstCompany, firstCompany.End(xlDown))\n''' End With\n''' With ThisWorkbook.Worksheets(\"Consolidated\")\n''' Set pasteTarget = Something.End(xlDown) ' At this point I can't tell which is the active cell and where to paste the data.\n''' pasteTarget.Value = allData.Value\n''' End With\n''' Next sheetIterator\n\n' now that we have identified the repetition and put it into the routine\n' all we have to do is call the routine\n\n CopyData \"Company\", 1\n CopyData \"location\", 2\n CopyData \"store\", 3\n CopyData \"RCT\", 4\n CopyData \"Vendor\", 5\n CopyData \"Vendor Name\", 6\n CopyData \"date\", 7\n CopyData \"reference\", 8\n CopyData \"amount\", 9\n CopyData \"period\", 10\n CopyData \"JE\", 11\n CopyData \"Project\", 12\n CopyData \"expected\", 13\n CopyData \"comment\", 14\n\n Application.ScreenUpdating = True ' turn it back on!\nEnd Sub\n\nPrivate Sub CopyData(category As String, columnNumber As Long)\n\n Dim firstFind As Range\n Dim allData As Range\n Dim sheetIterator As Long\n\n With ThisWorkbook.Sheets(15) ' magic number\n Set firstFind = .Range(\"A1:N4\").Find(category, LookAt:=xlPart).Offset(1, 0)\n Set allData = .Range(firstFind, firstFind.End(xlDown))\n End With\n With ThisWorkbook.Worksheets(\"Consolidated\")\n ' the use of the Cells method will open up to making a generic routine\n .Range(.Cells(1, columnNumber), .Cells(1, columnNumber)).Value = allData.Value\n ' set the values instead of copying cells. But you could adjust this to copy and paste if you wanted.\n End With\n\n Dim pasteTarget As Range\n For sheetIterator = 16 To Worksheets.Count\n With ThisWorkbook.Sheets(sheetIterator)\n Set firstFind = .Range(\"A1:N5\").Find(category, LookAt:=xlPart).Offset(1, 0)\n Set allData = .Range(firstFind, firstFind.End(xlDown))\n End With\n With ThisWorkbook.Worksheets(\"Consolidated\")\n Set pasteTarget = Something.End(xlDown) ' At this point I can't tell which is the active cell and where to paste the data.\n pasteTarget.Value = allData.Value\n End With\n Next sheetIterator\n\nEnd Sub\n</code></pre>\n\n<p>Of course, the code is not tested so I apologise in advance for any minor errors or other typos that you may find. Also, in re-working the code I identified an ambiguity in selecting where to paste the data - <code>Something</code> is not declared and will cause a compile error. I am sure you can now work something out that does not involve <code>Select</code> or an <code>ActiveCell</code>!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T14:07:54.903",
"Id": "423386",
"Score": "0",
"body": "Thanks @AJD i ran into some bugs with the code you gave me but i will try my best to fix it to accommodate what i need. it is like a foreign right now but it is a learning curve that will help me. thank you alot !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:42:03.347",
"Id": "219157",
"ParentId": "219127",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T19:07:32.693",
"Id": "219127",
"Score": "3",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Consolidating several Excel sheets into one"
} | 219127 |
<p>What the code does: Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list. Example:</p>
<pre><code>symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
</code></pre>
<p>Note: Symmetry occurs if the value of the ith element from the start of the list is equal to the value of the ith element from the end of the list.</p>
<pre><code>def symmetrical_sum(a):
'''Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list
Example: symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the
ith element at the end of the list'''
#extract duplicate value
dupe = [x for n, x in enumerate(a) if x in a[:n]]
#if no duplicate values found, do the following:
if dupe == []:
middle = float(len(a))/2
if middle % 2 != 0:
sym = a[int(middle - .5):int(middle + .5)]
ans = a[int(middle - .5)]
tuple1 = (sym,ans)
elif middle % 2 == 0:
sym = a[int(middle - 1):int(middle + 1)]
ans = sum(a[int(middle - 1):int(middle + 1)])//2
tuple1 = (sym,ans)
return tuple1
else:
d_to_i = int("".join(map(str, dupe))) #convert duplicate value to integer
p1 = a.index(d_to_i) #get index of first duplicate
p2 = a.index(d_to_i, p1+1) #get index of second duplicate
sym = a[p1:p2+1] #[symmetrical-portion]
ans = sum(sym) #sum-of-symmetrical-portion
tuple2 = (sym, ans)
return tuple2
</code></pre>
<p>Looking at my code I realize that it could probably be more efficient than this. It works, but I'm sure it could be better. I just don't possess the skills to 'compress it'. I've submitted my code already so this is just for my own personal development.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:38:08.663",
"Id": "423257",
"Score": "0",
"body": "It is not a palindrome function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:41:58.223",
"Id": "423259",
"Score": "0",
"body": "So to clarify, it's only symmetrical if the outer elements are the same, but the inner elements don't have to be?\n\nSo, [12, 13, 1, 2, 3, 90, 100, 4, 2, 6, 7, 22] would have an \"symmetrical\" sub list of [2, 3, 90, 100, 4, 2]?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:44:35.117",
"Id": "423260",
"Score": "1",
"body": "Upon looking into this more. What is `symmetrical_sum([1, 2, 1, 3, 4, 5])` meant to return? Also what are `symmetrical_sum([1, 2])`, `symmetrical_sum([1, 2, 3])` and `symmetrical_sum([1, 2, 3, 4])` meant to return? This looks like it's _really_ not working as you intend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:57:57.370",
"Id": "423261",
"Score": "0",
"body": "@Acejhm yes, that is correct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:06:47.043",
"Id": "423262",
"Score": "0",
"body": "@Peilonrayz `symmetrical_sum([1, 2, 1, 3, 4, 5])` would return `([1,2,1],4)`... the symmetrical numbers in your use case are the `1`'s. When it is `[1, 2, 3]` it would return the median which is `2` in this case. when it is `[1, 2, 3, 4]` again the median rule would apply, so `(2+3)\\2 = 2.5`, but since it needs to be an `int` it would return `([2,3],2)`. You can put the code into an IDE to check it out. but I've tested all the cases I can think of and got what I expected. a zero would return `([0],0)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:11:52.263",
"Id": "423263",
"Score": "0",
"body": "And what should `[1, 2]` return?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:15:47.200",
"Id": "423264",
"Score": "0",
"body": "Why is `[1, 2, 1, 3, 4, 5]` -> `[1, 2, 1]` when -0 is 5?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:20:36.433",
"Id": "423265",
"Score": "0",
"body": "@Peilonrayz good question, I didn't use that as a test case, however the code would return `([1],1)`. I am not entirely sure what the correct output should be in that event. The autograder returned a pass on all it's test cases. I guess my supervisors didn't take a case like this into account so did not specify how to handle a case of 2 non-symmetrical values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:23:35.507",
"Id": "423266",
"Score": "0",
"body": "@Peilonrayz reading your last question, I'm starting to think you do not entirely understand what the function is supposed to do. What do you think it does? The number on the outside of the `[ ]` is the sum of the sublist"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:37:55.817",
"Id": "423267",
"Score": "2",
"body": "I'm not talking about the sum, I'm talking about the \"Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the ith element at the end of the list\" with `l = [1, 2, 1, 3, 4, 5]` `l[0] != l[~0]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:18:56.110",
"Id": "423484",
"Score": "0",
"body": "The code in the question doesn't work in the manner it's described to. I have highlighted this [in my disposable answer below](https://codereview.stackexchange.com/a/219256). [meta about disposable answers](https://codereview.meta.stackexchange.com/a/6977)"
}
] | [
{
"body": "<p>The code in the question is not working as intended.</p>\n\n<ol>\n<li><blockquote>\n <p>Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the \n ith element at the end of the list</p>\n</blockquote>\n\n<p>Meaning for any list <code>l</code> the symmetry occurs when <code>l[i] == l[~i]</code>.</p>\n\n<pre><code>>>> symmetrical_sum([1, 2, 1, 3, 4])\n([1, 2, 1], 4)\n>>> symmetrical_sum([0, 1, 2, 1, 3, 4])\n([1, 2, 1], 4)\n</code></pre>\n\n<p>This says that the midpoint is the same distance from the end of the list as the starting value. And it says 1 and -3 are the same distance.</p></li>\n<li><p>No where does it say the input will only have one duplicate.</p>\n\n<pre><code>>>> symmetrical_sum([1, 2, 3, 4, 2, 1])\nValueError: 21 is not in list\n>>> symmetrical_sum([1, 2, 3, 4, 1, 2])\nValueError: 12 is not in list\n>>> symmetrical_sum([1, 2, 3, 1, 4, 2])\nValueError: 12 is not in list\n</code></pre></li>\n<li><p>The output returns different amount of values when the size of the input are different multiples of two.</p>\n\n<pre><code>>>> symmetrical_sum([1, 2])\n([1], 1)\n>>> symmetrical_sum([1, 2, 3, 4])\n([2, 3], 2)\n>>> symmetrical_sum([1, 2, 3, 4, 5, 6])\n([3], 3)\n>>> symmetrical_sum([1, 2, 3, 4, 5, 6, 7, 8])\n([4, 5], 4)\n>>> symmetrical_sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n([5], 5)\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:16:17.997",
"Id": "219256",
"ParentId": "219134",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:08:33.630",
"Id": "219134",
"Score": "2",
"Tags": [
"python",
"algorithm"
],
"Title": "Search for a symmetrical inner portion of a list"
} | 219134 |
<p>I'm developing a new Look and Feel that is based on animation ,
so I've decided to make animated text caret too !
The caret works as expected every thing is fine except that am worried about how I defined my animation rules in making the <code>babySteps</code> method and <code>repaint</code> in the <code>movementTimer</code> not the caret one but the component one !!</p>
<p>at the installation of the <code>Caret</code> I add <code>PropertyChangeListener</code> witch invokes <code>prepareColorsList</code> if the property is "caretColor" with the new value </p>
<pre><code>private void prepareColorsList(Color c) {
Color end = reFactorAlphaBy(c, 0);
ar.clear();
ar.add(c);
while (!ColorsEquals(c, end)) {
ar.add((c = step(c, end)));
}
}
</code></pre>
<p><code>ar</code> is a <code>List<Color></code> and <code>reFactorAlphaBy</code> just returns a new color with same red,green and blue but with the specified <code>int</code> as alpha .
the <code>stepColor</code> just call the <code>babySteps</code> method on each value of the color and return the new color .
I did this because I didn't want to invoke the <code>step</code> method in the timer , am afraid this will be bad practice.</p>
<p>The <code>stepsColor(int from, int to, int max)</code> provide the maximum addition to add it to <code>from</code> to be <code>to</code> but the return will be less than <code>max</code> </p>
<pre><code>public static int babySteps(int from, int to, int max) {
int ret = 0;
if (from > to) {
for (int j = 0; j <= max; j++) {
if (from >= to + j) {
ret = -j;
} else {
break;
}
}
} else if (from < to) {
for (int j = 0; j <= max; j++) {
if (from + j <= to) {
ret = j;
} else {
break;
}
}
}
return ret;
}
</code></pre>
<p>I'm afraid of the usage of the for loops (I haven't faced a performance issue with them in any project yet but if this project made it to the light it gonna have a lot of users and i need to predict if it's gonna be issue).</p>
<p>Last thing, it's also about the <code>babySteps</code> as am using it in the movement timer too.
This is a brief explanation of what I am doing:</p>
<ol>
<li>I have two <code>Rectangle</code> objects: one to draw and the other to get the location of where that drawing rect should go .</li>
<li>I have overridden the <code>setDot</code> method to change the second rect bounds .</li>
<li>The movement timer has an <code>ActionListener</code> that moves the bounds of the first rect to the other one using the <code>babySteps</code> method </li>
</ol>
<pre><code>@Override
public void actionPerformed(ActionEvent e) {
draw.height += babySteps(draw.height, follow.height, 2);
draw.width += babySteps(draw.width, follow.width, 2);
draw.x += babySteps(draw.x, follow.x, 2);
draw.y += babySteps(draw.y, follow.y, 2);
getComponent().repaint();
}
</code></pre>
<p>Here I am calling the component <code>repaint</code> instead of the class one because the class <code>repaint</code> implementation will repaint the caret rect only witch it will lead in the old carets stick to the screen !! </p>
<p>Am just afraid of the for loops that is inside <code>Timer</code> objects would make an heavy effect to ui and making crashes if the user have a lot of <code>JTextComponent</code> and I don't know even how to predict what will happen.</p>
| [] | [
{
"body": "<p>Hey Not 100% sure what's up with the babySteps function<br><br></p>\n\n<blockquote>\n <p>\"the stepsColor(int from, int to, int max) provide the maximum addition to add it to > from to be to but the return will be less than max\"</p>\n</blockquote>\n\n<p>Is a little confusing anyway I refactored</p>\n\n<pre><code>public static int babySteps(int from, int to, int max) {\n int j = 0;\n int currentPoint = to;\n for (;j <= max; j++) {\n if (!from >= currentPoint || !from <= currentPoint) {\n return j;\n }\n }\n}\n</code></pre>\n\n<p>Can you send me the GitHub link so I can look into the code base thanks</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:04:21.367",
"Id": "423970",
"Score": "0",
"body": "thank you for the response ;) i started to think that i will have non , any way your code won't compile as a starter friend !! but any how my repo is private , not that i want to make it closed source but i want to at least reach 60% of my millage then make it public but if you want to take a look gimme your github name and i will invite you gladly ;). @AdamSever"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:15:41.390",
"Id": "424148",
"Score": "0",
"body": "Whats the compile error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:16:07.073",
"Id": "424149",
"Score": "0",
"body": "Oh I see it trying to use the var j before i init it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:17:38.843",
"Id": "424150",
"Score": "0",
"body": "Its avacadoadam on github aswell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:26:45.187",
"Id": "424154",
"Score": "0",
"body": "i just invited you check your email."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:24:12.250",
"Id": "219374",
"ParentId": "219136",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T22:50:25.500",
"Id": "219136",
"Score": "1",
"Tags": [
"java",
"swing",
"animation"
],
"Title": "Caret color and movement animation in Swing"
} | 219136 |
<p>The Goldbach conjecture says: <strong>any even number greater than two can be represented by the sum of two prime numbers.</strong></p>
<blockquote>
<p>G(n) = { (p1, p2) | p1 + p2 = n, p1 and p2 are prime numbers with p1 < p2 }</p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>G(6) = <strong>{(3, 3)}</strong></p>
<p>G(12) = <strong>{(5, 7)}</strong></p>
<p>G(26) = <strong>{(3, 23),(7, 19),(13, 13)}</strong></p>
</blockquote>
<p>So I have to do an algorithm that determines which three numbers n1, n2 and n3 are between <strong>1,000,000</strong> and <strong>2,000,000</strong> for which the
<strong>G (n1)</strong>, <strong>G (n2)</strong> and <strong>G (n3)</strong> have the largest number of elements.</p>
<p>I do not know if I need to improve something in my code, or even optimize some part that is poorly written. It currently taking about 12 seconds.</p>
<pre><code>public class Goldbach {
private static int j;
private static int k;
private static int [] primes;
private static int [] just_primes;
private static int [] conjunct;
public static void main(String[] args)
{
primes = new int[2000000];
for ( int i=0; i<2000000; i++ ) {
primes[i] = i+1;
}
for ( int i=1; i<1000000; i++ ) {
if ( primes[i] != 0 ) {
j = primes[i];
k = j;
while ( k <= 2000000 ) {
k += j;
if ( k <= 2000000 ) {
primes[ k-1 ] = 0;
}
}
}
}
just_primes = new int [primes.length];
for ( int i = 0; i< primes.length-1 ; i++ ) {
just_primes[i] = 0;
}
k = 0;
for ( int i = 1; i< primes.length-1 ; i++ ) {
if ( primes[i] > 0 ) {
just_primes[k] = primes[i];
k++;
}
}
conjunct = new int[1000001];
for ( int i = 0; i<1000001 ; i++ ) {
conjunct[i] = 0;
}
int p;
for ( int i = 0; i< k ; i++ ) {
for ( int j = i; j< k ; j++ ) {
int w = just_primes[i]+just_primes[j];
if ( w >= 1000000 && w <= 2000000 ) {
p = w - 1000000;
conjunct[p]++;
}
}
}
int big1 = 0;
int big2 = 0;
int big3 = 0;
int n1 = 0;
int n2 = 0;
int n3 = 0;
for ( int i = 0; i<1000001 ; i++ ) {
if ( conjunct[i] >= big1 ) {
big3 = big2;
big2 = big1;
big1 = conjunct[i];
n3 = n2;
n2 = n1;
n1 = i;
} else {
if ( conjunct[i] >= big2 ) {
big3 = big2;
big2 = conjunct[i];
n3 = n2;
n2 = i;
} else {
if ( conjunct[i] >= big3 ) {
big3 = conjunct[i];
n3 = i;
}
}
}
}
System.out.println( "Largest conjunct 1: " + n1 + " " + 1000000+big1 + " pairs" );
System.out.println( "Largest conjunct 2: " + n2 + " " + 1000000+big2 + " pairs" );
System.out.println( "Largest conjunct 3: " + n3 + " " + 1000000+big3 + " pairs" );
}
}
</code></pre>
<p>Expected result:</p>
<pre><code>Largest conjunct 1: 981980 100000027988 pairs
Largest conjunct 2: 951950 100000027802 pairs
Largest conjunct 3: 995630 100000027730 pairs
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T14:59:15.923",
"Id": "423392",
"Score": "0",
"body": "How are 981980, 951950, and 995630 \"between 1,000,000 and 2,000,000\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T15:01:34.750",
"Id": "423393",
"Score": "0",
"body": "Good point, he needs to add 10^6 to the number first."
}
] | [
{
"body": "<p>I think it looks pretty good. One possible way to make it faster is in this part:</p>\n\n<pre><code>for ( int i = 0; i< k ; i++ ) {\n for ( int j = i; j< k ; j++ ) {\n int w = just_primes[i]+just_primes[j];\n if ( w >= 1000000 && w <= 2000000 ) {\n p = w - 1000000;\n conjunct[p]++;\n }\n }\n}\n</code></pre>\n\n<p>Notice that for each value of justprimes[i] you are currently testing all values of justprimes[j] and after this you are testing if the sum is in the desired interval.</p>\n\n<p>One way to work around this is by using a two pointer method that tells us the biggest possible value j can take for any value of i, and also by breaking out of the loop as soon as j becomes to small. </p>\n\n<pre><code>int high = k-1;\n for ( int i = 0; i< k ; i++ ) {\n for ( int j = high; j>=i ; j-- ) {\n int w = just_primes[i]+just_primes[j];\n if(w< 1000000) break;\n if ( w <= 2000000 ) {\n p = w - 1000000;\n conjunct[p]++;\n }\n else{\n while( just_primes[i]+ just_primes[high] > 2000000 && high > 0){\n high --;\n }\n }\n }\n }\n</code></pre>\n\n<p>This seems to give a 15% speed boost in my computer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:30:56.513",
"Id": "219139",
"ParentId": "219137",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219139",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:00:22.370",
"Id": "219137",
"Score": "5",
"Tags": [
"java",
"performance",
"algorithm",
"primes"
],
"Title": "Goldbach conjecture solution finder"
} | 219137 |
<p>This a working function as part of a drag and drop task manager im playing around with. The function is working fine, but it just looks messy and long to me. I haven't added all the code as I'm looking just to tidy up the function itself. I have added the state though as guidance.</p>
<p><strong>function</strong></p>
<pre><code>onDrop = () => {
let people = [...this.state.people]
let newPeopleArray = []
let newChoresArray = []
let personToUpdate = {}
people.forEach( person => {
if ( person.name !== this.state.targetPerson ) {
newPeopleArray.push(person)
} else {
personToUpdate = person
personToUpdate.chores.forEach( chore => {
if ( chore !== this.state.targetChore ) {
newChoresArray.push(chore)
}})
personToUpdate.chores = newChoresArray
}})
newPeopleArray.push(personToUpdate)
this.setState ({ people: newPeopleArray})
}
</code></pre>
<p><strong>state</strong></p>
<pre><code>class App extends Component {
state = {
targetChore: '',
targetPerson: '',
people: [
{ name: 'Grace', chores: ['clean kitchen', 'wash dog', 'laundry'] },
{ name: 'Sam', chores: ['walk dog', 'wash car', 'go shopping'] },
{ name: 'Rose', chores: ['wash windows', 'vaccum', 'clean bathroom'] }
]
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T09:27:25.440",
"Id": "423463",
"Score": "0",
"body": "I update my question let me know what you think about it . I prefer object oriented programming"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T17:36:09.043",
"Id": "424632",
"Score": "0",
"body": "Thanks @FabrizioBertoglio, its an interesting take and a completely different method which is interesting! I need to explore OOP more. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T18:02:22.770",
"Id": "424637",
"Score": "0",
"body": "Yes. I find Object Oriented programming is easier to refactor and mantain, as it already iherints properties from real world objects .. It is easier to copy something from the real world instead of re-inventing everything"
}
] | [
{
"body": "<p>A <code>Person</code> class encapsulates the attributes/methods and logic for the <code>Person</code> object. Currently inherits from <code>Object</code>, but you can at any time extend this logic by creating an new super class or children and distribute the logic between those hierarchies. </p>\n\n<pre><code>class Person extends Object {\n constructor(props) {\n super\n this.name = props.name\n this.chores = props.chores\n }\n\n addSubject() {\n if (this.isFound) { return new People().push(person) }\n // your choice to either create a chore class or write some subroutine\n else { person.chores.forEach( chore => chore.addChore ) }\n }\n\n // either pass targetPerson as param or add it to the Person object as attribute\n isFound() { this.name !== this.state.targetPerson }\n\n}\n</code></pre>\n\n<pre><code>people = [ new Person('Grace', 'clean kitchen', 'wash dog'..), etc..]\n</code></pre>\n\n<p>I also believe the <code>onDrop</code> subroutine should just have the responsibility of <code>dropping person</code> or <code>returning</code> a new <code>people</code> object. It would be an <code>instance method</code> of the <code>People</code> class</p>\n\n<pre><code>class People extends Object {\n drop = () => {\n this.each( person => person.addSubject() )\n // etc...\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:32:08.970",
"Id": "219213",
"ParentId": "219138",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T23:24:44.700",
"Id": "219138",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "React onDrop function for a task manager"
} | 219138 |
<p>I've recently learned BEM & SASS, and I'd like to know if my BEM syntax is correct. I'm trying to create just the header of this page: <a href="https://blackrockdigital.github.io/startbootstrap-agency/" rel="nofollow noreferrer">https://blackrockdigital.github.io/startbootstrap-agency/</a></p>
<p>Are there any differences you would make to my class names? I get very confused about how to deal with elements when they are nested within other elements. I find that I often want to chain elements, like <code>class="header__navbar__logo"</code>, but I've heard this is not good BEM.</p>
<pre><code><header class="header">
<div class="header__navbar">
<div class="container">
<h1 class="header__logo">Start Bootstrap</h1>
<ul class="header__navigation">
<li class="header__nav-item"><a class="header__nav-link" href="#">Services</a></li>
<li class="header__nav-item"><a class="header__nav-link" href="#">Portfolio</a></li>
<li class="header__nav-item"><a class="header__nav-link" href="#">About</a></li>
<li class="header__nav-item"><a class="header__nav-link" href="#">Team</a></li>
<li class="header__nav-item"><a class="header__nav-link" href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="header__content">
<h1 class="heading-primary">
<span class="heading-primary--main">Welcome To Our Studio!</span>
<span class="heading-primary--sub">It's Nice To Meet You</span>
</h1>
<a class="btn btn-yellow" href="#"></a>
</div>
</header>
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T01:44:30.783",
"Id": "425310",
"Score": "0",
"body": "In my opinion, the real question you should ask yourself is \"do I really need all these class selectors\". Only declare IDs and classes when you need them. I think using class names for the `<li>` AND the `<a>` tags is not necessary."
}
] | [
{
"body": "<p>Well, if you are using Bootstrap, you should not alter the classes that Framework is using, like <code>navabar</code> for example.</p>\n<p>The basic with BEM is that you should chain classes in a way to create a meaningful hierarchy, like in a component, where you have an object that contains everything else. Like that you leverage SASS nesting to create a component-like structure.</p>\n<p>For example:</p>\n<pre><code><header>\n\n <navbar class="navigationBar navbar">\n <div class="container">\n <div class="navigationBar--logo"></div>\n <ul class="navigationBar--navigation">\n <li class="navigationBar--navigation--item">\n <a class="navigationBar--navigation--item--link" href="#">Item-1</a>\n <a class="navigationBar--navigation--item--link" href="#">Item-2</a>\n <a class="navigationBar--navigation--item--link" href="#">Item-3</a>\n </li>\n </ul>\n </div>\n </div>\n </navbar>\n\n <section class="content">\n <div class="container">\n <div class="content--heading--primary">\n <span class="content--heading--primary--main">Welcome To Our Studio!</span>\n <span class="content--heading--primary--sub">It's Nice To Meet You</span>\n </div>\n </div>\n </section>\n\n</header>\n</code></pre>\n<p>In this case the SASS will be:</p>\n<pre><code>.navigationBar {\n width:104px;\n \n &--logo { width:103px; }\n &--navigation {\n width:102px;\n \n &--item {\n width:101px;\n \n &--link {width:100px; } \n }\n }\n}\n\n\n.content {\n width:100px;\n \n &--heading--primary {\n width: 101px;\n \n &--main { width: 102px; }\n &--sub { width: 103px; }\n }\n}\n</code></pre>\n<p>Check the SASS code with <strong>SassMeister</strong> (<a href=\"https://www.sassmeister.com\" rel=\"nofollow noreferrer\">https://www.sassmeister.com</a>) to see how it turns to CSS</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T20:07:47.887",
"Id": "248568",
"ParentId": "219140",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T00:18:32.340",
"Id": "219140",
"Score": "1",
"Tags": [
"css",
"bem"
],
"Title": "CSS organization with BEM"
} | 219140 |
<p>A program that I work on constantly updates and modifies program state containing an arbitrarily deep and wide tree. The data looks something like this.</p>
<pre class="lang-clj prettyprint-override"><code>(defonce state
(r/atom {:some "program"
:state "here"
:tree [{:topic "Books"
:expanded true
:children [{:topic "Titles"}
{:topic "Authors"
:expanded true
:children [{:topic "Alice"}
{:topic "Bob"}
{:topic "Carol"}]}
{:topic "Genres"}]}
{:topic "CDs"
:children [{:topic "Genres"}
{:topic "Albums"}
{:topic "Artists"}]}
{:topic "To Do"
:expanded true
:children [{:topic "Spouse Birthday"
:expanded nil
:due-date "07/31/2025"
:children [{:topic "Buy Card"}
{:topic "Buy Jewelry"}
{:topic "Buy Cake"}]}]}]}))
</code></pre>
<p>As the program runs, I need to extract the series of numeric vector indices to reach the visible topics (those that have <code>:children</code> where the <code>:expanded</code> flag is present and "truthy"). </p>
<p>Here is a method that works.</p>
<pre class="lang-clj prettyprint-override"><code>;; This flattening function is from an idea presented in response to
;; this question:
;; https://stackoverflow.com/questions/5232350/clojure-semi-flattening-a-nested-sequence
(defn flatten-to-vectors
[s]
(mapcat #(if (every? coll? %) (flatten-to-vectors %) (list %)) s))
(defn visible-nodes
[tree so-far]
(flatten-to-vectors
(map-indexed
(fn [idx ele]
(let [new-id (conj so-far idx)]
(if (not (and (:children ele) (:expanded ele)))
new-id
(cons new-id (visible-nodes (:children ele) new-id)))))
tree)))
;; The function can be called like this on the data above.
(println (visible-nodes (:tree @state) []))
;; => ([0] [0 0] [0 1] [0 1 0] [0 1 1] [0 1 2] [0 2] [1] [2] [2 0])
</code></pre>
<p>Although this works, it seems like I should be able to generate the correct result without creating nested sequences that require flattening. But I just can't come up with anything.</p>
<p>Any suggestions would be appreciated.</p>
| [] | [
{
"body": "<p>Depending on your final goal, you may be interested in <a href=\"https://github.com/cloojure/tupelo/blob/master/docs/forest.adoc\" rel=\"nofollow noreferrer\">the Tupelo Forest library</a>. Here is a sample of what you can do (data converted to the \"tree\" format):</p>\n\n<pre><code>(dotest-focus\n (with-forest (new-forest)\n (let [data {:tag \"program\"\n :state \"here\"\n ::tf/kids [{:topic \"Books\"\n :expanded true\n ::tf/kids [{:topic \"Titles\" ::tf/kids []}\n {:topic \"Authors\"\n :expanded true\n ::tf/kids [{:topic \"Alice\" ::tf/kids []}\n {:topic \"Bob\" ::tf/kids []}\n {:topic \"Carol\" ::tf/kids []}]}\n {:topic \"Genres\" ::tf/kids []}]}\n {:topic \"CDs\"\n ::tf/kids [{:topic \"Genres\" ::tf/kids []}\n {:topic \"Albums\" ::tf/kids []}\n {:topic \"Artists\" ::tf/kids []}]}\n {:topic \"To Do\"\n :expanded true\n ::tf/kids [{:topic \"Spouse Birthday\"\n :expanded nil\n :due-date \"07/31/2025\"\n ::tf/kids [{:topic \"Buy Card\" ::tf/kids []}\n {:topic \"Buy Jewelry\" ::tf/kids []}\n {:topic \"Buy Cake\" ::tf/kids []}]}]}]}\n</code></pre>\n\n<p>processing:</p>\n\n<pre><code> root-hid (add-tree data)\n expanded-hids (find-hids root-hid [:** {:expanded true}])\n ]\n (spy-pretty (hid->bush root-hid))\n (doseq [hid expanded-hids]\n (newline)\n (println \"-----------------------------------------------------------------------------\")\n (spy-pretty :node (hid->node hid))\n (spy-pretty :bush (hid->bush hid)))\n )\n )\n )\n</code></pre>\n\n<p>with results, overall data in \"bush\" format:</p>\n\n<pre><code>[{:tag \"program\", :state \"here\"}\n [{:topic \"Books\", :expanded true}\n [{:topic \"Titles\"}]\n [{:topic \"Authors\", :expanded true}\n [{:topic \"Alice\"}]\n [{:topic \"Bob\"}]\n [{:topic \"Carol\"}]]\n [{:topic \"Genres\"}]]\n [{:topic \"CDs\"}\n [{:topic \"Genres\"}]\n [{:topic \"Albums\"}]\n [{:topic \"Artists\"}]]\n [{:topic \"To Do\", :expanded true}\n [{:topic \"Spouse Birthday\", :expanded nil, :due-date \"07/31/2025\"}\n [{:topic \"Buy Card\"}]\n [{:topic \"Buy Jewelry\"}]\n [{:topic \"Buy Cake\"}]]]]\n</code></pre>\n\n<p>and the 3 nodes with a truthy value for <code>:expanded</code> as both a raw node or a \"bush\":</p>\n\n<pre><code>-----------------------------------------------------------------------------\n :node => \n{:tupelo.forest/khids [1001 1005 1006], :topic \"Books\", :expanded true}\n\n :bush => \n[{:topic \"Books\", :expanded true}\n [{:topic \"Titles\"}]\n [{:topic \"Authors\", :expanded true}\n [{:topic \"Alice\"}]\n [{:topic \"Bob\"}]\n [{:topic \"Carol\"}]]\n [{:topic \"Genres\"}]]\n\n-----------------------------------------------------------------------------\n :node => \n{:tupelo.forest/khids [1002 1003 1004],\n :topic \"Authors\",\n :expanded true}\n\n :bush => \n[{:topic \"Authors\", :expanded true}\n [{:topic \"Alice\"}]\n [{:topic \"Bob\"}]\n [{:topic \"Carol\"}]]\n\n-----------------------------------------------------------------------------\n :node => \n{:tupelo.forest/khids [1015], :topic \"To Do\", :expanded true}\n\n :bush => \n[{:topic \"To Do\", :expanded true}\n [{:topic \"Spouse Birthday\", :expanded nil, :due-date \"07/31/2025\"}\n [{:topic \"Buy Card\"}]\n [{:topic \"Buy Jewelry\"}]\n [{:topic \"Buy Cake\"}]]]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T01:39:02.713",
"Id": "423281",
"Score": "0",
"body": "Did something happen to your code in the migration? The \"processing\" section looks cut off at the top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:14:36.080",
"Id": "423374",
"Score": "0",
"body": "It's OK, just a continuation of the `let` form above`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:47:30.940",
"Id": "423436",
"Score": "0",
"body": "Thanks for pointing out this library. I had not heard of it. My needs are so simple though that I don't need the added dependency at this time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T00:14:12.877",
"Id": "219145",
"ParentId": "219144",
"Score": "2"
}
},
{
"body": "<p>You are right to want to avoid creating the nested structure to begin with. I imagine you read my answer in the question you linked (the second one). As there, here the solution is to use <code>mapcat</code> instead of <code>map</code>. And as I also say in the comments there, while <code>mapcat-indexed</code> does not exist, you can just pass an extra <code>(range)</code> argument to get numbering.</p>\n\n<pre><code>(defn visible-nodes [tree]\n (mapcat (fn [idx ele]\n (map #(cons idx %)\n (cons []\n (when (:expanded ele)\n (visible-nodes (:children ele))))))\n (range), tree))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:45:35.837",
"Id": "423435",
"Score": "0",
"body": "Thanks for this. It works. You are right; I did read your comments on the other question I linked to. That's what prompted me to look for a better solution. I tried using `mapcat` and adding the `(range)` argument with variations of the original function, but could not manage to come up with something that worked."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T01:02:55.180",
"Id": "219146",
"ParentId": "219144",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219146",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T18:24:19.867",
"Id": "219144",
"Score": "4",
"Tags": [
"clojure",
"tree",
"clojurescript"
],
"Title": "Extract indices of visible nodes in a tree where only some nodes are expanded"
} | 219144 |
<p>I put together this code as part of a <a href="https://pastebin.com/VkpDgS9L" rel="nofollow noreferrer">practice problem</a>. The instructions for the program are to accept JSON messages, transform the messages and then dispatch them to the right queue according to a series of rules.</p>
<p>The message service must accept messages when the following method is called: <code>enqueue(msg)</code>. It must provide a single method that returns the next message for the queue with the number <code>queue_number</code>.</p>
<blockquote>
<h2>Transformation Rules</h2>
<p>You must implement the following transformations on input messages. These rules must be applied in order, using the transformed output in later steps. Multiple rules may apply to a single tuple.</p>
<ul>
<li>You must string-reverse any string value in the message that contains the exact string Mootium.
For instance, <code>{"company": "Mootium, Inc.", "agent": "007"}</code> changes to <code>{"company": ".cnI ,muitooM", "agent": "007"}</code>.</li>
<li>You must replace any integer values with the value produced by computing the bitwise negation of that integer's value.
For instance, <code>{"value": 512}</code> changes to <code>{"value": -513}</code></li>
<li>You must add a field hash to any message that has a field <code>_hash</code>. The value of <code>_hash</code> may be the name of another field.
The value of your new field hash must contain the base64-encoded SHA-256 digest of the UTF-8-encoded value of that field. You may assume that the value you're given to hash is a string. If a hash field already exists in the message and the value is different to the computed hash value, then an exception should be thrown.</li>
</ul>
<p>Transformation rules, except the hash rule, must ignore the values of "private" fields whose names begin with an underscore (<code>_</code>).</p>
<h2>Dispatch Rules</h2>
<p>There are five output queues, numbered 0 through 4.</p>
<p>You must implement the following "dispatch" rules to decide which queue gets a message. These rules must be applied in order; the first rule that matches is the one you should use.</p>
<ul>
<li>If a message contains the key <code>_special</code>, send it to queue 0.</li>
<li>If a message contains a hash field, send it to queue 1.</li>
<li>If a message has a value that includes <code>muidaQ</code> (<code>Qadium</code> in reverse), send it to queue 2.</li>
<li>If a message has an integer value, send it to queue 3.</li>
<li>Otherwise, send the message to queue 4.</li>
</ul>
<p>Dispatch rules must ignore the values of "private" fields whose names begin with an underscore (<code>_</code>). (Of course, rules that test the presence of keys that begin with <code>_</code> still apply.)</p>
<h2>Sequences</h2>
<p>Certain messages may be parts of a sequence. Such messages include some special fields:</p>
<ul>
<li><code>_sequence</code>: an opaque string identifier for the sequence this message is part of</li>
<li><code>_part</code>: an integer indicating which message this is in the sequence, starting at 0</li>
</ul>
<p>Sequences must be outputted in order. Dispatch rules are to be applied based on the first message in a sequence (message 0) only, while transformation rules must be applied to all messages.</p>
<p>The output queue must enqueue messages from a sequence as soon as it can; don't try to wait to output all messages of a sequence at a time. The output queue must return messages within a sequence in the correct order by part number (message 0 before message 1, before message 2 ...).</p>
</blockquote>
<pre><code>import queue
import json
import re
import base64
import hashlib
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
class MootiumError(Exception):
"""Raised in the case of requesting a message from an empty queue """
pass
class Queue:
"""Simple delivery message service. Transforms incoming messages
and sends each message to the appropriate queue, keeping sequences in order.
"""
def __init__(self):
#list of output queues
self.queue_dict = {
'0': queue.Queue(),
'1': queue.Queue(),
'2': queue.Queue(),
'3': queue.Queue(),
'4': queue.Queue()
}
#store sequences in a dictionary-like structure
self.sequenceDict = AutoVivification()
def transform(self, msg):
"""Transforms incoming messages to match the transformation rules.
Args:
msg: A string with the message.
Raises:
ValueError: If the message has a key for "hash" and the value
differs from the calculated hash.
Returns:
The transformed data as a dictionary.
"""
messageDict = json.loads(msg)
keys = [i for i in messageDict.keys()]
for i in keys:
# skip private fields
if re.match("_", i):
continue
# reverse strings that include Mootium
if re.search("Mootium", str(messageDict[i])):
messageDict[i] = messageDict[i][::-1]
# replace integer values with its bitwise negation
if isinstance(messageDict[i], int):
messageDict[i] = ~messageDict[i]
if "_hash" in keys:
# if _hash references another field, encode the value from that field.
# otherwise, encode the value associated with _hash
if messageDict["_hash"] in keys:
toEncode = messageDict[messageDict["_hash"]].encode()
else:
toEncode = messageDict["_hash"].encode()
# base64-encoded SHA-256 digest of the UTF-8 encoded value
encodedSHA256 = base64.b64encode(
(hashlib.sha256(toEncode)).digest())
if "hash" in keys:
# make sure the values are the same, if a hash field already exists
if encodedSHA256 != messageDict["hash"]:
raise ValueError(
'The computed hash has a different value from the existing hash field'
)
messageDict["hash"] = encodedSHA256
return messageDict
def dispatch(self, msg, output=None):
"""Delivers a message to the right queue to match the dispatch rules.
Args:
msg: A dictionary with the message.
output: The queue for the message, if it belongs to a sequence
and is not the first part.
Returns:
The number for the queue where the message was delivered.
"""
# set keys and separate public and private message contents
keys = [i for i in msg.keys()]
publicKeys = [i for i in keys if not i.startswith('_')]
publicContents = [msg[i] for i in publicKeys]
#turn the output into string
msgDump = json.dumps(msg)
#for sequenced messages with part > 0
if output:
self.queue_dict[str(output)].put(msgDump)
else:
if "_special" in keys:
output = 0
elif "hash" in publicKeys:
output = 1
elif re.search("muidaQ", str(publicContents)):
output = 2
elif sum([isinstance(msg[i], int) for i in publicKeys]) > 0:
output = 3
else:
output = 4
self.queue_dict[str(output)].put(msgDump)
return output
def enqueue(self, msg):
"""Adds a standard JSON message to the right queue, after applying
the rules for transformation. It will apply the transformations to
messages that belong to a sequence, determine the queue from
the first message in the sequence and add them in proper order.
Args:
msg: A standard JSON message with either strings or numerics.
"""
cleanmsg = self.transform(msg)
if "_sequence" in [i for i in cleanmsg.keys()]:
sequence = cleanmsg["_sequence"]
part = cleanmsg["_part"]
self.sequenceDict[sequence][part] = cleanmsg
if part == "0":
#dispatch the first message and get the queue number
self.sequenceDict[sequence]["output"] = self.dispatch(cleanmsg)
self.sequenceDict[sequence]["current"] = 0
# send the next message, if it is available and the output is set
if self.sequenceDict[sequence]["output"]:
output = self.sequenceDict[sequence]["output"]
while self.sequenceDict[sequence][str(
self.sequenceDict[sequence]["current"] + 1)]:
self.sequenceDict[sequence][
"current"] = self.sequenceDict[sequence]["current"] + 1
self.dispatch(
self.sequenceDict[sequence][str(
self.sequenceDict[sequence]["current"])], output)
else:
self.dispatch(cleanmsg)
def next(self, queue_number):
"""Pulls the next value from the specified queue.
Args:
msg: A standard JSON message with either strings or numerics.
Raises:
ValueError: If the queue number is outside the range of options.
QadiumError: If the requested queue is empty.
Returns:
The next value in the selected queue.
"""
valueError = 'Check your queue_number. Valid options include: 0, 1, 2, 3, 4.'
if queue_number not in [0, 1, 2, 3, 4]:
raise ValueError(valueError)
try:
return self.queue_dict[str(queue_number)].get(block=False)
except queue.Empty:
raise MootiumError("Nothing is available on the queue")
def get_message_service():
"""Returns a new, "clean" Q service."""
return Queue()
</code></pre>
<p>I'm curious for feedback. In particular, what would you have used instead of the auto vivification and are there ways you would make this more efficient or pieces of code you would exclude?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:11:06.343",
"Id": "423294",
"Score": "1",
"body": "Welcome to Code Review! Please put the description of the task you want to accomplish (possibly abbreviated) directly in the question. Otherwise your question will lose in quality or even become useless as reference for others once the pastebin link goes down."
}
] | [
{
"body": "<p>Welcome to Codereview, and welcome to Python!</p>\n\n<p>Your code looks good -- indentation is good, names are mostly good (but see below), docblock comments are mostly good (but see below). It seems like you need to \"soak in\" Python a bit, and you'll be up and running.</p>\n\n<h3>Names</h3>\n\n<p>Python's coding standard is <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> which for the purposes of naming can be simplified to:</p>\n\n<ul>\n<li><code>snake_case</code> except for classes</li>\n<li><code>CAPS</code> for constants</li>\n<li>unless you have to do something else</li>\n</ul>\n\n<p>Since your method names were mostly determined by the problem spec, you didn't have a lot of wiggle room. I still fault you for being inconsistent, though:</p>\n\n<pre><code> self.queue_dict = { ... }\n self.sequenceDict = AutoVivification()\n</code></pre>\n\n<p>That last attribute should be <code>sequence_dict</code>. Except putting type in names is so Windows 3.1! So maybe <code>pending_sequences</code>.</p>\n\n<h3>Comments</h3>\n\n<p>If your comment says in English what the code says in Python, delete it. Comments should explain parts of the code that aren't clear or that have possibly-surprising effects.</p>\n\n<pre><code> #list of output queues\n self.queue_dict = {\n</code></pre>\n\n<p>This comment is already a lie, since <code>queue_dict</code> isn't a <code>list</code> at all!</p>\n\n<p>Also, there's a copy/paste error in the docblock for <code>next</code>: the Args are wrong.</p>\n\n<h3>Types</h3>\n\n<p>The name for <code>AutoVivification</code> is <a href=\"https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>.</p>\n\n<p><code>class MootiumError</code> should have a different name, since it has a fairly specific purpose. Considering that you later catch <code>queue.Empty</code>, I'm surprised at your choice. Perhaps <code>MootiumQueueEmpty</code>? Or even <code>MootiumQueueError</code>?</p>\n\n<p>You construct a dictionary of numbered queues, but index the dictionary with strings. Then in <code>dispatch</code> you have to convert your number to a string to index the queue. Why not just use integer keys for the dictionary? Better still, why not use a list, which takes integer keys always? (And it would make your comment valid again!)</p>\n\n<pre><code>def __init__(self):\n self.queue_dict = [queue.Queue() for _ in range(5)]\n # Store sequence-parts in a se[arate dict for each sequence\n self.pending_sequences = collections.defaultdict(dict)\n</code></pre>\n\n<p>There are three iterator functions for dictionaries: <code>keys()</code>, <code>values()</code>, and <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict%20items#dict.items\" rel=\"nofollow noreferrer\"><code>items()</code></a>. The <code>items</code> iterator yields (key, value) tuples.</p>\n\n<p>Dictionaries can be checked for the presence of keys using the <code>in</code> operator. Strings can be checked for substrings using the <code>in</code> operator. Sequences can be linearly scanned for items using the <code>in</code> operator. It's the most expensive way. Naturally, that's what you're doing. Don't do that!</p>\n\n<p>Python is not as regex-first as Perl. So there are non-re string functions, like <code>startswith</code>. They're faster and more expressive.</p>\n\n<pre><code>def transform(self, msg):\n \"\"\" ... \"\"\"\n\n message = json.loads(msg)\n\n for k, v in message.items():\n if k.startswith('_'):\n continue\n\n # reverse strings that include Mootium \n if isinstance(v, str) and 'Mootium' in v:\n message[k] = v[::-1]\n\n # replace integer values with its bitwise negation\n elif isinstance(v, int):\n message[k] = ~v\n\n if '_hash' in message:\n # if _hash references another field, encode the value from that field.\n # otherwise, encode the value associated with _hash\n if message[\"_hash\"] in message:\n toEncode = message[message[\"_hash\"]].encode()\n else:\n toEncode = message[\"_hash\"].encode()\n\n digest = base64.b64encode(hashlib.sha256(toEncode).digest())\n\n if message.setdefault('hash', digest) != digest:\n raise ValueError(\n 'The computed hash has a different value from the existing hash field'\n )\n return message\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T03:44:34.433",
"Id": "219150",
"ParentId": "219148",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219150",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T01:34:29.630",
"Id": "219148",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"json",
"queue"
],
"Title": "JSON messaging queue with transformation and dispatch rules"
} | 219148 |
<p>This is my second attempt with unit-tests. Like my <a href="https://codereview.stackexchange.com/questions/217810/gui-button-element-with-unit-tests">previous attempt</a>, I would prefer a focus on the unit-tests, however I am always happy to improve my code in any way reviewers can help.</p>
<p>Once again it is just a single class along with supporting unit-tests. The class is named <code>UpgradeButton</code> and represents upgrades that the user can purchase in the game.</p>
<p>The button still looks like this:</p>
<p><a href="https://i.stack.imgur.com/pZHsV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pZHsV.png" alt="Rectangle button with mouse over it and a green and red indicator"></a></p>
<p>The boxes along the bottom are updated programatically through the input() and update() functions that indicate what level you are at and what you can purchase. The number of tiers is assigned in the constructor, as is the label.</p>
<p><code>Expressions.h</code> is just a header of <code>constexpr</code> for replacing magic numbers, and as you can see I am using SFML. Version 2.4.2 if it matters. I'd also like to point out that I am aware of the difference between <code>#pragma once</code> and include guards. I chose the former because they are less verbose and supported by the major compilers. Lastly, it is a small personal project, completely in my control.</p>
<p><strong><code>UpgradeButton.h</code></strong></p>
<pre><code>#pragma once
#include "Expressions.h"
#include <Graphics.hpp>
#include <string>
namespace fleet {
class UpgradeButton : public sf::Drawable {
public:
explicit UpgradeButton(const std::string& newLabel, const sf::Font& font, unsigned short numUpgrades);
void setPosition(float x, float y);
void setPosition(const sf::Vector2f& position);
void setLabelString(const std::string& string);
void setCharacterSize(unsigned newSize);
void setTextFillColor(const sf::Color& color);
const sf::Vector2f& getPosition() const { return button.getPosition(); }
const sf::String& getLabelString() const { return label.getString(); }
unsigned getCharacterSize() const { return label.getCharacterSize(); }
const sf::Color& getTextFillColor() const { return label.getFillColor(); }
const std::vector<sf::RectangleShape>& getIndicators() const { return indicators; }
bool input(const sf::Vector2f& mousePos, bool canAfford);
void update(const sf::Vector2f& mousePos, unsigned currentLevel, bool canAfford);
private:
sf::RectangleShape button{ sf::Vector2f(default_upgrade_width, default_upgrade_height) };
sf::Text label;
std::vector<sf::RectangleShape> indicators;
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
};
}
</code></pre>
<p><strong><code>UpgradeButton.cpp</code></strong></p>
<pre><code>#include "UpgradeButton.h"
#include "Exceptions.h"
namespace fleet {
UpgradeButton::UpgradeButton(const std::string& newLabel, const sf::Font& font, unsigned short numUpgrades) :
label{ newLabel, font }
{
if (numUpgrades == 0) {
throw DivideByZeroException("Attempted to divide by zero in the constructor of UpgradeButton");
}
float indicatorWidth = default_upgrade_width / numUpgrades;
for (unsigned i = 0; i < numUpgrades; ++i) {
indicators.emplace_back(sf::RectangleShape(sf::Vector2f(indicatorWidth, default_indicator_height)));
}
button.setFillColor(sf::Color::Cyan);
button.setOutlineThickness(upgrade_button_outline);
for (auto& indicator : indicators) {
indicator.setFillColor(sf::Color::Cyan);
indicator.setOutlineThickness(upgrade_button_outline);
}
}
// UpgradeButton requires one call to setPosition minimum to properly initialize indicators
// in there proper position. Failure to do so will leave them all positioned at 0, 0;
void UpgradeButton::setPosition(float x, float y)
{
button.setPosition(x, y);
float indicatorX = x;
float indicatorY = y + (default_upgrade_height - default_indicator_height);
for (auto& indicator : indicators) {
indicator.setPosition(indicatorX, indicatorY);
indicatorX += indicator.getSize().x;
}
float labelY = y + default_upgrade_height + upgrade_label_y_offset;
label.setPosition(x, labelY);
}
void UpgradeButton::setPosition(const sf::Vector2f& position)
{
setPosition(position.x, position.y);
}
void UpgradeButton::setLabelString(const std::string& string)
{
label.setString(string);
}
void UpgradeButton::setCharacterSize(unsigned newSize)
{
label.setCharacterSize(newSize);
}
void UpgradeButton::setTextFillColor(const sf::Color& color)
{
label.setFillColor(color);
}
bool UpgradeButton::input(const sf::Vector2f& mousePos, bool canAfford)
{
return canAfford && button.getGlobalBounds().contains(mousePos);
}
void UpgradeButton::update(const sf::Vector2f& mousePos, unsigned currentLevel, bool canAfford)
{
for (unsigned i = 0; i < currentLevel && i < indicators.size(); ++i) {
indicators[i].setFillColor(sf::Color::Green);
}
for (unsigned i = currentLevel; i < indicators.size(); ++i) {
indicators[i].setFillColor(sf::Color::Cyan);
}
if (currentLevel >= indicators.size()) { return; }
if (button.getGlobalBounds().contains(mousePos)) {
if (canAfford) {
indicators[currentLevel].setFillColor(sf::Color::Green);
}
else {
indicators[currentLevel].setFillColor(sf::Color::Red);
}
}
else {
indicators[currentLevel].setFillColor(sf::Color::Cyan);
}
}
void UpgradeButton::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(button, states);
for (auto& indicator : indicators) {
target.draw(indicator, states);
}
target.draw(label, states);
}
}
</code></pre>
<p>As for the tests. I am using Google Test. I got rid of the tests of primitive setter methods. They always felt exceedingly trivial. I tried to recognize the assumptions I make in my code and then test for it, but I have found that isn't as easy as it sounds. There are currently nine tests, and they all pass. </p>
<p><strong><code>UpgradeButtonTests.cpp</code></strong></p>
<pre><code>#include "gtest/gtest.h"
#include "UpgradeButton.h"
#include "Exceptions.h"
#include "Expressions.h"
#include <Graphics.hpp>
namespace fleet {
class UpgradeButtonTest : public testing::Test {
protected:
UpgradeButton* button;
};
TEST_F(UpgradeButtonTest, constructor_accepts_empty_string) {
button = new UpgradeButton("", sf::Font(), 5);
ASSERT_STREQ("", button->getLabelString().toAnsiString().c_str());
delete button;
}
TEST_F(UpgradeButtonTest, constructor_handles_large_strings) {
std::string longString = "This is a very long string to test that the constructor of the \
UpgradeButton class properly handles very long strings.";
button = new UpgradeButton(longString, sf::Font(), 5);
ASSERT_EQ(longString, button->getLabelString());
}
TEST_F(UpgradeButtonTest, constructor_fails_on_zero) {
ASSERT_THROW(button = new UpgradeButton("Test String", sf::Font(), 0), DivideByZeroException);
}
TEST_F(UpgradeButtonTest, text_is_white_on_contruction) {
button = new UpgradeButton("Test String", sf::Font(), 5);
ASSERT_EQ(sf::Color::White, button->getTextFillColor());
}
TEST_F(UpgradeButtonTest, indicators_stacked_at_origin_point_on_construction) {
button = new UpgradeButton("Test String", sf::Font(), 5);
for (auto& indicator : button->getIndicators())
{
ASSERT_EQ(sf::Vector2f(), indicator.getPosition());
}
}
TEST_F(UpgradeButtonTest, setPosition_sets_indicators_correctly) {
unsigned short numIndicators = 5;
button = new UpgradeButton("Test String", sf::Font(), numIndicators);
sf::Vector2f position(5.F, 5.F);
button->setPosition(position);
float indicatorX = position.x;
float indicatorY = position.y + (default_upgrade_height - default_indicator_height);
for (auto& indicator : button->getIndicators()) {
ASSERT_FLOAT_EQ(indicatorX, indicator.getPosition().x);
ASSERT_FLOAT_EQ(indicatorY, indicator.getPosition().y);
indicatorX += indicator.getSize().x;
}
position = sf::Vector2f(indicatorX, indicatorY);
button->setPosition(position);
indicatorY = position.y + (default_upgrade_height - default_indicator_height);
for (auto& indicator : button->getIndicators()) {
ASSERT_FLOAT_EQ(indicatorX, indicator.getPosition().x);
ASSERT_FLOAT_EQ(indicatorY, indicator.getPosition().y);
indicatorX += indicator.getSize().x;
}
}
TEST_F(UpgradeButtonTest, input) {
button = new UpgradeButton("Test String", sf::Font(), 5);
ASSERT_TRUE(button->input(sf::Vector2f(), true));
ASSERT_FALSE(button->input(sf::Vector2f(), false));
ASSERT_FALSE(button->input(sf::Vector2f(500.F, 900.F), true));
ASSERT_FALSE(button->input(sf::Vector2f(500.F, 900.F), false));
}
TEST_F(UpgradeButtonTest, update_does_not_fail_out_of_range) {
unsigned short numIndicators = 5;
button = new UpgradeButton("Test String", sf::Font(), numIndicators);
numIndicators += 7;
ASSERT_NO_THROW(button->update(sf::Vector2f(), numIndicators, true));
}
TEST_F(UpgradeButtonTest, update_handles_mousePos_correctly) {
unsigned short numIndicators = 5;
button = new UpgradeButton("Test String", sf::Font(), numIndicators);
button->update(sf::Vector2f(-10.F, -10.F), 0, true);
for (auto& indicator : button->getIndicators()) {
ASSERT_EQ(sf::Color::Cyan, indicator.getFillColor());
}
button->update(sf::Vector2f(), 0, true);
ASSERT_EQ(sf::Color::Green, button->getIndicators()[0].getFillColor());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:49:16.210",
"Id": "423622",
"Score": "2",
"body": "I think there is a small typo in the comment for the `setPosition` function (there/their)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T12:21:28.240",
"Id": "423624",
"Score": "1",
"body": "@yuri good catch thanks. I fixed it in my repo but not here as it is a trivial edit. If I find another reason to edit the post hopefully I remember to fix that as well."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T04:07:47.883",
"Id": "219151",
"Score": "3",
"Tags": [
"c++",
"unit-testing",
"gui",
"sfml"
],
"Title": "GUI Button Element with Unit Tests follow-up"
} | 219151 |
<p>I made this hex dump after being dissatisfied with the free hexdumps out there. The biggest dissatisfaction is that the encodings for the char bytes were not color encoded, just like the hexyl hexdump program.</p>
<p>If you are interested in reading the full background story, you may click on the Medium link: <a href="https://medium.com/@tanveerasalim/my-new-colorful-hex-dump-command-a114a043b61c" rel="nofollow noreferrer">https://medium.com/@tanveerasalim/my-new-colorful-hex-dump-command-a114a043b61c</a></p>
<p>I tested this hexdump on macOS, Linux, and Windows (CYGWIN) before posting here. </p>
<p>I plan to transform this hex dump into an actual vim-like hex editor, since I could not find a preexisting one of the like of it either.</p>
<p>Instructions For Use:</p>
<p>NAME</p>
<p>tscd</p>
<p>SYNOPSIS</p>
<p>tscd [options] [infile [outfile]]</p>
<p>DESCRIPTION</p>
<p>tscd can create a hexadecimal, decimal, binary, or octal dump of any file. The numerical values will be displayed in a table.To the rightmost of each row will be the ASCII characters corresponding to the ASCII codes in the table.</p>
<p>COLOR ENCODINGS</p>
<p>Below is the Color Encoding Scheme (ASCII):</p>
<p>Red: Non-printable ASCII characters</p>
<p>Orange: Printable (Alphabetic) Characters</p>
<p>Yellow: Base 10 Numerical Digits</p>
<p>Green: ASCII Whitespace Characters</p>
<p>Purple: Punctuation Characters</p>
<p>Gray: NUL byte (00)</p>
<p>OPTIONS</p>
<p>-b Binary dump specified. Each character in file will be translated into its binary number form and displayed in the table.</p>
<p>-c Specify number of columns per row in ASCII code table.</p>
<p>-d Decimal Dump specified. Each character in file will be translated into its binary number form and displayed in the table.</p>
<p>-o Octal Dump specified. Each character in file will be translated into its octal number form and displayed in the table.</p>
<p>-p Print view specified. tscd will simply print the contents of the file directly intointo stdout.</p>
<p>Questions:</p>
<ol>
<li><p>Would you actually prefer to use this compared to all other free command-line hexdumps out there, not counting GUI-based ones?</p></li>
<li><p>Are you interested in me transforming this program into a vim-like color-encoded hex editor program?</p></li>
<li><p>Are you also confident the implementation is portable across Windows (such as on CYGWIN), macOS, and Linux systems?</p></li>
</ol>
<p>Implementation:</p>
<p>The link to the GitHub Repository page is: <a href="https://github.com/tanveerasalim/TSCD" rel="nofollow noreferrer">https://github.com/tanveerasalim/TSCD</a></p>
<p>The complete implementation of the hex dump is below:</p>
<pre><code>#if 0
NOTICE: All the software in this repository
comes with absolutely
NO WARRANTY and provided "as is" basis.
Copyright (C) Tanveer Salim 2018-INFINITY
This software and all other software in
this repository is distributed with a GNU GPL
License v2.0. All are free to copy, share,
distribute, and/or modify this software,
even commercially as long as it compliant
with GNU GPL v2.0 LICENSING terms as well
as the terms of this copyright and license
statement.
All software that was inspired
or is a derivative of this work must have
the exact same LICENSE and copyright permissions.
#endif
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#ifndef __rsize_t_defined
typedef size_t rsize_t;
#define __rsize_t_defined 1
#endif
#ifdef __RSIZE_MAX__
#define RSIZE_MAX (__RSIZE_MAX__)
#else
#define RSIZE_MAX ( (SIZE_MAX ) >> ( 1 ) )
#endif
#ifndef __uint8_t_defined
typedef unsigned char uint8_t;
#define __uint8_t_defined 1
#endif
#ifndef __uint32_t_defined
typedef unsigned int uint32_t;
#define __uint32_t_defined 1
#endif
#if 0
Bug: When Number of characters in row
is equal to NUM_HEX_ROWS, the last f
in 0xff is deleted and replaced with
a period.
Bug: Number of columns == Number of bytes per row!
NUM_HEX_ROWS == (desired number of columns)/2
default number of columns: 16 to make 16 bytes displayed in total per row
So:
NUM_HEX_ROWS == Number of desired columns
Simple! :D
#endif
//#define NUM_HEX_ROWS_ORIGINAL 16
rsize_t NUM_HEX_ROWS = 16;
rsize_t NUM_BIN_ROWS = 6;
rsize_t NUM_OCT_ROWS = 12;
rsize_t NUM_DEC_ROWS = 12;
rsize_t UTF8_HEX_ROWS = 6;
_Bool bintable_request = 0;
_Bool octtable_request = 0;
_Bool dectable_request = 0;
void colorchar(uint8_t c)
{
if ( c == 0x0 )
{
printf("\e[38;5;244m");
}
else if ( isalpha(c) )
{
printf("\e[38;5;208m");
}
else if ( isdigit(c) )
{
printf("\e[38;5;226m");
}
else if ( !isprint(c) )
{
printf("\e[38;5;196m");
}
else if ( isspace(c) )
{
printf("\e[38;5;40m");
}
else if ( ispunct(c) )
{
// printf("\e[38;5;164m");
printf("\e[38;5;201m");
}
else if ( c < 16 )
{
printf("\e[0;32m");
}
else if ( c >= 16 && c <= 31 )
{
printf("\e[1;35m");
}
}
void resetcolor(void)
{
printf("\033[0m");
}
_Bool isutf8cntrl(uint32_t c)
{
}
void colorutf8(uint8_t * s)
{
uint32_t utf8_hex = 0x00;
uint8_t * s_p = s;
while ( *s_p != 0x00 )
{
utf8_hex += *s_p;
utf8_hex <<= 8;
s_p++;
}
}
void printview(FILE * in, FILE * out,const rsize_t FILE_SIZE)
{
rsize_t i = 0;
uint8_t c = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
if ( out != stdout )
{
fprintf(out,"%c",c);
}
else
{
colorchar(c);
printf("%c",c);
resetcolor();
}
i++;
}
}
void reverse(unsigned char s[])
{
for (int i = 0, j = strlen(s)-1; i < j; i++, j--)
{
unsigned char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
unsigned char * print_binary(unsigned char input)
{
static unsigned char s[10];
unsigned char * s_p = &s[0];
while (input > 0)
{
*s_p++ = (unsigned char)((input&1)+'0');
input >>= 1;
}
*s_p = '\0';
reverse(s);
return s;
}
void print_bintable2(FILE * in, FILE * out, unsigned char ASCII[], const rsize_t FILE_SIZE)
{
rsize_t i = 0;
rsize_t u = 0;
unsigned long fpos = 0;
rsize_t j = 0; //need this to create printable ASCII in output
unsigned char c = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
#if 0
This printf actually forces printing of ASCII.
#endif
if ( i == 0 )
{ colorchar(c); fprintf(out,"%08x:%c",i,0x20); resetcolor(); }
else if ( (i%NUM_BIN_ROWS) == 0 )
{
fputc(0x20,out);
if ( i >= NUM_BIN_ROWS )
{
fseek(in,-NUM_BIN_ROWS-1,SEEK_CUR);
}
else
{
fseek(in,0,SEEK_SET);
}
u = 0;
while (
u < NUM_BIN_ROWS
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
c = fgetc(in); //catch up to latest row
colorchar(c);
fprintf(out,"\n%08x:%c",i,0x20);
resetcolor();
}
colorchar(c);
fprintf(out,"%08s%c",print_binary(c),0x20);
resetcolor();
#if 0
(i%2 == 0) ? ( fprintf(out,"%08s",print_binary(c)) ) : ( fprintf(out,"%08s%c",print_binary(c),0x20) );
#endif
i++;
// Bug: Write code to place ff and extra spaces to align last ASCII line here
}
if ( i == FILE_SIZE )
{
rsize_t index = i;
while ( index % NUM_BIN_ROWS != 0 )
{
(index%2 == 0)
?
( fprintf(out,"%*c",0x9,0x20) )
:
( fprintf(out,"%*c",0x9,0x20) );
index++;
}
#if 0
This while loop is meant for
a line that is equal to
NUM_BIN_ROWS
#endif
if ( index % NUM_BIN_ROWS == 0 )
{
fputc(0x20,out);
}
}
if ( i == FILE_SIZE && (i%NUM_BIN_ROWS) != 0 )
{
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(i%NUM_BIN_ROWS),SEEK_CUR);
u = 0;
while (
u < ( i%NUM_BIN_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
else // ( i == FILE_SIZE && (i%NUM_BIN_ROWS) == 0 )
{
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(NUM_BIN_ROWS),SEEK_CUR);
u = 0;
while (
u < ( NUM_BIN_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
}
void print_dectable(FILE * in, FILE * out, unsigned char ASCII[], const rsize_t FILE_SIZE)
{
rsize_t i = 0;
rsize_t u = 0;
unsigned long fpos = 0;
rsize_t j = 0; //need this to create printable ASCII in output
unsigned char c = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
colorchar(c);
#if 0
This printf actually forces printing of ASCII.
#endif
if ( i == 0 )
{ fprintf(out,"%08x:%c",i,0x20); }
else if ( (i%NUM_DEC_ROWS) == 0 )
{
fputc(0x20,out);
fputc(0x20,out);
if ( i >= NUM_DEC_ROWS )
{
fseek(in,-NUM_DEC_ROWS-1,SEEK_CUR);
}
else
{
fseek(in,0,SEEK_SET);
}
u = 0;
while (
u < NUM_DEC_ROWS
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
c = fgetc(in); //catch up to latest row
colorchar(c);
fprintf(out,"\n%08x:%c",i,0x20);
resetcolor();
}
colorchar(c);
(i%1 != 0) ? ( fprintf(out,"%03u",c) ) : ( fprintf(out,"%c%03u",0x20,c) );
i++;
resetcolor();
// Bug: Write code to place ff and extra spaces to align last ASCII line here
}
if ( i == FILE_SIZE )
{
rsize_t index = i;
while ( index % NUM_DEC_ROWS != 0 )
{
(index%2 == 0)
?
( fprintf(out,"%c%c%c%c",0x20,0x20,0x20,0x20) )
:
( fprintf(out,"%c%c%c%c",0x20,0x20,0x20,0x20) );
index++;
}
#if 0
This while loop is meant for
a line that is equal to
NUM_DEC_ROWS
#endif
if ( index % NUM_DEC_ROWS == 0 )
{
fputc(0x20,out);
}
}
if ( i == FILE_SIZE && (i%NUM_DEC_ROWS) != 0 )
{
fputc(0x20,out);
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(i%NUM_DEC_ROWS),SEEK_CUR);
u = 0;
while (
u < ( i%NUM_DEC_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
else // ( i == FILE_SIZE && (i%NUM_DEC_ROWS) == 0 )
{
fputc(0x20,out);
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(NUM_DEC_ROWS),SEEK_CUR);
u = 0;
while (
u < ( NUM_DEC_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
}
void print_octtable(FILE * in, FILE * out, unsigned char ASCII[], const rsize_t FILE_SIZE)
{
rsize_t i = 0;
rsize_t u = 0;
unsigned long fpos = 0;
rsize_t j = 0; //need this to create printable ASCII in output
unsigned char c = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
colorchar(c);
#if 0
This printf actually forces printing of ASCII.
#endif
if ( i == 0 )
{ fprintf(out,"%08x:%c",i,0x20); }
else if ( (i%NUM_OCT_ROWS) == 0 )
{
fputc(0x20,out);
fputc(0x20,out);
if ( i >= NUM_OCT_ROWS )
{
fseek(in,-NUM_OCT_ROWS-1,SEEK_CUR);
}
else
{
fseek(in,0,SEEK_SET);
}
u = 0;
while (
u < NUM_OCT_ROWS
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
c = fgetc(in); //catch up to latest row
colorchar(c);
fprintf(out,"\n%08x:%c",i,0x20);
resetcolor();
}
colorchar(c);
(i%1 != 0) ? ( fprintf(out,"%03o",c) ) : ( fprintf(out,"%c%03o",0x20,c) );
i++;
resetcolor();
// Bug: Write code to place ff and extra spaces to align last ASCII line here
}
if ( i == FILE_SIZE )
{
rsize_t index = i;
while ( index % NUM_OCT_ROWS != 0 )
{
(index%2 == 0)
?
( fprintf(out,"%c%c%c%c",0x20,0x20,0x20,0x20) )
:
( fprintf(out,"%c%c%c%c",0x20,0x20,0x20,0x20) );
index++;
}
#if 0
This while loop is meant for
a line that is equal to
NUM_OCT_ROWS
#endif
if ( index % NUM_OCT_ROWS == 0 )
{
fputc(0x20,out);
}
}
if ( i == FILE_SIZE && (i%NUM_OCT_ROWS) != 0 )
{
fputc(0x20,out);
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(i%NUM_OCT_ROWS),SEEK_CUR);
u = 0;
while (
u < ( i%NUM_OCT_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
else // ( i == FILE_SIZE && (i%NUM_OCT_ROWS) == 0 )
{
fputc(0x20,out);
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(NUM_OCT_ROWS),SEEK_CUR);
u = 0;
while (
u < ( NUM_OCT_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
}
#if 0
For is_utf8cont, assume correct UTF-8 encoding
#endif
#if 0
_Bool is_utf8cont(uint8_t c)
{
//First try to disprove by detecting starting byte
if ( ( c >> 3 ) == 0b11110 )
{
return 0;
}
else if ( ( c >> 4 ) == 0b1110 )
{
return 0;
}
else if ( ( c >> 5 ) == 0b110 )
{
return 0;
}
else if ( ( c >> 7 ) == 0b0 )
{
return 0;
}
return 1;
}
#endif
#if 0
void print_utf8hextable(FILE * in, FILE * out,const rsize_t FILE_SIZE)
{
rsize_t i = 0;
rsize_t utf8i = 0; //for printing actual UTF8 character
static uint32_t utf8_hex = 0x00;
const rsize_t UTF8_STR_SIZE = UTF8_HEX_ROWS*4*sizeof(uint8_t)+1;
static uint8_t utf8_str[UTF8_HEX_ROWS*4*sizeof(uint8_t)+1];
memset_s(utf8_str,UTF8_STR_SIZE,0x00,UTF8_STR_SIZE);
static uint8_t c = 0;
static long utf8_offsets[UTF8_HEX_ROWS];
static long * utf8op;
utf8op = utf8_offsets;
rsize_t cur_utf8char = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
#if 0
Print actual hexadecimal representation of UTF-8
character
#endif
if ( i == 0 )
{
printf("%.08x: ",i);
}
else if ( !is_utf8cont(c) ) //starting byte for UTF-8 character
{
printf("%.08x ",utf8_hex);
utf8_hex = 0x00;
*utf8op = ftell(in);
}
else
{
utf8_hex += c;
utf8_hex <<= 8;
utf8_hex &= 0xffffff00
}
if ( utf8i == UTF8_HEX_ROWS )
{
cur_utf8char = ftell(in);
utf8op = utf8_offsets;
rsize_t ic = 0;
while ( utf8op < (utf8_offsets + UTF8_HEX_ROWS) )
{
fseek(in,*utf8op,SEEK_BEG);
while (ic > 0 && !is_utf8cont(c) )
{
c = fgetc(in);
fputc(c,out);
ic++;
}
utf8op++;
ic = 0;
}
memset_s(utf8_offsets,UTF8_HEX_ROWS*sizeof(uint8_t),0x00,UTF8_HEX_ROWS*sizeof(uint8_t));
fseek(in,cur_utf8char,SEEK_BEG);
utf8i = 0;
printf("\n%.08x: ",i);
}
else
{
utf8i++;
}
i++;
}
}
#endif
void print_hextable(FILE * in, FILE * out, unsigned char ASCII[], const rsize_t FILE_SIZE)
{
rsize_t i = 0;
rsize_t u = 0;
unsigned long fpos = 0;
rsize_t j = 0; //need this to create printable ASCII in output
unsigned char c = 0;
while ( i < FILE_SIZE )
{
c = fgetc(in);
colorchar(c);
#if 0
This printf actually forces printing of ASCII.
#endif
if ( i == 0 )
{ fprintf(out,"%08x:%c",i,0x20); }
else if ( (i%NUM_HEX_ROWS) == 0 )
{
fputc(0x20,out);
fputc(0x20,out);
if ( i >= NUM_HEX_ROWS )
{
fseek(in,-NUM_HEX_ROWS-1,SEEK_CUR);
}
else
{
fseek(in,0,SEEK_SET);
}
u = 0;
while (
u < NUM_HEX_ROWS
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
c = fgetc(in); //catch up to latest row
colorchar(c);
fprintf(out,"\n%08x:%c",i,0x20);
resetcolor();
}
colorchar(c);
(i%1 != 0) ? ( fprintf(out,"%02x",c) ) : ( fprintf(out,"%c%02x",0x20,c) );
i++;
resetcolor();
// Bug: Write code to place ff and extra spaces to align last ASCII line here
}
if ( i == FILE_SIZE )
{
rsize_t index = i;
while ( index % NUM_HEX_ROWS != 0 )
{
(index%2 == 0)
?
( fprintf(out,"%c%c%c",0x20,0x20,0x20) )
:
( fprintf(out,"%c%c%c",0x20,0x20,0x20) );
index++;
}
#if 0
This while loop is meant for
a line that is equal to
NUM_HEX_ROWS
#endif
if ( index % NUM_HEX_ROWS == 0 )
{
fputc(0x20,out);
fputc(0x20,out);
}
}
if ( i == FILE_SIZE && (i%NUM_HEX_ROWS) != 0 )
{
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(i%NUM_HEX_ROWS),SEEK_CUR);
u = 0;
while (
u < ( i%NUM_HEX_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
else // ( i == FILE_SIZE && (i%NUM_HEX_ROWS) == 0 )
{
rsize_t space_align = i;
fpos = ftell(in);
fseek(in,-(NUM_HEX_ROWS),SEEK_CUR);
u = 0;
while (
u < ( NUM_HEX_ROWS )
)
{
( c = fgetc(in) );
colorchar(c);
if ( isprint(c) )
{
fputc(c,out);
}
else
{
fprintf(out,"\u00b7");
}
u++;
resetcolor();
}
fseek(in,fpos,SEEK_SET);
}
}
#if 0
Last argument, argument index
argc-1, must have filename
#endif
int main(int argc, char ** argv)
{
FILE * in = NULL;
FILE * out = stdout;
if ( argc < 2 )
{
fprintf(in,"%llu: Less than two arguments!\n",__LINE__);
return 1;
}
if ( ( (argc-2) > 0 ) && ( ( in = fopen(argv[argc-2],"rb") ) != NULL ) )
{
if ( ( out = fopen(argv[argc-1],"wb+") ) == NULL )
{
fprintf(stderr,"\033[1;31m\n\0");
fprintf(stdout,"%llu: Failed to write to file %s!\n",__LINE__,argv[argc-1]);
fprintf(stderr,"\033[0m\n\0");
return 1;
}
}
else if ( ( in = fopen(argv[argc-1],"rb") ) == NULL )
{
fprintf(stderr,"\033[1;31m\n\0");
fprintf(stdout,"%llu: Failed to open file!\n",__LINE__);
fprintf(stderr,"\033[0m\n\0");
return 1;
}
fseek(in,0L,SEEK_END);
const rsize_t SIZE = ftell(in);
static unsigned char * ascii_line;
ascii_line = (unsigned char *)calloc(NUM_HEX_ROWS+1,sizeof(unsigned char));
rewind(in);
while ( *++argv != NULL && **argv == 0x2d )
{
switch ( *++(*argv) )
{
case 0x63:
{
// get column number
char const * column_num = *++argv;
while ( isdigit( *(*argv) ) != 0 )
{ (*argv)++; }
if ( **argv != 0x0 )
{
fprintf(stderr,"\033[1;31m\n\0");
fprintf(stderr,"%llu: Error! Column"
" argument is not a"
" type of unsigned"
" integer!\n",
__LINE__
);
fprintf(stderr,"\033[0m\n\0");
return 1;
}
NUM_HEX_ROWS = (rsize_t)strtol(column_num,NULL,10);
free(ascii_line);
ascii_line = (unsigned char *)calloc(NUM_HEX_ROWS,sizeof(unsigned char));
NUM_BIN_ROWS = (rsize_t)strtol(column_num,NULL,10);
NUM_OCT_ROWS = (rsize_t)strtol(column_num,NULL,10);
NUM_DEC_ROWS = (rsize_t)strtol(column_num,NULL,10);
break;
}
case 0x62:
{
bintable_request = 1;
free(ascii_line);
ascii_line = (unsigned char *)calloc(NUM_BIN_ROWS+1,sizeof(unsigned char));
break;
}
case 0x64:
{
dectable_request = 1;
free(ascii_line);
ascii_line = (unsigned char *)calloc(NUM_DEC_ROWS+1,sizeof(unsigned char));
break;
}
case 0x6f:
{
octtable_request = 1;
free(ascii_line);
ascii_line = (unsigned char *)calloc(NUM_OCT_ROWS+1,sizeof(unsigned char));
break;
}
case 0x70:
{
printview(in,out,SIZE);
return 0;
}
default:
{
break;
}
}
}
if ( dectable_request == 1 )
{
print_dectable(in,out,ascii_line,SIZE);
}
else if ( octtable_request == 1 )
{
print_octtable(in,out,ascii_line,SIZE);
}
else if ( bintable_request == 1 )
{
print_bintable2(in,out,ascii_line,SIZE);
}
else
{
print_hextable(in,out,ascii_line,SIZE);
}
if ( fclose(in) == EOF )
{
fprintf(stderr,"\033[1;31m\n\0");
fprintf(stderr,"%llu: Error! Failed to close %s\n",__LINE__,argv[argc-1]);
fprintf(stderr,"\033[0m\n\0");
return 1;
}
if ( fclose(out) == EOF )
{
fprintf(stderr,"\033[1;31m\n\0");
fprintf(stderr,"%llu: Error! Failed to close %s\n",__LINE__,argv[argc-1]);
fprintf(stderr,"\033[0m\n\0");
return 1;
}
return 0;
}
</code></pre>
<p>SHA256SUM:
592e94e830a99919e89f76e313513e5d87aee948c8bc7a324ef834c51e634e60 *tscd6.c</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T00:16:08.757",
"Id": "423444",
"Score": "3",
"body": "This code would be way more readable without most of the blank lines."
}
] | [
{
"body": "<p>Don't write prose in <code>#if 0</code> sections. The following won't work:</p>\n\n<pre><code>#if 0\ndon't do this\n#endif\n</code></pre>\n\n<p>The C preprocessor still has to parse the lines, and unbalanced single and double quotes will lead to syntax errors or at least warnings. No one else does this, and for good reason.</p>\n\n<hr>\n\n<p>Regarding the license statement: forget it. Any code that is posted on this site is <a href=\"https://stackoverflow.com/help/licensing\">covered by a Creative Commons license</a>, no matter what you write inside your code.</p>\n\n<p>You probably made up the license terms in your code, since I never saw this wording anywhere else. If you want your software to be reused, stick to the standard license terms. Otherwise people will not use your code because they are afraid of not knowing what exactly you mean by your terms.</p>\n\n<hr>\n\n<p>Do not mess around with any identifiers starting with <code>__</code>. For <code>rsize_t</code> and <code>uint8_t</code>, just assume they are defined. It's pretty easy to pass a <code>-Drsize_t=size_t</code> command line option for the very few systems that don't support these types.</p>\n\n<hr>\n\n<p>All global variables that are only used in your translation unit should be declared <code>static</code>. So instead of:</p>\n\n<pre><code>rsize_t NUM_HEX_ROWS = 16;\n</code></pre>\n\n<p>better write:</p>\n\n<pre><code>static rsize_t NUM_HEX_ROWS = 16;\n</code></pre>\n\n<p>This will make this variable invisible for code outside of this translation unit, which is good. If any other file in the whole project also defines its <code>NUM_HEX_ROWS</code> variable, your code should not be influenced by that.</p>\n\n<p>The same goes for functions such as <code>colorchar</code>. These should also be declared <code>static</code>.</p>\n\n<hr>\n\n<p>Instead of using <code>_Bool</code>, you should rather <code>#include <stdbool.h></code> and use <code>bool</code>. This header is available since C99, which is 20 years old by now. You can just assume it exists. Everyone who is using older compilers will already know how to make your code work with their compiler.</p>\n\n<hr>\n\n<p>In <code>colorchar</code>, using the <code>\\e</code> escape sequence is not portable. Better use <code>\\x1B</code> instead. You could also define a function to print a colored character:</p>\n\n<pre><code>static void putchar_colored(uint8_t ch, int color)\n{\n printf(\"\\x1B[38;5;%dm%c\\x1B[0m\", color, ch);\n}\n\n...\nputchar_colored('x', 244);\n</code></pre>\n\n<hr>\n\n<p>The function <code>isutf8cntrl</code> never returns a value. That's undefined behavior. Remove that function, or fix it.</p>\n\n<p>All function names starting with <code>is</code> followed by a lowercase letter are reserved by the C standard for future extensions. You should name your function <code>is_utf8_control</code> instead.</p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<pre><code>void colorutf8(uint8_t * s)\n</code></pre>\n\n<p>the parameter <code>s</code> should point to constant memory, since this function never modifies it:</p>\n\n<pre><code>void colorutf8(const uint8_t * s)\n</code></pre>\n\n<p>I have no idea what the purpose of that function is. Converting a string to a number has nothing to do with UTF-8. Furthermore the function is unused. Remove it.</p>\n\n<hr>\n\n<p>Next time, before posting any code here, let your IDE or your editor format the code properly. This means:</p>\n\n<ul>\n<li>an empty line between functions</li>\n<li>no excessive empty lines between your lines of code, especially in <code>print_bintable2</code>. There's no point in inserting an empty line after <em>every</em> line of code. Empty lines have a meaning, it's like a paragraph in written prose.</li>\n</ul>\n\n<p>I don't understand this code:</p>\n\n<pre><code> while (\n\n u < NUM_BIN_ROWS\n\n\n )\n</code></pre>\n\n<p>That's a mess. There is no point of having this much whitespace in your code. Rewrite it as:</p>\n\n<pre><code> while (u < NUM_BIN_ROWS)\n</code></pre>\n\n<hr>\n\n<pre><code>if (i % 1 != 0) {\n</code></pre>\n\n<p>This condition always evaluates to true.</p>\n\n<pre><code>if (index % 2 == 0) {\n fprintf(out, \"%c%c%c\", 0x20, 0x20, 0x20);\n} else {\n fprintf(out, \"%c%c%c\", 0x20, 0x20, 0x20);\n}\n</code></pre>\n\n<p>There's no point in having an <code>if</code> statement in which the <code>then</code> and the <code>else</code> branch have identical code.</p>\n\n<hr>\n\n<p>The code in <code>print_dectable</code> looks structurally similar to the code in <code>print_bintable2</code>. You should look for the common parts yourself and try to merge them into one function. It's probably a good idea to have functions called <code>dump_line_dec</code> and <code>dump_line_hex</code>, since the rest of the code is probably the same.</p>\n\n<p>As a guideline, none of your functions should ever be longer than 50 lines. If the whole text of a function doesn't fit on a single screen, it's too large and can probably be split into at least two separate functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T00:26:53.253",
"Id": "219221",
"ParentId": "219155",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T05:51:35.463",
"Id": "219155",
"Score": "2",
"Tags": [
"c",
"formatting",
"number-systems"
],
"Title": "256-bit ASCII Color Encoded Hex Dump in C"
} | 219155 |
<p>Similar questions have been asked here before and my solution is pretty much in line with some of the answers.
I wanted to work on this a bit. </p>
<blockquote>
<p>Scenario</p>
<p>Basic sales tax is applicable at a rate of 10% on all goods – except
books, food and medical products, which are exempt. Import duty is an
additional sales tax applicable on all imported goods at a rate of 5%,
with no exemptions. The tax rates or item categories may change in
future.</p>
<p>When I purchase items I receive a receipt which lists the name of all
the items and their price (including tax), finishing with the total
cost of the items, and the total amounts of sales taxes paid. The
rounding rules for sales tax are that for a tax rate of n%, a shelf
price of p contains (n*p/100 rounded up to the nearest 0.05) amount of
sales tax.</p>
</blockquote>
<p>I defined a interface <code>IProductTax</code> </p>
<pre><code>public interface IProductTax
{
bool IsApplicableTo(IProduct product);
decimal Compute(IProduct product);
}
</code></pre>
<p>which each tax class, <code>Sales</code>, <code>Import</code> must implement. <code>IsApplicableTo</code> checks if that tax is valid for the input <code>Product</code> and <code>Compute</code> computes the tax on this product. </p>
<p>The <code>TaxProcessor</code> class takes in a list of taxes during construction and for each product thereby passed it runs the entire tax rules and check if it is valid for the product and then applies it. </p>
<pre><code>public class TaxProcessor : ITaxProcessor
{
List<IProductTax> SalesTaxes;
public TaxProcessor()
{
SalesTaxes = new List<IProductTax>()
{
new SalesTax(),
new ImportDuty()
};
}
public decimal ComputeTotalTax(IProduct product)
{
decimal computedSalesTax = 0;
foreach (var tax in SalesTaxes)
{
computedSalesTax += tax.Compute(product);
}
return computedSalesTax;
}
}
</code></pre>
<p>One drawback of this approach is that the single product will pretty much run through the entire set of possible taxes to compute the taxes. I'm not sure how to overcome this in a OO way.</p>
<pre><code>public class SalesTax : IProductTax
{
public decimal Compute(IProduct product)
{
if (IsApplicableTo(product))
return product.Price * 0.1m;
return 0m;
}
public bool IsApplicableTo(IProduct product)
{
return !product.ItemType.HasFlag(ItemTypes.SalesTaxEmptedItemTypes);
}
}
public class ImportDuty : IProductTax
{
public decimal Compute(IProduct product)
{
if (IsApplicableTo(product))
return product.Price * 0.05m;
return 0m;
}
public bool IsApplicableTo(IProduct product)
{
return product.IsImport;
}
}
</code></pre>
<p>The <code>BillProcessor</code> class return a <code>Receipt</code> DTO after processing the shopping cart</p>
<pre><code>public class BillProcessor
{
public BillProcessor(ITaxProcessor salesTaxProcess)
{
SalesTaxProcessor = salesTaxProcess;
}
public Reciept ProcessCart(List<ShoppingItem> shoppingCart)
{
var billedShopppingItems = new List<BilledShopppingItem>();
decimal totalTaxForCart = 0;
decimal totalBilledAmount = 0;
foreach (var shoppingItem in shoppingCart)
{
decimal individualTax = SalesTaxProcessor.ComputeTotalTax(shoppingItem.Product);
decimal taxForAllProducts = individualTax * shoppingItem.Quantity;
decimal totalPrice = shoppingItem.Product.Price * shoppingItem.Quantity;
decimal totalPriceAfterTax = totalPrice + taxForAllProducts;
billedShopppingItems.Add(new BilledShopppingItem(shoppingItem, taxForAllProducts,
totalPriceAfterTax));
totalTaxForCart += taxForAllProducts;
totalBilledAmount += totalPriceAfterTax;
}
return new Reciept(billedShopppingItems, totalBilledAmount, totalTaxForCart);
}
public ITaxProcessor SalesTaxProcessor { get; }
}
</code></pre>
<p>And a few DTOs and enum</p>
<p><code>Shopping Item</code></p>
<pre><code>public class ShoppingItem
{
public ShoppingItem(IProduct product, int quantity)
{
Product = product;
Quantity = quantity;
}
public IProduct Product { get; }
public int Quantity { get; }
}
</code></pre>
<p><code>Product</code></p>
<pre><code>public class Product : IProduct
{
public Product(string name, decimal price, bool isImport, ItemTypes itemType)
{
Name = name;
Price = price;
IsImport = isImport;
ItemType = itemType;
}
public string Name { get; }
public decimal Price { get; }
public bool IsImport { get; }
public ItemTypes ItemType { get; }
}
</code></pre>
<p><code>BilledShoppingItem</code></p>
<pre><code>public class BilledShopppingItem
{
public BilledShopppingItem(ShoppingItem shoppingItem, decimal tax, decimal totalPrice)
{
ShoppingItem = shoppingItem;
Tax = tax;
TotalPrice = totalPrice;
}
public ShoppingItem ShoppingItem { get; }
public decimal Tax { get; }
public decimal TotalPrice { get; }
}
</code></pre>
<p><code>Reciept</code></p>
<pre><code>public class Reciept
{
public Reciept(List<BilledShopppingItem> processedShoppingCart, decimal totalBillAmount, decimal totalSalesTax)
{
ProcessedShoppingCart = processedShoppingCart;
TotalBillAmount = totalBillAmount;
TotalSalesTax = totalSalesTax;
}
public void PrintBill()
{
foreach (var processedItem in ProcessedShoppingCart)
{
Console.WriteLine($"{processedItem.ShoppingItem.Product.Name} { processedItem.TotalPrice }");
}
Console.WriteLine($"Sales Taxes {TotalSalesTax}");
Console.WriteLine($"Total {TotalBillAmount}");
}
public List<BilledShopppingItem> ProcessedShoppingCart { get; }
public decimal TotalBillAmount { get; }
public decimal TotalSalesTax { get; }
}
</code></pre>
<p>Types of products</p>
<pre><code>[Flags]
public enum ItemTypes
{
None = 0,
Book = 1 << 0,
Food = 1 << 1,
Medical = 1 << 2,
Others = 1 << 3,
SalesTaxEmptedItemTypes = Book | Food | Medical
}
</code></pre>
<p>I know there access modifiers are pretty liberal and naming conventions isn't the best. </p>
<p>However, I'm looking if this type of solution is extendable especially when we have more products and more and more tax rules. </p>
<p>I'm not very keen on putting <code>isImport</code> inside of <code>Product</code> and that depends on the geography. </p>
<p>The code is also on github if thats easier to read though. <a href="https://github.com/benneyman/SalesTax/tree/1355bfe09d762e24a883cb98a378166bd6b0f698" rel="nofollow noreferrer">https://github.com/benneyman/SalesTax</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:52:57.170",
"Id": "423300",
"Score": "1",
"body": "Very clean. One thought, it looks like the `IsApplicableTo` makes sense only internally so it might be a better idea to make it a `protected abstract` method of an `abstract class ProductTax`. I don't think anyone else would need it but the derived types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:59:12.250",
"Id": "423301",
"Score": "0",
"body": "Can you clarify wether it is possible that multiple taxes are applicable for the same product?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:05:34.913",
"Id": "423302",
"Score": "0",
"body": "Yes, that's totally possible. The Tax processor takes in a list of applicable tax objects. Currently, sales and import duty are being applied for products which are imported."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:11:08.827",
"Id": "423304",
"Score": "1",
"body": "@t3chb0t That makes sense. However, I was thinking if we need to support operations like given a product find all the applicable taxes. It makes sense to have them as public."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:04:19.900",
"Id": "423317",
"Score": "1",
"body": "The problem statement says `ImportDuty` is a `SalesTax` - and I'm not sure if in future `ImportDuty` class could have more functionality than `SalesTax` class. So we can make `SalesTax` methods virtual while implementing the interface `IProductTax` and inherit `ImportDuty` from `SalesTax` by overriding parent class methods. Also we can make virtual properties for % values like `0.1m` and Tax classes can override them (this will be more OO way). This will also make calculation in `Compute` method more intuitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:17:48.317",
"Id": "423346",
"Score": "0",
"body": "I thought about that too. But if we have other `duty` in addition to `SalesTax` in future I do not think we will be able to handle such change."
}
] | [
{
"body": "<p>Personally I tend to avoid creating classes, which do not implement any logic. Sometimes it makes sense or is even necessary, but always when I see such a class, I try to find out what operations are performed on its data and if they shouldn't be implemented as methods of that class.</p>\n\n<p>What I don't like about your code is the <code>ProcessCart</code> method, which pretty much contains all the logic and as such needs to be modified virtually every time when any requirement changes. The <code>BilledShopppingItem</code> class could at least calculate the tax itself, getting the tax rate as a constructor parameter, but I would probably go further and pass it the whole <code>ITaxProcessor</code>. Ideally, the only responsibility of the <code>BillProcessor</code> class should to iterate through all the elements and perform only operations requiring knowledge of the whole shopping cart (e.g. the cheapest article is for free, 10% discount if total bill amount > $100 etc.).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-15T14:54:48.053",
"Id": "224220",
"ParentId": "219156",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T06:39:13.063",
"Id": "219156",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"programming-challenge",
"calculator"
],
"Title": "Straightforward tax calculator OO design"
} | 219156 |
<p>Given input array of <code>UINT8</code> (<code>unsigned char</code>) with <code>numElements</code> how could one efficiently convert it into array of <code>Float32</code> (<code>float</code>)?</p>
<p>For instance, here is a vanilla code for it (Pay attention there is a scaling operation):</p>
<pre><code>void ConvertFromUint8(float* mO, unsigned char* mI, int numElements, float scalingFctr)
{
int ii;
for (ii = 0; ii < numElements; ii++) {
mO[ii] = (float)(mI[ii]) * scalingFctr;
}
}
</code></pre>
<p>Where <code>mO</code> is the output array.</p>
<p>I need a code which utilizes up to <code>AVX2</code> intrinsics.<br>
The objective is to yield faster code than the vanilla example as in <a href="https://godbolt.org/z/7k95yL" rel="nofollow noreferrer">Compiler Explorer - <code>ConvertFromUint8</code></a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:18:49.780",
"Id": "423327",
"Score": "0",
"body": "Doing the other way around - https://codereview.stackexchange.com/questions/219175."
}
] | [
{
"body": "<p>A straightforward transliterating to AVX2 intrinsics works, but I didn't like what the compilers made of it.</p>\n\n<p>For example, an obvious approach is to load 8 bytes, widen them to 8 ints, etc. And that obvious way to do that, I think, is with <code>_mm_loadl_epi64</code> to do the loading. Unfortunately, MSVC and even GCC refuse to merge a <code>_mm_loadl_epi64</code> into the memory operand of <code>_mm256_cvtepu8_epi32</code>, and there is no overload of <code>_mm256_cvtepu8_epi32</code> with an explicit memory operand.. Using <code>_mm_loadu_si128</code> to do the loading is fine and does merge, but that merger means that the 16-byte loading intrinsic is used but only 8 bytes of memory are actually loaded. It's strange, but it works, though it may make some people nervous to use this near the end of the data as it <em>looks</em> like it would read past the end.</p>\n\n<p>Anyway, my first concern was the stores. The GCC auto-vectorized version split the 256bit store into two 128bit stores, perhaps to avoid unaligned 256bit stores. But it's not so hard to align the destination, assuming <code>mO</code> is at least 8-aligned, so I'd say that's a better approach. The ICC auto-vectorized version doesn't try to avoid the big potentially-unaligned stores, perhaps it hopes for the best or thinks it shouldn't matter much. It is my understanding though that we should avoid wide unaligned stores (in the sense of the address actually being unaligned) as long as the cost for doing so is reasonable. The ICC versions also avoids small loads, preferring this construct:</p>\n\n<pre><code>vmovdqu ymm3, YMMWORD PTR [r9+rsi] #15.26\nvextracti128 xmm7, ymm3, 1 #15.26\nvpsrldq xmm4, xmm3, 8 #15.26\nvpsrldq xmm8, xmm7, 8 #15.26\n</code></pre>\n\n<p>I don't like it, this trades 4 loads (in the form of memory operands of <code>vpmovzxbd</code>) for a large load and some shuffle-type operations. That raises the total to 7 shuffle-type operations per iteration, they all need to go to p5 on current Intel µarchs, so that's a likely bottleneck. LLVM-MCA agrees with that and calculates that the loop takes just over 7 cycles per iteration on average, due to p5 contention. Plus, such a larger load increases to ratio of \"slow loads\" (eg 4K crossings and cache misses) to \"fast loads\", and makes more work dependent on that slow load, making it less likely that OoOE can hide the slowness.</p>\n\n<p>On the other hand with 4 separate loads, the loop is like this (code below, compiled with ICC):</p>\n\n<pre><code>..B2.8: # Preds ..B2.47 ..B2.6 ..B2.8\n vpmovzxbd ymm2, QWORD PTR [rax+rsi] #34.42\n vpmovzxbd ymm5, QWORD PTR [8+rax+rsi] #36.42\n vpmovzxbd ymm8, QWORD PTR [16+rax+rsi] #38.42\n vpmovzxbd ymm11, QWORD PTR [24+rax+rsi] #40.42\n vcvtdq2ps ymm3, ymm2 #34.23\n vcvtdq2ps ymm6, ymm5 #36.23\n vcvtdq2ps ymm9, ymm8 #38.23\n vcvtdq2ps ymm12, ymm11 #40.23\n vmulps ymm4, ymm0, ymm3 #35.42\n vmulps ymm7, ymm0, ymm6 #37.46\n vmulps ymm10, ymm0, ymm9 #39.47\n vmulps ymm13, ymm0, ymm12 #41.47\n vmovups YMMWORD PTR [rdi+rax*4], ymm4 #35.33\n vmovups YMMWORD PTR [32+rdi+rax*4], ymm7 #37.33\n vmovups YMMWORD PTR [64+rdi+rax*4], ymm10 #39.33\n vmovups YMMWORD PTR [96+rdi+rax*4], ymm13 #41.33\n add rax, 32 #33.43\n cmp rax, rcx #33.39\n jb ..B2.8 # Prob 82% #33.39\n</code></pre>\n\n<p>Which LLVM-MCA thinks is just under 5 cycles per iteration, which seems good to me. This could be improved slightly by unrolling even more, because the scalar arithmetic does \"get in the way\" a bit.</p>\n\n<p>By the way I changed some <code>int</code> to <code>size_t</code> to avoid some sign-extension, it wasn't really a big deal though.</p>\n\n<pre><code>void ConvertFromUint8_AVX2(float* mO, unsigned char* mI, size_t numElements, float scalingFctr)\n{\n size_t ii;\n __m256 vscalingFctr, tmp;\n\n vscalingFctr = _mm256_set1_ps(scalingFctr);\n\n // prologue, do scalar iterations until the output address is 32-aligned\n for (ii = 0; ii < numElements && ((uintptr_t)(mO + ii) & 31); ii++) {\n mO[ii] = (float)(mI[ii]) * scalingFctr;\n }\n // main loop\n if (numElements >= 32) {\n for (; ii < numElements - 31; ii += 32) {\n tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii))));\n _mm256_store_ps(mO + ii, _mm256_mul_ps(tmp, vscalingFctr));\n tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 8))));\n _mm256_store_ps(mO + ii + 8, _mm256_mul_ps(tmp, vscalingFctr));\n tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 16))));\n _mm256_store_ps(mO + ii + 16, _mm256_mul_ps(tmp, vscalingFctr));\n tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 24))));\n _mm256_store_ps(mO + ii + 24, _mm256_mul_ps(tmp, vscalingFctr));\n }\n }\n // epilogue\n for (; ii < numElements; ii++) {\n mO[ii] = (float)(mI[ii]) * scalingFctr;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:56:03.953",
"Id": "423321",
"Score": "0",
"body": "Harold, If I understand it correctly, the loop above is unrolled by a factor of 4. The line `tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii))));` loads 8 elemens of `UINT8` into `tmp` and then you store them. Am I correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:03:21.827",
"Id": "423322",
"Score": "0",
"body": "@Royi yes that loads 8 bytes and widens to 8 ints (`vpmovzxbd ymm2, QWORD PTR [rax+rsi]`), then converts to floats. The next line scales and stores."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:27:43.807",
"Id": "219164",
"ParentId": "219158",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219164",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T07:09:30.853",
"Id": "219158",
"Score": "0",
"Tags": [
"c",
"floating-point",
"vectorization",
"x86",
"simd"
],
"Title": "Converting Array of `UINT8` (`unsigned char`) to Array of `Float32` (`float`) Using AVX2"
} | 219158 |
<p>I'm developing an internal API using Flask, although due to limitations with our platform the endpoints will be accessible over the public internet. It will only have a very small number of users and it's not likely that this will increase much in the future. They will query the service programatically from a backend.</p>
<p>As only a small number of users will be consuming the API I think it makes sense to have a single key that can be used to access it. This will keep the authentication process simple and as the API doesn't provide access to anything really sensitive I don't believe we need to go too extreme on security. I've written the following:</p>
<p><code>app_config.py</code></p>
<pre><code>import yaml
config = yaml.safe_load(open('config.yml'))
</code></pre>
<p><code>auth.py</code></p>
<pre><code>from functools import wraps
from flask import request
from app_config import config
def valid_auth(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
if 'x-api-key' not in request.headers:
return("Credentials not present in request", 401)
elif request.headers['x-api-key'] != config['api_key']:
return ("Credentials not valid", 401)
else:
return func(*args, **kwargs)
return func_wrapper
</code></pre>
<p><code>main.py</code></p>
<pre><code>import api_module as api
from flask import Flask, request
from auth import valid_auth
app = Flask(__name__)
@app.route('/route1')
@valid_auth
def api_function():
#do api stuff here
</code></pre>
<p>Essentially the process is:</p>
<ul>
<li>API key is stored in config.yml on API server</li>
<li>(SSL) Request from backend includes the key in a header called x-api-key</li>
<li>A wrapper function checks that the key sent in this header matches the key in the configuration before executing any API functions. If not, the user gets an error.</li>
</ul>
<p>Does this seem like a reasonable approach to authentication for an internal API that will be used by a small number of users and that doesn't provide access to any sensitive information? Any general suggestions for how this process might be improved?</p>
| [] | [
{
"body": "<p>Just because you don't have many people using this API now, this does not mean that this will always be the case.</p>\n\n<p>In addition, you might want to discriminate between the users of the API for various reasons:</p>\n\n<ul>\n<li>To know how many there actually are</li>\n<li>To know which user/application is generating all those requests suddenly</li>\n<li>To rate-throttle some of them if needed</li>\n<li>To disallow access for someone who abused the API or just left the company or an obsolete application</li>\n</ul>\n\n<p>I would at least set this up in a very barebone way to have different API keys. For now you can just hardcode them in a dictionary in the config file, but this allows you to easily extract them to a database at some future point (which may never come). You can manually add users when needed (if it is only a few), or write a page that adds a user (if the manual task becomes too much).</p>\n\n<p>In your config just have something like this:</p>\n\n<p><code>config.yml</code></p>\n\n<pre><code>api_keys:\n 08zEk8IC0le3I0kPwSF1g4XU9R5WgbpUq2vZkZ0pkQU: User 1\n ZtRE7FXwZdtCLMfFHWPTom7_d-4XFbXEkHR5bIdG2TM: User 2\n Wg1vaDs8uqFbYtNDsJ8H3gKjl_oI0T_O6Jg8qNLWJcU: App 1\n ...\n</code></pre>\n\n<p>Your code needs to be only minimally changed:</p>\n\n<p><code>auth.py</code></p>\n\n<pre><code>def valid_auth(func):\n @wraps(func)\n def func_wrapper(*args, **kwargs):\n if 'x-api-key' not in request.headers:\n return \"Credentials not present in request\", 401\n elif request.headers['x-api-key'] not in config['api_keys']:\n return \"Credentials not valid\", 401\n else:\n return func(*args, **kwargs)\n return func_wrapper\n</code></pre>\n\n<p>Note that <code>()</code> around tuples are not needed in <code>return</code> since it is an expression and not a function.</p>\n\n<hr>\n\n<p>Returning a tuple of message, status code to raise in one case and the result of the function in another case can also be a potential source of bugs. If the using code expects the return value to be a single value, checking for there being two and those two being a string and an int is not very fool-proof. Even worse if the function actually also returns a string and int tuple.</p>\n\n<p>Instead, raise exceptions, which you can then deal with in <code>api_function</code>. Use custom classes inheriting from <code>Exception</code>:</p>\n\n<pre><code>class NoCredentials(Exception):\n status_code = 401\n\nclass WrongCredentials(Exception):\n status_code = 401\n\n...\nif 'x-api-key' not in request.headers:\n raise NoCredentials(\"Credentials not present in request\")\n</code></pre>\n\n<p><a href=\"http://flask.pocoo.org/docs/1.0/patterns/apierrors/\" rel=\"nofollow noreferrer\">This page in the official documentation</a> explains in more detail how to use custom exceptions correctly in flask.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:24:37.937",
"Id": "423354",
"Score": "1",
"body": "Thanks a lot for the advice. The info about raising exceptions is particularly useful. I think I will implement separate keys too for the sake of following a good practice, although in this case I feel pretty safe saying that the number of users isn't going to grow significantly in the future (it will be in the single digits). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:44:19.477",
"Id": "219166",
"ParentId": "219163",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:07:31.547",
"Id": "219163",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"authentication",
"flask"
],
"Title": "Authenticating an internal API with Flask"
} | 219163 |
<p>I have this method, which first basically shows a Welcome screen to user only once per day. The code I have so far is this</p>
<pre><code>private func showGreetingScreen (tabbar: UITabBarController) {
let defaults = UserDefaults.standard
if defaults.object(forKey: "greetingDate") == nil {
defaults.set(Date(), forKey: "greetingDate")
presentWelcomeScreen(tabbar: tabbar)
} else {
if let greetingDate = defaults.object(forKey: "greetingDate") as? Date {
let order = Calendar.current.compare(Date(), to: greetingDate, toGranularity: .day)
if order == .orderedDescending {
defaults.set(Date(), forKey: "greetingDate")
presentWelcomeScreen(tabbar: tabbar)
}
}
}
}
</code></pre>
<p>Now as you can see first I am checking whether Welcome Screen was shown in past or not and then I am saving current date. Then next time app will load, it will compare current date and the date Welcome Screen was shown and based on that It will show Welcome screen to User.
I have feeling that this code can be refactored more.</p>
| [] | [
{
"body": "<ul>\n<li><p>You could rearrange the conditions this way :</p>\n\n<pre><code>if let greetingDate = defaults.object(forKey: \"greetingDate\") as? Date {\n let order = Calendar.current.compare(date, to: greetingDate, toGranularity: .day)\n if order == .orderedDescending {\n defaults.set(date, forKey: \"greetingDate\")\n presentWelcomeScreen(tabbar: tabbar)\n }\n} else {\n defaults.set(date, forKey: \"greetingDate\")\n presentWelcomeScreen(tabbar: tabbar)\n}\n</code></pre></li>\n<li><p>You could extract <code>Date()</code> as a local variable in this function just in case you are crossing midnight between checks.</p></li>\n<li><p>The parameter name <code>tabbar</code> in both <code>showGreetingScreen</code> and <code>presentWelcomeScreen</code> doesn't seem necessary, you could use a wild card external name <code>_</code> to avoid being too verbose:</p>\n\n<pre><code>private func showGreetingScreen (_ tabbar: UITabBarController) { \n ... \n presentWelcomeScreen(tabbar)\n}\n</code></pre></li>\n<li><p><code>tabbar</code> isn't used in this function. It is only passed to <code>presentWelcomeScreen</code>, and this calls for refactoring the messaging in your code.</p></li>\n<li><p>Instead of having string literals laying around inside your code, I would prefer to have a struct with all the keys to avoid possible errors:</p>\n\n<pre><code>struct UDKeys {\n static let greetingDateKey = \"greetingDate\"\n static let otherKey = \"anotherKey\"\n}\n</code></pre>\n\n<p>Or declare these keys in an extension of <code>UserDefaults</code> itself :</p>\n\n<pre><code>extension UserDefaults {\n static let greetingDateKey = \"greetingDate\"\n static let otherKey = \"anotherKey\"\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Finally, your code would look like this :</p>\n\n<pre><code>struct UDKeys {\n static let greetingDateKey = \"greetingDate\"\n static let otherKey = \"anotherKey\"\n}\n\nprivate func showGreetingScreen (_ tabbar: UITabBarController) {\n let defaults = UserDefaults.standard\n let date = Date()\n if let greetingDate = defaults.object(forKey: UDKeys.greetingDateKey) as? Date {\n let order = Calendar.current.compare(date, to: greetingDate, toGranularity: .day)\n if order == .orderedDescending {\n defaults.set(date, forKey: UDKeys.greetingDateKey)\n presentWelcomeScreen(tabbar)\n }\n } else {\n defaults.set(date, forKey: UDKeys.greetingDateKey)\n presentWelcomeScreen(tabbar)\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:28:37.093",
"Id": "219169",
"ParentId": "219165",
"Score": "4"
}
},
{
"body": "<p>There is some code duplication for the cases “greeting date has never been set” and “last greeting was yesterday or earlier.” This can be avoided if you use the nil-coalescing operator <code>??</code> to set the last greeting date to a default value in the past:</p>\n\n<pre><code>let defaults = UserDefaults.standard\nlet lastGreeting = defaults.object(forKey: \"greetingDate\") as? Date ?? .distantPast\nlet now = Date()\nif Calendar.current.compare(now, to: lastGreeting, toGranularity: .day) == .orderedDescending {\n defaults.set(now, forKey: \"greetingDate\")\n presentWelcomeScreen(tabbar: tabbar)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:29:27.467",
"Id": "219183",
"ParentId": "219165",
"Score": "8"
}
},
{
"body": "<p>just some other refactoring hints:</p>\n\n<ul>\n<li>encapsulate the check in a own <code>UserUsageController</code> class</li>\n<li>then you can test it better</li>\n<li>maybe the check for midnight is dependend on timezone?</li>\n</ul>\n\n<p>user returning over time zone:</p>\n\n<ul>\n<li>show the welcome screen also if the last visit longer then a 8 hours - maybe user comes there at 23:00 and again at 02:00 - then it also not make sense to show the welcome screen</li>\n</ul>\n\n<p>short time user:</p>\n\n<ul>\n<li>maybe only set the lastVisitDate if the user has used the app more then 2 minutes (for example if he enter the app because he accidently tap on a push notification)</li>\n<li>or set the last visit date only when the user exits the welcome screen</li>\n</ul>\n\n<p>sample implementation (thanks to @Martin-R for code deduplication):</p>\n\n<pre><code>import UIKit\n\nclass UserUsageController {\n\n static let greetingDateKey = \"greetingDate\"\n\n static func isReturning(now: Date = Date(), minHours: Int = 8) -> Bool {\n\n let lastGreeting = getLastVisit() ?? .distantPast\n\n let dayBefore = isDayBefore(now: now, last: lastGreeting)\n let leastTime = isLeastTime(now: now, last: lastGreeting, minHours: minHours)\n return dayBefore && leastTime\n }\n\n private static func isDayBefore(now: Date, last: Date) -> Bool {\n return Calendar.current.compare(now, to: last, toGranularity: .day) == .orderedDescending\n }\n\n private static func isLeastTime(now: Date, last: Date, minHours: Int) -> Bool {\n let hours = Calendar.current.dateComponents([.hour], from: last, to: now ).hour ?? 0\n return hours > minHours\n }\n\n static func setLastVisit(date: Date = Date()){\n UserDefaults.standard.set(date, forKey: greetingDateKey)\n }\n\n static func getLastVisit() -> Date? {\n return UserDefaults.standard.object(forKey: greetingDateKey) as? Date\n }\n}\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>let df = DateFormatter()\ndf.dateFormat = \"yyyy/MM/dd HH:mm\"\n\nUserUsageController.setLastVisit(date: df.date(from: \"2019/04/20 01:00\")! )\nassert(false == UserUsageController.isReturning(now: df.date(from: \"2019/04/20 09:00\")!))\nassert(false == UserUsageController.isReturning(now: df.date(from: \"2019/04/20 23:00\")!))\n\nUserUsageController.setLastVisit(date: df.date(from: \"2019/04/20 22:00\")! )\n\nassert(false == UserUsageController.isReturning(now: df.date(from: \"2019/04/21 01:00\")!))\nassert(true == UserUsageController.isReturning(now: df.date(from: \"2019/04/21 01:00\")!,\n minHours: 1))\nassert(false == UserUsageController.isReturning(now: df.date(from: \"2019/04/21 06:59\")!))\nassert(true == UserUsageController.isReturning(now: df.date(from: \"2019/04/21 07:00\")!))\nassert(true == UserUsageController.isReturning(now: df.date(from: \"2019/04/21 08:00\")!))\nassert(true == UserUsageController.isReturning(now: df.date(from: \"2019/04/22 08:00\")!))\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>\n// in calling class\n\nif UserUsageController.isReturning() {\n // OpenWelcomeScreen\n}\n\n\n// onClose at welcomeScreen\nUserUsageController.setLastVisit()\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T17:12:32.357",
"Id": "219196",
"ParentId": "219165",
"Score": "2"
}
},
{
"body": "<p>All of these answers are great for optimizing the code that is already written, but these are all details. Hide it all behind a protocol to prevent these details from cluttering your view controller.</p>\n\n<pre><code>protocol OnboardingRepo {\n func shouldShowWelcomeScreen(): Bool\n}\n\nlet onboardingRepo: OnboardingRepo = //some implementation that uses everything in the other answers\n\nprivate func showGreetingScreen (tabbar: UITabBarController) {\n if onboardingRepo.shouldShowWelomeScreen() {\n presentWelcomeScreen(tabbar: tabbar)\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T18:10:19.377",
"Id": "221551",
"ParentId": "219165",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219183",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:36:54.003",
"Id": "219165",
"Score": "2",
"Tags": [
"swift",
"ios"
],
"Title": "Showing a welcome screen once per day"
} | 219165 |
<p>I have a function that checks user level and limits the data before saving it to mongoDB database (pre 'save' middleware for mongoose).
It have been getting complexity warnings and tried to rewrite it, and came up with the second version. I think now it's really not human readable! Anyone has any suggestions?</p>
<p><strong>Before:</strong></p>
<pre><code>providerSchema.pre('save', function(next) {
if(this.level === 4){
if(this.description.length >= 80 || this.certifications.length > 5){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
} else if(this.level === 3){
if(this.description.length >= 50 || this.certifications.length > 3){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
} else if(this.level === 2){
if(this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
} else if(this.level === 1){
if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
} else {
if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
});
</code></pre>
<p><strong>After:</strong></p>
<pre><code>providerSchema.pre('save', function(next) {
if(((this.level === 4) && (this.description.length >= 80 || this.certifications.length > 5)) ||
((this.level === 3) && (this.description.length >= 50 || this.certifications.length > 3)) ||
((this.level === 2) && (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0)) ||
((this.level === 1 || this.level === 0) && (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart))){
next(new Error('your current plan does not have this feature'));
} else {
next()
}
});
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:21:33.333",
"Id": "423417",
"Score": "1",
"body": "Welcome to Code Review! The standard for this site is for titles to state the task accomplished by the code; otherwise, too many questions would have the same title. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T20:08:20.063",
"Id": "423427",
"Score": "0",
"body": "@200_success oh alright :) thanks for the correction."
}
] | [
{
"body": "<p>I would suggest to refactor the code to make it cleaner using a function that checks user level and limits</p>\n\n<pre><code>function validateData(data) {\n\n switch(data.level) {\n case 0:\n case 1:\n return data.description || data.certifications.length > 0 || data.teaser || data.social.length > 0 || data.locationLat || data.locationLong || data.workingHourEnd || data.workingHourStart\n case 2: \n return data.description.length >= 30 || data.certifications.length > 0 || data.teaser || data.social.length > 0);\n case 3: \n return (data.description.length >= 50 || data.certifications.length > 3));\n case 4: \n return (data.description.length >= 80 || data.certifications.length > 5);\n }\n}\n\nproviderSchema.pre('save', function(next) {\n\n if(validateData(this)){\n next(new Error('your current plan does not have this feature'));\n } else {\n next()\n }\n});\n</code></pre>\n\n<p>I think this could be improved again, but that's a starting point</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:36:39.757",
"Id": "219170",
"ParentId": "219167",
"Score": "5"
}
},
{
"body": "<p>According to <a href=\"http://www.lizard.ws/\" rel=\"nofollow noreferrer\">www.lizard.ws</a> the original's function cyclomatic complexity is 29 and for the second version is 22. Both numbers are usually considered high, and teams aim for much lower values (<a href=\"https://softwareengineering.stackexchange.com/questions/194061/cyclomatic-complexity-ranges\">debatable</a> what the good range is though and will see within this answer why).</p>\n\n<p>In order to reduce it, one way is to encapsulate the <code>if</code> statements, among with removing the code duplication and separate the responsibilities. </p>\n\n<p>The <code>next</code> calls seem duplicate, so let's reduce them first.</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n\n var valid = true;\n if (this.level === 4) {\n if (this.description.length >= 80 || this.certifications.length > 5) {\n valid = false;\n }\n } else if (this.level === 3) {\n if (this.description.length >= 50 || this.certifications.length > 3) {\n valid = false;\n }\n } else if (this.level === 2) {\n if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {\n valid = false;\n }\n } else if (this.level === 1) {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n valid = false;\n }\n } else {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n valid = false;\n }\n }\n\n if (valid) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n});\n</code></pre>\n\n<p>With this first refactoring we didn't gain much in terms of lowering CC, in fact it increased to 30, because of the added <code>if</code> statement. However this can let us to split the validation responsibility from enabling the actual feature (as @Margon mentioned).</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (this.level === 4) {\n if (this.description.length >= 80 || this.certifications.length > 5) {\n return false;\n }\n } else if (this.level === 3) {\n if (this.description.length >= 50 || this.certifications.length > 3) {\n return false;\n }\n } else if (this.level === 2) {\n if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {\n return false;\n }\n } else if (this.level === 1) {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n return false;\n }\n } else {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n return false;\n }\n }\n return true;\n }\n});\n</code></pre>\n\n<p>The <code>isValidFeatureRequest</code> function is at 29 and <code>providerSchema</code> is at 2. We still need to work on.</p>\n\n<p>Checking again the code duplication, I noticed the last two blocks have the the same checks for other levels than 2, 3 or 4, so let's merge them.</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (this.level === 4) {\n if (this.description.length >= 80 || this.certifications.length > 5) {\n return false;\n }\n } else if (this.level === 3) {\n if (this.description.length >= 50 || this.certifications.length > 3) {\n return false;\n }\n } else if (this.level === 2) {\n if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {\n return false;\n }\n } else {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n return false;\n }\n }\n return true;\n }\n});\n</code></pre>\n\n<p>We gained the following figures</p>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 20\n</code></pre>\n\n<p>The CC for <code>isValidFeatureRequest</code> is now at 20, which is an improvement.\nThe check for <code>description</code> and <code>certifications</code> also seems to vary, so I can encapsulate it into a function.</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (this.level === 4) {\n if (descriptionOrCertificationsOffLimits(80, 5)) {\n return false;\n }\n } else if (this.level === 3) {\n if (descriptionOrCertificationsOffLimits(40, 3)) {\n return false;\n }\n } else if (this.level === 2) {\n if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {\n return false;\n }\n } else {\n if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {\n return false;\n }\n }\n return true;\n }\n\n function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {\n return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;\n }\n});\n</code></pre>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 17\ndescriptionOrCertificationsOffLimits | 2\n</code></pre>\n\n<p>CC is now at 17, slightly better.</p>\n\n<p>There is lot to check in the last branch, so let's extract it into his own function.</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (this.level === 4) {\n if (descriptionOrCertificationsOffLimits(80, 5)) {\n return false;\n }\n } else if (this.level === 3) {\n if (descriptionOrCertificationsOffLimits(40, 3)) {\n return false;\n }\n } else if (this.level === 2) {\n if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {\n return false;\n }\n } else if (hasAny()) {\n return false;\n }\n return true;\n }\n\n function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {\n return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;\n }\n\n function hasAny() {\n return this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart;\n }\n});\n</code></pre>\n\n<p>Which results into</p>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 10\ndescriptionOrCertificationsOffLimits | 2\nhasAny | 8\n</code></pre>\n\n<p>We have now 4 functions with manageable complexities.\nThe <code>hasAny</code> function seems to have a large CC, compared to what it does. What we can do here is to improve its readability, by displaying one condition per line. This is also the moment when I think we can't do anything about this function, and is the time not to look at an arbitrary CC limit in order to squize the code just to pass the analyzer.</p>\n\n<pre><code> function hasAny() {\n return this.description ||\n this.certifications.length > 0 ||\n this.teaser ||\n this.social.length > 0 ||\n this.locationLat ||\n this.locationLong ||\n this.workingHourEnd ||\n this.workingHourStart;\n }\n</code></pre>\n\n<p>Let's extract more, to check if it has a teaser or social data</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (this.level === 4) {\n if (descriptionOrCertificationsOffLimits(80, 5)) {\n return false;\n }\n } else if (this.level === 3) {\n if (descriptionOrCertificationsOffLimits(40, 3)) {\n return false;\n }\n } else if (this.level === 2) {\n if (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {\n return false;\n }\n } else if (hasAny()) {\n return false;\n }\n return true;\n }\n\n function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {\n return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;\n }\n\n function hasTeaserOrSocial() {\n return this.teaser || this.social.length > 0;\n }\n\n function hasAny() {\n return this.description ||\n this.certifications.length > 0 ||\n this.teaser ||\n this.social.length > 0 ||\n this.locationLat ||\n this.locationLong ||\n this.workingHourEnd ||\n this.workingHourStart;\n }\n});\n</code></pre>\n\n<p>Which results into</p>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 9\ndescriptionOrCertificationsOffLimits | 2\nhasTeaserOrSocial | 2\nhasAny | 8\n</code></pre>\n\n<p>The <code>if</code> followed by an inner <code>if</code> can be combined into and <code>and</code> operation so we can have this</p>\n\n<pre><code> function isValidFeatureRequest() {\n if (this.level === 4 && descriptionOrCertificationsOffLimits(80, 5)) {\n return false;\n } else if (this.level === 3 && descriptionOrCertificationsOffLimits(40, 3)) {\n return false;\n } else if (this.level === 2 && descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {\n return false;\n } else if ((this.level === 1 || this.level === 0) && hasAny()) {\n return false;\n }\n return true;\n }\n</code></pre>\n\n<p><del>The CC doesn't change, but</del> it enables me to extract validation for every level, so I gain smaller functions, with smaller complexity.\n<strong>Edit to fix a bug here</strong> - <em>This step introduced a bug, as @Roland Illig mentioned in the comments (the story of my life when I refactor even a simple <code>if</code>).\nAfter fixing it the CC actually increased with 2, to 11, as I introduced two new checks and I also had to add a new function.</em> <strong>end of edit</strong></p>\n\n<pre><code>function isValidFeatureRequest() {\n if (isLevel4AndNotValid()) {\n return false;\n } else if (isLevel3AndNotValid()) {\n return false;\n } else if (isLevel2AndNotValid()) {\n return false;\n } else if (isBellowLevel2AndNotValid()) {\n return false;\n }\n return true;\n}\n\nfunction isLevel4AndNotValid() {\n return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);\n}\n\nfunction isLevel3AndNotValid() {\n return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);\n}\n\nfunction isLevel2AndNotValid() {\n return this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());\n}\n\nfunction isBellowLevel2AndNotValid() {\n return (this.level === 1 || this.level === 0) && hasAny();\n}\n</code></pre>\n\n<p>Which are</p>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 5\nisLevel4AndNotValid | 2\nisLevel3AndNotValid | 2\nisLevel2AndNotValid | 3\nisBellowLevel2AndNotValid | 3\ndescriptionOrCertificationsOffLimits | 2\nhasTeaserOrSocial | 2\nhasAny | 8\n</code></pre>\n\n<p>The <code>isValidFeatureRequest</code> still looks odd, I can remove the else statements and I can convert the last call into a return statement, which decrease the complexity with one point.</p>\n\n<pre><code>function isValidFeatureRequest() {\n if (isLevel4AndNotValid()) {\n return false;\n }\n\n if (isLevel3AndNotValid()) {\n return false;\n }\n\n if (isLevel2AndNotValid()) {\n return false;\n }\n\n if (isBellowLevel2AndNotValid()) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>My final attempt is this:</p>\n\n<pre><code>providerSchema.pre('save', function (next) {\n if (isValidFeatureRequest()) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n\n function isValidFeatureRequest() {\n if (isLevel4AndNotValid()) {\n return false;\n }\n\n if (isLevel3AndNotValid()) {\n return false;\n }\n\n if (isLevel2AndNotValid()) {\n return false;\n }\n\n if (isBellowLevel2AndNotValid()) {\n return false;\n }\n\n return true;\n }\n\n function isLevel4AndNotValid() {\n return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);\n }\n\n function isLevel3AndNotValid() {\n return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);\n }\n\n function isLevel2AndNotValid() {\n this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());\n }\n\n function isBellowLevel2AndNotValid() {\n return (this.level === 1 || this.level === 0) && hasAny();\n }\n\n function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {\n return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;\n }\n\n function hasTeaserOrSocial() {\n return this.teaser || this.social.length > 0;\n }\n\n function hasAny() {\n return this.description ||\n this.certifications.length > 0 ||\n this.teaser ||\n this.social.length > 0 ||\n this.locationLat ||\n this.locationLong ||\n this.workingHourEnd ||\n this.workingHourStart;\n }\n});\n</code></pre>\n\n<p>With the following resuts:</p>\n\n<pre><code>function | CC\n-------------------------------------------\nproviderSchema | 2\nisValidFeatureRequest | 5\nisLevel4AndNotValid | 2\nisLevel3AndNotValid | 2\nisLevel2AndNotValid | 3\nisBellowLvel2AndNotValid | 3\ndescriptionOrCertificationsOffLimits | 2\nhasTeaserOrSocial | 2\nhasAny | 8\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T22:36:55.357",
"Id": "423443",
"Score": "1",
"body": "\"The if followed by an inner if can be combined into and and operation\" — this step changes the behavior since now `hasAny()` is called even when in level 4."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:11:50.750",
"Id": "219182",
"ParentId": "219167",
"Score": "10"
}
},
{
"body": "<p>I am not a mongoDB user but is there not some type of validation API, not sure if it can be used on schemes. If it can then maybe that is the better option for your code.</p>\n\n<p>The Question</p>\n\n<blockquote>\n <p>It have been getting complexity warnings and tried to rewrite it.</p>\n</blockquote>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"noreferrer\">Cyclomatic complexity</a> (CC) is a count of the paths through a section of code. Note some code linters use a different metric than described in this answer.</p>\n\n<h2>Calculating Cyclomatic Complexity.</h2>\n\n<p>To get an estimate of the CC you can count the paths in the section of code.</p>\n\n<p>For example the following functions have 2 paths and thus have a CC of 2</p>\n\n<pre><code>function bar(foo) {\n if (foo === 2) { foo = 3 } // path 1\n else { foo = 4 } // path 2\n return foo;\n}\n\n\nfunction bar(foo) {\n if (foo === 2) { foo = 3 } // path 1\n // hidden else path 2\n return foo;\n}\n</code></pre>\n\n<p>If we add another <code>if</code> statement we get another path. The next function has a CC of 3</p>\n\n<pre><code>function bar(foo) {\n if (foo === 2) { foo = 3 } // path 1\n else if (foo === 4) { foo = 5 } // path 2\n else { foo = 4 } // path 3\n return foo;\n}\n</code></pre>\n\n<p>It is not just the if statement that creates a path, each clause in a statement creates a path. Thus the following function also has a CC of 3</p>\n\n<pre><code>function bar(foo) {\n if (foo === 2 || foo === 4) { foo = 3 } // path 1 and 2\n else { foo = 4 } // path 3\n return foo;\n}\n</code></pre>\n\n<p>Things get a little involved when you are using functions. CC is calculated per function so the next example will have a median CC of 3 and a max CC of 3. The CC of <code>(bar + poo) / number of functions</code></p>\n\n<pre><code>function poo(foo) {\n if (foo === 2 || foo === 4) { foo = 3 }\n else { foo = 4 }\n return foo;\n}\nfunction bar(foo) {\n if (foo === 2 || foo === 4) { foo = 3 }\n else { foo = poo(foo) }\n return foo;\n}\n</code></pre>\n\n<h2>Your function</h2>\n\n<p>Counting the clauses in your function (below) I estimate the CC to be near 20, which is in the high range. Counting the first version in your question has a lot of nested branches so that may have a value near 30.</p>\n\n<pre><code>providerSchema.pre('save', function(next) {\n\n if(((this.level === 4) && (this.description.length >= 80 || this.certifications.length > 5)) || \n ((this.level === 3) && (this.description.length >= 50 || this.certifications.length > 3)) ||\n ((this.level === 2) && (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0)) || \n ((this.level === 1 || this.level === 0) && (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart))){\n next(new Error('your current plan does not have this feature'));\n } else {\n next()\n }\n});\n</code></pre>\n\n<p>The <a href=\"https://codereview.stackexchange.com/a/219170/120556\">answer</a> by Margon has separated the code into two functions. This will reduce the median CC. However it has failed to spread the complexity across the two functions, this will drive the max CC up. The first functions CC is 2 and <code>validateData</code> is about 17 giving a median CC of <code>(2 + 17) / 2 ~= 10</code> and a max CC of 17.</p>\n\n<h2>Reducing the CC</h2>\n\n<p>As you can see moving code into functions can go a long way to reduce the complexity.</p>\n\n<p>Another way is to remove branching paths altogether. Consider the following function</p>\n\n<pre><code>function foo(a) {\n if(a === 1) { a = 2 }\n else if (a === 2) { a = 3 }\n else if (a === 3) { a = 4 }\n else { a = undefined }\n return a;\n}\n</code></pre>\n\n<p>it has a CC of 4. Now we can do the same with only one path by using a lookup to take the place of the if statements.</p>\n\n<pre><code>function foo(a) {\n return ({\"1\": 2, \"2\": 3, \"3\": 4})[a];\n}\n</code></pre>\n\n<p>The function above has a CC of 1. There is one path yet 4 outcomes.</p>\n\n<h2>Applying to your code</h2>\n\n<p>Using a combination of functions and lookups we can reduce the CC of you code considerably. However I will point out that CC is but a metric and is only part of what makes good or bad code. Paying too much attention on the CC can be to the detriment of the source code quality. Good code is a balance of many metrics.</p>\n\n<p><strong>Example</strong></p>\n\n<p>There are 8 functions one lookup (object <code>levels</code>). The CC are about (in order top to bottom) 2 (outer function), 3, 4, 1, 1, 2, 2, and 5 so the median CC is <code>(2 + 3 + 4 + 1 + 1 + 2 + 2 + 5) / 8 = 20 / 8 ~= 2</code> and the max CC is 5.</p>\n\n<pre><code>providerSchema.pre('save', function(next) {\n const checkSocial = () => this.description || this.teaser || this.social.length > 0;\n const checkLocation = () => this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart;\n const fail = () => false;\n const levels = {\n \"4\": {desc: 80, cert: 6, fail},\n \"3\": {desc: 50, cert: 4, fail},\n \"2\": {desc: 30, cert: 1, fail() { return checkSocial() } },\n \"1\": {desc: -1, cert: 1, fail() { return checkSocial() || checkLocation() } },\n \"0\": {desc: -1, cert: 1, fail() { return checkSocial() || checkLocation() } },\n };\n\n const checkPass= ({level, description, certifications}) => {\n if(levels[level]) {\n const check = levels[level];\n if(check.fail() && check.desc < description.length && check.cert < certifications.length) {\n return false;\n }\n }\n return true;\n }\n checkPass(this) ? next() : next(new Error(\"Your current plan does not have this feature.\"));\n\n});\n</code></pre>\n\n<h2>Summing up.</h2>\n\n<p>From a high CC of around 20 down to 2. Now the questions that remain are.</p>\n\n<ul>\n<li>Is it more readable? That is debatable, it is hard for me to tell as I am good at reading my own style.</li>\n<li>Is it more manageable? Yes making changes or adding conditions is simpler as a lot of repeated clauses have been removed or grouped in functions.</li>\n<li>Is it worth the effort? That is up to the coder!</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T13:40:10.480",
"Id": "219184",
"ParentId": "219167",
"Score": "9"
}
},
{
"body": "<h1>Paradigm shift: <a href=\"https://stackoverflow.com/questions/105311/what-are-table-driven-methods\">Table-driven methods</a></h1>\n<p>Once logic becomes complex enough, you may find it easier to manage the rules from a data structure than from code. Here's how I picture that working for you here.</p>\n<p><em>Disclaimer: I made some assumptions about your business processes that may not be correct. Definitely review this code for correctness, and maybe rewrite it so that it makes more sense to <strong>you</strong>.</em></p>\n\n<pre><code>// For each data field we care about, at what level do various\n// conditions on that field become available?\nconst LEVEL_REQUIREMENTS = [\n ({description}) => {\n if (description.length >= 80) return 5; // or maybe Infinity?\n if (description.length >= 50) return 4;\n if (description.length >= 30) return 3;\n if (description) return 2;\n return 0;\n },\n ({certifications}) => {\n if (certifications.length > 5) return 5;\n if (certifications.length > 3) return 4;\n if (certifications.length > 0) return 3;\n return 0;\n },\n ({teaser}) => teaser ? 3 : 0,\n ({social}) => social.length > 0 ? 3 : 0,\n ({locationLat}) => locationLat ? 2 : 0,\n ({locationLong}) => locationLong ? 2 : 0,\n ({workingHourEnd}) => workingHourEnd ? 2 : 0,\n ({workingHourStart}) => workingHourStart ? 2 : 0,\n];\n\nfunction validate(data) {\n return LEVEL_REQUIREMENTS.every(levelRequirement => data.level >= levelRequirement(data));\n}\n\n...\n\nproviderSchema.pre('save', function(next) {\n if (validate(this)) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n});\n</code></pre>\n<p>Here, <code>LEVEL_REQUIREMENTS</code> is an array of functions (ES6 arrow functions with parameter destructuring, because I think they look nice - feel free to refactor if you disagree, or if you are restricted to ES5). All of the logic for whether a given data blob is allowed at a given plan level is contained within this array.</p>\n<p>That reduces the validation function to a simple "Is your level at or above the plan level required to use each feature?"</p>\n<p>You may wish to structure the data differently, to make it easier to tell <em>why</em> a given save request was rejected.</p>\n<p><em>Hopefully</em> this looks similar to how the rest of the business thinks about this feature; the more closely your code matches their conceptions, the easier it will be for them to communicate requirements to you, for you to respond to their requirements, for those requirements to change, and so on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:47:00.657",
"Id": "219215",
"ParentId": "219167",
"Score": "2"
}
},
{
"body": "<p>After looking at your code for a while, I think I understood your requirements. They can be summarized in this table:</p>\n\n<pre><code>Level Descrs Certs TSoc Other\n 1 0 0 no no\n 2 29 0 no yes\n 3 49 3 yes yes\n 4 79 5 yes yes\n</code></pre>\n\n<p>That's the essence of your feature matrix, and that's probably how it looks in the requirements document. The code should have this data in table form so that later requirements can be adjusted easily, without having to dive deep into the code.</p>\n\n<p>You should have a function that tests if such a plan is satisfied:</p>\n\n<pre><code>const plans = {\n 1: {maxDescriptions: 0, maxCertifications: 0, teaserAndSocial: false, other: false},\n 2: {maxDescriptions: 29, maxCertifications: 0, teaserAndSocial: false, other: true},\n 3: {maxDescriptions: 49, maxCertifications: 3, teaserAndSocial: true, other: true},\n 4: {maxDescriptions: 79, maxCertifications: 5, teaserAndSocial: true, other: true}\n};\n\nfunction planSatisfied(plan, obj) {\n if (obj.description.length > plan.maxDescriptions) {\n return false;\n }\n\n if (obj.certifications.length > plan.maxCertifications) {\n return false;\n }\n\n if (!plan.teaserAndSocial && (obj.teaser || obj.social.length > 0)) {\n return false;\n }\n\n if (!plan.other && (obj.locationLat || obj.locationLong || obj.workingHourEnd || obj.workingHourStart)) {\n return false;\n }\n\n return true;\n}\n\nproviderSchema.pre('save', function(next) {\n const plan = plans[this.level] || plans[1];\n if (planSatisfied(plan, this)) {\n next();\n } else {\n next(new Error('your current plan does not have this feature'));\n }\n});\n</code></pre>\n\n<p>Using this code structure, it is easy to:</p>\n\n<ul>\n<li>see what the actual requirements for the plans are, by only looking at the \n<code>plans</code> table.</li>\n<li>change the features of a plan, you just have to edit the <code>plans</code> table.</li>\n<li>add a new feature to all plans, you just have to add it to the table and then once to the <code>planSatisfied</code> function.</li>\n<li>understand the structure of the code, since it still uses only functions, if clauses and comparisons.</li>\n</ul>\n\n<p>This should cover the typical changes that you will face. Anything else will need a code rewrite anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T23:04:40.797",
"Id": "219217",
"ParentId": "219167",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219184",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:53:13.660",
"Id": "219167",
"Score": "8",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"mongoose",
"cyclomatic-complexity"
],
"Title": "Checks user level and limit the data before saving it to mongoDB"
} | 219167 |
<p>I am writing a C# program wherein I need to populate an array based on a lookup table and set of string arrays with metadata. My lookup table looks like this (Table with key: transmitter, value: Array of receiver):</p>
<pre><code>{
LED1: ["px1","px2","px3"],
LED2: ["px4","px5","px6"]
}
</code></pre>
<p>and my meta arrays looks like this (it is dynamic (just an example) and comes as a response from a DB query):</p>
<pre><code>var transmitters = new string[] { "LED1", "LED2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
</code></pre>
<p>My requirement is:</p>
<ul>
<li>If the transmitter LED1 or LED2 (or any other transmitter) is present in the lookup table, the value of the transmitter (i.e. ["px1","px2","px3"]) has to be compared with the receiver which are present in the lookup and led has to be marked yellow.</li>
<li>Orphan transmitter or/ receiver has to be marked red.</li>
</ul>
<p><strong>Example</strong></p>
<p><strong>Lookup</strong></p>
<pre><code>{
LED1: ["px1", "px2", "px3"],
LED2: ["px5", "px8"]
}
</code></pre>
<p>Transmitters and receivers</p>
<pre><code>var transmitters = new string[] { "led1", "led2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
</code></pre>
<p>The result should be a list as:</p>
<pre><code>led1-yellow
px1-yellow
px2-yellow
px3-yellow
led2-yellow
px5-yellow
px4-red
px6-red.
</code></pre>
<p>I have written code that works:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var transmitters = new string[] { "led1", "led2", "led3" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
var lookup = new Dictionary<string, string[]>() {
{ "led1", new string[] { "px1", "px2", "px3" } },
{ "led2", new string[] { "px5", "px8"} }
};
var blocks = new List<Block>();
var blocksTracker = new List<string>();
foreach (var transmitter in transmitters)
{
if (lookup.ContainsKey(transmitter))
{
var receiverLookup = lookup[transmitter];
var intersection = receivers.Intersect(receiverLookup).ToArray();
if (intersection.Length > 0)
{
blocks.Add(new Block() { Id = transmitter, status = "yellow"});
blocksTracker.Add(transmitter);
foreach (var receiver in intersection)
{
blocks.Add(new Block(){Id = receiver, status = "yellow"});
blocksTracker.Add(receiver);
}
} else
{
blocks.Add(new Block(){Id = transmitter, status = "red"});
blocksTracker.Add(transmitter);
}
}
}
var ungrouped = receivers.Except(blocksTracker).ToArray();
foreach (var receiver in ungrouped)
{
blocks.Add(new Block(){Id = receiver, status = "red"});
blocksTracker.Add(receiver);
}
foreach (var i in blocks)
{
Console.WriteLine(i.Id + "-"+i.status);
}
}
public class Block
{
public string Id { get; set; }
public string status { get; set; }
}
}
</code></pre>
<p>I am new to C# and I wanted to know if there is a better way of doing this. You can see the working Fiddle <a href="https://dotnetfiddle.net/d3E7n0" rel="nofollow noreferrer">here</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:19:09.333",
"Id": "423328",
"Score": "0",
"body": "I have updated the question. Please have a look. Also you can see it working https://dotnetfiddle.net/d3E7n0"
}
] | [
{
"body": "<blockquote>\n<pre><code> if (lookup.ContainsKey(transmitter))\n {\n var receiverLookup = lookup[transmitter];\n</code></pre>\n</blockquote>\n\n<p>This searches for the <code>KeyValuePair</code> twice. There's a more efficient approach:</p>\n\n<pre><code> if (lookup.TryGetValue(transmitter, out var receiverLookup))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> var ungrouped = receivers.Except(blocksTracker).ToArray();\n\n foreach (var receiver in ungrouped)\n {\n blocks.Add(new Block(){Id = receiver, status = \"red\"});\n blocksTracker.Add(receiver);\n }\n</code></pre>\n</blockquote>\n\n<p>The <code>ToArray()</code> there is unnecessary: the enumerable can be left as a lazy enumerable because the only use is to iterate over it once.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var intersection = receivers.Intersect(receiverLookup).ToArray();\n if (intersection.Length > 0)\n {\n blocks.Add(new Block() { Id = transmitter, status = \"yellow\"});\n blocksTracker.Add(transmitter);\n foreach (var receiver in intersection)\n {\n blocks.Add(new Block(){Id = receiver, status = \"yellow\"});\n blocksTracker.Add(receiver);\n }\n } else \n {\n blocks.Add(new Block(){Id = transmitter, status = \"red\"});\n blocksTracker.Add(transmitter); \n }\n</code></pre>\n</blockquote>\n\n<p>This seems rather complicated. I think the whole thing could be simplified:</p>\n\n<pre><code>var transmittersPaired = new HashSet<string>();\nvar receiversPaired = new HashSet<string>();\n\nforeach (var transmitter in transmitters)\n{\n if (lookup.TryGetValue(transmitter, out var receiverLookup) && receiverLookup.Any())\n {\n transmittersPaired.Add(transmitter);\n foreach (var receiver in receiverLookup)\n {\n receiversSeen.Add(receiver);\n }\n }\n}\n\nvar blocks = new List<Block>();\nforeach (var transmitter in transmitters)\n{\n blocks.Add(new Block { Id = transmitter, status = transmittersPaired.Contains(transmitter) ? \"yellow\" : \"red\" });\n}\nforeach (var receiver in receivers)\n{\n blocks.Add(new Block { Id = receiver, status = receiversPaired.Contains(receiver) ? \"yellow\" : \"red\" });\n}\n</code></pre>\n\n<p>There's still some repeated code, which might be simplified in one of two ways. If there's a guarantee that the transmitters and receivers will never share IDs then <code>transmittersPaired</code> and <code>receiversPaired</code> could be merged into one set, and the <code>foreach</code> loops at the end could be merged into one loop over <code>transmitters.Concat(receivers)</code>. Alternatively, a method could be factored out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T04:33:07.740",
"Id": "423672",
"Score": "0",
"body": "Makes sense ...Thanks :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:52:51.340",
"Id": "219176",
"ParentId": "219172",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219176",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T10:52:53.720",
"Id": "219172",
"Score": "3",
"Tags": [
"c#",
".net"
],
"Title": "Assigning values to array elements based on a lookup table"
} | 219172 |
<p>Given input array of <code>Float32</code> (<code>float</code>) with <code>numElements</code> how could one efficiently convert it into array of <code>UINT8</code> (<code>unsigned char</code>)?<br>
The tricky part here is to apply <a href="https://stackoverflow.com/questions/12141075">Unsigned Saturation</a> in the conversion</p>
<p>For instance, here is a vanilla code for it (Pay attention there is a scaling operation):</p>
<pre><code>void ConvertToUint8(unsigned char* mO, float* mI, int numElements, float scalingFctr)
{
int ii;
for (ii = 0; ii < numElements; ii++) {
mO[ii] = (unsigned char)(fmin(fmax(mI[ii] * scalingFctr, 0.0), 255.0));
}
}
</code></pre>
<p>Where <code>mO</code> is the output array. </p>
<p>I'm looking for a way to optimize (Performance wise) this code on AVX2 enabled CPU's. Any idea, Intrinsics included, is welcome.</p>
<p><strong>Pay attention</strong> the above code apply unsigned saturation manually (Is there a function for unsigned saturation based casting in <code>C</code>?). I think in practice <code>SSE</code> and AVX have it built in (See <a href="https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_packus_epi16&expand=3819,4109" rel="nofollow noreferrer"><code>_mm_packus_epi16()</code></a> for <code>SSE</code>).</p>
<p>The objective is to yield faster code than the vanilla example as in <a href="https://godbolt.org/z/pCYd7V" rel="nofollow noreferrer">Compiler Explorer - ConvertToUint8</a>.</p>
<p>For simplicity one could assume the arrays are aligned.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:21:08.943",
"Id": "423329",
"Score": "1",
"body": "Can the scale factor put the resulting float outside of the range of an int as well? That would be more annoying"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:22:15.270",
"Id": "423330",
"Score": "0",
"body": "Yes. You should assume `mI[ii] * scalingFctr` can have any legit `Float32` value (But not `NAN` or `INF`). I think in `SSE` the intrinsic `_mm_packus_epi16` does the trick"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:29:00.890",
"Id": "423332",
"Score": "1",
"body": "I don't think it works out so nicely, `vcvttps2dq` produces `INT_MIN` for out of range floats (including large positive), and then a pack-with-unsigned-saturation still interprets that as `INT_MIN` so it would result in zero, but maybe we wanted 0xFF. So it gets trickier"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:34:51.413",
"Id": "423334",
"Score": "0",
"body": "Harold, I tried to define the code more accurately. I mean that values after scaling which are lower than 0 will be clipped into zero and values above 255 will be clipped into 255."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:31:22.427",
"Id": "423533",
"Score": "0",
"body": "C doesn't have a saturation cast operator built-in."
}
] | [
{
"body": "<p>This is a tryout I cam up with - <a href=\"https://godbolt.org/z/JaiSHr\" rel=\"nofollow noreferrer\"><code>ConvertToUint8()</code></a>:</p>\n\n<pre><code>#include <immintrin.h> // AVX & AVX2\n\n#define AVX_STRIDE 8\n#define AVX_STRIDE_DOUBLE 16\n#define AVX_STRIDE_TRIPLE 24\n#define AVX_STRIDE_QUAD 32\n\nvoid ConvertToUint8(unsigned char* mO, float* mI, int numElements, float scalingFctr)\n{\n int ii;\n float *ptrInputImage;\n int *ptrOutputImage;\n\n __m256 floatPx1, floatPx2, floatPx3, floatPx4;\n __m256 scalingFactor;\n __m256i int32Px1, int32Px2, int32Px3, int32Px4;\n __m256i uint8Px1, uint8Px2;\n __m256i *ptrOutputImageAvx;\n\n for (ii = 0; ii < numElements; ii += AVX_STRIDE_QUAD) {\n ptrInputImage = mI;\n ptrOutputImageAvx = (__m256i*)(mO);\n // AVX Pack is 8 Floats (8 * 32 Bit) -> 32 UINT8 (32 * 8 Bit)\n // Hence loading 4 * 8 Floats which will be converted into 32 UINT8\n\n floatPx1 = _mm256_loadu_ps(ptrInputImage);\n floatPx2 = _mm256_loadu_ps(ptrInputImage + AVX_STRIDE);\n floatPx3 = _mm256_loadu_ps(ptrInputImage + AVX_STRIDE_DOUBLE);\n floatPx4 = _mm256_loadu_ps(ptrInputImage + AVX_STRIDE_TRIPLE);\n\n ptrInputImage += AVX_STRIDE_QUAD;\n\n // See https://stackoverflow.com/questions/51778721\n int32Px1 = _mm256_cvtps_epi32(_mm256_mul_ps(floatPx1, scalingFactor)); // Converts the 8 SP FP values of a to 8 Signed Integers (32 Bit).\n int32Px2 = _mm256_cvtps_epi32(_mm256_mul_ps(floatPx2, scalingFactor));\n int32Px3 = _mm256_cvtps_epi32(_mm256_mul_ps(floatPx3, scalingFactor));\n int32Px4 = _mm256_cvtps_epi32(_mm256_mul_ps(floatPx4, scalingFactor));\n uint8Px1 = _mm256_packs_epi32(uint16Px1, uint16Px2); // Saturating and packing 2 of 8 Integers into 16 of INT16\n uint8Px2 = _mm256_packs_epi32(uint16Px3, uint16Px4); // Saturating and packing 2 of 8 Integers into 16 of INT16\n uint8Px1 = _mm256_packus_epi16(uint8Px1, uint8Px2); // Saturating and packing 2 of 16 INT16 into 32 of UINT8\n uint8Px1 = _mm256_permutevar8x32_epi32(uint8Px1, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); // Permitation for Linear Orderinmg\n _mm256_storeu_si256(ptrOutputImageAvx++, uint8Px1); // Storing 32 UINT8, Promoting the pointer\n\n }\n}\n</code></pre>\n\n<p>The code is based on <a href=\"https://stackoverflow.com/a/51779212/195787\">answer of Peter Cordes - How to Convert 32 [Bit] Float to 8 [Bit] Signed <code>char</code></a>?<br>\nI'd love to hear thoughts about it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:49:16.723",
"Id": "423502",
"Score": "0",
"body": "This looks like the code you actually want a review of. You should put this in your question. Your current codereview question is written like an SO question, asking for someone to vectorize it. It should be written to ask for a review of *your* vectorization of it, with the scalar version working as documentation of what the vectorized code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:29:22.680",
"Id": "423532",
"Score": "0",
"body": "I revised my question objective to match the site rules. So I'm not explicitly asks for intrinsics but open to any code that improve the performance of the vanilla code on AVX2 enabled CPU's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:33:09.937",
"Id": "423535",
"Score": "0",
"body": "You seem to be missing the point of code review, and still trying to use it like Stack Overflow without even posting your own attempt at an optimized implementation. There's very little to review in the code you posted as the question, as far as style or performance, because you're not even claiming it's an actual finished attempt at a good implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T22:31:13.630",
"Id": "423567",
"Score": "0",
"body": "@PeterCordes, Let's play a game. I'm a student on a university. You are my University [Research Software Engineer](http://www.walkingrandomly.com/?page_id=2). I tell you I have a code which runs not fast enough on my research computer which has `AVX2`. I show you the code above and ask you to review it. What would you suggest me doing? On top of that, if you show me where my question doesn't fulfill the community guidelines I will vote closing it as well. On top of that, I don't understand why people even bother with it. Someone asks for assistance, can you assist?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:29:26.417",
"Id": "423570",
"Score": "0",
"body": "It's not a codereview question because the answer you're really hoping/asking for is a complete rewrite using intrinsics. You *know* the implementation in the question isn't what you want or close to efficient on any compiler. Everything about how you present the problem is written as a StackOverflow question (which is a duplicate of [How to convert 32-bit float to 8-bit signed char?](//stackoverflow.com/q/51778721) because there isn't a faster way to multiply). Unless your inputs and scaling factor are both exact integers, in which case you could use 16-bit integer multiply."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:31:55.263",
"Id": "423571",
"Score": "0",
"body": "It might be interesting to ask on meta.codereview.SE whether this kind of question, asking for a major rewrite, is on-topic, to see how CR regulars explain it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T03:46:59.570",
"Id": "423576",
"Score": "0",
"body": "We had a talk about it on the Chat of CR."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:58:22.703",
"Id": "219207",
"ParentId": "219175",
"Score": "0"
}
},
{
"body": "<p>Harold's comment is correct.</p>\n\n<p>Consider what happens for float inputs like <code>5000000000 * 1.0</code>. Conversion to <code>int32_t</code> with <a href=\"https://www.felixcloutier.com/x86/cvtps2dq\" rel=\"nofollow noreferrer\"><code>cvtps2dq</code></a> will give you <code>-2147483648</code> from that out-of-range positive <code>float</code>. (2's complement integer bit-pattern <code>0x80000000</code> is the \"indefinite integer value\" described by Intel's documentation for this case.)</p>\n\n<p>In that case, your vectorized version that clamps via integer saturation will start with a negative (and ultimately do unsigned saturation to 0), not matching your <code>fmin</code> which clamps before even converting to integer, resulting in 255.</p>\n\n<p><strong>So you have to be able to rule out such inputs if you want to vectorize without clamping in the FP domain before conversion to integer.</strong></p>\n\n<p>Remember that IEEE754 binary32 <code>float</code> can represent values outside the range of <code>int32_t</code> or <code>int64_t</code>, and what x86 FP->int conversions do in that case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:27:47.400",
"Id": "423531",
"Score": "0",
"body": "I see. In my case you can assume the range of values is within the range of `INT32`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:59:52.520",
"Id": "219260",
"ParentId": "219175",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:16:20.470",
"Id": "219175",
"Score": "-3",
"Tags": [
"performance",
"c",
"vectorization",
"x86",
"simd"
],
"Title": "Converting Array of `Float32` (`float`) to Array of `UINT8` (`unsigned char`) Using AVX2"
} | 219175 |
<p>The actual data types here are probably not relevant to post an answer. I use <code>Qt</code> types here, but the question should apply for other structured types as well.</p>
<p>I receive a data frame via can bus using the <code>QtSerialBus</code> module in <code>Qt</code>. I want to look for each received frame, if it matches a <code>QCanBusDevice::Filter</code> that I maintain in a <code>QList<QCanBusDevice::Filter></code>.</p>
<p>To see if one filter matches for the currently received frame, I initially came up with those lines of code. Edits below show the code evolution, so that anyone can see the progress. </p>
<pre><code>bool MyCanClass::isFrameMatchedByFilter(const QCanBusFrame& frameToFilter)
{
if (mFilterList.isEmpty()) {
return true;
} else {
for (auto& filter : mFilterList) {
// Go down the chain as far as needed and proceed to the next list entry as soon as a mismatch comes up
// First ID/Mask filtering, format and type afterwards
if ((frameToFilter.frameId() & filter.frameId) != (filter.frameId & filter.frameIdMask)) {
continue;
}
// FrameFormat only matters if set either base or extended, not both
if (filter.format != QCanBusDevice::Filter::FormatFilter::MatchBaseAndExtendedFormat) {
if (!(frameToFilter.hasExtendedFrameFormat() == (filter.format == QCanBusDevice::Filter::FormatFilter::MatchExtendedFormat))) {
continue;
}
}
// Invalid frame is the default and matches every frame type
if (filter.type != QCanBusFrame::FrameType::InvalidFrame) {
if (filter.type != frameToFilter.frameType()) {
continue;
}
}
return true;
}
return false;
}
}
</code></pre>
<p>I personally find the level of nesting and the general approach not too unclean here, but probably it can get improved, so that it is easier to understand or even faster.</p>
<h3>Edit 1</h3>
<p>After a few steps of refactoring, based on answers I got, I refactored everything a bit, made it more modular and easier to understand.</p>
<p>I might sort the IDs in the filter list beforehand to gain speed via binary search, but I am not sure, whether it is worth it, so I'll stay with that for now:</p>
<pre><code>bool MyCanClass::isFrameOfInterest(const QCanBusFrame& frame)
{
if (mFilterList.isEmpty()) {
return true;
} else {
return isCanFrameMatchingFilterList(frame, mFilterList);
}
}
bool isCanFrameMatchingFilterList(const QCanBusFrame& frame, const QList<QCanBusDevice::Filter>& filterList)
{
for (auto& filter : filterList) {
// Go down the chain as far as needed and proceed to the next list entry as soon as a mismatch comes up
// First ID/Mask filtering, format and type afterwards
if (!isCanIdMatchedByFilter(frame, filter)) {
continue;
}
// FrameFormat only matters if set either base or extended, not both
if (!isFrameFormatMatchedByFilter(frame, filter)) {
continue;
}
// Invalid frame is the default and matches every frame type
if (!isFrameTypeMatchedByFilter(frame, filter)) {
continue;
}
return true;
}
return false;
}
bool isCanIdMatchedByFilter(const QCanBusFrame& frame, const QCanBusDevice::Filter& filter)
{
return (frame.frameId() & filter.frameId) == (filter.frameId & filter.frameIdMask);
}
bool isFrameFormatMatchedByFilter(const QCanBusFrame& frame, const QCanBusDevice::Filter& filter)
{
if (filter.format == QCanBusDevice::Filter::FormatFilter::MatchBaseAndExtendedFormat) {
return true;
}
bool extended = frame.hasExtendedFrameFormat();
if (filter.format == QCanBusDevice::Filter::FormatFilter::MatchBaseFormat) {
return (extended) ? false : true;
} else {
return (extended) ? true : false;
}
}
bool isFrameTypeMatchedByFilter(const QCanBusFrame& frame, const QCanBusDevice::Filter& filter)
{
// invalid frame matches all frame types
if (filter.type != QCanBusFrame::FrameType::InvalidFrame) {
if (filter.type != frame.frameType()) {
return false;
}
}
return true;
}
</code></pre>
<p>While the new <code>isFrameFormatMatchedByFilter()</code> is way easier to understand at the first view, I assume that there are at least two extra instructions involved to execute that code on the CPU, am I wrong?</p>
<p>It's always a bit hard to figure out which part of your own codes are considered to be "too clever" and which aren't :-)</p>
| [] | [
{
"body": "<p>Cleaner and clearer it can certainly be:</p>\n\n<ul>\n<li><p>your function is called <code>isFrameMatchedByFilter</code> but returns true if there is no filter in the filter list: does that mean the frame is matched by a void filter? It's rather unclear, you need to either find another name or change the behavior of the function.</p></li>\n<li><p>your argument is called <code>frameToFilter</code>, but it's a bad idea. First because there's only one frame in this function and <code>frame</code> is shorter than <code>frameToFilter</code>; second because <code>frameToFilter</code> can also be interpreted as a kind of transformation from a frame to a filter (like in <code>to_string</code> for instance). </p></li>\n<li><p>the whole loop could be subsumed in a named algorithm: either <code>std::any_of</code>, or, if you change the semantics a bit, <code>std::find_if</code>: it might be interesting to return the matching filter rather than a simple <code>bool</code>. You then only need to compare the return iterator to <code>filter_list.end()</code> to produce a <code>bool</code>.</p></li>\n<li><p>the mask system comes with a cognitive cost. What <code>(frameToFilter.frameId() & filter.frameId) != (filter.frameId & filter.frameIdMask)</code> could possibly mean, I've no substantial idea. A function, or even a simple lambda to enlighten the reader would be nice. It would also encapsulate this calculation, and you could change this to a more robust system (like an <code>enum</code> -but I don't know the context, so it might not be the right choice) afterwards.</p></li>\n<li><p>this kind of things: <code>!(frameToFilter.hasExtendedFrameFormat() == (filter.format == QCanBusDevice::Filter::FormatFilter::MatchExtendedFormat))</code> is too clever. Again, write a one-liner around it or at least write it a way a mere mortal can read (I mean, without a 50% chance not to understand it correctly).</p></li>\n</ul>\n\n<p>Can it be faster? It depends on several factors: you can rearrange the match conditions to have the fastest * most discriminating first if it isn't already done (but it looks like the right order); you can sort the filters by id and perform a binary search rather than a flat one; you can go parallel if there are a lot of them. But as always, only optimize if it's worth it -measure first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:06:18.427",
"Id": "423731",
"Score": "0",
"body": "Thanks a lot for your precise comments. I refactored a bit with them in mind and updated the question. Your third point seems reasonable, but due to the fact, that multiple filters in the list could match the criteria for the frame, it is not possible, to return \"the one filter found\". The mask comparison is well-defined and I am not concerned about possible misunderstandings. Your \"too clever\" comment was absolutely right. One always is proud of such constructs unless hinted ;-) The binary search approach might be worth thinking about. But, as you guessed, I don't think it's worth it for now"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:24:50.077",
"Id": "219179",
"ParentId": "219177",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "219179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T11:57:21.087",
"Id": "219177",
"Score": "4",
"Tags": [
"c++",
"search",
"qt"
],
"Title": "Filter for CANbus frames"
} | 219177 |
<p>i want to know can this be hacked/injected?</p>
<pre><code>$stmt = $mysqli->prepare("SELECT * FROM myTable WHERE name = ?");
$stmt->bind_param("s", $_POST['name']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
//do some stuff
}
var_export($ages);
$stmt->close();
</code></pre>
| [] | [
{
"body": "<p>Given an <a href=\"https://stackoverflow.com/a/60496/285587\">answer on Stack Overflow</a> suggests <strong>almost identical code for protection</strong>, let alone using exactly the same <strong>principle</strong> you can safely assume that your query is protected. </p>\n\n<p>If you want to know how it works, I also wrote an answer on Stack Overflow, <a href=\"https://stackoverflow.com/a/8265319/285587\">https://stackoverflow.com/a/8265319/285587</a> </p>\n\n<p>Nevertheless, as this site is for the code reviews offering some suggestions, I would suggest to use PDO for database interactions instead of mysqli. Simply because PDO API is much more versatile and easier to use. see your snippet rewritten in PDO: </p>\n\n<pre><code>$stmt = $mysqli->prepare(\"SELECT * FROM myTable WHERE name = ?\");\n$stmt->execute([$_POST['name']]);\nif($stmt->rowCount() === 0) exit('No rows');\nwhile($row = $stmt->fetch_assoc()) {\n //do some stuff\n}\n</code></pre>\n\n<p>as you can see some nagging operations are just gone. I wrote a <a href=\"https://phpdelusions.net/pdo\" rel=\"nofollow noreferrer\">tutorial on PDO</a>, which I would quite expectedly recommend. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:36:07.590",
"Id": "219180",
"ParentId": "219178",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T12:09:32.827",
"Id": "219178",
"Score": "1",
"Tags": [
"php",
"mysqli",
"sql-injection"
],
"Title": "PHP MySQLi Prepared Statements: Can this select query be hacked/injected?"
} | 219178 |
<p>I have some JSON where each key stores an array, and I need to combine all those arrays into a single array. My current solution doesn't seem the most friendly to review, but without <code>forEach</code> not able to return a value i'm struggling for a succinct solution.</p>
<pre><code>config = {"levels": {"first": ["a", "b", "c"], "second": ["d", "e", "f"]}};
let combine = [];
Object.keys(config["levels"]).forEach(key=>combine.push(config["levels"][key]));
let levels = [].concat.apply([], combine);
// levels == ["a", "b", "c", "d", "e", "f"]
</code></pre>
<p>I never know how children <code>config["levels"]</code> will have there will be so this needs to be dynamic.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:38:52.430",
"Id": "423415",
"Score": "0",
"body": "`const levels = [].concat.apply([], Object.values(config.levels));` will do it. BTW access object properties is much better using dot notation `config.levels.first` rather than bracket notation `config[\"levels\"][\"first\"]`"
}
] | [
{
"body": "<h2>First</h2>\n<blockquote>\n<p>but without forEach not able to return a value i'm struggling for a succinct solution.</p>\n</blockquote>\n<p>Addressing this in your post, in the future it may help to know you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">.map() function</a>, which <em>does</em> return values to an array, unlike <code>forEach()</code></p>\n<p>an example using .map() and what you have:\n<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 config = {\"levels\": {\"first\": [\"a\", \"b\", \"c\"], \"second\": [\"d\", \"e\", \"f\"]}};\nconst accessor = config.levels\n\nlet combine = Object.keys(accessor).map(key=>{return accessor[key]});\nlet levels = [].concat.apply([], combine);\n\nconsole.log(levels);\n// levels == [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>More Succinct Solution</h2>\n<p>That said, something like this may be what you're looking for:</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 config = {\"levels\": {\"first\": [\"a\", \"b\", \"c\"], \"second\": [\"d\", \"e\", \"f\"]}};\nconst accessor = config.levels\n\nconst combine = Array.prototype.concat(...Object.values(accessor));\nconsole.log(combine)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>NOTE 1: Accessor is pulled out in case it needs to change, but is not necessary</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:38:17.760",
"Id": "219202",
"ParentId": "219187",
"Score": "2"
}
},
{
"body": "<h2>Feedback</h2>\n\n<p>Is this code wrapped in a function? I ask because in the first line, i.e. </p>\n\n<blockquote>\n<pre><code>config = {\"levels\": {\"first\": [\"a\", \"b\", \"c\"], \"second\": [\"d\", \"e\", \"f\"]}};\n</code></pre>\n</blockquote>\n\n<p><code>config</code> is declared outside any brackets and without any keyword like <code>var</code>, <code>let</code> or <code>const</code>, which leads to it being declared globally. It is wise to avoid using global variables unless you are absolutely sure you have no other way to accomplish a task. This avoids scenarios like unintentional re-assignment and tight coupling.</p>\n\n<p>Also, unless a variable is re-assigned, it is wise to use <code>const</code> instead of <code>let</code>. This will prevent unintentional re-assignment. <code>combine</code> could be declared with <code>const</code> since it is never re-assigned. </p>\n\n<hr>\n\n<p>Whenever an array is declared and then added to via a loop (like <code>forEach</code>) you should consider using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\"><code>map</code></a> method instead. </p>\n\n<p>So the following lines </p>\n\n<blockquote>\n<pre><code>let combine = [];\n Object.keys(config[\"levels\"]).forEach(key=>combine.push(config[\"levels\"][key]));\n</code></pre>\n</blockquote>\n\n<p>Could be rewritten like this:</p>\n\n<pre><code>const combine = Object.keys(config[\"levels\"]).map(key=>combine.push(config[\"levels\"][key]));\n</code></pre>\n\n<p>Perhaps it would be helpful to go through <a href=\"http://reactivex.io/learnrx/\" rel=\"nofollow noreferrer\">these functional JS exercises</a>, where you practice implementing methods like <code>map</code>, <code>filter</code>, <code>reduce</code>. </p>\n\n<hr>\n\n<p>As was mentioned in a comment, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Dot_notation\" rel=\"nofollow noreferrer\">dot notation</a> can be used instead of bracket notation to accessing object properties. It is <a href=\"https://stackoverflow.com/a/4968448/1575353\">\"<em>faster to write and clearer to read</em>\"</a><sup><a href=\"https://stackoverflow.com/a/4968448/1575353\">1</a></sup></p>\n\n<h2>A Simpler Technique</h2>\n\n<p>One simplification would be to use <code>Object.values()</code> to get the nested arrays, and then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\"><code>Array.flat()</code></a> to join the arrays together.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const config = {\"levels\": {\"first\": [\"a\", \"b\", \"c\"], \"second\": [\"d\", \"e\", \"f\"]}};\nconst levels = Object.values(config.levels).flat();\nconsole.log(\"levels: \", levels);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup>1</sup><sub><a href=\"https://stackoverflow.com/a/4968448/1575353\">https://stackoverflow.com/a/4968448/1575353</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:33:22.030",
"Id": "219206",
"ParentId": "219187",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219202",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T14:34:45.693",
"Id": "219187",
"Score": "1",
"Tags": [
"javascript",
"array",
"ecmascript-6",
"iterator"
],
"Title": "Combining arbitrary number of lists inside json"
} | 219187 |
<p>Just a very simplified and stright-forward way of serialize/deserialize to/from JSON using standard .NET 4+ libs. I was trying to avoid "complexity", so get rid of 3rd part libs and <em>heavy-infrastructured</em> standard libs.</p>
<pre><code> #region JSON API
public static string ObjectToJson(object o, Type t, Type[] pTypes = null)
{
DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));
MemoryStream mStrm = new MemoryStream();
serializer.WriteObject(mStrm, o);
mStrm.Position = 0;
using (var sr = new StreamReader(mStrm, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
public static object JsonToObject(string json, Type t, Type[] pTypes = null)
{
DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return serializer.ReadObject(stream);
}
}
#endregion // JSON API
</code></pre>
<p>And an example of its usage:</p>
<pre><code> public bool ListOfGames(bool pMyGames, bool pGamesITookPartIn)
{
this.GamesListInfo = null;
this.LastErrorInfo = null;
try
{
string formValues =
"&playerId=" + this.LogonInfo.userId.ToString() +
"&createdBy=" + pMyGames.ToString() +
"&tookPartIn=" + pGamesITookPartIn.ToString() +
"";
WebRequest request = createRequest("myGamesList", formValues);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
if (responseText.Contains("\"errType\":"))
this.LastErrorInfo = (ErrorInfoContract)JsonToObject(responseText, typeof(ErrorInfoContract));
else
this.GamesListInfo = (GamesListContract)JsonToObject(responseText, typeof(GamesListContract), new Type[] { typeof(GameInfoContract) });
Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format("NewGame.ListOfGames: {0}{1}",
(this.LogonInfo != null ? this.LogonInfo.ToString() : ""), (this.LastErrorInfo != null ? this.LastErrorInfo.ToString() : "")) : "");
}
}
catch (Exception exc)
{
this.LastErrorInfo = new ErrorInfoContract()
{
errType = exc.GetType().ToString(),
message = exc.Message,
stackTrace = exc.StackTrace,
timestamp = StrUtils.NskTimestampOf(DateTime.Now)
};
}
return (this.LogonInfo != null && this.LogonInfo.userId > 0 && this.LogonInfo.authKey > 0);
}
private WebRequest createRequest(string pAction, string pFormValues)
{
WebRequest request = WebRequest.Create(this.ServerUrl + "?action=" + pAction);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = pFormValues.Length;
byte[] data = Encoding.UTF8.GetBytes(pFormValues);
using (Stream strm = request.GetRequestStream())
{
strm.Write(data, 0, data.Length);
}
return request;
}
</code></pre>
<p>Just searched where to publish a code and example (for some purposes).</p>
<p>I do not expect any inputs but if you would like to - welcome, would be appreciated. :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T17:16:36.123",
"Id": "423407",
"Score": "0",
"body": "This doesn't really look simpler. I'd be great if you could write more about what you are doing here and why. We also need more context like what is `DataContractJsonSerializer`? Complete classes were better than just some _random_ methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:01:17.073",
"Id": "423412",
"Score": "0",
"body": "Sorry. Full class name is System.Runtime.Serialization.Json.DataContractJsonSerializer it resides in System.Runtime.Serialization.dll, v4.0.0.0. It is part of .NET. I'm doing client-server communication for primitive online game. There is very simple web server with *.ashx which handle HTTP requests and returns JSON."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:58:49.310",
"Id": "423423",
"Score": "0",
"body": "Please upload the real code, as-written, not a simplified version of what you've made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T06:37:30.553",
"Id": "423459",
"Score": "0",
"body": "This is real piece of code which is currently working inside a solution. It is not \"simplified version\". By using word \"simplified\" in my post I mean - to keep solution simple and minimalistic, that was my goal when I was developing it."
}
] | [
{
"body": "\n\n<h3>Frame challenge</h3>\n\n<blockquote>\n <p>I was trying to avoid \"complexity\", so get rid of 3rd part libs</p>\n</blockquote>\n\n<p>Although it's not strictly code review, I would like to start by challenging this goal. There are many many official Microsoft libraries with dependencies on Newtonsoft.Json. (See <a href=\"https://softwareengineering.stackexchange.com/a/347972/13258\">this answer on our software engineering sister site</a>).</p>\n\n<hr>\n\n<h3>Core code</h3>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> public static string ObjectToJson(object o, Type t, Type[] pTypes = null)\n</code></pre>\n</blockquote>\n\n<p>This absolutely needs documentation comments explaining what <code>t</code> and <code>pTypes</code> are for. As a maintenance programmer this signature is unhelpful on two counts:</p>\n\n<ol>\n<li>I have no idea why I need to pass types at all. If <code>ObjectToJson</code> needs the type of the object for some reason it can call <code>o.GetType()</code>.</li>\n<li>The names are not helpful. I'm guessing that <code>t</code> is the type of <code>o</code>, but that's a pure guess. As for <code>pTypes</code>, is that Hungarian notation for \"<em>pointer to type</em>\"? That has no place in C# code unless you're using <code>unsafe</code> and actual pointers (and even there the name should tell you what the variable is for and not just what its type is).</li>\n</ol>\n\n<p>With respect to point 1, I would suggest that in addition to improving the names and adding documentation you consider two further refactorings: either making <code>t</code> an optional parameter with default <code>null</code> and calling <code>o.GetType()</code> if necessary; or changing the signature to <code>public static string ObjectToJson<T>(T obj, IEnumerable<Type> whateverPTypesShouldBeCalled)</code> so that the compiler can infer the type but the caller can impose a supertype if that's necessary for some bizarre reason. (In case you don't know: you can use <code>typeof(T)</code> with <code>T</code> a type variable to get a <code>Type</code> object).</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));\n</code></pre>\n</blockquote>\n\n<p>Might it make more sense to use <code>new DataContractJsonSerializer(t, pTypes ?? Enumerable.Empty<Type>())</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> MemoryStream mStrm = new MemoryStream();\n ...\n using (var sr = new StreamReader(mStrm, Encoding.UTF8))\n</code></pre>\n</blockquote>\n\n<p>This is inconsistent: . I would favour the approach of always using <code>using</code> with <code>IDisposable</code>, even when you know that it doesn't use any unmanaged resources.</p>\n\n<p>A comment explaining why <code>Encoding.UTF8</code> is correct would be an improvement.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> public static object JsonToObject(string json, Type t, Type[] pTypes = null)\n {\n DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));\n using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))\n {\n return serializer.ReadObject(stream);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>I think all of the comments on <code>ObjectToJson</code> apply equally to <code>JsonToObject</code> with one exception: this time the signature makes a much stronger argument for use of generics. As it stands you probably have to cast the return value almost every time you use this method.</p>\n\n<hr>\n\n<h3>Usage example</h3>\n\n<p>This is again marginally off-topic, so I won't do a detailed review of the example usage code, but I think it's important to address a couple of points.</p>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> private WebRequest createRequest(string pAction, string pFormValues)\n</code></pre>\n</blockquote>\n\n<p>Every caller of this method is expected to compose <code>pFormValues</code>. That's the antithesis of <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>. The method which factors out the commonalities of requests should be the one place which composes the query string, and unlike the example</p>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> string formValues =\n \"&playerId=\" + this.LogonInfo.userId.ToString() +\n \"&createdBy=\" + pMyGames.ToString() +\n \"&tookPartIn=\" + pGamesITookPartIn.ToString() +\n \"\";\n</code></pre>\n</blockquote>\n\n<p>it should take care to escape the values.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> WebRequest request = createRequest(\"myGamesList\", formValues);\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n using (StreamReader sr = new StreamReader(response.GetResponseStream()))\n {\n string responseText = sr.ReadToEnd();\n\n if (responseText.Contains(\"\\\"errType\\\":\"))\n</code></pre>\n</blockquote>\n\n<p>Again, I would hope that the web service on the other end is consistent enough that handling the response can be done in one place rather than being repeated for every single call. And I would hope that it uses HTTP well enough that you don't have to do heuristic guessing to figure out whether there was a problem. Instead of looking for <code>\"errType\":</code> it should switch on <code>response.StatusCode</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code> WebRequest request = WebRequest.Create(this.ServerUrl + \"?action=\" + pAction);\n\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n request.ContentLength = pFormValues.Length;\n</code></pre>\n</blockquote>\n\n<p>I find it bizarre that the form values are split between the URL and the request body.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:54:49.777",
"Id": "423895",
"Score": "0",
"body": "It looks like the built-in json-serializer uses the additional types for validating [msdn](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer.-ctor?view=netframework-4.8#System_Runtime_Serialization_Json_DataContractJsonSerializer__ctor_System_Type_System_Collections_Generic_IEnumerable_System_Type__) says: _, with a collection of known types that may be present in the object graph_"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:16:49.093",
"Id": "219409",
"ParentId": "219191",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:00:43.037",
"Id": "219191",
"Score": "1",
"Tags": [
"c#",
".net",
"json"
],
"Title": "Simplified light Serialize/Deserialize to/from JSON for .NET"
} | 219191 |
<p>I wrote a query that searches <code>people</code> based on search parameters from 3 other tables (<code>phones</code>, <code>emails</code>, <code>addresses</code>). I'm pretty sure this is not the most efficient way to do this, any performance tips are greatly appreciated :)</p>
<p>Note that the user may choose to search by less than all the possible criteria, for example search only by phone and email but not by address and name. In such cases a php code will dynamically generate a search query that excludes the unwanted parameters.</p>
<h1>SQL</h1>
<pre><code>SELECT
id,
name,
group_concat(
DISTINCT concat( number, ' (', phones.description, ')' )
ORDER BY phones.description
SEPARATOR '<br>'
) AS phones,
group_concat(
DISTINCT concat( email, ' (', emails.description, ')' )
ORDER BY emails.description
SEPARATOR '<br>'
) AS emails,
group_concat(
DISTINCT concat( address, ' (', addresses.description, ')' )
ORDER BY addresses.description
SEPARATOR '<br>'
) AS addresses
FROM people
LEFT OUTER JOIN phones
ON phones.person_id = id
LEFT OUTER JOIN emails
ON emails.person_id = id
LEFT OUTER JOIN addresses
ON addresses.person_id = id
WHERE id IN (
SELECT DISTINCT person_id
FROM phones
WHERE number LIKE ?
AND person_id IN (
SELECT DISTINCT person_id
FROM emails
WHERE email LIKE ?
AND person_id IN (
SELECT DISTINCT person_id
FROM addresses
WHERE address LIKE ?
)
)
)
AND name LIKE ?
GROUP BY id
ORDER BY id DESC;
</code></pre>
<h1>Sample database tables</h1>
<pre><code>people:
+----+----------------------+
| id | name |
+----+----------------------+
| 1 | Bob |
| 2 | Daniel |
| 3 | Joe |
| 4 | Some other name |
| 5 | Robby Williams |
+----+----------------------+
phones:
+-----------+------------+-------------+
| person_id | number | description |
+-----------+------------+-------------+
| 1 | 123456789 | home |
| 1 | 123412341 | office |
| 2 | 1234554321 | |
| 3 | 8525824725 | home |
| 3 | 5832593952 | office |
| 3 | 6035262953 | fax |
| 3 | 6832525753 | office 2 |
| 3 | 6735926752 | z |
| 3 | 6830589736 | zz |
| 3 | 2893475979 | zzz |
| 3 | 7823569459 | zzzz |
| 4 | 666 | secretary |
| 4 | 444422220 | office |
| 4 | 111111111 | home |
| 5 | 444422220 | office |
| 5 | 1111111111 | home |
+-----------+------------+-------------+
emails:
+-----------+------------------+-------------+
| person_id | email | description |
+-----------+------------------+-------------+
| 1 | bob@fakemail.com | |
| 2 | tbb@fakemail.com | fake email |
| 3 | joejoe@joe.joe | |
+-----------+------------------+-------------+
addresses:
+-----------+----------------------------------------------------+-------------+
| person_id | address | description |
+-----------+----------------------------------------------------+-------------+
| 1 | Anywhere | home |
| 1 | Nowhere, apt 2 | work |
| 2 | The Moon | home |
| 2 | Venus | office |
| 3 | 123 something something, apt -2.5 | basement |
| 4 | Hello, apt 26 | |
| 5 | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | office |
+-----------+----------------------------------------------------+-------------+
</code></pre>
<h1>Sample output</h1>
<p>For search parameters: <code>[ '%1%', '%fakemail%', '%moon%', '%d%' ]</code></p>
<pre><code>+----+--------+---------------+-------------------------------+-----------------------------------+
| id | name | phones | emails | addresses |
+----+--------+---------------+-------------------------------+-----------------------------------+
| 2 | Daniel | 1234554321 () | tbb@fakemail.com (fake email) | The Moon (home)<br>Venus (office) |
+----+--------+---------------+-------------------------------+-----------------------------------+
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:08:02.197",
"Id": "423483",
"Score": "0",
"body": "You've created a very weird query. Does it actually do what you want? Talking about that: What kind of search do you really want to perform? Do all three parameters have to exactly match? Could one match? Do you want partial matches of parameters? It would even be better if you gave a reason for this, some context to this query. I also wonder what is in the `description` columns? What _do_ your tables actually look like? The cherry on the pudding would be some example data..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:43:47.033",
"Id": "423501",
"Score": "0",
"body": "@KIKOSoftware added examples of database and sample output. The parameters need to be a partial match (hence the `LIKE` operator). The user may choose to search by less than all of these parameters, in which case a `php` code will dynamically create a query string that excludes the unwanted search parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:53:18.427",
"Id": "423503",
"Score": "0",
"body": "As a joke I added some weird stuff to this database, but the `description` columns are supposed to contain stuff like \"home\", \"office\", \"fax\", etc."
}
] | [
{
"body": "<p>Please note that on Code Review we actually <em>review all</em> of your code. So, even though you concentrated on one aspect; The most efficient query, I have to discuss more than that. I'll have to accept that you left out the PHP code, which seems to be an integral part of this query. I have work with what you have given.</p>\n\n<h1>The query</h1>\n\n<p>Let me first answer your question about the query. Yes, it can be more efficient if you loose the sub-queries. I will make this a two step process, which is easy when you're using PHP. In the first step you get the the id's of the persons that match the search: </p>\n\n<pre><code>SELECT\n id\nFROM people\nJOIN phones\n ON phones.person_id = id AND\n phones.number LIKE ? \nJOIN emails\n ON emails.person_id = id AND\n emails.email LIKE ?\nJOIN addresses\n ON addresses.person_id = id AND\n addresses.address LIKE ?\nWHERE name LIKE ?\nGROUP BY id\nORDER BY id DESC;\n</code></pre>\n\n<p>Then when you go through the results of this query you ask for the details of each person:</p>\n\n<pre><code>SELECT\n name,\n group_concat(\n DISTINCT concat(number, ' (', phones.description, ')')\n ORDER BY phones.description\n SEPARATOR '<br>'\n ) AS phones,\n group_concat(\n DISTINCT concat(email, ' (', emails.description, ')')\n ORDER BY emails.description\n SEPARATOR '<br>'\n ) AS emails,\n group_concat(\n DISTINCT concat(address, ' (', addresses.description, ')')\n ORDER BY addresses.description\n SEPARATOR '<br>'\n ) AS addresses\nFROM people\nJOIN phones ON phones.person_id = id \nJOIN emails ON emails.person_id = id \nJOIN addresses ON addresses.person_id = id \nWHERE id = ?;\n</code></pre>\n\n<p>Now you might think this is much worse than what you had. You had one query, and I have two of which one is repeated. This cannot possibly be better? Well, you're partially right. It is only better because it is simpler. It might even be faster. Why? Well, looking for single rows, with an indexed column, can be very fast. So the slower query is the first one, not the second one that is repeated. And my slow query is faster than yours because it doesn't have all the sub-queries. It is simpler. More over, the second query shouldn't be repeated that often. You don't want to present an user with hunderds of results, one page, with a maximum of about 10 to 20 results will do. If you really want to you could get these in one query with:</p>\n\n<pre><code>SELECT\n name,\n group_concat(\n DISTINCT concat(number, ' (', phones.description, ')')\n ORDER BY phones.description\n SEPARATOR '<br>'\n ) AS phones,\n group_concat(\n DISTINCT concat(email, ' (', emails.description, ')')\n ORDER BY emails.description\n SEPARATOR '<br>'\n ) AS emails,\n group_concat(\n DISTINCT concat(address, ' (', addresses.description, ')')\n ORDER BY addresses.description\n SEPARATOR '<br>'\n ) AS addresses\nFROM people\nJOIN phones ON phones.person_id = id \nJOIN emails ON emails.person_id = id \nJOIN addresses ON addresses.person_id = id \nWHERE FIND_IN_SET(id, ?);\n</code></pre>\n\n<p>Where <code>FIND_IN_SET()</code> contains the comma seperated id's of the persons you want to show on a page.</p>\n\n<h1>Search method</h1>\n\n<p>You seem to use separate search fields for the name, phone number, email and address tables. This might be useful, but I think most users would like a <em>single</em> search field to search through all the data in the database tables. This will become more obvious, the more fields you want to make searchable. Yes, it is nice to be able to search for a combination of a name and an email address, but often users don't need this. A single search field is easy to understand, and often what users expect. Check how <a href=\"https://support.google.com/websearch/answer/2466433\" rel=\"nofollow noreferrer\">Google let's you refine web searches</a>.</p>\n\n<h1>Efficiency</h1>\n\n<p>The query above is looking through four tables. This is fine, unless those tables get very large, or you want to search through many more tables. One method of gaining more efficiency is by making a 'search summary' column in the <code>people</code> table. Whenever a detail of a person changes, the summary for that person should be updated, but that can be done quickly since it only involves one person. With such a summary you will only have to look in one column, in one table, to perform a search through the whole database. More advanced search algorithms exist, but I'll leave it at this. My point is, you have to think about the future of your database <em>now</em>. If there is even a slight possibility it will grow a lot, then you need to take that into account at the design stage. </p>\n\n<h1>Primary keys</h1>\n\n<p>The tables <code>phones</code>, <code>emails</code> and <code>addresses</code> are missing unique primary keys. You often need one, for instance to join tables, or for something as simple as being able to edit rows in <a href=\"https://www.phpmyadmin.net\" rel=\"nofollow noreferrer\">PHPMyAdmin</a>. I'm not saying you should have them, but in practice they are often handy.</p>\n\n<h1>Naming consistency</h1>\n\n<p>I notice that you use plurals for database table names. Most people will argue to use <a href=\"https://stackoverflow.com/questions/338156/table-naming-dilemma-singular-vs-plural-names\">singulars</a>. What I really have a problem with is a table called <code>people</code> and then a foreign key called <code>person_id</code>. Either call the table <code>person</code> or the key <code>people_id</code>. No matter what you prefer, you have to be consistent about it.</p>\n\n<p>When I work with databases I find it often confusing when there are many tables with the same column names in it. I always try to choose very descriptive and unique names. So instead of <code>number</code> I would choose <code>phoneNo</code>, and instead of <code>description</code> I would use <code>connectionType</code> and <code>phoneLocation</code>. That way you would always know which column it is, and you would also not mix the connection type and phone location in one column. And if similary named columns, in different tables, really contain the same information then it is probably time to <a href=\"https://www.guru99.com/database-normalization.html\" rel=\"nofollow noreferrer\">normalize the database</a>.</p>\n\n<h1>Addresses</h1>\n\n<p>Hardly anybody stores a whole address in a single column. It is almost always useful to separate them into meaningful items. Before you know it, you will want to use an API that requires you to supply a ZIP code of a person. I got caught out once by an shipping API that insisted on a separate house number. I had to split the addresses of thousands of records, and believe me, that was no fun.</p>\n\n<p><h1>HTML in queries</H1>\nI noticed that you have some HTML in your query. That is highly unusual. Such a query is part of the data management in your <em>model</em>, not part of the final output <em>view</em> to the user. See the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC pattern</a>. <a href=\"https://i.stack.imgur.com/uZoZc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uZoZc.png\" alt=\"MVC pattern\"></a> \n I know that patterns are no fun, but believe me, it is useful, in the long run, to separate your search query from the HTML output to the user. For instance, if you want to output the result of the search in anything else than HTML. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:50:18.463",
"Id": "423536",
"Score": "0",
"body": "A quick comment before I read the whole review: the search query you propose doesn't select the entire contact information, only the (phones/emails/addresses) that match the search criteria. If I search for a person with email `LIKE '%example%'`, I want the search results to include all of this person's emails even if not all of them contain the word `'example'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:58:31.633",
"Id": "423539",
"Score": "0",
"body": "Ah, oke, I didn't get that from the question. But it makes sense. My query doesn't do that. I'll have to rethink this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:12:10.543",
"Id": "423541",
"Score": "0",
"body": "Great review, taught me some important lessons, thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:17:26.180",
"Id": "423544",
"Score": "0",
"body": "I've updated the query bit. It is simply better not to try to do this in one query, especially since this is going to be part of PHP code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:40:12.933",
"Id": "219274",
"ParentId": "219192",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219274",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:07:29.897",
"Id": "219192",
"Score": "1",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Search by parameters from multiple tables"
} | 219192 |
<p>I have a long roster where I'd like to categorize the rates by time/day of service. Most shifts ends the same date but there are some special cases where the shift ends on a different date. I have to prorate those shifts. My solutions seems to have used a lot of for loops. I would appreciate any help improving my coding.</p>
<pre><code>from datetime import datetime, timedelta, date, time
from scrape import scrape
import csv
def time_intersect(start_A, end_A, start_B, end_B):
"""
accepts 2 timeframe and return the overlap
:param start_A: datetime
:param end_A: datetime
:param start_B: datetime
:param end_B: datetime
:return: timedelta
"""
latest_start = max(start_A, start_B)
earliest_end = min(end_A, end_B)
if latest_start <= earliest_end:
return (earliest_end - latest_start).total_seconds()/3600
else:
return 0
def create_datelist(start_A, end_B, time_start, time_end, sat=False, sun=False):
"""
takes 2 datetime object iterates to all dates in range of the 2 datetime object
and combine the time_start and time_end to all dates in range. Returns a list of 2 datetime item list
:param start_A: datetime
:param end_B: datetime
:param time_start: int 0 to 23
:param time_end: int 0 to 23
:return: datetime
"""
if time_start > time_end:
day_offset = 1
else:
day_offset = 0
counter = 0
datelist = []
while True:
if sat and start_A.weekday() == 5:
datelist.append([datetime.combine(start_A, time(0)),
datetime.combine(start_A + timedelta(days=1), time(0))])
elif sun and start_A.weekday() == 6:
datelist.append([datetime.combine(start_A, time(0)),
datetime.combine(start_A + timedelta(days=1), time(0))])
elif not sat and not sun:
datelist.append([datetime.combine(start_A, time(time_start)),
datetime.combine(start_A + timedelta(days=day_offset), time(time_end))])
counter += 1
start_A += timedelta(days=counter)
if start_A.date() > end_B.date():
break
return datelist
#Sample data from scrape() [[2019-03-19 00:00:00,2019-03-19 06:00:00,Staff name,Client name]] there would 1000+ items
rosters = scrape()
rates = {'am':48.14,
'pm':52.79,
'on':34.14,
'sat':66.77,
'sun':85.45}
roster_rated = []
for roster in rosters:
mornings = create_datelist(roster[0],roster[1],6,20)
evenings = create_datelist(roster[0],roster[1],20,0)
over_nights = create_datelist(roster[0],roster[1],0,6)
if roster[1].hour == 0:#adjust for midnight
roster[1] += timedelta(days=1)
sat = 0
sun = 0
am = 0
pm = 0
on = 0
if roster[0].weekday() == 5:
saturdays = create_datelist(roster[0], roster[1], 0, 6, sat=True)
for saturday in saturdays:
sat += time_intersect(roster[0], roster[1], saturday[0], saturday[1])
elif roster[0].weekday() == 6:
sundays = create_datelist(roster[0], roster[1], 0, 6, sun=True)
for sunday in sundays:
sun += time_intersect(roster[0], roster[1], sunday[0], sunday[1])
else:
for morning in mornings:
am += time_intersect(roster[0], roster[1], morning[0], morning[1])
for evening in evenings:
pm += time_intersect(roster[0], roster[1], evening[0], evening[1])
for over_night in over_nights:
on += time_intersect(roster[0], roster[1], over_night[0], over_night[1])
roster.extend([am,am*rates['am'],pm,pm*rates['pm'],on,on*rates['on'],sat,sat*rates['sat'],sun,sun*rates['sun']])
roster_rated.append(roster)
with open('roster_rated.csv', 'w', newline='') as f:
writer = csv.writer(f)
for each in roster_rated:
writer.writerow(each)
</code></pre>
<p>Sample Input</p>
<pre><code>from,to,staff,client
8/04/2019 8:30,8/04/2019 23:00,John Doe,Juan Dela Cruz
8/04/2019 12:00,8/04/2019 15:00,John Doe,Juan Dela Cruz
8/04/2019 20:00,8/04/2019 21:30,John Doe,Juan Dela Cruz
8/04/2019 10:00,8/04/2019 23:00,John Doe,Juan Dela Cruz
9/04/2019 8:30,9/04/2019 11:00,John Doe,Juan Dela Cruz
9/04/2019 13:30,9/04/2019 14:30,John Doe,Juan Dela Cruz
9/04/2019 20:00,9/04/2019 21:30,John Doe,Juan Dela Cruz
9/04/2019 22:00,9/04/2019 23:00,John Doe,Juan Dela Cruz
10/04/2019 9:00,10/04/2019 12:00,John Doe,Juan Dela Cruz
10/04/2019 13:30,10/04/2019 14:30,John Doe,Juan Dela Cruz
10/04/2019 13:30,10/04/2019 14:00,John Doe,Juan Dela Cruz
10/04/2019 22:00,10/04/2019 23:00,John Doe,Juan Dela Cruz
11/04/2019 8:30,11/04/2019 11:00,John Doe,Juan Dela Cruz
11/04/2019 11:00,11/04/2019 14:30,John Doe,Juan Dela Cruz
11/04/2019 8:00,11/04/2019 21:30,John Doe,Juan Dela Cruz
11/04/2019 22:00,11/04/2019 23:00,John Doe,Juan Dela Cruz
12/04/2019 8:30,12/04/2019 11:00,John Doe,Juan Dela Cruz
12/04/2019 11:30,12/04/2019 16:30,John Doe,Juan Dela Cruz
12/04/2019 22:00,12/04/2019 23:00,John Doe,Juan Dela Cruz
13/04/2019 8:30,13/04/2019 10:30,John Doe,Juan Dela Cruz
13/04/2019 13:30,13/04/2019 14:30,John Doe,Juan Dela Cruz
13/04/2019 16:00,13/04/2019 17:00,John Doe,Juan Dela Cruz
13/04/2019 20:00,13/04/2019 21:30,John Doe,Juan Dela Cruz
13/04/2019 22:00,13/04/2019 23:00,John Doe,Juan Dela Cruz
14/04/2019 8:30,14/04/2019 10:30,John Doe,Juan Dela Cruz
14/04/2019 13:30,14/04/2019 14:30,John Doe,Juan Dela Cruz
14/04/2019 16:00,14/04/2019 17:00,John Doe,Juan Dela Cruz
14/04/2019 22:00,14/04/2019 23:00,John Doe,Juan Dela Cruz
</code></pre>
<p>Expected Outcome</p>
<pre><code>from,to,staff,client,am,am_cost,pm,pm_cost,on,on_cost,sat,sat_cost,sun,sun_cost
8/04/2019 8:30,8/04/2019 23:00,John Doe,Juan Dela Cruz,2.5,120.35,12,633.48,0,0,0,0,0,0
8/04/2019 12:00,8/04/2019 15:00,John Doe,Juan Dela Cruz,3,144.42,0,0,0,0,0,0,0,0
8/04/2019 20:00,8/04/2019 21:30,John Doe,Juan Dela Cruz,0,0,1.5,79.185,0,0,0,0,0,0
8/04/2019 10:00,8/04/2019 23:00,John Doe,Juan Dela Cruz,12,577.68,1,52.79,0,0,0,0,0,0
9/04/2019 8:30,9/04/2019 11:00,John Doe,Juan Dela Cruz,2.5,120.35,0,0,0,0,0,0,0,0
9/04/2019 13:30,9/04/2019 14:30,John Doe,Juan Dela Cruz,1,48.14,0,0,0,0,0,0,0,0
9/04/2019 20:00,9/04/2019 21:30,John Doe,Juan Dela Cruz,0,0,1.5,79.185,0,0,0,0,0,0
9/04/2019 22:00,9/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,1,52.79,0,0,0,0,0,0
10/04/2019 9:00,10/04/2019 12:00,John Doe,Juan Dela Cruz,3,144.42,0,0,0,0,0,0,0,0
10/04/2019 13:30,10/04/2019 14:30,John Doe,Juan Dela Cruz,1,48.14,0,0,0,0,0,0,0,0
10/04/2019 13:30,10/04/2019 14:00,John Doe,Juan Dela Cruz,0.5,24.07,0,0,0,0,0,0,0,0
10/04/2019 22:00,10/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,1,52.79,0,0,0,0,0,0
11/04/2019 8:30,11/04/2019 11:00,John Doe,Juan Dela Cruz,2.5,120.35,0,0,0,0,0,0,0,0
11/04/2019 11:00,11/04/2019 14:30,John Doe,Juan Dela Cruz,3.5,168.49,0,0,0,0,0,0,0,0
11/04/2019 8:00,11/04/2019 21:30,John Doe,Juan Dela Cruz,12,577.68,1.5,79.185,0,0,0,0,0,0
11/04/2019 22:00,11/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,1,52.79,0,0,0,0,0,0
12/04/2019 8:30,12/04/2019 11:00,John Doe,Juan Dela Cruz,2.5,120.35,0,0,0,0,0,0,0,0
12/04/2019 11:30,12/04/2019 16:30,John Doe,Juan Dela Cruz,5,240.7,0,0,0,0,0,0,0,0
12/04/2019 22:00,12/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,1,52.79,0,0,0,0,0,0
13/04/2019 8:30,13/04/2019 10:30,John Doe,Juan Dela Cruz,0,0,0,0,0,0,2,133.54,0,0
13/04/2019 13:30,13/04/2019 14:30,John Doe,Juan Dela Cruz,0,0,0,0,0,0,1,66.77,0,0
13/04/2019 16:00,13/04/2019 17:00,John Doe,Juan Dela Cruz,0,0,0,0,0,0,1,66.77,0,0
13/04/2019 20:00,13/04/2019 21:30,John Doe,Juan Dela Cruz,0,0,0,0,0,0,1.5,100.155,0,0
13/04/2019 22:00,13/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,0,0,0,0,1,66.77,0,0
14/04/2019 8:30,14/04/2019 10:30,John Doe,Juan Dela Cruz,0,0,0,0,0,0,0,0,2,170.9
14/04/2019 13:30,14/04/2019 14:30,John Doe,Juan Dela Cruz,0,0,0,0,0,0,0,0,1,85.45
14/04/2019 16:00,14/04/2019 17:00,John Doe,Juan Dela Cruz,0,0,0,0,0,0,0,0,1,85.45
14/04/2019 22:00,14/04/2019 23:00,John Doe,Juan Dela Cruz,0,0,0,0,0,0,0,0,1,85.45
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:16:00.257",
"Id": "219193",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"datetime",
"csv",
"interval"
],
"Title": "Getting service rate based on time/day of service"
} | 219193 |
<p>I'm trying to make my code more readable. I created a function <code>toString</code> - It returns a string in the following format:</p>
<pre><code>Name: <Name>.
IdNumber: <Number>.
Age: <Number>.
Colors: <Color1, Color2, ..., ColorN>.
</code></pre>
<p>Please notice that the colors should be sorted alphabetically. The function I wrote for now:</p>
<pre><code>public String toString() {
String colorsString = this.colors.stream().sorted().collect(Collectors.joining(", "));
return "Name: " + this.Name+".\n" +
"IdNumber: " + this.Id+".\n" +
"Age: " + this.Age+".\n" +
"Colors: " + colorsString + ".";
}
</code></pre>
<p>I don't like the way I sorted the colors. I would like to use stream, but in other way if possible. Also, I feel like the format should be constant. Is it possible to keep it as a constant and add values to it? Future more I don't like the use of <code>\n</code> - is it possible without it?</p>
| [] | [
{
"body": "<p><a href=\"https://stackoverflow.com/a/878704\">This answer to a question on multi line strings</a> contains a lot of good examples of trouble with building multi line string output this way but in particular I think the String.format approach works best with a template string.</p>\n\n<p>Your setup would be something like</p>\n\n<pre><code>String template = “ Name: %s %n ID: ...”\n</code></pre>\n\n<p>And you would place it with</p>\n\n<pre><code>String formatted = String.format(template, nameString, idString,...);\n</code></pre>\n\n<hr>\n\n<p>Don’t like their sorting algorithm? I’d recommend extending your own! You can provide your own comparator for the sort stream function. This gives you complete control over how it sorts, at the expense of providing the desired sorting logic.\n<a href=\"https://www.geeksforgeeks.org/stream-sorted-comparator-comparator-method-java/amp/\" rel=\"nofollow noreferrer\">This article contains several examples of ways to extend your own comparators to this function</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:42:31.150",
"Id": "423489",
"Score": "0",
"body": "Thank you. what can you say about the creating of `colorsString`? Is there another and better way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:43:25.487",
"Id": "423490",
"Score": "0",
"body": "The second link/ bottom half of the answer is answering that: the stream/sort you are doing is perfectly fine. My only recommendations would be, since you stated you didn’t like how it sorted out of the box, the second link contains several examples of how to change the sort by writing your own sorting algorithm :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T03:52:31.753",
"Id": "219230",
"ParentId": "219201",
"Score": "1"
}
},
{
"body": "<ul>\n<li>You can use the line separator property instead of \"\\n\".</li>\n<li>You can use a StringBuffer for more speed.</li>\n<li>For better readability you can only pass the parameters. If you format them like I have done in the example below, you can just add a new parameter by copying/pasting an existing one. That's the reason I added the empty string \"\", so no need for deleting the comma after the last parameter. </li>\n<li>I intentionally left the id unassigned to test the null.</li>\n<li>To keep the example compact, I used an inner class StringUtilities(). Of course you should extract it and put it in a common place to access it from everywhere.</li>\n</ul>\n\n<p>Here is the code:</p>\n\n<pre><code>public class Main {\n public static class StringUtilities {\n public static String newLine = System.getProperty(\"line.separator\");\n\n public static String buildString(final Object... parameters) {\n StringBuffer buffer = new StringBuffer(20 * parameters.length);\n for (int i = 0; i < parameters.length; i++) {\n Object parameter = parameters[i];\n buffer.append(parameter == null ? \"null\" : parameter);\n if (i % 2 == 1) {\n buffer.append(newLine);\n }\n }\n return buffer.toString();\n }\n }\n\n private String name = \"myName\";\n private int age = 13;\n private String colors = \"red, green\";\n static class IdNumber {\n }\n private IdNumber id;\n\n public String toString() {\n return StringUtilities.buildString(\n \"name: \", name,\n \"id: \", id,\n \"age: \", age,\n \"colors: \", colors,\n \"\");\n }\n\n public static void main(String[] args) {\n System.out.println(new Main().toString());\n }\n}\n</code></pre>\n\n<p>Here is the console output:</p>\n\n<pre><code>name: myName\nid: null\nage: 13\ncolors: red, green\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:19:53.150",
"Id": "219373",
"ParentId": "219201",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:33:40.393",
"Id": "219201",
"Score": "1",
"Tags": [
"java"
],
"Title": "Making toString function more readable In Java"
} | 219201 |
<p>This is an algorithm to return a list of consecutive integer ranges from a list of integers.</p>
<p>The practical use of such an algorithm is to filter lists more efficiently, i.e. rather than check e.g. 1000 items (1..1000; x==1 || x==2 || ... || x==1000), it might be possible to check only 2 items (x >= 1 && x <= 1000).</p>
<p>Does this algorithm have any mistakes, can it be optimized, or are there any other improvements you can suggest?</p>
<p>(As a side note: I know this code does not follow the standard C# naming conventions. I do not like to follow that particular convention; I prefer "snake_case" as it is easier on my eyes.)</p>
<p>Sample output:</p>
<pre><code>(x >= 0 && x <= 1690)
(x >= 13642 && x <= 15331)
(x >= 27283 && x <= 27296)
(x >= 27769 && x <= 27776)
(x >= 28249 && x <= 28256)
(x >= 28729 && x <= 28736)
(x >= 29209 && x <= 29222)
</code></pre>
<p>The algorithm (built Visual Studio 2017, C# 7.3, .NET 4.7.2):</p>
<pre><code>public static List<(int from, int to)> get_consecutive_ranges(List<int> fids)
{
if (fids == null || fids.Count == 0) return null;
fids = fids.OrderBy(a => a).Distinct().ToList();
var fids_fast = new List<(int from, int to)>();
var is_conseq_with_last = true;
var start_index = 0;
var end_index = 0;
for (var fids_index = 0; fids_index < fids.Count; fids_index++)
{
var first = fids_index == 0;
var last = fids_index == fids.Count - 1;
if (!first && fids[fids_index - 1] == fids[fids_index] - 1)
{
is_conseq_with_last = true;
}
else if (!first)
{
is_conseq_with_last = false;
}
if (!is_conseq_with_last && !first && !last)
{
end_index = !first && !last ? fids_index - 1 : fids_index;
fids_fast.Add((fids[start_index], fids[end_index]));
start_index = fids_index;
}
else if (last)
{
if (!is_conseq_with_last)
{
if (!first)
{
end_index = fids_index - 1;
}
fids_fast.Add((fids[start_index], fids[end_index]));
start_index = fids_index;
}
end_index = fids_index;
fids_fast.Add((fids[start_index], fids[end_index]));
}
}
fids_fast.ForEach(a => Console.WriteLine($"(x >= {a.@from} && x <= {a.to})"));
return fids_fast;
}
</code></pre>
<p>Example use:</p>
<pre><code>// slow:
body = body.Where(a => fids.Contains(a.fid)).ToList();
// fast:
body = body.Where(a => fids_fast.Any(x => a.fid >= x.from && a.fid <= x.to)).ToList();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:48:04.400",
"Id": "423421",
"Score": "1",
"body": "@t3chb0t no I just dislike camel case as I personally find it to be quite difficult to read and thus more likely to cause eye strain. Thanks for your suggestion, I will add it to my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T20:02:04.393",
"Id": "423425",
"Score": "0",
"body": "One more suggestion... if you have any running demo console/unit-test code (which I strongly believe) then you should add it too. It'll make it easier to review your algorithm as people will be able to actually execute it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T20:40:13.723",
"Id": "423428",
"Score": "1",
"body": "What does `fids` stand for? Would help me understand what your algorithm is doing better ( at least I would hope )."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:42:12.400",
"Id": "423434",
"Score": "0",
"body": "@Shelby115 actually, your naming makes it more generic, which is good. However, to answer the question, fids means 'features ids'. The reason I am writing this method is to filter criteria-specific feature id numbers from millions of id numbers (integers). The actual use case is machine learning, classification specifically, where millions of features are available, but only a small subset can be used or tested together."
}
] | [
{
"body": "<p>As a pre-note, I had to translate everything to camelCase and PascalCase because I was having a very difficult time reading your code. No judgments, just understand I was running short on time and didn't translate it back on the conclusion.</p>\n\n<p><strong>Readability</strong></p>\n\n<p>Use meaningful names.</p>\n\n<ul>\n<li><code>fids</code> I changed to <code>integers</code> as from your description I gather it's the list of integers used to create the ranges.</li>\n<li><code>fids_index</code> seems very noisy. Standard convention is <code>i</code>, <code>j</code>, etc. When you reduce the iterator variable down to a single character it's much easier to focus on what actually matters.</li>\n<li>Booleans should be prefixed with <code>Is</code> or <code>Has</code> or <code>Was</code> etc. So in this case <code>IsFirst</code> and <code>IsLast</code> instead of <code>first</code> and <code>last</code> makes it easier to read as english. You could even consider using <code>var isNotFirst = i != 0;</code> as you only use <code>!first</code> in the algorithm.</li>\n<li>Last vs Previous. <code>is_conseq_with_last</code> is refering to previous, so I switched it to previous to avoid confusion with <code>last</code>.</li>\n<li><code>start_index</code> and <code>end_index</code> sound like they would be <code>0</code> and <code>integers.Count</code>. They're the start and end of the range you're tracking, let's name them accordingly: <code>rangeStart</code> and <code>rangeEnd</code>.</li>\n</ul>\n\n<p><strong>If-Statement Ordering & Flow</strong></p>\n\n<p>We've all been there, written an algorithm, tested it, and it works, all done right? Well, sometimes that algorithm can be restructured to express what we're actually doing much clearer.</p>\n\n<pre><code> if (!first && fids[fids_index - 1] == fids[fids_index] - 1)\n {\n is_conseq_with_last = true;\n }\n else if (!first)\n {\n is_conseq_with_last = false;\n }\n</code></pre>\n\n<p>There's a common denominator here, <code>!first</code> let's work with that, clearly neither of these happen if it's true.</p>\n\n<pre><code>if (!first)\n{\n if (fids[fids_index - 1] == fids[fids_index] - 1)\n {\n is_conseq_with_last = true;\n }\n else\n {\n is_conseq_with_last = false;\n }\n}\n</code></pre>\n\n<p>Well, now it's obvious that inner if-statement can be reduced.</p>\n\n<pre><code>if (!first)\n{\n is_conseq_with_last = fids[fids_index - 1] == fids[fids_index] - 1;\n}\n</code></pre>\n\n<p>And if you wanted, a ternary operator.</p>\n\n<pre><code>is_conseq_with_last = !first && fids[fids_index - 1] == fids[fids_index] - 1;\n</code></pre>\n\n<p>And it's now also obvious that you're setting the variable with each iteration, so there's no need to declare it outside the loop.</p>\n\n<p>Similar can be done with the bottom if-statement. Here's what I ended up with altogether.</p>\n\n<p><strong>My Version</strong></p>\n\n<p>I am running short on time so there might be a mistake or two and it's still in my coding style so don't take it for face value and try to apply the concepts I'm showing above yourself.</p>\n\n<pre><code>public static List<(int from, int to)> GetConsecutiveRanges(List<int> integers)\n{\n if (integers == null || integers.Count == 0) { return null; }\n\n integers = integers.OrderBy(a => a).Distinct().ToList();\n var ranges = new List<(int from, int to)>();\n\n var rangeStart = 0;\n var rangeEnd = 0;\n\n for (var i = 0; i < integers.Count; i++)\n {\n var isFirst = i == 0;\n var isLast = i == integers.Count - 1;\n var isConsecutiveFromPrevious = isFirst == false && integers[i-1] == integers[i] - 1;\n\n if (last)\n {\n if (isConsecutiveFromPrevious == false)\n {\n rangeEnd = isFirst == false ? i - 1 : rangeEnd;\n ranges.Add((integers[rangeStart], integers[rangeEnd]));\n rangeStart = i;\n }\n\n rangeEnd = i;\n ranges.Add((integers[rangeStart], integers[rangeEnd]));\n }\n else if (isConsecutiveFromPrevious == false && isFirst == false)\n {\n rangeEnd = isFirst == false && isLast == false ? i - 1 : i;\n ranges.Add((integers[rangeStart], integers[rangeEnd]));\n rangeStart = i;\n }\n\n }\n\n ranges.ForEach(a => Console.WriteLine($\"(x >= {a.@from} && x <= {a.to})\"));\n\n return ranges;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:28:19.987",
"Id": "423431",
"Score": "0",
"body": "I wonder whether it would be more efficient to swap these two calls `.OrderBy(a => a).Distinct().`- just thinking aloud..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:36:43.643",
"Id": "423432",
"Score": "0",
"body": "@t3chb0t I had exactly the same thought, but in the end, both methods must track values, so performance must surely be similar either way around?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:37:44.767",
"Id": "423433",
"Score": "0",
"body": "@Shelby115 There are some very interesting points in your answer - thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T08:31:08.933",
"Id": "423460",
"Score": "0",
"body": "_I had to translate everything to camelCase and PascalCase because I was having a very difficult time reading your code_ - same here ;-) and I think we'll need this for other questions too: `Regex.Replace(File.ReadAllText(path), \"_([a-zA-Z])\", m => m.Groups[1].Value.ToUpper());`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:08:22.247",
"Id": "423732",
"Score": "1",
"body": "@t3chb0t Would be cool if the site implemented something like a toggle button to view code in a different convention. Obviously there are a lot of complications to being able to do that, so it wouldn't quite work in practice necessarily."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:09:44.230",
"Id": "219209",
"ParentId": "219204",
"Score": "4"
}
},
{
"body": "<p>Your code is really complicated. First, your code should be abstracted a little more. It is not specific to feature IDs, therefore the terminology should not use these words. The same algorithm can be used to select which pages to print from a document, therefore the variables should be just <code>nums</code> and <code>ranges</code>. To test your current code, I wrote:</p>\n\n<pre><code>[Test]\npublic void TestRanges()\n{\n Assert.AreEqual(\"\", Str(Ranges(new List<int>())));\n Assert.AreEqual(\"1\", Str(Ranges(new List<int> { 1 })));\n Assert.AreEqual(\"1-5\", Str(Ranges(new List<int> { 1, 2, 3, 4, 5 })));\n Assert.AreEqual(\"1-3, 5\", Str(Ranges(new List<int> { 1, 2, 3, 5 })));\n Assert.AreEqual(\"1, 3, 5-6\", Str(Ranges(new List<int> { 1, 3, 5, 6 })));\n}\n</code></pre>\n\n<p>I wrote a helper function <code>Str</code> so that I don't have to construct a list of ranges for each test case:</p>\n\n<pre><code>public static string Str(List<(int from, int to)> ranges)\n{\n var parts = new List<string>();\n\n foreach (var range in ranges) {\n if (range.from == range.to) {\n parts.Add(range.from.ToString());\n } else {\n parts.Add(range.@from + \"-\" + range.to);\n }\n }\n\n return string.Join(\", \", parts);\n}\n</code></pre>\n\n<p>After renaming your function to <code>Ranges</code>, these tests ran successfully. So I was ready to refactor your code. I did not really do this since your code looked too complicated to start with. Instead, I remembered that I had successfully used the following pattern quite often:</p>\n\n<pre><code>var start = ...;\nwhile (start < nums.Count) {\n var end = ...;\n while (end < nums.Count) {\n }\n}\n</code></pre>\n\n<p>With this knowledge I wrote the following code:</p>\n\n<pre><code>public static List<(int from, int to)> Ranges(List<int> nums)\n{\n nums = nums.OrderBy(a => a).Distinct().ToList();\n\n var ranges = new List<(int from, int to)>();\n\n var start = 0;\n while (start < nums.Count) {\n var end = start + 1; // the range is from [start, end).\n\n while (end < nums.Count && nums[end - 1] + 1 == nums[end]) {\n end++;\n }\n\n ranges.Add((nums[start], nums[end - 1]));\n start = end; // continue after the current range\n }\n\n return ranges;\n}\n</code></pre>\n\n<p>This code doesn't need any special cases for the last range, or anything else. A range either stops when the end of the numbers is reached, or when the following number is not consecutive. This sounds sensible, and this is exactly what the code is doing.</p>\n\n<p>I removed the check for <code>nums == null</code> since it is not necessary. Collections should never be null, and if they are, the code immediately throws an exception, which is fine.</p>\n\n<p>I also removed the special case for <code>nums.Count == 0</code> since returning an empty list is much better than returning null. Again, expressions that have collection type should never be null. The test cases cover this case, so there's nothing to worry about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T01:13:52.377",
"Id": "219223",
"ParentId": "219204",
"Score": "5"
}
},
{
"body": "<p>Your code takes a list, ensures it's sorted and distinct, then assembles and returns another list. This approach is problematic when the input is in fact a generator, in which case your code forces the entire list to memory first. Also, the data might already be sorted or the caller might not be interested in the entire result.</p>\n\n<pre><code>public static List<(int from, int to)> get_consecutive_ranges(List<int> fids)\n{\n if (fids == null || fids.Count == 0) return null;\n\n fids = fids.OrderBy(a => a).Distinct().ToList();\n</code></pre>\n\n<p>A much more idiomatic approach is to build an extension method that works on <code>IEnumerable</code> and <code>yield</code>s its results. The call to <code>Distinct().OrderBy(a => a)</code> should be left to the caller. Also note that <code>Distinct</code> doesn't guarantee any particular order, so the sorting must always happen afterwards. The actual logic is overly complicated in your code and be greatly simplified as well. Here is how I would do it:</p>\n\n<pre><code>public static IEnumerable<(int begin, int end)> Ranges(this IEnumerable<int> nums)\n{\n var e = nums.GetEnumerator();\n if (e.MoveNext())\n {\n var begin = e.Current;\n var end = begin + 1;\n while (e.MoveNext())\n {\n if (e.Current != end)\n {\n yield return (begin, end);\n begin = end = e.Current;\n }\n end++;\n }\n yield return (begin, end);\n }\n}\n</code></pre>\n\n<p>Add a simple helper function for pretty printing, which should also be an extension method:</p>\n\n<pre><code>public static string Show(this IEnumerable<(int begin, int end)> ranges)\n{\n return \"[\" + string.Join(\",\", ranges.Select(r => r.end - r.begin == 1 ? $\"{r.begin}\" : $\"{r.begin}-{r.end-1}\")) + \"]\";\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>Console.WriteLine(new int[] { }.Ranges().Show()); -> \"[]\"\nConsole.WriteLine(new int[] { 1 }.Ranges().Show()); -> \"[1]\"\nConsole.WriteLine(new int[] { 1, 2, 3, 4, 5 }.Ranges().Show()); -> \"[1-5]\"\nConsole.WriteLine(new int[] { 1, 2, 3, 5 }.Ranges().Show()); -> \"[1-3,5]\"\nConsole.WriteLine(new int[] { 1, 3, 5, 6 }.Ranges().Show()); -> \"[1,3,5-6]\"\nConsole.WriteLine(new int[] { 1, 3, 3, 3, 5, 6 }.Distinct().Ranges().Show()); -> \"[1,3,5-6]\"\nConsole.WriteLine(new int[] { 6, 3, 5, 1 }.OrderBy(i => i).Ranges().Show()); -> \"[1,3,5-6]\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T08:40:24.130",
"Id": "423461",
"Score": "0",
"body": "_A much more idiomatic approach is to build an extension method the works on IEnumerable and yields its results._ - This is exactly how it should be done ;-]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T03:26:38.420",
"Id": "219227",
"ParentId": "219204",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219223",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:06:11.600",
"Id": "219204",
"Score": "6",
"Tags": [
"c#",
"algorithm",
"interval"
],
"Title": "Get consecutive integer number ranges from list of int"
} | 219204 |
<p>I've written a piece of code that determines if a piece toast with butter lands on the butter-side or not, depending on its initial velocity and the table height. </p>
<p>The code is written in Mathematica and to be honest, it was my first time writing a piece of code in this language (which wasn't a simple calculation of an integral or something alike). It works and produces results I would expect but it incredibly slow and I don't even know where to start to correct it. </p>
<p>So what I'm looking for are some general hints on how to imporve when writing Mathematica code, style conventions (is there something like pep8 for Python?) and how to speed the code up.</p>
<hr>
<pre><code>ClearAll["Global`*"]
MapMonitored[f_, args_List] := Module[{x = 0},
Monitor[MapIndexed[(x = #2[[1]]; f[#1]) &, args],
ProgressIndicator[x/Length[args]]]]
DrawBread[sol_,t_]:=Module[{bb=0.02,LL=0.1},ut=Flatten[u[t]/.sol];
xb:=trajectory[t]/.{b\[Rule]0.02,L\[Rule]0.1}+{-bb/2.0 \
Sin[ut],-bb/2.0 Cos[ut]};
xleftdown:=xb+{-LL/2.0 Cos[ut],LL/2.0 Sin[ut]};
xleftup:=xleftdown+{bb Sin[ut],bb Cos[ut]};
xrightup:=xleftup+{LL Cos[ut],-LL Sin[ut]};
xrightdown:=xrightup+{-bb Sin[ut],-bb Cos[ut]};
p=Block[{b=0.02,L=0.1},
Show[
ListLinePlot[
{Flatten[{xb,xleftdown,xleftup,xrightup,xrightdown,xb}]},
PlotStyle\[Rule]Blue
],
ListLinePlot[
{Flatten[xleftup],Flatten[xrightup]},
PlotStyle[Rule]Red
],
ListLinePlot[
{Flatten[xrightup],Flatten[xrightdown],Flatten[xb]},
PlotStyle\[Rule] Blue
],
ListPlot[
{0.0,trajectory[t]},
PlotStyle\[Rule]Red
],
AspectRatio\[Rule]1.0,
PlotRange\[Rule]{{-0.1,1.0},{0.05,-1.5}}
]
];
Return[p]];
DrawBreadAfterChange[sol_,t_,tst_,vtstar_]:=Module[{bb=0.02,LL=0.1},
uu[time_]=Flatten[u[time]/.sol];
uu0=Abs[uu[tst]-uu'[tst] tst+uu[tst]];
angle:=uu'[tst] t-uu[tst]+uu0;
xb:=wurfparabel[t,sol,tst,vtstar]+{-bb/2.0 Sin[angle],-bb/2.0 Cos[angle]};
xleftdown:=xb+{-LL/2.0 Cos[angle],LL/2.0 Sin[angle]};
xleftup:=xleftdown+{bb Sin[angle],bb Cos[angle]};
xrightup:=xleftup+{LL Cos[angle],-LL Sin[angle]};
xrightdown:=xrightup+{-bb Sin[angle],-bb Cos[angle]};
p=Block[{b=0.02,L=0.1},
Show[
ListLinePlot[
{Flatten[xb],Flatten[xleftdown],Flatten[xleftup],Flatten[xrightup],
Flatten[xrightdown],Flatten[xb]},
PlotRange\[Rule]{{-0.1,1.0},{0.05,-1.5}},
PlotStyle\[Rule]Blue
],
ListLinePlot[
{Flatten[xleftup],Flatten[xrightup]},
PlotRange\[Rule]{{-0.1,1.0},{0.05,-1.5}},
PlotStyle\[Rule]Red
],
ListLinePlot[
{Flatten[xrightup],Flatten[xrightdown],Flatten[xb]},
PlotRange\[Rule]{{-0.1,1.0},{0.05,-1.5}},
PlotStyle\[Rule]Blue
],
ListPlot[{Flatten[wurfparabel[t,sol,tst,vtstar]]},
PlotStyle\[Rule]Red],
AspectRatio\[Rule]1.0
]
];
Return[p]
];
DrawBreadFinal[sol_,t_,tst_,vtstar_]:=If[t\[LessEqual]tst,
DrawBread[sol,t],
DrawBreadAfterChange[sol,t,tst,vtstar]
];
CalculateEdgesOfBread[sol_, t_, tst_, vtstar_] :=
Module[{bb = 0.02, LL = 0.1},
uu[time_] = Flatten[u[time] /. sol];
uu0 = Abs[uu[tst] - uu'[tst] tst + uu[tst]];
angle = uu'[tst] t - uu[tst] + uu0;
xb = wurfparabel[t, sol, tst,vtstar] + {-bb/2.0 Sin[angle], -bb/2.0 Cos[angle]};
xleftdown = xb + {-LL/2.0 Cos[angle], LL/2.0 Sin[angle]};
xleftup = xleftdown + {bb Sin[angle], bb Cos[angle]};
xrightup = xleftup + {LL Cos[angle], -LL Sin[angle]};
xrightdown = xrightup + {-bb Sin[angle], -bb Cos[angle]};
Return[
Abs[Min[xleftdown, xleftup, xrightup, xrightdown]]]
];
AngleAtGround[sol_, tst_, tt_] := Module[{},
uu[t_] = Flatten[u[t] /. sol];
uu0 = Abs[uu[tst] - uu'[tst] tst + uu[tst]];
angle = uu'[tst] tt - uu[tst] + uu0;
Return[Mod[angle[[1]], 2.0 Pi]]];
BreadOrButterSide[phi_] :=
If[Pi/2.0 <= phi, If[phi <= 3.0 Pi/2.0, 1.0, 0.0], 0.0];
wurfparabel[tt_, sol_, tst_, vtstar_] := Module[{g = 9.81},
beta = Abs[Flatten[u[tst] /. sol]];
xspace = vtstar[[1]] tt Cos[beta];
xx0 = Abs[trajectory[tst][[1]] - vtstar[[1]] tst Cos[beta]];
yspace = -(Norm[v[tst]] tt Sin[beta] + g tt^2/2.0);
y0 = Abs[
trajectory[tst][[
2]] + (Norm[v[tst]] tst Sin[beta] + g tst^2/2.0)];
Return[{xspace + xx0, yspace + y0}]];
x[t_] = {{s[t] Cos[u[t]] + b/2 Sin[u[t]]}, {-s[t] Sin[u[t]] +
b/2 Cos[u[t]]}};
m = 0.1; l = 0.1; g = 9.81;
J = 1.0/12.0 m (l^2 + b^2);
T[t_] = Simplify[1.0/2.0 (m) Flatten[x'[t]].Flatten[x'[t]]] +
1.0/2.0 J u'[t]^2;
V[t_] = m g x[t][[2, 1]];
L[t_] = Simplify[T[t] - V[t]];
<< VariationalMethods`
GetTheThingsINeed[StartingValuesList_, Lagrangian_: L,
PositionVector_: x] := Module[{g = 9.81},
b = 0.02;
eoms[t_] = Simplify[VariationalD[Lagrangian[t], s[t], t]];
eomu[t_] = Simplify[VariationalD[Lagrangian[t], u[t], t]];
TabelHeight = StartingValuesList[[2]];
solution =
NDSolve[{eoms[t] == 0.0, eomu[t] == 0.0, u[0] == 0.0, s[0] == 0.01,
s'[0] == StartingValuesList[[1]], u'[0] == 0.1}, {u, s}, {t,
0.0, 10.0}];
f[t_] = D[x[t][[1, 1]], {t, 2}] /. solution;
tstar = t /. FindRoot[f[t], {t, 0.1}];
trajectory[t_] := Flatten[x[t] /. solution];
v[t_] = Flatten[D[trajectory[t], t]];
tGroundTime =
t /. Flatten[
FindRoot[{CalculateEdgesOfBread[solution, t, tstar, v[tstar]] -
TabelHeight}, {t, 0.5}]];
Return[BreadOrButterSide[
AngleAtGround[solution, tstar, tGroundTime]]]];
velocities = Range[0.1, 1.8, 0.2];
TabelHeights = Range[0.3, 1.5, 0.8];
mesh = Tuples[{velocities, TabelHeights}];
plotmesh =
MapMonitored[GetTheThingsINeed, mesh] //
AbsoluteTiming; plotmesh[[1]]
ListPlot[Lookup[
GroupBy[
Thread[{mesh, plotmesh[[2]]}],
Last -> First],
{1.0, 0.0}],
PlotStyle -> {Green, Red}, AxesLabel -> {"v", "h"}
]
</code></pre>
<p><strong>Edit:</strong> I cleared the code up a bit.. Didn't impact performance at all. </p>
<p><strong>Edit II:</strong> On a whim I just changed the line</p>
<pre><code>tGroundTime =
t /. Flatten[
NSolve[{CalculateEdgesOfBread[solution, t, tstar, v[tstar]] ==
TabelHeight, t > 0.0}, t]];
</code></pre>
<p>to </p>
<pre><code>tGroundTime =
t /. Flatten[
FindRoot[{CalculateEdgesOfBread[solution, t, tstar, v[tstar]] -
TabelHeight}, {t, 0.5}]];
</code></pre>
<p>and the Code is now approximately 1000 times faster.. Not sure why this makes such a huge change..</p>
<p><strong>EDIT III:</strong> Cleared the code up again and moved as much as possible out of the <code>GetTheThingsINeed</code> out. Turns out this improves the performance again, now the code runs in about 0.8 sec compared to the 12 sec in the beginning. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:15:41.703",
"Id": "423529",
"Score": "1",
"body": "`NSolve` was searching for all possible positive solutions, whereas `FindRoot` uses something like Newton's method to find a single solution."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T19:25:29.327",
"Id": "219205",
"Score": "4",
"Tags": [
"performance",
"beginner",
"physics",
"wolfram-mathematica"
],
"Title": "Butter side up?"
} | 219205 |
<p>I wrote a program in haskell that aims to let the user encrypt, decrypt and crack/cryptanalyse pre-electromechanical era ciphers in Haskell. I want to know your opinion on it since this is my first Haskell project and so my approach to it is slightly different from the approach I would make on other languages.</p>
<p>It currently supports Caesar, Vigenere and ADFGVX ciphers and lets the user crack the first two. It also lets the user perform some cryptanalysis methods like count letter/substring frequencies and substituting letters until the user is satisfied with the result.</p>
<p>My code has a lot of functions defined on the top-level so I'm starting to get a bit worried if I should have defined some of them locally. I'm also a bit worried about the types of my functions because maybe some of them could be more generalized.</p>
<p>Please bear in mind, that the Vigenere cracking and the ADFGVX implementations have still some work to do. As for the Vigenere cracking, the user has to manually enter the mininum and maximum size of the words that are repeated along the ciphertext to be searched for (Kasiski algorithm) and the ADFGVX encryption and decryption still doesn't work 100% because i'm filling the ciphertext with the letter 'a' until it fits totally on the grid. </p>
<p>I will show you all the modules starting from the CLI (since it acts as the main method).</p>
<p><strong>cct.hs</strong></p>
<pre><code>import Control.Monad
import System.Exit
import System.IO
import MyUtils
import Ciphers.Caesar
import Ciphers.Vigenere
import Ciphers.ADFGVX
import Codebreaking.Cryptanalysis
import Codebreaking.VigenereCrack
caesarEncryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Enter the shift number:"
shift <- getLine
putStrLn "Enter the message:"
message <- getLine
let shift_int = (read shift :: Int) --convert input to int
let ciphertext = caesarShift shift_int message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Ciphertext:"
print (ciphertext)
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input <- getLine
main
vigenereEncryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Enter the desired keyword:"
key <- getLine
putStrLn "Enter the message:"
message <- getLine
let ciphertext = vigenereEncrypt key message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ("Ciphertext:")
print (ciphertext)
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input <- getLine
main
adfgvxEncryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "The program will now read the substitution key from my_grid.txt."
putStrLn "Do you want to change it (y/n)?"
input1 <- getLine
when (input1 == "y") (do createSubstitutionKey; putStrLn "Substitution key created.")
handle <- openFile "my_grid.txt" ReadMode
substitution_key <- hGetContents handle
putStrLn "Enter the desired keyword:"
key <- getLine
putStrLn "Enter the message:"
message <- getLine
let ciphertext = adfgvxEncrypt substitution_key key message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ("Ciphertext:")
print (ciphertext)
putStrLn "\nDon't forget to share the substitution key with the recipient"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input2 <- getLine
main
caesar_decryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Enter the shift number:"
shift <- getLine
putStrLn "Enter the message:"
message <- getLine
let shift_int = (read shift :: Int) --convert input to int
let plaintext = caesarShift (-shift_int) message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Plaintext:"
print (plaintext)
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input <- getLine
main
vigenereDecryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Enter the keyword:"
key <- getLine
putStrLn "Enter the message:"
message <- getLine
let plaintext = vigenereDecrypt key message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ("Plaintext:")
print (plaintext)
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input <- getLine
main
adfgvxDecryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "The program will now read the substitution key from my_grid.txt."
handle <- openFile "my_grid.txt" ReadMode
substitution_key <- hGetContents handle
putStrLn "Enter the keyword:"
key <- getLine
putStrLn "Enter the message:"
message <- getLine
let plaintext = adfgvxDecrypt substitution_key key message
clearAll
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ("Plaintext:")
print (plaintext)
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Press any key to return to the main menu."
input <- getLine
main
decryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::1 - Caesar's cipher ::"
putStrLn "::2 - Vigenere's cipher ::"
putStrLn "::3 - ADFGVX ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::r - Return e - Exit ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
input <- getLine
case input of
"1" -> caesar_decryption
"2" -> vigenereDecryption
"3" -> adfgvxDecryption
"r" -> main
"e" -> exitSuccess
otherwise -> do
putStrLn ""
putStrLn ("Please enter a valid option")
encryption
encryption = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::1 - Caesar's cipher ::"
putStrLn "::2 - Vigenere's cipher ::"
putStrLn "::3 - ADFGVX ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::r - Return e - Exit ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
input <- getLine
case input of
"1" -> caesarEncryption
"2" -> vigenereEncryption
"3" -> adfgvxEncryption
"r" -> main
"e" -> exitSuccess
otherwise -> do
putStrLn ""
putStrLn ("Please enter a valid option")
encryption
tools :: String -> String -> IO()
tools ciphertext guess = forever $ do
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Ciphertext:"
print (ciphertext)
putStrLn ""
putStrLn "My guess:"
print (guess)
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::0 - Display the letter frequency in descending order ::"
putStrLn "::1 - Break Caesar's cipher ::"
putStrLn "::2 - Break Vigenere's cipher (Babbage/Kasiski Algorithm) ::"
putStrLn "::3 - Get repeated substrings ::"
putStrLn "::4 - Count the occurrences of a substring ::"
putStrLn "::5 - Count the occurrences of a letter immediately before/after other letters ::"
putStrLn "::6 - Count the occurrences of a letter immediately before other letters ::"
putStrLn "::7 - Count the occurrences of a letter immediately after other letters ::"
putStrLn "::8 - Substitute a letter by another in the ciphertext ::"
putStrLn "::r - Return ::"
putStrLn "::e - Exit ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
input <- getLine
case input of
"0" -> do
putStrLn ""
putStrLn "Letter frequency:"
print (sortAlphabetCount ciphertext)
putStrLn ""
"1" -> do
putStrLn ""
print(breakCaesar ciphertext)
putStrLn ""
"2" -> do
putStrLn ""
putStrLn "For this tool to work it is necessary to find some substrings that have multiple occurrences along the ciphertext."
crackVigenere ciphertext
"3" -> do
putStrLn ""
putStrLn "Enter the minimum size of the substrings to be searched for:"
min_size <- getLine
putStrLn "Enter the maximum size of the substrings to be searched for:"
max_size <- getLine
let min_size_int = (read min_size :: Int)
max_size_int = (read max_size :: Int)
putStrLn "Repeated substrings:"
print (repeatedSubs min_size_int max_size_int ciphertext)
"4" -> do
putStrLn ""
putStrLn "Enter the substring:"
substring <- getLine
putStrLn "Occurrences:"
print(countSubstring substring ciphertext)
putStrLn ""
"5" -> do
putStrLn ""
putStrLn "Enter the letter(between ''):"
letter <- getLine
let letter_char = (read letter :: Char)
putStrLn "Occurrences:"
print(countAllNeighbours letter_char ciphertext)
putStrLn ""
"6" -> do
putStrLn ""
putStrLn "Enter the letter(between ''):"
letter <- getLine
let letter_char = (read letter :: Char)
putStrLn "Occurrences:"
print(countAllBefore letter_char ciphertext)
putStrLn ""
"7" -> do
putStrLn ""
putStrLn "Enter the letter(between ''):"
letter <- getLine
let letter_char = (read letter :: Char)
putStrLn "Occurrences:"
print(countAllAfter letter_char ciphertext)
putStrLn ""
"8" -> do
putStrLn ""
putStrLn "Enter the letter(between '') you wish to substitute:"
letter1 <- getLine
let letter1_char = (read letter1 :: Char)
putStrLn "Enter the letter(beween '') to substitute by:"
letter2 <- getLine
let letter2_char = (read letter2 :: Char)
new_ciphertext = substitute letter1_char letter2_char guess
putStrLn "New ciphertext:"
print(new_ciphertext)
tools ciphertext new_ciphertext
"r" -> main
"e" -> exitSuccess
otherwise -> do
putStrLn ""
putStrLn ("Please enter a valid option")
tools ciphertext guess
crack = do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "Enter the message:"
ciphertext <- getLine
tools ciphertext ciphertext
main = forever $ do
clearAll
putStrLn ""
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ":: /<span class="math-container">$$$$</span><span class="math-container">$$ /$$</span><span class="math-container">$$$$</span> /<span class="math-container">$$$$</span><span class="math-container">$$$$</span> ::"
putStrLn ":: /<span class="math-container">$$__ $$</span> /<span class="math-container">$$__ $$</span> |__ <span class="math-container">$$__/ ::"
putStrLn "::| $$</span> __/ /<span class="math-container">$$ /$$</span> | <span class="math-container">$$ __/ /$$</span> /<span class="math-container">$$| $$</span> ::"
putStrLn "::| <span class="math-container">$$ |__/|__/| $$</span> |__/|__/| <span class="math-container">$$ ::"
putStrLn "::| $$</span> | <span class="math-container">$$ | $$</span> ::"
putStrLn "::| <span class="math-container">$$ $$</span> /<span class="math-container">$$ /$$</span>| <span class="math-container">$$ $$</span> /<span class="math-container">$$ /$$</span>| <span class="math-container">$$ ::"
putStrLn "::| $$</span><span class="math-container">$$$$</span>/|__/|__/| <span class="math-container">$$$$</span><span class="math-container">$$/|__/|__/| $$</span> ::"
putStrLn ":: |______/ |______/ |__/ ::"
putStrLn "::::::::Classic Cryptography Toolbox:::::::::::::::::::::::::::::::::::::::::::::"
putStrLn ":: ::"
putStrLn "::What would you like to do? ::"
putStrLn ":: ::"
putStrLn "::1 - Encrypt a message ::"
putStrLn "::2 - Decrypt a message ::"
putStrLn "::3 - Cryptanalyse an encrypted message ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
putStrLn "::e - Exit ::"
putStrLn ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
input <- getLine
case input of
"1" -> encryption
"2" -> decryption
"3" -> crack
"e" -> exitSuccess
otherwise -> do
putStrLn ""
putStrLn ("Please enter a valid option")
main
</code></pre>
<p><strong>MyUtils.hs</strong></p>
<pre><code>module MyUtils where
import Data.Char
import Data.List
import System.Console.ANSI
import System.Random
--lowercase letter to int conversion
let2int :: Char -> Int
let2int c = ord c - ord 'a'
--int to lowercase letter conversion
int2let :: Int -> Char
int2let n = chr(ord 'a' + n)
--converts an entire string an array of ints (each char -> int)
text2ints :: String -> [Int]
text2ints xs = map (let2int) xs
--convrets an array of ints into a string (each int -> char)
ints2text :: [Int] -> String
ints2text xs = map (int2let) xs
--shifts the given lowercase letter n positions
shift :: Int -> Char -> Char
shift n c |isLower c = int2let((let2int c + n) `mod` 26)
|otherwise = c
--gets the factors of n
factors :: Int -> [Int]
factors n = [x |x<-[2..n], n`mod`x == 0]
--deletes all occurrences of an element within a list
deleteAll :: Eq a => a -> [a] -> [a]
deleteAll x s = filter (/=x) s
--gives a list of all the elements that have multiple occurrences within a list
equals :: Eq a => [a] -> [a]
equals [] = []
equals (x:xs)
|elem x xs = x : equals (deleteAll x xs)
|otherwise = equals xs
--gives a list of all the elements that are common to all the lists within a list of lists
commonElems :: Eq a => [[a]] -> [a]
commonElems l = equals [x | y<-l, x<-y, length (filter (elem x) l) == length l]
--gives a list of all the factors in common to all the integers in a list
commonFactors :: [Int] -> [Int]
commonFactors xs
|length xs == 1 = factors (head (xs))
|otherwise = commonElems [factors x | x<-xs]
--gives a list of the indexes of each occurrence of a substring within a string
matchIndices :: (Eq a, Num b, Enum b) => [a] -> [a] -> [b]
matchIndices needle = map fst . filter (isPrefixOf needle . snd) . zip [0..] . tails
--gives a list of the lengths between each consecutive occurrences of a substring within a string
spaceBetween :: String -> String -> [Int]
spaceBetween needle = diffs . matchIndices needle -- calculates the difference between each consecutive index
where diffs xs = zipWith (flip(-)) xs (tail xs)
--count the space between the first occurrence of a subtring and the next occurrence within a string
repeatSpacing :: String -> String -> Int
repeatSpacing substring ciphertext
|spaceBetween substring ciphertext == [] = 0
|otherwise = head (spaceBetween (substring) (ciphertext))
--gives a list of the lengths between the first occurrence of multiple substrings and the next respective occurrence
multRepeatSpacing :: [String] -> String -> [Int]
multRepeatSpacing substrings ciphertext = [y | x<-substrings, y<-[repeatSpacing x ciphertext]]
--gets all chars n chars away from each other
getSpacedLetters :: Int -> String -> String
getSpacedLetters n (x:xs)
|n > length xs = [x]
|otherwise = x : getSpacedLetters n (drop (n-1) xs)
--gets all chars "size" chars away from each other starting from the nth position
getNthSpacedLetters :: Int -> Int -> String -> String
getNthSpacedLetters size n s
|n > length s = ""
|otherwise = getSpacedLetters size (drop (n-1) s)
--removes all tuples with x as fst
removeAllTuplesByInt :: Int -> [(a,Int)] -> [(a,Int)]
removeAllTuplesByInt x [] = []
removeAllTuplesByInt x list
|snd (head list) /= x = head list : removeAllTuplesByInt x (tail list)
|otherwise = removeAllTuplesByInt x (tail list)
--gets the index of a char in a dictionary of type [(Char,Integer)]
getDictIndex :: Eq a => a -> [(a,Integer)] -> Integer
getDictIndex c [key]
|c == fst key = snd key
|otherwise = error "no such element"
getDictIndex c dict
|c == fst (head dict) = snd (head dict)
|otherwise = getDictIndex c (tail dict)
--gives a list of the elements in a list withou repeating them
delRepeated :: Eq a => [a] -> [a]
delRepeated [] = []
delRepeated list = x : delRepeated (deleteAll x (tail list))
where x = head list
--clears the terminal and sets the cursor position to 0 0
clearAll :: IO()
clearAll = do
clearScreen
setCursorPosition 0 0
--converts something of type a into the corresponding value of type b in a dictionary of the type [(b,a)]
convertTo :: Eq a => a -> [(b,a)]-> b
convertTo x [] = error ("int not found in the dict")
convertTo x dict
|x == (snd (head dict)) = fst (head dict)
|otherwise = convertTo x (tail dict)
convertFrom :: Eq a => a -> [(a,b)] -> b
convertFrom x [] = error ("not found in the dict")
convertFrom x dict
|x == (fst (head dict)) = snd (head dict)
|otherwise = convertFrom x (tail dict)
--converts an entire list into the corresponding dictionary values
toDictValue :: Eq a => [a] -> [(b,a)] -> [b]
toDictValue ns dict = map (\x -> convertTo x dict) ns
--generates a list of different random integers from n1 to n2 of size n2
genRandNrs :: Integer -> Integer -> IO([Integer])
genRandNrs n1 n2 = do
g <- newStdGen
return (take (fromIntegral n2) (nub (randomRs (n1,n2) g :: [Integer])))
--groups the given list in a list of lists in, n by n
groupN:: Int -> [a] -> [[a]]
groupN 0 _ = []
groupN size [] = []
groupN size s = (take (size) s) : groupN size (drop size s)
</code></pre>
<p><strong>Cryptanalysis.hs</strong></p>
<pre><code>module Codebreaking.Cryptanalysis where
import Data.Char
import Data.List
import Data.Function
import MyUtils
alphabet = "abcdefghijklmnopqrstuvwxyz"
--most to least frequent letters in english with respective index
etaoin = zip "etaoinshrdlcumwfgypbvkjxqz" [1..]
en_letter_most_freq = "etaoin" --most frequent english letters
en_letter_least_freq = "vkjxqz" --least frequent english letters
--counts the number of ocurrences of a char in a string
count :: Char -> String -> Int
count a [x]
|a == x = 1
|otherwise = 0
count a (x:xs)
|a == x = 1 + count a xs
|otherwise = count a xs
--counts the numbers of ocurrences of a string in another string
countSubstring :: String -> String -> Int
countSubstring s1 s2
|length s1 > length s2 = 0
|take (length s1) s2 == s1 = 1 + countSubstring s1 (drop 1 s2)
|otherwise = countSubstring s1 (drop 1 s2)
--given a number m and a string, finds all the substrings with size n that have multiple occurrences on the given string
repeatedSubsBySize :: Int -> String -> [String]
repeatedSubsBySize n [] = []
repeatedSubsBySize n s
|countSubstring (take n s) s > 1 = (take n s) : repeatedSubsBySize n (drop 1 s)
|otherwise = repeatedSubsBySize n (drop 1 s)
--finds all the substrings with sizes between n1 and n2 that have multiple occurrences on the given string
repeatedSubs :: Int -> Int -> String -> [String]
repeatedSubs n1 n2 [] = []
repeatedSubs n1 n2 s = [sub | n<-[n1..n2], sub<-repeatedSubsBySize n s]
--counts the number of ocurrences of each letter of the alphabet in a string
countAlphabet :: String -> [(Char, Int)]
countAlphabet s = [(letter,occurs) | letter<-alphabet, occurs<-[count letter s]]
--outputs the result of count alphabet from the most frequent letter to the least
sortAlphabetCount :: String -> [(Char, Int)]
sortAlphabetCount s = reverse (sortOn (snd) (countAlphabet s))
--substitutes all occurrences of c1 by c2 on the given string
substitute :: Char -> Char -> String -> String
substitute c1 c2 [] = []
substitute c1 c2 (x:xs)
|c1 == x = toUpper c2 : substitute c1 c2 xs
|otherwise = x : substitute c1 c2 xs
--counts the occurrences of c1 immediately before c2
countBefore :: Char -> Char -> String -> Int
countBefore c1 c2 [x] = 0
countBefore c1 c2 (x:xs)
|head xs == c2 && x == c1 = 1 + countBefore c1 c2 xs
|otherwise = 0 + countBefore c1 c2 xs
--counts the occurrences of c1 immediately after c2
countAfter :: Char -> Char -> String -> Int
countAfter c1 c2 [x] = 0
countAfter c1 c2 (x:xs)
|x == c2 && head xs == c1 = 1 + countAfter c1 c2 xs
|otherwise = 0 + countAfter c1 c2 xs
-- counts the ocurrences of c1 immediately before or after c2
countNeighbours :: Char -> Char -> String -> Int
countNeighbours c1 c2 s = (countBefore c1 c2 s) + (countAfter c1 c2 s)
--counts the occurrences of c immediately before or after every letter of the alphabet
countAllNeighbours :: Char -> String -> [(Char, Int)]
countAllNeighbours c s = [(letter, occurs) | letter<-alphabet, occurs<-[countNeighbours c letter s]]
--counts the occurrences of c immediately before every letter of the alphabet
countAllBefore :: Char -> String -> [(Char, Int)]
countAllBefore c s = [(letter, occurs) | letter<-alphabet, occurs<-[countBefore c letter s]]
--counts the occurrences of c immediately after every letter of the alphabet
countAllAfter :: Char -> String -> [(Char, Int)]
countAllAfter c s = [(letter, occurs) | letter<-alphabet, occurs<-[countAfter c letter s]]
--attributes a letter frequency score to the first 6 letters in a string
matchFreqScoreFirst :: String -> Int
matchFreqScoreFirst [] = 0
matchFreqScoreFirst s
|elem (head sorted_first) en_letter_most_freq = 1 + matchFreqScoreFirst (drop 1 sorted_first)
|otherwise = 0 + matchFreqScoreFirst (drop 1 sorted_first)
where sorted_first = take 6 s
--attributes a letter frequency score to the last 6 letters in a string
matchFreqScoreLast :: String -> Int
matchFreqScoreLast [] = 0
matchFreqScoreLast s
|elem (head sorted_last) en_letter_least_freq = 1 + matchFreqScoreLast (drop 1 sorted_last)
|otherwise = 0 + matchFreqScoreLast (drop 1 sorted_last)
where sorted_last = take 6 (reverse s)
--sorts the strings in the tuple in reverse ETAOIN order
reverseEtaoinSortFreqs :: [(Int, String)] -> [(Int, String)]
reverseEtaoinSortFreqs [] = []
reverseEtaoinSortFreqs [x]
|length (snd x) > 1 = [(fst x, reverseEtaoinSort (snd x))]
|otherwise = [x]
reverseEtaoinSortFreqs (x:xs)
|length (snd x) > 1 = (fst x, reverseEtaoinSort (snd x)) : reverseEtaoinSortFreqs xs
|otherwise = x : reverseEtaoinSortFreqs xs
--gives a list of frequencies and the respective group of letters
sortFreqToLetters :: String -> [(Int, String)]
sortFreqToLetters s = reverseEtaoinSortFreqs [(snd (head gr), map fst gr) | gr <- groupBy ((==) `on` snd) (sorted_freqs)]
where
sorted_freqs = (sortAlphabetCount s)
--inserts a letter in a "reverse_etaoin" ordered string keeping its order
reverseEtaoinInsert :: Char -> String -> String
reverseEtaoinInsert c [] = [c]
reverseEtaoinInsert c (x:xs)
|(getDictIndex c etaoin) > (getDictIndex x etaoin) = c : x : xs
|otherwise = x : reverseEtaoinInsert c xs
--sorts a string in reverse ETAOIN order
reverseEtaoinSort :: String -> String
reverseEtaoinSort [] = []
reverseEtaoinSort (x:xs) = reverseEtaoinInsert x (reverseEtaoinSort xs)
--gives the 2 highest ints in lust of (Char,Int)
getHighestFreqScores :: [(Char,Int)] -> [Int]
getHighestFreqScores scores = [maximum (map (snd) scores),maximum (map (snd) rest)]
where rest = removeAllTuplesByInt (maximum (map (snd) scores)) scores
--outputs the letters corresponding to the given highest freq scores
getHighestLetters :: [Int] -> [(Char,Int)] -> String
getHighestLetters highest_scores [] = []
getHighestLetters highest_scores scores
|elem (snd (head scores)) highest_scores = fst (head scores) : getHighestLetters highest_scores (tail scores)
|otherwise = getHighestLetters highest_scores (tail scores)
--given a reverse_etaoin sorted string, attributes a frequency match score
matchFreqScore :: String -> Int
matchFreqScore s = matchFreqScoreFirst s + matchFreqScoreLast s
--gets the reverse etaoin sorted string of a string
sortedEtaoinString :: String -> String
sortedEtaoinString x = concat (map (snd) (init (sortFreqToLetters x)))
</code></pre>
<p><strong>Caesar.hs</strong></p>
<pre><code>module Ciphers.Caesar where
import MyUtils
import Data.Char
--encrypts(n) or decrypts(-n)
caesarShift :: Int -> String -> String
caesarShift n xs = [shift n x | x <- map (toLower) xs]
--given a string, shifts it 26 times and generates a list with all of the shifted strings
--one of the elements might mean something
breakCaesar :: String -> [String]
breakCaesar xs = [s | n<-[(0)..(25)], s<- [caesarShift (-n) (map (toLower) xs)]]
</code></pre>
<p><strong>Vigenere.hs</strong></p>
<pre><code>module Ciphers.Vigenere where
import MyUtils
import Data.Char
--encrypts the plaintext with the given key
vigenereEncrypt :: String -> String -> String
vigenereEncrypt key plaintext = ints2text result
where result = map (`mod` 26) (zipWith (+) keyCycle intPlainText)
keyCycle = (cycle(text2ints key))
intPlainText = text2ints (map (toLower) (filter (isAlphaNum) plaintext))
--decrypts the ciphertext with the given key
vigenereDecrypt :: String -> String -> String
vigenereDecrypt key ciphertext = ints2text result
where result = map (`mod` 26) (zipWith (-) intciphertext keyCycle)
keyCycle = (cycle(text2ints key))
intciphertext = text2ints (map (toLower)(filter (isAlphaNum) ciphertext))
</code></pre>
<p><strong>ADFGVX.hs</strong></p>
<pre><code>module Ciphers.ADFGVX where
import Control.Monad
import System.Directory
import Data.List
import Data.Char
import Data.Maybe
import MyUtils
grid = sequence ["adfgvx","adfgvx"]
alpha_nums = zip ['a'..'z'] [1..] ++ zip ['0'..'9'] [27..]
--creates a file with a random substitution key
createSubstitutionKey :: IO()
createSubstitutionKey = do
let filename = "my_grid.txt"
fileExists <- doesFileExist (filename)
when fileExists (removeFile filename)
rands <- genRandNrs 1 36--random list of alpha_nums indexes
writeFile filename (toDictValue rands alpha_nums)
--fills the ADFGVX grid with the given string
fillGrid :: String -> [(String,Char)]
fillGrid s = zip grid s
--substitutes all chars in a string for their respecive value in the ADFGVX grid
substitutionStep :: String -> [(String,Char)] -> String
substitutionStep plaintext filled_grid = concat (toDictValue plaintext filled_grid)
--attributes each letter in the ciphertext to each letter of the key in a cyclic fashion
--if the the ciphertext leaves blank spaces on the gird, fills it with encrypted 'a's
createKeyGrid :: String -> String -> [(Char,Char)]
createKeyGrid key ciphertext = zip (cycle key) fit_ciphertext
where fit_ciphertext = if length (ciphertext) `mod` length (key) == 0 then ciphertext else ciphertext ++ replicate (rest) 'a'
rest = length key - length (ciphertext) `mod` length (key)
--sorts the key grid columns in alphabetical order
sortKeyGrid :: String -> [(Char,Char)] -> [(Char,Char)]
sortKeyGrid key [] = []
sortKeyGrid key keygrid = sortOn (fst) (take (length key) keygrid) ++ (sortKeyGrid key (drop (length key) keygrid))
--ouputs the key grid with the columns as lines
groupByCols :: Eq a => [(a,b)] -> [(a,b)]
groupByCols [] = []
groupByCols [x] = [x]
groupByCols (x:xs) = [x] ++ (filter (\t -> fst(t) == fst(x)) xs) ++ groupByCols (filter (\t2 -> fst(t2) /= fst(x)) xs)
--gives the elements of the key grid as a string
transpositionStep :: String -> [(Char,Char)] -> String
transpositionStep key keygrid = map (snd) (groupByCols sorted_keygrid)
where sorted_keygrid = sortKeyGrid key keygrid
--given a key, sorts the key and fills the grid the same way it was on the encryption process
recreateKeyGrid :: String -> String -> [(Char,String)]
recreateKeyGrid key ciphertext = zip (sorted_key) (groupN nrows ciphertext)
where nrows = cipher_text_size `div` key_size
sorted_key = sort key
cipher_text_size = length ciphertext
key_size = length key
--sorts the columns of the grid by the order of the password
unSortKeyGrid :: String -> [(Char,String)] -> [(Char,String)]
unSortKeyGrid key [] = []
unSortKeyGrid key keygrid = found : unSortKeyGrid (drop 1 key) (delete found keygrid)
where found = fromJust (find (\x -> fst(x) == head key) keygrid)
--get the untransposed text from the unsorted grid
getPreCipherText :: [(Char,String)] -> [String]
getPreCipherText keygrid = groupN 2 [s | n<-[1..nrows], s<-getNthSpacedLetters (nrows) n gridstring]--(map (head) (map (snd) keygrid)) ++ getPreCipherText (map (tail) (map (snd) keygrid))
where gridstring = concat (map (snd) keygrid)
nrows = length (snd (head keygrid))
--converts the untransposed text into plaintext
getPlainText :: [String] -> [(String,Char)] -> String
getPlainText preciphertext adfgvxgrid = map (\x -> convertFrom x adfgvxgrid) preciphertext
--encryption algorithm
adfgvxEncrypt :: String -> String -> String -> String
adfgvxEncrypt substitution_key key plaintext = transpositionStep key keygrid
where keygrid = createKeyGrid key ciphertext1
ciphertext1 = substitutionStep (filter (isAlphaNum) (map (toLower) plaintext)) my_grid
my_grid = fillGrid substitution_key
--decryption algorithm
adfgvxDecrypt :: String -> String -> String -> String
adfgvxDecrypt substitution_key key ciphertext = getPlainText preciphertext my_grid
where my_grid = fillGrid substitution_key
preciphertext = getPreCipherText (unSortKeyGrid key keygrid)
keygrid = recreateKeyGrid key ciphertext
</code></pre>
<p><strong>VigenereCrack.hs</strong></p>
<pre><code>module Codebreaking.VigenereCrack where
import Ciphers.Caesar
import Ciphers.Vigenere
import Codebreaking.Cryptanalysis
import MyUtils
import Control.Monad
import System.Exit
import System.Console.ANSI
import Control.Concurrent
import Data.Function
--given two numbers representing the min and max size of the substrings that may repeat along the ciphertext and the ciphertext gives a list of all the possible lengths of the vigenere key
guessKeyLength :: Int -> Int -> String -> [Int]
guessKeyLength n1 n2 ciphertext = commonFactors (multRepeatSpacing (repeatedSubs n1 n2 ciphertext) ciphertext)
--given a list of possible keysizes and the ciphertext, splits the ciphertext into subkey parts for each possible keysize
groupBySubkeys :: [Int] -> String -> [(Int,String)]
groupBySubkeys sizes ciphertext = [(keysize,x) | keysize<-sizes, n<-[1..keysize], x<-[getNthSpacedLetters keysize n ciphertext]]
--attributes a frequency score to each caesar shift of the string
subkeyScores :: String -> [(Char,Int)]
subkeyScores s = zip alphabet [matchFreqScore shifted | shifted <- map (sortedEtaoinString) (breakCaesar s)]
--filters the most likely subkeys out of the string
filterSubkey :: (Int,String) -> (Int,String)
filterSubkey subkey_group = (keysize, candidates)
where keysize = fst subkey_group
string = snd subkey_group
candidates = getHighestLetters (getHighestFreqScores (subkeyScores (string))) (subkeyScores (string))
--outputs the possible subkeys for each position of each possible key size
possibleSubkeys :: [(Int,String)] -> [(Int,String)]
possibleSubkeys subkey_groups = map (filterSubkey) subkey_groups
--given a keysize, ouputs the components of the key
getKeysizeGroup :: Int -> [(Int,String)] -> [(Int,String)]
getKeysizeGroup x group = filter (\i -> fst i == x) group
--given a list of possible subkeys and the respective keysize, gives a list of all the keys for all the possible keysizes
possibleKeys :: [(Int,String)] -> [String]
possibleKeys subkeys = [ key | keysize <- keysizes, key<-keys keysize]
where keysizes = delRepeated (map (fst) subkeys)
keys x = sequence (map (snd) (getKeysizeGroup x subkeys))
--tries all the keys
bruteForceKeys :: [String] -> String -> IO()
bruteForceKeys [] ciphertext = putStrLn "\nDone"
bruteForceKeys keys ciphertext = do
let key = head keys
putStrLn ""
putStrLn ("Attempting with key: " ++ key ++ " :")
threadDelay 500000
print(vigenereDecrypt key ciphertext)
bruteForceKeys (drop 1 keys) ciphertext
--kasiski Algorithm
--user interaction
crackVigenere :: String -> IO()
crackVigenere ciphertext = do
putStrLn "Enter min size of repeated words:"
readMin <- getLine
putStrLn "Enter max size of repeated words:"
readMax <- getLine
let minsize = (read readMin :: Int)
maxsize = (read readMax :: Int)
let key_lengths = guessKeyLength minsize maxsize ciphertext
--putStrLn "Possible key lengths:"
clearAll
putStrLn "Possible keys:"
putStrLn "Calculating possible key lengths..."
--print (key_lengths)
let subkey_groups = groupBySubkeys key_lengths ciphertext
--putStrLn "Subkey groups for each possible key size:"
--print (subkey_groups)
let subkeys = possibleSubkeys subkey_groups
--putStrLn "Possible subkeys:"
--print (subkeys)
let keys = possibleKeys subkeys
print (keys)
forever $ do
putStrLn "1 - Try a key"
putStrLn "2 - Brute-force attack"
putStrLn "r - Retry"
putStrLn "e - Exit"
input <- getLine
case input of
"1" -> do
key <- getLine
let plaintext = vigenereDecrypt key ciphertext
print (plaintext)
"2" -> bruteForceKeys keys ciphertext
"r" -> crackVigenere ciphertext
"e" -> exitSuccess
otherwise -> do
putStrLn "Please enter a valid option."
exitFailure
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>Some quick initial comments - will edit as I move. For your cct.hs file you probably want to put different prompt lines into a list and map a print over that list for example:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Control.Monad\n\nmainMenuText = [\"Line 1\",\n \"Line 2\",\n \"Line 3\",\n ...]\n\nmain = mapM_ putStrLn mainMenuText\n</code></pre>\n\n<p>Or use QuasiQuuotes</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE QuasiQuotes #-}\nimport Data.String.QQ\n\nmain = putStrLn [s|\nLine 1\nLine 2\nLine 3|]\n</code></pre>\n\n<p>Or use multiline strings:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>main = putStrLn \"Line 1 \\n \\\n \\ Line 2 \\n \\\n \\ Line 3\"\n</code></pre>\n\n<p>You may also want to an enum for each case statement menu so if need be you can pass around the value and it makes sense everywhere. In your case <code>\"1\"</code> being encryption is lost fairly early. I suggest adding a data type for the command:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data Command = ENCRYPTION | DECRYPTION | ...\n</code></pre>\n\n<p>So that you have one function to do both encryption and decryption: </p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>type Message = String\ntype Shift = Int\n\ncaesarCipher :: Command -> Message -> Shift -> String \n</code></pre>\n\n<p>Or something of that nature. It'll make the interface cleaner.</p>\n\n<p>Also be consistent in your use of camelCase.</p>\n\n<p>This is a lot of code but lemme get to the parts which I think are worth addressing.</p>\n\n<p>The <code>commonElems</code> function seems grossly inefficient. Checking that each item appears in every list by doing a length check then removing duplicates seems confusing. I think the simpler algorithm would be to take the unions of the running intersections.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\n\ncommonElems xs = foldr intersect intialElement xs\n where initialElement = if (null xs) then [] else (head xs) \n</code></pre>\n\n<p><code>matchIndices</code> would look better with explicit recursion.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>matchIndices needle haystack = go needle haystack 0\n where go _ [] _ = []\n go n (x:xs)@h i = if n `isPrefixOf` h then i : (go n xs (i + 1)) else (go n xs (i + 1))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:39:52.727",
"Id": "423500",
"Score": "0",
"body": "thank you very much for going through my code and for your suggestions! i will apply those"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T09:22:02.027",
"Id": "423701",
"Score": "0",
"body": "On having encrypt/decrypt in a single function: I agree with the sentiment of making the interface cleaner, but I object to the method. [Functions should do one thing](https://softwareengineering.stackexchange.com/a/137957/129674), as adviced by Robert C. Martin's Clean Code. What you can do instead is have common interfaces to different modules, e.g. `Ciphers.Caesar.(encrypt, decrypt, crack)`, `Ciphers.Vigenere.(encrypt, decrypt, crack)` and let them have common type signatures, to the extent that it's possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:31:46.863",
"Id": "219258",
"ParentId": "219208",
"Score": "1"
}
},
{
"body": "<p>I'd also maybe suggest making helper functions for pretty printing to the terminal.</p>\n\n<pre><code>screenLength :: Int\nscreenLength = 82\n\ncolons :: Int -> String\ncolons = flip replicate ':'\n\nprintFill :: IO ()\nprintFill = putStrLn $ colons screenLength\n\nprintFillT :: String -> IO ()\nprintFillT s = do\n putStrLn $ begin ++ fillSpace ++ end\n when (not $ null rest) $ printFillT rest\n where (fstStr, rest) = splitAt (screenLength - 6) s\n begin = \":: \" ++ fstStr\n end = \"::\"\n fillSpace = replicate (screenlength - length begin - length end) ' '\n\nprintTitle :: String -> IO ()\nprintTitle s = putStrLn $ begin ++ s ++ end\n where begin = colons 8\n end = colons $ screenLength - length begin - length s\n</code></pre>\n\n<p>This way, your main functions will look a lot cleaner, and they're reusable everywhere, so there's less <code>putStrLn</code>s filling the code:</p>\n\n<pre><code>logo :: [String]\nlogo =\n [ \" /<span class=\"math-container\">$$$$</span><span class=\"math-container\">$$ /$$</span><span class=\"math-container\">$$$$</span> /<span class=\"math-container\">$$$$</span><span class=\"math-container\">$$$$</span>\"\n , \" /<span class=\"math-container\">$$__ $$</span> /<span class=\"math-container\">$$__ $$</span> |__ <span class=\"math-container\">$$__/\"\n , \"| $$</span> __/ /<span class=\"math-container\">$$ /$$</span> | <span class=\"math-container\">$$ __/ /$$</span> /<span class=\"math-container\">$$| $$</span>\"\n , \"| <span class=\"math-container\">$$ |__/|__/| $$</span> |__/|__/| <span class=\"math-container\">$$\"\n , \"| $$</span> | <span class=\"math-container\">$$ | $$</span>\"\n , \"| <span class=\"math-container\">$$ $$</span> /<span class=\"math-container\">$$ /$$</span>| <span class=\"math-container\">$$ $$</span> /<span class=\"math-container\">$$ /$$</span>| <span class=\"math-container\">$$\"\n , \"| $$</span><span class=\"math-container\">$$$$</span>/|__/|__/| <span class=\"math-container\">$$$$</span><span class=\"math-container\">$$/|__/|__/| $$</span>\"\n , \" \\______/ \\______/ |__/\"\n ]\n\nprintMenu :: IO ()\nprintMenu = do\n putStrLn \"\"\n printFill\n mapM_ printFillT logo\n printTitle \"Classic Cryptography Toolbox\n mapM_ printFillT menu\n printFill\n printFillT \"e - Exit\"\n printFill\n where menu =\n [ \"\"\n , \"What would you like to do?\"\n , \"\"\n , \"1 - Encrypt a message\"\n , \"2 - Decrypt a message\"\n , \"3 - Cryptanalyse an encrypted message\"\n , \"\"\n ]\n\n\nmain = forever $ do\n clearAll\n printMenu\n input <- getLine\n case input of\n \"1\" -> encryption\n \"2\" -> decryption\n \"3\" -> crack\n \"e\" -> exitSuccess\n otherwise -> do\n putStrLn \"\"\n putStrLn $ \"Please enter a valid option\"\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:10:23.960",
"Id": "423568",
"Score": "0",
"body": "thanks for the suggestion. yeah i thought so. i'm currently working on a very simple CLI framework to aid me on this project and also in future ones"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T22:20:59.773",
"Id": "219279",
"ParentId": "219208",
"Score": "2"
}
},
{
"body": "<p>First some comments related to your module structure:</p>\n\n<ul>\n<li><p>You may want to mirror the module structure of the <a href=\"https://hackage.haskell.org/package/cryptonite\" rel=\"nofollow noreferrer\">cryptonite</a> and <a href=\"https://hackage.haskell.org/package/crypto-api\" rel=\"nofollow noreferrer\">crypto-api</a> packages, which are the most popular cryptography packages on Hackage; <code>Crypto.Cipher.Caesar</code>, <code>Crypto.Cipher.Vigenere</code>, etc.</p></li>\n<li><p>You may want to place the Vigenere crack implementation in <code>Crypto.Cipher.Vigenere.Crack</code>, call the method <code>crack</code> rather than <code>crackVigenere</code> (since the cipher is implied by the module), and only export <code>crack</code>:</p>\n\n<pre><code>module Crypto.Cipher.Vigenere.Crack ( crack\n ) where\n\n...\n</code></pre>\n\n<p>as this provides a clean interface to the algorithm.</p>\n\n<p>If, for some reason, you wish to export the internal functions (such that they may be used by other modules), a common thing to do is to place the actual implementation in a module called <code>Crypto.Cipher.Vigenere.Crack.Impl</code>, and in the module <code>Crypto.Cipher.Vigenere.Crack</code> import this <code>Impl</code> but only export the public interface. This means that users of your library will know that <code>Impl</code> might change and should be referred to at their own risk, whereas <code>Crack</code> has a stable interface.</p></li>\n<li><p>If you import these modules using <code>qualified</code>, you don't need to prefix each combinator as <code>caesarEncrypt</code>, <code>vigenereEncrypt</code>, etc. You can instead write e.g.</p>\n\n<pre><code>import qualified Crypto.Cipher.Caesar as Caesar\nimport qualified Crypto.Cipher.Vigenere as Vigenere\n\n... Caesar.encrypt ...\n... Vigenere.decrypt ...\n</code></pre></li>\n<li><p>Give your modules a common interface, so it's <code>Caesar.encrypt</code>, <code>Caesar.decrypt</code>, <code>Vigenere.encrypt</code>, <code>Vigenere.decrypt</code>, and finally <code>break</code> or <code>crack</code> in the corresponding implementations, whichever you choose.</p></li>\n<li><p>In the ADFGVX module in particular, and also in general, consider placing the high-level definitions / the definitions you aim to explicitly export, such as <code>encrypt</code> and <code>decrypt</code>, first in the file and all its helper definitions below. This provides more clarity when reading the code.</p></li>\n<li><p>The <code>Codebreaking.Cryptanalysis</code> module is only used in the Vigenere cipher, so perhaps name this accordingly as e.g. <code>Crypto.Cipher.Vigenere.Analysis</code> to clarify what its use is.</p></li>\n<li><p>Since the cryptonite package already has a module <code>Crypto.Cipher.Utils</code>, adding your <code>MyUtils</code> under this name may conflict with use-cases where you wish to use both packages simultaneously.</p></li>\n</ul>\n\n<p>Secondly some low-level comments related to your syntax and helper functions:</p>\n\n<ul>\n<li><p>As Michael Chav suggested, you may want to use quasi quotation on your longer strings. As an additional suggestion, you may want to consider the module <a href=\"https://hackage.haskell.org/package/file-embed\" rel=\"nofollow noreferrer\"><code>Data.FileEmbed</code></a> to move your very long formattable strings to a separate file:</p>\n\n<pre><code>import Data.FileEmbed (embedStringFile)\n\nsomeVeryLongStringWithWhitespaceFormatting :: String\nsomeVeryLongStringWithWhitespaceFormatting = $(embedStringFile \"path/to/foo.txt\")\n</code></pre></li>\n<li><p>But for your terminal user-interface, you may want to use a library for building this; there are quite a lot out there, and I can only personally recommend <a href=\"https://hackage.haskell.org/package/brick\" rel=\"nofollow noreferrer\">brick</a>, but there are also byline, cli, haskeline, HCL and structured-cli.</p>\n\n<p>Depending on whether you choose one of these or not, cct.hs could see some refactoring on its own that warrants its own code review, I think. Mainly there's a lot of UI-related code duplication and some separation of displaying the UI and reacting to input that could be separated. E.g. <a href=\"https://en.wikipedia.org/wiki/Functional_reactive_programming\" rel=\"nofollow noreferrer\">FRP</a> with Brick would enforce that.</p></li>\n<li><p>Consider using HLint as it will provide you with a lot of helpful warnings about redundant parentheses and formatting; I won't comment on these, but there's for example quite a lot of parentheses that are not necessary and do not improve reading (one case is <code>map (toLower) xs</code>).</p></li>\n<li><p>I assume the intent with MyUtils is to extract the most generic helper functions you've used. But it seems to me that a lot of these are dead (no longer used) or only used in one cipher. I understand that some of these helper functions are used by other helper functions inside MyUtils.</p>\n\n<p>And finally, perhaps, generic functions used in multiple ciphers?</p>\n\n<p>I'd recommend not extracting things to a common place until you need them in two places, and not export functions that are not expected to be used outside of a library. There's a principle to back this up somewhere, but I can only think of <a href=\"http://wiki.c2.com/?PrematureGeneralization\" rel=\"nofollow noreferrer\">premature generalization</a> right now.</p>\n\n<p>If this completely eradicates MyUtils, that's good.</p>\n\n<p>Notice that <a href=\"https://hackage.haskell.org/package/cryptonite-0.25/docs/Crypto-Cipher-Utils.html\" rel=\"nofollow noreferrer\">cryptonite's <code>Crypto.Cipher.Utils</code></a> only has a single definition.</p></li>\n<li><p>As another point of comparison with the cryptonite package, you'll notice that it works on <code>Data.ByteArray</code>. Since your ciphers are not binary but letter-based, this is not really appropriate, but have you considered <code>Data.Text</code> for more efficient representation of strings? See the <a href=\"https://haskell.fpcomplete.com/tutorial/string-types\" rel=\"nofollow noreferrer\">String Types</a> tutorial by FPComplete for an intro.</p></li>\n<li><p>Avoid a mixture of <code>CamelCase</code> and <code>snake_case</code>. You have both <code>adfgvxEncryption</code> and <code>caesar_decryption</code>.</p></li>\n<li><p>You don't want as complex machinery as in <a href=\"https://hackage.haskell.org/package/cryptonite-0.25/docs/Crypto-Cipher-Types.html#t:Cipher\" rel=\"nofollow noreferrer\"><code>Crypto.Cipher.Types</code></a>, but you may want to create some type aliases to convey the meaning behind the many <code>String</code> and <code>Int</code> arguments.</p>\n\n<p>E.g. instead of</p>\n\n<pre><code>caesarShift :: Int -> String -> String\ncaesarShift n xs = [shift n x | x <- map (toLower) xs]\n\n...\n\nvigenereEncrypt :: String -> String -> String\nvigenereEncrypt key plaintext = ...\n</code></pre>\n\n<p>you can have</p>\n\n<pre><code>type CaesarKey = Int\n\nencrypt :: CaesarKey -> String -> String\nencrypt key plaintext = map (shift key . toLower) plaintext\n\n...\n\ntype VigenereKey = String\n\nencrypt :: VigenereKey -> String -> String\nencrypt key plaintext = ...\n</code></pre></li>\n<li><p>The <code>vigenereEncrypt</code> function is nicely written in the sense of its use of combinators, so you're using Haskell's standard library quite well. Stylistically I might prefer to rewrite</p>\n\n<pre><code>vigenereEncrypt :: String -> String -> String\nvigenereEncrypt key plaintext = ints2text result\n where result = map (`mod` 26) (zipWith (+) keyCycle intPlainText)\n keyCycle = (cycle(text2ints key))\n intPlainText = text2ints (map (toLower) (filter (isAlphaNum) plaintext))\n</code></pre>\n\n<p>into</p>\n\n<pre><code>encrypt :: VigenereKey -> String -> String\nencrypt key plaintext = ints2text . encrypt' . text2ints $ plaintext'\n where\n encrypt' = map (`mod` 26) . zipWith (+) (cycle key')\n plaintext' = map toLower (filter isAlphaNum plaintext)\n key' = text2ints key\n</code></pre>\n\n<p>although I'm still a little unsatisfied with the name and use of <code>text2ints</code> and <code>ints2text</code>.</p></li>\n</ul>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:33:44.130",
"Id": "423744",
"Score": "0",
"body": "Thanks! Most detailed comment so far. I really appreciate it. I'm currently cleaning the CLI part (from 300 lines to 120) and i will deal with the modulation next, then the types and finally some efficiency tweaks before proceding to tune the logic itself. Do you think this is a good way to go?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T07:41:36.353",
"Id": "423837",
"Score": "0",
"body": "@GuilhermeLima: Sure, that sounds like a good plan."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:15:02.190",
"Id": "219365",
"ParentId": "219208",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219365",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T20:09:15.517",
"Id": "219208",
"Score": "4",
"Tags": [
"haskell",
"caesar-cipher",
"vigenere-cipher"
],
"Title": "Classic cryptography toolbox: Caesar, Vigenere and ADFGVX ciphers"
} | 219208 |
<p>Apart from PEP8 issues which I will eventually get my head around, what do you think of my update to the 3 jugs jug problem (which now works for n number of jugs)</p>
<blockquote>
<p>For jugs size A, B and C find the minimum number of steps to reach D, where D < max (A,B,C)</p>
</blockquote>
<p>Original code: <a href="https://codereview.stackexchange.com/questions/219033/jug-problem-3-jugs/219072#219072">Jug problem - 3 jugs</a></p>
<pre><code>from math import factorial
global list_previous_jug_states
list_previous_jug_states = []
global list_running_count
list_running_count = []
global list_running_index
list_running_index = []
global list_volumes
list_volumes = []
global list_jug_max
list_jug_max = []
class CreateJugs:
#Create a new jug instance
def __init__ (self,jug_name,jug_max):
self.name = jug_name
self.max = jug_max
list_jug_max.append(self)
@property
def jug_max (self):
return self.max
def set_fill_states (number_jugs, jug_max):
#Create a list of binary starting states (e.g: 0,0,0,0....1,1,1,0 where 1 = MAX and 0 = empty)
global list_binary_states
list_binary_states = []
for i in range (1<<number_jugs):
binary_state =bin(i)[2:]
binary_state ='0'*(number_jugs-len(binary_state))+binary_state
list_binary_states.append(binary_state)
list_binary_states = list_binary_states[0:len(list_binary_states)-1]
#Create lists to hold previous states, running count for each jug, running index of previous positions
#Running count: if start position is (binary): 1,1,0 that = 2
#Running count: start 0,0,1 = 1
#Sort list by number of 1s
new_list = []
for x in range (number_jugs):
for item in list_binary_states:
if item.count('1') == x:
new_list.append(item)
list_running_count.append(x)
#Copy list back to origina function
list_binary_states = new_list[:]
#Now print all possible starting oreintations
for n in range (len(list_binary_states)):
jug_binary_state = list_binary_states[int(n)]
jug_state = []
for x in range (number_jugs):
if int(jug_binary_state[x]) == 1:
jug_state.append(list_jug_max[x].max)
else:
jug_state.append (0)
list_previous_jug_states.append(jug_state)
list_running_index.append([n])
def make_moves (jug_state,
running_total, running_index,
target_volume, number_jugs):
for from_jug in range (number_jugs):
from_jug_max = list_jug_max[from_jug].jug_max
from_jug_state = jug_state[from_jug]
for to_jug in range (number_jugs):
if to_jug == from_jug: continue
to_jug_max = list_jug_max[to_jug].jug_max
to_jug_state = jug_state[to_jug]
#Empty from_jug, ignore to_jug
new_jug_state = jug_state [:]
new_jug_state[from_jug] = 0
if new_jug_state not in list_previous_jug_states:
list_previous_jug_states.append(new_jug_state)
list_running_count.append (running_total+1)
new_index = [len(list_previous_jug_states)-1]
list_running_index.append (running_index + new_index)
#Fill from_jug, ignore to_jug
new_jug_state = jug_state [:]
new_jug_state[from_jug] = from_jug_max
if new_jug_state not in list_previous_jug_states:
list_previous_jug_states.append(new_jug_state)
list_running_count.append (running_total+1)
new_index = [len(list_previous_jug_states)-1]
list_running_index.append (running_index + new_index)
#Move as much from from_jug to to_jug
if to_jug_state == to_jug_max: continue
if from_jug_state == 0: continue
if from_jug_state < (to_jug_max-to_jug_state):
new_jug_state = jug_state [:]
new_jug_state[from_jug] = 0
new_jug_state[to_jug] = to_jug_state + from_jug_state
else:
amount_transfer = to_jug_max - to_jug_state
new_jug_state = jug_state [:]
new_jug_state[from_jug] = from_jug_state - amount_transfer
new_jug_state[to_jug] = to_jug_state + amount_transfer
if new_jug_state not in list_previous_jug_states:
list_previous_jug_states.append(new_jug_state)
list_running_count.append (running_total+1)
new_index = [len(list_previous_jug_states)-1]
list_running_index.append (running_index + new_index)
if any (jug == target_volume for jug in new_jug_state):
print ("Target reached in ", running_total + 1, "steps")
for item in running_index:
print (list_previous_jug_states[item])
print (new_jug_state)
return True
return False, 0
if __name__ == "__main__":
number_jugs = int(input("Please enter the number of jugs you have: "))
#Set jug volumes
for i in range (number_jugs):
jug_volume = int(input(f"Please enter the volume of jug {i+1}: "))
list_volumes.append(jug_volume)
#Set target volume
target_volume = int(input("Please enter the target volume: "))
#Sort jugs in size order
list_volumes.sort(reverse=True)
#Create object instances
for i in range (number_jugs):
jug_name = "Jug" + str(i+1)
CreateJugs (jug_name, list_volumes[i])
# set_fill_states(number_jugs) #Set the fill states
set_fill_states(number_jugs,list_volumes)
#Continue iterating through jug_previous_state
for item in list_previous_jug_states:
jug_state = item
index = list_previous_jug_states.index(item)
running_total = list_running_count [index]
running_index = list_running_index [index]
is_destination = make_moves (jug_state,
running_total,
running_index,
target_volume,
number_jugs)
if is_destination == True:
print ("=====")
break
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T03:08:01.220",
"Id": "423451",
"Score": "2",
"body": "There's no need to declare `global <variable>` in global scope"
}
] | [
{
"body": "<h2>Global variables</h2>\n\n<p>You never need to execute <code>global variable_name</code> in the global scope; variables created in the global scope are automatically global variables. So the following statements should all be removed:</p>\n\n<pre><code>global list_previous_jug_states \nglobal list_running_count \nglobal list_running_index \nglobal list_volumes \nglobal list_jug_max\n</code></pre>\n\n<p>JSYK: You rarely need <code>global variable_name</code> inside of functions. If a function references a variable that it has not created, and that variable exists in the global scope, that variable is automatically brought into the function scope. It is only necessary when you want to create (<code>variable_name = ...</code>) or modify (<code>variable_name += 10</code>) a global variable inside a function scope. Note that modifying an object (ie, dictionary, list, etc) held in a global variable is not modifying the global variable itself, so <code>variable_name[x] = y</code> would not require <code>global variable_name</code>.</p>\n\n<hr>\n\n<h2>class CreateJugs</h2>\n\n<p>This class is ill-named. A class is (usually) an item ... a noun such as a person, place or thing. It is rarely an action. \"Create\" is an action. Functions do things (actions), so you could have <code>def create_jug():</code>, but <code>class CreateJugs</code> is calling something which should be a thing by a name that describes an action.</p>\n\n<p>Moreover, a class is an object ... singular. It shouldn't have a plural name.</p>\n\n<p>A better name for the class might be simply <code>Jug</code>.</p>\n\n<p><code>max</code> is a built-in function name in Python. You should avoid using it as the name of a class member (<code>self.max</code>).</p>\n\n<p>If you want a property of a jug, you must already have a jug object, so repeating <code>jug_</code> in the property name is redundant. In the following statement, you are using <code>jug</code> 4 times. Would it be any less clear to remove <code>jug_</code> from the property name? Or would it actually be clearer, because it is shorter and more concise?</p>\n\n<pre><code>to_jug_max = list_jug_max[to_jug].jug_max\n</code></pre>\n\n<p>Base on the above points, I would instead write:</p>\n\n<pre><code>class Jug:\n\n def __init__(self, name, capacity):\n self._name = name\n self._capacity = capacity\n\n list_jug_max.append(self)\n\n @property\n def capacity(self):\n return self._capacity\n</code></pre>\n\n<p>But the only places where <code>Jug</code> objects are used, are the following statements:</p>\n\n<pre><code>jug_state.append(list_jug_max[x].max)\nfrom_jug_max = list_jug_max[from_jug].jug_max\nto_jug_max = list_jug_max[to_jug].jug_max\n</code></pre>\n\n<p>You are only ever using the Jug objects to access a single property: the jug's capacity. (Worse, you are doing so inconsistently ... sometimes directly getting the <code>.max</code> member, other times accessing the <code>.jug_max</code> property!)</p>\n\n<p>Since the jugs are created using the values in <code>list_volumes</code>, you could completely remove the class and <code>list_jug_max</code>, and replace the above statements with:</p>\n\n<pre><code>jug_state.append(list_volumes[x])\nfrom_jug_max = list_volumes[from_jug]\nto_jug_max = list_volumes[to_jug]\n</code></pre>\n\n<hr>\n\n<h2>set_fill_states</h2>\n\n<p>The variable <code>list_binary_states</code> is only used in the function <code>set_fill_states</code>. Why make it <code>global</code>?</p>\n\n<hr>\n\n<p>You are using <code>'0' * (number_jugs - len(binary_state)) + binary_state</code> to pad a string with leading 0's. There is a built-in function which does this:</p>\n\n<pre><code>binary_state = binary_state.rjust(number_jugs, '0')\n</code></pre>\n\n<p>Without the need for getting the length of <code>binary_state</code> separately, you can now convert the number into binary, remove the prefix, and add the padding in one statement:</p>\n\n<pre><code>binary_state = bin(i)[2:].rjust(number_jugs, '0')\n</code></pre>\n\n<p>Or, using format strings for formatting a number as binary, without a prefix, in a certain field width, with leading zeros:</p>\n\n<pre><code>binary_state = f\"{i:0{number_jugs}b}\"\n</code></pre>\n\n<hr>\n\n<p>Why:</p>\n\n<pre><code>list_binary_states = list_binary_states[0:len(list_binary_states)-1]\n</code></pre>\n\n<p>Shouldn't starting with all the jugs filled be a valid possibility?</p>\n\n<p>If you want to remove the last item of a list, you can simply use a slice that ends one element before the end of the list:</p>\n\n<pre><code>list_binary_states = list_binary_states[:-1]\n</code></pre>\n\n<hr>\n\n<p>Python comes with a lot of built-in capability. That includes sorting.</p>\n\n<p>You've implemented a selection sort (<span class=\"math-container\">\\$O(N^2)\\$</span>), where you search for items by counting the number of <code>'1'</code> characters in a N character string, making this sort into a <span class=\"math-container\">\\$O(N^3)\\$</span> complexity. Ouch!</p>\n\n<pre><code>list_binary_states.sort(key=lambda item: item.count('1'))\n</code></pre>\n\n<p>Done in 1 statement, in <span class=\"math-container\">\\$O(N \\log N)\\$</span> time.</p>\n\n<hr>\n\n<pre><code>for n in range (len(list_binary_states)):\n # ...\n list_running_index.append([n])\n</code></pre>\n\n<p>This is simply:</p>\n\n<pre><code>list_running_index = list(range(len(list_binary_states)))\n</code></pre>\n\n<p>Without that, the loop becomes ...</p>\n\n<pre><code>for n in range (len(list_binary_states)):\n jug_binary_state = list_binary_states[int(n)]\n # ...\n</code></pre>\n\n<p>... with no other references to <code>n</code> (which was alway an integer, so there was never a need to evaluate <code>int(n)</code>). Since you are only using <code>n</code> to index into <code>list_binary_states</code>, which is what you are looping over, you can replace this loop with:</p>\n\n<pre><code>for jug_binary_state in list_binary_states:\n # ...\n</code></pre>\n\n<hr>\n\n<pre><code> jug_state = []\n for x in range (number_jugs):\n if int(jug_binary_state[x]) == 1: \n jug_state.append(list_jug_max[x].max)\n else:\n jug_state.append (0)\n</code></pre>\n\n<p>Now, <code>jug_binary_state</code> is a string of length <code>number_jugs</code>. So we can loop over the characters of the string, instead of over the number of jugs. <code>list_volumes</code> is a list (of length <code>number_jugs</code>) of the maximum volume of each jug. We just need to zip the characters and the volumes together, to construct the <code>jug_state</code>.</p>\n\n<pre><code> jug_state = []\n for ch, volume in zip(jug_binary_state, list_volumes):\n if ch == '1':\n jug_state.append(volume)\n else:\n jug_state.append(0)\n</code></pre>\n\n<p>Or, using list comprehension:</p>\n\n<pre><code> jug_state = [ volume if ch == '1' else 0\n for ch, volume in zip(jug_binary_state, list_volumes) ]\n</code></pre>\n\n<hr>\n\n<h2>make_moves</h2>\n\n<pre><code>for from_jug in range (number_jugs):\n for to_jug in range (number_jugs):\n if to_jug == from_jug: continue \n #Empty from_jug, ignore to_jug\n #Fill from_jug, ignore to_jug\n #Move as much from from_jug to to_jug\n</code></pre>\n\n<p>For each <code>from_jug</code>, you loop over each possible <code>to_jug</code>, and then ignore the <code>to_jug</code> for the \"Empty\" and \"Fill\" possible moves. But you are still evaluating the new state for these moves for every <code>to_jug</code>, only to discarding the duplicate states. Why? That is a lot of extra work.</p>\n\n<p>How about moving the \"Empty\" and \"Fill\" steps out of the inner loop?</p>\n\n<pre><code>for from_jug in range (number_jugs):\n #Empty from_jug\n #Fill from_jug\n for to_jug in range (number_jugs):\n if to_jug == from_jug: continue \n #Move as much from from_jug to to_jug\n</code></pre>\n\n<hr>\n\n<p>Move common steps out of <code>if</code> statements. Here, you are always create <code>new_jug_state</code> the same way:</p>\n\n<pre><code> if from_jug_state < (to_jug_max-to_jug_state):\n new_jug_state = jug_state [:]\n #...\n else:\n new_jug_state = jug_state [:]\n #...\n</code></pre>\n\n<p>And if <code>transfer_amount</code> is set to <code>from_jug_state</code>, the last two statements of the <code>else</code> clause would do what the last two statements of the \"then\" clause would do:</p>\n\n<pre><code> if ...:\n # ...\n new_jug_state[from_jug] = 0\n new_jug_state[to_jug] = to_jug_state + from_jug_state\n else:\n # ...\n new_jug_state[from_jug] = from_jug_state - amount_transfer\n new_jug_state[to_jug] = to_jug_state + amount_transfer\n</code></pre>\n\n<p>So you can simplify this to:</p>\n\n<pre><code> if ...:\n # ...\n transfer_amount = from_jug_state\n else:\n # ...\n new_jug_state[from_jug] = from_jug_state - amount_transfer\n new_jug_state[to_jug] = to_jug_state + amount_transfer\n</code></pre>\n\n<hr>\n\n<p>What does <code>make_moves()</code> return? A boolean or a tuple?</p>\n\n<pre><code>return True\n\nreturn False, 0\n</code></pre>\n\n<p>Always return the same kind of thing from a function. If the function returns a boolean, only return a boolean. If the function returns a tuple of values, always return a tuple of values. Don't change what it returned; the caller won't know what to expect, so won't know how to interpret the results without going to heroic efforts. The tuple <code>False, 0</code> is truthy value (not a falsy value) because the tuple contains more than 0 values!</p>\n\n<hr>\n\n<p>Use functions! <code>make_moves()</code> is a long function. It has easy-to-make sub-functions, like <code>fill_a_jug()</code>, <code>empty_a_jug()</code>, <code>pour_between_jugs()</code>, which will help a reader of the code understand what the function does at a high level without being bogged down with lower level details, and the reader can look at the sub-functions separately for the lower-level details.</p>\n\n<hr>\n\n<h2>Don't modify lists while you iterate over them</h2>\n\n<pre><code>for item in list_previous_jug_states:\n\n make_moves(...) # Appends to list_previous_jug_states\n</code></pre>\n\n<p>While it can be made to work, you've had to use global variables, maintain other lists (<code>list_running_count</code>, <code>list_running_index</code>) to determine how many steps were required to reach the current step, and where a given step came from.</p>\n\n<p>Consider an alternate strategy:</p>\n\n<pre><code>visited = { state: None for state in initial_states }\ncurrent_states = initial_states\nsteps = 0\n\nwhile not solved:\n\n new_states = []\n\n for state in current_states:\n for new_state in valid_moves(state):\n if new_state not in visited:\n visited[new_state] = current_state\n new_states.append(new_state)\n\n current_states = new_states\n steps += 1\n</code></pre>\n\n<p>Here, I'm looping over all of the <code>current_state</code> values, and building up a new list of <code>new_states</code>, for the next step. When all the new states that are reachable from all of the current states have been determined, that list of new states replaces the <code>current_states</code>, and the process repeats for the next step.</p>\n\n<p>The <code>visited</code> dictionary keeps track of the previous state that the current state was reached from. Once a solution has been found, simply trace the path back to the initial state (<code>None</code>) to determine the shortest solution path.</p>\n\n<p>Like mentioned in my <a href=\"https://codereview.stackexchange.com/a/219072/100620\">previous answer</a>, you will need to use a <code>tuple</code> for the states, to allow them to be used as a key in the <code>visited</code> dictionary.</p>\n\n<hr>\n\n<p>This \"N-Jug\" problem can be <em>simplified</em> (as in, less code) into an \"N+1 Jug\" problem, with just the \"Pour from Jug A to Jug B\" moves. Simply create one additional jug with a capacity equal to the sum of all other jug capacities, and initialize it with a volume equal to its capacity less the volume initially contained in the remaining jugs. With this extra jug called \"Jug 0\", the \"Fill Jug A\" move becomes \"Pour from Jug 0 to Jug A\", and the \"Empty Jug A\" move becomes \"Pour from Jug A to Jug 0\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T20:19:14.283",
"Id": "423934",
"Score": "0",
"body": "Wow! thanks for such a detailed reply"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:47:31.340",
"Id": "219384",
"ParentId": "219211",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219384",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:14:34.470",
"Id": "219211",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Solve the jug problem for n jugs"
} | 219211 |
<p>I have written a small program in C# to plot <code>ROC</code>, <code>PR</code> (equal to <code>AP</code>) and <code>PRI</code> (equal to <code>API</code>) curves using the <code>plot_curve()</code> method. (The program also calculates the approximate AUC of the curves using the <code>area_under_curve_trapz()</code> method, but that isn't the main point. The main point and purpose is to plot the curves.)</p>
<p>Plotting <code>ROC</code> and <code>PR</code> curves in C# appears to be a task which has not yet been done effectively. Therefore, this algorithm is written from scratch. I also hope this algorithm will be useful for those interested in data science and machine learning, especially those using C#.</p>
<p>Please review and suggest any improvements in the algorithm. (In particular, I am curious about better methods of averaging the x,y coordinates for the outer-cross-validation results (i.e. nested-cross-validation), considering the variable decision boundary thresholds, i.e. the input of x,y can never be pre-determined, and using the standard 11 point averaging does not give accurate results; rather a very poor approximation. Still, it is supported by the method.)</p>
<p>The whole (working) algorithm is in the following file - plot.cs.
It can be tested using the static <code>plot.test_plot()</code> method which contains some real sample data. The generated bmp images will be loaded in the default program after execution.</p>
<p>Note that this was written using Visual Studio 2017, C# 7.3 and .NET 4.7.2. It may be incompatible with some lower C# or .NET versions. Please also note that this algorithm purposely ignores standard C# naming conventions.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
namespace svm_compute
{
public static class plot
{
public static void test_plot()
{
// this function plots sample ROC, PR and PRI (approximated interpolated) curves, using all thresholds and 11 point thresholds.
var encoded_roc = @"
FPR;TPR/0;0/0;0.022222/0;0.044444/0.030303;0.044444/0.030303;0.066667/0.030303;0.088889/0.030303;0.111111/0.030303;0.133333/0.030303;0.155556/0.030303;0.177778/0.060606;0.177778/0.060606;0.2/0.060606;0.222222/0.060606;0.244444/0.060606;0.266667/0.060606;0.288889/0.090909;0.288889/0.090909;0.311111/0.090909;0.333333/0.121212;0.333333/0.121212;0.355556/0.151515;0.355556/0.151515;0.377778/0.181818;0.377778/0.181818;0.4/0.181818;0.422222/0.181818;0.444444/0.181818;0.466667/0.212121;0.466667/0.212121;0.488889/0.242424;0.488889/0.242424;0.511111/0.242424;0.533333/0.242424;0.555556/0.242424;0.577778/0.242424;0.6/0.242424;0.622222/0.242424;0.644444/0.242424;0.666667/0.272727;0.666667/0.272727;0.688889/0.30303;0.688889/0.333333;0.688889/0.333333;0.711111/0.333333;0.733333/0.333333;0.755556/0.363636;0.755556/0.363636;0.777778/0.363636;0.8/0.363636;0.822222/0.393939;0.822222/0.393939;0.844444/0.393939;0.866667/0.393939;0.888889/0.424242;0.888889/0.424242;0.911111/0.424242;0.933333/0.454545;0.933333/0.484848;0.933333/0.515152;0.933333/0.515152;0.955556/0.515152;0.977778/0.545455;0.977778/0.545455;1/0.606061;1/0.636364;1/0.666667;1/0.69697;1/0.727273;1/0.757576;1/0.787879;1/0.818182;1/0.848485;1/0.878788;1/0.909091;1/0.939394;1/0.969697;1/1;1
FPR;TPR/0;0/0;0.030303/0;0.060606/0;0.090909/0;0.121212/0;0.151515/0;0.181818/0;0.212121/0;0.242424/0;0.272727/0;0.30303/0;0.333333/0;0.363636/0;0.393939/0;0.454545/0.022222;0.454545/0.022222;0.484848/0.044444;0.484848/0.066667;0.484848/0.066667;0.515152/0.066667;0.545455/0.066667;0.575758/0.088889;0.575758/0.111111;0.575758/0.111111;0.606061/0.133333;0.606061/0.155556;0.606061/0.177778;0.606061/0.177778;0.636364/0.2;0.636364/0.222222;0.636364/0.244444;0.636364/0.244444;0.666667/0.266667;0.666667/0.288889;0.666667/0.311111;0.666667/0.311111;0.69697/0.311111;0.727273/0.333333;0.727273/0.333333;0.757576/0.355556;0.757576/0.377778;0.757576/0.4;0.757576/0.422222;0.757576/0.444444;0.757576/0.466667;0.757576/0.488889;0.757576/0.511111;0.757576/0.511111;0.787879/0.533333;0.787879/0.533333;0.818182/0.555556;0.818182/0.577778;0.818182/0.6;0.818182/0.622222;0.818182/0.622222;0.848485/0.644444;0.848485/0.644444;0.878788/0.666667;0.878788/0.666667;0.909091/0.688889;0.909091/0.711111;0.909091/0.711111;0.939394/0.733333;0.939394/0.755556;0.939394/0.777778;0.939394/0.8;0.939394/0.822222;0.939394/0.822222;0.969697/0.844444;0.969697/0.866667;0.969697/0.888889;0.969697/0.911111;0.969697/0.933333;0.969697/0.955556;0.969697/0.955556;1/0.977778;1/1;1
FPR;TPR/0;0/0;0.022222/0;0.044444/0.030303;0.044444/0.030303;0.066667/0.030303;0.088889/0.030303;0.111111/0.030303;0.133333/0.030303;0.155556/0.030303;0.177778/0.030303;0.2/0.060606;0.2/0.060606;0.222222/0.060606;0.244444/0.060606;0.266667/0.060606;0.288889/0.060606;0.311111/0.090909;0.311111/0.121212;0.311111/0.121212;0.333333/0.121212;0.355556/0.121212;0.377778/0.121212;0.4/0.121212;0.422222/0.121212;0.444444/0.151515;0.444444/0.151515;0.466667/0.151515;0.488889/0.181818;0.488889/0.181818;0.511111/0.212121;0.511111/0.242424;0.511111/0.242424;0.533333/0.242424;0.555556/0.242424;0.577778/0.242424;0.6/0.272727;0.6/0.272727;0.622222/0.272727;0.644444/0.272727;0.666667/0.272727;0.688889/0.30303;0.688889/0.30303;0.711111/0.333333;0.711111/0.333333;0.733333/0.363636;0.733333/0.393939;0.733333/0.424242;0.733333/0.424242;0.755556/0.424242;0.777778/0.424242;0.8/0.424242;0.822222/0.424242;0.844444/0.424242;0.866667/0.424242;0.888889/0.454545;0.888889/0.484848;0.888889/0.484848;0.911111/0.515152;0.911111/0.545455;0.911111/0.545455;0.933333/0.575758;0.933333/0.606061;0.933333/0.606061;0.955556/0.666667;0.955556/0.69697;0.955556/0.69697;0.977778/0.727273;0.977778/0.757576;0.977778/0.787879;0.977778/0.787879;1/0.818182;1/0.848485;1/0.878788;1/0.909091;1/0.939394;1/0.969697;1/1;1
FPR;TPR/0;0/0;0.030303/0;0.060606/0;0.090909/0;0.121212/0;0.151515/0;0.181818/0;0.212121/0.022222;0.212121/0.022222;0.242424/0.022222;0.272727/0.022222;0.30303/0.044444;0.30303/0.044444;0.333333/0.044444;0.393939/0.066667;0.393939/0.066667;0.424242/0.066667;0.454545/0.088889;0.454545/0.088889;0.484848/0.088889;0.515152/0.111111;0.515152/0.111111;0.545455/0.111111;0.575758/0.133333;0.575758/0.155556;0.575758/0.177778;0.575758/0.2;0.575758/0.222222;0.575758/0.244444;0.575758/0.266667;0.575758/0.266667;0.606061/0.266667;0.636364/0.266667;0.666667/0.288889;0.666667/0.288889;0.69697/0.311111;0.69697/0.311111;0.727273/0.333333;0.727273/0.355556;0.727273/0.377778;0.727273/0.4;0.727273/0.4;0.757576/0.422222;0.757576/0.444444;0.757576/0.466667;0.757576/0.488889;0.757576/0.488889;0.787879/0.488889;0.818182/0.511111;0.818182/0.511111;0.848485/0.533333;0.848485/0.555556;0.848485/0.555556;0.878788/0.577778;0.878788/0.6;0.878788/0.622222;0.878788/0.644444;0.878788/0.666667;0.878788/0.688889;0.878788/0.688889;0.909091/0.688889;0.939394/0.711111;0.939394/0.733333;0.939394/0.755556;0.939394/0.777778;0.939394/0.8;0.939394/0.8;0.969697/0.822222;0.969697/0.844444;0.969697/0.866667;0.969697/0.888889;0.969697/0.911111;0.969697/0.933333;0.969697/0.955556;0.969697/0.955556;1/0.977778;1/1;1
FPR;TPR/0;0/0;0.022222/0;0.044444/0;0.066667/0;0.088889/0;0.111111/0;0.133333/0;0.155556/0;0.177778/0.030303;0.177778/0.030303;0.2/0.060606;0.2/0.060606;0.222222/0.060606;0.244444/0.060606;0.266667/0.090909;0.266667/0.090909;0.288889/0.090909;0.311111/0.090909;0.333333/0.121212;0.333333/0.121212;0.355556/0.121212;0.377778/0.121212;0.4/0.121212;0.422222/0.151515;0.422222/0.151515;0.444444/0.151515;0.466667/0.151515;0.488889/0.151515;0.511111/0.151515;0.533333/0.151515;0.555556/0.151515;0.577778/0.181818;0.577778/0.181818;0.6/0.181818;0.622222/0.212121;0.622222/0.212121;0.644444/0.242424;0.644444/0.272727;0.644444/0.272727;0.666667/0.272727;0.688889/0.30303;0.688889/0.333333;0.688889/0.333333;0.711111/0.333333;0.733333/0.333333;0.755556/0.333333;0.777778/0.363636;0.777778/0.393939;0.777778/0.424242;0.777778/0.424242;0.8/0.454545;0.8/0.454545;0.822222/0.454545;0.844444/0.454545;0.866667/0.454545;0.888889/0.484848;0.888889/0.484848;0.911111/0.515152;0.911111/0.545455;0.911111/0.545455;0.933333/0.575758;0.933333/0.575758;0.955556/0.606061;0.955556/0.636364;0.955556/0.666667;0.955556/0.666667;0.977778/0.69697;0.977778/0.727273;0.977778/0.757576;0.977778/0.787879;0.977778/0.818182;0.977778/0.848485;0.977778/0.878788;0.977778/0.909091;0.977778/0.909091;1/0.939394;1/0.969697;1/1;1
FPR;TPR/0;0/0;0.030303/0;0.060606/0;0.090909/0.022222;0.090909/0.022222;0.121212/0.022222;0.151515/0.022222;0.181818/0.022222;0.212121/0.022222;0.242424/0.022222;0.272727/0.022222;0.30303/0.022222;0.333333/0.044444;0.333333/0.044444;0.363636/0.044444;0.393939/0.044444;0.424242/0.066667;0.424242/0.066667;0.454545/0.088889;0.454545/0.088889;0.484848/0.088889;0.515152/0.111111;0.515152/0.111111;0.545455/0.133333;0.545455/0.155556;0.545455/0.177778;0.545455/0.2;0.545455/0.2;0.575758/0.222222;0.575758/0.222222;0.606061/0.222222;0.636364/0.222222;0.666667/0.244444;0.666667/0.266667;0.666667/0.288889;0.666667/0.311111;0.666667/0.311111;0.69697/0.311111;0.727273/0.333333;0.727273/0.355556;0.727273/0.355556;0.757576/0.355556;0.787879/0.377778;0.787879/0.377778;0.818182/0.4;0.818182/0.422222;0.818182/0.422222;0.848485/0.444444;0.848485/0.466667;0.848485/0.488889;0.848485/0.511111;0.848485/0.533333;0.848485/0.555556;0.848485/0.577778;0.848485/0.577778;0.878788/0.6;0.878788/0.622222;0.878788/0.644444;0.878788/0.666667;0.878788/0.666667;0.909091/0.688889;0.909091/0.711111;0.909091/0.733333;0.909091/0.733333;0.939394/0.755556;0.939394/0.777778;0.939394/0.8;0.939394/0.8;0.969697/0.822222;0.969697/0.822222;1/0.844444;1/0.866667;1/0.888889;1/0.911111;1/0.933333;1/0.955556;1/0.977778;1/1;1
FPR;TPR/0;0/0;0.022222/0;0.044444/0;0.066667/0;0.088889/0;0.111111/0;0.133333/0;0.155556/0;0.177778/0;0.2/0;0.222222/0;0.244444/0;0.266667/0;0.288889/0;0.311111/0;0.333333/0.030303;0.333333/0.030303;0.355556/0.030303;0.377778/0.030303;0.4/0.030303;0.422222/0.060606;0.422222/0.060606;0.444444/0.060606;0.466667/0.060606;0.488889/0.090909;0.488889/0.090909;0.511111/0.090909;0.533333/0.090909;0.555556/0.121212;0.555556/0.121212;0.577778/0.151515;0.577778/0.151515;0.6/0.151515;0.622222/0.181818;0.622222/0.181818;0.644444/0.181818;0.666667/0.212121;0.666667/0.212121;0.688889/0.242424;0.688889/0.242424;0.711111/0.272727;0.711111/0.30303;0.711111/0.333333;0.711111/0.363636;0.711111/0.363636;0.733333/0.363636;0.755556/0.393939;0.755556/0.393939;0.777778/0.424242;0.777778/0.424242;0.8/0.454545;0.8/0.454545;0.822222/0.484848;0.822222/0.515152;0.822222/0.545455;0.822222/0.545455;0.844444/0.545455;0.866667/0.545455;0.888889/0.545455;0.911111/0.575758;0.911111/0.606061;0.911111/0.606061;0.933333/0.636364;0.933333/0.666667;0.933333/0.666667;0.955556/0.69697;0.955556/0.727273;0.955556/0.727273;0.977778/0.757576;0.977778/0.757576;1/0.787879;1/0.818182;1/0.848485;1/0.878788;1/0.909091;1/0.939394;1/0.969697;1/1;1
FPR;TPR/0;0/0;0.030303/0;0.060606/0;0.090909/0;0.121212/0;0.151515/0;0.181818/0;0.212121/0;0.242424/0.022222;0.242424/0.022222;0.272727/0.044444;0.272727/0.044444;0.30303/0.044444;0.333333/0.066667;0.333333/0.066667;0.363636/0.066667;0.393939/0.088889;0.393939/0.088889;0.424242/0.088889;0.454545/0.111111;0.454545/0.133333;0.454545/0.155556;0.454545/0.177778;0.454545/0.177778;0.484848/0.177778;0.515152/0.177778;0.545455/0.2;0.545455/0.2;0.575758/0.222222;0.575758/0.222222;0.606061/0.244444;0.606061/0.244444;0.636364/0.266667;0.636364/0.288889;0.636364/0.288889;0.666667/0.288889;0.69697/0.288889;0.727273/0.288889;0.757576/0.311111;0.757576/0.311111;0.787879/0.333333;0.787879/0.333333;0.818182/0.355556;0.818182/0.377778;0.818182/0.377778;0.848485/0.4;0.848485/0.422222;0.848485/0.422222;0.878788/0.444444;0.878788/0.444444;0.909091/0.466667;0.909091/0.488889;0.909091/0.511111;0.909091/0.511111;0.939394/0.533333;0.939394/0.555556;0.939394/0.577778;0.939394/0.577778;0.969697/0.6;0.969697/0.622222;0.969697/0.644444;0.969697/0.666667;0.969697/0.666667;1/0.688889;1/0.711111;1/0.733333;1/0.755556;1/0.777778;1/0.8;1/0.822222;1/0.844444;1/0.866667;1/0.888889;1/0.911111;1/0.933333;1/0.955556;1/0.977778;1/1;1
";
var encoded_pr = @"
TPR;PPV/0;1/0.022222;1/0.044444;1/0.044444;0.666667/0.066667;0.75/0.088889;0.8/0.111111;0.833333/0.133333;0.857143/0.155556;0.875/0.177778;0.888889/0.177778;0.8/0.2;0.818182/0.222222;0.833333/0.244444;0.846154/0.266667;0.857143/0.288889;0.866667/0.288889;0.8125/0.311111;0.823529/0.333333;0.833333/0.333333;0.789474/0.355556;0.8/0.355556;0.761905/0.377778;0.772727/0.377778;0.73913/0.4;0.75/0.422222;0.76/0.444444;0.769231/0.466667;0.777778/0.466667;0.75/0.488889;0.758621/0.488889;0.733333/0.511111;0.741935/0.533333;0.75/0.555556;0.757576/0.577778;0.764706/0.6;0.771429/0.622222;0.777778/0.644444;0.783784/0.666667;0.789474/0.666667;0.769231/0.688889;0.775/0.688889;0.756098/0.688889;0.738095/0.711111;0.744186/0.733333;0.75/0.755556;0.755556/0.755556;0.73913/0.777778;0.744681/0.8;0.75/0.822222;0.755102/0.822222;0.74/0.844444;0.745098/0.866667;0.75/0.888889;0.754717/0.888889;0.740741/0.911111;0.745455/0.933333;0.75/0.933333;0.736842/0.933333;0.724138/0.933333;0.711864/0.955556;0.716667/0.977778;0.721311/0.977778;0.709677/1;0.714286/1;0.692308/1;0.681818/1;0.671642/1;0.661765/1;0.652174/1;0.642857/1;0.633803/1;0.625/1;0.616438/1;0.608108/1;0.6/1;0.592105/1;0.584416/1;0.576923
TPR;PPV/0;1/0.030303;1/0.060606;1/0.090909;1/0.121212;1/0.151515;1/0.181818;1/0.212121;1/0.242424;1/0.272727;1/0.30303;1/0.333333;1/0.363636;1/0.393939;1/0.454545;1/0.454545;0.9375/0.484848;0.941176/0.484848;0.888889/0.484848;0.842105/0.515152;0.85/0.545455;0.857143/0.575758;0.863636/0.575758;0.826087/0.575758;0.791667/0.606061;0.8/0.606061;0.769231/0.606061;0.740741/0.606061;0.714286/0.636364;0.724138/0.636364;0.7/0.636364;0.677419/0.636364;0.65625/0.666667;0.666667/0.666667;0.647059/0.666667;0.628571/0.666667;0.611111/0.69697;0.621622/0.727273;0.631579/0.727273;0.615385/0.757576;0.625/0.757576;0.609756/0.757576;0.595238/0.757576;0.581395/0.757576;0.568182/0.757576;0.555556/0.757576;0.543478/0.757576;0.531915/0.757576;0.520833/0.787879;0.530612/0.787879;0.52/0.818182;0.529412/0.818182;0.519231/0.818182;0.509434/0.818182;0.5/0.818182;0.490909/0.848485;0.5/0.848485;0.491228/0.878788;0.5/0.878788;0.491525/0.909091;0.5/0.909091;0.491803/0.909091;0.483871/0.939394;0.492063/0.939394;0.484375/0.939394;0.476923/0.939394;0.469697/0.939394;0.462687/0.939394;0.455882/0.969697;0.463768/0.969697;0.457143/0.969697;0.450704/0.969697;0.444444/0.969697;0.438356/0.969697;0.432432/0.969697;0.426667/1;0.434211/1;0.428571/1;0.423077
TPR;PPV/0;1/0.022222;1/0.044444;1/0.044444;0.666667/0.066667;0.75/0.088889;0.8/0.111111;0.833333/0.133333;0.857143/0.155556;0.875/0.177778;0.888889/0.2;0.9/0.2;0.818182/0.222222;0.833333/0.244444;0.846154/0.266667;0.857143/0.288889;0.866667/0.311111;0.875/0.311111;0.823529/0.311111;0.777778/0.333333;0.789474/0.355556;0.8/0.377778;0.809524/0.4;0.818182/0.422222;0.826087/0.444444;0.833333/0.444444;0.8/0.466667;0.807692/0.488889;0.814815/0.488889;0.785714/0.511111;0.793103/0.511111;0.766667/0.511111;0.741935/0.533333;0.75/0.555556;0.757576/0.577778;0.764706/0.6;0.771429/0.6;0.75/0.622222;0.756757/0.644444;0.763158/0.666667;0.769231/0.688889;0.775/0.688889;0.756098/0.711111;0.761905/0.711111;0.744186/0.733333;0.75/0.733333;0.733333/0.733333;0.717391/0.733333;0.702128/0.755556;0.708333/0.777778;0.714286/0.8;0.72/0.822222;0.72549/0.844444;0.730769/0.866667;0.735849/0.888889;0.740741/0.888889;0.727273/0.888889;0.714286/0.911111;0.719298/0.911111;0.706897/0.911111;0.694915/0.933333;0.7/0.933333;0.688525/0.933333;0.677419/0.955556;0.68254/0.955556;0.661538/0.955556;0.651515/0.977778;0.656716/0.977778;0.647059/0.977778;0.637681/0.977778;0.628571/1;0.633803/1;0.625/1;0.616438/1;0.608108/1;0.6/1;0.592105/1;0.584416/1;0.576923
TPR;PPV/0;1/0.030303;1/0.060606;1/0.090909;1/0.121212;1/0.151515;1/0.181818;1/0.212121;1/0.212121;0.875/0.242424;0.888889/0.272727;0.9/0.30303;0.909091/0.30303;0.833333/0.333333;0.846154/0.393939;0.866667/0.393939;0.8125/0.424242;0.823529/0.454545;0.833333/0.454545;0.789474/0.484848;0.8/0.515152;0.809524/0.515152;0.772727/0.545455;0.782609/0.575758;0.791667/0.575758;0.76/0.575758;0.730769/0.575758;0.703704/0.575758;0.678571/0.575758;0.655172/0.575758;0.633333/0.575758;0.612903/0.606061;0.625/0.636364;0.636364/0.666667;0.647059/0.666667;0.628571/0.69697;0.638889/0.69697;0.621622/0.727273;0.631579/0.727273;0.615385/0.727273;0.6/0.727273;0.585366/0.727273;0.571429/0.757576;0.581395/0.757576;0.568182/0.757576;0.555556/0.757576;0.543478/0.757576;0.531915/0.787879;0.541667/0.818182;0.55102/0.818182;0.54/0.848485;0.54902/0.848485;0.538462/0.848485;0.528302/0.878788;0.537037/0.878788;0.527273/0.878788;0.517857/0.878788;0.508772/0.878788;0.5/0.878788;0.491525/0.878788;0.483333/0.909091;0.491803/0.939394;0.5/0.939394;0.492063/0.939394;0.484375/0.939394;0.476923/0.939394;0.469697/0.939394;0.462687/0.969697;0.470588/0.969697;0.463768/0.969697;0.457143/0.969697;0.450704/0.969697;0.444444/0.969697;0.438356/0.969697;0.432432/0.969697;0.426667/1;0.434211/1;0.428571/1;0.423077
TPR;PPV/0;1/0.022222;1/0.044444;1/0.066667;1/0.088889;1/0.111111;1/0.133333;1/0.155556;1/0.177778;1/0.177778;0.888889/0.2;0.9/0.2;0.818182/0.222222;0.833333/0.244444;0.846154/0.266667;0.857143/0.266667;0.8/0.288889;0.8125/0.311111;0.823529/0.333333;0.833333/0.333333;0.789474/0.355556;0.8/0.377778;0.809524/0.4;0.818182/0.422222;0.826087/0.422222;0.791667/0.444444;0.8/0.466667;0.807692/0.488889;0.814815/0.511111;0.821429/0.533333;0.827586/0.555556;0.833333/0.577778;0.83871/0.577778;0.8125/0.6;0.818182/0.622222;0.823529/0.622222;0.8/0.644444;0.805556/0.644444;0.783784/0.644444;0.763158/0.666667;0.769231/0.688889;0.775/0.688889;0.756098/0.688889;0.738095/0.711111;0.744186/0.733333;0.75/0.755556;0.755556/0.777778;0.76087/0.777778;0.744681/0.777778;0.729167/0.777778;0.714286/0.8;0.72/0.8;0.705882/0.822222;0.711538/0.844444;0.716981/0.866667;0.722222/0.888889;0.727273/0.888889;0.714286/0.911111;0.719298/0.911111;0.706897/0.911111;0.694915/0.933333;0.7/0.933333;0.688525/0.955556;0.693548/0.955556;0.68254/0.955556;0.671875/0.955556;0.661538/0.977778;0.666667/0.977778;0.656716/0.977778;0.647059/0.977778;0.637681/0.977778;0.628571/0.977778;0.619718/0.977778;0.611111/0.977778;0.60274/0.977778;0.594595/1;0.6/1;0.592105/1;0.584416/1;0.576923
TPR;PPV/0;1/0.030303;1/0.060606;1/0.090909;1/0.090909;0.75/0.121212;0.8/0.151515;0.833333/0.181818;0.857143/0.212121;0.875/0.242424;0.888889/0.272727;0.9/0.30303;0.909091/0.333333;0.916667/0.333333;0.846154/0.363636;0.857143/0.393939;0.866667/0.424242;0.875/0.424242;0.823529/0.454545;0.833333/0.454545;0.789474/0.484848;0.8/0.515152;0.809524/0.515152;0.772727/0.545455;0.782609/0.545455;0.75/0.545455;0.72/0.545455;0.692308/0.545455;0.666667/0.575758;0.678571/0.575758;0.655172/0.606061;0.666667/0.636364;0.677419/0.666667;0.6875/0.666667;0.666667/0.666667;0.647059/0.666667;0.628571/0.666667;0.611111/0.69697;0.621622/0.727273;0.631579/0.727273;0.615385/0.727273;0.6/0.757576;0.609756/0.787879;0.619048/0.787879;0.604651/0.818182;0.613636/0.818182;0.6/0.818182;0.586957/0.848485;0.595745/0.848485;0.583333/0.848485;0.571429/0.848485;0.56/0.848485;0.54902/0.848485;0.538462/0.848485;0.528302/0.848485;0.518519/0.878788;0.527273/0.878788;0.517857/0.878788;0.508772/0.878788;0.5/0.878788;0.491525/0.909091;0.5/0.909091;0.491803/0.909091;0.483871/0.909091;0.47619/0.939394;0.484375/0.939394;0.476923/0.939394;0.469697/0.939394;0.462687/0.969697;0.470588/0.969697;0.463768/1;0.471429/1;0.464789/1;0.458333/1;0.452055/1;0.445946/1;0.44/1;0.434211/1;0.428571/1;0.423077
TPR;PPV/0;1/0.022222;1/0.044444;1/0.066667;1/0.088889;1/0.111111;1/0.133333;1/0.155556;1/0.177778;1/0.2;1/0.222222;1/0.244444;1/0.266667;1/0.288889;1/0.311111;1/0.333333;1/0.333333;0.9375/0.355556;0.941176/0.377778;0.944444/0.4;0.947368/0.422222;0.95/0.422222;0.904762/0.444444;0.909091/0.466667;0.913043/0.488889;0.916667/0.488889;0.88/0.511111;0.884615/0.533333;0.888889/0.555556;0.892857/0.555556;0.862069/0.577778;0.866667/0.577778;0.83871/0.6;0.84375/0.622222;0.848485/0.622222;0.823529/0.644444;0.828571/0.666667;0.833333/0.666667;0.810811/0.688889;0.815789/0.688889;0.794872/0.711111;0.8/0.711111;0.780488/0.711111;0.761905/0.711111;0.744186/0.711111;0.727273/0.733333;0.733333/0.755556;0.73913/0.755556;0.723404/0.777778;0.729167/0.777778;0.714286/0.8;0.72/0.8;0.705882/0.822222;0.711538/0.822222;0.698113/0.822222;0.685185/0.822222;0.672727/0.844444;0.678571/0.866667;0.684211/0.888889;0.689655/0.911111;0.694915/0.911111;0.683333/0.911111;0.672131/0.933333;0.677419/0.933333;0.666667/0.933333;0.65625/0.955556;0.661538/0.955556;0.651515/0.955556;0.641791/0.977778;0.647059/0.977778;0.637681/1;0.642857/1;0.633803/1;0.625/1;0.616438/1;0.608108/1;0.6/1;0.592105/1;0.584416/1;0.576923
TPR;PPV/0;1/0.030303;1/0.060606;1/0.090909;1/0.121212;1/0.151515;1/0.181818;1/0.212121;1/0.242424;1/0.242424;0.888889/0.272727;0.9/0.272727;0.818182/0.30303;0.833333/0.333333;0.846154/0.333333;0.785714/0.363636;0.8/0.393939;0.8125/0.393939;0.764706/0.424242;0.777778/0.454545;0.789474/0.454545;0.75/0.454545;0.714286/0.454545;0.681818/0.454545;0.652174/0.484848;0.666667/0.515152;0.68/0.545455;0.692308/0.545455;0.666667/0.575758;0.678571/0.575758;0.655172/0.606061;0.666667/0.606061;0.645161/0.636364;0.65625/0.636364;0.636364/0.636364;0.617647/0.666667;0.628571/0.69697;0.638889/0.727273;0.648649/0.757576;0.657895/0.757576;0.641026/0.787879;0.65/0.787879;0.634146/0.818182;0.642857/0.818182;0.627907/0.818182;0.613636/0.848485;0.622222/0.848485;0.608696/0.848485;0.595745/0.878788;0.604167/0.878788;0.591837/0.909091;0.6/0.909091;0.588235/0.909091;0.576923/0.909091;0.566038/0.939394;0.574074/0.939394;0.563636/0.939394;0.553571/0.939394;0.54386/0.969697;0.551724/0.969697;0.542373/0.969697;0.533333/0.969697;0.52459/0.969697;0.516129/1;0.52381/1;0.515625/1;0.507692/1;0.5/1;0.492537/1;0.485294/1;0.478261/1;0.471429/1;0.464789/1;0.458333/1;0.452055/1;0.445946/1;0.44/1;0.434211/1;0.428571/1;0.423077
";
var p11 = false;
var average_for_closest_points = true;
var open_bmp = true;
plot_curve(perf_curve_types.roc, encoded_roc, $@"c:\svm_compute\charts\{nameof(perf_curve_types.roc)}.bmp", p11, average_for_closest_points, open_bmp);
plot_curve(perf_curve_types.pr, encoded_pr, $@"c:\svm_compute\charts\{nameof(perf_curve_types.pr)}.bmp", p11, average_for_closest_points, open_bmp);
plot_curve(perf_curve_types.pri_from_pr, encoded_pr, $@"c:\svm_compute\charts\{nameof(perf_curve_types.pri_from_pr)}.bmp", p11, average_for_closest_points, open_bmp);
p11 = true;
plot_curve(perf_curve_types.roc, encoded_roc, $@"c:\svm_compute\charts\{nameof(perf_curve_types.roc)}{(p11 ? "_p11" : "")}.bmp", p11, average_for_closest_points, open_bmp);
plot_curve(perf_curve_types.pr, encoded_pr, $@"c:\svm_compute\charts\{nameof(perf_curve_types.pr)}{(p11 ? "_p11" : "")}.bmp", p11, average_for_closest_points, open_bmp);
plot_curve(perf_curve_types.pri_from_pr, encoded_pr, $@"c:\svm_compute\charts\{nameof(perf_curve_types.pri_from_pr)}{(p11 ? "_p11" : "")}.bmp", p11, average_for_closest_points, open_bmp);
}
public enum perf_curve_types : int
{
pr = 1,
pri = 2,
pri_from_pr = 3,
roc = 4
}
public static double scale(double value, double min, double max, double min_scale, double max_scale)
{
return (max_scale - min_scale) * ((value - min) / (max - min)) + min_scale;
}
public static double area_under_curve_trapz(List<(double x, double y)> coordinate_list)
{
coordinate_list = coordinate_list.Distinct().ToList();
coordinate_list = coordinate_list.OrderBy(a => a.x).ThenBy(a => a.y).ToList();
var auc = coordinate_list.Select((c, i) => i >= coordinate_list.Count - 1 ? 0 : (coordinate_list[i + 1].x - coordinate_list[i].x) * ((coordinate_list[i].y + coordinate_list[i + 1].y) / 2)).Sum();
return auc;
}
public static void plot_curve(perf_curve_types perf_curve_type, string encoded_plot_data, string save_filename, bool convert_to_p11 = false, bool average_for_closest_points = true, bool open_bmp = true)
{
// the data is in the format of x_title;y_title/x;y/x;y/x;y/...
// each line represents a different curve. usually from outer-cross-validation, there would be 5 or 10 curves (although it could be any number >= 2). if the input the average value from cross-validation, there would only be one curve.
// note, it is not necessary that the number of values is equal per curve. however, they should all be x,y values of either ROC or PR curves - other types of curves are not necessarily supported as there is code here specific to ROC and PR.
if (perf_curve_type == 0)
{
throw new ArgumentException("Invalid performance curve type specified.", nameof(perf_curve_type));
}
if (string.IsNullOrWhiteSpace(save_filename))
{
throw new ArgumentException("BMP filename required to save curve.", nameof(save_filename));
}
if (string.IsNullOrWhiteSpace(encoded_plot_data))
{
throw new ArgumentException("Plot x,y coordinate data is missing.", nameof(encoded_plot_data));
}
List<(string x_title, string y_title, List<(double x, double y)> xy)> parsed_xy = encoded_plot_data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(line =>
{
var headers = line.Trim().Split('/').First().Split(';');
var r = (x_title: headers[0], y_title: headers[1], xy: line.Trim().Split('/').Skip(1).Select(b => (x: double.Parse("" + b.Split(';')[0]), y: double.Parse("" + b.Split(';')[1]))).ToList());
r.xy = r.xy.OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).ToList();
return r;
}).ToList();
if (convert_to_p11)
{
// convert the x,y coordinate to the 11 point thresholds (useful for comparison of different classification models, where thresholds are unlikely to be meaningful)
var points11 = new[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
for (var index = 0; index < parsed_xy.Count; index++)
{
if (perf_curve_type == perf_curve_types.roc)
{
parsed_xy[index] = (parsed_xy[index].x_title, parsed_xy[index].y_title, points11.Select(t => (t, parsed_xy[index].xy.Where(a => a.x <= t).Max(a => a.y))).ToList());
}
else
{
parsed_xy[index] = (parsed_xy[index].x_title, parsed_xy[index].y_title, points11.Select(t => (t, parsed_xy[index].xy.Where(a => a.x >= t).Max(a => a.y))).ToList());
}
}
}
if (perf_curve_type == perf_curve_types.pri_from_pr)
{
// interpolate the x,y values (also for comparison of classifiation models)
var last_y = 0d;
parsed_xy = parsed_xy.Select(a => (x_title: a.x_title, y_title: a.y_title, xy: a.xy.Select((b, i) =>
{
//x = TPR; y = PPV
var max_ppv = a.xy.Where(c => c.x >= b.x).Max(c => c.y);
if (double.IsNaN(max_ppv)) max_ppv = last_y;
last_y = max_ppv;
return (x: b.x, y: max_ppv);
}).ToList())).ToList();
}
(string x_title, string y_title, List<(double x, double y)> xy) average_xy2 = (parsed_xy.First().x_title, parsed_xy.First().y_title, new List<(double x, double y)>());
if (average_for_closest_points)
{
// make average curve for all outer-cv curves
var all_xy = parsed_xy.SelectMany(a => a.xy).OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).Distinct().ToList();
var closest_to_all_xy = all_xy.Select(z => parsed_xy.Select(a => a.xy.OrderBy(b => Math.Abs(b.x - z.x) + Math.Abs(b.y - z.y)).First()).ToList()).ToList();
average_xy2.xy = closest_to_all_xy.Select(a => (x: a.Average(b => b.x), y: a.Average(b => b.y))).Distinct().OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).ToList();
average_xy2.xy = average_xy2.xy.Distinct().OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).ToList();
}
List<(string x_title, string y_title, List<(double x, double y)> xy)> data = parsed_xy;
var average_curves = 0;
if (average_xy2.xy != null && average_xy2.xy.Count > 0) { data.Add(average_xy2); average_curves++; }
var graph_title = perf_curve_type.ToString().Replace("_", " ").ToUpperInvariant() + " " + string.Join(" ", string.Join("|", data.Select(a => a.x_title + "/" + a.y_title).Distinct().ToList()), "Curve");
var axis_x_title = string.Join(" ", string.Join("|", data.Select(a => a.x_title).Distinct().ToList()), "(X)");
var axis_y_title = string.Join(" ", string.Join("|", data.Select(a => a.y_title).Distinct().ToList()), "(Y)");
var width_x = 2000; // could be specified as a parameter
var height_y = 2000; // could be specified as a parameter
var bg_color = Color.Transparent;
var fg_color = Color.White; // not in use - using transparent instead
var grid_color = Color.LightSlateGray;
var title_color = Color.White;
var axis_start_color = Color.Blue;
var axis_end_color = Color.Red;
var bmp = new Bitmap(width_x, height_y);
var graph_width_x = (double)bmp.Width * 0.8; // could be specified as a parameter
var graph_height_y = (double)bmp.Height * 0.8; // could be specified as a parameter
var graph_start_x = ((double)width_x - (double)graph_width_x) / (double)2;
var graph_end_x = (double)graph_start_x + (double)graph_width_x;
var graph_start_y = ((double)height_y - (double)graph_height_y) / (double)2;
var graph_end_y = (double)graph_start_y + (double)graph_height_y;
program.WriteLine($@"{nameof(graph_start_x)}={graph_start_x}, {nameof(graph_start_y)}={graph_start_y}, {nameof(graph_end_x)}={graph_end_x}, {nameof(graph_end_y)}={graph_end_y}");
using (var bmp_gfx = Graphics.FromImage(bmp))
{
/////////////////////////////////////////////////////////
// set bg colour, and other gfx parameters
bmp_gfx.Clear(bg_color);
bmp_gfx.SmoothingMode = SmoothingMode.AntiAlias;
bmp_gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
bmp_gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
bmp_gfx.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
};
/////////////////////////////////////////////////////////
// draw title
{
var title_font = new Font("Tahoma", (int)graph_start_y / 4, GraphicsUnit.Pixel);
var title_brush = new SolidBrush(title_color);
bmp_gfx.DrawString(graph_title, title_font, title_brush, new RectangleF(0, 0, bmp.Width, (int)graph_start_y), format);
}
/////////////////////////////////////////////////////////
// draw diagonal graph grid lines
{
bmp_gfx.DrawLine(new Pen(grid_color, 2), (float)graph_start_x, (float)graph_start_y, (float)graph_end_x, (float)graph_end_y);
bmp_gfx.DrawLine(new Pen(grid_color, 2), (float)graph_start_x, (float)graph_end_y, (float)graph_end_x, (float)graph_start_y);
}
/////////////////////////////////////////////////////////
// draw x axis title
{
var axis_x_font = new Font("Tahoma", (int)((height_y - graph_end_y) / 4), GraphicsUnit.Pixel);
var axis_x_title_size = bmp_gfx.MeasureString(axis_x_title, axis_x_font);
var axis_x_title_start_x = (float)(((double)width_x / (double)2) - ((double)axis_x_title_size.Width / (double)2));
var axis_x_title_start_y = (float)((double)height_y - ((double)axis_x_title_size.Height));
var axis_x_brush = new LinearGradientBrush(new RectangleF(axis_x_title_start_x, axis_x_title_start_y, axis_x_title_size.Width, axis_x_title_size.Height), axis_start_color, axis_end_color, LinearGradientMode.Horizontal);
bmp_gfx.DrawString(axis_x_title, axis_x_font, axis_x_brush, axis_x_title_start_x, axis_x_title_start_y);
}
/////////////////////////////////////////////////////////
// draw y axis title
{
var axis_y_font = new Font("Tahoma", (int)graph_start_x / 4, GraphicsUnit.Pixel);
var axis_y_title_size = bmp_gfx.MeasureString(axis_y_title, axis_y_font); //, new StringFormat(StringFormatFlags.DirectionVertical));
var axis_y_title_start_x = (float)0; // (axis_y_title_size.Height/2);
var axis_y_title_start_y = (float)((bmp.Height / 2) + (axis_y_title_size.Width / 2));
var axis_y_title_end_x = axis_y_title_start_x + axis_y_title_size.Height;
var axis_y_title_end_y = axis_y_title_start_y + axis_y_title_size.Width;
bmp_gfx.TranslateTransform(axis_y_title_start_x, axis_y_title_start_y);
bmp_gfx.RotateTransform(90 * 3);
var axis_y_brush = new LinearGradientBrush(new RectangleF(0, 0, axis_y_title_size.Width, axis_y_title_size.Height), axis_start_color, axis_end_color, LinearGradientMode.Horizontal);
bmp_gfx.DrawString(axis_y_title, axis_y_font, (Brush)axis_y_brush, 0, 0);
bmp_gfx.ResetTransform();
}
/////////////////////////////////////////////////////////
// draw grid lines horizonal (x changes, y in min to max)
{
var ticks_axis_x_brush = new LinearGradientBrush(new Rectangle((int)0, (int)0, (int)bmp.Width, bmp.Height), axis_start_color, axis_end_color, LinearGradientMode.Horizontal);
var ticks_axis_x_font = new Font("Tahoma", (int)((height_y - graph_end_y) / 4), GraphicsUnit.Pixel);
for (var x = 0.0; x <= 1.0; x += 0.1)
{
var x1 = scale(x, 0.0, 1.0, graph_start_x, graph_end_x);
var x2 = scale(x, 0.0, 1.0, graph_start_x, graph_end_x);
var y1 = scale(0.0, 0.0, 1.0, graph_start_y, graph_end_y);
var y2 = scale(1.0, 0.0, 1.0, graph_start_y, graph_end_y);
program.WriteLine($@"{nameof(x1)}={x1}, {nameof(y1)}={y1}, {nameof(x2)}={x2}, {nameof(y2)}={y2}");
bmp_gfx.DrawLine(new Pen(grid_color, 2), (float)x1, (float)y1, (float)x2, (float)y2);
var tick_text_size = bmp_gfx.MeasureString(x.ToString("0.0"), ticks_axis_x_font); // swap width and height, since it is rotated to side
bmp_gfx.TranslateTransform((float)x1 - (tick_text_size.Height / 2), (float)(graph_end_y + (tick_text_size.Width * 1.1)));
bmp_gfx.RotateTransform(90 * 3);
bmp_gfx.DrawString(x.ToString("0.0"), ticks_axis_x_font, ticks_axis_x_brush, 0, 0); // tick_text_size.Height);//, new StringFormat(StringFormatFlags.DirectionVertical));
bmp_gfx.ResetTransform();
}
}
/////////////////////////////////////////////////////////
// draw grid lines vertical (y changes, x is min to max)
{
var ticks_axis_y_brush = new LinearGradientBrush(new Rectangle((int)0, (int)0, (int)bmp.Width, bmp.Height), axis_start_color, axis_end_color, LinearGradientMode.Horizontal);
var ticks_axis_y_font = new Font("Tahoma", (int)((graph_start_x) / 4), GraphicsUnit.Pixel);
for (var y = 0.0; y <= 1.0; y += 0.1)
{
var x1 = scale(0.0, 0.0, 1.0, graph_start_x, graph_end_x);
var x2 = scale(1.0, 0.0, 1.0, graph_start_x, graph_end_x);
var y1 = scale(y, 0.0, 1.0, graph_start_y, graph_end_y);
var y2 = scale(y, 0.0, 1.0, graph_start_y, graph_end_y);
program.WriteLine($@"{nameof(x1)}={x1}, {nameof(y1)}={y1}, {nameof(x2)}={x2}, {nameof(y2)}={y2}");
bmp_gfx.DrawLine(new Pen(grid_color, 2), (float)x1, (float)y1, (float)x2, (float)y2);
var tick_text_size = bmp_gfx.MeasureString((1 - y).ToString("0.0"), ticks_axis_y_font);
bmp_gfx.DrawString((1 - y).ToString("0.0"), ticks_axis_y_font, ticks_axis_y_brush, (float)(graph_start_x - (tick_text_size.Width * 1.0)), (float)(y2 - (tick_text_size.Height / 2)));
}
}
/////////////////////////////////////////////////////////
// draw data
var color_rnd = new Random(2);
for (var i = 0; i < data.Count; i++)
{
var is_average_curve = i >= data.Count - average_curves;
var c = is_average_curve ? Color.White : Color.FromArgb(color_rnd.Next(0, 255), color_rnd.Next(0, 255), color_rnd.Next(0, 255));
var auc = area_under_curve_trapz(data[i].xy);
auc = Math.Round(auc, 2);
var auc_str = "AUC " + auc.ToString("0.00");
var auc_str_font = new Font("Tahoma", (int)((graph_start_x) / 4), GraphicsUnit.Pixel);
var auc_str_size = bmp_gfx.MeasureString(auc_str, auc_str_font);
bmp_gfx.DrawString(auc_str, auc_str_font, new SolidBrush(c), (int)(width_x - auc_str_size.Width), (int)(graph_start_y + (auc_str_size.Height * i)));
for (var a = 1; a < data[i].xy.Count; a++)
{
var xy1 = data[i].xy[a - 1];
var xy2 = data[i].xy[a];
var x1 = scale(xy1.x, 0.0, 1.0, graph_start_x, graph_end_x);
var y1 = scale((1 - xy1.y), 0.0, 1.0, graph_start_y, graph_end_y);
var x2 = scale(xy2.x, 0.0, 1.0, graph_start_x, graph_end_x);
var y2 = scale((1 - xy2.y), 0.0, 1.0, graph_start_y, graph_end_y);
var point_size = 20;
var pen_size = 4;
bmp_gfx.DrawLine(new Pen(c, pen_size), (float)x1, (float)y1, (float)x2, (float)y2);
if (a == 1)
{
bmp_gfx.DrawEllipse(new Pen(c, pen_size), (int)x1 - (point_size / 2), (int)y1 - (point_size / 2), point_size, point_size);
}
bmp_gfx.DrawEllipse(new Pen(c, pen_size), (int)x2 - (point_size / 2), (int)y2 - (point_size / 2), point_size, point_size);
}
}
}
Directory.CreateDirectory(Path.GetDirectoryName(save_filename));
bmp.Save(save_filename, ImageFormat.Bmp);
if (open_bmp)
{
Process.Start(save_filename);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>When drawing graphics I admit that it in general can be difficult to split the code into meaningful sub methods because often many variables are used across different sections of the process. A way to do it could be to make a non static class, that holds the entire data set, constant key measurements and other resources as member fields/properties and then split the huge method <code>plot_curve(...)</code> into meaningful sub methods.</p>\n\n<p>At least I would extract the preprocessing of the input data and the postprocessing of the resulting bmp in to dedicated methods.</p>\n\n<hr>\n\n<blockquote>\n <p><code>List<(double x, double y)</code></p>\n</blockquote>\n\n<p>You use a named tuple as data type for points. Why not use the built in <code>PointF</code> instead. Or - if you want the double precision in calculations - make your own <code>PointD</code> data type - and then abstract the conversion to and from <code>Point</code> and <code>PointF</code> away in cast operators. I think that would make the entire code more readable. There are a lot of inline casting, that could be avoided this way, and you could use the <code>Graphics.DrawXXX(...)</code> overrides that take <code>PointF</code> arguments instead of <code>x,y</code> arguments.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (perf_curve_type == 0)\n {\n throw new ArgumentException(\"Invalid performance curve type specified.\", nameof(perf_curve_type));\n }\n</code></pre>\n</blockquote>\n\n<p>You make this test, but what about values above 4? Should it even be necessary for an <code>enum</code> type?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> List<(string x_title, string y_title, List<(double x, double y)> xy)> parsed_xy = encoded_plot_data.Split(new char[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(line =>\n {\n var headers = line.Trim().Split('/').First().Split(';');\n var r = (x_title: headers[0], y_title: headers[1], xy: line.Trim().Split('/').Skip(1).Select(b => (x: double.Parse(\"\" + b.Split(';')[0]), y: double.Parse(\"\" + b.Split(';')[1]))).ToList());\n r.xy = r.xy.OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).ToList();\n return r;\n }).ToList();\n</code></pre>\n</blockquote>\n\n<p>This fails for the provided test input, because there is a whitespace line as the last line. You need to filter that out before the <code>Select(line...)</code> statement:</p>\n\n<pre><code> CultureInfo parseFormat = CultureInfo.InvariantCulture;\n List<(string x_title, string y_title, List<(double x, double y)> xy)> parsed_xy = encoded_plot_data.Split(new char[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries)\n .Where(line => !string.IsNullOrWhiteSpace(line)) \n .Select(line =>\n {\n var headers = line.Trim().Split('/').First().Split(';');\n\n var r = (x_title: headers[0], y_title: headers[1], xy: line.Trim().Split('/').Skip(1).Select(b => (x: double.Parse(\"\" + b.Split(';')[0], parseFormat), y: double.Parse(\"\" + b.Split(';')[1], parseFormat))).ToList());\n\n r.xy = r.xy.OrderBy(a => a.x).ThenBy(a => perf_curve_type == perf_curve_types.roc ? a.y : 1 - a.y).ToList();\n return r;\n }).ToList();\n</code></pre>\n\n<p>As shown above you also need a proper format provider, when parsing the coordinates and other numbers in order to handle <code>'.' and ','</code> correctly in respect to the file format.</p>\n\n<p>Have you considered to use a <code>Regex</code> pattern instead?</p>\n\n<hr>\n\n<blockquote>\n <p><code>.ToList()</code></p>\n</blockquote>\n\n<p>You have a lot of these calls where you make a LINQ queries. For large data sets they might be expensive, because they create a copy of the data set. They should be unnecessary when just querying the set, so consider to avoid them as much as possible and only use them when you want to create a sub set reused more than once.</p>\n\n<p>For instance:</p>\n\n<blockquote>\n<pre><code>public static double area_under_curve_trapz(List<(double x, double y)> coordinate_list)\n{\n coordinate_list = coordinate_list.Distinct().ToList();\n coordinate_list = coordinate_list.OrderBy(a => a.x).ThenBy(a => a.y).ToList();\n var auc = coordinate_list.Select((c, i) => i >= coordinate_list.Count - 1 ? 0 : (coordinate_list[i + 1].x - coordinate_list[i].x) * ((coordinate_list[i].y + coordinate_list[i + 1].y) / 2)).Sum();\n return auc;\n}\n</code></pre>\n</blockquote>\n\n<p>could be written as:</p>\n\n<pre><code>public static double area_under_curve_trapz(List<(double x, double y)> coordinate_list)\n{\n var auc = coordinate_list\n .Distinct()\n .OrderBy(a => a.x)\n .ThenBy(a => a.y)\n .Select((c, i) => \n i >= coordinate_list.Count - 1 \n ? 0 \n : (coordinate_list[i + 1].x - coordinate_list[i].x) * ((coordinate_list[i].y + coordinate_list[i + 1].y) / 2)).Sum();\n return auc;\n}\n</code></pre>\n\n<p>It's just a query, that doesn't modify the source set, so it's safe to operate on that directly. </p>\n\n<hr>\n\n<p>In general all graphic resources like pens, fonts, brushes etc as:</p>\n\n<blockquote>\n <p><code>new SolidBrush(title_color)</code></p>\n</blockquote>\n\n<p>should be disposed after use, so wrap them in a <code>using</code> statement.</p>\n\n<hr>\n\n<blockquote>\n <p><code>new Font(\"Tahoma\", (int)graph_start_y / 4, GraphicsUnit.Pixel)</code>\n <code>new Font(\"Tahoma\", (int)graph_start_x / 4, GraphicsUnit.Pixel);</code></p>\n</blockquote>\n\n<p>You repeatedly recreate these fonts, but <code>graph_start_x</code> and <code>graph_start_y</code> are constant throughout the method, so create them once</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for (var y = 0.0; y <= 1.0; y += 0.1)\n {\n var x1 = scale(0.0, 0.0, 1.0, graph_start_x, graph_end_x);\n var x2 = scale(1.0, 0.0, 1.0, graph_start_x, graph_end_x);\n ...\n</code></pre>\n</blockquote>\n\n<p>In some of the loops you instantiate <code>x1, x2</code> or <code>y1, y2</code> inside the loop although they are invariant while the loop is running. Consider to declare them before the loop:</p>\n\n<pre><code> var x1 = scale(0.0, 0.0, 1.0, graph_start_x, graph_end_x); are constant => out of loop\n var x2 = scale(1.0, 0.0, 1.0, graph_start_x, graph_end_x);\n for (var y = 0.0; y <= 1.0; y += 0.1)\n {\n ...\n</code></pre>\n\n<hr>\n\n<p>All in all I think the output is quite nice. I would make some adjustments in font sizes and the placement of the AUC results, and I wouldn't rotate the values on the x-axis.</p>\n\n<p>Consider to use a bitmap format that is compressed - for instance png. The produced output in bmp format has a size of about 15 MB where a png only takes < 1 MB.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T08:14:32.627",
"Id": "219240",
"ParentId": "219212",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:20:45.537",
"Id": "219212",
"Score": "3",
"Tags": [
"c#",
"graphics",
"data-visualization"
],
"Title": "Plot ROC, PR, and PRI curves in C# using pre-calculated coordinates"
} | 219212 |
<p>This is a TensorFlow regressor that tells me that if you get x score, you will have x% to win a game in x game(game is not important).</p>
<p>Doing this as a project to learn tensorflow.</p>
<pre><code>from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
stats = pd.read_csv(r"D:\Trabajo\Proyectos\Api Fort - copia\user_matches\csv_all.csv", sep=",")
my_feature = stats[['Score']]
feature_columns = [tf.feature_column.numeric_column('Score')]
targets = stats['Win']
my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0000001)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
linear_regressor = tf.estimator.LinearRegressor(
feature_columns=feature_columns,
optimizer=my_optimizer,
model_dir='none'
)
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
features = {key:np.array(value) for key,value in dict(features).items()}
ds = Dataset.from_tensor_slices((features,targets))
ds = ds.batch(batch_size).repeat(num_epochs)
if shuffle:
ds = ds.shuffle(buffer_size=10000)
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
_ = linear_regressor.train(
input_fn = lambda:my_input_fn(my_feature, targets),
steps=1000
)
prediction_input_fn =lambda: my_input_fn(my_feature, targets, num_epochs=1, shuffle=False)
#Llamo la funcion predict() en el regresor lineal para hacer predicciones
predictions = linear_regressor.predict(input_fn=prediction_input_fn)
#Format las predicciones como un Numpy array, asi podemos calcular el error.
predictions = np.array([item['predictions'][0] for item in predictions])
##Display el mean squared error y el root mean squared error
mean_squared_error = metrics.mean_squared_error(predictions, targets)
root_mean_squared_error = math.sqrt(mean_squared_error)
min_win_value = stats['Win'].min()
max_win_value = stats['Win'].max()
min_max_difference = max_win_value - min_win_value
##revisando predicciones
calibration_data = pd.DataFrame()
calibration_data["predictions"] = pd.Series(predictions)
calibration_data["targets"] = pd.Series(targets)
calibration_data.describe()
sample = stats.sample(n=300)
x_0 = sample['Win'].min()
x_1 = sample['Win'].max()
weight = linear_regressor.get_variable_value('linear/linear_model/Score/weights')[0]
bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')
y_0 = weight * x_0 + bias
y_1 = weight * x_1 + bias
plt.plot([x_0, x_1], [y_0, y_1], c='r')
plt.ylabel("Win")
plt.xlabel("Score")
# Plot a scatter plot from our data sample.
plt.scatter(sample["Score"], sample["Win"])
def train_model(learning_rate, steps, batch_size, input_feature="Score"):
periods = 10
steps_per_period = steps / periods
my_feature = input_feature
my_feature_data = stats[[my_feature]]
my_label = "Win"
targets = stats[my_label]
# Crear columnas de feature.
feature_columns = [tf.feature_column.numeric_column(my_feature)]
# Crear funciones de input
training_input_fn = lambda:my_input_fn(my_feature_data, targets, batch_size=batch_size)
prediction_input_fn = lambda: my_input_fn(my_feature_data, targets, num_epochs=1, shuffle=False)
# Crear un objeto de regresor lineal
my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
linear_regressor = tf.estimator.LinearRegressor(
feature_columns=feature_columns,
optimizer=my_optimizer
)
# Configurar un plot para que muestre el estado de nuestra linea de modelo por cada periodo.
plt.figure(figsize=(15, 6))
plt.subplot(1, 2, 1)
plt.title("Learned Line by Period")
plt.ylabel(my_label)
plt.xlabel(my_feature)
sample = stats.sample(n=300)
plt.scatter(sample[my_feature], sample[my_label])
colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]
# Entrenar el modelo, pero haciendolo en un look asi podemos revisar periodicamente.
# Metricas de perdida
print("Training model...")
print("RMSE (on training data):")
root_mean_squared_errors = []
for period in range (0, periods):
# Entrenar el modelo, empezando desde el punto anterior
linear_regressor.train(
input_fn=training_input_fn,
steps=steps_per_period
)
# Computando predicciones
predictions = linear_regressor.predict(input_fn=prediction_input_fn)
predictions = np.array([item['predictions'][0] for item in predictions])
# Computando perdidas
root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(predictions, targets))
# Ocasionalmente print la perdida
# Agregar la perdida de metrica de este periodo a nuestra lista
root_mean_squared_errors.append(root_mean_squared_error)
# Finalmente rastrearemos los weights y biases over time.
# Aplicar matematica para asegurarnos de que la data y la linea estan bien graficadas
y_extents = np.array([0, sample[my_label].max()])
weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]
bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')
x_extents = (y_extents - bias) / weight
x_extents = np.maximum(np.minimum(x_extents,
sample[my_feature].max()),
sample[my_feature].min())
y_extents = weight * x_extents + bias
plt.plot(x_extents, y_extents, color=colors[period])
# Mostrar una graph de las perdidas sobre los periodos
plt.subplot(1, 2, 2)
plt.ylabel('RMSE')
plt.xlabel('Periods')
plt.title("Root Mean Squared Error vs. Periods")
plt.tight_layout()
plt.plot(root_mean_squared_errors)
# Mostrar tabla con data de prediccion
calibration_data = pd.DataFrame()
calibration_data["predictions"] = pd.Series(predictions)
calibration_data["targets"] = pd.Series(targets)
display.display(calibration_data.describe())
train_model(
learning_rate=0.000001,
steps=100000,
batch_size=20
)
</code></pre>
<p>If you have any comments or suggestions, feel free to comment.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:39:21.117",
"Id": "219214",
"Score": "3",
"Tags": [
"python",
"numpy",
"statistics",
"pandas",
"tensorflow"
],
"Title": "TensorFlow regressor to predict probability of winning, given a current score"
} | 219214 |
<p><em>People here often ask to share as much code as possible. My app is just a sandbox, a typical freshly created AspNetCore + Angular template without much code. So please don't blame me - I provide ALL OF the code related to dates & timezones.</em></p>
<hr>
<p>I'm playing with dates in .NET and started learning Moment.js in detail.</p>
<p>I think the best way to learn it is to code something like rudimentary Hotel Booking app - simply because it brings enough complexity and you deal with a lot of timezone-related nuances.</p>
<p>Tutorials on the web only cover most common cases like operations with dates. Very little is written about handling timezone offsets.</p>
<p>We all know that when a date is fetched by back-end it must be stored in the DB as UTC date - there's <a href="http://blog.abodit.com/2010/02/datetime-values-should-always-be-stored-in-utc/" rel="nofollow noreferrer">a great article</a> about it and I agree with this guy completely.</p>
<p>Let's start!</p>
<hr>
<p><strong>INITIAL INFO:</strong></p>
<p><strong>Location of the Hotel:</strong> Spain (GMT+1 / GMT+2 - depending on DST)</p>
<p><strong>Check-In Date & Time:</strong> 24 Apr 2019 14:30:00 Spanish Local Time</p>
<hr>
<p><strong>HOTEL BOOKING WEB SERVICE:</strong></p>
<p><em>(say, we haven't started creating separate portals for hotel staff and hotel guests - to keep it simple we just have 2 separate pages as our app is more like a sandbox - I've picked ASP.NET Core & Angular template in Visual Studio)</em></p>
<ul>
<li>there's a page where we, as a guest, choose the date and time of our arrival - <em>the page contains DateTimePicker UI control</em></li>
<li>there's a separate page where the hotel staff can see the Check-Ins</li>
</ul>
<p><em>Sounds pretty feasible? I've got bad news. Let's dive in...</em></p>
<p>We are dealing with JavaScript front-end - it may be AngularJS / Angular 2+ / Vue / React or even jQuery. No big difference as AJAX calls are involved.</p>
<hr>
<p><strong>PART 1 - BOOKING PAGE:</strong></p>
<p>Multiple users from different time-zones are accessing this page. They want to book a hotel - they pick Date & Time using DateTimePicker.</p>
<p><strong>Nuance 1 - your timezone:</strong></p>
<p>What happens if your time-zone is GMT+3 and you new up a date variable in JavaScript?</p>
<p>The ANSWER is:</p>
<p>your date now has an offset e.g. <em>Mon Apr 24 2019 00:00:00 GMT+0300 (Moscow Standard Time)</em>.</p>
<p>And if you pass this date to the back-end it will be 3 hours out - Apr 23 2019 21:00:00 - hence it's no longer 24th but April 23rd.</p>
<p>You think it's the only nuance? Diving deeper...</p>
<p><strong>Nuance 2 - timezone of the hotel:</strong></p>
<p>Hotels are located in different timezones. In most cases they wouldn't necessarily match your timezone.</p>
<p>What if you are booking a hotel in Spain? The timezone of your hotel is GTM+1 / GMT+2. And your timezone is GMT+3. You are picking Date & Time. Which timezone does the freshly picked Date & Time belong to?</p>
<p>The ANSWER is:</p>
<p>By all means the freshly picked Date belongs to the timezone of the hotel.</p>
<p><strong>When you pick a hotel the page must take into account the timezone of the hotel and use it when converting date to UTC.</strong></p>
<p>What are our next steps? Well, it depends. The DatePicker I use is from ng-bootstrap and it produces the following object:</p>
<pre><code>{
"year": 2019,
"month": 4,
"day": 24
}
</code></pre>
<p><em>to keep it yet simpler I'm excluding the time part, so we only pick date - I'm hard-coding the time, so from now on it's 14:30:00</em> <code>moment([e.year, e.month - 1, e.day, 14, 30, 0])</code>.</p>
<p><strong>We need to pass a UTC date to the back-end</strong> - what should we do about it?</p>
<p>My workaround:</p>
<ol>
<li>produce a date using Moment.js</li>
<li>format it to exclude the timezone offset</li>
<li>convert it from GMT+1 / GMT+2 (the timezone of your hotel in Spain) to UTC</li>
<li>format it again to exclude the timezone offset</li>
</ol>
<p>code:</p>
<pre><code>let format = 'YYYY-MM-DDTHH:mm:ss';
let zone = "Europe/Madrid";
let initialDateString = moment([e.year, e.month - 1, e.day, 14, 30, 0]).format(format); // "2019-04-24T14:30:00"
let resultDateString = moment.tz(initialDateString , format, zone).utc().format(format); // results in "2019-04-24T12:30:00" - Spain is 2 hours ahead of UTC right now in April
</code></pre>
<p>So, the only remaining part is AJAX request and controller action invocation where the Booking record gets created.</p>
<p>You may be still wondering how come the time part of the Date being stored in the DB is <strong>12:30:00 and not 14:30:00</strong>. In our specs (see INITIAL INFO section above) it reads</p>
<blockquote>
<p>Check-In Date & Time: 24 Apr 2019 14:30:00 GMT+1 / GMT+2.</p>
</blockquote>
<p>The ANSWER is:</p>
<p>Relax, this is a <strong>UTC</strong> DateTime. When UTC clock hits <strong>12:30:00</strong> - the Spanish time is <strong>14:30:00</strong>.</p>
<p>Your next question might be:
If the time stored in the DB is 12:30:00 UTC how does the hotel staff know you are arriving at <strong>14:30:00</strong> ? The answer is in the next part.</p>
<hr>
<p><strong>PART 2 - HOTEL STAFF PAGE:</strong></p>
<p>Remember in the Part 1 we used the timezone of the hotel for date conversion? (Converting from Hotel's Timezone to UTC)</p>
<p>Right now we must consider user's local timezone - the hotel staff person opens browser, navigates to a web service and the bookings for their particular hotel are getting rendered on the page. Under each booking they can see the Check-In Date & Time.</p>
<p>What should we do with UTC date so it is displayed as GMT+1 / GMT+2 ?</p>
<p>The ANSWER is:</p>
<p>We must convert it to GMT+1 / GMT+2 which is obvious.</p>
<ol>
<li><p>back-end returns <strong>24 Apr 2019 12:30:00</strong></p></li>
<li><p>front-end converts it from UTC to GMT+1 / GMT+2</p></li>
</ol>
<p>Here's the bit which handles conversion:</p>
<pre><code>let fmt = 'YYYY-MM-DDTHH:mm:ss';
let zone = "Europe/Madrid";
let utc = moment.tz("2019-04-24T12:30:00",'UTC');
let spanishTime = moment.tz(utc.format(), zone).format(fmt);
</code></pre>
<hr>
<p><strong>CODE:</strong></p>
<p>So, I've revealed all of the JavaScript code involved.</p>
<p>You may be wondering what does the back-end code look like, right?</p>
<p>Like, it must be something tricky and smart... Or, whether it involves any timezone-related operations or any convoluted stuff.</p>
<p>Surprise!</p>
<pre><code>[HttpGet("[action]")]
public List<Booking> CheckBookings()
{
using (var db = new AppDbContext())
{
var booking = db.Bookings.ToList();
return booking;
}
}
[HttpPost("[action]")]
public bool BookHotel([FromBody] CheckIn input)
{
using (var db = new AppDbContext())
{
var booking = new Booking() { Name = "NAME", Date = input.Value };
db.Bookings.Add(booking);
db.SaveChanges();
}
return true;
}
</code></pre>
<p><em>we're not interested in anything except for dates, so I use hardcoded name...</em></p>
<hr>
<p><strong>I've heard about Noda Time library. A few people recommended it to me for this booking functionality. It does look great. But in all honesty I can't see where it may be applicable here.</strong></p>
<p><strong>The back-end deals with UTC dates only.
That is to say the back-end receives UTC dates from the front-end and sends UTC dates to it.</strong></p>
<p><strong>Looks like all we need is Moment.js - so I can't see where any other libraries may be of help.</strong></p>
| [] | [
{
"body": "<h2>Drop the timezones</h2>\n<p>As a learning exercise (dealing with timezones) I think you have picked the wrong application.</p>\n<h2>Date time as string</h2>\n<p>I suggest that you use a date time string with no time zone info rather than the UTC Unix tick. Standard format ISO 8601 using moment.js client side (browser ISO 8601 compliance is all over the place) to parse for the date picker, and format without timezone (offset zero "Z") for transport to the back-end</p>\n<p>The back-end (.net) supports ISO 8601. Parse the booking date time string to store, then send as a date time string using <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#the-round-trip-o-o-format-specifier\" rel=\"nofollow noreferrer\">round-trip format specifier</a> eg <code>bookingDate.ToString("o");</code></p>\n<h2>Why</h2>\n<p>Handing multiple timezones on the client will be problematic at best. You will need a robust library for the timezones. moment.js is not up to the job, its successor <a href=\"https://moment.github.io/luxon/\" rel=\"nofollow noreferrer\"><code>Luxon</code></a> will provide better timezone management but that comes with a hefty data overhead.</p>\n<p>All you want is a date time picker for the client to make a booking, for that I do not think the complication of juggling timezones is worth the effort when a local time string (location of hotel) will do the job.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T22:34:50.113",
"Id": "219280",
"ParentId": "219216",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219280",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T21:56:12.723",
"Id": "219216",
"Score": "0",
"Tags": [
"c#",
"javascript",
"datetime",
"ajax"
],
"Title": "Hotel Booking functionality - handling UTC dates & timezones"
} | 219216 |
<p>I have the following:</p>
<pre><code>public class Person{
public string FirstName {get; set;} = "";
public string MiddleName {get; set;} = "";
public string LastName {get; set;} = "";
public string Title {get; set;} = "";
}
public class Program
{
public static void Main()
{
var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
}
}
</code></pre>
<p>I am writing a service class that reports back a user's </p>
<ul>
<li>Full name (First + Middle + Last names)</li>
<li>Title + Full name</li>
<li>First name and last name </li>
</ul>
<p>Using dependency injection, I have the following:</p>
<p><strong>(1)</strong></p>
<pre><code>public class NameService{
private readonly Person _person;
public NameService(Person person){
_person = person;
}
public string GetFullName(){
var fullName = $"{_person.FirstName} {_person.MiddleName} {_person.LastName}";
return fullName;
}
public string GetFullNameWithTitle(){
var fullNameWithTitle = $"{_person.Title} {_person.FirstName} {_person.MiddleName} {_person.LastName}";
return fullNameWithTitle;
}
public string GetFirstLastName(){
var fullName = $"{_person.FirstName} {_person.LastName}";
return fullName;
}
}
</code></pre>
<p>Which I can use like this:</p>
<pre><code>var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
var service = new NameService(person);
var fullName = service.GetFullName();
</code></pre>
<p><strong>However</strong>, I can also define the service like this:</p>
<p><strong>(2)</strong></p>
<pre><code>public class NameService
{
public NameService(){}
public string GetFullName(Person person)
{
var fullName = $"{person.FirstName} {person.MiddleName} {person.LastName}";
return fullName;
}
public string GetFullNameWithTitle(Person person)
{
var fullNameWithTitle = $"{person.Title} {person.FirstName} {person.MiddleName} {person.LastName}";
return fullNameWithTitle;
}
public string GetFirstLastName(Person person)
{
var fullName = $"{person.FirstName} {person.LastName}";
return fullName;
}
}
</code></pre>
<p>And then get a person's full name like so:</p>
<pre><code> var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
var service = new NameService();
var fullName = service.GetFullName(person);
</code></pre>
<p>Which is the better approach? My thoughts:</p>
<p><strong>(1)</strong></p>
<p>Looks like the service is designed on a "per Person" basis. This means calling another person's full name will require instantiating a new service with a new Person argument (and that's okay).</p>
<p><strong>(2)</strong></p>
<p>This is a lightweight constructor that allows different Person object to be supplied into GetFullName(person) to allow different rendition of full name.</p>
<p>What other pros and cons can you think of?</p>
| [] | [
{
"body": "<p>There is no reason for DI here because <strong><code>Person</code> is not a service</strong>. It doesn't provide any functionality that you need to do other things. It's the data that the APIs are build for. </p>\n\n<p>This means that you should <strong>choose the 2nd version</strong> with their pure methods.</p>\n\n<hr>\n\n<p>However, there is a <strong>3rd option</strong>...</p>\n\n<p>You can split all three methods into their own services and have:</p>\n\n<pre><code>public class FullNameService : INameService { ... }\npublic class FullNameWithTitleService : INameService { ... }\npublic class FirstLastNameService : INameService { ... }\n</code></pre>\n\n<p>where all implement an interface like this one</p>\n\n<pre><code>public interface INameService\n{\n string CreateName(Person person);\n}\n</code></pre>\n\n<p>With such a design you would have even <strong>more freedom in adding and testing new services</strong> and they wouldn't affect each other.</p>\n\n<hr>\n\n<p>No matter which solution you pick, you should always have some abstraction for the service (<strong>abstract class</strong> or <strong>interface</strong>). Without abstraction DI is pretty pointless because you cannot easily exchange the service and use an improved, different or even a test version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:55:31.210",
"Id": "423522",
"Score": "1",
"body": "not all dependencies are services, primitives or POCOs can be dependencies too. https://blog.ploeh.dk/2012/07/02/PrimitiveDependencies/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:17:15.810",
"Id": "423530",
"Score": "0",
"body": "@AdrianIftode true, sometimes, very rarely they can be POCOs..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:21:56.843",
"Id": "423608",
"Score": "0",
"body": "That's a seriously informative article @AdrianIftode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:26:12.747",
"Id": "423609",
"Score": "0",
"body": "@t3chb0t - I find putting the contract in the constructor that a Person object is required to call GetFullName() appealing. When I used the term DI, in a way I was using it \"loosely\" to describe something is required for the service (as opposed to an external service is required)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T08:14:41.993",
"Id": "219241",
"ParentId": "219218",
"Score": "1"
}
},
{
"body": "<p>If you use second option you should probably declare methods as static. Since you dont have any \"data\" associated with NameService object instance(service).</p>\n\n<p>Like this:</p>\n\n<pre><code>public static string GetFullName(Person person)\n{\n var fullName = $\"{person.FirstName} {person.MiddleName} {person.LastName}\";\n return fullName;\n}\n</code></pre>\n\n<p>And then you can call... </p>\n\n<pre><code>NameService.GetFullName(person);\n</code></pre>\n\n<p>... without object initialazing - without line var service=new NameService(); </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:23:55.800",
"Id": "219272",
"ParentId": "219218",
"Score": "2"
}
},
{
"body": "<p>Another option:</p>\n\n<p>I always like to keep the methods and as close to the domain model as possible. This way you don't have to go looking for (or remember) a service which can do the naming for you.</p>\n\n<p>In this solution you'll see a GetName method on the Person class itself with an option to supply how you want to have the name formatted. </p>\n\n<p>Now after constructing a Person instance, you don't need to go looking for a piece of code which can do the naming for you, the method is there, you just need to go and find implementations of the INamingFormatter class and choose the one you need.</p>\n\n<pre><code>public class Person\n{\n public string FirstName { get; private set; }\n public string MiddleName { get; private set; }\n public string LastName { get; private set; }\n public string Title { get; private set; }\n\n public Person(string title, string firstName, string middleName, string lastName)\n {\n Title = title;\n FirstName = firstName;\n MiddleName = middleName;\n LastName = lastName;\n }\n\n public Person(string firstName, string middleName, string lastName)\n : this(null, firstName, middleName, lastName)\n { }\n\n public string GetName(INamingFormatter namingFormatter)\n {\n return namingFormatter.Format(this);\n }\n}\n</code></pre>\n\n<p>Interface:</p>\n\n<pre><code>public interface INamingFormatter\n{\n string Format(Person person);\n}\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>public class FullNameFormatter : INamingFormatter\n{\n public static FullNameFormatter Instance = new FullNameFormatter();\n\n public string Format(Person person) => $\"{person.FirstName} {person.MiddleName} {person.LastName}\";\n}\n</code></pre>\n\n<p>Call:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var person = new Person(\"Mr\", \"Danial\", \"W\", \"Craig\");\n\n var name = person.GetName(FullNameFormatter.Instance);\n\n Console.WriteLine(name);\n\n Console.WriteLine(\"Hello World!\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:46:45.913",
"Id": "423660",
"Score": "0",
"body": "Thanks for your thoughts. I'm more keen to separate it out in view of `Single Responsibility Principle`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T06:02:11.347",
"Id": "423825",
"Score": "0",
"body": "But putting it in a separate view in favor of SRP affects the Cohesion (https://softwareengineering.stackexchange.com/questions/163090/what-is-the-meaning-of-high-cohesion) of the class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T12:09:42.423",
"Id": "219305",
"ParentId": "219218",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T23:19:10.223",
"Id": "219218",
"Score": "4",
"Tags": [
"c#",
"dependency-injection"
],
"Title": "Dependency injection in constructor vs Supplying argument in utility functions"
} | 219218 |
<p>I am currently working on a game, and I get the configuration in an .ini file, and I get information with this library <a href="https://github.com/benhoyt/inih" rel="nofollow noreferrer">https://github.com/benhoyt/inih</a> I would like to improve the readability / performance of this code, as I do not know much about good practices.</p>
<pre><code>include "project.h"
// typedef struct s_server_conf {
// const char *ip;
// unsigned int port;
// } t_server_conf;
// typedef struct s_db_conf {
// const char *host;
// const char *user;
// const char *passwd;
// const char *db;
// unsigned int port;
// } t_db_conf;
// typedef struct s_conf {
// t_server_conf server;
// t_db_conf conf;
// } t_conf;
static int parse_server(t_conf *conf, const char *name, const char *value)
{
# define MATCH(n) (strcmp(name, n) == 0)
if (MATCH("ip"))
conf->server->ip = strdup(value);
else if (MATCH("port"))
conf->server->port = atoi(value);
else
return (0);
return (1);
}
static int parse_database(t_conf *conf, const char *name, const char *value)
{
# define MATCH_NAME(n) (strcmp(name, n) == 0)
if (MATCH_NAME("host"))
conf->db->host = (strdup(value));
else if (MATCH_NAME("user"))
conf->db->user = (strdup(value));
else if (MATCH_NAME("passwd"))
conf->db->passwd = (strdup(value));
else
return (0);
return (1);
}
static int handler(void *conf, const char *section, const char *name, const char *value)
{
# define MATCH_SECTION(s) (strcmp(section, s) == 0)
printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section)
;
if (MATCH_SECTION("database"))
return (parse_database((t_conf*)conf, name, value));
if (MATCH_SECTION("server"))
return (parse_server((t_conf*)conf, name, value));
return (0);
}
void clear_conf(t_conf *conf)
{
if (conf->db)
free(conf->db);
if (conf->server)
free(conf->server);
free(conf);
}
static t_conf *create_conf(void)
{
t_conf *conf;
if (!(conf = (t_conf*)malloc(sizeof(t_conf))))
return (NULL);
memset(conf, '\0', sizeof(t_conf));
if (!(conf->db = (t_db_conf*)malloc(sizeof(t_db_conf))))
{
clear_conf(conf);
return (NULL);
}
conf->db->port = 3306;
if (!(conf->server = (t_server_conf*)malloc(sizeof(t_server_conf))))
{
clear_conf(conf);
return (NULL);
}
return (conf);
}
t_conf *get_conf(void)
{
t_conf *conf;
if (!(conf = create_conf()))
return (NULL);
if (ini_parse("settings.ini", handler, conf) < 0)
{
printf("Unable to load configuration\n");
exit (1);
}
return (conf);
}
</code></pre>
| [] | [
{
"body": "<p><strong>Design</strong></p>\n\n<p>Rather than bury a magic filename, consider passing it in.</p>\n\n<pre><code>//t_conf *get_conf(void) {\n// ... \n// if (ini_parse(\"settings.ini\", handler, conf) < 0)\n\nt_conf *get_conf(const char *ini_file_name) {\n ... \n if (ini_parse(ini_file_name, handler, conf) < 0)\n</code></pre>\n\n<p>Maybe add before the <code>if()</code></p>\n\n<pre><code> if (ini_file_name == NULL) {\n ini_file_name = \"settings.ini\";\n }\n</code></pre>\n\n<p><strong>Devoid of overall comments</strong></p>\n\n<p>Consider comments to at least convey the coding goals.</p>\n\n<p><strong>Allocate to the size of the de-referenced object</strong></p>\n\n<p>... rather than allocate to the size of the type - easier to code right, review and maintain. Cast not needed.</p>\n\n<pre><code>//if (!(conf = (t_conf*)malloc(sizeof(t_conf))))\n// return (NULL);\nconf = malloc(sizeof *conf);\nif (conf == NULL) {\n return NULL;\n}\n\n// like-wise\n// memset(conf, '\\0', sizeof(t_conf));\nmemset(conf, 0, sizeof *conf);\n</code></pre>\n\n<p><strong>Use auto formatting</strong></p>\n\n<p>Life is too short for manual formatting. Find and use an auto formatter - customized as needed.</p>\n\n<p><strong>Comments of typedefs not needed</strong></p>\n\n<p>As is now, this code has comments that is not required to match what is truly in <code>\"project.h\"</code> and as time goes on, can diverge. For code posting here, post a portion of <code>\"project.h\"</code> instead.</p>\n\n<p><strong>Invalid code</strong></p>\n\n<p><code>include \"project.h\"</code> should be <code>#include \"project.h\"</code></p>\n\n<p><strong>Hiding objects here is bad</strong></p>\n\n<p><code># define MATCH(n) (strcmp(name, n) == 0)</code> brings in <code>name</code>, but not obvious from the call <code>if (MATCH(\"ip\"))</code>.</p>\n\n<p>Alternative:</p>\n\n<pre><code>static bool streq(const char *a, const char *b) {\n return strcmp(a,b) == 0;\n}\n...\nif (streq(name, \"ip\"))\n</code></pre>\n\n<p><strong>Naked magic number</strong></p>\n\n<p>Buried in code is </p>\n\n<pre><code>conf->db->port = 3306;\n</code></pre>\n\n<p>Better to have</p>\n\n<pre><code>// near top of code\n#define PORT_DEFAULT 3306\n\n// later on\nconf->db->port = PORT_DEFAULT;\n</code></pre>\n\n<p><strong>Unneeded <code>if</code></strong></p>\n\n<p>Just call <code>free()</code>. <code>free(NULL)</code> is OK.</p>\n\n<pre><code>//if (conf->db)\n// free(conf->db);\nfree(conf->db);\n</code></pre>\n\n<p>Like <code>free()</code>, I'd expect <code>clear_conf(NULL)</code> to not error</p>\n\n<pre><code>void clear_conf(t_conf *conf) {\n if (conf) { // add \n</code></pre>\n\n<p><strong>() not needed in <code>return</code> and others</strong></p>\n\n<p>Many places</p>\n\n<pre><code>// return (conf);\nreturn conf;\n\n// conf->db->host = (strdup(value));\nconf->db->host = strdup(value);\n</code></pre>\n\n<p><strong>Non-standard C</strong></p>\n\n<p>Note: <code>strdup()</code> is not standard, yet ubiquitous.</p>\n\n<p><strong>Missing <code>#include <></code></strong></p>\n\n<p>Do not rely on \"project.h\" to provide them unless that is clearly a project rule.</p>\n\n<p><strong><code>NULL</code> as <code>name</code></strong></p>\n\n<p>Given the potential generic use of <code>handler</code>, I'd guard against <code>NULL</code>.</p>\n\n<pre><code>// printf(\"Le nom du champ est %s, la valeur est %s (La section est %s)\\n\", name, value, section);\nif (name === NULL || value == NULL || section == NULL) {\n tbd();\n} else {\n printf(\"Le nom du champ est %s, la valeur est %s (La section est %s)\\n\", name, value, section);\n}\n</code></pre>\n\n<p>Further I'd bracket such strings to help detect leading/trailing white spaces in them</p>\n\n<pre><code> printf(\"Le nom du champ est \\\"%s\\\", la valeur est \\\"%s\\\" (La section est \\\"%s\\\")\\n\",\n name, value, section);\n</code></pre>\n\n<p><strong>Lack of error checking</strong></p>\n\n<pre><code>// what if `value` is \"\", \"abc\", \"123xyz\", \"12345678901234567890\", ...?\nconf->server->port = atoi(value);\n\n// what if allocation returns NULL? \nconf->server->ip = strdup(value);\n</code></pre>\n\n<p><strong>Respect presentation width</strong></p>\n\n<pre><code> printf(\"Le nom du champ est %s, la valeur est %s (La section est %s)\\n\", name, value, section)\n;\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code> printf(\"Le nom du champ est %s, la valeur est %s (La section est %s)\\n\",\n name, value, section);\n</code></pre>\n\n<p>Another reason for an auto formatter.</p>\n\n<p><strong>Curious dual language</strong></p>\n\n<p>I'd expect one.</p>\n\n<pre><code>printf(\"Le nom du champ est %s, la valeur est %s (La section est %s)\\n\", ...\nprintf(\"Unable to load configuration\\n\");\n</code></pre>\n\n<p><strong>Conversion changes sign-ness</strong></p>\n\n<pre><code>unsigned port;\n...\nconf->server->port = atoi(value);\n</code></pre>\n\n<p>Perhaps a helper function</p>\n\n<pre><code>// return error status\nbool to_unsigned(unsigned *u, const char *s) {\n if (s == NULL) {\n return true;\n }\n char *endptr;\n errno = 0;\n unsigned long = strtoul(s, &endptr, 10); \n if (errno || s == endptr || *endptr || value > UINT_MAX) {\n return true;\n }\n\n if (u) {\n *u = (unsigned) value;\n }\n return false;\n}\n\nif (to_unsigned(&conf->server->port, value)) {\n hanlde_oops();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T05:56:56.447",
"Id": "219620",
"ParentId": "219219",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T23:52:40.333",
"Id": "219219",
"Score": "1",
"Tags": [
"c",
"configuration"
],
"Title": "INI File configuration handler"
} | 219219 |
<p>I've always used <code>fgets</code> to read a file. However, I want to read a file that may have embedded <code>\0</code>. I thought of using <code>ftell</code> to query the size, but it doesn't seem to work on all files.</p>
<p>I've got a test file,</p>
<pre><code>31 32 33 00 34 35 36 0A E2 82 AC 0D 0A 61
</code></pre>
<p>Here is my <code>fgets</code>.</p>
<pre><code>#include <stdlib.h> /* EXIT */
#include <stdio.h> /* printf perror fputc fread */
#include <string.h> /* strlen */
#include <errno.h> /* errno */
#include <assert.h> /* assert */
int main(void) {
char file[1000], *f = file, *a;
const int granularity = 80;
int is_done = 0;
for( ; ; ) {
/* Fail when contents bigger than the size;
would be a good spot to use realloc. */
if(granularity > sizeof file - (f - file))
{ errno = ERANGE; break; }
if(!fgets(f, granularity, stdin))
{ if(ferror(stdin)) break; is_done = 1; break; }
f += strlen(f);
}
for(a = file; a < f; a++) printf("%02hhX ", *a);
fputc('\n', stdout);
return is_done ? EXIT_SUCCESS : (perror("stdin"), EXIT_FAILURE);
}
</code></pre>
<p>Running this, (I'm on a UNIX-like machine,)</p>
<pre><code>$ bin/fgets < test
31 32 33 E2 82 AC 0D 0A 61
</code></pre>
<p>Here is my <code>fread</code>.</p>
<pre><code>#include <stdlib.h> /* EXIT */
#include <stdio.h> /* printf perror fputc fread */
#include <errno.h> /* errno */
#include <assert.h> /* assert */
int main(void) {
char file[1000], *f = file, *a;
const int granularity = 80;
size_t read;
int is_done = 0;
for( ; ; ) {
if(granularity > sizeof file - (f - file))
{ errno = ERANGE; break; }
read = fread(f, 1, granularity, stdin);
if(ferror(stdin)) break;
assert(read >= 0 && read <= granularity);
f += read;
if(read != granularity) { is_done = 1; break; }
}
for(a = file; a < f; a++) printf("%02hhX ", *a);
fputc('\n', stdout);
return is_done ? EXIT_SUCCESS : (perror("stdin"), EXIT_FAILURE);
}
</code></pre>
<p>Running this,</p>
<pre><code>$ bin/fread < test
31 32 33 00 34 35 36 0A E2 82 AC 0D 0A 61
</code></pre>
<p>I would like to know if this is pedantically correct and how I improve.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T01:53:40.123",
"Id": "423448",
"Score": "2",
"body": "If a file contains NULs, then it would usually be called a binary file rather than a text file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:18:44.640",
"Id": "423515",
"Score": "0",
"body": "I thought that depended on what encoding it's in. Would UTF-8 be a potentially binary file, then? https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8 Is there an unambiguous definition of text/binary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:20:37.387",
"Id": "423516",
"Score": "0",
"body": "UTF-8 does not have NUL bytes. UTF-16 would."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:09:05.493",
"Id": "423540",
"Score": "2",
"body": "What is the point of `granularity` vs. just using `fread(fine, 1, sizeof file, stdin)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:21:39.563",
"Id": "423545",
"Score": "0",
"body": "@200_success Although uncommon to have a _null character_ in a text file, C's _read_file_ does not exclude them and robust code does have have UB when reading them. Neil's goal is a good one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:27:10.627",
"Id": "423546",
"Score": "0",
"body": "@chux I have no objection to the goal or the task. Just making a remark about the terminology."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:19:52.917",
"Id": "423553",
"Score": "0",
"body": "@chux This would have been more obvious, but I didn't want to use `sizeof file` because this was a MCVE of a dynamic array."
}
] | [
{
"body": "<p>I find your code hard to read, for the following reasons:</p>\n\n<ul>\n<li>the variable <code>file</code> is not really a file but a buffer</li>\n<li>the variable <code>f</code> (which usually stands for file) is a pointer into that buffer</li>\n<li>the variable <code>a</code> has a name which does not convey any meaning at all</li>\n<li>if the first <code>if</code> statement you indent the brace in the next line, and in the very last <code>if</code> statement the body is in the same line</li>\n<li>there are spaces missing in the code at places where I expect them, such as after an <code>if</code> or <code>for</code></li>\n<li>the forever loop is usually written as <code>for (;;)</code>, not <code>for( ; ; )</code></li>\n<li>the main block of the code is inside the <code>for</code> loop, and there's not a single empty line in that part. This suggests that the whole block is doing a single thing with no possible interruption or logical break</li>\n<li>the comma operator is generally frowned upon</li>\n<li><code>is_done</code> is not really about the work being done, it's more about being successful</li>\n</ul>\n\n<p>Because of all the above reasons, I would write the code differently:</p>\n\n<pre><code>#include <errno.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(void) {\n char buf[1000];\n size_t buflen = 0;\n const size_t granularity = 80;\n\n while (true) {\n if (granularity > sizeof buf - buflen) {\n errno = ERANGE;\n break;\n }\n\n size_t nread = fread(buf + buflen, 1, granularity, stdin);\n if (ferror(stdin))\n break;\n\n buflen += nread;\n }\n\n for (size_t i = 0; i < buflen; i++)\n printf(\"%02hhX \", buf[i]);\n fputc('\\n', stdout);\n\n if (ferror(stdin)) {\n perror(\"stdin\");\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n\n<p>And here is what I changed:</p>\n\n<ul>\n<li>I renamed all variables to match their purpose</li>\n<li>I replaced the various pointers into the buffer with indexes</li>\n<li>I removed the <code>is_done</code> variable since the program should not print an error just because the file is a multiple of 80 bytes</li>\n<li>I moved the variable <code>a</code> to a smaller scope by declaring it inside the <code>for</code> loop where it is used; I also renamed it to <code>i</code>, since it is now an index instead of a pointer</li>\n<li>I replaced the comma operator with an <code>if</code> statement, since that is the form that is commonly used</li>\n<li>I included <code><stdbool.h></code> to have a boolean type and the constants <code>true</code> and <code>false</code></li>\n<li>I replaced <code>for (;;)</code> with <code>while (true)</code>, which is less magic</li>\n<li>I sorted the included headers alphabetically since for headers from the C standard library, the order doesn't matter</li>\n<li>I renamed the variable <code>read</code> to <code>nread</code>, to avoid possible conflicts with the POSIX function of the same name</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:23:11.213",
"Id": "423506",
"Score": "0",
"body": "This is an excellent review. `ssize_t` and `bool` are C99, but agree. I'm more interested in is how your control flow differs from mine; https://pubs.opengroup.org/onlinepubs/007904875/functions/fread.html says nothing about returning a negative value, though in practice that's what it does. Could you elaborate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:28:30.080",
"Id": "423507",
"Score": "0",
"body": "Oops, I must have remembered something wrong then. Sorry. I fixed my review. Thanks for notifying me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:10:30.230",
"Id": "423514",
"Score": "0",
"body": "No, I thought so, too; in practice a negative value indicates error, but upon reading the spec carefully, I see no indication, unless it's in one of the links. Usually I use `fgets`. If I'm understanding this, you could have a partial read and `errno` would be set, it would return a positive value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:55:20.670",
"Id": "423521",
"Score": "0",
"body": "@NeilEdelman Yep, that's my interpretation, too, and that of many others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:58:02.757",
"Id": "423538",
"Score": "3",
"body": "@NeilEdelman \"`ssize_t` and `bool` are C99\" --> `ssize_t` is not C99. it is not part of any C standard, yet common *nix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T15:22:34.850",
"Id": "423633",
"Score": "2",
"body": "The only part I would disagree with is replacing `for(;;)` (read: forever), as that's very idiomatic."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T02:06:32.787",
"Id": "219224",
"ParentId": "219220",
"Score": "6"
}
},
{
"body": "<p>I would normally use ftell and allocate the buffer size needed, but I assume that you have some non-standard Unix Distro with specific environment or compiler settings, if you say that ftell doesnt work sometimes.</p>\n\n<p>I provide an example with fix buffer size, just for demonstration.\nBuffer size reallocation and more error checking would probably be needed for production code.</p>\n\n<p>Regarding code, generally, I always preferr staying generic and grouping code in functions.\nIt's not only making code easier to read, but also makes a thinking process easier. And there's a reusabillity point too, of course.</p>\n\n<p>So this would be my refactoring - suggestion (I didn't pay much attention to your error codes. And it could be that you have to put declarations on top, if you are using some older C compiler like C89 etc.):</p>\n\n<pre><code>#include <stdio.h>\n\n#define GRANULARITY 80\n#define MIN(a, b) (((a) < (b)) ? (a) : (b))\n\nsize_t read_file(FILE* fd, // file descriptor\n char *buf, // buffer\n size_t size); // buffer size\n\nint main(int argc, char* argv[])\n{\n char buf[1000];\n size_t num_read = read_file(stdin, buf, sizeof(buf));\n\n if (num_read > 0)\n {\n for (int i = 0; i < sizeof(buf); ++i)\n printf(\"%02hhX \", buf[i]);\n }\n else if (errno == ERANGE)\n {\n // error - there are more bytes to read, handle it\n } \n else if (ferror(fd)) \n {\n // stream error - handle it\n }\n\n return 0;\n}\n\nsize_t read_file(FILE* fd,\n char *buf,\n size_t size)\n{\n size_t num_read = 0;\n char *pos = buf;\n size_t n = 0;\n\n while ( (n = fread(pos, 1, MIN(GRANULARITY, buf+size-pos), fd)) > 0 )\n {\n num_read += n;\n pos += n;\n }\n\n if (!feof(fd))\n errno = ERANGE; // buf too small - there are more bytes to read\n\n return num_read;\n</code></pre>\n\n<p><strong>Edit:</strong>\nAfter reading some comments: changed the interface return type from <strong>ssize_t</strong> to <strong>size_t</strong> and moved the error-code checking responsibility to the caller.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:58:25.127",
"Id": "423513",
"Score": "0",
"body": "That's a good generalisation. If you set `errno` to eg, `ERANGE`, and always returned -1, then the code would have one less level of errors to check for. My intention was to write it to work on any compliant C90 system, so I've been careful what assumptions I'm making, viz http://c-faq.com/osdep/filesize.html and http://c-faq.com/stdio/textvsbinary.html."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:13:11.813",
"Id": "423542",
"Score": "1",
"body": "When reading _large_ files that can fit in `size_t`, `num_read += n;` can readily exceed `ssize_t` range. Recommend staying with `size_t` and not convolute with `ssize_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:15:29.167",
"Id": "423543",
"Score": "1",
"body": "Pedantically `if (ferror(fd))` can be true even with no read errors here, as `ferror()` can be true before `read_file()` is called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:14:17.830",
"Id": "423595",
"Score": "1",
"body": "@chux: yes, that's good point. have considered it in the edit. also regarding ferror(fd) checking - it's the responsibility of the caller now - at my opinion, that would be more correct regarding interface semantics. the caller should check ferror(fd) before and after calling the read_file funciton. this also very similar with the standard library fread()."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T05:30:04.780",
"Id": "219235",
"ParentId": "219220",
"Score": "2"
}
},
{
"body": "<p>Roland Illig provided an excellent review; there are a couple of points I'd like to add:</p>\n\n<p>The standard header file <code><stdio.h></code> defines the macro/constant <code>BUFSIZ</code>. This macro was developed primarily for input and output buffers. In the original C it was defined as 1024, but now it varies from system to system, probably based on the file system blocking size.</p>\n\n<p>It might have been better to define to define the character array using <code>BUFSIZ</code>.</p>\n\n<p>The <code>assert()</code> macro is generally useful as a debugging tool and not included in production code. It will be <a href=\"http://www.cplusplus.com/reference/cassert/assert/\" rel=\"nofollow noreferrer\">optimized out of the code if the macro <code>NDEBUG</code> is defined</a>.</p>\n\n<p>The first time I read through the code, I missed all of the <code>break;</code> statements; it might be better if each statement is on a separate line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:24:46.293",
"Id": "423654",
"Score": "0",
"body": "In your opinion, is not `ferror` an absolute guarantee that the return value is between `[0, read]`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T12:23:59.310",
"Id": "219247",
"ParentId": "219220",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>Reading a text file that may have embedded nulls</p>\n</blockquote>\n\n<p><code>fgets()</code> is simply not the best tool to to do this. </p>\n\n<p>Code that well handles text files with <em>null characters</em> employs *nix <code>getline()</code> or similar functions.</p>\n\n<pre><code>#include <stdlib.h>\n#include <stdio.h>\n\nint main(void) {\n size_t sz = 0;\n char *buf = NULL;\n unsigned long long line = 0;\n ssize_t count;\n char ch = '\\n';\n while ((count = getline(&buf, &sz, stdin)) > 0) {\n printf(\"%llu\", ++line);\n for (ssize_t i = 0; i < count; i++) {\n ch = buf[i];\n printf(\" %02hhX:\", ch);\n }\n }\n if (ch != '\\n') {\n printf(\"\\n\");\n }\n free(buf);\n if (ferror(stdin)) {\n perror(\"stdin\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:42:39.690",
"Id": "423558",
"Score": "1",
"body": "If you're using `GNU C99`, I think this is the way to go."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:40:13.493",
"Id": "219276",
"ParentId": "219220",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219224",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T00:15:06.390",
"Id": "219220",
"Score": "4",
"Tags": [
"c",
"file",
"null",
"c89"
],
"Title": "Reading a text file that may have embedded nulls"
} | 219220 |
<p>I have an initial pool of subjects, then I need to apply a set of general criteria to retain a smaller subset (SS1) of subjects. Then I need to divide this smaller subset (SS1) into yet finer subsets (SS1-A, SS1-B and the rest). A specific set of criteria will be applied to SS1 to obtain the SS1-A, while another set of specific criteria will be applied to obtain the SS1-B, and the rest will be discarded. The set of criteria/filter will need to be flexible, I would like to add, remove, or combine filters for testing and development, as well as for further clients' requests.</p>
<p>I created a small structure code below to help me understand and test the implementation of template method and filter methods. I use a list and some filter instead of actual subject pool, but the idea is similar that the list items can be seen as subjects with different attributes.</p>
<pre><code>from abc import ABC, abstractmethod
class DataProcessing(ABC):
def __init__(self, my_list):
self.my_list = my_list
def data_processing_steps(self):
self.remove_duplicate()
self.general_filtering()
self.subject_specific_filtering()
self.return_list()
def remove_duplicate(self):
self.my_list = set(list(self.my_list))
@abstractmethod
def general_filtering(self): pass
def subject_specific_filtering(self): pass
def return_list(self):
return self.my_list
class DataProcessing_Project1(DataProcessing):
def general_filtering(self):
maxfilter_obj = MaxFilter()
minfilter_obj = MinFilter()
CombinedFilter_obj = CombinedFilter(maxfilter_obj, minfilter_obj)
self.my_list = CombinedFilter_obj.filter(self.my_list)
class DataProcessing_Project1_SubjectA(DataProcessing_Project1):
def subject_specific_filtering(self):
twentythreefilter_obj = TwentyThreeFilter()
self.my_list = twentythreefilter_obj.filter(self.my_list)
class DataProcessing_Project1_SubjectB(DataProcessing_Project1): pass
class Criteria():
@abstractmethod
def filter(self, request):
raise NotImplementedError('Should have implemented this.')
class CombinedFilter(Criteria):
def __init__(self, filter1, filter2):
self.filter1 = filter1
self.filter2 = filter2
def filter(self, this_list):
filteredList1 = self.filter1.filter(this_list)
filteredList2 = self.filter2.filter(filteredList1)
return filteredList2
class MaxFilter(Criteria):
def __init__(self, max_val=100):
self.max_val = max_val
def filter(self, this_list):
filteredList = []
for item in this_list:
if item <= self.max_val:
filteredList.append(item)
return filteredList
class MinFilter(Criteria):
def __init__(self, min_val=10):
self.min_val = min_val
def filter(self, this_list):
filteredList = []
for item in this_list:
if item >= self.min_val:
filteredList.append(item)
return filteredList
class TwentyThreeFilter(Criteria):
def __init__(self): pass
def filter(self, this_list):
filteredList = []
for item in this_list:
if item != 23:
filteredList.append(item)
return filteredList
this_list = [1, 2, 23, 4, 34, 456, 234, 23, 3457, 5, 2]
ob = MaxFilter()
this_list2 = ob.filter(this_list)
print(this_list2)
ob2 = MinFilter()
this_list3 = ob2.filter(this_list2)
print(this_list3)
ob3 = CombinedFilter(ob, ob2)
this_list4 = ob3.filter(this_list)
print(this_list4)
ob4 = DataProcessing_Project1(my_list=this_list)
ob4.data_processing_steps()
print(ob4.return_list())
ob5 = DataProcessing_Project1_SubjectA(my_list=this_list)
ob5.data_processing_steps()
print(ob5.return_list())
# Error
twentythreefilter_obj = TwentyThreeFilter()
ob6 = CombinedFilter(ob, ob2, twentythreefilter_obj)
this_list4 = ob3.filter(this_list)
print(this_list4)
</code></pre>
<p>I am fairly new to design pattern, I wonder if this is implemented correctly, and if there are areas that can be improved?</p>
<p>Also for <code>ob6</code>, I would like to add another filter as a parameter for <code>combinedFilter()</code>, but I am not sure how to set the <code>__init__</code> and <code>filter()</code> within the <code>ComninedFilter</code> class so that it can accommodate the addition of any number of new filters.</p>
| [] | [
{
"body": "<p>Your approach is suitable for a language like Java. But in Python? <a href=\"https://pyvideo.org/pycon-us-2012/stop-writing-classes.html\" rel=\"noreferrer\">Stop writing classes!</a> This is especially true for your task, where much of the code consists of do-nothing placeholders (in <b>bold</b> below) just to allow functionality to be implemented by subclasses.</p>\n\n<pre><b>from abc import ABC, abstractmethod\n\nclass DataProcessing(ABC):\n def __init__(self, my_list):\n self.my_list = my_list\n\n def data_processing_steps(self):</b>\n self.remove_duplicate()\n <b>self.general_filtering()\n self.subject_specific_filtering()\n self.return_list()</b>\n\n def remove_duplicate(self):\n self.my_list = set(list(self.my_list))\n\n <b>@abstractmethod\n def general_filtering(self): pass\n\n def subject_specific_filtering(self): pass\n\n def return_list(self):\n return self.my_list</b>\n\nclass DataProcessing_Project1(DataProcessing):\n def general_filtering(self):\n maxfilter_obj = MaxFilter()\n minfilter_obj = MinFilter()\n CombinedFilter_obj = CombinedFilter(maxfilter_obj, minfilter_obj)\n self.my_list = CombinedFilter_obj.filter(self.my_list)\n\nclass DataProcessing_Project1_SubjectA(DataProcessing_Project1):\n def subject_specific_filtering(self):\n twentythreefilter_obj = TwentyThreeFilter()\n self.my_list = twentythreefilter_obj.filter(self.my_list)\n\nclass DataProcessing_Project1_SubjectB(DataProcessing_Project1): pass\n</pre>\n\n<p>Furthermore, it's unnatural to have <code>my_list</code> be part of the state of the <code>DataProcessing</code> instance, and it's especially awkward to have to retrieve the result by calling <code>.return_list()</code>.</p>\n\n<p>Note that in</p>\n\n<blockquote>\n<pre><code>def remove_duplicate(self):\n self.my_list = set(list(self.my_list))\n</code></pre>\n</blockquote>\n\n<p>… <code>my_list</code> temporarily becomes a <code>set</code> rather than a <code>list</code>. You should have written <code>self.my_list = list(set(self.my_list))</code> instead.</p>\n\n<h2>Suggested solution</h2>\n\n<p>This task is more naturally suited to functional programming. Each filter can be a function that accepts an iterable and returns an iterable. You can then easily combine filters through <a href=\"https://en.wikipedia.org/wiki/Function_composition_%28computer_science%29\" rel=\"noreferrer\">function composition</a>.</p>\n\n<p>As a bonus, you can take advantage of <strong>default parameter values</strong> in Python to supply generic processing steps. Then, just <strong>use <code>None</code> to indicate that an absent processing step</strong>.</p>\n\n<pre><code>######################################################################\n# Primitive filters\n######################################################################\ndef deduplicator():\n return lambda iterable: list(set(iterable))\n\ndef at_least(threshold=10):\n return lambda iterable: [n for n in iterable if n >= threshold]\n\ndef at_most(threshold=100):\n return lambda iterable: [n for n in iterable if n <= threshold]\n\ndef is_not(bad_value):\n return lambda iterable: [n for n in iterable if n != bad_value]\n\n######################################################################\n# Higher-order filters\n######################################################################\ndef compose(*filters):\n def composed(iterable):\n for f in filters:\n if f is not None:\n iterable = f(iterable)\n return iterable\n return composed\n\ndef data_processing(\n deduplicate=deduplicator(),\n general=compose(at_least(), at_most()),\n specific=None,\n ):\n return compose(deduplicate, general, specific)\n\n######################################################################\n# Demonstration\n######################################################################\nthis_list = [1, 2, 23, 4, 34, 456, 234, 23, 3457, 5, 2]\n\nob = at_most()\nthis_list2 = ob(this_list)\nprint(this_list2) # [1, 2, 23, 4, 34, 23, 5, 2]\n\nob2 = at_least()\nthis_list3 = ob2(this_list2)\nprint(this_list3) # [23, 34, 23]\n\nob3 = compose(ob, ob2)\nthis_list4 = ob3(this_list)\nprint(this_list4) # [23, 34, 23]\n\nob4 = data_processing()\nprint(ob4(this_list)) # [34, 23]\n\nob5 = data_processing(specific=is_not(23))\nprint(ob5(this_list)) # [34]\n\nob6 = compose(ob, ob2, is_not(23))\nprint(ob6(this_list)) # [34]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:49:28.887",
"Id": "423491",
"Score": "0",
"body": "Is your don't write class comment pointing to my boilerplate code above, or in general? I see that many design patterns (ie abstract factory - https://sourcemaking.com/design_patterns/abstract_factory/python/1) use a lot of empty classes (with pass) as interface, does it mean refactoring code with these design patterns are generally bad? My code above was a subsequent question that I tried following `Girish`'s comments (https://stackoverflow.com/questions/55858784/how-to-apply-template-method-pattern-in-python-data-science-process-while-not-kn/55860141#55860141)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:13:19.943",
"Id": "423495",
"Score": "0",
"body": "Also, my above code is basically a test code. My data will be as Pandas df which I will be using different var column as attributes to filter subjects. Would the iterable suggestion still apply? If so, do I treat each row/subject as an iterable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:13:32.793",
"Id": "423496",
"Score": "1",
"body": "A lot of \"design patterns\" are just workarounds for limitations of straitjacket OOP languages like Java or C++. Watch the video."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:15:09.197",
"Id": "423497",
"Score": "1",
"body": "We encourage users to post real code for review, because we can't review what you had in mind but decided not to show. (See [ask].) If you have another question, then post it as a separate follow-up question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T04:04:24.507",
"Id": "423671",
"Score": "0",
"body": "I've been on SE for 7 years and it's never occurred to me to put code in a `<pre>` so you can bold important sections. +1 Fantastic approach! I'm 100% stealing this."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T05:29:04.183",
"Id": "219234",
"ParentId": "219228",
"Score": "12"
}
},
{
"body": "<p>I think you would benefit from viewing your processing steps and criteria as <em>filters</em> that operate on <a href=\"https://docs.python.org/3/library/stdtypes.html#iterator-types\" rel=\"nofollow noreferrer\">iterables</a>.</p>\n\n<p>Suppose you have a sequence, like a <code>set</code> or a <code>list</code> or a <code>tuple</code>. You could iterate over that sequence like so:</p>\n\n<pre><code>for item in sequence:\n pass\n</code></pre>\n\n<p>Now suppose you use the <a href=\"https://docs.python.org/3/library/functions.html?highlight=iter%20built#iter\" rel=\"nofollow noreferrer\"><code>iter()</code></a> built-in function to create an iterator, instead. Now you can pass around that iterator, and even extract values from it:</p>\n\n<pre><code>it = iter(sequence)\nfirst_item = next(it)\nprint_remaining_items(it)\n</code></pre>\n\n<p>Finally, suppose you take advantage of <a href=\"https://docs.python.org/3/glossary.html#term-generator\" rel=\"nofollow noreferrer\">generator functions</a> and avoid collecting and returning entire lists. You can iterate over the elements of an iterable, inspect the individual values, and yield the ones you choose:</p>\n\n<pre><code>def generator(it):\n for item in it:\n if choose(item):\n yield item\n</code></pre>\n\n<p>This allows you to process one iterable, and iterate over the results of your function, which makes it another iterable. </p>\n\n<p>Thus, you can build a \"stack\" of iterables, with your initial sequence (or perhaps just an iterable) at the bottom, and some generator function at each higher level:</p>\n\n<pre><code>ibl = sequence\nst1 = generator(ibl)\nst2 = generator(st1)\nst3 = generator(st2)\n\nfor item in st3:\n print(item) # Will print chosen items from sequence\n</code></pre>\n\n<p>So how would this work in practice?</p>\n\n<p>Let's start with a simple use case: you have an iterable, and you wish to filter it using one or more simple conditionals.</p>\n\n<pre><code>class FilteredData:\n def __init__(self, ibl):\n self.iterable = ibl\n self.condition = self.yes\n\n def __iter__(self):\n for item in self.ibl:\n if self.condition(item):\n yield item\n\n def yes(self, item):\n return True\n\nobj = FilteredData([1,2,3,4])\n\nfor item in obj:\n print(item) # 1, 2, 3, 4\n\nobj.condition = lambda item: item % 2 == 0\n\nfor item in obj:\n print(item) # 2, 4\n</code></pre>\n\n<p>How can we combine multiple conditions? By \"stacking\" objects. Wrap one iterable item inside another, and you \"compose\" the filters:</p>\n\n<pre><code>obj = FilteredData([1,2,3,4])\nobj.condition = lambda item: item % 2 == 0\nobj2 = FilteredData(obj)\nobj2.condition = lambda item: item < 3\n\nfor item in obj2:\n print(item) # 2\n</code></pre>\n\n<p>Obviously, you can make things more complex. I'd suggest that you not do that until you establish a clear need.</p>\n\n<p>For example, you could pass in the lambda as part of the constructor. Or subclass FilteredData.</p>\n\n<p>Another example, you could \"slurp\" up the entire input as part of your <code>__iter__</code> method in order to compute some aggregate value (like min, max, or average) then yield the values one at a time. It's painful since it consumes O(N) memory instead of just O(1), but sometimes it's necessary. That would require a subclass, or a more complex class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T05:47:06.707",
"Id": "219236",
"ParentId": "219228",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T03:33:15.673",
"Id": "219228",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Combinable filters"
} | 219228 |
<p>I saw <a href="https://codereview.stackexchange.com/questions/219119/rotate-a-linked-list-to-the-right-by-k-places">this question</a> (javascript - rotate linked list to the right by k places) the other day and I tried implementing it in Ruby in a totally different way. Here's the code (I also created a REPL if you want to test it - <a href="https://repl.it/repls/PrimeSomeBlock" rel="nofollow noreferrer">https://repl.it/repls/PrimeSomeBlock</a>):</p>
<p><strong>node.rb</strong></p>
<pre class="lang-rb prettyprint-override"><code>class Node
attr_accessor :value, :next_node
def initialize(value:, next_node: nil)
@value = value
@next_node = next_node
end
end
</code></pre>
<p><strong>linked_list.rb</strong></p>
<pre class="lang-rb prettyprint-override"><code>class LinkedList
attr_reader :nodes
def initialize(nodes: [])
@nodes = nodes
end
def rotate(k)
self.class.new(nodes: rotate_nodes(k))
end
def rotate!(k)
@nodes = rotate_nodes(k)
end
def to_s
@nodes.map(&:value).join("->")
end
private
def rotate_nodes(k)
if !k.between?(1, @nodes.length) || !k.is_a?(Integer)
raise "`k` must be an integer between 1 and the length of the list"
end
@nodes.map do |node|
n = @nodes.find_index(node)
@nodes[n - k].next_node = n - k == 1 ? nil : @nodes[n - k + 1]
@nodes[n - k]
end
end
end
</code></pre>
<p><strong>main.rb</strong></p>
<pre class="lang-rb prettyprint-override"><code>require_relative "./node"
require_relative "./linked_list"
n4 = Node.new(value: 5)
n3 = Node.new(value: 3, next_node: n4)
n2 = Node.new(value: 7, next_node: n3)
n1 = Node.new(value: 7, next_node: n2)
linked_list1 = LinkedList.new(
nodes: [n1, n2, n3, n4]
)
puts <<~HEREDOC
Rotating #{linked_list1.to_s} by 2 places.
:: #{linked_list1.rotate(2).to_s}
HEREDOC
n9 = Node.new(value: 5)
n8 = Node.new(value: 4, next_node: n9)
n7 = Node.new(value: 3, next_node: n8)
n6 = Node.new(value: 2, next_node: n7)
n5 = Node.new(value: 1, next_node: n6)
linked_list2 = LinkedList.new(
nodes: [n5, n6, n7, n8, n9]
)
puts <<~HEREDOC
Rotating #{linked_list2.to_s} by 3 places.
:: #{linked_list2.rotate(3).to_s}
HEREDOC
</code></pre>
<p>Thoughts? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T09:33:24.433",
"Id": "423464",
"Score": "2",
"body": "My thoughts are that your code is perfect. There is no need to refactor it... It is very elegant and very beautiful :-)"
}
] | [
{
"body": "<p>My ruby is a little rusty, but I can give you some general pointers.</p>\n\n<p>First off, this isn't really a linked list. You use an array in <code>LinkedList</code>. That is not how a linked list works. A linked list does not maintain an array of all of its nodes. If it is singly linked (usually the forward direction, which is what you're doing with <code>next_node</code>) then <code>LinkedList</code> should only hold the head of the list. So, first thing's first let's fix that. You also shouldn't expose <code>Node</code>. Your constructor is also a little strange. I'd expect it to <a href=\"https://ruby-doc.org/core-2.6.3/Array.html#class-Array-label-Creating+Arrays\" rel=\"nofollow noreferrer\">work like the builtin <code>Array</code></a>. Namely, you don't pass nodes. You pass a size and a value or a size and a block to <code>Array.new</code> or through a separate method (<code>Array()</code>) something that is <code>to_ary</code> or <code>to_a</code>-able.</p>\n\n<p>Again my ruby is rusty, but that would probably look something like this:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class LinkedList\n attr_reader :length\n alias_method :count, :length\n\n def initialize(length: 0, value: nil)\n @length = length\n\n (0..@length).reduce(Node.new) do |last_node, i|\n node = Node.new(if block_given? yield i else value end)\n last_node.next = node\n @head = node if i == 0\n node\n end\n end\n\n def first\n @head.?value\n end\n\n # Technically incomplete\n # if !block_given?, then it should return an enumerator\n def each\n node = @head\n while !node.nil?\n yield node.value\n node = node.next\n end\n end\n\n def to_a\n values = []\n each { |v| values << v }\n values\n end\nend\n\ndef LinkedList(values)\n values = values.to_ary if values.respond_to?(:to_ary) else values.to_a end\n LinkedList.new(values.length) { |i| values[i] }\nend\n</code></pre>\n\n<p>There may be a more elegant way to build the list from an arrayable (without needing to first construct the array), but it's not coming to me now. For completeness's sake, you probably want to also define the usual <code>Enumerable</code> methods (particularly <code>each</code>) so that you can test this. I provided <code>first</code> and <code>each</code> as examples of following the <code>Enumerable</code> convention.</p>\n\n<p>Differentiating between <code>rotate</code> and <code>rotate!</code> is good. And your code reuse there is pretty nice (although given my qualms with the use of the array, I'm not a fan of <code>rotate_nodes</code>, more on that in a second). However, I'd recommend some further refactoring. It's unclear to me whether rotate is left or right. How about making it explicit: <code>rotate_left</code>, <code>rotate_left!</code>, <code>rotate_right</code>, and <code>rotate_right!</code>? And why not accept 0 or negative rotations? Let's say we defined right rotation. We could then define left rotation like this:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class LinkedList\n # ...\n\n def rotate_left(delta)\n rotate_right(-delta)\n end\n\n def rotate_left!(delta)\n rotate_right!(-delta)\n end\n</code></pre>\n\n<p>That feels much cleaner to me. I also wouldn't put the restriction that <code>delta</code> must be less than the length of your list (something you should definitely store by the way, don't rely on storing all the nodes in an array!). Instead, modulo the delta by the list length. So if the list has 5 elements and you rotate right by 7, that's the same as rotating right by 2. And if it isn't clear, rotating left by a negative amount should rotate right and vice versa.</p>\n\n<p>Now, onto a more core problem. We'll start with your <code>map</code> in <code>rotate_nodes</code>:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def rotate_nodes(k)\n # ...\n\n @nodes.map do |node|\n n = @nodes.find_index(node)\n # ...\n end\n</code></pre>\n\n<p><code>find_index</code> is O(n). There's no reason to do this. This ends up being O(n^2). Instead use <code>@nodes.each_with_index.map { |node, index| # ... }</code>. But, like I've mentioned before, you shouldn't have <code>@nodes</code> in the first place. Without it, you have some concerns to deal with regarding the differences between your bang rotate methods and non-bang rotate methods. Namely this:</p>\n\n<p>Let's say you added a <code>first=</code> method so you could change the value of the first element in the list:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code> def first=(value)\n if @head.nil?\n @head = Node.new(value)\n @length = 1\n else\n @head.value = value\n end\n end\n</code></pre>\n\n<p>This could be used like so:</p>\n\n<pre><code>> a = LinkedList([1, 2, 3])\n> a.head = 4\n> a.to_a\n[4, 2, 3]\n</code></pre>\n\n<p>Now, what do you expect when we do the following:</p>\n\n<pre><code>> a = LinkedList([1, 2, 3])\n> a.rotate_right(1).rotate_left(1).head = 4\n> a.to_a\n</code></pre>\n\n<p><code>rotate_left</code> and <code>rotate_right</code> aren't bang methods, so we don't expect to be able to change the underlying linked list. You demonstrate this understanding in how you initialize and return a new linked list for those methods. But, returning a new linked list isn't enough. <code>rotate_right(1)</code> is the equivalent of taking the tail of the linked list and placing it at the head. This can be done fairly trivially by moving some of the <code>next</code>s around and then setting <code>@head</code>. But, if you share <code>Node</code>s between <code>LinkedList</code>s, then that <code>.head = 4</code> will modify the original list. I'm not sure that's the behavior you want. You'll have to think about the semantics you desire. It's clear that the bang methods should modify the existing <code>LinkedList</code> in place. But, it's less clear what an example like the one above should do. On the one hand, you could copy all of the nodes so that each <code>Node</code> belongs to only one <code>LinkedList</code>. However, this incurs a high memory penalty, especially if you didn't actually need the copy (say for some reason you just did <code>a.rotate_right(10).head</code>, you don't actually need the copy, this is equivalent to just getting the 11th element in the list). On the other hand, you could have <code>Node</code>s belong to multiple <code>LinkedList</code>s. In this way a <code>LinkedList</code> behaves much more like a view than an independent collection. What I mean by this is <code>my_list.rotate_right(10)</code> isn't a new <code>LinkedList</code> really, it's just a different way of looking at <code>my_link</code>. Specifically, it's looking at <code>my_list</code> as if it started 11 elements in instead of where it's head currently is. I feel like the first approach doesn't make the copying obvious enough. You may want to avoid it entirely for something more explicit like requiring something like:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>new_list = my_list.copy\nnew_list.rotate_right!(10)\n</code></pre>\n\n<p>If you prefer the second approach, I'd recommend making the <code>Node</code>'s <code>value</code> immutable and severely limiting mutation on the lists. This is a space that functional programming languages have explored extensively. Mutation and multiple aliases often lead to disaster. It's best to pick one or the other.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T03:29:33.010",
"Id": "219335",
"ParentId": "219232",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219335",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T04:21:07.673",
"Id": "219232",
"Score": "3",
"Tags": [
"ruby",
"linked-list"
],
"Title": "(Ruby version) Rotate linked list to the right by k places"
} | 219232 |
<p>I made a simple python script using the BeautifulSoup and Selenium to automatically download adult comics from <a href="https://www.8muses.com/comics" rel="nofollow noreferrer">8muses</a>. I've used selenium for the reason that the website uses javascript to load the images. </p>
<p>Enter the the gallery url and download location to start downloading.
Sample gallery urls: </p>
<p><a href="https://www.8muses.com/comics/album/MilfToon-Comics/Milfage/Issue-1" rel="nofollow noreferrer">https://www.8muses.com/comics/album/MilfToon-Comics/Milfage/Issue-1</a>
<a href="https://www.8muses.com/comics/album/MilfToon-Comics/Lemonade/Lemonade-1" rel="nofollow noreferrer">https://www.8muses.com/comics/album/MilfToon-Comics/Lemonade/Lemonade-1</a></p>
<p>I would like to know improvements to the code or alternative methods to make it work faster. Thanks !</p>
<p>Code : app.py </p>
<pre><code>import os
from multiprocessing.dummy import Pool
from queue import Queue
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from threading import Thread
import urllib.request
import requests
import shutil
options = Options()
options.headless = True
chrome_driver_path = r"C:\Users\NH\PycharmProjects\SeleniumTest\drivers\chromedriver.exe"
base_url = "https://www.8muses.com"
def fetch_image_url(url,filename,download_location):
driver = webdriver.Chrome(chrome_driver_path, chrome_options=options)
driver.get(url)
page = driver.page_source
soup = BeautifulSoup(page,"lxml")
image_url = "http:"+soup.find("img",{"class":"image"})['src']
download_image(image_url,filename,download_location)
def download_image(image_url,filename,download_location):
r = requests.get(image_url,stream=True, headers={'User-agent': 'Mozilla/5.0'})
if r.status_code == 200:
with open(os.path.join(download_location,str(filename)+".png"), 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
print("Downloaded page {pagenumber}".format(pagenumber=filename))
if __name__=="__main__":
print("Album Url : ")
album_url = input()
print("Download Location : ")
download_location = input()
driver = webdriver.Chrome(chrome_driver_path, chrome_options=options)
print("Loading Comic...")
driver.get(album_url)
album_html = driver.page_source
print("Comic successfully loaded")
soup = BeautifulSoup(album_html,"lxml")
comic_name = soup.find("title").text.split("|")[0].strip()
download_location = os.path.join(download_location,comic_name)
os.mkdir(download_location)
print("Finding comic's pages")
images = soup.find_all("a",{"class":"c-tile t-hover"})
page_urls = []
pages = []
threads = []
for image in images:
page_urls.append(base_url + image['href'])
print("Found {} pages".format(len(page_urls)))
for i in range(len(page_urls)):
pages.append((page_urls[i],i,download_location))
p = Pool(3) # 3 threads in the pool
p.starmap(fetch_image_url,pages)
p.close()
p.join()
driver.quit()
print ("DONE ! Happy Reading ")
</code></pre>
<p>Github for the project : <a href="https://github.com/ggrievous/8muser" rel="nofollow noreferrer">https://github.com/ggrievous/8muser</a></p>
| [] | [
{
"body": "<p>There's no reason to use selenium here. Instead of reaching for selenium, first try the easier path. Load the page without javascript and see if you can find any helpful information about how the images get there. There must be something (perhaps AJAX) that gets the URLs for them. They don't just magically appear!</p>\n\n<p>It turns out if you do this, you'll see there isn't any fancy JS stuff. The images are there, they just look like this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><div class=\"image\">\n <img class=\"lazyload\" data-src=\"/image/th/QD-H-4F3JpxykaxnIIFbrixlkt4rwBphjoSmX2E8fvoJ8JanT-+S2MdyjKTADNm+SJdCVhXQwkdIZ0tQel-n8-y70M9EOTmeW06uA5ubLwnl2gi5X14+yw6GKhNbhj7S.jpg\">\n</div>\n</code></pre>\n\n<p>This means, you can extract all these URLs with a single line of BeautifulSoup:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>urls = [img['data-src'] for img in doc.find_all('img', class_='lazyload')]\n</code></pre>\n\n<p>Now some comments about your code:</p>\n\n<ul>\n<li>PEP8 it! Your spacing is inconsistent. Make good use of vertical whitespace. Phrase things like you would paragraphs. That makes things much easier to read.</li>\n<li>You don't need selenium, but you definitely shouldn't hard code a driver path in a project that you open source. How many people have a selenium driver exactly at <code>C:\\Users\\NH\\PycharmProjects\\SeleniumTest\\drivers\\chromedriver.exe</code> on their computer?</li>\n<li>Nice use of functions to separate concerns</li>\n<li>You should probably use <code>BeautifulSoup(page, 'html5lib')</code> instead of lxml</li>\n<li>Your construction of <code>image_url</code> is a bit sloppy. Typically, we'd reach for <code>urllib.path</code> to build paths instead of just doing string concatenation.</li>\n<li>Use <code>pathlib</code> instead of <code>os.path</code></li>\n<li><code>'Mozilla/5.0'</code> isn't a User-Agent that's going to fool anybody. If you're really trying to stay under the radar, use a real UA</li>\n<li>But none of that matters, because you appear to request pages as fast as possible. Add <code>sleep()</code>s in between downloading. Throttle your scraper.</li>\n<li><code>threading</code> is a bit useless in Python. This is somewhat of an I/O bound task (for which threads are well suited), but the HTML parsing and extraction could definitely be done concurrently with web requests (but threading doesn't allow this). You almost always want to reach for <code>multiprocessing</code>.</li>\n<li>Use the context manager of a pool instead of manually calling <code>close()</code> and <code>join()</code>:</li>\n</ul>\n\n\n\n<pre class=\"lang-py prettyprint-override\"><code>with Pool() as pool:\n pool.imap_unorderd(fetch_image_url, pages)\n</code></pre>\n\n<ul>\n<li>Also, don't pass a parameter to <code>Pool</code>. It defaults to the number of CPU cores, which is almost always what you want</li>\n<li><code>starmap</code> is ordered and blocking. It only can process things in order. This is okay in this case, because you aren't actually returning anything, but if you were say doing math you probably want <code>imap_unordered</code> which yields results as they arrive (likely out of order).</li>\n<li>Don't <code>print</code> from a separate process. You want a single process writing to stdout, otherwise you can have write contention (which you'll luck out and probably never run into because your strings probably fit inside the stdout buffer, but it's possible they may not under certain circumstances).</li>\n</ul>\n\n<p>But this all culminates in the following advice: don't use Python to download things!</p>\n\n<p>Especially since this scraping doesn't appear to be useful as a library (instead, it seems like you just are providing a CLI utility for a human to download these things). Given this, it's much smarter and safer to not reinvent the wheel. There are tools that already do jobs like this well: namely, <code>wget</code> (it appears that you're on windows, you can and should use the Ubuntu subsystem, which will have <code>wget</code>). <code>wget</code> is particularly suited for this job and has <em>tons</em> of builtin functionality which will be super useful to you. This includes:</p>\n\n<ul>\n<li>Not redownloading things</li>\n<li>Throttling (including random delays)</li>\n<li>Restarting after a catastrophic (program crashing) failure</li>\n<li>Retrying requests per HTTP spec</li>\n</ul>\n\n<p>All of these are things that your script doesn't do currently. In particular, in python it's very easy to do something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>pages = download_hundreds_of_pages() # takes hours...\nfor page in paages: # oops, this NameErrors and you lose everything you've downloaded\n pass\n</code></pre>\n\n<p>Mistakes like this are too easy to make. You can completely avoid them with the following workflow:</p>\n\n<ol>\n<li>Build up a list of urls you want to download (perhaps with python)</li>\n<li>Use <code>wget -nc -i urls.txt</code> to download them</li>\n<li>Repeat as necessary</li>\n</ol>\n\n<p>For you, that would involve making a list of urls containing the images. Then do <code>wget -nc -i pages.txt</code>. That will download all of the pages to the current directory. Then you can make a Python script which uses beautiful soup (and the line I mentioned above) to extract the image urls: <code>python3 extract_image_urls.py > image_urls.txt</code>. Then to download them do <code>wget -nc -i image_urls.txt</code>. If your python script fails at any point, you don't lose all of the downloads you've already done. You can wrap all of this in a convenient bash script.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T04:01:22.657",
"Id": "219336",
"ParentId": "219237",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219336",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T06:03:55.743",
"Id": "219237",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup",
"selenium"
],
"Title": "Python script to download adult comics from 8muses"
} | 219237 |
<p>With the new additions in c++11 and c++17 I wanted to create a simple implementation of thread pool.</p>
<p>I would like your opinion on: </p>
<ul>
<li>Thread safety</li>
<li>API</li>
<li>performace</li>
<li>and general code quality </li>
</ul>
<p>I also would like to know if it good idea to have <code>wait_until_empty</code> method.
Without id I probably could have avoided using a mutex.</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef WORKER_POOL_H
#define WORKER_POOL_H
#include <../cpp11-on-multicore/common/sema.h>
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <thread>
#include <vector>
#if __cplusplus < 201703l
#error "Compile using c++17 or later"
#endif
/**
* Simplistic implementation of thread pool
* using C++17.
*/
class worker_pool {
private:
/**
* Inner class that represents individual workers.
*/
class worker {
private:
worker_pool *wp;
long id;
public:
worker(worker_pool *_wp, long _id) : wp(_wp), id(_id){};
/**
* Main worker loop.
*/
void operator()() {
// work until asked to stop
while (!wp->stop.load()) {
auto t = wp->fetch();
// when asked to stop workers will wake up
// and recieve a nullopt
if (t.has_value())
t.value()();
}
};
};
std::vector<std::thread> workers;
std::queue<std::function<void(void)>> job_queue;
// access control for the queue
std::mutex queue_mutex;
Semaphore queue_sem;
// this is used to notify that queue has been emptied
std::condition_variable cv_empty;
// stop indicates that we were asked to stop but workers are not terminated
// yet
std::atomic<bool> stop;
// term means that workers are terminated
std::atomic<bool> term;
/**
* Thread safe job fetchind
*/
std::optional<std::function<void(void)>> fetch() {
queue_sem.wait();
std::unique_lock l(queue_mutex);
// return nothing if asked to stop
if (stop.load())
return std::nullopt;
auto res = std::move(job_queue.front());
// if we happen to have emptied the queue notify everyone who is waiting
job_queue.pop();
if (job_queue.empty())
cv_empty.notify_all();
return std::move(res);
};
public:
/**
* Initializing worker pool with n workers.
* By default the number of workers is equal to number
* of cores on the machine.
*/
worker_pool(long tcount = std::thread::hardware_concurrency())
: queue_sem(0), stop(false), term(false) {
assert(tcount > 0);
for (long i = 0; i < tcount; i++) {
workers.push_back(std::thread(worker(this, i)));
}
}
/**
* Terminate all workers before getting destroyed
*/
~worker_pool() { terminate(); }
/**
* No-copy and no-move
*/
worker_pool(worker_pool const &) = delete;
worker_pool &operator=(worker_pool const &) = delete;
worker_pool(worker_pool &&) = delete;
worker_pool &operator=(worker_pool &&) = delete;
/**
* Thread-safe job submition. Accepts any callable and
* returns a future.
*/
template <typename F, typename... Args>
auto submit(F &&f, Args &&... args) -> std::future<decltype(f(args...))> {
std::lock_guard l(queue_mutex);
// Wrapping callable with arguments into a packaged task
auto func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
auto task_ptr =
std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);
// Wrapping packaged task into a simple lambda for convenience
job_queue.push([task_ptr] { (*task_ptr)(); });
queue_sem.signal();
return task_ptr->get_future();
}
/**
* Terminate will stop all workers ignoring any remaining jobs.
*/
void terminate() {
// do nothing if already terminated
if (term.load())
return;
stop.store(true);
// wakeup all workers
queue_sem.signal(workers.size());
// wait for each worker to terminate
for (size_t i = 0; i < workers.capacity(); i++) {
if (workers[i].joinable())
workers[i].join();
}
term.store(true);
}
/**
* Check how many jobs remain in the queue
*/
long jobs_remaining() {
std::lock_guard l(queue_mutex);
return job_queue.size();
}
/**
* This function will block until all
* the jobs in the queue have been processed
*/
void wait_until_empty() {
std::unique_lock l(queue_mutex);
while (!(job_queue.empty() || stop.load()))
cv_empty.wait(l, [&] { return job_queue.empty() || stop.load(); });
}
/**
* Check if there was a demand to stop.
* Note: there may be still workers running.
*/
bool stopped() { return stop.load(); }
/**
* Check if workers have been terminated
*/
bool terminated() { return term.load(); }
};
#endif // WORKER_POOL_H
</code></pre>
<p>Edit: updated code, added an assert to contructor, removed a mutex, typos</p>
| [] | [
{
"body": "<pre><code>#include <../cpp11-on-multicore/common/sema.h>\n</code></pre>\n\n<p>You didn't show this file, so I cannot comment on it nor the use of the semaphore.</p>\n\n<pre><code>#if __cplusplus < 201703l\n#error \"Compile using c++17 or later\"\n#endif\n</code></pre>\n\n<p>What's the point of this? If some feature isn't supported, the compiler will say so.</p>\n\n<pre><code>class worker_pool {\nprivate:\n</code></pre>\n\n<p>I would put the public interface on top, since that is what's relevant to the largest audience.</p>\n\n<pre><code> class worker {\n</code></pre>\n\n<p>This can just be a lambda function. <code>id</code> is unused.</p>\n\n<pre><code> // work until asked to stop\n while (!wp->stop.load()) {\n auto t = wp->fetch();\n // when asked to stop workers will wake up\n // and recieve a nullopt\n if (t.has_value())\n t.value()();\n }\n</code></pre>\n\n<p>You check for the stop condition twice in each iteration. Accessing the atomic can be quite expensive when done frequently from multiple threads. Instead, you can simply write:</p>\n\n<pre><code> // work until asked to stop\n while (true) {\n auto t = wp->fetch();\n // when asked to stop workers will wake up\n // and recieve a nullopt\n if (!t.has_value())\n break;\n t.value()();\n }\n</code></pre>\n\n<p>.</p>\n\n<pre><code> // stop indicates that we were asked to stop but workers are not terminated\n // yet\n std::atomic<bool> stop;\n // term means that workers are terminated\n std::atomic<bool> term;\n</code></pre>\n\n<p>This allows for an invalid state (<code>term && !stop</code>). You can represent this better with an <code>enum { Running, Stopping, Stopped }</code>.</p>\n\n<pre><code> std::optional<std::function<void(void)>> fetch() {\n queue_sem.wait();\n std::unique_lock l(queue_mutex);\n // return nothing if asked to stop\n if (stop.load())\n return std::nullopt;\n auto res = std::move(job_queue.front());\n // if we happen to have emptied the queue notify everyone who is waiting\n job_queue.pop();\n if (job_queue.empty())\n cv_empty.notify_all();\n return std::move(res);\n };\n</code></pre>\n\n<p>There's no need to return an <code>optional</code> here. <code>function</code> can already be empty.</p>\n\n<p>You can check for the <code>stop</code> condition before locking the mutex. It's best to unlock the mutex as soon as possible; in this case, before notifying the CV.</p>\n\n<p>Finally, there shouldn't be a semicolon after a function body.</p>\n\n<pre><code> for (long i = 0; i < tcount; i++) {\n workers.push_back(std::thread(worker(this, i)));\n }\n</code></pre>\n\n<p>You can write <code>workers.emplace_back(worker(this, i));</code>.</p>\n\n<pre><code> /**\n * Terminate all workers before getting destroyed\n */\n ~worker_pool() { terminate(); }\n</code></pre>\n\n<p>When dealing with threads, \"terminate\" usually means killing a thread, which should almost always be avoided, as it leaves the program in an unpredictable (if not undefined) state. Better just use the term \"stop\" instead.\nSince the only way to start the threads in a worker pool is to instantiate one, it would make sense if the only way to stop them is by destroying that instance.</p>\n\n<pre><code> worker_pool(worker_pool const &) = delete;\n worker_pool &operator=(worker_pool const &) = delete;\n worker_pool(worker_pool &&) = delete;\n worker_pool &operator=(worker_pool &&) = delete;\n</code></pre>\n\n<p>There's no need to explicitly declare the move c'tor/assignment operator deleted here.</p>\n\n<pre><code> template <typename F, typename... Args>\n auto submit(F &&f, Args &&... args) -> std::future<decltype(f(args...))> {\n std::lock_guard l(queue_mutex);\n // Wrapping callable with arguments into a packaged task\n auto func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);\n auto task_ptr =\n std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);\n // Wrapping packaged task into a simple lambda for convenience\n job_queue.push([task_ptr] { (*task_ptr)(); });\n queue_sem.signal();\n return task_ptr->get_future();\n }\n</code></pre>\n\n<p>Note that in the return value declaration you do not forward the arguments, which could yield a different overload resolution (and therefore a different return type) than when the function is actually called.</p>\n\n<p>I don't think the <code>bind</code> will work well here when you pass a temporary as an argument to this function, since it will not store a copy of the argument. When the function gets called on the worker thread, the argument has been destroyed.</p>\n\n<pre><code> void terminate() {\n // do nothing if already terminated\n if (term.load())\n return;\n stop.store(true);\n // wakeup all workers\n queue_sem.signal(workers.size());\n // wait for each worker to terminate\n for (size_t i = 0; i < workers.capacity(); i++) {\n if (workers[i].joinable())\n workers[i].join();\n }\n term.store(true);\n }\n</code></pre>\n\n<p>You should compare the index to the size of <code>workers</code>, not its capacity.</p>\n\n<p>This function has a race condition. When it's called from two threads, the second call may begin before <code>term</code> has been updated. Then, the two threads may call <code>join</code> on the same thread instance.</p>\n\n<pre><code> /**\n * Check how many jobs remain in the queue\n */\n long jobs_remaining() {\n std::lock_guard l(queue_mutex);\n return job_queue.size();\n }\n</code></pre>\n\n<p>I don't see any real use for this function.</p>\n\n<pre><code> /**\n * This function will block until all\n * the jobs in the queue have been processed\n */\n void wait_until_empty() {\n std::unique_lock l(queue_mutex);\n while (!(job_queue.empty() || stop.load()))\n cv_empty.wait(l, [&] { return job_queue.empty() || stop.load(); });\n }\n</code></pre>\n\n<p>The comment is wrong. This function only waits for all jobs to be taken off the queue. The function may return while the last jobs are still being processed. That makes the whole function pointless to begin with. I would remove it.</p>\n\n<pre><code> /**\n * Check if there was a demand to stop.\n * Note: there may be still workers running.\n */\n bool stopped() { return stop.load(); }\n\n /**\n * Check if workers have been terminated\n */\n bool terminated() { return term.load(); }\n</code></pre>\n\n<p>These functions also seem useless.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T22:39:27.953",
"Id": "219281",
"ParentId": "219244",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T09:53:11.050",
"Id": "219244",
"Score": "6",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "Worker pool implementation"
} | 219244 |
<p>I've made an Android app that converts between cooking measurements, taking into account the type of product you use (that way it can convert between mass and volume by using the density). What are your thoughts on Android- and Kotlin-specific idioms I might be missing?</p>
<p>For brevity's sake, I've included the main types below. Screenshots for context can be found <a href="https://play.google.com/store/apps/details?id=com.calcubaker.Calcubaker" rel="nofollow noreferrer">here</a>.</p>
<p>In the <code>MetricsService</code> I'm using a shortest-path approach to convert from any arbitrary metric (say, Liter) to another (say, Ounces). The idea is that the only requirement to add a metric is that you define a conversion to a single other existing metric and it will plug into the rest of the graph.</p>
<p><strong>Service</strong></p>
<pre><code>class MetricsService(
private val metricsRepository: MetricsRepository,
private val conversionRepository: ConversionRepository,
private val productRepository: ProductRepository) {
fun getMetrics() : List<Metric> = metricsRepository.getMetrics()
fun getProducts() : List<Product> = productRepository.getProducts().sortedBy { product -> product.name }
fun getMetric(metricUnit: MetricUnit) : Metric = metricsRepository.getMetrics().first { metric -> metric.id == metricUnit}
private fun getConversion(source: Metric, destination: Metric) : Conversion {
val conversions = conversionRepository.getConversions()
val conversion = conversions.find { c -> c.from == source.id && c.to == destination.id }
return conversion ?: getChainedConversions(source, destination)
}
private fun getChainedConversions(source: Metric, destination: Metric) : Conversion {
val conversions = conversionRepository.getConversions()
val edges = arrayListOf<Edge>()
conversions.forEach { conversion ->
edges.add(Edge(Vertex(conversion.from.id), Vertex(conversion.to.id), 1))
}
val graph = Graph(edges)
val dijkstra = DijkstraAlgorithm(graph)
val sourceVertex = dijkstra.execute(Vertex(source.id.id))
val path = sourceVertex.getPath(Vertex(destination.id.id))
val chainedConversions = arrayListOf<Conversion>()
var index = 1
var start = parseInt((path[0].payload.toString()))
var end: Int
do
{
end = parseInt((path[index].payload.toString()))
var conversion = conversions.first { conv -> conv.from.id == start && conv.to.id == end }
chainedConversions.add(conversion)
index++;
start = end;
} while (chainedConversions.last().to.id != destination.id.id)
return ComposedConversion(source.id, destination.id, chainedConversions)
}
fun calculate(amount: Double, product: Product, source: Metric, destination: Metric) : Double {
if (source.id == destination.id) { return amount }
val conversion = getConversion(source, destination)
return conversion.calculate(amount, product)
}
}
</code></pre>
<p><strong>Viewmodel</strong></p>
<pre><code>class CalculatorViewmodel(private val metricsService: MetricsService) {
var product: Product? = null
var amount: Double? = null
var sourceMetric: Metric? = null
val results: ArrayList<CalculationResult> = arrayListOf()
fun getMetrics() : List<Metric> = metricsService.getMetrics()
fun getProducts() : List<Product> = listOf(Product.Generic).plus(metricsService.getProducts().toList())
fun calculate() {
if (product == null || amount == null || sourceMetric == null) {
return
}
Answers.getInstance().logCustom(
CustomEvent("MetricConversion")
.putCustomAttribute("From", sourceMetric!!.name)
.putCustomAttribute("Product", product!!.name)
.putCustomAttribute("Amount", amount.toString()))
val destinationMetrics = metricsService.getMetrics()
for(destinationMetric in destinationMetrics)
{
val result = metricsService.calculate(amount!!, product!!, sourceMetric!!, destinationMetric);
results.add(CalculationResult(result, destinationMetric))
}
}
}
</code></pre>
<p><strong>Activity</strong></p>
<pre><code>class MainActivity : AppCompatActivity(), OnItemSelectedListener, TextWatcher, View.OnClickListener {
private val viewmodel: CalculatorViewmodel = CalculatorViewmodel(
MetricsService(
MetricsRepository() ,
ConversionRepository(),
ProductRepository()
)
)
private lateinit var sourceMetrics: Spinner
private lateinit var products: Spinner
private lateinit var table: TableLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Fabric.with(this, Crashlytics())
Fabric.with(this, Answers())
setContentView(R.layout.activity_main)
sourceMetrics = findViewById(R.id.sourceMetric)
products = findViewById(R.id.product)
table = findViewById(R.id.resultsTable)
table.removeAllViews()
sourceMetrics.onItemSelectedListener = this
products.onItemSelectedListener = this
findViewById<EditText>(R.id.quantity).addTextChangedListener(this)
findViewById<Button>(R.id.calculateButton).setOnClickListener(this)
loadMetrics()
loadProducts()
}
private fun loadMetrics() {
val adapter = ArrayAdapter(this, R.layout.spinner_item, viewmodel.getMetrics().map { metric -> metric.name })
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
sourceMetrics.adapter = adapter
}
private fun loadProducts() {
val adapter = ArrayAdapter(this, R.layout.spinner_item, viewmodel.getProducts().map { product -> product.name })
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
products.adapter = adapter
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
reset()
if (parent == sourceMetrics) {
val metric = viewmodel.getMetrics().first { metric -> metric.name == sourceMetrics.getItemAtPosition(position)}
viewmodel.sourceMetric = metric
} else if (parent == products) {
val product = viewmodel.getProducts().first { product -> product.name == products.getItemAtPosition(position)}
viewmodel.product = product
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
reset()
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (p0 == null || p0.isEmpty()) {
viewmodel.amount = 0.0
} else {
viewmodel.amount = parseDouble(p0.toString())
}
}
override fun onClick(v: View?) {
recalculate()
}
private fun reset() {
table.visibility = View.INVISIBLE
}
private fun recalculate() {
viewmodel.calculate()
viewmodel.results.forEach { result ->
var row = table.findViewWithTag<TableRow>(result.metric.id.id)
if (row == null) {
row = createRow(result)
table.addView(row)
} else {
val viewGroup = row as ViewGroup
val valueText = viewGroup.getChildAt(0) as TextView
valueText.text = result.displayAmount
}
}
hideKeyboard(this)
table.visibility = View.VISIBLE
}
private fun createRow(calculationResult: CalculationResult) : TableRow {
val row = TableRow(this)
row.tag = calculationResult.metric.id.id
val rowLayout = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)
rowLayout.topMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5f, this.resources.displayMetrics).toInt()
row.layoutParams = rowLayout
val valueText = TextView(this)
valueText.text = calculationResult.displayAmount
valueText.setTypeface(valueText.typeface, Typeface.BOLD)
valueText.setTextColor(Color.BLACK)
valueText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f);
valueText.layoutParams = TableRow.LayoutParams(22, TableRow.LayoutParams.WRAP_CONTENT, 2f)
val paddingPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5f, this.resources.displayMetrics).toInt()
valueText.setPadding(paddingPx, 0, 0, 0)
val labelText = TextView(this)
labelText.text = calculationResult.metric.name
labelText.layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 3f)
valueText.setTextColor(Color.BLACK)
row.addView(valueText)
row.addView(labelText)
return row
}
// https://stackoverflow.com/a/17789187/1864167
private fun hideKeyboard(activity: Activity) {
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Find the currently focused view, so we can grab the correct window token from it.
var view = activity.currentFocus
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = View(activity)
}
view.clearFocus()
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
</code></pre>
<p>Unit test(s):</p>
<pre><code>@RunWith(Parameterized::class)
class CalculationTests(private val amount: Double, private val fromUnit: MetricUnit, private val toUnit: MetricUnit, private val expected: Double) {
private val service = MetricsService(MetricsRepository(), ConversionRepository(), ProductRepository())
companion object {
@JvmStatic
@Parameterized.Parameters
fun data() = listOf(
arrayOf(100.0, MetricUnit.Grams, MetricUnit.Milliliter, 100.0),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.Kilogram, 0.100),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.Liter, 0.100),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.MetricCups, 0.400),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.USNutritionalCups, 0.4166666667),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.UsRecipeCups, 0.4226721332),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.MetricTeaspoons, 20.0),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.UsTeaspoons, 20.2884136211),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.MetricTablespoons, 6.6666666667),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.UsTablespoons, 6.7628045404),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.Pounds, 0.220462442),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.Ounces, 3.5278470608),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.UsFluidOunces, 3.3814022702),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.UKPint, 0.1706484642),
arrayOf(100.0, MetricUnit.Grams, MetricUnit.USPint, 0.2114164905)
)
}
@Test
fun shouldCalculateTheCorrectConversion() {
val from = service.getMetric(fromUnit)
val to = service.getMetric(toUnit)
val result = service.calculate(amount, Product.Generic, from, to)
val formattedResult = java.lang.Double.valueOf(DecimalFormat("#.##########", DecimalFormatSymbols(Locale.UK)).format(result))
assertThat(expected, equalTo(formattedResult))
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T13:39:28.693",
"Id": "423474",
"Score": "0",
"body": "Did you write any unit tests? It would help a lot if you included these, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T13:43:05.383",
"Id": "423475",
"Score": "0",
"body": "@RolandIllig I've added the one unit tests I've written to verify conversions are correct though I don't think it will help much. The other classes I've left out are simple data classes. Do you have any specific concerns about confusing parts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:33:23.303",
"Id": "423510",
"Score": "0",
"body": "No, no specific concerns. I just thought reading the unit tests would be a nice starting point for understanding the code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T12:09:49.933",
"Id": "219245",
"Score": "5",
"Tags": [
"android",
"kotlin",
"unit-conversion"
],
"Title": "Converting between cooking measurements"
} | 219245 |
<h2>Background</h2>
<p>I'm writing code that searches for the row number of the maximum value in a partial column of a matrix. The partial column corresponds with the non-zero values of an equivalent <a href="https://en.wikipedia.org/wiki/Triangular_matrix" rel="nofollow noreferrer">lower triangular matrix</a>. That is, starting from the input row index <code>idx</code> through the final row. (This is my own version of subroutine for Gaussian Elimination with Partial Pivoting, for those who are interested).</p>
<p>Basically, the behavior of <code>MaxLocColumnWise</code> is the search of columnwise <code>maximum location</code> in the submatrices of A. Passing by reference, <code>MaxLocColumnWise</code> changes the value of <code>k</code>.</p>
<p>For example, for the following matrix
<span class="math-container">$$
A = \begin{bmatrix}1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{bmatrix}
$$</span></p>
<ul>
<li>when <code>k=0</code>, <code>MaxLocColumnWise(A,k)</code> converts <code>k</code> to the index of maximum element in <code>[1,4,7]</code>, which is <code>2</code>, which is the index of <code>7</code> i.e. we get <code>2</code> as a result of</li>
</ul>
<pre><code> int k = 0;
`MaxLocColumnWise(A,k)`;
std::cout << k <<"\n";
</code></pre>
<ul>
<li><p>when <code>k=1</code>, <code>MaxLocColumnWise(A,k)</code> converts <code>k</code> to the index of maximum element in <code>[5,8]</code>, which is <code>2</code>, which is the index of <code>8</code>. (This case is highlighted in red here)</p></li>
<li><p>when <code>k=2</code>, <code>MaxLocColumnWise(A,k)</code> converts <code>k</code> to the index of maximum element in <code>[9]</code>, which is <code>2</code>, which is the index of <code>9</code> </p></li>
</ul>
<hr>
<h2>Code</h2>
<p>Interestingly it turns out that the following code takes quite long time. </p>
<pre><code>void MaxLocColumnWise(Matrix A, int &idx){
int n = A.size();
int col = idx;
double currentAbsMax = abs(A[col][col]);
for (int i=(col+1); i<n; i++){
double currentVal = abs(A[i][col]);
if (currentVal > currentAbsMax){
currentAbsMax = currentVal;
idx = i;
}
}
}
</code></pre>
<hr>
<p>I have implemented this subroutine to the following <code>Gaussian elimination with partial pivoting</code> routine:</p>
<pre><code>void GaussElimPartialPivot(Matrix& A, Vector& b){
int n = A.size();
for (int j=0; j<(n-1); j++){
int index = j;
MaxLocColumnWise(A, index);
SwapMatrixRows(A, j, index);
SwapVector(b, j, index);
// main loop
for (int i=(j+1); i<n; i++){
double m = A[i][j]/A[j][j];
b[i] -= m*b[j];
for(int k=j; k<n; k++){
A[i][k] -= m*A[j][k];
}
}
}
}
</code></pre>
<p>But when A gets large, the program gets slower exactly due to the subroutine <code>MaxLocColumnWise</code>, which was verified from excluding each subroutine in the main code. </p>
<p>But I'm not sure exactly where in <code>MaxLocColumnWise()</code> to blame. Any help will be appreciated.</p>
<p>(<em>An excuse for the exclusion of the code : <code>Matrix</code> is just from <code>typedef std::vector<Vector> Matrix;</code>, and the <code>Vector</code> is <code>typedef std::vector<double> Vector;</code></em>)</p>
| [] | [
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Pass by const reference where practical</h2>\n\n<p>The first argument to <code>MaxLocColumnWise</code> is a <code>Matrix</code> but that causes the entire input matrix to be duplicated. Better would be to make it <code>const Matrix &</code> because it is not modified and it doesn't need to be duplicated. This is very likely the crux of your code's performance problem. On my machine with a matrix of size 1000, that single change drops the execution time down from 3.1 seconds to 11 milliseconds.</p>\n\n<h2>Prefer return value over reference</h2>\n\n<p>Instead of modifying one of the passed parameters, it's often better to <code>return</code> a value instead. So in this case, the function would be </p>\n\n<pre><code>int MaxLocColumnWise(const Matrix &A, int idx);\n</code></pre>\n\n<h2>Check parameters before use</h2>\n\n<p>If <code>idx</code> is a negative number or beyond the end of the <code>Matrix</code>, your program will invoke <em>undefined behavior</em> and it could crash or worse. Better would be to verify the value is in a valid range before use. </p>\n\n<h2>Use appropriate data types</h2>\n\n<p>An index into an array is never negative, so instead of <code>int</code>, I'd recommend using <code>std::size_t</code>. </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. I split your code into a header <code>Gauss.h</code> and implementation file <code>Gauss.cpp</code> and then created a test driver. These are the resulting files, after applying all of the suggestions above:</p>\n\n<h3>Gauss.h</h3>\n\n<pre><code>#ifndef GAUSS_H\n#define GAUSS_H\n#include <vector>\ntypedef std::vector<double> Vector;\ntypedef std::vector<Vector> Matrix;\nstd::size_t MaxLocColumnWise(const Matrix &A, std::size_t idx);\nvoid GaussElimPartialPivot(Matrix& A, Vector& b);\n#endif // GAUSS_H\n</code></pre>\n\n<h3>Gauss.cpp</h3>\n\n<pre><code>#include \"Gauss.h\"\n#include <cmath>\n\nstd::size_t MaxLocColumnWise(const Matrix &A, std::size_t idx){\n auto maxIndex{idx};\n const auto col{idx};\n for (double maxValue{-1}; idx < A.size(); ++idx) {\n auto currentVal{std::abs(A[idx][col])};\n if (currentVal > maxValue){\n maxValue = currentVal;\n maxIndex = idx;\n } \n }\n return maxIndex;\n}\n\nvoid GaussElimPartialPivot(Matrix& A, Vector& b) {\n const std::size_t n{A.size()};\n for (std::size_t j{1}; j < n; ++j) {\n auto maxcol{MaxLocColumnWise(A, j)};\n SwapMatrixRows(A, j, maxcol);\n SwapVector(b, j, maxcol);\n for (std::size_t i{j-1}; i < n; ++i) {\n double m{A[i][j]/A[j][j]};\n b[i] -= m*b[j];\n for (auto k{j}; k < n; ++k){\n A[i][k] -= m*A[j][k];\n }\n }\n }\n}\n</code></pre>\n\n<h3>main.cpp</h3>\n\n<pre><code>#include \"Gauss.h\"\n#include <iostream>\n#include <numeric>\n\nint main() {\n constexpr size_t n{1000};\n Matrix m;\n m.reserve(n);\n int startval{1};\n for (size_t i{0}; i < n; ++i) {\n Vector v(n);\n std::iota(v.begin(), v.end(), startval);\n m.push_back(v);\n startval += n;\n }\n for (int i=0; i < n; ++i) {\n auto max{MaxLocColumnWise(m, i)};\n if (max != n-1) {\n std::cout << \"Error:\" << i << \", \" << MaxLocColumnWise(m, i) << '\\n';\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:51:43.297",
"Id": "423519",
"Score": "1",
"body": "Using unsigned for indexes is a bad idea. OP has `for (int j=0; j<(n-1); j++)` in which switching to unsigned would introduce a bug (consider `n ==0`). Also, range checks can be left to `std::vector` here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:08:18.013",
"Id": "423525",
"Score": "2",
"body": "In the rewrite, no range check is required exactly *because* the revised code is using a `std::size_t` instead of an `int`, and the bug you suggest does not exist, so I think you may want to reconsider your statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T20:38:22.943",
"Id": "423548",
"Score": "1",
"body": "Please explain \"the bug does not exist\". Following your advice yields `std::vector<int> v; for (size_t i = 0, n = v.size(); i < n - 1; ++i) ++v[i];`. That's a bug!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:30:31.323",
"Id": "423555",
"Score": "2",
"body": "The code can't be used as is with the updated version because of the changed interface, so any calling code must also be revised. Revising the code can easily be done to avoid introducing a bug. I've shown one means by which that might be done in my answer. I hadn't posted it before because we don't actually know the interface for `SwapMatrixRows` or `SwapVector`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:32:32.917",
"Id": "423556",
"Score": "3",
"body": "I'd also note that the `size` operator for all STL containers typically returns `std::size_t` and not `int`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:49:15.180",
"Id": "423559",
"Score": "1",
"body": "_\"Revising the code can easily be done to avoid introducing a bug.\"_ So you agree there is a bug? If so, \"I think you may want to reconsider your statement\" that \"the bug does not exist\". ;) In any case, fixing the bug first requires the realization that there is a bug. That's not obvious in code similar to the example I gave. That's why I said using unsigned for indexes is a bad idea, because it forces you to using unsigned arithmetics, which is unnatural to humans, as we all grow up learning signed arithmetics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:52:49.930",
"Id": "423561",
"Score": "1",
"body": "Letting `size()` return an unsigned is now considered to be a mistake by many prominent C++ standard committee members."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:34:01.433",
"Id": "423573",
"Score": "1",
"body": "@Edward Besides, thank you so much for your time and kind explanation. It helps me a lot indeed, anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:35:28.700",
"Id": "423587",
"Score": "0",
"body": "`size()` actually returns the corresponding `size_type` member type, which may or may not be `std::size_t`. It is guaranteed to be unsigned, though."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:25:06.930",
"Id": "219265",
"ParentId": "219249",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T13:49:34.747",
"Id": "219249",
"Score": "4",
"Tags": [
"c++",
"performance",
"matrix"
],
"Title": "Search for row number of maximum value in matrix column"
} | 219249 |
<p><a href="https://projecteuler.net/problem=76" rel="nofollow noreferrer">Project Euler Problem 76</a> asks:</p>
<blockquote>
<p>How many different ways can one hundred be written as a sum of at least two positive integers?</p>
</blockquote>
<p>My code is correct but just works slowly.</p>
<pre><code>import time
start = time.perf_counter()
def con(H):
J = []
Q = []
W = []
for i in H:
for j in range(len(i)-1):
Cop = i[::]
y = i[j]+i[j+1]
del Cop[j:j+2]
Cop.insert(j,y)
J.append(Cop)
for i in J:
y =(sorted("".join(str(j) for j in i)))
Q.append("".join(y))
T = list(set(Q))
for i in T:
y = [int(j) for j in i]
W.append(y)
return W
num = 5
K = [[1 for i in range(num)]]
count = 0
for i in range(len(K[0])-2):
K = con(K)
print(K)
count = count + len(K)
print(count+1)
end = time.perf_counter()
print(end-start,"second")
</code></pre>
<p>Here what this code does. For example, let us say num = 4. Then it creates an array of</p>
<p>[[1,1,1,1]]. Then it sums the consecutive numbers so our result becomes (from line 9-14)</p>
<p>[[2,1,1],[1,2,1],[1,1,2]] Since they are all same my code (from line 15-18) makes them just one function and returns ["112"] and then from 18-21 turns ["112"] to [[1,1,2]] and then I do this whole process again for the [[1,1,2]] and then I count the number of these arrays (from 25-29). The problem is its fast up to num = 20-30 but then it really slows down. Is there a way to increase the speed of my code or should I try a different algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T02:27:47.460",
"Id": "423575",
"Score": "0",
"body": "That fact that you need to spend a paragraph explaining how your code works is a pretty good sign that your code is in desperate need of better variable names and some commenting."
}
] | [
{
"body": "<p>The optimal solution to this is significantly simpler than what you have. We'll get to that in a second. First, let's examine your code:</p>\n\n<ul>\n<li><code>Cop</code> should not begin with a capital letter. Variables should be <code>snake_case</code>. Furthermore, <code>cop</code> is a bad name. At the least it should be <code>copy</code> (don't shorten names, it only makes things less clear--unless the shortening is a broadly understood acronym like HTML). But copy of <em>what</em>? From that name, I can't tell. I have to go hunting for the initialization of it (and all of the mutations to it) to figure out what it actually does. What are <code>J</code>, <code>Q</code>, and <code>W</code>? Again, they should be lowercase. But also, letters make awful variable names (except for maybe <code>i</code> and <code>j</code> for numeric loop variables). \nn</li>\n<li>Your code either has or is precariously close to an off by one issue with all of the <code>+1</code>ing that you're doing. Why is it <code>print(count + 1)</code> and not <code>print(count)</code>?</li>\n<li><code>count = count + len(K)</code> should be <code>count += len(K)</code></li>\n<li><code>[[1 for i in range(num)]]</code> can just be <code>[[1] * num]</code></li>\n<li>PEP8 your code. It is messy and has little whitespace, which makes it hard to follow.</li>\n<li><code>con</code> is a poorly named function. What does that even mean? Clearly it doesn't count anything because you have to use it in a loop to get the answer to the problem.</li>\n<li>Why are you maintaining <code>Q</code> as a list to only use it in <code>T = list(set(Q))</code>? <code>Q</code> should just be a set from the start, that's more efficient.</li>\n<li>There's no need to do the <code>list</code> in <code>T = list(set(Q))</code>. You can iterate over <code>T = set(Q)</code> (without the need to create a <code>list</code>).</li>\n<li>You need to comment this code. The fact that you need to spend a paragraph explaining how your code works is a pretty good sign of this. It would take a long time for me to walk through this an understand how each piece works. Comment things that aren't clear. Comment why not how. Add docstrings to functions. I wouldn't even know how to just use your code to get the answer to the problem. I assume setting <code>num</code>, but it's unclear to me if that gives the answer for 5 or 4, given that you do <code>range(num)</code> which is exclusive not inclusive (it's <code>[0, 1, 2, 3, 4]</code>)</li>\n</ul>\n\n<p>That's a not exhaustive list of issues with your code as it exists. But, we need to start from scratch, because what you have is <em>way</em> too complicated for the task at hand. If we take a step back and rethink the problem, we can come up with a much more elegant solution.</p>\n\n<p>Let's start by looking at the problem:</p>\n\n<blockquote>\n <p>It is possible to write five as a sum in exactly six different ways:</p>\n\n<pre><code>4 + 1\n3 + 2\n3 + 1 + 1\n2 + 2 + 1\n2 + 1 + 1 + 1\n1 + 1 + 1 + 1 + 1\n</code></pre>\n \n <p>How many different ways can one hundred be written as a sum of at least two positive integers?</p>\n</blockquote>\n\n<p>Here's a question: can we write out all of the ways to write <em>four</em> as a sum? Sure, it looks like:</p>\n\n<pre><code>3 + 1\n2 + 2\n2 + 1 + 1\n1 + 1 + 1 + 1\n</code></pre>\n\n<p>Hmm, that looks suspiciously similar to the list above. Let's rewrite the sums for five. I'll put the parts that are unique to five in parenthesis:</p>\n\n<pre><code>(4 + 1)\n(3 + 2)\n3 + 1 (+ 1)\n2 + 2 (+ 1)\n2 + 1 + 1 (+ 1)\n1 + 1 + 1 + 1 (+ 1)\n</code></pre>\n\n<p>We should notice a pattern here. Namely, the sums for five are the sums for four with <code>+ 1</code> added and an additional 2 new ways. The 2 new ways are just combinations of the first sum of four <code>+ 1</code>. <code>3 + 1 + 1</code> if you merge the <code>1 + 1</code> is <code>3 + 2</code> and <code>3 + 1 + 1</code> if your merge the <code>3 + 1</code> is <code>4 + 1</code>.</p>\n\n<p>Similarly, we can write the sums for four as the sums of three with some extras added on:</p>\n\n<pre><code>(3 + 1)\n(2 + 2)\n2 + 1 (+ 1)\n1 + 1 + 1 (+ 1)\n</code></pre>\n\n<p>This pattern continues all the way down to one where there is only one sum: <code>1</code> itself.</p>\n\n<p>Hopefully, this pattern is hinting to you that there is a recurrence relation we could take advantage of. Namely, if we know the number of sums for 5 is the number of sums for 4 plus some extras. This goes all the way down to 1. This should hint to you that a recursive solution may be appropriate. However, there's a catch. While we can implement it recursively, it turns out that the dependency chain isn't linear. Each answer depends on every answer before it. Because of this, even though you could compute the answer recursively, it would be inefficient, because it would require recomputing the answer for every number below. But we're really close.</p>\n\n<p>As an aside, there are other (perhaps more natural) phrasings of this problem, which may make this <code>+1</code> structure more obvious. Consider you have <code>n</code> pennies. How many unique groups of all <code>n</code> pennies can you make (each group is like one of the terms in the addition). For example, if <code>n = 5</code> then a group of 4 pennies and a group of 1 pennies (one of the sums for 5) is like 4 + 1.</p>\n\n<p>The efficient solution recalls that we can take a dynamic programming approach where we memoize answers to smaller problems. We can do so by accumulating a list of the previous answers <code>num_ways_to_sum</code> and build this up from 1 up to the desired number:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def count_number_of_ways_to_sum(target_sum):\n \"\"\"\n Compute the number of unique ways (order does not matter) of summing to target_sum\n using numbers from 1 to target_sum, exclusive.\n \"\"\"\n if target_sum <= 1:\n raise ValueError('there are no numbers greater than 0 less than the target sum')\n\n # ith index contains the answer to the (i + 1)th subproblem\n num_ways_to_sum = [0] * (target_sum + 1)\n\n # There is only 1 way to sum to 1\n num_ways_to_sum[0] = 1\n\n # Consider sums involving numbers in [1, target_sum)\n for i in range(1, target_sum):\n # Every subproblem j >= i depends on i\n for j in range(i, target_sum + 1):\n # The number of ways to sum j includes all the ways to sum i \n # with all the ways to sum (j - i) appended (like the parenthesis)\n num_ways_to_sum[j] += num_ways_to_sum[j - i]\n\n return num_ways_to_sum[target_sum]\n</code></pre>\n\n<p>Note a few things:</p>\n\n<ul>\n<li>We document and properly name the function</li>\n<li>We are careful with domain. We <code>raise ValueError</code> when we are given an impossible <code>target_sum</code>. (1 has no solution, because there are no counting numbers less than 1 but greater than 0)</li>\n<li>We name variables appropriately. It is clear what <code>num_ways_to_sum</code> is. We may even consider renaming <code>i</code> and <code>j</code>, although the comments perhaps make them clear enough (and given that they are only used over 3 lines, this information is close together and intelligible as a single unit.</li>\n<li>We comment!</li>\n<li>We use python standard library features appropriately (like <code>list</code>s, <code>range</code>, etc.)</li>\n</ul>\n\n<p>Now, you should definitely test this with the <code>unittest</code> package.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:45:00.613",
"Id": "423602",
"Score": "0",
"body": "Thanks a lot for your great explanation and effort. From now on, I'll be much more careful about the variable names and syntax.I ll test it and try to understand the dynamical programming. Thanks a lot again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T05:39:56.300",
"Id": "219290",
"ParentId": "219250",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "219290",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T14:06:03.217",
"Id": "219250",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge",
"combinatorics"
],
"Title": "Project Euler 76: Counting summations"
} | 219250 |
<p>Here is the <a href="https://leetcode.com/problems/number-of-islands/description/" rel="nofollow noreferrer">question</a>:</p>
<blockquote>
<p>Given a 2d grid map of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically. You may assume
all four edges of the grid are all surrounded by water.</p>
<h3>Example 1:</h3>
<p>Input:</p>
<pre><code>11110
11010
11000
00000
</code></pre>
<p>Output: 1</p>
<h3>Example 2:</h3>
<p>Input:</p>
<pre><code>11000
11000
00100
00011
</code></pre>
<p>Output: 3</p>
</blockquote>
<p>And this is my proposed solution. Can someone please help me understand how can I improve the code. Any comments are most welcome.</p>
<pre><code>public class NumberOfIsland {
private static final int MIN_ROW = 0;
private static final int MIN_COL = 0;
int noOfRows;
int noOfColumn;
boolean[][] isVisited;
char[][] gridArray;
public int numIslands(char[][] grid) {
final char LAND = '1';
final char WATER = '0';
int numOfIsLands = 0;
if(grid.length == 0) {
return 0;
}
gridArray = grid;
noOfRows = grid.length;
noOfColumn = grid[0].length;
// Assuming that no of rows and columns are constant.
isVisited = new boolean[noOfRows][noOfColumn];
for (int i = 0; i < noOfRows; i++) {
for (int j = 0; j < noOfColumn; j++) {
if(gridArray[i][j] == LAND && !isVisited[i][j]) {
doDFSStartingFromNode(i, j);
numOfIsLands++;
}
}
}
return numOfIsLands;
}
private void doDFSStartingFromNode(final int i, final int j) {
Stack<Coordinates> stack = new Stack<>();
stack.push(new Coordinates(i,j));
while (!stack.empty()) {
Coordinates peekedCoordinates = stack.peek();
if(Objects.isNull(peekedCoordinates)) {
return;
}
if(isNoMorePathAvailable(peekedCoordinates)) {
stack.pop();
} else {
stack.push(nextAvailablePath(peekedCoordinates));
}
}
}
private Coordinates nextAvailablePath(Coordinates peekedCoordinates) {
if(canMoveUp(peekedCoordinates)) {
isVisited[peekedCoordinates.x-1][peekedCoordinates.y] = true;
return new Coordinates(peekedCoordinates.x-1, peekedCoordinates.y);
} else if(canMoveRight(peekedCoordinates)) {
isVisited[peekedCoordinates.x][peekedCoordinates.y+1] = true;
return new Coordinates(peekedCoordinates.x, peekedCoordinates.y+1);
} else if(canMoveBottom(peekedCoordinates)) {
isVisited[peekedCoordinates.x+1][peekedCoordinates.y] = true;
return new Coordinates(peekedCoordinates.x+1, peekedCoordinates.y);
} else if(canMoveLeft(peekedCoordinates)) {
isVisited[peekedCoordinates.x][peekedCoordinates.y-1] = true;
return new Coordinates(peekedCoordinates.x, peekedCoordinates.y-1);
}
return null;
}
private boolean isNoMorePathAvailable(final Coordinates peekedCoordinates) {
if(!canMoveUp(peekedCoordinates) && !canMoveRight(peekedCoordinates) && !canMoveBottom(peekedCoordinates) && !canMoveLeft(peekedCoordinates) ) {
return true;
}
return false;
}
private boolean canMoveBottom(Coordinates peekedCoordinates) {
int x = peekedCoordinates.x;
int y = peekedCoordinates.y;
if((x + 1 <= noOfRows - 1) && (gridArray[x+1][y] == '1' ) && !isVisited[x + 1][y]) {
return true;
}
return false;
}
private boolean canMoveLeft(Coordinates peekedCoordinates) {
int x = peekedCoordinates.x;
int y = peekedCoordinates.y;
if((y-1 >= MIN_COL) && (gridArray[x][y-1] == '1' ) && !isVisited[x][y-1]) {
return true;
}
return false;
}
private boolean canMoveRight(Coordinates peekedCoordinates) {
int x = peekedCoordinates.x;
int y = peekedCoordinates.y;
if((y+1 <= noOfColumn -1) && (gridArray[x][y+1] == '1' ) && !isVisited[x][y+1]) {
return true;
}
return false;
}
private boolean canMoveUp(Coordinates peekedCoordinates) {
int x = peekedCoordinates.x;
int y = peekedCoordinates.y;
if((x-1 >= MIN_ROW) && (gridArray[x-1][y] == '1') && !isVisited[x-1][y]) {
return true;
}
return false;
}
}
class Coordinates {
int x;
int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
</code></pre>
| [] | [
{
"body": "<h1>Code Organization</h1>\n\n<p>Assigning fields in the method. Intialize your fields in the constructor. It isn't clear what <code>numIslands</code> does. The public API lies. It pretends to be a \"service\" whereas it actually is a \"method object\". Services should be immutable.</p>\n\n<p>API says I could use this class like so:</p>\n\n<pre><code>final NumberOfIsland n = new NumberOfIsland();\ntestCases.parallelStream().map(grid -> n.numIslands(grid));\n</code></pre>\n\n<p>Intended usage is actually:</p>\n\n<pre><code>testCases.parallelStream().map(grid -> new NumberOfIsland().numIslands(grid));\n</code></pre>\n\n<ul>\n<li>Constants are defined in local scope, and later also used hardcoded. If you define a constant replace all instances of the literal value. for example <code>char LAND = '1'</code> should be a static field and later <code>'1'</code>s also should be changed.</li>\n</ul>\n\n<p>Whereas you can omit MIN_ROW, because you can assume everyone knows 0 is the minimum array index.</p>\n\n<ul>\n<li><code>doDFSStartingFromNode(final int i, final int j)</code>:\nIn this method you create a <code>Coordinates</code> from <code>i</code>, <code>j</code> and never use them again. <code>i</code>, <code>j</code> are not a node, they are a pair of indices. You can pass the object into the method instead. such that the signature can now become <code>doDFS(Node startNode)</code>.</li>\n</ul>\n\n<h2>Naming problems</h2>\n\n<ul>\n<li>Classes are nouns, methods are verbs etc. These are not hard rules but even if you violate them, you should name your code artefacts such that your code reads well regardless.\nCompare:</li>\n</ul>\n\n<blockquote>\n <p>A <code>NumberOfIsland</code> consists of a <code>gridArray</code>, an <code>isVisited</code> matrix,\n ...</p>\n</blockquote>\n\n<p>with </p>\n\n<blockquote>\n <p>A <code>NumberOfIslandsSolver</code> consists of a <code>grid</code>, a <code>visited</code> matrix,\n ...</p>\n</blockquote>\n\n<ul>\n<li><code>Coordinates</code> Do not use plural names unless it's a collection. And this is not a collection, you cannout add a coordinate to coordinates etc. (Even when a class is a collection, name it such that reader can guess its behavior, CoordinateSet, CoordinateQueue etc.) Location, Position, or Cell, or GridCell etc are better names for this class.</li>\n</ul>\n\n<h2>Redundant code</h2>\n\n<ul>\n<li><code>canMoveBottom</code> etc are copy pasted code. and in each of them <code>y+1</code> etc is repeated three times. Factor out repetitive code.</li>\n</ul>\n\n<h2>Inefficiencies</h2>\n\n<ul>\n<li><p>You should use an <code>ArrayDeque</code> instead of <code>Stack</code>. Don't use synchronized classes unless you really know what you are doing, or it causes poor performance. (Similarly you shouldn't use <code>Vector</code> where an <code>ArrayList</code> will do, <code>StringBuffer</code> where a <code>StringBuilder</code> will do, etc... (Protip: If you encounter a class with synchronized methods in an API, it's either very special purpose or a legacy class kept around for backwards compatibility; and you probably should use something else.)</p></li>\n<li><p>You call <code>canMoveX</code> thrice: once in <code>nextAvailablePath</code>, once in <code>isNoMorePathAvailable</code> and once after. Organize your logic such that you shouldn't call that code multiple times.</p></li>\n</ul>\n\n<h2>Style</h2>\n\n<ul>\n<li><p>If you follow standard java spacing you can lose unnecessary parentheses and <code>if</code>s etc like so:</p>\n\n<pre><code>private boolean canMoveRight(Coordinates peekedCoordinates) {\n int x = peekedCoordinates.x;\n int y = peekedCoordinates.y;\n int newY = y + 1;\n\n return newY < noOfColumn && gridArray[x][newY] == '1' && !isVisited[x][newY];\n}\n</code></pre></li>\n<li><p>Speaking of standard spacing; put a space after keywords <code>if</code>, <code>while</code>, <code>try</code> so they don't look weird.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:12:21.897",
"Id": "219364",
"ParentId": "219252",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T14:18:16.820",
"Id": "219252",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"graph",
"depth-first-search",
"backtracking"
],
"Title": "Find number of islands Leetcode"
} | 219252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.