body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is quite a specific script I have written, for Kubernetes Cluster monitoring purposes (specifically the Nodes). Essentially, I need to ensure that the Nodes within a NodeGroup all have the same labels and label values, or else they will not be scaled out evenly for Node Scale out in the version of Kubernetes we are using (Cluster Auto Scaler wants the values to be the same in order to treat the Nodes equally).</p>
<p>The env var IN_CLUSTER is used so I can set whether the script is run from my local machine (which can read kubectl config) or whether it's running as a container within the cluster (leverage RBAC permissions).</p>
<p>The script I have written works and does what I need - get a list of Nodes in the cluster, iterate through each NodeGroup (there are four Node Groups - core, general, observability, pci). We group the Nodes into their relevant NodeGroup. We then check each Node within the NodeGroup, and do a comparison to ensure the labels match.</p>
<p>The script implements the Kubernetes client for retrieving list of Nodes. The script also implements the Kuberhealthy client, which is simply to report the check results (success or failure) to the Kuberhealthy master.</p>
<p>I do not like the fact that the four NodeGroups are hardcoded in the script but can't think how to achieve what I want with an array stored as an env var.</p>
<p>The script is intended to simply run top to bottom and be simple. I'm not sure it makes sense to have the <code>if __name__ == '__main__'</code> directive as it's never going to be imported as a module.</p>
<pre><code>from kubernetes import client, config
from kh_client import *
import os
# requires cluster role with permissions list, get nodes!
# needs refactoring, for time being have kept it as a 'top to bottom' script
def main():
if os.getenv('IN_CLUSTER') == "TRUE":
config.load_incluster_config()
else:
config.load_kube_config()
try:
api_instance = client.CoreV1Api()
node_list = api_instance.list_node()
except client.exceptions.ApiException:
print("401 Unauthorised. Please check you are authenticated for the target cluster / have set the IN_CLUSTER env var.")
exit(2)
node_group_core = []
node_group_general = []
node_group_observability = []
node_group_pci = []
# print("%s\t\t%s" % ("NAME", "LABELS"))
# this needs changing but difficult to do with an env_var
for node in node_list.items:
if node.metadata.labels.get('nodegroup-name') == "core":
node_group_core.append(node)
if node.metadata.labels.get('nodegroup-name') == "general":
node_group_general.append(node)
if node.metadata.labels.get('nodegroup-name') == "observability":
node_group_observability.append(node)
if node.metadata.labels.get('nodegroup-name') == "pci":
node_group_pci.append(node)
check_node_group_labels(node_group_core)
check_node_group_labels(node_group_general)
check_node_group_labels(node_group_observability)
check_node_group_labels(node_group_pci)
# everything has checked successfully, report success.
print("Reporting Success.")
try:
report_success()
except Exception as e:
print(f"Error when reporting success: {e}")
def check_node_group_labels(node_group):
# ignored labels taken from https://github.com/kubernetes/autoscaler/blob/3a69f118d95cd653bf101aecc0ea5e00bf7ba370/cluster-autoscaler/processors/nodegroupset/aws_nodegroups.go#L26
# this can be refactored
ignored_labels = [ "alpha.eksctl.io/instance-id",
"alpha.eksctl.io/nodegroup-name",
"eks.amazonaws.com/nodegroup",
"k8s.amazonaws.com/eniConfig",
"lifecycle",
# labels i've added
"topology.kubernetes.io/zone",
"kubernetes.io/hostname",
"failure-domain.beta.kubernetes.io/zone" ]
node_group_labels = []
for l in node_group[0].metadata.labels:
if l not in ignored_labels:
node_group_labels.append(l)
print(f"There are {len(node_group)} nodes in {node_group[0].metadata.labels.get('nodegroup-name')}")
for label in node_group_labels:
# compare against the 'benchmark' label, any difference means a mismatch as far as CAS is concerned
# print(label)
benchmark_label = node_group[0].metadata.labels.get(label)
# print("benchmark label: ", benchmark_label)
for node in node_group[1:]:
# print("node label", node.metadata.labels.get(label))
if node.metadata.labels.get(label) != benchmark_label:
print("Reporting Failure.")
try:
report_failure([f"Warning! label mismatch detected, for nodegroup and node {node.metadata.name}, benchmark value: {benchmark_label}, this node value: {node.metadata.labels.get(label)}"])
except Exception as e:
print(f"Error when reporting failure: {e}")
if __name__ == '__main__':
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Regarding:</p>\n<blockquote>\n<p>I do not like the fact that the four NodeGroups are hardcoded in the\nscript but can't think how to achieve what I want with an array stored\nas an env var.</p>\n</blockquote>\n<p>We can start first by creating a dictionary with all the <code>node_groups</code> and then start to refactor a bit of our code:</p>\n<pre><code>NODE_GROUPS = {\n 'core': [],\n 'general': [],\n 'observability': [],\n 'pci': [],\n}\n</code></pre>\n<p>By doing this, we'll remove some of the duplicate code we have in the <code>main</code> function:</p>\n<pre><code>def main():\n # ...\n for node in node_list.items:\n nodegroup_name = node.metadata.labels.get('nodegroup-name')\n\n for node_group_name, nodes in NODE_GROUPS.items():\n if nodegroup_name == node_group_name:\n nodes.append(node)\n\n for node_group in NODE_GROUPS.values():\n check_node_group_labels(node_group)\n \n # ...\n</code></pre>\n<p>Now, storing <code>NODE_GROUPS</code> into a config file wouldn't be a great idea because the new format would not help us. If you really want to take the node groups out I'd suggest you use a different method.</p>\n<hr />\n<blockquote>\n<p>I'm not sure it makes sense to have the <code>if __name__ == '__main__'</code>\ndirective as it's never going to be imported as a module.</p>\n</blockquote>\n<p>This guard is boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:</p>\n<ul>\n<li><p>If you import the guardless script in another script (e.g. <code>import my_script_without_a_name_eq_main_guard</code>), then the second script will trigger the first to run at import time and using the second script's command line arguments. This is almost always a mistake.</p>\n</li>\n<li><p>If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.</p>\n</li>\n</ul>\n<p>I'd say it's usually good practice to have it in your code but not mandatory. To read more about it <a href=\"https://stackoverflow.com/a/419185/8605514\">check this answer</a></p>\n<p>Here's how I'd style the whole script:</p>\n<pre><code>import os\nimport sys\n\nfrom kh_client import *\nfrom kubernetes import client, config\n\n\nNODE_GROUPS = {\n 'core': [],\n 'general': [],\n 'observability': [],\n 'pci': [],\n}\nIGNORED_LABELS = (\n "alpha.eksctl.io/instance-id",\n "alpha.eksctl.io/nodegroup-name",\n "eks.amazonaws.com/nodegroup",\n "k8s.amazonaws.com/eniConfig",\n "lifecycle",\n \n # custom labels\n "topology.kubernetes.io/zone",\n "kubernetes.io/hostname",\n "failure-domain.beta.kubernetes.io/zone"\n)\n\n\ndef load_config():\n if os.getenv('IN_CLUSTER') == "TRUE":\n config.load_incluster_config()\n else:\n config.load_kube_config()\n\n\ndef get_nodes():\n try:\n api_instance = client.CoreV1Api()\n return api_instance.list_node()\n except client.exceptions.ApiException:\n print("401 Unauthorised. Please check you are authenticated "\n "for the target cluster / have set the IN_CLUSTER env "\n "var.")\n sys.exit(2)\n \n \ndef get_group_labels(node_group):\n return [\n node_group_label for node_group_label in node_group[0].metadata.labels\n if node_group_label not in IGNORED_LABELS\n ]\n\n\ndef check_node_group_labels(node_group):\n node_group_labels = get_group_labels(node_group)\n\n print(f"There are {len(node_group)} nodes in "\n f"{node_group[0].metadata.labels.get('nodegroup-name')}")\n\n for label in node_group_labels:\n # compare against the 'benchmark' label, any difference means \n # a mismatch as far as CAS is concerned\n benchmark_label = node_group[0].metadata.labels.get(label)\n \n for node in node_group[1:]:\n label = node.metadata.labels.get('nodegroup-name')\n if label != benchmark_label:\n print("Reporting Failure.")\n \n try:\n report_failure([\n f"Warning! label mismatch detected, for nodegroup and "\n f"node {node.metadata.name}, benchmark value: {benchmark_label}, "\n f"this node value: {label}"\n ])\n except Exception as e:\n print(f"Error when reporting failure: {e}")\n\n\ndef main():\n load_config()\n nodes = get_nodes()\n\n for node in nodes.items:\n nodegroup_name = node.metadata.labels.get('nodegroup-name')\n\n for node_group_name, group_nodes in NODE_GROUPS.items():\n if nodegroup_name == node_group_name:\n group_nodes.append(node)\n\n for node_group in NODE_GROUPS.values():\n check_node_group_labels(node_group)\n\n print("Reporting Success.")\n try:\n report_success()\n except Exception as e:\n print(f"Error when reporting success: {e}")\n \n \nif __name__ == '__main__':\n main()\n</code></pre>\n<p>I haven't tested this as I don't have any kube cluster but here are some of the things I've improved:</p>\n<ul>\n<li>create smaller functions to easier allow writing unit tests / check the correctness of your code</li>\n<li>improved some variable names</li>\n<li>reordered the imports</li>\n<li><code>exit</code> is a helper for the interactive shell - <code>sys.exit</code> is intended for use in programs. Use the second one.</li>\n</ul>\n<hr />\n<p>Homework for OP:</p>\n<ul>\n<li>try adding docstrings to your code;</li>\n<li>avoid using bare excepts unless necessary</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T08:54:08.143",
"Id": "521835",
"Score": "0",
"body": "That's brilliant thanks very much. Will take a look at your suggestions now and feed back in due course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T09:44:10.700",
"Id": "521836",
"Score": "0",
"body": "this code here (line 65 in yours) causes my script to fail... i dont think it's doing what it looks like (not sure if it conflicts with 'label' defined above) \n```label = node.metadata.labels.get(label)```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T12:45:14.827",
"Id": "521839",
"Score": "0",
"body": "Oupsie, that should actually be: `label = node.metadata.labels.get('nodegroup-name')`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T08:21:26.030",
"Id": "264231",
"ParentId": "264230",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T06:38:42.137",
"Id": "264230",
"Score": "4",
"Tags": [
"python",
"kubernetes"
],
"Title": "Kuberhealthy Check - check NodeGroup labels are matching"
}
|
264230
|
<blockquote>
<p>Update at the end</p>
</blockquote>
<p>Is it possible to implement <code>IDisposable</code> pattern correctly while using object composition principle to promote code-reuse, reduce code duplication and hide <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose" rel="nofollow noreferrer">verbose "official" implementation</a>?</p>
<h2>Rational</h2>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow noreferrer">Composition over inheritance</a> is a good principle</li>
<li>Implementing <code>IDisposable</code> correctly and thoroughly is very verbose and cumbersome</li>
</ul>
<h2>Proposal</h2>
<p>Delegate the dispose logic to a dedicated class:</p>
<pre><code>public class DisposeManager
{
public Action Managed { get; set; }
public Action Unmanaged { get; set; }
protected virtual void Dispose(bool disposing)
{
// only dispose once
if (disposed)
return;
if (disposing)
{
Managed?.Invoke();
}
Unmanaged?.Invoke();
disposed = true;
}
public void DisposeObject(object o)
{
Dispose(disposing: true);
GC.SuppressFinalize(o);
}
public void FinalizeObject()
{
Dispose(disposing: false);
}
private bool disposed;
}
</code></pre>
<p>Implement <code>IDisposable</code> in user class in the following way:</p>
<pre><code>public class DisposeUser : IDisposable
{
public DisposeUser()
{
// using lambda
disposeManager.Managed = () =>
{
// [...]
};
// or using member method
disposeManager.Unmanaged = DisposeUnmanaged;
}
~DisposeUser()
{
disposeManager.FinalizeObject();
}
public void Dispose()
{
disposeManager.DisposeObject(this);
}
private void DisposeUnmanaged()
{
// [...]
}
private readonly DisposeManager disposeManager = new DisposeManager();
}
</code></pre>
<h2>Benefits</h2>
<ul>
<li>much simpler to implement for user classes</li>
<li>more explicit (managed, unmanaged)</li>
<li>use composition</li>
<li>remove the needs for multiple base classes all implementing the dispose pattern and creating code duplication</li>
</ul>
<h2>Questions</h2>
<ul>
<li>Is it ever a good idea or more of a programmer fancy "improvement" idea ?</li>
<li>I've made a decent number of research on the dispose pattern and implementation but never found someone suggesting such idea, any reason why?</li>
<li>Any potential problems around hard refs, especially with Action capturing members, etc. that would prevent the actual user class to be collected correctly?</li>
<li>Other thought?</li>
</ul>
<p>Thanks!</p>
<h1>Update</h1>
<h2>Drawbacks mention in answers</h2>
<p>Mainly the drawbacks that were pointed in the answers are:</p>
<ul>
<li>probably overkill for most case because it's rare to have unmanaged resources to dispose</li>
<li>doesn't cover <code>IAsyncDisposable</code></li>
<li>performance impact (delegates)</li>
<li><code>Managed</code> and <code>Unmanaged</code> action properties can re-set later</li>
<li>Loose the <em>well-known pattern</em> knowledge for other developers</li>
<li>Not much simpler/reducing code</li>
</ul>
<h2>New version</h2>
<p>After using this base version in a project, I've made some improvements that may address some of the drawbacks mentioned. However this new version also accentuates some of them.</p>
<h3>Changes</h3>
<ul>
<li>expose list of actions to allow child class to easily add dispose logic</li>
<li>add extensions methods to ease the add of disposable child(s)</li>
<li>extension method to register to an event and unregister on dispose in one line</li>
</ul>
<p>Those changes doesn't address much of the drawbacks mentioned, but I think it starts to bring enough benefits for the developer on a daily-basis usage to be worth it. Of course it's the case only if performance is not a concern and you need to dispose stuff in various places.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:41:10.463",
"Id": "522057",
"Score": "2",
"body": "`but never found someone suggesting such idea, any reason why?` Disposing/Memory Management is a pretty sensitive to implementation topic. The solution for 99% cases looks like overkill (i have no unmanaged resources to dispose), for 0,99% looks like too generic because a very special implementation is needed. Also performance concern forces me to think about delegate allocations which can be simply avoided with implementing `IDisposable` natively. Finally, why there's nothing about `IAsyncDisposable`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T07:29:03.380",
"Id": "522338",
"Score": "1",
"body": "`DisposeManager`'s `Managed` and `Unmanaged` properties feel so wrong. Allowing consumers to define their own method without any constraint can be really dangerous. For example they can call [ReRegisterForFinalize](https://docs.microsoft.com/en-us/dotnet/api/system.gc.reregisterforfinalize) and with that they can resurrect the object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:17:14.513",
"Id": "525554",
"Score": "0",
"body": "@aepot I see your point about \"too generic\" and I also asked this question myself. Therefore I was thinking to simply implement `IDisposable` directly were needed and ignore unmanaged.\nHowever, what if a derived class needs to dispose **unmanaged** resources but the base class already implement `IDisposable` with a simple `public virtual void Dispose()` that doesn't deal with unmanaged?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:18:18.140",
"Id": "525556",
"Score": "0",
"body": "@PeterCsala Agree, would be better to give them a ctor time. Is it what you suggest?"
}
] |
[
{
"body": "<p>I think there is nothing wrong with your code, however I am unsure if it provides a significant benefit. What you are doing here is replacing one pattern with another, which is for sure simpler, but only marginally. So instead of one if and one SupressFinalize you need a FinalizeObject, DisposeObject a lambda. Not convinced this is a huge improvement, that might be the reason why you don't see it anywhere, although some kind of a dispose-helper is a frequent sight in many codebases. The problem with the new patterns is of course is that they are not known to people, so between a well-known pattern and a new pattern which is marginally better, I think the old pattern is preferable.\nLet's address your list of questions and benefits:</p>\n<p><strong>Benefits</strong></p>\n<ul>\n<li><p><em>much simpler to implement for user classes</em></p>\n<p>As discussed, simpler, but not much simpler.</p>\n</li>\n<li><p><em>more explicit (managed, unmanaged)</em></p>\n<p>True, however since there is no compile-time difference between the callbacks, my guess that after a while you will find that they are mixed up in the code base.</p>\n</li>\n<li><p><em>use composition</em></p>\n<p>This is not a benefit. True, composition preferred to inheritance in most cases, but there is a reason for that, we should not just do composition for it's own sake.</p>\n</li>\n<li><p><em>remove the needs for multiple base classes all implementing the dispose pattern and creating code duplication</em></p>\n<p>True, but then again, it has nearly as much code as before.</p>\n</li>\n</ul>\n<p>Questions</p>\n<ul>\n<li><p><em>Is it ever a good idea or more of a programmer fancy "improvement"\nidea ?</em></p>\n<p>Might be both. I don't see anything wring with using it, but forcing it on the codebase would be unwise.</p>\n</li>\n<li><p><em>I've made a decent number of research on the dispose pattern and\nimplementation but never found someone suggesting such idea, any\nreason why?</em></p>\n<p>Probably for the reasons above</p>\n</li>\n<li><p><em>Any potential problems around hard refs, especially with Action\ncapturing members, etc. that would prevent the actual user class to\nbe collected correctly?</em></p>\n<p>I don't thinks so. There might be an issue with disposable ref-structs, but you would not want to use your code for them anyway. In some high-perf scenarios creating a bunch of new objects is a no-go, but it is rare.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:56:38.217",
"Id": "525564",
"Score": "0",
"body": "Thanks for the detailed answer. I agree about the _well-known pattern_ and also the _not much simpler_. I've tried using this in a project and added some functionalities that make this more useful and provide more benefits I think. I will edit by question to share it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:44:23.350",
"Id": "264335",
"ParentId": "264232",
"Score": "5"
}
},
{
"body": "<p>Your code neither inherits nor composes "disposable-ability" with class DisposeManager. It is not being injected - the definition of composition. How many different "dispose" schemes does any class need anyway? Encapsulating DisposeManager implementation is not inherited, as a practical matter, without public methods. And you still must implement IDisposable. Inheriting means your object IS A "Disposable" type when an object should just BE "disposable", which is what an interface does. Besides subverting .NET GC design these notions conflate the complementary but distinct purposes of interface, composition, and inheritance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:07:45.717",
"Id": "525550",
"Score": "0",
"body": "From my understanding [Composition over inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance) doesn't necessarily implies ctor injection. Taken from the C++ example they do for example `Player() : Object(new Visible(), new Movable(), new Solid())`. Besides this article, I think it's often a good idea to group a set of related behaviors in a sep. class to promote easier code reuse elsewhere. Even if it's not up to the point where it is injected. For the rest I can see your point about the possible confusion of this solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T05:02:37.117",
"Id": "264366",
"ParentId": "264232",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264335",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T09:27:57.447",
"Id": "264232",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
".net",
"memory-management"
],
"Title": "Implement IDisposable correctly using object composition principle"
}
|
264232
|
<p>Python Noob building an automation irrigation system in Python for Raspberry Pi.</p>
<p>Python has two functions in the most basic use case:</p>
<ol>
<li>on/off the LED (which will in future be a relay->pump) and</li>
<li>Notifies "This is out of water" (which will in future be a HTTP post)</li>
</ol>
<ul>
<li>I have a GPIO switch that working successfully on: <code>water_level_sensor.value </code></li>
<li>I obviously don't want the While loop to just spam that its looping, it should <strong>only</strong> print on each change of state</li>
</ul>
<p>The below code appears to work successfully on both use cases, however, I am unsatisfied/unconfident that this is a very good/clean method to achieve the "print once" per change of state loop.</p>
<p>It works by having:</p>
<ul>
<li>X = "Wet" outside the outer while loop</li>
<li>X = "Dry" at the bottom of the nest while</li>
<li>X = "NULL" at the bottom of the inner loop</li>
</ul>
<p>It just seems messy... <strong>How should someone solve this kind of problem neatly/efficiently?</strong>
I'm also concerned that I will struggle to pull out of this solution any state data.</p>
<pre><code>def water_level():
while True:
x = "Wet"
while water_level_sensor.value == False:
water_level_led.value = False
if x == "Wet":
print("They System has Water")
x = "Dry"
while water_level_sensor.value == True:
water_level_led.value = True
if x == "Dry":
print("The System is Dry and needs Water")
x = ""
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T14:51:54.480",
"Id": "521845",
"Score": "1",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>If I understand what you are trying to do, I think you can (1) remember the\nprior state, (2) print only on changes, and (3) select the message to\nprint based on the new state.</p>\n<pre><code>def water_level():\n messages = {\n False: "The system has water",\n True: "The system is dry and needs water",\n }\n previous = None\n while True:\n val = water_level_sensor.value\n if val != previous:\n water_level_led.value = val\n print(messages[val])\n previous = val\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:00:01.167",
"Id": "521926",
"Score": "1",
"body": "Shouldn't there be some sleep call somewhere?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:07:04.117",
"Id": "264241",
"ParentId": "264236",
"Score": "6"
}
},
{
"body": "<p>Just curious, but have you checked CPU usage ? Programs that run in a while loop can be terribly inefficient and taxing. Here you are just probing a sensor, this does not look like a computationally-intensive task but it's still overkill.</p>\n<p>Seems to me that a <strong>timer</strong> would be preferable. Sampling values from your sensors at regular intervals, even every few minutes, would be sufficient.\nYou have a simple example of Python timer here: <a href=\"https://stackoverflow.com/q/35410498\">How to repeat a function every N minutes?</a> and links to more advanced discussions.</p>\n<p>There is no real-time imperative here. Most of the time your application will be idle and should not consume a lot of resources.</p>\n<p>I see one possible improvement: given that the accuracy of the sensors may be approximate, and that threshold values could cause ups and downs in the sampled reading, I would wait for multiple confirmations of low water levels before triggering the "need water" event. This is not ICU, the plant is not going to die if it has to wait a bit for its dose of water :)</p>\n<p>Don't use variable names like x, instead use more meaningful names like you did in the rest of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T22:37:47.437",
"Id": "521965",
"Score": "0",
"body": "Not checked CPU... I'll need to do that. For your other point, You're right - not super time-sensitive, a minute or so is not going to kill the plants. I'm just unsure how to represent this with an N function - will take your recommended reading - thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T20:51:28.657",
"Id": "264260",
"ParentId": "264236",
"Score": "8"
}
},
{
"body": "<p>I agree with @Anonymous that you should not loop continuously like that, or you'll waste energy and CPU time continuously checking the values. To solve this you can just sleep, wake up every minute, check the state and go back to sleep.</p>\n<p>Another more code-style related observation is that you don't need to nest <code>while</code> loops like that, but only keep track of the last value.</p>\n<p>The variable naming is also not ideal, use descriptive naming instead of <code>x</code>. Actually in this case, you do not need the variable at all.</p>\n<p>For instance, you could do:</p>\n<pre><code>import time\n\ndef water_level():\n previous_water_low = None\n while True:\n water_low = water_level_sensor.value\n\n if water_low != previous_water_low:\n on_water_level_change(water_low)\n\n previous_water_low = water_low\n time.sleep(60)\n\n def on_water_level_change(water_low: bool):\n water_level_led.value = water_low\n\n if water_low:\n print("The System is Dry and needs Water")\n else:\n print("They System has Water")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T22:45:15.177",
"Id": "521966",
"Score": "0",
"body": "Thank you for the detail and example code - very helpful. Its slightly confusing to me as my coding is not sufficient to understand what is fully going on here. particularly around \"on_water_level_change\" and \"def on_water_level_change(water_low: bool):\" Its very efficient looking solution though. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T07:37:31.257",
"Id": "521987",
"Score": "0",
"body": "@GlennB This is similar to what @FMc proposed in the other answer. You just keep track of what the last `water_level_sensor` value and if that changes it triggers a `on_water_level_change`, where you can take actions based on the change. I also added an extra sleep to reduce energy use. I just like to factor the real actions into an own function, so that you have a loop doing the triggering and another function defining what happens on water level change. You could also change the trigger condition (multiple sensors? wait for multiple dry minutes?), without changing the action function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:47:42.543",
"Id": "524814",
"Score": "0",
"body": "Thanks @francesco-pasa; I updated your code and its working perfectly with the following format"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:44:02.863",
"Id": "264281",
"ParentId": "264236",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "264281",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T14:19:15.263",
"Id": "264236",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"raspberry-pi",
"status-monitoring"
],
"Title": "Loop to print changes in irrigation state to turn on and off a pump when water is low"
}
|
264236
|
<p>Hello programming gurus/reviewers,
I attempted to solve the Minimum Window Substring (Leetcode 76) problem using Python 3. My solution involved using Counters and backtracking. On submission, the solution worked for all cases, other than the last test case where the strings were almost 10000 characters long. This last case timed out, and I am wondering if someone could point out the bottleneck(s) in my code that's causing this. Any input would be greatly appreciated. Thanks in advance!</p>
<pre><code>from collections import Counter
def get_indices(s: str, t: str, left_edge: int):
"""
Helper method to return the indices of test string 't' in main string 's'
:param s: Main string to determine window in
:param t: Test string
:param left_edge: Starting index where search for t in s should take place
:return: A List of indices corresponding to positions of characters of t in s. If character is not found, the index
is set to -1
"""
indices = [0] * len(t)
index_list = dict()
for index, char in enumerate(t):
if char not in s[left_edge:]:
index_list[char] = -1
else:
if index_list.get(char, -1) >= 0:
index_list[char] = s.find(char, index_list.get(char, 0) + 1)
else:
index_list[char] = s.find(char, left_edge)
indices[index] = index_list[char]
return indices
def is_valid_window(main_string, search_string):
"""
Helper method to determine if the search_string is in the main_string. This is done using the character count in
both strings
:param main_string: String where the window is to be validated
:param search_string: Substring to search for in the main string
:return: True, if the search string is 'contained' in the main string
False, otherwise
"""
main_counter = Counter(main_string)
search_counter = Counter(search_string)
for key, value in search_counter.items():
if main_counter[key] < value:
return False
return True
def get_min_window(s, t):
"""
Main method to determine the smallest window of substring t in s. The substring may or may not be contained in the
same order/sequence in s. If a substring is not found, return an empty string
:param s: Main string to determine a window in
:param t: Test string to search for, in the main string
:return: If found, the smallest window in s, that contains t. Empty string otherwise
"""
min_window = ''
# Set the min length to be larger than the main string's length
min_length = len(s) + 1
# If the test string is larger than the main string, or if either string is empty, or the test string is a single
# character which is not in the main string, return an empty string
if not s or not t:
return min_window
if len(s) < len(t):
return min_window
if len(t) == 1:
if t in s:
return t
else:
return min_window
# Markers to track the left and right edges of the window
left = right = 0
while right < len(s):
indices = get_indices(s, t, left)
left = min(indices)
right = max(indices)
if left < 0:
return min_window
# At this point, we have a window in place. But now, we need to determine if this is the smallest window between
# characters at 'left' and 'right' indices. For that, we move from 'left' to 'right' and see if t can still be
# contained in s. This will give us a new left index. Then we determine if this is the smallest window we have
# encountered thus far, and update if necessary
while left < right:
if is_valid_window(s[left + 1:right + 1], t):
left += 1
break
if right - left + 1 < min_length:
min_window = s[left:right + 1]
min_length = len(min_window)
# We have now found the smallest window at index left. So we move on to the next index
left += 1
return min_window
</code></pre>
|
[] |
[
{
"body": "<h3 id=\"style-naming-comments-etc-k9ke\">Style, naming, comments, etc.</h3>\n<p>Great job! Yes, you could add some more type annotations, but never mind. You're good.</p>\n<h3 id=\"optimization-la92\">Optimization</h3>\n<p>Python is a great language in terms of readability... and not so great in terms of performance traps. Every slice, <code>in</code> and <code>find</code> on <code>str</code> are <span class=\"math-container\">\\$O(n)\\$</span> time complexity, and used in a loop over characters of that string, you get <span class=\"math-container\">\\$O(n^2)\\$</span>, which is not good. You got the idea right, but because of this hidden work you're losing it.</p>\n<h3 id=\"dont-save-the-string-save-its-coordinates-aqzz\">Don't save the string - save its coordinates</h3>\n<p>I think code speaks for itself:</p>\n<pre><code>if right - left + 1 < min_length:\n min_right, min_left = right, left\n min_length = right - left + 1\n...\nreturn s[min_right:min_left+1]\n</code></pre>\n<p>One slice after the loop is enough.</p>\n<h3 id=\"keep-track-on-counters-pzmo\">Keep track on counters</h3>\n<p>The whole algorithm is something like this:</p>\n<ul>\n<li>We start at <code>left</code>=0, <code>right</code>=0, counter of <code>t</code> (<code>tcounter</code>) filled (and remains so), counter of <code>s[left:right]</code> (<code>scounter</code>) empty.</li>\n<li>While <code>scounter</code> doesn't have all needed characters (compare it to <code>tcounter</code>), increase <code>right</code>, adding s[right] into <code>scounter</code> (with <code>Counter.update()</code>)</li>\n<li>While <code>scounter</code> has all needed characters, increase <code>left</code>, removing from <code>scounter</code> (with <code>Counter.subract()</code>)</li>\n<li>Save <code>(left-1,right)</code> pair (not the substring!), if it is minimal (i.e. right-left is minimal), and repeat the process until <code>right</code> reaches the end of the string.</li>\n<li>Now, use saved left and right values to get the slice you need.</li>\n</ul>\n<p>This algorithm is something near <span class=\"math-container\">\\$O(len(s) len(t) log(len(t)))\\$</span>, with everything after <span class=\"math-container\">\\$len(s)\\$</span> is for accesing counter. I guess it should fit.</p>\n<h3 id=\"can-we-do-better-brzx\">Can we do better?</h3>\n<p>I think yes. We can use <code>list</code>s instead of <code>Counter</code>s (like <code>scounter[s[right]-'a'] += 1</code> instead of <code>scounter.update(s[right])</code>), removing <span class=\"math-container\">\\$log(len(t))\\$</span> part, and even more:</p>\n<ul>\n<li>let's count the number of needed chars, say <code>needed</code>.</li>\n<li>Whenever a char is added to <code>scounter</code>, if it brings us closer to the value in <code>tcounter</code>, <code>needed</code> is reduced.</li>\n<li>Whenever a char is removed, if it makes not enough chars, <code>needed</code> is increased. -</li>\n<li>If <code>needed</code> is 0 - we have the window between <code>left</code> and <code>right</code>. This way we can get <span class=\"math-container\">\\$O(len(s))\\$</span> time complexity.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:51:23.600",
"Id": "521946",
"Score": "0",
"body": "Ahh thank you sir! My initial guess was that Counters were causing this to slow down. But I forgot about slicing and other operations operating in O(n) complexity! I am going to try your suggestions to see if I can get over the hump. Will probably update this thread in a few days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T17:42:19.040",
"Id": "522373",
"Score": "0",
"body": "Just incorporated your suggestions in a new method. Worked like a charm! Thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T17:05:00.203",
"Id": "264248",
"ParentId": "264237",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264248",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T14:36:32.730",
"Id": "264237",
"Score": "3",
"Tags": [
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Attempting to solve minimum window substring problem using Python 3.8"
}
|
264237
|
<p>I have been coding in Java for about a month now and I'm seeking advice for my program on things I can improve. This project was mainly made for me to incorporate all the new things I learned and utilize them effectively. I appreciate any feedback :).</p>
<p>About the program itself, it takes in a string and reverses it. It also counts the amount of characters (spaces, numbers, letters, and other characters) and it checks if the typed string is a palindrome or not.</p>
<h1 id="main-class-lv71">Main class</h1>
<pre><code>public class Main {
public static void main(String[] args) {
Application application = new Application();
application.printInstructions();
application.programLoop();
application.printSeparator(); // Prints a separator before the program terminates.
}
}
</code></pre>
<h1 id="application-class-nqvj">Application class</h1>
<pre><code>import java.util.Scanner;
public class Application {
Scanner userInput = new Scanner(System.in);
String definedString;
// Main function for reversing the string.
private String reverseString(String string) {
StringBuilder stringBuilder = new StringBuilder();
char[] charArray = string.toCharArray();
for (int i = string.length() - 1; i >= 0; i--) {
stringBuilder.append(charArray[i]);
}
return stringBuilder.toString();
}
// Processes the output and prints it out.
private void processInput() {
printSeparator();
System.out.println("Reversed String: " + reverseString(definedString));
printSeparator();
countCharacters(definedString);
isPalindrome();
programLoop();
}
// Main program loop.
public boolean programLoop() {
System.out.print("-: ");
definedString = userInput.nextLine();
// If the input isn't the break command, it processes and prints out the results.
while (!definedString.equals("!break")) {
processInput();
}
return false;
}
// Prints starting instructions.
public void printInstructions() {
System.out.println("StringModifier - Reverses a string and returns information about it.");
System.out.println("Type '!break' to exit");
}
// Counts the amount of characters in the reversed string.
private void countCharacters(String string) {
char[] charArray = string.toCharArray();
int letters = 0;
int numbers = 0;
int spaces = 0;
int other = 0;
for (int i = 0; i < string.length(); i++) {
if (Character.isSpaceChar(charArray[i])) {
spaces++;
} else if (Character.isDigit(charArray[i])) {
numbers++;
} else if (Character.isLetter(charArray[i])) {
letters++;
} else {
other++;
}
}
System.out.println("Spaces: " + spaces);
System.out.println("Numbers: " + numbers);
System.out.println("Letters: " + letters);
System.out.println("Other: " + other);
}
// Adds a separating line.
public void printSeparator() {
System.out.println("—————————————————————————————————————");
}
// Checks if the string is a palindrome.
public void isPalindrome() {
if (definedString.equals(reverseString(definedString))) {
System.out.println("Is a Palindrome: Yes");
} else {
System.out.println("Is a Palindrome: No");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You should rewrite your <code>reverseString</code> to use the built-in <a href=\"https://devdocs.io/openjdk%7E15/java.base/java/lang/stringbuilder#reverse()\" rel=\"nofollow noreferrer\">StringBuilder.reverse()</a>.</p>\n<p>Your class structure is a little bit mixed up. The <code>Application</code> and <code>Main</code> classes currently have some of the same obligations. Rephrase this to, perhaps,</p>\n<ul>\n<li>a <code>Main</code> class that only cares about display and does your program loop</li>\n<li>a <code>StringInfo</code> class that does no integrated display in its logic methods, and has accessor functions for reversed (returning a string and not printing), isPalindrome (returning a boolean and not printing), spaceCount (returning an integer and not printing), etc.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n final Scanner userInput = new Scanner(System.in);\n\n public static void main(String[] args) {\n Main app = new Main();\n\n printInstructions();\n app.programLoop();\n printSeparator();\n }\n\n // Prints starting instructions.\n public static void printInstructions() {\n System.out.println("StringModifier - Reverses a string and returns information about it.");\n System.out.println("Type '!break' to exit");\n }\n\n // Main program loop.\n public void programLoop() {\n // If the input isn't the break command, it processes and prints out the results.\n while (true) {\n printSeparator();\n System.out.print("-: ");\n String definedString = userInput.nextLine();\n if (definedString.equals("!break"))\n break;\n (new StringInfo(definedString)).dump();\n }\n }\n\n // Adds a separating line.\n public static void printSeparator() {\n System.out.println("—————————————————————————————————————");\n }\n}\n\npublic class StringInfo {\n public final String definedString;\n\n public StringInfo(String definedString) {\n this.definedString = definedString;\n }\n\n public String reversed() {\n StringBuilder builder = new StringBuilder(definedString);\n builder.reverse();\n return builder.toString();\n }\n\n public long nSpaces() {\n return definedString.chars().filter(ch -> Character.isSpaceChar(ch)).count();\n }\n\n public long nLetters() {\n return definedString.chars().filter(ch -> Character.isLetter(ch)).count();\n }\n\n public long nDigits() {\n return definedString.chars().filter(ch -> Character.isDigit(ch)).count();\n }\n\n public long nOther() {\n return definedString.chars().filter(ch -> !(\n Character.isSpaceChar(ch)\n || Character.isLetter(ch)\n || Character.isDigit(ch)\n )).count();\n }\n\n public boolean isPalindrome() {\n return definedString.equals(reversed());\n }\n\n public void dump() {\n System.out.printf("Reversed String: %s%n", reversed());\n System.out.printf("Spaces: %d%n", nSpaces());\n System.out.printf("Digits: %d%n", nDigits());\n System.out.printf("Letters: %d%n", nLetters());\n System.out.printf("Other: %d%n", nOther());\n\n System.out.print("Is a palindrome: ");\n if (isPalindrome()) System.out.println("yes");\n else System.out.println("no");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T06:51:09.213",
"Id": "521905",
"Score": "0",
"body": "Thank you for your feedback! I do have one question though. Why is it preferable to use return statements instead of just printing it out from the method? My thought is to probably have flexible values which I can use anywhere in my program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T11:47:53.517",
"Id": "521923",
"Score": "1",
"body": "@Kimosauraus Why prefer return over printing? Because you might want to re-use things like string reverting or character counting later in a program with a GUI, or in a web server or whatever. Make it a habit to separate information processing from input/output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T11:56:43.883",
"Id": "521925",
"Score": "0",
"body": "Ah, I see. Thank you for your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:27:07.050",
"Id": "264244",
"ParentId": "264238",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T14:47:29.143",
"Id": "264238",
"Score": "1",
"Tags": [
"java",
"performance",
"beginner"
],
"Title": "StringModifier - Reverses a string and returns information about it"
}
|
264238
|
<p>This code was an answer to my own <a href="//stackoverflow.com/questions/68411538">question on SO</a>, however I am looking at the line <code>global X</code> and wondering if there is a better way to do this. I try to minimize the amount of global declarations in my code in order to avoid namespace collisions. I'm considering changing this code to use <a href="https://docs.python.org/3/library/multiprocessing.shared_memory.html" rel="nofollow noreferrer">multiprocessing.shared_memory</a>, but I would like some feedback on the code below 'as is'.</p>
<p>The purpose of this code is to compute in parallel the <a href="https://en.wikipedia.org/wiki/Pearson_correlation_coefficient" rel="nofollow noreferrer">Pearson's product-moment correlation coefficient</a> on all pairs of random variables. The columns of NumPy array <code>X</code> index the variables, and the rows index the sample.</p>
<p><span class="math-container">$$r_{x,y} = \frac{\sum_{i=1}^{n}(x_i- \bar{x})(y_i- \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i- \bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_i- \bar{y})^2}}$$</span></p>
<p>This is actual code that should run on your machine (ex. <code>python 3.6</code>).</p>
<pre class="lang-py prettyprint-override"><code>from itertools import combinations
import numpy as np
from scipy.stats import pearsonr
from multiprocessing import Pool
X = np.random.random(100000*10).reshape((100000, 10))
def function(cols):
result = X[:, cols]
x,y = result[:,0], result[:,1]
result = pearsonr(x,y)
return result
def init():
global X
if __name__ == '__main__':
with Pool(initializer=init, processes=4) as P:
print(P.map(function, combinations(range(X.shape[1]), 2)))
</code></pre>
<p>In addition to considering <code>global X</code>, any constructive feedback and suggestions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:18:08.480",
"Id": "521850",
"Score": "2",
"body": "Please clarify the purpose of the code. What problem does it solve? Perhaps taking a look at the [help/on-topic] will help in determining whether you posted your question in the right place, especially the part talking about example code might be relevant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:23:03.327",
"Id": "521851",
"Score": "2",
"body": "\"toy examples\", sadly, are explicitly off-topic for CodeReview. If you show this code in its real context we are more likely able to help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:27:23.137",
"Id": "521852",
"Score": "0",
"body": "@Reinderien Toy examples being off-topic surprises me. I expect they should have clearer and simpler scope and behaviour, and consequently easier to explain and understand. I will have to think on whether to edit or delete this question. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:48:31.927",
"Id": "521855",
"Score": "1",
"body": "To a first approximation, `global` is never needed in Python (the legitimate exceptions are truly rare). Even more strongly, one can say the `global` will never help with any kinds of shared-memory or parallelism problems, because it doesn't address the real issue — namely, what happens when two processes/threads operate on the same data and the same time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T03:33:43.760",
"Id": "524939",
"Score": "1",
"body": "The applied edits do not address the close reason. Note that the close reason is essentially saying that there isn't enough code to review. So to address it, you would need to add more code. Of course, since there is an answer, you can't do that. Rather than throwing it into the Reopen queue, a better approach would be to discuss it on meta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T03:58:48.630",
"Id": "524941",
"Score": "0",
"body": "@mdfst13 For future questions, it would be useful to know precisely how much code is required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T04:21:26.933",
"Id": "524942",
"Score": "0",
"body": "Sure, which is also better asked on meta if the links in the close reason are not sufficient."
}
] |
[
{
"body": "<p>If you are not going to write anything to <code>X</code> (which it seems you are not doing), and just going to read from it, you should be good to just have all processes access the same variable without some locking mechanism.</p>\n<p>Now, <code>global</code> is not necesarily the way to go. Here is different approach:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import combinations\nimport numpy as np\nfrom scipy.stats import pearsonr\nfrom multiprocessing import Pool\n\n\nclass MyCalculator:\n\n def __init__(self, X):\n self.X = X\n\n def function(self, cols):\n result = self.X[:, cols]\n x,y = result[:,0], result[:,1]\n result = pearsonr(x,y)\n return result\n\n\ndef main():\n X = np.random.random(100000*10).reshape((100000, 10))\n myCalculator = MyCalculator(X)\n with Pool(processes=4) as P:\n print(P.map(myCalculator.function, \n combinations(range(X.shape[1]), 2)))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:43:34.900",
"Id": "521861",
"Score": "0",
"body": "Yes, good work on inferring that I am interested in the read-only cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:44:00.317",
"Id": "521862",
"Score": "0",
"body": "Tried to run the code in this answer and got a traceback: `AttributeError: Can't pickle local object 'main.<locals>.<lambda>'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:58:06.553",
"Id": "521864",
"Score": "0",
"body": "My bad, I'll update the approach. Nested function cannot be pickeld"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:39:31.643",
"Id": "264245",
"ParentId": "264240",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264245",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T14:56:59.287",
"Id": "264240",
"Score": "-1",
"Tags": [
"python",
"namespaces"
],
"Title": "Compute pairwise Pearson's R in parallel with tasks separated by pairs of columns of an array"
}
|
264240
|
<p>I'm developing a screen recording application using java. I've modified code from <a href="https://dzone.com/articles/screen-record-play-using-java" rel="nofollow noreferrer">https://dzone.com/articles/screen-record-play-using-java</a> where all the external jars required for this application are available.</p>
<p>If I lower <code>captureInterval</code> to 25 then the application runs out of memory - i.e. it throws a <strong>java.lang.OutOfMemoryError</strong> exception on the line below within the Recorder method <code>startRecord()</code>.</p>
<pre><code>List<Image> resolutionVariants = mrImage.getResolutionVariants();
</code></pre>
<p>How can the code be more efficient with memory?</p>
<p><strong>Recorder.java</strong></p>
<pre><code>import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.MultiResolutionImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.imageio.ImageIO;
import javax.media.MediaLocator;
public class Recorder {
/**
* Screen Width.
*/
public static final int screenWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
/**
* Screen Height.
*/
public static final int screenHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
/**
* Interval between which the image needs to be captured.
*/
public static final int captureInterval = 41;
/**
* Base folder to store the recorded video.
*/
public static final String videoPath = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "Records" + File.separator;
/**
* Temporary folder to store the screenshot.
*/
public static final String store = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "Records" + File.separator + "tmp" + File.separator;
/**
* Status of the recorder.
*/
private static AtomicBoolean record = new AtomicBoolean(false);
private static Thread recordThread;
private static Thread processThread;
private static BlockingDeque<Image> imageList = new LinkedBlockingDeque<>();
public static void startRecord() {
record.set(true);
recordThread = new Thread(() -> {
try {
Robot rt = new Robot();
Rectangle rect = new Rectangle(screenWidth, screenHeight);
while (record.get()) {
long startTime = System.currentTimeMillis();
Image nativeResImage;
MultiResolutionImage mrImage = rt.createMultiResolutionScreenCapture(rect);
List<Image> resolutionVariants = mrImage.getResolutionVariants();
if (resolutionVariants.size() > 1)
nativeResImage = resolutionVariants.get(1);
else
nativeResImage = resolutionVariants.get(0);
imageList.putLast(nativeResImage);
long endTime = System.currentTimeMillis();
long sleepTime = captureInterval - (endTime - startTime);
if (sleepTime > 0)
Thread.sleep(sleepTime);
}
} catch (Exception e) {
e.printStackTrace();
}
});
processThread = new Thread(() -> {
while (record.get() || (!imageList.isEmpty())) {
try {
Image nativeResImage = imageList.takeFirst();
ImageIO.write((BufferedImage) nativeResImage, "jpeg", new File(store
+ System.currentTimeMillis() + ".jpeg"));
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
});
processThread.start();
recordThread.start();
System.out.println("\nEasy Capture is recording now!!!!!!!");
}
}
</code></pre>
<p><strong>Main.java</strong></p>
<pre><code>import java.awt.*;
import java.io.File;
import java.util.Scanner;
import com.bel.recorder.Recorder;
public class Main {
public static void main(String[] args) {
System.out.println("######### Starting Easy Capture Recorder #######");
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println("Your Screen [Width, Height]: " + "[" + screen.getWidth() + ", " + screen.getHeight() + "]");
Scanner sc = new Scanner(System.in);
System.out.println("Rate [" + 24 + "] Frames/Per Sec.");
File fileDir = new File(Recorder.videoPath);
if (!fileDir.exists()) {
if (!fileDir.mkdir())
System.err.println("Error in creating the directory " + fileDir.getName());
}
fileDir = new File(Recorder.store);
if (!fileDir.exists()) {
if (!fileDir.mkdir())
System.err.println("Error in creating the directory " + fileDir.getName());
}
Recorder.startRecord();
System.out.println("Press x to exit:");
String exit = sc.next();
while (exit == null || "".equals(exit) || !"x".equalsIgnoreCase(exit)) {
System.out.println("\nPress x to exit:");
exit = sc.next();
}
// Recorder.stopRecord();
File tmpDirectory = new File(Recorder.store);
File[] files = tmpDirectory.listFiles();
if (files == null)
return;
for (File file : files)
file.delete();
tmpDirectory.delete();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T17:34:53.367",
"Id": "521869",
"Score": "0",
"body": "Thanks for providing more information about the scenario. I [changed the title](https://codereview.stackexchange.com/revisions/264243/5) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T21:34:31.260",
"Id": "521875",
"Score": "0",
"body": "I bet it is not so much about memory efficiency, but the file IO throughput. It seems that `recordThread` starts to produce frames faster than `processThread` may save them to a disk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T02:27:18.140",
"Id": "521889",
"Score": "0",
"body": "@vnp can you tell a better way of writing images to disk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T04:58:15.137",
"Id": "521898",
"Score": "0",
"body": "As I said, you cannot write them faster than your HD can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:02:05.030",
"Id": "521912",
"Score": "0",
"body": "As @vnp said and from the error it seems that your deque runs out all memory for the excessive number of the images present in the deque because you are created it with a capacity of `Integer.Max_value`. One thing I would do is create the deque with a fixed capacity with the appropriate constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T03:55:10.213",
"Id": "521977",
"Score": "0",
"body": "@dariosicily I tried doing that but still getting same exception. In the task manager memory keeps on increasing. I even tried writing `BufferedImage` to an `OutputStream` object instead to a `file` using `ImageIO.write`, but still no luck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T03:56:39.463",
"Id": "521978",
"Score": "0",
"body": "@vnp I want to know whether it's possible to record screen at `24fps`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:10:17.490",
"Id": "522022",
"Score": "0",
"body": "Depends. Screen size (including color depth), disk controller capabilities, jpeg quality - too many unknowns. One thing to consider is to use mpeg instead (_usually_ the screen is _mostly_ static). In any case, profile."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T15:56:44.517",
"Id": "264243",
"Score": "3",
"Tags": [
"java",
"memory-optimization"
],
"Title": "screen recording application"
}
|
264243
|
<p>I just wrote my pong DQN. It seems to work. I'm looking for a performance based review on anything that might slow down the training in complex models.</p>
<p>main.py:</p>
<pre class="lang-py prettyprint-override"><code>import gym
import torch
import torch.optim as optim
import matplotlib.pyplot as plt
from tensorboardX import SummaryWriter
import wrappers
import model
import common
plt.ion()
plt.show()
ENV_NAME = "PongNoFrameskip-v4"
DEVICE = torch.device("cuda")
EPSILON_START = 1.
EPSILON_FRAMES = 100000
EPSILON_FINAL = .02
REPLAY_SIZE = 100000
REPLAY_INITIAL = 10000
TGT_NET_SYNC = 1024
BATCH_SIZE = 64
LEARNING_RATE = 1e-4
GAMMA = .99
EVAL_INTERVAL = 10000
if __name__ == "__main__":
env = wrappers.wrap_env(gym.make(ENV_NAME))
net = model.ConvModel(env.observation_space.shape, env.action_space.n).to(DEVICE)
tgt_net = model.ConvModel(env.observation_space.shape, env.action_space.n).to(DEVICE)
net_opt = optim.Adam(net.parameters(), lr=LEARNING_RATE)
agent = common.DQNAgent(env, net, DEVICE, EPSILON_START)
buffer = common.ReplayBuffer(agent, REPLAY_SIZE)
test_env = gym.wrappers.Monitor(wrappers.wrap_env(gym.make(ENV_NAME)), "./records", force=True)
test_agent = common.DQNAgent(test_env, net, DEVICE, 0.)
writer = SummaryWriter(comment="DQN")
for batch_idx, batch in enumerate(buffer.iterate(REPLAY_INITIAL, BATCH_SIZE)):
if not batch_idx % TGT_NET_SYNC:
tgt_net.load_state_dict(net.state_dict())
if not batch_idx % EVAL_INTERVAL:
reward = sum([common.evaluate(test_agent) for _ in range(8)])/8
writer.add_scalar("reward", reward, batch_idx)
net_opt.zero_grad()
loss_v = common.calc_loss(batch, net, tgt_net, GAMMA, DEVICE)
loss_v.backward()
net_opt.step()
agent.epsilon = max(EPSILON_FINAL, EPSILON_START - batch_idx/EPSILON_FRAMES)
writer.add_scalar("loss", loss_v, batch_idx)
writer.add_scalar("eps", agent.epsilon, batch_idx)
</code></pre>
<p>common.py:</p>
<pre><code>import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import deque, namedtuple
Trajectory = namedtuple("Trajectory", ("state",
"action",
"reward",
"next_state",
"done",
"info"))
class DQNAgent(object):
def __init__(self, env, net, device, epsilon):
super(DQNAgent, self).__init__()
self.env = env
self.net = net
self.device = device
self.epsilon = epsilon
self.done = True
def __call__(self, obs):
if np.random.rand() > self.epsilon:
obs_v = torch.FloatTensor(obs[None, ...]).to(self.device)
action_vals = self.net(obs_v).squeeze().data.cpu().numpy()
action = int(np.argmax(action_vals))
else:
action = int(self.env.action_space.sample())
traj_raw = self.env.step(action)
traj = Trajectory(state=obs, action=action, reward=traj_raw[1],
next_state=traj_raw[0], done=traj_raw[2], info=traj_raw[3])
return traj
class ReplayBuffer(object):
def __init__(self, agent, maxlen):
super(ReplayBuffer, self).__init__()
self.agent = agent
self.core = deque(maxlen=maxlen)
self.last_obs = None
self.done = True
def populate_once(self):
if self.done:
self.last_obs = self.agent.env.reset()
self.done = False
traj = self.agent(self.last_obs)
self.last_obs = traj.next_state
self.done = traj.done
self.core.append(traj)
def populate(self, n):
for _ in range(n):
self.populate_once()
def sample(self, n):
indices = np.arange(len(self.core))
np.random.shuffle(indices)
return [self.core[idx] for idx in indices[:n]]
def iterate(self, initial, batch_size):
self.populate(initial)
while True:
yield self.sample(batch_size)
self.populate_once()
def calc_loss(batch, net, tgt_net, gamma, device):
states, actions, rewards, next_states, dones = [], [], [], [], []
for traj in batch:
states.append(np.array(traj.state, dtype=np.float32, copy=False))
next_states.append(np.array(traj.next_state, dtype=np.float32, copy=False))
actions.append(int(traj.action))
rewards.append(float(traj.reward))
dones.append(bool(traj.done))
states_v = torch.FloatTensor(np.array(states, copy=False)).to(device)
next_states_v = torch.FloatTensor(np.array(next_states, copy=False)).to(device)
actions_t = torch.LongTensor(np.array(actions, dtype=np.int64)).to(device)
rewards_v = torch.FloatTensor(np.array(rewards, dtype=np.float32)).to(device)
with torch.no_grad():
next_states_pred_v = tgt_net(next_states_v).max(dim=1)[0]
next_states_pred_v[dones] = 0.
bellman_unroll = (rewards_v + gamma * next_states_pred_v).detach()
values_pred_v = net(states_v)[range(states_v.shape[0]), actions_t]
return F.mse_loss(values_pred_v, bellman_unroll)
def evaluate(agent):
obs = agent.env.reset()
total_reward = 0.
while True:
traj = agent(obs)
obs = traj.next_state
total_reward += traj.reward
if traj.done:
break
return total_reward
</code></pre>
<p>model.py:</p>
<pre><code>import numpy as np
import torch
import torch.nn as nn
class ConvModel(nn.Module):
def __init__(self, input_shape, n_actions):
super(ConvModel, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels=input_shape[0], out_channels=16, kernel_size=(8, 8), stride=(4, 4), padding=(0, 0)), nn.LeakyReLU(.2),
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(4, 4), stride=(2, 2), padding=(0, 0)), nn.LeakyReLU(.2),
nn.Flatten())
self.fc = nn.Sequential(
nn.Linear(in_features=int(np.prod(self.conv(torch.zeros(1, *input_shape)).shape)), out_features=256), nn.LeakyReLU(.2),
nn.Linear(in_features=256, out_features=n_actions))
def forward(self, x):
return self.fc(self.conv(x))
</code></pre>
<p>wrappers.py:</p>
<pre><code>import gym
import numpy as np
import PIL.Image
from collections import deque
class ActionSkip(gym.Wrapper):
def __init__(self, env, n_skips=4):
super(ActionSkip, self).__init__(env)
self.observation_space = gym.spaces.Box(low=0, high=255, shape=(210, 160, 3), dtype=np.uint8)
self.n_skips = n_skips
def step(self, action):
queue = []
all_rewards = 0
for _ in range(self.n_skips):
obs, reward, done, _ = self.env.step(action)
queue.append(obs)
all_rewards += reward
if done:
break
return np.max(np.stack(queue), axis=0), all_rewards, done, {}
def reset(self, **kwargs):
return self.env.reset()
class ImageFormat(gym.ObservationWrapper):
def __init__(self, env):
super(ImageFormat, self).__init__(env)
self.observation_space = gym.spaces.Box(low=-1, high=1, shape=(1, 84, 84), dtype=np.float32)
def observation(self, observation):
obs_img = PIL.Image.fromarray(observation)
obs_resize = obs_img.resize((84, 84))
obs_transpose = np.asarray(obs_resize).mean(axis=-1)[None, ...]
return obs_transpose / 127.5 - 1.
class ResetEnv(gym.Wrapper):
def __init__(self, env=None):
super(ResetEnv, self).__init__(env)
self.observation_space = gym.spaces.Box(low=-1, high=1, shape=(1, 84, 84), dtype=np.float32)
def fire(self):
for _ in range(15):
obs, r, done, _ = self.env.step(self.env.action_space.sample())
if done:
return self.reset()
return obs
def step(self, action):
traj = self.env.step(action)
return traj
def reset(self):
self.env.reset()
return self.fire()
class FrameStack(gym.ObservationWrapper):
def __init__(self, env):
super(FrameStack, self).__init__(env)
self.queue = deque(maxlen=6)
self.observation_space = gym.spaces.Box(low=-1, high=1, shape=(6, 84, 84), dtype=np.float32)
def observation(self, observation):
self.queue.append(observation)
obs_stack = np.zeros((6, 84, 84))
for idx, element in enumerate(self.queue):
obs_stack[idx] = element[0]
return obs_stack
def reset(self, **kwargs):
self.queue.clear()
obs = self.env.reset()
obs_stack = np.zeros((6, 84, 84))
obs_stack[0] = obs[0]
return obs_stack
def wrap_env(env):
return FrameStack(ResetEnv(ImageFormat(ActionSkip(env))))
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T16:53:10.370",
"Id": "264246",
"Score": "2",
"Tags": [
"python",
"machine-learning",
"neural-network",
"pong"
],
"Title": "DQN implementation"
}
|
264246
|
<p>I wrote some code and realized they share similar logic. I am struggling to share the logic and welcome any suggestions.</p>
<pre><code>public List<string> SendTemplateAsSampleEmail(MtaConnection mtaConnection, ICollection<EmailRecipient> recipients,
SimpleContentDto renderedContent)
{
var errorStrings = new List<string>();
// Get the list of branded values
var fromAddress = BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase);
var replyToAddress = BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase);
var fromName = BrandingHelper.GetBrandName(_httpContextBase);
// First send as in TGE
if (!string.IsNullOrEmpty(renderedContent.HtmlText))
{
errorStrings.AddRange(SendTransactionalEmail(mtaConnection, recipients, renderedContent.HtmlText,
HtmlSubjectPrefixAsTge + renderedContent.Subject,
fromAddress, fromName, replyToAddress,
emailDomain: "bounce@bounce.myngp.com",
preHeader: null,
contentType: EmailContentType.HtmlContent));
}
return errorStrings;
}
public List<string> SendSampleEmailForHtmlContent(MtaConnection mtaConnection, ICollection<EmailRecipient> recipients, string name,
string htmlContent, string preHeader)
{
return SendTransactionalEmail(mtaConnection, recipients, htmlContent, HtmlSubjectPrefix + name,
fromAddress: BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase),
fromName: BrandingHelper.GetBrandName(_httpContextBase),
replyToAddress: BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase),
emailDomain: "bounce@bounce.myngp.com", preHeader: preHeader,
contentType: EmailContentType.HtmlContent);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T18:40:48.057",
"Id": "521872",
"Score": "1",
"body": "You're missing code - including the definition for `HtmlSubjectPrefix`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T18:45:35.240",
"Id": "521873",
"Score": "0",
"body": "Critically, also include the definition of `SendTransactionalEmail`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T06:56:30.830",
"Id": "522158",
"Score": "0",
"body": "Hi @dylandotnet, have you had a chance to read our reviews?"
}
] |
[
{
"body": "<p>There are many options. The most basic is to write a common routine with two frontends:</p>\n<pre><code>public List<string> SendTemplateAsSampleEmail(\n MtaConnection mtaConnection,\n ICollection<EmailRecipient> recipients,\n SimpleContentDto renderedContent)\n{\n if (string.IsNullOrEmpty(renderedContent.HtmlText))\n return new List<string>();\n // First send as in TGE\n return SendEmail(\n mtaConnection, recipients, \n content: renderedContent.HtmlText,\n subjectPrefix: HtmlSubjectPrefixAsTge,\n subject: renderedContent.Subject,\n preHeader: null\n );\n}\n\npublic List<string> SendSampleEmailForHtmlContent(\n MtaConnection mtaConnection, \n ICollection<EmailRecipient> recipients, \n string name,\n string htmlContent, \n string preHeader)\n{\n return SendEmail(\n mtaConnection, recipients, \n content: htmlContent, \n subjectPrefix: HtmlSubjectPrefix,\n subject: name,\n preHeader: preHeader,\n );\n}\n\npublic List<string> SendEmail(\n MtaConnection mtaConnection,\n ICollection<EmailRecipient> recipients,\n string content,\n string subjectPrefix,\n string subject,\n string preHeader)\n{\n return SendTransactionalEmail(\n mtaConnection, recipients, content, \n subjectPrefix + subject,\n fromAddress: BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase),\n fromName: BrandingHelper.GetBrandName(_httpContextBase),\n replyToAddress: BrandingHelper.GetFromAddressForSampleEmail(_httpContextBase),\n emailDomain: "bounce@bounce.myngp.com", \n preHeader: preHeader,\n contentType: EmailContentType.HtmlContent\n );\n}\n</code></pre>\n<p>But there are other problems with this code. If you ask to send an email with no body, it doesn't seem like a good idea to return a list of no errors - indicating that all went well; instead throw an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T19:15:33.953",
"Id": "264256",
"ParentId": "264251",
"Score": "0"
}
},
{
"body": "<p>Let's talk a little bit about the <code>SendTemplateAsSampleEmail</code> method:</p>\n<ul>\n<li>Perform the preliminary checks first\n<ul>\n<li>Your method might receive some "bad" input (like empty <code>HtmlText</code>) which can prevent the method to perform any kind of useful thing</li>\n<li>There is a common pattern called <a href=\"https://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\">fail fast</a> (or sometimes referred as <a href=\"https://medium.com/swlh/return-early-pattern-3d18a41bba8\" rel=\"nofollow noreferrer\">early exit</a>) which can be useful here</li>\n</ul>\n</li>\n</ul>\n<p>Before</p>\n<pre><code>public List<string> SendTemplateAsSampleEmail(...)\n{\n var errorStrings = new List<string>();\n var fromAddress = ...;\n var replyToAddress = ...;\n var fromName = ...;\n\n if (!string.IsNullOrEmpty(renderedContent.HtmlText))\n {\n errorStrings.AddRange(...);\n }\n return errorStrings;\n}\n</code></pre>\n<p>After</p>\n<pre><code>public List<string> SendTemplateAsSampleEmail(...)\n{\n if (string.IsNullOrEmpty(renderedContent.HtmlText))\n {\n return new List<string>();\n }\n\n var errorStrings = new List<string>();\n var fromAddress = ...;\n var replyToAddress = ...;\n var fromName = ...;\n\n errorStrings.AddRange(...);\n return errorStrings;\n}\n</code></pre>\n<ul>\n<li>So, instead of surrounding your core logic with a <a href=\"https://en.wikipedia.org/wiki/Guard_(computer_science)\" rel=\"nofollow noreferrer\">guard expression</a>, you can simply shortcut the execution if some conditions are not met\n<ul>\n<li>With this approach, you can omit the <code>BrandingHelper</code> calls if the <code>HtmlText</code> is empty</li>\n</ul>\n</li>\n<li>As it was said by <a href=\"https://codereview.stackexchange.com/users/25834/reinderien\">Reinderien</a> it might be a better idea to throw some exception whenever the <code>HtmlText</code> is empty rather than returning an empty collection</li>\n<li>You can further reduce the code by getting rid of the <code>errorStrings</code> variable</li>\n</ul>\n<pre><code>public List<string> SendTemplateAsSampleEmail(...)\n{\n //Preliminary checks\n if (string.IsNullOrEmpty(renderedContent.HtmlText))\n return new List<string>();\n\n //Data gathering\n var fromAddress = ...;\n var replyToAddress = ...;\n var fromName = ...;\n\n //Perform action and transform response to the desired format\n return SendTransactionalEmail(...).ToList();\n}\n</code></pre>\n<ul>\n<li>Because <code>AddRange</code> (<a href=\"http://ocs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.addrange\" rel=\"nofollow noreferrer\">Ref</a>) anticipates an <code>IEnumerable<T></code> that's why we need to call the <code>ToList</code>.\n<ul>\n<li>Of course if <code>SendTransactionalEmail</code> returns with a <code>List<string></code>\nthen the <code>ToList</code> can be omitted</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>For the sake of completeness I have to mention that early exit pattern is against the <a href=\"https://www.anthonysteele.co.uk/TheSingleReturnLaw.html\" rel=\"nofollow noreferrer\">single return law</a>.</p>\n<hr />\n<p>And one last remark</p>\n<ul>\n<li>It might be advisable to avoid relying on <code>HttpContext</code> in this method\n<ul>\n<li>Retrieve the necessary data as close to your http layer as possible</li>\n<li>This will give you reusability, you can call this method for those places as well where the <code>HttpContext</code> might not be available</li>\n<li>This will also give you <a href=\"https://en.wikipedia.org/wiki/Loose_coupling\" rel=\"nofollow noreferrer\">loose coupling</a> from the presentation layer</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:56:39.713",
"Id": "264273",
"ParentId": "264251",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T18:07:21.750",
"Id": "264251",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Factoring out common elements of an email transmission routine"
}
|
264251
|
<p>Kind of a noob at Python here, and this is one of my first "big"(big for a beginner like me) project that I undertook with <a href="https://docs.python.org/3/library/tkinter.html" rel="nofollow noreferrer">Tkinter</a> and <a href="https://pynput.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">Pynput</a>. Basically, this code will simulate an enemy's movement pattern based on some conditions that I made(you will be able to see the different "phases" being printed out on the console). You can then control the player using the arrow keys.</p>
<p>I would like some advice on what I should improve on for future projects. Should I add more comments? Is the code structured well? etc.</p>
<pre><code>import math
import tkinter as tk
from pynput import keyboard
class Application:
def __init__(self, master, height = 800, width = 800, updatesPerSecond = 10, safeCircle = True):
self.height = height
self.width = width
self.root = master
self.updatesPerSecond = updatesPerSecond
self.player = Player()
self.enemy = Enemy()
self.safeCircle = safeCircle
self.canvas = tk.Canvas(self.root, height = self.height, width = self.width)
self.canvas.pack()
self.player_rectangle = self.canvas.create_rectangle(self.player.x-self.player.hLength, self.player.y-self.player.hLength, self.player.x+self.player.hLength, self.player.y+self.player.hLength)
self.enemy_rectangle = self.canvas.create_rectangle(self.enemy.x-self.player.hLength, self.enemy.y-self.player.hLength, self.enemy.x+self.player.hLength, self.enemy.y+self.player.hLength)
if self.safeCircle:
self.safe_circle = self.canvas.create_oval(self.player.x-self.enemy.safe_distance, self.player.y-self.enemy.safe_distance, self.player.x+self.enemy.safe_distance, self.player.y+self.enemy.safe_distance)
self.keypress_list = []
self.listener = keyboard.Listener(on_press = self.on_press, on_release = self.on_release)
self.listener.start()
self.player_movement()
self.enemy_movement()
def player_movement(self):
if "down" in self.keypress_list:
self.player.update_y(self.player.speed)
if "up" in self.keypress_list:
self.player.update_y(-self.player.speed)
if "left" in self.keypress_list:
self.player.update_x(-self.player.speed)
if "right" in self.keypress_list:
self.player.update_x(self.player.speed)
self.player.boundary_check(self.height, self.width)
self.canvas.coords(self.player_rectangle, self.player.x-self.player.hLength, self.player.y-self.player.hLength, self.player.x+self.player.hLength, self.player.y+self.player.hLength)
if self.safeCircle:
self.canvas.coords(self.safe_circle, self.player.x-self.enemy.safe_distance, self.player.y-self.enemy.safe_distance, self.player.x+self.enemy.safe_distance, self.player.y+self.enemy.safe_distance)
self.root.after(1000//self.updatesPerSecond, self.player_movement)
def enemy_movement(self):
self.enemy.update_pos(self.player)
self.enemy.boundary_check(self.height, self.width)
self.canvas.coords(self.enemy_rectangle, self.enemy.x-self.enemy.length/2, self.enemy.y-self.enemy.length/2, self.enemy.x+self.enemy.length/2, self.enemy.y+self.enemy.length/2)
self.root.after(1000//self.updatesPerSecond, self.enemy_movement)
def key_test(self, key):
try:
return key.name
except:
return
def on_press(self, key):
key = self.key_test(key)
if not key in self.keypress_list:
self.keypress_list.append(key)
def on_release(self, key):
key = self.key_test(key)
self.keypress_list.remove(key)
class SimObject:
def __init__(self, x, y, speed, length):
self.x = x
self.y = y
self.speed = speed
self.length = length
self.hLength = self.length/2
def boundary_check(self, height, width):
if self.x - self.hLength < 0:
self.x = self.hLength
if self.y - self.hLength < 0:
self.y = self.hLength
if self.x + self.hLength > width:
self.x = width - self.hLength
if self.y + self.hLength > height:
self.y = height - self.hLength
def update_x(self, offset):
self.x+=offset
def update_y(self, offset):
self.y+=offset
class Player(SimObject):
def __init__(self, x = 400, y = 400, speed = 10, length = 20):
super().__init__(x, y, speed, length)
class Enemy(SimObject):
def __init__(self, x = 10, y = 10, speed = 5, length = 20, safe_distance = 100):
super().__init__(x, y, speed, length)
self.safe_distance = safe_distance
self.last_phase = -1
def update_phase(self, n):
phase_list=[f"{i} Phase" for i in ["Orbit", "Rush", "Run"]]
if self.last_phase!=n:
print(phase_list[n])
self.last_phase = n
def update_pos(self, player):
PI=math.pi
dx=player.x-self.x
dy=player.y-self.y
g_to_p_ang=math.atan2(dy,dx)
p_to_g_ang=PI+g_to_p_ang
dist=math.sqrt(dx*dx+dy*dy)
ang_increase=self.speed/self.safe_distance
t=p_to_g_ang
if abs(dist-self.safe_distance)<=self.speed:#near the orbit
self.update_phase(0)
t+=ang_increase
self.x=self.safe_distance*math.cos(t)+player.x
self.y=self.safe_distance*math.sin(t)+player.y
elif dist>self.safe_distance:#far from orbit
self.update_phase(1)
self.update_x(self.speed*math.cos(g_to_p_ang))
self.update_y(self.speed*math.sin(g_to_p_ang))
elif dist<self.safe_distance:#far inside of orbit
self.update_phase(2)
self.update_x(self.speed*math.cos(p_to_g_ang))
self.update_y(self.speed*math.sin(p_to_g_ang))
root = tk.Tk()
root.resizable(0,0)
root.title("Enemy Movement Test")
application = Application(root)
tk.mainloop()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Format your code according to PEP-8, there are automatic checker and even automatic formatters for that.</p>\n</li>\n<li><p>This is often considered as code smell:</p>\n</li>\n</ul>\n<pre><code> def key_test(self, key):\n try:\n return key.name\n except:\n return\n</code></pre>\n<p>See: <a href=\"https://stackoverflow.com/questions/10594113/bad-idea-to-catch-all-exceptions-in-python\">https://stackoverflow.com/questions/10594113/bad-idea-to-catch-all-exceptions-in-python</a></p>\n<ul>\n<li>Some methods are longer than I would consider readable and some of repetitive code. Try to extract some repeating code block as a methods and some repetitive expressions as well-named local variables to explain the process.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:44:29.793",
"Id": "264271",
"ParentId": "264257",
"Score": "2"
}
},
{
"body": "<p>In addition to what Roman Pavelka suggests:</p>\n<ul>\n<li>Represent your <code>keypress_list</code> as a <code>keypresses</code> set (note that it's not helpful to embed the type of a variable in its name; this is what type hints are for)</li>\n<li>Factor out rectangle-with-margin calculation routines into your <code>SimObject</code> class</li>\n<li>Do not 'start' anything in your constructor. 'start' in a separate routine or perhaps the entry method of a context manager, stopping in the corresponding exit routine.</li>\n<li>Do not assign a boolean to <code>self.safeCircle</code>; it should be an <code>Optional</code> (i.e. an object or <code>None</code>)</li>\n<li>Do not run separate timers for your enemy and player objects; just use one</li>\n<li><code>key_test</code> should be using <code>getattr</code> with a <code>None</code> default which will achieve the same effect in a more explicit and safe way</li>\n<li>Add PEP484 type hints</li>\n<li>Do not add the key name to the keypress set if the key name is <code>None</code></li>\n<li>Rephrase your <code>boundary_check</code> - which does not check at all (nothing is returned), so should be called something like <code>enforce_bounds</code> - as a series of <code>min</code> and <code>max</code> calls</li>\n<li>Represent <code>last_phase</code> as an enumeration for better maintainability and legibility</li>\n<li>No need to import <code>pi</code> if you just negate the coordinate deltas based on whether you are in the rush or run phase</li>\n<li>In <code>update_pos</code>, your last <code>else</code> needs no condition; that's redundant</li>\n<li>Move the logic at the bottom into a main guard</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>import enum\nimport math\nimport tkinter as tk\nfrom enum import Enum\nfrom typing import Optional, Tuple\n\nfrom pynput import keyboard\nfrom pynput.keyboard import Key\n\n\nclass Application:\n def __init__(\n self, master: tk.Tk, height: int = 800, width: int = 800,\n updates_per_second: int = 10, safe_circle: bool = True,\n ):\n self.height = height\n self.width = width\n self.root = master\n self.updates_per_second = updates_per_second\n self.player = Player()\n self.enemy = Enemy()\n self.canvas = tk.Canvas(self.root, height=self.height, width=self.width)\n self.canvas.pack()\n self.player_rectangle = self.canvas.create_rectangle(*self.player.rect)\n self.enemy_rectangle = self.canvas.create_rectangle(*self.enemy.rect)\n if safe_circle:\n self.safe_circle = self.canvas.create_oval(\n *self.player.margin_rect(self.enemy.safe_distance)\n )\n else:\n self.safe_circle = None\n self.keypresses = set()\n self.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)\n\n def __enter__(self) -> 'Application':\n self.listener.start()\n self.movement()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n self.listener.stop()\n\n def movement(self) -> None:\n self.player_movement()\n self.enemy_movement()\n self.root.after(1000 // self.updates_per_second, self.movement)\n\n def player_movement(self) -> None:\n if "down" in self.keypresses:\n self.player.update_y(self.player.speed)\n if "up" in self.keypresses:\n self.player.update_y(-self.player.speed)\n if "left" in self.keypresses:\n self.player.update_x(-self.player.speed)\n if "right" in self.keypresses:\n self.player.update_x(self.player.speed)\n self.player.enforce_bounds(self.height, self.width)\n self.canvas.coords(self.player_rectangle, *self.player.rect)\n if self.safe_circle:\n self.canvas.coords(\n self.safe_circle,\n *self.player.margin_rect(self.enemy.safe_distance)\n )\n\n def enemy_movement(self) -> None:\n self.enemy.update_pos(self.player.x, self.player.y)\n self.enemy.enforce_bounds(self.height, self.width)\n self.canvas.coords(\n self.enemy_rectangle,\n *self.enemy.margin_rect(self.enemy.length / 2),\n )\n\n @staticmethod\n def key_test(key: Key) -> Optional[str]:\n return getattr(key, 'name', None)\n\n def on_press(self, key: Key) -> None:\n key = self.key_test(key)\n if key is not None:\n self.keypresses.add(key)\n\n def on_release(self, key: Key) -> None:\n key = self.key_test(key)\n self.keypresses.discard(key)\n\n\n@enum.unique\nclass EnemyPhase(Enum):\n ORBIT = 'Orbit'\n RUSH = 'Rush'\n RUN = 'Run'\n\n\nclass SimObject:\n def __init__(self, x: int, y: int, speed: int, length: int):\n self.x = x\n self.y = y\n self.speed = speed\n self.length = length\n self.h_length = self.length / 2\n\n def enforce_bounds(self, height: int, width: int) -> None:\n self.x = max(self.h_length, min(width - self.h_length, self.x))\n self.y = max(self.h_length, min(height - self.h_length, self.y))\n\n def update_x(self, offset: float) -> None:\n self.x += offset\n\n def update_y(self, offset: float) -> None:\n self.y += offset\n\n def margin_rect(self, margin: float) -> Tuple[float, float, float, float]:\n return (\n self.x - margin, self.y - margin,\n self.x + margin, self.y + margin,\n )\n\n @property\n def rect(self) -> Tuple[float, float, float, float]:\n return self.margin_rect(self.h_length)\n\n\nclass Player(SimObject):\n def __init__(self, x: int = 400, y: int = 400, speed: int = 10, length: int = 20):\n super().__init__(x, y, speed, length)\n\n\nclass Enemy(SimObject):\n def __init__(\n self, x: int = 10, y: int = 10, speed: int = 5, length: int = 20,\n safe_distance: int = 100,\n ):\n super().__init__(x, y, speed, length)\n self.safe_distance = safe_distance\n self.last_phase = EnemyPhase.RUSH\n\n def update_phase(self, phase: EnemyPhase) -> None:\n if self.last_phase != phase:\n self.last_phase = phase\n print(f'{phase.value} Phase')\n\n def update_pos(self, player_x: float, player_y: float) -> None:\n dx = self.x - player_x\n dy = self.y - player_y\n p_to_g_ang = math.atan2(dy, dx)\n dist = math.sqrt(dx*dx + dy*dy)\n\n if abs(dist - self.safe_distance) <= self.speed: # near the orbit\n ang_increase = self.speed / self.safe_distance\n t = p_to_g_ang + ang_increase\n self.update_phase(EnemyPhase.ORBIT)\n self.x = self.safe_distance * math.cos(t) + player_x\n self.y = self.safe_distance * math.sin(t) + player_y\n else:\n sx = self.speed * math.cos(p_to_g_ang)\n sy = self.speed * math.sin(p_to_g_ang)\n if dist > self.safe_distance: # far from orbit\n self.update_phase(EnemyPhase.RUSH)\n self.update_x(-sx)\n self.update_y(-sy)\n else: # far inside of orbit\n self.update_phase(EnemyPhase.RUN)\n self.update_x(sx)\n self.update_y(sy)\n\n\ndef main():\n root = tk.Tk()\n root.resizable(0, 0)\n root.title("Enemy Movement Test")\n with Application(root):\n tk.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T22:28:02.583",
"Id": "521964",
"Score": "0",
"body": "Thanks for the review! As I did just start Python not long ago, I still have some trouble comprehending many parts of your suggested code, so I will need some time to be able to understand it. For now I just want to ask, do I need to install the `enum` and `typing` modules, and could you explain in more detail what those modules are doing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T02:01:18.860",
"Id": "521970",
"Score": "0",
"body": "Both modules are built-in; you have them already. `typing` adds non-runtime hints for programmers and static analysers to better understand your code. Enumerations are used to represent a variable that can take a constrained set of values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T21:40:40.753",
"Id": "264296",
"ParentId": "264257",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T19:30:09.023",
"Id": "264257",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"tkinter"
],
"Title": "Simple enemy movement simulation on Tkinter"
}
|
264257
|
<p>After much prompting from <a href="https://stackoverflow.com/questions/68464998/is-this-use-of-concurrentdictionary-correct-and-safe?noredirect=1#comment120999877_68464998">this post</a> I wanted to build a simple, in-memory, thread-safe cache.</p>
<p>The only caveat (as far as I was originally concerned) was the need for two different absolute expiration times for cached objects - those being based on a property of the item being cached (<code>IsFailureItem</code>). This is for a .NET Framework 4.6.1 solution.</p>
<p>I am primarily interested in anything which makes this either thread-unsafe, leak memory or simply bad practice. I know the class itself could be generically typed, but that is a decision for the future.</p>
<pre><code>public class CacheItem
{
public IEnumerable<DataItem> Response { get; set; }
public bool IsFailureItem { get; set; }
}
public class CacheHelper
{
public static CacheHelper Cache { get; set; }
private static IMemoryCache InMemoryCache { get; set; }
static CacheHelper()
{
Cache = new CacheHelper();
InMemoryCache = new MemoryCache(new MemoryCacheOptions { });
}
private CacheHelper() { }
public CacheItem this[string key]
{
get => InMemoryCache.Get<CacheItem>(key);
set => InMemoryCache.Set<CacheItem>(key, value, value.IsFailureItem ? FailureCacheEntryOption : SuccessCacheEntryOption );
}
private static MemoryCacheEntryOptions FailureCacheEntryOption => new MemoryCacheEntryOptions()
{ AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheFailureSecondsToLive) };
private static MemoryCacheEntryOptions SuccessCacheEntryOption => new MemoryCacheEntryOptions()
{ AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheSuccessSecondsToLive) };
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T05:43:07.970",
"Id": "521903",
"Score": "0",
"body": "Looks almost fine. `InMemoryCache` can be readonly field not property. Also you can remove setters from all other properties then introduce a constructor for `CacheItem`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:34:44.303",
"Id": "521908",
"Score": "0",
"body": "@aepot Thanks, changes added to post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:47:03.810",
"Id": "521910",
"Score": "2",
"body": "Don't edit the code in the post. That's not allowed here because it's making reviews not suitable to the post. Please rollback the edits through the edit history. If you want to share the final solution, you may post it in a separate answer. Btw, you may accept the review below in case it was helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:52:33.730",
"Id": "521911",
"Score": "1",
"body": "Thank you @aepot - very wise. Reverted."
}
] |
[
{
"body": "<p>No reason to have a public set on <code>public static CacheHelper Cache { get; set; }</code>\nnot anyway to set it so why expose it?</p>\n<p>I think CacheItem should be immutable. If calling Set with a CacheItem that IsFailureItem is true but later can be set to false, wouldn't effect time. Same with Response. Is it to be expected to be able to retrieve the CacheItem and update/replace the Response property?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:35:50.957",
"Id": "521909",
"Score": "0",
"body": "Thanks, changes applied in posted code. You're right about the immutability."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T20:45:22.013",
"Id": "264259",
"ParentId": "264258",
"Score": "3"
}
},
{
"body": "<p>Here is the code, after applying changes as advised by the wise commenters here:</p>\n<pre><code>public class CacheItem\n{\n public IEnumerable<DataItem> Response { get; }\n public bool IsFailureItem { get; }\n\n public CacheItem(bool isFailureItem, IEnumerable<DataItem> response = null)\n {\n IsFailureItem = isFailureItem;\n Response = response;\n }\n}\n\npublic class CacheHelper\n{\n public static CacheHelper Cache { get; }\n private static readonly IMemoryCache InMemoryCache;\n\n static CacheHelper()\n {\n Cache = new CacheHelper();\n InMemoryCache = new MemoryCache(new MemoryCacheOptions { });\n }\n\n private CacheHelper() { }\n\n public CacheItem this[string key]\n {\n get => InMemoryCache.Get<CacheItem>(key);\n set => InMemoryCache.Set<CacheItem>(key, value, value.IsFailureItem ? FailureCacheEntryOption : SuccessCacheEntryOption );\n }\n\n private static MemoryCacheEntryOptions FailureCacheEntryOption => new MemoryCacheEntryOptions()\n { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheFailureSecondsToLive) };\n\n private static MemoryCacheEntryOptions SuccessCacheEntryOption => new MemoryCacheEntryOptions()\n { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheSuccessSecondsToLive) };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:05:28.627",
"Id": "521937",
"Score": "0",
"body": "I would recommend in the constructor of CacheItem when setting Response to be 'Response = response ?? Enumerable.Empty<DataItem>()' I personally don't like null IEnumerables as linq will throw but on flip side setting value if someone passed in null would also be strange. Its a design choice you will need to make. To me I always lean to IEnumerables shouldn't be null"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:45:47.753",
"Id": "521945",
"Score": "0",
"body": "Actually, it would be great to be able to force that parameter/property to be non-null, but that's not possible at present. I guess I will actually throw an InvalidArgumentException. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:53:46.917",
"Id": "521947",
"Score": "0",
"body": "Actually, in retrospect, the `IEnumerable<DataItem> response = null` is there because it should only be null if `bool isFailureItem` is true. This is an application specific decision."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:53:49.847",
"Id": "264272",
"ParentId": "264258",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264259",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T20:15:29.250",
"Id": "264258",
"Score": "2",
"Tags": [
"c#",
".net",
"thread-safety",
"cache"
],
"Title": "Simple MemoryCache implementation for thread safe caching"
}
|
264258
|
<p>I am new to quant. finance and trying to calculate <code>trend</code>, <code>momentum</code>, <code>correlation</code> and <code>volatility</code>. Below are the functions I have created</p>
<pre><code>import pandas as pd
def roll_correlation(first_df, second_df, rolling_period):
"""
Rolling correlation
"""
return first_df.rolling(rolling_period).corr(second_df)
def roll_volatility(df, rolling_period):
"""
Rolling volatility
"""
return df.pct_change().rolling(rolling_period).std(ddof=0)
# ASK: is rolling momentum calculation is correct
def roll_momentum(df, rolling_period):
"""
Rolling momentum
"""
return df.pct_change(rolling_period)
def roll_returns(df, rolling_period):
"""
Rolling returns
"""
return df.rolling(rolling_period).apply(lambda x: x.iloc[[0, -1]].pct_change()[-1])
def trend(df, rolling_period):
"""
Identify trend
"""
return df.apply(lambda x: x.autocorr(rolling_period))
if __name__ == '__main__':
df = pd.Dataframe({'A': [1,2,3,4]})
print (trend(df,2))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T03:32:41.417",
"Id": "264264",
"Score": "1",
"Tags": [
"python",
"pandas",
"finance"
],
"Title": "quant. code. to calculate trend, momentum, correlation and volatility in Pandas(Python)"
}
|
264264
|
<p>My code in Julia, almost identical as the Python code (see below), runs in 4.6 s while the Python version runs in 2.4 s. Obviously there is a lot or room for improvement.</p>
<pre><code>function Problem12()
#=
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number would be:
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred
divisors?
=#
function num_divisors(n)
res = floor(sqrt(n))
divs = []
for i in 1:res
if n%i == 0
append!(divs,i)
end
end
if res^2 == n
pop!(divs)
end
return 2*length(divs)
end
triangle = 0
for i in Iterators.countfrom(1)
triangle += i
if num_divisors(triangle) > 500
return string(triangle)
end
end
end
</code></pre>
<p>Python version below:</p>
<pre><code>import itertools
from math import sqrt, floor
# Returns the number of integers in the range [1, n] that divide n.
def num_divisors(n):
end = floor(sqrt(n))
divs = []
for i in range(1, end + 1):
if n % i == 0:
divs.append(i)
if end**2 == n:
divs.pop()
return 2*len(divs)
def compute():
triangle = 0
for i in itertools.count(1):
# This is the ith triangle number, i.e. num = 1 + 2 + ... + i =
# = i*(i+1)/2
triangle += i
if num_divisors(triangle) > 500:
return str(triangle)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:16:51.813",
"Id": "521913",
"Score": "0",
"body": "What are compiler options for julia? Are you using interactive mode?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:32:38.693",
"Id": "521915",
"Score": "0",
"body": "Not sure about that. I'm just running vanilla Julia in VSCode"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T09:40:57.890",
"Id": "521916",
"Score": "1",
"body": "Check it. Also how do you measure time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T01:34:35.630",
"Id": "521969",
"Score": "0",
"body": "The big performance killer is due to `res` being a floating-point number. Replace `res = floor(sqrt(n))` by `res = isqrt(n)` and you should get an order of magnitude improvement in speed. I'll write up an answer that includes this."
}
] |
[
{
"body": "<p>You need the number of divisors, not divisors. So you don't need to gather all divisors, just remember the count. Increase it by 1 instead of push!/append, decrease instead of pop/</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:31:57.463",
"Id": "521914",
"Score": "0",
"body": "Thx for your answer! Although your suggestions do help in terms of allocations, they don't help in terms of performance :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:17:11.720",
"Id": "264274",
"ParentId": "264270",
"Score": "0"
}
},
{
"body": "<p>The performance discrepancy in your Julia code comes from</p>\n<pre><code>res = floor(sqrt(n)) # is a Float64\n</code></pre>\n<p>which is a floating-point number (specifically, Float64) due to <code>sqrt</code>. This causes the loop variable <code>i</code> to be a Float64 as well, leading to a massive slowdown when you test for divisibility via taking the modulus <code>(if n%i == 0</code>) because Euclidean division (i.e., <code>mod</code>/<code>rem</code> and <code>div</code>/<code>fld</code>/<code>cld</code>) is very slow for floats. It is much faster for integers.</p>\n<p>Furthermore, this does not always give the mathematically correct answer due to the inherently limited precision of floats. For example,</p>\n<pre><code>julia> Int(floor(sqrt(67108865^2 - 1)))\n67108865\n</code></pre>\n<p>Instead, you should call <code>isqrt</code> to take the integer square root</p>\n<pre><code>res = isqrt(n) # is an Int\n</code></pre>\n<p>which also gives the exact answer</p>\n<pre><code>julia> isqrt(67108865^2 - 1)\n67108864\n</code></pre>\n<p>Avoid <code>Int(floor(sqrt(n)))</code> and <code>floor(Int, sqrt(n))</code> due to the limited precision outlined above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T12:42:15.293",
"Id": "522078",
"Score": "0",
"body": "The biggest performance issue is not isqrt vs sqrt, it's using trial division instead of a better factorisation method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T13:56:30.023",
"Id": "522082",
"Score": "1",
"body": "@EmilyL. Thanks, I've edited my answer to clarify what it answers. Note that the OP's question is why their translated Julia code is slower than their Python code. The answer as explained is that the inner loop in the Julia code is taking floating-point modulus (via `libc`'s `fmod`) whereas the Python code is taking integer modulus, ultimately because `floor(sqrt(n))` is a float in Julia. The solution is to use `isqrt(n)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:31:47.163",
"Id": "264347",
"ParentId": "264270",
"Score": "5"
}
},
{
"body": "<p>You're applying a brute force solution by counting all the divisors through trial division this is excessively slow and we can do better.</p>\n<p>First, realize that all integers can be written as a product of prime numbers, this is by definition of prime numbers. In particular as a product of prime numbers to integer powers.</p>\n<p>I.e: any integer <span class=\"math-container\">\\$n\\$</span> can be written as <span class=\"math-container\">\\$n = \\prod p_i^{k_i}\\$</span> where <span class=\"math-container\">\\$p_i\\$</span> is a prime number and <span class=\"math-container\">\\$k_i\\$</span> is an integer.</p>\n<p>Note further that a "triangle number" is just the arithmetic sum from 1 to n.</p>\n<p>So we're looking for <span class=\"math-container\">\\$n\\$</span> such that <span class=\"math-container\">\\$n(n+1)/2 = \\prod p_i^{k_i}\\$</span> under the condition that <span class=\"math-container\">\\$\\prod k_i+1 > 500\\$</span>. Note here that product of powers plus one computes the number of ways you can pick zero (the +1) to all of the powers of a prime to contribute to a number, which is the number of divisors you can have.</p>\n<p>Your program would then be something like this:</p>\n<ol>\n<li>generate large list of primes using a prime sieve or hard code.</li>\n<li>for each n, starting at 1 compute the "triangle number", do prime factorisation using the list of primes, this is our speedup we only need to try dividing by known primes. Then count the prime powers, compute their product to get the divisors and check if larger than 500.</li>\n</ol>\n<p>This will be faster than OPs code because we only test division with known primes rather than all integers.</p>\n<p>You might be able to do some fancy math to determine a better starting point than n=1 in step 2 by using the expressions above but that's left as an academic exercise for the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T12:30:42.483",
"Id": "264351",
"ParentId": "264270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264347",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T07:41:09.383",
"Id": "264270",
"Score": "3",
"Tags": [
"julia"
],
"Title": "Project Euler #12 in Julia slower than Python?"
}
|
264270
|
<p>I am completely new to JavaScript and I will be grateful for your comments on my Electron app (electron is a JS framework allowing to create of desktop apps).</p>
<p>I needed to create an application that stores a small database and allows me to do simple operations on the data. I just include a small fraction of that app here that embraces just basic CRUD functionality on one table. The table is serialized into a <code>teams.json</code> file with the following structure:</p>
<pre><code>[
{
"name": "Blue",
"gold": 0,
"food": 0,
"fame": 0
},
{
"name": "Red",
"gold": 0,
"food": 0,
"fame": 0
},
{
"name": "Green",
"gold": 0,
"food": 0,
"fame": 0
}
]
</code></pre>
<p>App has just two screens. The first screen is just a whole table. The second screen allows modifications (see the picture).</p>
<p><a href="https://i.stack.imgur.com/c0tL7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c0tL7.png" alt="enter image description here" /></a></p>
<p>The edit screen has two main parts:</p>
<ol>
<li>Read from JSON and construction of the HTML</li>
<li>Serialization into JSON</li>
</ol>
<p><strong>1. Read and construction</strong></p>
<pre><code>function create_team(team) {
var div_team = document.createElement("div");
div_team.setAttribute("id", "team");
var div_html_string = "<textarea class=\'divedit_str\'>" + team.name + "</textarea>"
div_html_string += "<textarea class=\'divedit\'>" + team.gold + "</textarea>";
div_html_string += "<textarea class=\'divedit\'>" + team.food + "</textarea>";
div_html_string += "<textarea class=\'divedit\'>" + team.fame + "</textarea>";
div_team.innerHTML = div_html_string;
var remove_button = document.createElement("button");
remove_button.setAttribute("class", "remove")
remove_button.innerHTML = "Remove";
remove_button.addEventListener("click", (e) => {
e.target.parentElement.remove();
})
div_team.appendChild(remove_button)
return div_team;
}
function loading_panels() {
teams = JSON.parse(fs.readFileSync('./app/teams.json').toString());
//// loading view teams panel
teams.forEach((team) => {
div_teams.appendChild(create_team(team));
});
}
</code></pre>
<p><strong>2. Serialization</strong></p>
<pre><code>button_teams.addEventListener('click', () => {
var teams_div = document.querySelectorAll("div#team");
var json_teams = [];
teams_div.forEach((team) => {
json_teams.push({ "name": team.children[0].value, "gold": Number(team.children[1].value), "food": Number(team.children[2].value), "fame": Number(team.children[3].value) });
});
fs.writeFileSync('./app/teams.json', JSON.stringify(json_teams), function (err) {
if (err) throw err;
});
window.location.replace("./index.html");
});
</code></pre>
<p>The working code can be found in <a href="https://github.com/RadimBaca/teams_code_review.git" rel="nofollow noreferrer">this GitHub repository</a>.</p>
<p>Since this is a common MVC problem I'm curious whether there is a solution where I can separate the view and main logic. Please ignore the CSS of the app. I'm not a frontend developer, therefore, I believe the styles are completely wrong.</p>
<p>Thank you for any comments!</p>
|
[] |
[
{
"body": "<p>The easy stuff:</p>\n<ul>\n<li>Remove unnecessary comments. <code>loading view teams panel</code> - This comment adds nothing. If anything, it tells me that your code is not organized properly since you have to add these reminders. In the repo you have many more examples (for example <code>// JSON variable</code>). In my opinion you can remove basically all your comments and have it more readable as a result. Focus on organizing your code instead. Focus on good variable names and good abstractions.</li>\n<li>You're in electron, so you can use new javascript syntax. Use const/let instead of var. Use arrow functions. Etc.</li>\n<li>When reading a file synchronously you don't need to use a callback. Also, you should use async/await instead of callbacks when async.</li>\n<li>You're outputting variable content directly into html. Even for a single user this will cause problems. Escape your output (or use a framework that does it for you, like react).</li>\n<li>Nit: In javascript it is idiomatic to use camel case. Not a big deal, just pointing it out.</li>\n</ul>\n<p>The hard stuff:</p>\n<p>When you update your file, you don't reload it or trigger a new render. If you are to scale this up, you need to have a way to do this (or have a proxy cache for the file if you don't want to update it constantly). Let's say you have a second component that uses the same team state (in fact it seems you do in the repo). It won't get updated. It's a good idea to separate the storage/model from the rendering/event listeners/etc. If this were react, you would have events flowing up, triggering model changes, and a new model flowing down, triggering renders. This can be done in a number of ways (see mvc, flux, redux, or react state). In your app you could manually call loading_panels after each update, but you can see how that is not a lasting solution. You could probably get by with a simple storage object: storage.update and either subscribe to the storage for changes, or simply have the storage trigger a full render after each change. The key point here is to separate storage/model from rendering/view.</p>\n<p>Some ideas to get you started:</p>\n<ul>\n<li>Remove the file reader from the renderer, and name the remaining function something to do with render (as opposed to the generic loader that does everything)</li>\n<li>Make a separate storage solution (that currently is duplicated across multiple components).</li>\n<li>Have every renderer take its data as an argument</li>\n<li>Call the necessary renderers whenever the storage is updated.</li>\n<li>Load the storage just once, at startup</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:47:30.283",
"Id": "522215",
"Score": "0",
"body": "\"When you update your file, you don't reload it or trigger a new render\", I thought that I'm doing this calling: \"window.location.replace(\"./index.html\");\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:52:23.793",
"Id": "522217",
"Score": "0",
"body": "I did not mention it explicitly, but I want my model to be persisted somewhere after each update (that is important for me). I would like to separate model from view. So you say react is a way to go, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T18:31:30.720",
"Id": "522298",
"Score": "0",
"body": "You're sort of triggering rendering by reloading the page, but this approach only goes so far. As your page grows, you'll most likely get into situations where one part of the page is out of sync with another. Using react is a solution for rendering and local state (unless you count react context). But in your case you have global state. For this people usually go for something outside of react, like redux (or you can use react context). The idea is the same without react as well though. I would try separating the global storage from rendering as a start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T17:57:43.170",
"Id": "522374",
"Score": "0",
"body": "Thanks. Is it possible to add an example that would illustrate the separation of rendering and model?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:15:25.727",
"Id": "264428",
"ParentId": "264275",
"Score": "1"
}
},
{
"body": "<h1>MVC</h1>\n<p>Separating the code into MVC components is possible. Consider the example in <a href=\"https://codereview.stackexchange.com/q/194423/120114\">this post</a>. As we pointed out in reviews the controller had aspects that would likely have been more appropriate left up the the view. Be careful to separate the three components so each only handles its own responsibilities.</p>\n<p>A good example of this separation is demonstrated in the example at the end of <a href=\"https://codereview.stackexchange.com/a/194631/120114\">the answer by sineemore</a> where the controller calls methods and accesses public properties of the model and view to coordinate when each should do something. The controller doesn’t need to know that the view uses a DOM - the view could potentially be replaced with a view that uses a console if need be and the controller should still perform its responsibilities the same way.</p>\n<h1>Suggestions</h1>\n<h2>function names</h2>\n<p>The name <code>create_team</code> almost makes it sound like it makes a team. A more appropriate name might be something like <code>create_row_for_team</code> or as Magnus’s answer recommends: idiomatic JavaScript uses camelCase - e.g. <code>createRowForTeam</code>.</p>\n<p>The name <code>loading_panels</code> appropriately describes what it does - almost. Typically function names would have a verb in the imperative form instead of a gerund - e.g. <code>loadPanels</code>.</p>\n<h2>id attributes</h2>\n<p>Even though this is an electron app and not a typical HTML page, there is a fundamental aspect to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\"><strong>id</strong> attribute</a>: it "<em>must be unique in the whole document.</em>"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\">1</a></sup>. Consider using a class attribute instead of id, or else use a unique identifier - possibly existing property or new property incremented from a given integer.</p>\n<h2>Textarea creation</h2>\n<p>The code to create the HTML of textareas is a bit repetitive:</p>\n<blockquote>\n<pre><code>var div_html_string = "<textarea class=\\'divedit_str\\'>" + team.name + "</textarea>"\ndiv_html_string += "<textarea class=\\'divedit\\'>" + team.gold + "</textarea>";\ndiv_html_string += "<textarea class=\\'divedit\\'>" + team.food + "</textarea>";\ndiv_html_string += "<textarea class=\\'divedit\\'>" + team.fame + "</textarea>";\n</code></pre>\n</blockquote>\n<p>In the past there were <a href=\"https://stackoverflow.com/q/16696632/1575353\">discussions about the most efficient way to concatenate strings</a>. Browsers have come a long way in the past decade and that may not really be a major concern anymore - perhaps with Electron it isn't anyway. Also, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Ecmascript 6 template literals</a> can help. A script tag could also be used as a template. Or to be consistent with other code in the function <code>document.createElement()</code> could be used - perhaps in a loop for the last three properties:</p>\n<pre><code>['gold', 'food', 'fame'].forEach(property => {\n const textarea = document.createElement('textarea');\n textarea.classList.add('divedit');\n textarea.innerText = team[property];\n div_team.appendChild(textarea);\n});\n</code></pre>\n<p>If all of those properties should be integers then consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number\" rel=\"nofollow noreferrer\"><code><input type="number"></code></a> so the user can increment the numbers if desired.</p>\n<pre><code>['gold', 'food', 'fame'].forEach(property => {\n const input = document.createElement('input');\n input.type = 'number';\n input.value = team[property];\n div_team.appendChild(input);\n});\n</code></pre>\n<h2><code>const</code> instead of <code>var</code></h2>\n<p>Because Ecmascript-6 features like arrow functions are used, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> can be used to declare variables. This keeps the scope limited to the block. And using <code>const</code> can be used for any variable that is only assigned once. This can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>pushing in <code>forEach()</code></h2>\n<p>In the serialization code there are these lines:</p>\n<blockquote>\n<pre><code>var json_teams = [];\nteams_div.forEach((team) => {\n json_teams.push({ "name": team.children[0].value, "gold": Number(team.children[1].value), "food": Number(team.children[2].value), "fame": Number(team.children[3].value) });\n});\n</code></pre>\n</blockquote>\n<p>This can be simplified by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>.map()</code></a> method- then the callback function can simply <code>return</code> the object instead of pushing it into the array manually:</p>\n<pre><code>const json_teams = teams_div.map((team) => {\n "name": team.children[0].value, "gold": Number(team.children[1].value), "food": Number(team.children[2].value), "fame": Number(team.children[3].value)\n});\n</code></pre>\n<p>or for readability it might be better to add new lines after each comma:</p>\n<pre><code>const json_teams = teams_div.map((team) => {\n "name": team.children[0].value,\n "gold": Number(team.children[1].value),\n "food": Number(team.children[2].value),\n "fame": Number(team.children[3].value)\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T17:47:31.807",
"Id": "264453",
"ParentId": "264275",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T08:22:42.983",
"Id": "264275",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"ecmascript-6",
"electron"
],
"Title": "Single user Electron application allowing basic CRUD operation on a table (stored in JSON)"
}
|
264275
|
<p>Recently I was assigned a URL shortener design problem while interviewing with a well known organization. Here is the exact problem statement:</p>
<blockquote>
<ol>
<li><p>Build a simple URL shortener service that will accept a URL as an argument over a REST API and return a shortened URL as a result.</p>
</li>
<li><p>The URL and shortened URL should be stored in memory by applicaon.</p>
<p>a. [BONUS] Instead of in memory, store these things in a text file.</p>
</li>
<li><p>If I again ask for the same URL, it should give me the same URL as it gave before instead of generating a new one.</p>
</li>
<li><p>[BONUS] Put this application in a Docker image by writing a Dockerfile and provide the docker image link along with the source code link.</p>
</li>
</ol>
</blockquote>
<p>The problem looked simpler and I did all bonus points as well but still didn't hear back from them (not even the feedback).</p>
<p>Here is my approach:</p>
<ul>
<li>As they have asked for multiple storage mechanisms, I created a factory for key-value stores and implemented memory and file based stores.</li>
<li>I could think of two approaches for shortening the URLs: 1) Hashing 2) Base 62 of a counter. Base 62 seemed proper approach but they have added a requirement that for same long URL, the same shortened URL should be returned. As Base 62 works with an autoincrement counter, achieving this requirement without extra memory/storage is not possible. So I went with hashing the long URLs (I know there are chances of collisions, I mentioned this as a trade-off).</li>
</ul>
<p>Here is my base key-value store:</p>
<p><strong>kvstore_base.py</strong></p>
<pre><code>from abc import ABC, abstractmethod
class KVStoreBase(ABC):
"""
Base key-value store class that provides abstract methods required for
any storage mechanism used to store shortened URLs.
"""
def __init__(self, store):
"""
Constructor.
:param store: Object of any storage mechanism.
"""
self.store = store
@abstractmethod
def __getitem__(self, key: str) -> str:
pass
@abstractmethod
def __setitem__(self, key: str, value: str) -> None:
pass
@abstractmethod
def __contains__(self, key: str) -> bool:
pass
</code></pre>
<p><strong>file_store.py</strong></p>
<pre><code>import io
from .kvstore_base import KVStoreBase
class FileStore(KVStoreBase):
"""
Memory store, which uses 'dict' data structure to
store the key-value pairs.
"""
def __init__(self):
super().__init__(open("db.txt", "a+"))
def __getitem__(self, key: str) -> str:
"""
Get value for the given key from dict
:param key: Key for which the value is to be retrieved.
:return: value
"""
# iterate over file and search for given key.
try:
# move pointer to initial position in file
self.store.seek(0, io.SEEK_SET)
for line in self.store:
suffix, long_url = line.split()
if suffix == key:
return long_url
except Exception as err:
print(str(err))
return ""
def __setitem__(self, key: str, value: str) -> None:
"""
Set value for the given key into dict.
:param key: Key to be added.
:param value: Value corresponding to the key.
:return: None
"""
# move pointer to the end of the file for writing.
self.store.seek(0, io.SEEK_END)
if self.store.tell() != 0:
self.store.write(f"\n{key} {value}")
else:
self.store.write(f"{key} {value}")
self.store.flush()
def __contains__(self, key: str) -> bool:
"""
Check whether the given key is present in the dict.
:param key: Key whose presence is to be checked.
:return: True if key is present, False otherwise.
"""
return True if self.__getitem__(key) else False
def __del__(self) -> None:
"""
Free file resource.
"""
self.store.close()
</code></pre>
<p><strong>kvstore_factory.py</strong></p>
<pre><code>from .memory_store import MemoryStore
from .file_store import FileStore
from .kvstore_base import KVStoreBase
class Factory:
"""
KV Store factory to instantiate storage objects.
"""
kvstore_map: dict = {"MEMORY": MemoryStore, "FILE": FileStore}
@staticmethod
def get_instance(instance_type: str) -> KVStoreBase:
"""
Instantiate given KV store class dynamically.
:param instance_type: Type of KV store to be instantiated.
:return: KV store object.
"""
try:
return Factory.kvstore_map[instance_type]()
except KeyError:
raise Exception("Invalid instance requested.")
</code></pre>
<p>I used FastAPI to create endpoints, here is the two main routes (one for shortening the URL and one for redirecting):</p>
<p><strong>routes/urls.py</strong></p>
<pre><code>import hashlib
from urllib.parse import urlparse
from fastapi import APIRouter, HTTPException, Request
from ..utils.store_connector import StoreConnector
from ..models.urls import Url
from starlette.responses import RedirectResponse
router = APIRouter()
store = StoreConnector().store
def _get_base_url(endpoint_url: str) -> str:
"""
Extract base url from any endpoint URL.
:param endpoint_url: Endpoint URL from which the base URL is to be extracted.
:return: Base URL
"""
return f"{urlparse(endpoint_url).scheme}://{urlparse(endpoint_url).hostname}:{urlparse(endpoint_url).port}"
@router.post("/shorten", tags=["URLs"])
async def shorten(url_obj: Url, request: Request) -> Url:
"""
Shorten the given long URL.
:param request: request object
:param url_obj: URL object
:return: shortened URL.
"""
suffix = hashlib.sha256(url_obj.url.encode("utf-8")).hexdigest()[:8]
if suffix not in store:
# store short-url-suffix: long-url into data store.
store[suffix] = url_obj.url
return Url(url=f"{_get_base_url(request.url_for('shorten'))}/{suffix}")
@router.get("/{suffix}", tags=["URLs"])
async def redirect(suffix: str) -> RedirectResponse:
"""
Redirect to long URL for the given URL ID.
:param suffix: URL ID for the corresponding long URL.
:return: Long URL.
"""
long_url = store[suffix]
if long_url:
# return permanent redirect so that browsers store this in their cache.
response = RedirectResponse(url=long_url, status_code=301)
return response
raise HTTPException(status_code=404, detail="Short URL not found.")
</code></pre>
<p>I exposed the storage mechanism to docker environment variable and created a storage connector class, which calls the factory based on the user configuration.</p>
<p><strong>store_connector.py</strong></p>
<pre><code>import os
import sys
from sys import stderr
from .singleton import Singleton
from ..kvstores.kvstore_factory import Factory
from ..kvstores.kvstore_base import KVStoreBase
class StoreConnector(metaclass=Singleton):
"""
Key Value store singleton class that can be used across all modules.
"""
def __init__(self):
try:
store_type = os.environ.get("STORE_TYPE", "MEMORY")
self._store = Factory.get_instance(store_type)
except KeyError as ex:
print(ex, file=stderr)
# one of the required environment variable is not set
print(
"One of the required environment variables is not set",
file=stderr,
)
sys.exit(1)
except Exception as ex:
print(ex, file=stderr)
sys.exit(1)
@property
def store(self) -> KVStoreBase:
return self._store
</code></pre>
<p>Here is my directory structure:</p>
<pre><code> url-shortener/
├── Dockerfile
├── LICENSE
├── README.md
├── requirements.txt
├── src
│ ├── __init__.py
│ ├── kvstores
│ │ ├── __init__.py
│ │ ├── file_store.py
│ │ ├── kvstore_base.py
│ │ ├── kvstore_factory.py
│ │ └── memory_store.py
│ ├── main.py
│ ├── models
│ │ ├── __init__.py
│ │ └── urls.py
│ ├── routes
│ │ ├── __init__.py
│ │ └── urls.py
│ └── utils
│ ├── singleton.py
│ └── store_connector.py
├── start.sh
└── tests
├── __init__.py
├── test_file_store.py
├── test_kvstore_factory.py
├── test_memory_store.py
├── test_routes.py
└── test_store.py
</code></pre>
<p>In the instructions, they emphasized the following points:</p>
<ul>
<li>Readability of code</li>
<li>Tests - Unit tests definitely and more if you can think of</li>
<li>A good structure to your code and well written file & variable names etc.</li>
</ul>
<p>So, which of those points my code lacks?</p>
|
[] |
[
{
"body": "<p>Your code looks nice and readable in my opinion; I can understand most of what's going on. A few points I'm unsure about, however:</p>\n<p><strong>(1) Your exception handling seems a bit weird to me</strong></p>\n<p>In <code>filestore.py</code>, you catch all exceptions in your <code>__getitem__</code> method. This is generally bad practice — if there's a specific kind of exception that you're anticipating, then you should catch that specific exception only. There are some situations where you might want to catch and suppress all exceptions, but they're rare, and (to me at least) it's not evident why this would be one of them. There's nothing in the docstring or anything to explain why you're catching it and just printing it out. Rather than catching all errors in <code>__getitem__</code> and returning an empty string if you weren't successful, I would catch <code>KeyError</code>s in <code>routes/urls.py</code></p>\n<p>Similarly, in <code>kvstore_factory.py</code>, it's unclear to me why you'd catch a <code>KeyError</code> exception — a specific kind of exception, which is informative about what might have caused it — and replace it with a general <code>Exception</code>. If you want to add some useful additional information into the error message, I would do either this:</p>\n<pre><code># kvstore_factory.py\n\nclass Factory:\n kvstore_map: dict = {"MEMORY": MemoryStore, "FILE": FileStore}\n\n @staticmethod\n def get_instance(instance_type: str) -> KVStoreBase:\n try:\n return Factory.kvstore_map[instance_type]()\n except KeyError as err:\n raise KeyError("Invalid instance requested.") from err\n</code></pre>\n<p>Or this:</p>\n<pre><code># kvstore_factory.py\n\nclass InvalidInstanceRequest(KeyError):\n """\n Raised when a user requests an instance\n that does not exist in Factory.kvstore_map\n """\n\n\nclass Factory:\n kvstore_map: dict = {"MEMORY": MemoryStore, "FILE": FileStore}\n\n @staticmethod\n def get_instance(instance_type: str) -> KVStoreBase:\n try:\n return Factory.kvstore_map[instance_type]()\n except KeyError as err:\n raise InvalidInstanceRequest("Invalid instance requested.") from err\n</code></pre>\n<p>Lastly, I'm confused about why, in <code>store_connector.py</code>, you're catching exceptions and then calling <code>sys.exit</code>. Why not just re-raise the original exception, like so? I think it would lead to a more readable traceback. I would take out the second <code>except</code> clause altogether — if all you're doing is printing it and then calling <code>sys.exit()</code>, you may as well not catch it at all and let the exception end the programme.</p>\n<pre><code># store_connector.py\n\nimport os\n\nfrom .singleton import Singleton\nfrom ..kvstores.kvstore_factory import Factory\n\n\nclass StoreConnector(metaclass=Singleton):\n def __init__(self):\n try:\n store_type = os.environ.get("STORE_TYPE", "MEMORY")\n self._store = Factory.get_instance(store_type)\n except KeyError as ex:\n raise KeyError("One of the required environment variables is not set") from ex\n</code></pre>\n<p><strong>(2) Two minor points</strong></p>\n<p>Firstly, in <code>kvstore_factory.py</code>, you could have much richer type hints. I'm also not quite sure why you're using a <code>staticmethod</code>, when a <code>classmethod</code> would seem more elegant here.</p>\n<pre><code># kvstore_factory.py\n\nfrom typing import ClassVar\nfrom .memory_store import MemoryStore\nfrom .file_store import FileStore\nfrom .kvstore_base import KVStoreBase\n\n\nclass Factory:\n kvstore_map: ClassVar[dict[str, KVStoreBase]] = {"MEMORY": MemoryStore, "FILE": FileStore}\n\n @classmethod\n def get_instance(cls, instance_type: str) -> KVStoreBase:\n try:\n return cls.kvstore_map[instance_type]()\n except KeyError as ex:\n # exception handling as discussed above \n\n# -- snip --\n</code></pre>\n<p>Secondly, you can simplify your <code>__contains__</code> method in <code>file_store.py</code> by simply writing <code>return bool(self[key])</code></p>\n<p><strong>(3) I would have put some of the logic in <code>routes/urls.py</code> elsewhere</strong></p>\n<p>The exact manner in which you're hashing the urls seems like an implementation detail. It seems strange to me that this logic is in <code>routes/urls.py</code>. I might rewrite your code like this:</p>\n<p>kvstore_base.py:</p>\n<pre><code># kvstore_base.py\n\nimport hashlib\nfrom abc import ABC, abstractmethod\nfrom collections.abc import MutableMapping\nfrom functools import cache\n\n@MutableMapping.register\nclass KVStoreBase(ABC):\n def __init__(self, store):\n self.store = store\n\n def get_shortened_url(self, long_url: str) -> str:\n shortened_url = self.shorten_url(long_url)\n self[shortened_url] = long_url\n return shortened_url\n\n @staticmethod\n @cache\n def shorten_url(url: str) -> str:\n return hashlib.sha256(url.encode("utf-8")).hexdigest()[:8]\n\n @abstractmethod\n def __getitem__(self, key: str) -> str: ...\n\n @abstractmethod\n def __setitem__(self, key: str, value: str) -> None: ...\n\n @abstractmethod\n def __contains__(self, key: str) -> bool: ...\n</code></pre>\n<p>routes/urls.py:</p>\n<pre><code># routes/urls.py\n\nfrom urllib.parse import urlparse\n\nfrom fastapi import APIRouter, HTTPException, Request\n\nfrom ..utils.store_connector import StoreConnector\nfrom ..models.urls import Url\nfrom starlette.responses import RedirectResponse\n\nrouter = APIRouter()\nstore = StoreConnector().store\n\n\ndef _get_base_url(endpoint_url: str) -> str:\n return f"{urlparse(endpoint_url).scheme}://{urlparse(endpoint_url).hostname}:{urlparse(endpoint_url).port}"\n\n\n@router.post("/shorten", tags=["URLs"])\nasync def shorten(url_obj: Url, request: Request) -> Url:\n suffix = store.get_shortened_url(url_obj.url)\n return Url(url=f"{_get_base_url(request.url_for('shorten'))}/{suffix}")\n\n# -- snip --\n</code></pre>\n<p><strong>Alternative refactoring of KVStore class, if you don't believe hashing details belong in the base class KVStore class:</strong></p>\n<pre><code># kvstore_base.py\n\nimport hashlib\nfrom abc import ABC, abstractmethod\nfrom collections.abc import MutableMapping, Callable\nfrom functools import cache\nfrom typing import TypeVar\n\n@MutableMapping.register\nclass KVStoreBase(ABC):\n def __init__(self, store):\n self.store = store\n\n @abstractmethod\n def __getitem__(self, key: str) -> str: ...\n\n @abstractmethod\n def __setitem__(self, key: str, value: str) -> None: ...\n\n @abstractmethod\n def __contains__(self, key: str) -> bool: ...\n\n\nT = TypeVar('T', bound='URLStoreMixin')\n\n\nclass URLStoreMixin:\n """\n Mixin class for extending the capabilities of classes inheriting from KVStoreBase,\n useful for situations in which the KVStore is being used\n to store mappings of shortened URLs to long URLs\n """\n\n # type hint so mypy doesn't get confused by this being a Mixin class\n __setitem__: Callable[[T, str, str], None]\n\n def get_shortened_url(self, long_url: str) -> str:\n shortened_url = self.shorten_url(long_url)\n self[shortened_url] = long_url\n return shortened_url\n\n @staticmethod\n @cache\n def shorten_url(url: str) -> str:\n return hashlib.sha256(url.encode("utf-8")).hexdigest()[:8]\n</code></pre>\n<p>Then have your MemoryStore and FileStore objects solely inherit from KVStoreBase, as you were before, but create MemoryURLStore and FileURLStore classes like so:</p>\n<pre><code>class MemoryURLStore(MemoryStore, URLStoreMixin):\n pass\n\nclass FileURLStore(FileStore, URLStoreMixin):\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T11:51:46.143",
"Id": "521924",
"Score": "1",
"body": "Great! Thanks for the detailed review. I really liked the exception handling suggestions. I don't understand why you would store long URLs as key and short URLs as values? When user calls API using short URL, finding the long URL would be O(n) instead of O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:14:15.023",
"Id": "521927",
"Score": "0",
"body": "Yes, good point — didn't think about that. Have edited my answer to fix that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:28:22.133",
"Id": "521928",
"Score": "0",
"body": "Thanks. You are right that hashing is implementation detail/business logic of the application and can be at a different place. But I don't think KV store is the right place because it should be only aware of keys and values (decoupling) so that it can be used for different purpose other than storing URLs as well. Just my thoughts though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:37:06.267",
"Id": "521929",
"Score": "0",
"body": "Sure, I can see that — perhaps my `get_shortened_url` and `shorten_url` methods would be better as functions in the global namespace, either in routes/urls.py or in a third file. I think it depends on how you conceptualise the KV store objects — whether you see them as mapping objects *for a specific purpose*, or as generalised mapping objects *that just happen to be being used for a specific purpose*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:43:13.797",
"Id": "521930",
"Score": "0",
"body": "Have added an alternative refactoring of KVStore to my question — would be interested to hear your thoughts!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:02:47.150",
"Id": "522069",
"Score": "1",
"body": "Thanks! What is the meaning of Mixin btw?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:05:22.520",
"Id": "522070",
"Score": "1",
"body": "I think those last changes are not that major to reject someone from further interviews. The only potential cause of my rejection seems to be exception handling then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:10:28.743",
"Id": "522071",
"Score": "1",
"body": "Can't comment on that — it might have been for a completely different reason that I haven't spotted! — but the exception handling definitely stuck out most to me, for sure. As I say though, I think the code overall is really nicely written, I can very easily understand what's going on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:14:33.673",
"Id": "522072",
"Score": "1",
"body": "The concept of a \"mixin\" class is a class that it would never make sense to instantiate directly, but that you use to \"mix in\" with other classes in multiple inheritance, to allow code reuse. In my code, you'd never instantiate `URLStore` directly — it only exists to extend the capabilities of other classes in fairly specific ways using multiple inheritance — so I label it explicitly as a \"Mixin\" to make this clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:24:39.830",
"Id": "522074",
"Score": "1",
"body": "Mixins come highly recommended https://www.residentmar.io/2019/07/07/python-mixins.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T08:10:02.777",
"Id": "522160",
"Score": "1",
"body": "Thanks for all the details!"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T11:32:25.837",
"Id": "264278",
"ParentId": "264277",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "264278",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T09:23:43.717",
"Id": "264277",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"design-patterns",
"interview-questions"
],
"Title": "Designing an URL Shortener"
}
|
264277
|
<p>I wrote the below as a solution to:</p>
<h3 id="problem-lt3z">Problem</h3>
<p>Find the highest product of three numbers in a list</p>
<h3 id="constraints-s0r6">Constraints</h3>
<ul>
<li>Is the input a list of integers?
<ul>
<li>Yes</li>
</ul>
</li>
<li>Can we get negative inputs?
<ul>
<li>Yes</li>
</ul>
</li>
<li>Can there be duplicate entries in the input?
<ul>
<li>Yes</li>
</ul>
</li>
<li>Will there always be at least three integers?
<ul>
<li>No</li>
</ul>
</li>
<li>Can we assume the inputs are valid?
<ul>
<li>No, check for None input</li>
</ul>
</li>
<li>Can we assume this fits memory?
<ul>
<li>Yes</li>
</ul>
</li>
</ul>
<h3 id="solution-6xvb">Solution</h3>
<pre><code>from functools import reduce
from typing import List, Set, Callable
class Solution(object):
def max_prod_three(self, array: List[int]) -> int:
if array is None:
raise TypeError("array cannot be None")
if len(array) < 3:
raise ValueError("array must have at least 3 elements")
pos: List[int] = [n for n in array if n >= 0]
neg: List[int] = [n for n in array if n < 0]
pos_len: int = len(pos)
neg_len: int = len(neg)
candidates: Set[int] = set()
mult: Callable[[int, int], int] = lambda x,y:x*y
# possible combinations are:
# ---, --+, -+-, +--, -++, +-+, ++-, +++
# but order does not matter, so left with:
# --- -> - : len(neg) >= 3, will never be the max if len(pos) > = 3, if len(pos) < 3,
# max will be with 3 lowest absolute values
# --+ -> + : len(neg) >= 2, len(pos) >= 1, will be the max if exists -- > any ++
# -++ -> - : len(neg) >= 1, len(pos) >= 2, will never be the max if len(pos >= 3,
# if len(pos) == 2, max will be with lowest absolute value
# +++ -> + : len(pos) >= 3, max is with 3 highest values
if neg_len >= 3 and pos_len < 3:
candidates.add(reduce(mult, sorted(neg)[-3:]))
if neg_len >= 2 and pos_len >= 1:
candidates.add(reduce(mult, sorted(neg)[:2] + [max(pos)]))
if neg_len >= 1 and pos_len == 2:
candidates.add(reduce(mult, sorted(neg)[-1:] + pos))
if pos_len >= 3:
candidates.add(reduce(mult, sorted(pos)[-3:]))
return max(candidates)
</code></pre>
<p>Please could I get some feedback on it? In particular:</p>
<ul>
<li>Readability and does the comment make it clear what the code is doing?</li>
<li>Pythonic-ness</li>
<li>Typing - I have not really used typing before. Is using it on every variable worth doing, or overkill? If you know of a good resource to help a beginner, please add a link, thanks :)</li>
<li>Complexity - how would I calculate this in big-0 notation? The provided solution <a href="https://github.com/donnemartin/interactive-coding-challenges/blob/master/online_judges/prod_three/prod_three_solution.ipynb" rel="nofollow noreferrer">here</a> is O(n) for time and O(1) space, but this runs much faster than that (~10x faster for list of 7,000 entries, ~2x faster for very small lists). Notice I loop over the array twice (to separate -ve and +ve numbers), while the solution given only loops over it once, but with quite a few min/max ops within that loop. As I understand it, my code is also O(n) (since O(2n) == O(n)). But if that is correct, how is the time taken so different?</li>
<li>Lastly, this is not written to be production code of course. But, what would/could I add to it for some hypothetical production use case?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:49:17.553",
"Id": "521931",
"Score": "0",
"body": "Just to make the last question clearer, I am asking \"If this were production code, what should or could I add that is currently missing?\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T13:03:36.903",
"Id": "521932",
"Score": "0",
"body": "`sorted()` is \\$O(nlog(n))\\$, so is your code. Try to sort each array once."
}
] |
[
{
"body": "<p>Regarding readability, I'd say typing variables makes them harder to read. As is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>mult = lambda x, y: x * y\n</code></pre>\n<p>I can already tell its a function with two arguments that returns their product. I think this just adds noise to that:</p>\n<pre class=\"lang-py prettyprint-override\"><code>mult: Callable[[int, int], int] = lambda x, y: x * y\n</code></pre>\n<p>Also, these lines are kind of hard to read (there is a lot going on in each line, plus they have duplicated code):</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates: Set[int] = set()\nmult: Callable[[int, int], int] = lambda x,y:x*y\n\nif neg_len >= 3 and pos_len < 3:\n candidates.add(reduce(mult, sorted(neg)[-3:]))\nif neg_len >= 2 and pos_len >= 1:\n candidates.add(reduce(mult, sorted(neg)[:2] + [max(pos)]))\nif neg_len >= 1 and pos_len == 2:\n candidates.add(reduce(mult, sorted(neg)[-1:] + pos))\nif pos_len >= 3:\n candidates.add(reduce(mult, sorted(pos)[-3:]))\n\nreturn max(candidates)\n</code></pre>\n<p>You could change them to something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates_groups = []\n\nif neg_len >= 3 and pos_len < 3:\n candidates_groups.add(sorted(neg)[-3:])\n\nif neg_len >= 2 and pos_len >= 1:\n candidates_groups.add(sorted(neg)[:2] + [max(pos)])\n\nif neg_len >= 1 and pos_len == 2:\n candidates_groups.add(sorted(neg)[-1:] + pos)\n\nif pos_len >= 3:\n candidates_groups.add(sorted(pos)[-3:])\n\n# reduce is cool, but this is more readable\ncandidates = [cand[0] * cand[1] * cand[2] for cand in candidates_groups]\n\nreturn max(candidates)\n</code></pre>\n<p>Then regarding your answer's Big-O notation, as @Pavlo Slavynsky said, sorting a list is already <strong><em>O(nlog(n))</em></strong>, so that is your codes time complexity. Regarding space complexity, you store all of the values in the input in a new list, so that would make it <strong><em>O(n)</em></strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T19:57:44.713",
"Id": "264293",
"ParentId": "264279",
"Score": "2"
}
},
{
"body": "<p>A few points:</p>\n<ol>\n<li>Why is your <code>max_prod_three</code> function in a class at all? It seems to me like it would be fine in the global namespace.</li>\n<li>Why write your own <code>mult</code> function when you can just import <code>mul</code> from the <code>operator</code> module in the standard library?</li>\n<li>I agree with @m-alorda on the type hints being a bit overkill. I'm a big fan of type hints, but they do make the code less legible, and a lot of yours are unnecessary. Type hints are only useful when they tell IDEs and/or other programmers things about your code that wouldn't otherwise be obvious. A call to <code>len()</code> is never going to return a value that isn't an integer, and any IDE or python programmer worth its/their salt will know that. So annotating the return value of a call to <code>len()</code> as being an integer doesn't add any non-obvious information to the code, and just clutters it up a little.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T11:04:06.070",
"Id": "524481",
"Score": "1",
"body": "This was an answer to a code challenge. It already provided the Solution class and function signature - just like on Leetcode.\nGood point about the mul operator, thanks! Also good advice on the type hints - seems restricting them to function args and return type is best, with occasional use where they clarify something not obvious is best."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T21:32:46.630",
"Id": "264295",
"ParentId": "264279",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264293",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T12:46:12.903",
"Id": "264279",
"Score": "2",
"Tags": [
"python-3.x",
"algorithm",
"complexity"
],
"Title": "Find the highest product of three numbers in a list (Python)"
}
|
264279
|
<p>I am working with <code>C#</code>, <code>Npgsql</code>, <code>EF Core</code> and <code>Postgres</code>.<br/>
I defined an endpoint for a paginated search, where the filters and orderBy column are dynamic. The endpoint accepts a <code>PaginationOptions</code> instance:</p>
<pre><code>public class PaginationOptions
{
public int Page { get; set; }
public int ItemsPerPage { get; set; }
public string OrderBy { get; set; }
public bool Desc { get; set; }
public IList<FilterValues> Filters { get; set; }
}
public class FilterValues
{
public string FieldName { get; set; }
public IEnumerable<string> Values { get; set; }
}
</code></pre>
<p>The following method performs the search and returns a Tuple with the sorted items and a counter for the total items in the table:</p>
<pre><code>public Tuple<IList<T>, int> Search(PaginationOptions paginationOptions)
{
if (!string.IsNullOrEmpty(paginationOptions.OrderBy))
{
CheckFilterField(paginationOptions.OrderBy);
}
int offset = (paginationOptions.Page - 1) * paginationOptions.ItemsPerPage;
string orderBy = !string.IsNullOrEmpty(paginationOptions.OrderBy) ? paginationOptions.OrderBy : $"{prefix}.title";
string order = paginationOptions.Desc ? "DESC" : "ASC";
using (NpgsqlConnection connection = GetConnection())
{
string query = $"{GetQueryfields()} {GetFromClause()} {BuildWhere(paginationOptions.Filters)}";
string itemsQuery = $"SELECT {query} ORDER BY {orderBy} {order}";
NpgsqlCommand command = BuildCommand(connection, itemsQuery, paginationOptions.Filters);
IDataReader reader = command.ExecuteReader();
ISet<Guid> guids = new HashSet<Guid>(paginationOptions.ItemsPerPage);
while (reader.Read())
{
Guid guid = reader.GetGuid(0);
if (!guids.Contains(guid))
{
guids.Add(guid);
}
}
ISet<Guid> filteredGuids = guids.Skip(offset).Take(paginationOptions.ItemsPerPage).ToHashSet();
IList<T> items = GetItems(filteredGuids);
return Tuple.Create(items, guids.Count);
}
}
</code></pre>
<p>In words: In each entity there are the query fields and the FROM clause defiend. They are splitted because I need the FROM clause in another method as well.<br/> The WHERE (prepared statement) and ORDER BY are built dynamically using the parameters. The <code>BuildCommand</code> creates the <code>NpgsqlCommand</code> and sets the parameters. Then I use Dapper for a raw query in order to get the ids of the requested items, then I load them using the <code>EF</code> and at the end I <code>Skip</code> and <code>Take</code> in order to have the right pagination.<br/>
The problem ist that <code>EF</code> does not allow to add an ORDER BY clause for raw queries, it is only available throug the <code>Linq</code> expression:</p>
<pre><code>context.AnEntity.FromSqlRaw("Select * from users ORDER BY id").OrderBy(x => x.Title);
</code></pre>
<p><code>ORDER BY id</code> is ignored, items are sorted by the expression. If no orderby linq expression is used, the framework adds <code>ORDER BY entity.id</code>. Otherwise I could have done followings:</p>
<pre><code>string itemsQuery = $"SELECT {query} ORDER BY {orderBy} {order}";
context.AnEntity.FromSqlRaw(itemsQuery).Skip(offset).Take(limit)...
</code></pre>
<p>It works. Even on a table with 1mil a query takes 2,8sec<br/>
Comments? Improvment hints?</p>
<p>Edit:<br/>
I ended up with a query which loads the paged data in 2,2sec over a table with 1mil rows. Is it an acceptable result?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:20:00.407",
"Id": "521940",
"Score": "0",
"body": "Is the Guid-column the primary key?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:24:16.390",
"Id": "521942",
"Score": "0",
"body": "Did you look at DynamicLinq or even making your own expression tree for the orderbys? example - https://codereview.stackexchange.com/a/256123/52662. Also you state its an endpoint if it's a webapi project what about just adding OData support for the pagenation? OData has some flexibility to intercept the iqueryable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:24:44.223",
"Id": "521943",
"Score": "0",
"body": "yes, the `id (uuid)` column is the primary key."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T06:22:31.910",
"Id": "521983",
"Score": "0",
"body": "@CharlesNRice Didn't know about `DynamicLinq`, will take a look. I am not fan of `OData` but I will give it a try."
}
] |
[
{
"body": "<p>Just a quick shot at</p>\n<pre><code>IDataReader reader = command.ExecuteReader();\nISet<Guid> guids = new HashSet<Guid>(paginationOptions.ItemsPerPage);\nwhile (reader.Read())\n{\n Guid guid = reader.GetGuid(0);\n if (!guids.Contains(guid))\n {\n guids.Add(guid);\n }\n}\nISet<Guid> filteredGuids = guids.Skip(offset).Take(paginationOptions.ItemsPerPage).ToHashSet();\n</code></pre>\n<p>Because the Guid-column is your primary-key-column, you should just use a <code>List<Guid></code>. You won't need to check if <code>reader.GetGuid(0)</code> exists because that just can't happen.</p>\n<p>I wouldn't create the former <code>HashSet<Guid></code> by using the capacity of <code>paginationOptions.ItemsPerPage</code> but would use a fixed number which should be in the lower range but not too low. Because if you use this overloaded constructor, then you should use it in a way that it scales good. Having a low number for capacity, you may reach the point fast that there aren't any slots left meaning the <code>HashSet</code> needs to be resized. If the number for capacity is too high it may take more time at initialization because its createing two array with the length of the passed capacity.</p>\n<p>Take a look at the <a href=\"https://referencesource.microsoft.com/#system.core/system/Collections/Generic/HashSet.cs,831ca3e6d9c0d78b\" rel=\"nofollow noreferrer\">reference-source for <code>HashSet<T></code></a></p>\n<p>This applies for a <code>List<T></code> as well.</p>\n<p>To come to an end I would change the code a bove to</p>\n<pre><code>IDataReader reader = command.ExecuteReader();\nList<Guid> guids = new List<Guid>(2000);\nwhile (reader.Read())\n{\n guids.Add(reader.GetGuid(0));\n}\nISet<Guid> filteredGuids = guids.Skip(offset).Take(paginationOptions.ItemsPerPage).ToHashSet();\n</code></pre>\n<p>but would extract the <code>2000</code> to a meaningful named constant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T05:53:58.427",
"Id": "521981",
"Score": "0",
"body": "Thanks for the hint, but If the query has a join with, the result could include two rows with the same id and different joined values which are neede for filtering. That's why I used a ISet. I could use a IList, but in this case I`d need the check `if contains...`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T06:15:32.013",
"Id": "521982",
"Score": "0",
"body": "I've just tried to change from `ISet<Guid> guids = new HashSet<Guid>(paginationOptions.ItemsPerPage);` to `List<Guid> guids = new List<Guid>(2000);`. For the same query the first takes 500ms, the latter 12sec."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:44:24.060",
"Id": "264282",
"ParentId": "264280",
"Score": "0"
}
},
{
"body": "<ul>\n<li>[<code>PaginationOptions</code>] Rename <code>Des</code> to <code>OrderByDescending</code> and remove <code>OrderBy</code>, this would be more manageable as you already have a default <code>order by</code> in your query.</li>\n<li>I can't see a check for the fields ? if not, try to ensure that every field name exists on your table before building the query.</li>\n<li>Use <code>Dapper</code> to count and select queries, as they're faster in dapper than <code>EF</code>.</li>\n<li>Since this is a Web API, a <code>Tuple</code> would be an overkill for your controller, you might consider returning <code>IEnumerable</code> or <code>IDictionary<int, IList<T>></code> or any simpler type, just try to simplify the results to the consumer.</li>\n<li>you can use <code>FETCH clause</code> instead of LINQ's <code>Take</code> and <code>Skip</code>, which would make it faster and also would decrease the allocated memory. referrer to this <a href=\"https://www.postgresqltutorial.com/postgresql-fetch/\" rel=\"nofollow noreferrer\">page</a> to read more about it.\n<em>(FYI : PostgreSQL, SQL Server, Oracle, and MySQL supports <code>FETCH clause</code> with some caveats).</em></li>\n<li><code>guids</code> is already a <code>HashSet<Guid></code> so checking the guid in the loop is unnecessary, as the <code>guids.Add(guid)</code> would ignore the value if it's already in the collection.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T05:48:16.660",
"Id": "521980",
"Score": "0",
"body": "For the `Count` and `Select` I am using Npgsql, no EF nor Dapper. This `Search` method is not in the controller, it is in an abstract class, called by the controller where i manage the returned items. `Take` and `Skip` are not used on a IO operation since the Guids are already in memory, so it makes no difference, right? Thanks for the rest!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:20:07.923",
"Id": "521990",
"Score": "0",
"body": "@Emaborsa if you are using `Npgsql` you should state that, and edit your post to clearify this, as the first line of your post states that you're using `Dapper` and `EF`. for the method, I know it's not the controller. what I meant is the service should always returns simple types, as you don't want to add more data processing inside your controller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:27:14.660",
"Id": "521992",
"Score": "0",
"body": "not sure how things work on your application, but if you just storing guids to re-query the DB with the full data, unless if it's a requirement, you might loose some performance for that. though using `Fetch clause` would give you what you need with faster results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:34:22.690",
"Id": "521993",
"Score": "0",
"body": "About the method: But I need to return the pagend data AND the total items count. About of performance: I agree that is non sense to retrieve all the data and then filter it for the paging, but since the performance is not too bad, I though it was a good solution anyway. I will review the query,."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T03:13:03.557",
"Id": "264305",
"ParentId": "264280",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:01:53.307",
"Id": "264280",
"Score": "1",
"Tags": [
"c#",
"performance",
"database",
"entity-framework-core"
],
"Title": "Database dynamic query"
}
|
264280
|
<p>I completed the following question but it seems a lot of space complexity.</p>
<p>Do you think is there a way to complete it with graph search or so?</p>
<p>Thanks for the comments.</p>
<p>Suppose we have some input data describing a graph of relationships between parents and children over multiple generations. The data is formatted as a list of (parent, child) pairs, where each individual is assigned a unique positive integer identifier.</p>
<p>For example, in this diagram, 3 is a child of 1 and 2, and 5 is a child of 4:</p>
<pre><code>1 2 4 15
\ / / | \ /
3 5 8 9
\ / \ \
6 7 11
</code></pre>
<p>Sample input/output (pseudodata):</p>
<p>parentChildPairs = [
(1, 3), (2, 3), (3, 6), (5, 6), (15, 9),
(5, 7), (4, 5), (4, 8), (4, 9), (9, 11)
]</p>
<p>Write a function that takes this data as input and returns two collections: one containing all individuals with zero known parents, and one containing all individuals with exactly one known parent.</p>
<p>Output may be in any order:</p>
<pre><code>findNodesWithZeroAndOneParents(parentChildPairs) => [
[1, 2, 4, 15], // Individuals with zero parents
[5, 7, 8, 11] // Individuals with exactly one parent
]
</code></pre>
<p>Complexity Analysis variables:</p>
<p>n: number of pairs in the input</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ParentChild2 {
public static void main(String[] argv) {
int[][] parentChildPairs = new int[][] {
{1, 3}, {2, 3}, {3, 6}, {5, 6}, {15, 9}, {5, 7},
{4, 5}, {4, 8}, {4, 9}, {9, 11}
};
List<List<Integer>> list = findNodesWithZeroAndOneParents(parentChildPairs);
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
static List<List<Integer>> findNodesWithZeroAndOneParents(int[][] parentChildPairs){
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> childMap = new HashMap<>();
Map<Integer, Integer> parentMap = new HashMap<>();
for(int i=0;i<parentChildPairs.length; i++){
if(!childMap.containsKey(parentChildPairs[i][1])){
childMap.put(parentChildPairs[i][1], 1);
} else{
int value = childMap.get(parentChildPairs[i][1]);
childMap.put(parentChildPairs[i][1], value + 1);
}
}
for(int i=0;i<parentChildPairs.length;i++){
if(!childMap.containsKey(parentChildPairs[i][0])){
parentMap.put(parentChildPairs[i][0], 1);
}
}
ArrayList<Integer> temp2 = new ArrayList<>();
for( Map.Entry<Integer, Integer> entry: parentMap.entrySet()){
if(entry.getValue() == 1){
temp2.add(entry.getKey());
}
}
result.add(temp2);
ArrayList<Integer> temp = new ArrayList<>();
for( Map.Entry<Integer, Integer> entry: childMap.entrySet()){
if(entry.getValue() == 1){
temp.add(entry.getKey());
}
}
result.add(temp);
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T17:31:22.983",
"Id": "521956",
"Score": "0",
"body": "Can the number of nodes in the graph be taken as a parameter? Are the nodes always going to be labelled 1..n, where n is the number of nodes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T18:17:29.897",
"Id": "521959",
"Score": "0",
"body": "This looks like the space complexity is proportional to n, what's wrong with it?"
}
] |
[
{
"body": "<p>Your space complexity looks like it is proportional to n (<code>O(n)</code>? I'm unsure of the notation). That doesn't seem bad to me, and I don't think it can be improved (but don't take my word for it, I'm not at all an expert). However, let me try cleaning up your code a bit. It's well-formatted, but there are some minor things that can be improved.</p>\n<ul>\n<li><code>args</code> is the convention in Java for the argument to the main method, not <code>argv</code>.</li>\n<li>You can leave out the <code>new int[][]</code> when initializing a variable.</li>\n<li>If you're iterating over every element of an <code>Iterable</code> or array in order, you can use a foreach loop to help you out.</li>\n<li>You've also left blank lines in your code where they're not necessary, e.g. after the start of each for loop and between two closing braces.</li>\n<li>You can inline <code>result</code> using <code>List.of</code>, but that may be more a matter of personal style.</li>\n<li>You could name <code>temp2</code> and <code>temp</code> something more descriptive such as <code>zeroParentNodes</code> and <code>oneParentNodes</code>.</li>\n<li><code>value</code> could be named <code>numParents</code> or something similar to indicate that it is the number of parents found so far.</li>\n<li>You could initialize <code>parent</code> and <code>child</code> variables instead of indexing into the pair each time.</li>\n</ul>\n<p>One odd thing I noticed - you add keys from <code>parentMap</code> whose values are 1 to <code>temp2</code>, but <code>parentMap</code> <em>only</em> contains values that are 1. Why not use a <code>Set</code> instead?</p>\n<p>Also, you don't need to iterate over <code>parentChildPairs</code> twice - just put the <code>parentSet</code> and <code>childMap</code> operations in a single loop, and remove from <code>parentSet</code> as necessary.</p>\n<p>Furthermore, instead of iterating over <code>childMap</code> to find children with a single parent, you can maintain two separate sets of children with one parent and children with multiple parents from the very start.</p>\n<p>We now have this. The space complexity seems to be the same, but at least it's clearer (at least to me).</p>\n<pre><code>static List<List<Integer>> findNodesWithZeroAndOneParents(int[][] parentChildPairs) {\n Set<Integer> zeroParentNodes = new HashSet<>();\n Set<Integer> oneParentNodes = new HashSet<>();\n Set<Integer> extraParentNodes = new HashSet<>();\n\n for (int[] parentChild : parentChildPairs) {\n int parent = parentChild[0];\n int child = parentChild[1];\n\n if (!oneParentNodes.contains(parent) && !extraParentNodes.contains(parent)) {\n zeroParentNodes.add(parent);\n }\n\n if (zeroParentNodes.contains(child)) {\n zeroParentNodes.remove(child);\n oneParentNodes.add(child);\n } else if (oneParentNodes.contains(child)) {\n oneParentNodes.remove(child);\n extraParentNodes.add(child);\n } else {\n oneParentNodes.add(child);\n }\n }\n\n return List.of(new ArrayList<>(zeroParentNodes), new ArrayList<>(oneParentNodes));\n}\n</code></pre>\n<p>I'd also suggest making your own <code>Pair</code> class for the input and output, but I don't know if you can change the input/output format, and it won't help with the space complexity anyway.</p>\n<p>As Eric Stein suggested in the comments, the second <code>if</code> inside the for loop can be written more succinctly taking advantage of <code>Set#remove</code>'s returned value, but I fear it loses some clarity that way.</p>\n<pre><code>if (zeroParentNodes.remove(child)) {\n oneParentNodes.add(child);\n} else if (oneParentNodes.remove(child)) {\n extraParentNodes.add(child);\n} else {\n oneParentNodes.add(child);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T02:01:41.017",
"Id": "521971",
"Score": "0",
"body": "This can be further improved by leveraging the fact that `Set#remove()` returns a boolean to get rid of the contains() checks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T10:51:32.830",
"Id": "521996",
"Score": "0",
"body": "@user thanks for the more concise solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T10:51:59.357",
"Id": "521997",
"Score": "0",
"body": "I am looking for a BFS solution, is there any solution ideas for these?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T12:07:35.490",
"Id": "522001",
"Score": "0",
"body": "@EricStein I’m afraid the code will become unclear if I do that, even if it will be concise. Thanks for the suggestion though, I’ll add it to my answer once I’m on my laptop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T12:09:50.293",
"Id": "522002",
"Score": "0",
"body": "@NeslihanBozer If you’re not taking some kind of graph object as input, I don’t see how DFS or BFS could help. It seems to me you’ll first have to construct a Map or some such object representing a graph and then find nodes with 0/1 parents, which will just take up more space."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T18:38:16.980",
"Id": "264290",
"ParentId": "264283",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T14:46:56.840",
"Id": "264283",
"Score": "1",
"Tags": [
"java",
"hash-map",
"search"
],
"Title": "Finding nodes with 0 or 1 parents - DFS or BFS"
}
|
264283
|
<p>I've put together an example single file upload script that attempts to cover all the things PHP could check for prior to allowing a successful file upload. Is there anything else maybe now available in PHP 7.4+ I could use to make this more secure? For example, I use <code>filter_input</code> below even though I don't find it in many scripts out there.</p>
<p>Take a look</p>
<pre><code><?php
# EVALUATE REQUEST METHOD
$REQUEST_METHOD = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
switch ($REQUEST_METHOD) {
# HTTP:POST - PAYLOAD:BLOB
case 'POST':
# POST IMAGE
if(\in_array(@$_FILES["files"], $_FILES) && \count($_FILES) === 1) {
upload();
}
break;
default:
methodInvalid();
break;
}
/**
* Function upload() uploads a single file.
*
*
*/
function upload() {
// Establish the upload file directory
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/gui/v1/uploads/submittals/';
// Establish the upload file path
$upload_file = $upload_dir . $_FILES['files']['name'][0];
// Derive the upload file extension
$upload_file_extension = strtolower(pathinfo($upload_file, PATHINFO_EXTENSION));
// Allowed file types
// $allowed_file_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif'];
$allowed_file_extensions = ['pdf'];
/**
* Does tmp file exist?
*
*
*/
if (!file_exists($_FILES['files']['tmp_name'][0])) {
# ERROR object
$errorObject = new stdClass();
$errorObject->apiVersion = '1.0';
$errorObject->context = 'upload.submittal';
# ABOUT ERROR object
$aboutError = new stdClass();
$aboutError->code = 'ERR-000';
$aboutError->message = 'Select file to upload.';
# APPEND ABOUT ERROR object TO ERROR object
$errorObject->error = $aboutError;
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($errorObject));
}
/**
* Is file extension allowed?
*
*
*/
if (!in_array($upload_file_extension, $allowed_file_extensions)) {
# ERROR object
$errorObject = new stdClass();
$errorObject->apiVersion = '1.0';
$errorObject->context = 'upload.submittal';
# ABOUT ERROR object
$aboutError = new stdClass();
$aboutError->code = 'ERR-000';
$aboutError->message = 'Allowed file formats .pdf';
# APPEND ABOUT ERROR object TO ERROR object
$errorObject->error = $aboutError;
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($errorObject));
}
/**
* Is file bigger than 20MB?
*
*
*/
if ($_FILES['files']['size'][0] > 20000000) {
# ERROR object
$errorObject = new stdClass();
$errorObject->apiVersion = '1.0';
$errorObject->context = 'upload.submittal';
# ABOUT ERROR object
$aboutError = new stdClass();
$aboutError->code = 'ERR-000';
$aboutError->message = 'File is too large. File size should be less than 20 megabytes.';
# APPEND ABOUT ERROR object TO ERROR object
$errorObject->error = $aboutError;
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($errorObject));
}
/**
* Does file already exist?
*
*
*/
if (file_exists($upload_file)) {
/**
* File overwritten successfuly!
*
*
*/
move_uploaded_file($_FILES['files']['tmp_name'][0], $upload_file);
# SUCCESS object
$successObject = new stdClass();
$successObject->apiVersion = '1.0';
$successObject->context = 'upload.submittal';
$successObject->status = 'OK';
# UPLOAD SUBMITTAL object
$data = new stdClass();
$data->submittalUploaded = true;
# APPEND DATA object TO SUCCESS object
$successObject->data = $data;
# APPEND empty arrays to DATA object
$successObject->data->arr1 = [];
$successObject->data->arr2 = [];
$successObject->data->arr3 = [];
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($successObject));
}
/**
* Can file actually be uploaded?
*
*
*/
if (!move_uploaded_file($_FILES['files']['tmp_name'][0], $upload_file)) {
/**
* File upload error!
*
*
*/
# ERROR object
$errorObject = new stdClass();
$errorObject->apiVersion = '1.0';
$errorObject->context = 'upload.submittal';
# ABOUT ERROR object
$aboutError = new stdClass();
$aboutError->code = 'ERR-000';
$aboutError->message = 'File couldn\'t be uploaded.';
# APPEND ABOUT ERROR object TO ERROR object
$errorObject->error = $aboutError;
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($errorObject));
} else {
/**
* File uploaded successfuly!
*
*
*/
# SUCCESS object
$successObject = new stdClass();
$successObject->apiVersion = '1.0';
$successObject->context = 'upload.submittal';
$successObject->status = 'OK';
# UPLOAD SUBMITTAL object
$data = new stdClass();
$data->submittalUploaded = true;
# APPEND DATA object TO SUCCESS object
$successObject->data = $data;
# APPEND empty arrays to DATA object
$successObject->data->arr1 = [];
$successObject->data->arr2 = [];
$successObject->data->arr3 = [];
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($successObject));
// We could insert URL file path to a database from here...
}
}
/**
* Function methodInvalid() warns about invalid method.
*
*
*/
function methodInvalid() {
# ERROR object
$errorObject = new stdClass();
$errorObject->apiVersion = '1.0';
$errorObject->context = 'uploads';
# ABOUT ERROR object
$aboutError = new stdClass();
$aboutError->code = 'ERR-000';
$aboutError->message = 'Invalid Request. Allowed Methods are POST.';
# APPEND ABOUT ERROR object TO ERROR object
$errorObject->error = $aboutError;
# RETURN JSON RESPONSE
header('Content-type:application/json;charset=utf-8');
return print(json_encode($errorObject));
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:07:42.537",
"Id": "522051",
"Score": "2",
"body": "Please do not describe the type of review that you are seeking in your title. Your title should only describe what your script does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T01:38:54.753",
"Id": "522064",
"Score": "0",
"body": "Agreed. Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T01:43:40.570",
"Id": "522065",
"Score": "1",
"body": "\"Security\" is still describing your concern (not the function of the script)."
}
] |
[
{
"body": "<p>A few of my thoughts after quick top-to-bottom scan:</p>\n<p>Filtering REQUEST_METHOD is absurdly future-proof (you'd have to anticipate an evolution of the code where the literal contents are stored in a database and end up being output without validation to somebodies browser),\nbut somehow I like your mind-set.</p>\n<p>The check count($_FILES) === 1 is sort of the opposite. If the front-end evolves into uploading a second file (in a different POST-variable) your code ignores both uploads. It doesn't call methodInvalid nor does it log an error-message.</p>\n<p>Later in the code you double-check if PHP has indeed put the temporary file where it says it has put it (that's overkill, but it's better to be overly paranoid than overly relaxed).\nYet you don't don't check if $_FILES['files']['name'] contains nasty stuff like "../" which could cause files to be uploaded to places you don't want them to go.</p>\n<p>I noticed a lot of magic values which make their appearance in the guts of your code (the extensions you support, the maximum file size, the upload directory, error codes, api versions etc.). Pull them out.</p>\n<p>The code has no structure (unless you count "one statement after the other" as a structure). Introducing functions to isolate/encapsulate functional aspects makes the codes much easier to maintain & evolve.</p>\n<p>Invoking "new stdclass" and giving it a field "apiVersion" raised an eyebrow and a half. If you're serious about developing an API, introduce some dedicated classes for responses.</p>\n<p>In summary: the code has many opportunities for improvements, but I really appreciate your goal of making it as secure as possible. As it stands, it looks pretty solid security-wise. But don't ignore the fact that the current low level of readability makes it hard/too tedious to truly verify if it really is secure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T10:17:50.807",
"Id": "264316",
"ParentId": "264285",
"Score": "1"
}
},
{
"body": "<p>Personally I am more interested in looking at the possible <strong>security issues</strong>. File uploads are notoriously dangerous if not done right. A vulnerable form could allow an attacker to upload a webshell and take over your server.</p>\n<p>Let focus on this line:</p>\n<pre><code>// Establish the upload file path\n$upload_file = $upload_dir . $_FILES['files']['name'][0];\n</code></pre>\n<p>You are relying on the <strong>original file name</strong>, which could be malicious. By definition, it is untrusted third-party input. What would happen if the file name contains stuff like '../../'. The uploaded file could land outside the designated folder. This is a classic path traversal attack.</p>\n<p>Or what happens if the file contains spaces, what about "shell.php test.pdf". This file name will match the allowed file extensions but what happens next ? What could possibly go wrong ? Maybe not an immediate vulnerability but your script could easily choke on a malformed file name.</p>\n<p>You should never ever blindly reuse the original file name, which anyway can contain special characters or even be too long for your file system. At the very least sanitize it, discard or replace undesirable characters etc.</p>\n<p>The absolute minimum you should have done is resolve the canonical path, you have a function like <a href=\"https://www.php.net/manual/en/function.realpath.php\" rel=\"nofollow noreferrer\">realpath</a> for this purpose.</p>\n<p>However the doc <a href=\"https://www.php.net/manual/en/function.move-uploaded-file.php\" rel=\"nofollow noreferrer\">says</a>:</p>\n<blockquote>\n<p>move_uploaded_file() is open_basedir aware. However, restrictions are\nplaced only on the to path as to allow the moving of uploaded files in\nwhich from may conflict with such restrictions. move_uploaded_file()\nensures the safety of this operation by allowing only those files\nuploaded through PHP to be moved.</p>\n</blockquote>\n<hr />\n<p>Regarding the <strong>request methods</strong>: I am afraid these are moot security considerations.</p>\n<p>First of all, the allowed methods should be set in your webserver configuration or virtual host directives. I don't think your script should concern itself with the method (verb). It should simply expect GET or POST requests. If anything else is submitted, your script will not see it and will not process it.</p>\n<p>So I would configure the webserver to accept GET, POST, and I would also add HEAD because search engines might use it.</p>\n<p>The PHP doc for <a href=\"https://www.php.net/manual/en/function.move-uploaded-file.php\" rel=\"nofollow noreferrer\">move_uploaded_file</a> says (emphasis is mine):</p>\n<blockquote>\n<p>move_uploaded_file(string $from, string $to): bool</p>\n<p>This function checks to ensure that the file designated by from is a\nvalid upload file (<strong>meaning that it was uploaded via PHP's HTTP POST\nupload mechanism</strong>). If the file is valid, it will be moved to the\nfilename given by to.</p>\n</blockquote>\n<p>So that means a file upload will only work if done using POST. The move_uploaded_file function in itself is sufficient to assert that the upload indeed took place using the POST method.</p>\n<hr />\n<p>What is obvious in your code is the amount of unnecessary <strong>repetition</strong>. For instance you are testing the file extension, the file size, and also whether the file exists in the upload folder. Then you are repeating the $aboutError stuff in each block, when in fact the only thing that is different is the actual error message relevant to the condition you are testing:</p>\n<pre><code>$aboutError->message = 'File is too large. File size should be less than 20 megabytes.';\n</code></pre>\n<p>Even the error code is the same everywhere for the moment. The code is bloated, because there is lots of stuff that you could define just once. You can simply redefine the error message in each test with the appropriate message, and leave the rest of the variables unchanged since they have been set previously.</p>\n<p>What is clear is that certain variables like API version don't need to be defined multiple times. They should be <strong>constants</strong> and defined just once at the top of your code.</p>\n<hr />\n<p>At line 124: you check if the file already exists:</p>\n<pre><code>if (file_exists($upload_file)) {\n</code></pre>\n<p>but you overwrite it anyway, by design it seems. So this block of code is useless, you could as well remove it and let the procedure continue to the next block, where move_uploaded_file is actually run.</p>\n<p>And in fact the block starting at line 46 is pointless too:</p>\n<pre><code>if (!file_exists($_FILES['files']['tmp_name'][0])) {\n</code></pre>\n<p>because as previously mentioned, move_uploaded_file can verify that an uploaded file actually exists. By the way a sibling function exists: <a href=\"https://www.php.net/manual/en/function.is-uploaded-file.php\" rel=\"nofollow noreferrer\">is_uploaded_file</a></p>\n<p>But you are not even checking that move_uploaded_file returns true - this function returns a boolean value. If it does not return true, something went wrong.</p>\n<hr />\n<p>I don't understand the point of this code:</p>\n<pre><code># APPEND empty arrays to DATA object\n$successObject->data->arr1 = [];\n$successObject->data->arr2 = [];\n$successObject->data->arr3 = [];\n</code></pre>\n<p>If it is really useful or meaningful, this is where you should have added some comments to clarify the purpose.\nI am even wondering if your code actually works in its present form ?</p>\n<hr />\n<p>The <strong>indentation</strong> should be streamlined to make the code outline more clear, especially control blocks (ifs or loops).</p>\n<hr />\n<p>To sum up, I suggest to read the PHP docs and start over with simple examples that you can augment along the way. The bottom line is, don't do useless tests, and don't test for irrelevant conditions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T01:36:00.363",
"Id": "522063",
"Score": "0",
"body": "Love the feedback. The reason for repetition was for you to answer as specifically as you did. For you to see and expose flaws as clearly as you have while at the same time allowing a new programmer to easily follow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:14:50.467",
"Id": "264338",
"ParentId": "264285",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "264338",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T15:59:16.937",
"Id": "264285",
"Score": "1",
"Tags": [
"php"
],
"Title": "PHP File Upload Script"
}
|
264285
|
<p>Coming from a Java/Scala background with a strong focus on <strong>OOP+FP</strong>, I recently started working with Excel+VBA to implement a front-end for a SaaS. It was like stepping way back in time, over two decades, in software engineering trying to understand how to use and exploit VBA.</p>
<p>In the ensuing 3 months of being immersed in VBA, I have ended up running into and then unique solving a number of problems using a more principled software engineering principled approach. This includes things like <strong>DRY</strong> (Don't Repeat Yourself which means eschew copy/pasta), <strong>DbC</strong> (Design by Contract which means define clear boundaries around types and functions), <strong>encapsulation</strong>, <strong>immutability</strong>, <strong>referential transparency</strong>, etc.</p>
<p>The first things I hit had to do with VBA's <code>Array</code>. The code smell of the imperative solutions I found on StackOverflow and the web, in general, was very frustrating. Additionally, it seemed all the proposed solutions I found were not only not DRY (Don't Repeat Yourself) whatsoever, almost all of them seemed to have subtle errors for which they didn't account. After hitting issue after issue with just trying to figure out if an <code>Array</code> was allocated, empty, or defined (non-empty), I finally set about trying to create an optimal solution.</p>
<p>Given my lack of VBA-specific experience (I have a year's worth of VBA 3.0 from back in 1994-1995), I'd like to understand to what degree the solution I am proposing is safe, robust, and performant.</p>
<p>And just as a reminder, I am desiring the critique to be more from a software engineering principles perspective. IOW, I am not focused on novice Excel macro programmers. Or nitpicking about particular VBA syntax and semantics (unless that specifically relates to DRY, DbC, etc.). The intention is to assist future Java/Scala/Python/etc. software engineers who must create and support VBA code bases. Like me.</p>
<p>Feedback is appreciated.</p>
<p><strong>SIDENOTE:</strong> In this submission, to keep the discussion clean, I don't plan to discuss my unique VBA code formatting approach. If you are interested in a discussion around that, let me know in the comments below and I will start a separate review submission for that.</p>
<hr />
<p>The main function, <code>f_ua_lngSize</code>, just focuses on obtaining the size. The function can be called on any of the <code>Array</code>'s dimensions, and defaults to the first.</p>
<pre class="lang-vb prettyprint-override"><code>Public Const M_UA_SIZE_NOT_ARRAY As Long = -1
Public Const M_UA_SIZE_EMPTY As Long = 0
'Return Value:
' -1 - Not an Array
' 0 - Empty
' > 0 - Defined
Public Function f_ua_lngSize( _
ByRef pr_avarValues As Variant _
, Optional ByVal pv_lngDimensionOneBased As Long = 1 _
) As Long
Dim lngSize As Long: lngSize = M_UA_SIZE_NOT_ARRAY 'Default to not an Array
Dim lngLBound As Long
Dim lngUBound As Long
On Error GoTo Recovery
If (IsArray(pr_avarValues) = True) Then
lngSize = M_UA_SIZE_EMPTY 'Move default to Empty
lngLBound = LBound(pr_avarValues, pv_lngDimensionOneBased)
lngUBound = UBound(pr_avarValues, pv_lngDimensionOneBased)
If (lngLBound <= lngUBound) Then
lngSize = lngUBound - lngLBound + 1 'Non-Empty, so return size
End If
End If
NormalExit:
f_ua_lngSize = lngSize
Exit Function
Recovery:
GoTo NormalExit
End Function
</code></pre>
<p>Then I've created two helper functions, <code>f_ua_blnIsEmpty</code> and <code>f_ua_blnIsDefined</code>, which just interpret calls to <code>f_ua_lngSize</code> above.</p>
<pre class="lang-vb prettyprint-override"><code>Public Function f_ua_blnIsEmpty( _
ByRef pr_avarValues As Variant _
, Optional ByVal pv_lngDimensionOneBased As Long = 1 _
) As Boolean
f_ua_blnIsEmpty = f_ua_lngSize(pr_avarValues, pv_lngDimensionOneBased) = 0
End Function
Public Function f_ua_blnIsDefined( _
ByRef pr_avarValues As Variant _
, Optional ByVal pv_lngDimensionOneBased As Long = 1 _
) As Boolean
f_ua_blnIsDefined = f_ua_lngSize(pr_avarValues, pv_lngDimensionOneBased) > 0
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T07:17:37.327",
"Id": "521986",
"Score": "1",
"body": "Fwiw, the late Chip Pearson's [Functions for VBA arrays](http://www.cpearson.com/excel/vbaarrays.htm) cover edge cases very rigorously, although I cannot vouch for how performant they are (that said, I would only focus on performance if this is demonstrably a bottleneck). There are some things I would change and rubberduck would suggest many but it's a good start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:11:42.450",
"Id": "522054",
"Score": "0",
"body": "@greedo I did have a look at CP's stuff (although I didn't realize he had passed...my condolences). CP's stuff seemed to depend very deeply on `Variant` which I understood to have very poor performance. I do realize the code above is based on `Variant` as that is the only way to create collection \"generic\" code in VBA, from what I can tell."
}
] |
[
{
"body": "<p>Once you know you have an array it looks to me that this comparison is unecessary:</p>\n<pre><code>If (lngLBound <= lngUBound) Then\n lngSize = lngUBound - lngLBound + 1 'Non-Empty, so return size\nEnd If\n</code></pre>\n<p>The reason being that if you have an uninitialized array then</p>\n<pre><code>lngLBound = 0\nlngUBound = -1\n</code></pre>\n<p>So your equation evaluates to:</p>\n<pre><code>lngSize = -1 - 0 + 1\n</code></pre>\n<p>Which means that <code>lngSize = 0</code></p>\n<p>So it's safe to simplify your main function like so:</p>\n<pre><code>Public Function f_ua_lngSize( _\n ByRef pr_avarValues As Variant _\n , Optional ByVal pv_lngDimensionOneBased As Long = 1 _\n) As Long\n Dim lngSize As Long: lngSize = M_UA_SIZE_NOT_ARRAY 'Default to not an Array\n Dim lngLBound As Long\n Dim lngUBound As Long\n \n On Error GoTo Recovery\n \n If (IsArray(pr_avarValues) = True) Then\n lngLBound = LBound(pr_avarValues, pv_lngDimensionOneBased)\n lngUBound = UBound(pr_avarValues, pv_lngDimensionOneBased)\n lngSize = lngUBound - lngLBound + 1 ' return size\n End If\n \nNormalExit:\n f_ua_lngSize = lngSize\n Exit Function\n \nRecovery:\n GoTo NormalExit\nEnd Function\n</code></pre>\n<p>This makes <code>M_UA_SIZE_EMPTY</code> unused.</p>\n<p>To prove this out I recommend writing a unit test suite that tests all cases you expect to handle. You can have a test for at least your three states listed above the function.</p>\n<p>You can use <a href=\"https://rubberduckvba.com/\" rel=\"nofollow noreferrer\">RubberDuckVBA</a> to help you write and run unit tests. It will also give you some of the modern features you are missing in VBA. <strong>WARNING:</strong> It will tell you about all the style mistakes you are making that you said you don't want to hear about. So be prepared to be amazed and also prepare to have your feelings hurt.</p>\n<p><strong>NOTE:</strong> I have answered for performant by reducing an instruction. I have answered safe by suggesting that unit testing is your provable measure of safety. As for robustness I think it does what it says on the tin without side effect so it's good.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T21:59:38.637",
"Id": "522048",
"Score": "0",
"body": "I found and have been using RubberDuckVBA for the last month. It definitely enhanced my IDE experience. It didn't move the needle much on VBA itself, not that it really could have. I am curious about the Unit testing, though. I WAY prefer TDD. I use JUnit extensively in Java, and a similar tool in Scala. Is there a link somewhere showing how to get something similar via RubberDuckVBA? A quick look around didn't show anything obvious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:06:15.490",
"Id": "522050",
"Score": "0",
"body": "BTW, I went here: https://rubberduckvba.com/Features/Details/UnitTesting But the branch of links are all 404s. So, any guidance or examples of how to do Unit testing with RubberDuckVBA would be greatly appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:07:45.193",
"Id": "522052",
"Score": "1",
"body": "@chaotic3quilibrium yes, he made a new website and it's been under construction for quite some time. There is tons of good information about unit tests and all things VBA on the authors blog: https://rubberduckvba.wordpress.com/2017/10/19/how-to-unit-test-vba-code/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:11:57.477",
"Id": "522055",
"Score": "1",
"body": "You may enjoy his OOP articles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T16:16:26.650",
"Id": "522091",
"Score": "0",
"body": "I've begun reading through his blog posts going backward in time. He's quite the prolific and wordy writer. Very nice content. Just a bit laborious to read through at times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T15:35:56.850",
"Id": "522199",
"Score": "1",
"body": "@chaotic3quilibrium just FYI, he can hear you. He's quite active here."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T22:00:24.470",
"Id": "264297",
"ParentId": "264287",
"Score": "1"
}
},
{
"body": "<p>@Hackslash The assertion of</p>\n<pre><code>lngLBound = 0\nlngUBound = -1\n</code></pre>\n<p>for an uninitialised array is incorrect. The code below demonstrates why</p>\n<pre><code>Public Sub ArrayTypeInfo()\n\n Dim myUbound As Long\n Dim myUboundMsg As String\n On Error Resume Next\n Debug.Print , , , "TypeName", "VarType", "IsArray", "IsNull", "IsEmpty", "Ubound"\n \n Dim myLongs() As Long\n myUbound = UBound(myLongs)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "Dim myLongs() As Long", , TypeName(myLongs), VarType(myLongs), IsArray(myLongs), IsNull(myLongs), IsEmpty(myLongs), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n'@Demonstrates nicely the dangers of assumption after on error resume next\n'@ its not a Ubound error. You can't assign an array created using array to an array not declared as variant holding array of x.\n myLongs = Array(1&, 2&, 3&, 4&, 5&)\n myUbound = UBound(myLongs)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myLongs = Array(1&, 2&, 3&, 4&, 5&)", TypeName(myLongs), VarType(myLongs), IsArray(myLongs), IsNull(myLongs), IsEmpty(myLongs), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n ReDim myLongs(1 To 5)\n myUbound = UBound(myLongs)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "ReDim myLongs(1 To 5)", , TypeName(myLongs), VarType(myLongs), IsArray(myLongs), IsNull(myLongs), IsEmpty(myLongs), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n Debug.Print\n Dim myArray As Variant\n myUbound = UBound(myArray)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "Dim myArray As Variant", , TypeName(myArray), VarType(myArray), IsArray(myArray), IsNull(myArray), IsEmpty(myArray), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n myArray = Array()\n myUbound = UBound(myArray)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myArray = Array()", , TypeName(myArray), VarType(myArray), IsArray(myArray), IsNull(myArray), IsEmpty(myArray), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n myArray = Array(1, 2, 3, 4, 5)\n myUbound = UBound(myArray)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myArray = Array(1, 2, 3, 4, 5)", TypeName(myArray), VarType(myArray), IsArray(myArray), IsNull(myArray), IsEmpty(myArray), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n myArray = myLongs\n myUbound = UBound(myArray)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myArray = myLongs", , TypeName(myArray), VarType(myArray), IsArray(myArray), IsNull(myArray), IsEmpty(myArray), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n Debug.Print\n Dim myArrayOfVar() As Variant\n myUbound = UBound(myArrayOfVar)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "Dim myArrayOfVar() As Variant", TypeName(myArrayOfVar), VarType(myArrayOfVar), IsArray(myArrayOfVar), IsNull(myArrayOfVar), IsEmpty(myArrayOfVar), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n myArrayOfVar = Array()\n myUbound = UBound(myArrayOfVar)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myArrayOfVar = Array()", , TypeName(myArrayOfVar), VarType(myArrayOfVar), IsArray(myArrayOfVar), IsNull(myArrayOfVar), IsEmpty(myArrayOfVar), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \n myArrayOfVar = Array(1&, 2&, 3&, 4&, 5&)\n myUbound = UBound(myArrayOfVar)\n myUboundMsg = IIf(Err.Number = 0, CStr(myUbound), "Ubound error")\n Debug.Print "myArrayOfVar = Array(1&, 2&, 3&, 4&, 5&)", TypeName(myArrayOfVar), VarType(myArrayOfVar), IsArray(myArrayOfVar), IsNull(myArrayOfVar), IsEmpty(myArrayOfVar), myUboundMsg\n On Error GoTo 0\n On Error Resume Next\n \nEnd Sub\n</code></pre>\n<p>which gives the output</p>\n<pre><code> TypeName VarType IsArray IsNull IsEmpty Ubound\nDim myLongs() As Long Long() 8195 True False False Ubound error\nmyLongs = Array(1&, 2&, 3&, 4&, 5&) Long() 8195 True False False Ubound error\nReDim myLongs(1 To 5) Long() 8195 True False False 5\n\nDim myArray As Variant Empty 0 False False True Ubound error\nmyArray = Array() Variant() 8204 True False False -1\nmyArray = Array(1, 2, 3, 4, 5) Variant() 8204 True False False 4\nmyArray = myLongs Long() 8195 True False False 5\n\nDim myArrayOfVar() As Variant Variant() 8204 True False False Ubound error\nmyArrayOfVar = Array() Variant() 8204 True False False -1\nmyArrayOfVar = Array(1&, 2&, 3&, 4&, 5&) Variant() 8204 True False False 4\n</code></pre>\n<p>It should be noted that if Ubound gives a result of -1 it is also necessary to check Lbound for a valid result as the following definition is perfectly acceptable in VBA</p>\n<pre><code>Dim myArray(-10 to -1,-10 to -1, -10 to -1)\n</code></pre>\n<p><strong>Update 24 July2021 - I made a mistake below and forgot about the 0th index so my assertion that when crossing from negative to positive you only need Ubound-Lbound is wrong, Its still Ubound-Lbound+1</strong>\nand finally you also need to be aware that if Lbound and Ubound have the same sign then the size can be calculated using Ubound-Lbound+1 BUT if they have opposite signs then size is just Ubound-Lbound.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:02:27.517",
"Id": "522049",
"Score": "0",
"body": "Wow! Tysvm for your beyond thorough answer. I really appreciate it. I will make a code adjustment to handle the \"crossing zero\" case you identified. This is an example of an edge case I DID NOT SEE ADDRESSED ANYWHERE ELSE. And that is after looking at hundreds of StackOverflow questions/answers (of which there seems to be a huge number just around VBA Array Size issues - it's like it is the ultimate opportunity to ensure off-by-one issues)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:11:04.950",
"Id": "522053",
"Score": "1",
"body": "TIL. I've never seen a negative array index in all my years. I always thought indexes began at 0 (Unsigned int) and everything else was just hand waving."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T16:03:57.920",
"Id": "522089",
"Score": "0",
"body": "@HackSlash Yep. This is exactly the kind of thing I was describing in my OP. There are just too many weird corner cases. Personally, my own code ALWAYS uses an `LBound = 0` `Array`. If I must deal with an `Array` where `LBound <> 0`, I force it to become an `LBound = 0`. The number one issue in all of software engineering, by far, is off-by-one errors. And since VBA isn't very iterator friendly, it is really important to force simplify anything having to do with off-by-one error opportunities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T16:11:55.300",
"Id": "522090",
"Score": "0",
"body": "@freeflow I went to make the code changes related to your Answer's last paragraph addressing the `UBound - LBound + 1` issue. In writing the tests, I was unable to reproduce what you are asserting. What am I missing? The test code I used is here: https://gist.github.com/jim-oflaherty-jr-qalocate-com/abc191d0e76bbc015a086b133b2521e4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T17:00:44.687",
"Id": "522096",
"Score": "1",
"body": "Yeah am I being dumb, or does a 1D array with Lbound -1, Ubound 1 not have 3 elements, or 1 - (-1) _+1_. I.e. the original formula is fine even when crossing zero"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T17:22:36.270",
"Id": "522097",
"Score": "2",
"body": "Slaps face, puts on pointy hat and goes to stand in corner. I've updated my post to make sure the error is highlighted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T17:45:39.653",
"Id": "522099",
"Score": "1",
"body": "As a result of analyzing all of this, I did find a small performance improvement. I will post and answer showing the one improvement."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:06:31.500",
"Id": "264311",
"ParentId": "264287",
"Score": "0"
}
},
{
"body": "<p><strong>NOTE:</strong> Per the CodeReview rules, I am not allowed to modify my original question with suggestions and improvements. And instead, I'm required to post an answer showing any substantial adjustments and/or enhancements. Hence, the post below.</p>\n<hr />\n<p><strong>UPDATE 2021/Jul/31</strong></p>\n<p>Per deeply appreciated additional feedback from @Freeflow, I have updated the code to simplify the naming scheme (ex: removed the Hungarian Notation).</p>\n<hr />\n<p>Thanks to both comments and feedback by @HackSlash and @FreeFlow, it appears the original overall implementation is correct.</p>\n<p>However, in my continuous review, I discovered two things that can be changed to reduce the number of instructions executed leading to probably improved performance. A visual diff between the OP (above) and the new code (below) is <a href=\"https://editor.mergely.com/pIhhre77/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Const SIZE_NOT_ARRAY As Long = -1\nPublic Const SIZE_EMPTY As Long = 0\n\n'Return Value:\n' -1 - Not an Array\n' 0 - Empty\n' > 0 - Defined\nPublic Function size( _\n ByVal value As Variant _\n , Optional ByVal dimensionOneBased As Long = 1 _\n) As Long\n Dim result As Long: result = SIZE_NOT_ARRAY 'Default to not an Array\n\n Dim lowerBound As Long\n Dim upperBound As Long\n \n On Error GoTo NormalExit\n \n If (IsArray(value) = True) Then\n result = SIZE_EMPTY 'Move default to Empty\n lowerBound = LBound(value, dimensionOneBased) 'Possibly generates error\n upperBound = UBound(value, dimensionOneBased) 'Possibly generates error\n If (lowerBound < upperBound) Then\n result = upperBound - lowerBound + 1 'Size greater than 1\n Else\n If (lowerBound = upperBound) Then\n result = 1 'Size equal to 1\n End If\n End If\n End If\n \nNormalExit:\n size = result\nEnd Function\n\nPublic Function isEmpty( _\n ByVal value As Variant _\n , Optional ByVal dimensionOneBased As Long = 1 _\n) As Boolean\n isEmpty = size(value, dimensionOneBased) = 0\nEnd Function\n\nPublic Function isDefined( _\n ByVal value As Variant _\n , Optional ByVal dimensionOneBased As Long = 1 _\n) As Boolean\n isDefined = size(value, dimensionOneBased) > 0\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:53:58.417",
"Id": "522135",
"Score": "1",
"body": "COngratulations. You should still be aware that your code is still very hard to read as it is laced with 'mysterios' prefixes and other hungarion type notation. For comparison take a look as my TryGetSize Function\n\n```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:25:58.097",
"Id": "522211",
"Score": "0",
"body": "@FreeFlow Yes. I am experimenting with a strongly typed VBA which makes Java/Scala programmers more at home, given how poorly the VBA IDE surfaces information about the types. Rubberduck helps, but doesn't currently enable easily seeing the context and types of things directly in the code. IOW, I cannot hover over a variable and see critical aspects to understand with to use it. And given it isn't an object, I don't get intellisense assistance to be able to narrow context to what \"methods\" would be useful to use on the variable/function-result/etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:28:38.440",
"Id": "522212",
"Score": "0",
"body": "@FreeFlow And I didn't understand your function at all. While the variables were readable, they referred to \"hidden\" things for which I have ZERO context and are unable to clarify without seeing the rest of your codebase AND jumping into your definitions. IOW, while you might be elevating local readability slighty better by variable/function/etc. name, my clarifying the meaning makes me jump to other places in the code to get the clarifying context. As a Java/Scala coder with decades of experience, I want/need the context at the use site. Hence, my ongoing experimentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:35:55.240",
"Id": "522213",
"Score": "1",
"body": "LMAO! I just returned to Rubberduck and found that it does in fact show the return type for functions (right next to the \"Ready\" refresh button). That is SUPER helpful. There is still a ton of context not supplied that I want at the use sites. Like is a function referentially transparent, or not? Does it or one of the things it calls modify the spreadsheet, versus it just does something without modifying the spreadsheet state. These are really important things to avoid breaking my flow as I am coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:53:54.683",
"Id": "524568",
"Score": "0",
"body": "Given the rant you had last time, not a chance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T17:20:58.160",
"Id": "524576",
"Score": "0",
"body": "@FreeFlow No worries. I apologize if you felt insulted. That was certainly not my intention. Sometimes my text/comments do a poor job of communicating intent. And I do appreciate the comments and feedback you have already given. I wish you all the best in your future learnings in these areas."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T21:10:06.340",
"Id": "264359",
"ParentId": "264287",
"Score": "0"
}
},
{
"body": "<p>Your code is still laced with very ugly, impenetrable prefixes and other 'hungation nototation' stuff.. Try comparing the readability of your code with my TryGetSize function</p>\n<pre><code>'@Description("Returns the count of items in an iterable")\nPublic Function TryGetSize(ByVal ipIterable As Variant, Optional ByRef iopResult As ResultLong, Optional ByVal ipRank As Long = 1) As ResultLong\n\n If iopResult Is Nothing Then Set iopResult = ResultLong.Deb.SetFailure\n Set TryGetSize = iopResult\n \n If Types.Group.IsNotIterable(ipIterable) Then Exit Function\n \n If Types.IsArray(ipIterable) Then\n \n Arrays.TryGetSize ipIterable, ipRank, iopResult\n \n Else\n \n iopResult.SetSuccess ipIterable.Count\n \n End If\n \nEnd Function\n</code></pre>\n<p>Of course for the above code there is a fair bit of backing library code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:18:23.380",
"Id": "522214",
"Score": "0",
"body": "I didn't understand your function at all. While the variables were readable, they referred to \"hidden\" things for which I have ZERO context and are unable to clarify without seeing the rest of your codebase AND jumping into your definitions. More details in comments here: https://codereview.stackexchange.com/a/264359/4758"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:14:05.347",
"Id": "522312",
"Score": "1",
"body": "@chaotic3quilibrium I'm sorry you are feeling frustrated by the VBA Ide. For the code I presented everything is discoverable through Intellisense, and the detail through F2 and Shift F2. I'm sorry now I didn't make this clearer. I've never had the advantage of more sophisticated IDE's as I'm just a hobbyist programmer so have learnt how to make the best use of the limited facilities that the VBA ide does present. I did acknowledge that the code I provided was supported by a fair bit of backing Library code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T14:49:09.400",
"Id": "524564",
"Score": "0",
"body": "Per your comment about my naming convention experiments and now that I have far more Rubberduck IDE experience, I have now refactored the OP function. Please have a look at this Gist and let me know if you think it is more readable. And also if you have any other feedback about it. https://gist.github.com/jim-oflaherty-jr-qalocate-com/797fc70c0ed1d94843f4b1888ff94860"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T11:44:04.173",
"Id": "525038",
"Score": "0",
"body": "@Freeflow: I'm interested in your `Types.Group.` idea (and maybe more around). Could you somewhere/somehow explain a bit about 'what and how' is in your lib?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T16:25:02.400",
"Id": "525120",
"Score": "0",
"body": "@UnhandledException No problem. I'll open a code review item tomorrow and expose the ghastly details to view. I'll post a link here when I've done so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T11:59:14.833",
"Id": "525152",
"Score": "0",
"body": "@UnhandledException When I looked at the code is was going to be a bit problematical to upload to code review. Instead I've uploaded to my github repository. There should be two public projects you can view 1. VBALib (https://github.com/FullValueRider/VBALib) which contains the Types and related classes. The second is my VBAKvp class (https://github.com/FullValueRider/VBAKvp) which was the driver behind creating the VBALib (and Types class). If you follow the Add method in KVP you will see how the Types class is used to simplify code. Let me know if there are problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:01:44.690",
"Id": "525153",
"Score": "0",
"body": "@Freeflow: Great, thank you very much! I will take a look in thist evening."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T10:28:35.523",
"Id": "525228",
"Score": "0",
"body": "@Freeflow: Your second link leads to nirvana. Maybe the lib VBAKvp is not public?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T11:33:41.437",
"Id": "525231",
"Score": "0",
"body": "@UnhandledException. Apologies. SHould be public now."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:56:03.457",
"Id": "264394",
"ParentId": "264287",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "264359",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T18:00:16.427",
"Id": "264287",
"Score": "2",
"Tags": [
"array",
"vba"
],
"Title": "To what degree is my VBA Array size function safe, robust, and performant"
}
|
264287
|
<p>This nice hack should allow you to split a tuple into N-element tuples, thereby effectively splitting a tuple into pairs, triples, ... For example, this allows you to split an input parameter pack, into N-element tuples. Your thoughts?</p>
<pre><code>template <std::size_t N>
constexpr auto split(auto&& t) noexcept
{
static_assert(std::tuple_size_v<std::remove_cvref_t<decltype(t)>> &&
!(std::tuple_size_v<std::remove_cvref_t<decltype(t)>> % N));
return [&]<auto ...I>(std::index_sequence<I...>) noexcept
{
return std::make_tuple([&]<auto K, auto ...J>(
std::index_sequence<J...>) noexcept
{
return std::forward_as_tuple(std::get<K + J>(
std::forward<decltype(t)>(t))...);
}.template operator()<N * I>(std::make_index_sequence<N>())...
);
}(std::make_index_sequence<std::tuple_size_v<
std::remove_cvref_t<decltype(t)>> / N>());
}
</code></pre>
<p>Usage:</p>
<pre><code>auto foo(auto&& ...a)
{
auto const f([&](auto&&, auto&&)
{
}
);
return std::apply([&](auto&& ...t)
{
return (std::apply(f, std::forward<decltype(t)>(t)), ...);
},
split<2>(std::forward_as_tuple(a...))
);
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Corner-cases needing manual handling by the caller are the bane of correct and generic code.</p>\n<p>Remove them as possible, even if it would slightly complicate the implementation (it doesn't here). If it would impair efficiency that would necessitate more careful consideration, but might still be acceptable.</p>\n<ol>\n<li><p>Splitting an empty tuple is trivial.</p>\n</li>\n<li><p>Allowing the last tuple to be shorter removes that corner-case too.</p>\n</li>\n</ol>\n</li>\n<li><p>Make it SFINAE-friendly. Check applicability at overload-resolution using SFINAE, requires-clause, or concepts, not afterwards when it causes a hard error.<br />\nSee <a href=\"//stackoverflow.com/questions/68443804/c20-concept-to-check-tuple-like-types\">an example for thoroughly checking the tuple-like protocol on SO</a>.</p>\n</li>\n<li><p>Considering you depend on C++20 features, using C++17 CTAD instead of <code>std::make_tuple</code> would be appropriate.</p>\n</li>\n<li><p>Using an explicit template-argument on the lambda is a pointless complication.</p>\n</li>\n</ol>\n<pre><code>template <class T>\nconcept tuple_like_cvref = tuple_like<std::remove_cvref_t<T>>;\n\ntemplate <std::size_t N> requires(!!N)\nconstexpr auto split(tuple_like_cvref auto&& t) noexcept {\n constexpr auto n = std::tuple_size_v<std::remove_cvref_t<decltype(t)>>;\n return [&]<auto...I>(std::index_sequence<I...>){\n return std::tuple{\n [&]<auto...J>(std::index_sequence<J...>){\n constexpr auto M = I * N;\n return std::forward_as_tuple(std::get<M + J>(\n std::forward<decltype(t)>(t)\n )...);\n }(std::make_index_sequence<I < n / N ? N : n % N>())...\n };\n }(std::make_index_sequence<(n + N - 1) / N>());\n}\n</code></pre>\n<p>See <a href=\"//coliru.stacked-crooked.com/a/fcf7d677c72289a7\" rel=\"nofollow noreferrer\">live on coliru</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T10:24:17.203",
"Id": "264317",
"ParentId": "264289",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T18:36:46.393",
"Id": "264289",
"Score": "2",
"Tags": [
"c++",
"template",
"lambda",
"c++20",
"variadic"
],
"Title": "splitting a tuple into N-element tuples"
}
|
264289
|
<p>I have made a thread art generator that creates thread patterns from images. Mine is a bit different as it outputs an embroidery file (It embroiders quite nicely, though the settings need a lot of tweaking and the output file needs resizing) The code is quite inefficient, but that's python for you.</p>
<pre><code>from PIL import Image, ImageOps, ImageDraw, ImageEnhance
import numpy as np
from tqdm import tqdm
from skimage import feature
from skimage.morphology import dilation
from pyembroidery import *
#Variables
base_image = "test.jpg"
thread_count = 1000
nail_count = 600
min_dist = 30
contrast = 0.8
edge = 2
edge_size = 0
sizing = 5
def points_gen(r, n):
t = np.linspace(0, 2*np.pi, n, endpoint=False)
x = (r - 1) * np.cos(t) + r
y = (r - 1) * np.sin(t) + r
return np.c_[x.astype(int), y.astype(int)]
def plotLineLow(x0, y0, x1, y1):
dx = x1 - x0
dy = y1 - y0
yi = 1
if dy < 0:
yi = -1
dy = -dy
D = (2 * dy) - dx
y = y0
for x in range(x0, x1+1):
yield (x, y)
if D > 0:
y = y + yi
D = D + (2 * (dy - dx))
else:
D = D + 2*dy
def plotLineHigh(x0, y0, x1, y1):
dx = x1 - x0
dy = y1 - y0
xi = 1
if dx < 0:
xi = -1
dx = -dx
D = (2 * dx) - dy
x = x0
for y in range(y0, y1 + 1):
yield (x, y)
if D > 0:
x = x + xi
D = D + (2 * (dx - dy))
else:
D = D + 2*dx
def bresenham_line(x0, y0, x1, y1):
if abs(y1 - y0) < abs(x1 - x0):
if x0 > x1:
return plotLineLow(x1, y1, x0, y0)
else:
return plotLineLow(x0, y0, x1, y1)
else:
if y0 > y1:
return plotLineHigh(x1, y1, x0, y0)
else:
return plotLineHigh(x0, y0, x1, y1)
def white_to_transparency(img):
x = np.asarray(img.convert('RGBA')).copy()
x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(np.uint8)
return Image.fromarray(x)
def is_close(n, center, offset, length):
lo = (center - offset) % length
hi = (center + offset) % length
if lo < hi:
return lo <= n <= hi
else:
return n >= lo or n <= hi
def embroider(final_line):
pattern = EmbPattern()
pattern.add_block([line[0] for line in final_line], "black")
write_dst(pattern, "out.dst", {"long_stitch_contingency":CONTINGENCY_LONG_STITCH_SEW_TO})
#Open Image
img = Image.open(base_image)
img = img.resize((500, 500))
size = img.size
#Remove Trasperency
img = img.convert('RGBA')
background = Image.new('RGBA', size, (255,255,255))
img = Image.alpha_composite(background, img)
#Make B&W
img = img.convert("L")
#edge magic
edges = feature.canny(np.array(img), sigma=edge)
for _ in range(edge_size): edges = dilation(edges)
edges = white_to_transparency((ImageOps.invert(Image.fromarray((edges * 255).astype(np.uint8)).convert("L"))))
#Make RGBA
img = img.convert('RGBA')
#Add edge
img = Image.alpha_composite(img, edges)
#Make B&W Again
img = img.convert("L")
#Circle Crop
mask = Image.new('L', size, 255)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=1)
img = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))
img.paste(0, mask=mask)
#Contraster
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(contrast)
img.show()
points = points_gen(img.size[0] / 2, nail_count)
base_point = 0
final_line = []
img = np.asarray(img).copy()
for _ in tqdm(range(thread_count), desc="Calculating Threads"):
#get avg lumin
vals = dict()
max_num = len(points)
lines = ( (i, bresenham_line(*points[base_point], *point))
for i, point in enumerate(points)
if not is_close(i, base_point, min_dist, max_num))
for i, line in lines:
values = [img[value[1]][value[0]] for value in line]
vals[sum(values)/len(values)] = i
line = vals[min(vals.keys())]
final_line.append((tuple(points[base_point]), tuple(points[line])))
for pixel in bresenham_line(*points[base_point], *points[line]):
img[pixel[1]][pixel[0]] = 255
base_point = line
final_line = [[[i * sizing for i in x] for x in line] for line in final_line]
size = size[0]*sizing
output = Image.new('L', (size, size), 255)
out_draw = ImageDraw.Draw(output)
for line in final_line:
out_draw.line((*line[0], *line[1]), 0)
output.show()
output.save("out.jpg")
embroider(final_line)
</code></pre>
<p>I would show the embroidered piece, but it's of a family member and quite high in detail. I can show an outputted image of a random model I found on google images.</p>
<p><a href="https://i.stack.imgur.com/5J2P4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5J2P4.jpg" alt="Thread art image" /></a></p>
<p>There is a weird effect due to how we perceive faces that it looks more like a face the further you are from it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T02:25:00.873",
"Id": "521973",
"Score": "0",
"body": "What do you want to improve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T03:44:51.910",
"Id": "521976",
"Score": "0",
"body": "It runs a bit slow, but I've fixed that on my in. I was more wondering if I did something stupid or badly."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T19:13:47.150",
"Id": "264292",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Thread Art Generation that Creates Embroidery Files"
}
|
264292
|
<p>I have written a cryptographic hashing class named <code>Ccksum::DigestHasher</code> that allows the caller to select a hashing algorithm by name via OpenSSL's EVP interface. This class is the bread and butter of my <a href="https://gitlab.com/app-crypt/ccksum" rel="nofollow noreferrer">Ccksum</a> programming project. Here is the code so far (I combined the header and source files for the readability of this post. I also removed all documentation comments, because I believe the code speaks for itself):</p>
<pre><code>#include <iomanip>
#include <memory>
#include <openssl/evp.h>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
namespace Ccksum {
class Hasher {
public:
explicit Hasher() = default;
virtual ~Hasher() noexcept = default;
virtual std::string process(std::istream& input) const = 0;
virtual std::string name() const = 0;
};
class DigestHasher final : public Hasher {
public:
explicit DigestHasher(const std::string& name)
: m_context(EVP_MD_CTX_new(), EVP_MD_CTX_free)
, m_algorithm(EVP_get_digestbyname(name.c_str()))
, m_name(name)
{
if (m_context == nullptr) {
throw std::runtime_error("Cannot create hash algorithm context");
}
if (m_algorithm == nullptr) {
std::ostringstream errorMsg;
errorMsg << name << " is not a valid hash algorithm";
throw std::runtime_error(errorMsg.str());
}
}
~DigestHasher() noexcept override = default;
std::string process(std::istream& input) const override
{
if (!input.good()) {
throw std::runtime_error("Input stream is bad");
}
constexpr size_t bufferSize = 65536; // 64K seems good...
std::vector<char> buffer(bufferSize);
std::vector<unsigned char> hash(EVP_MD_size(m_algorithm));
if (EVP_DigestInit_ex(m_context.get(), m_algorithm, nullptr) == 0) {
throw std::runtime_error("Cannot initialize hash algorithm");
}
while (input.good()) {
input.read(buffer.data(), bufferSize);
if (EVP_DigestUpdate(m_context.get(), buffer.data(), input.gcount()) == 0) {
throw std::runtime_error("Cannot update hash context");
}
}
if (EVP_DigestFinal_ex(m_context.get(), hash.data(), nullptr) == 0) {
throw std::runtime_error("Cannot finalize hash context");
}
std::ostringstream formatHash;
formatHash << std::hex << std::setfill('0');
for (const auto& iterate : hash) {
formatHash << std::setw(2) << static_cast<unsigned int>(iterate);
}
return formatHash.str();
}
std::string name() const override
{
return m_name;
}
private:
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> m_context;
const EVP_MD* m_algorithm;
const std::string m_name;
};
} // Ccksum namespace
</code></pre>
<p><strong>NOTE:</strong> The <code>Ccksum::Hasher</code> abstract class exists for mocking purposes. My plan is to mock <code>Ccksum::DigestHasher</code> using <code>Ccksum::Hasher</code> to make it easier to unit test the <code>Ccksum::GenerateMode</code> class I am currently working on.</p>
<p><strong>Question 1:</strong> Should I wrap <code>m_algorithm</code> in a <code>std::unique_ptr</code> or leave it the way it is?</p>
<p><strong>Current rationale regarding question 1:</strong> I left <code>m_algorithm</code> as a raw const pointer of type <code>EVP_MD</code>, because the <a href="https://www.openssl.org/docs/man1.0.2/man3/EVP_DigestInit_ex.html#EXAMPLE" rel="nofollow noreferrer">example code</a> offered by OpenSSL's docs does not show freeing its <code>EVP_MD</code> variable, nor did I find any kind of <code>EVP_MD_free()</code> function. A <a href="https://stackoverflow.com/questions/65605731/need-to-free-evp-md-from-evp-sha256">Stack Overflow answer</a> states that there is no need to free <code>EVP_MD</code> at all. As a sanity check, I ran my code through valgrind and no memory leaks were found.</p>
<p><strong>EDIT 1:</strong> I changed the <code>bufferSize</code> constant to 64KB. This <a href="https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc938632(v=technet.10)?redirectedfrom=MSDN" rel="nofollow noreferrer">article</a> states that a buffer size of 64KB is a reasonable default for modern desktops.</p>
|
[] |
[
{
"body": "<p>This looks quite good already. However, some improvements can be made:</p>\n<h1 id=\"avoid-unnecessary-use-of-stringstreams-ke34\">Avoid unnecessary use of <code>stringstream</code>s</h1>\n<p>String streams are quite heavy, so using it to build small strings is perhaps not the way to go. Instead of:</p>\n<pre><code>std::ostringstream errorMsg;\nerrorMsg << name << " is not a valid hash algorithm";\nthrow std::runtime_error(errorMsg.str());\n</code></pre>\n<p>You can just write:</p>\n<pre><code>throw std::runtime_error(name + " is not a valid hash algorithm");\n</code></pre>\n<p>With C++20 (or using the <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">{fmt}</a> library for older versions of the C++ standard), you can <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\">format</a> strings the C way, but in a type-safe way:</p>\n<pre><code>throw std::runtime_error(std::format("{} is not a valid hash algorithm", name));\n</code></pre>\n<h1 id=\"incomplete-error-checking-ndx1\">Incomplete error checking</h1>\n<p><code>process()</code> is checking the state of the input string right at the start of the function, but then ignores any errors that might happen later on. What you should do is check that <code>input.eof()</code> is <code>true</code> after the <code>while</code>-loop; you can even omit the check at the start.</p>\n<h1 id=\"return-the-raw-hash-value-g21d\">Return the raw hash value</h1>\n<p><code>process()</code> calculates the hash <em>and</em> converts it to a hexadecimal string. But what if I just want to convert two hash values, which can be done more efficiently if they were just in the original binary encoding? Or what if I need the hash in base64 format? I would apply the <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a> design principle, and just let <code>process()</code> return a <code>std::vector<unsigned char></code> (even better, use <a href=\"https://en.cppreference.com/w/cpp/types/byte\" rel=\"nofollow noreferrer\"><code>std::byte</code></a> instead of <code>unsigned char</code>). Let the caller worry about converting it to other representations if so desired.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:33:51.250",
"Id": "522038",
"Score": "0",
"body": "Thank you for your input! I will update my code base and the code of my post to reflect your recommendations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:54:29.533",
"Id": "522040",
"Score": "0",
"body": "@g-sliepen I forgot to ask, when you state to check `input.eof()` after the while loop, would it also be correct to replace `while (input.good())` with `while (!input.eof())` instead of checking for `input.eof()` after while?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:07:22.480",
"Id": "522042",
"Score": "1",
"body": "@JasonPena No, because you might encounter an error before reaching the end of the file. The `while`-loop should just check if it makes sense to try to `read()` some more, after the loop you check whether you have really read all of the input. Also: don't edit your post, if you want updated code to be reviewed, just create a new question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:11:22.037",
"Id": "522043",
"Score": "1",
"body": "@g-sliepen Okay, so I check for `input.eof()` after the while loop and throw if it is not true as a replacement for the original sanity check at the start of `process()`. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T09:56:08.367",
"Id": "264315",
"ParentId": "264299",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "264315",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-22T22:49:58.477",
"Id": "264299",
"Score": "4",
"Tags": [
"c++",
"c++17",
"cryptography",
"openssl"
],
"Title": "Cryptographic hashing class using OpenSSL's EVP interface"
}
|
264299
|
<p>I started making a game in curses, but I feel like I am displaying the map inefficiently and ineffectively.</p>
<p>Here's the code (only the relevant parts):</p>
<pre><code>import curses
world_map = [
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000011111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000011111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000011111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000111111111111111111110000000000000000000000000000000001111111111111111111111111000000000000000000000000000',
'00000000000000000111111111111111111111000000000000000000000000000001111111111111111111111111000000000000000000000000000',
'00000000000000000011111111111111111000000000000000000000000000000001111133333111111111111111000000000000000000000000000',
'00000000000000000000011111111111100000000000000000000000000000000001111133333111111111111111000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000011111111111111111133333111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000011111111111111111133333111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000011111111111111111111111111111111222211000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111000000000000000000000000000',
'00000000000000001111111111111111111111111000000000000011111111111110000000000000000000000000000000000000000000000000000',
'00000000000000001111111111111111111111111000000000000011111111111110000000000000000000000000000000000000000000000000000',
'00000000000000001114444411111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000001111111111111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000001111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000']
def win(stdscr):
curses.init_color(255, 0, 0x64 * 1000 // 0xff, 0)
curses.init_color(254, 0xff * 1000 // 0xff, 0xff * 1000 // 0xff, 0xff * 1000 // 0xff)
curses.init_color(253, 0x82 * 1000 // 0xff, 0x8c * 1000 // 0xff, 0x51 * 1000 // 0xff)
curses.init_color(252, 0xff * 1000 // 0xff, 0xe4 * 1000 // 0xff, 0xb5 * 1000 // 0xff)
curses.init_color(251, 0xc0 * 1000 // 0xff, 0xc0 * 1000 // 0xff, 0xc0 * 1000 // 0xff)
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLUE) # water
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_GREEN) # grass
curses.init_pair(3, curses.COLOR_RED, 255) # trees
curses.init_pair(4, curses.COLOR_RED, 254) # mountains
curses.init_pair(5, curses.COLOR_RED, 253) # swamp
curses.init_pair(6, curses.COLOR_RED, 252) # desert
curses.init_pair(7, curses.COLOR_RED, 251) # village
colors = [curses.color_pair(1), curses.color_pair(2), curses.color_pair(3), curses.color_pair(4), curses.color_pair(5), curses.color_pair(6), curses.color_pair(7)]
while True:
for i in range(30):
for j in range(119):
stdscr.addch(i, j, ' ', colors[int(world_map[i][j])])
stdscr.refresh()
def main():
curses.wrapper(win)
if __name__ == '__main__':
main()
</code></pre>
<p>Running this produces this window:
<a href="https://i.stack.imgur.com/gnX1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gnX1t.png" alt="enter image description here" /></a>
(if you couldn't tell it's just a test)</p>
<p>Is there a better way I could be doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T09:16:40.263",
"Id": "521995",
"Score": "0",
"body": "If the water is the char that appears the most you can first fill the screen with it and than color only the things that are not water. You can also compare the prev frame to the curr frame and color only the differences, it might seem slow but actually most of the time here is wasted on IO and coloring operations."
}
] |
[
{
"body": "<p>Here's a slight refactoring of your code to improve readability and reduce repetitiveness. (I don't think anything I'm doing here will do much for you in terms of performance, sadly.)</p>\n<pre><code>import curses as c\nfrom itertools import product \n\nworld_map = [\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000011111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000011111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000011111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000111111111111111111110000000000000000000000000000000001111111111111111111111111000000000000000000000000000',\n '00000000000000000111111111111111111111000000000000000000000000000001111111111111111111111111000000000000000000000000000',\n '00000000000000000011111111111111111000000000000000000000000000000001111133333111111111111111000000000000000000000000000',\n '00000000000000000000011111111111100000000000000000000000000000000001111133333111111111111111000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000001111133333111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000011111111111111111133333111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000011111111111111111133333111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000011111111111111111111111111111111222211000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111000000000000000000000000000',\n '00000000000000001111111111111111111111111000000000000011111111111110000000000000000000000000000000000000000000000000000',\n '00000000000000001111111111111111111111111000000000000011111111111110000000000000000000000000000000000000000000000000000',\n '00000000000000001114444411111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000001114444411111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000001111111111111115555555111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000001111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',\n '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\n]\n\n\ncolors_for_initialising = [\n (n, *((i * 1000 // 0xff) for i in rgb))\n for n, *rgb in (\n (255, 0, 0x64, 0),\n (254, 0xff, 0xff, 0xff),\n (253, 0x82, 0x8c, 0x51),\n (252, 0xff, 0xe4, 0xb5),\n (251, 0xc0, 0xc0, 0xc0)\n )\n]\n\nRED, BLUE, GREEN = c.COLOR_RED, c.COLOR_BLUE, c.COLOR_GREEN\n\ncolor_pairs = (\n (1, RED, BLUE), # water\n (2, RED, GREEN), # grass\n (3, RED, 255), # trees\n (4, RED, 254), # mountains\n (5, RED, 253), # swamp\n (6, RED, 252), # desert\n (7, RED, 251) # village\n)\n\n\ndef win(stdscr):\n for color in colors_for_initialising:\n c.init_color(*color)\n\n for color_pair in color_pairs:\n c.init_pair(*color_pair)\n\n colors = [c.color_pair(i) for i in range(1, 8)]\n \n while True:\n for i, j in product(range(30), range(119)):\n stdscr.addch(i, j, ' ', colors[int(world_map[i][j])])\n stdscr.refresh()\n\n\ndef main():\n c.wrapper(win)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Summary of the changes I've made here:</p>\n<ul>\n<li>Introduced an alias for <code>curses</code> (<code>c</code>) to make the code more concise. You can debate whether this change makes the code more or less readable — when you're using a module heavily, such as in this example, I generally prefer to use a shorter alias rather than having to type out the whole module name each time.</li>\n<li>Also introduced aliases for <code>curses.COLOR_RED</code>, <code>curses.COLOR_BLUE</code> and <code>curses.COLOR_GREEN</code> later on in the code, for the same reason. Out of these three, only <code>curses.COLOR_RED</code> was used more than once, but I introduced aliases for the other two as well so as to keep the naming of colors consistent.</li>\n<li>In your <code>win</code> function, you were calling <code>curses.init_color</code> and <code>curses.init_pair</code> repeatedly, which led to some repetitive code. I took the arguments for these calls out of <code>win</code> and put them into the global namespace, then abstracted your series of calls to <code>init_color</code> and <code>init_pair</code> into two for-loops in <code>win</code>.</li>\n<li>I changed your <code>colors</code> list in <code>win</code> from a list-literal to a list-comprehension, making the code less repetitive, more concise and more readable.</li>\n<li>I took out your nested for-loop in <code>win</code> and replaced it with a call to <code>itertools.product</code>, which does the same thing but is more concise and (arguably) more readable.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:46:37.543",
"Id": "264313",
"ParentId": "264300",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T01:55:13.830",
"Id": "264300",
"Score": "3",
"Tags": [
"python",
"curses"
],
"Title": "Displaying a \"map\" with curses and python"
}
|
264300
|
<p>We wrote a code that parallelizes the divide phase of the mergesort algorithm. I.e. every recursive call is assigned to a thread but our teacher was disappointed because he said we should also parallelize the merge function. I have researched how one can do this and I found these (algorithm 3) <a href="https://stanford.edu/%7Erezab/classes/cme323/S16/notes/Lecture03/cme323_lec3.pdf" rel="nofollow noreferrer">lecture notes</a> which changes the complexity of the merge function from O(n) to O(n(log(n)) but which one can now parallelize. I wanted to ask for suggestions how to design the code for the fastest result possible:</p>
<p>(both should compile with g++ /there might be some warnings if one uses pedantic flag but since both yield the correct result one could ignore them)</p>
<p>Old code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <omp.h>
// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1
const int CUTOFF =11;
#endif
/**
* helper routine: check if array is sorted correctly
*/
bool isSorted(int ref[], int data[], const size_t size){
std::sort(ref, ref + size);
for (size_t idx = 0; idx < size; ++idx){
if (ref[idx] != data[idx]) {
return false;
}
}
return true;
}
/**
* sequential merge step (straight-forward implementation)
*/
void MsMergeSequential(int *out, int *in, long begin1, long end1, long begin2, long end2, long outBegin) {
long left = begin1;
long right = begin2;
long idx = outBegin;
while (left < end1 && right < end2) {
if (in[left] <= in[right]) {
out[idx] = in[left];
left++;
} else {
out[idx] = in[right];
right++;
}
idx++;
}
while (left < end1) {
out[idx] = in[left];
left++, idx++;
}
while (right < end2) {
out[idx] = in[right];
right++, idx++;
}
}
bool myfunc (long i , long j){return (i<j);}
/**
* sequential MergeSort
*/
void MsSequential(int *array, int *tmp, bool inplace, long begin, long end) {
if( end <= begin + CUTOFF -1){
std::sort(array+begin,array + end, myfunc);
}
else if (begin < (end - 1)) {
long half =(begin+end) / 2;
#pragma omp taskgroup
{
#pragma omp task shared(array) untied if(end-begin >= (1<<15))
MsSequential(array, tmp, !inplace, begin, half);
MsSequential(array, tmp, !inplace, half, end);
}
if (inplace){
MsMergeSequential(array, tmp, begin, half, half, end, begin);
} else {
MsMergeSequential(tmp, array, begin, half, half, end, begin);
}
} else if (!inplace) {
tmp[begin] = array[begin];
}
}
/**
* Serial MergeSort
*/
void MsSerial(int *array, int *tmp, const size_t size) {
MsSequential(array, tmp, true, 0, size);
}
/**
/**
* @brief program entry point
*/
int main(int argc, char* argv[]) {
// variables to measure the elapsed time
struct timeval t1, t2;
double etime;
// expect one command line arguments: array size
if (argc != 2) {
printf("Usage: MergeSort.exe <array size> \n");
printf("\n");
return EXIT_FAILURE;
}
else {
const size_t stSize = strtol(argv[1], NULL, 10);
int *data = (int*) malloc(stSize * sizeof(int));
int *tmp = (int*) malloc(stSize * sizeof(int));
int *ref = (int*) malloc(stSize * sizeof(int));
printf("Initialization...\n");
srand(95);
#pragma omp parallel for num_threads(100) schedule(static)
for (size_t idx = 0; idx < stSize; ++idx){
data[idx] = (int) (stSize * (double(rand()) / RAND_MAX));
}
std::copy(data, data + stSize, ref);
double dSize = (stSize * sizeof(int)) / 1024 / 1024;
printf("Sorting %zu elements of type int (%f MiB)...\n", stSize, dSize);
gettimeofday(&t1, NULL);
#pragma omp parallel num_threads(80)
{
#pragma omp single
{
MsSerial(data, tmp, stSize);
}
}
gettimeofday(&t2, NULL);
etime = (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000;
etime = etime / 1000;
printf("done, took %f sec. Verification...", etime);
if (isSorted(ref, data, stSize)) {
printf(" successful.\n");
}
else {
printf(" FAILED.\n");
}
free(data);
//delete[] data;
free(tmp);
//delete[] tmp;
free(ref);
//delete[] ref;
}
return EXIT_SUCCESS;
}
</code></pre>
<p>New code - merge is parallelizable:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <omp.h>
// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1
#endif
//Takes a sorted list of size n and a value, puts the value in one of n+1 possible positions,
//if value is same to an element of the list take the position before the first occurence of the same element
int binarysearchfindlowerrank(int *in,int n,int value,int projection){
int* array= in+projection;
int L=0;
int R=n;
while(R-L>1){
int middle = (R+L)/2;
if(array[middle]==value){
while(array[middle]==value&&middle>0){
middle=middle-1;
}
if(middle==0&&array[middle]>=value){
return 0;
}
else{
return middle+1;
}
}
if(array[middle]<value){
L=middle;
}
if(array[middle]>value){
R=middle;
}
}
if(n==1){
if(array[0]>=value){
return 0;
}
else return 1;
}
if(L==0&&array[L]>value){
return 0;
}
if(R==n && array[R-1]< value){
return n;
}
if(R==n&& array[R-1]>=value){
return R-1;
}
if(array[R]<value){
return R+1;
}
if(array[L]<value){
return R;
}
return L;
}
//Takes a sorted list of size n and a value, puts the value in one of n+1 possible positions,
//if value is same to an element of the list take the position after the last occurence of the same element
int binarysearchfinduperrank(int *in,int n,int value, int projection){
int* array= in+projection;
int L=0;
int R=n;
while(R-L>1){
int middle = (R+L)/2;
if(array[middle]==value){
while(array[middle]==value&&middle<n){
middle=middle+1;
}
return middle;
}
if(array[middle]<value){
L=middle;
}
if(array[middle]>value){
R=middle;
}
}
if(n==1){
if(array[0]> value){
return 0;
}
else{
return 1;
}
}
if(L==0&&array[L]>value){
return 0;
}
if(R==n && array[R-1]<= value){
return n;
}
if(R==n&& array[R-1]>value){
return R-1;
}
if(array[R]<=value){
return R+1;
}
if(array[L]<=value){
return R;
}
return L;
}
/**
* helper routine: check if array is sorted correctly
*/
bool isSorted(int ref[], int data[], const size_t size){
std::sort(ref, ref + size);
for (size_t idx = 0; idx < size; ++idx){
if (ref[idx] != data[idx]) {
printf("\nFalscher Index:%d\n",idx);
return false;
}
}
return true;
}
/**
* sequential merge step (straight-forward implementation)
*/
void MsMergeParallelized(int *out, int *in, long begin1, long end1, long begin2, long end2, long outBegin,int *data,int *tmp) {
if(begin1==end2){
out[begin1]=in[begin1];
}
if(begin1==begin2||begin2==end2){
out[begin1+binarysearchfinduperrank(in,1,in[end2],begin1)]=in[end2];
out[begin1+binarysearchfindlowerrank(in,1,in[begin1],end2)]=in[begin1];
}
else{
for(int i=0;i<(end2-begin2);i++){
out[begin1+i+binarysearchfinduperrank(in,(end1-begin1),in[begin2+i],begin1)]=in[begin2+i];
}
for(int i=0;i<(end1-begin1);i++){
out[begin1+i+binarysearchfindlowerrank(in,(end2-begin2),in[begin1+i],begin2)]=in[begin1+i];
}
}
}
bool myfunc (long i , long j){return (i<j);}
/**
* sequential MergeSort
*/
void MsParallelized(int *array, int *tmp, bool inplace, long begin, long end) {
if (begin < (end - 1)) {
long half =(begin+end) / 2;
MsParallelized(array, tmp, !inplace, begin, half);
MsParallelized(array, tmp, !inplace, half, end);
if (inplace){
MsMergeParallelized(array, tmp, begin, half, half, end, begin,array,tmp);
}
else {
MsMergeParallelized(tmp, array, begin, half, half, end, begin,array,tmp);
}
}
else if (!inplace) {
tmp[begin] = array[begin];
}
}
/**
* Serial MergeSort
*/
void MsParallel(int *array, int *tmp, const size_t size) {
MsParallelized(array, tmp, true, 0, size);
}
/**
/**
* @brief program entry point
*/
int main(int argc, char* argv[]) {
// variables to measure the elapsed time
struct timeval t1, t2;
double etime;
// expect one command line arguments: array size
if (argc != 2) {
printf("Usage: MergeSort.exe <array size> \n");
printf("\n");
return EXIT_FAILURE;
}
else {
const size_t stSize = strtol(argv[1], NULL, 10);
int *data = (int*) malloc(stSize * sizeof(int));
int *tmp = (int*) malloc(stSize * sizeof(int));
int *ref = (int*) malloc(stSize * sizeof(int));
printf("Initialization...\n");
srand(95);
for (size_t idx = 0; idx < stSize; ++idx){
data[idx] = (int) (stSize * (double(rand()) / RAND_MAX));
}
std::copy(data, data + stSize, ref);
double dSize = (stSize * sizeof(int)) / 1024 / 1024;
printf("Sorting %u elements of type int (%f MiB)...\n", stSize, dSize);
gettimeofday(&t1, NULL);
// Mergesort starts
MsParallel(data, tmp, stSize);
gettimeofday(&t2, NULL);
etime = (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000;
etime = etime / 1000;
printf("done, took %f sec. Verification...", etime);
if (isSorted(ref, data, stSize)) {
printf(" successful.\n");
}
else {
printf(" FAILED.\n");
}
free(data);
//delete[] data;
free(tmp);
//delete[] tmp;
free(ref);
//delete[] ref;
}
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>/**\n * helper routine: check if array is sorted correctly\n */\nbool isSorted(int ref[], int data[], const size_t size){\n</code></pre>\n<p>Review the standard library to be familiar with what all is in it. Specifically, look at <a href=\"https://en.cppreference.com/w/cpp/algorithm#Sorting_operations\" rel=\"nofollow noreferrer\">sorting operations</a> where you'll find the standard algorithm <code>is_sorted</code>. Don't re-implement standard library contents that's not directly part of the exercise!</p>\n<p>As for your implementation...<br />\nThe <code>int ref[]</code> syntax in a parameter actually means <code>int*</code>. You should avoid the faux array syntax. But more seriously, there are two "arrays" passed and they are <em>not</em> marked <code>const</code>?</p>\n<p>The first line is a call to <code>std::sort</code> ????<br />\nSo, it appears it wants you to make a copy of the data, pass both copies, then this function sorts one of the copies and checks to see if the two copies are now the same (manually re-implementing <code>std::equals</code>).</p>\n<p>It is generally true that you can check your "fancy" version of a function by comparing the results against the "normal" version. But in this case, checking to see if the array is sorted is much more straightforward, and what the name of the function implies.</p>\n<pre><code>int *data = (int*) malloc(stSize * sizeof(int));\nint *tmp = (int*) malloc(stSize * sizeof(int)); \nint *ref = (int*) malloc(stSize * sizeof(int));\nprintf("Initialization...\\n");\n</code></pre>\n<p>Why are you using <code>malloc</code> (and <code>printf</code>)?</p>\n<pre><code>data[idx] = (int) (stSize * (double(rand()) / RAND_MAX));\n</code></pre>\n<p>One might be more forgiving of <code>rand()</code> since we don't need particularly high-quality randomness here; but you are doing all the conditioning work and explicit casting to get a random <code>int</code>. Use the C++ random number library, and <em>simply</em> ask it for random integers in the desired range.</p>\n<p>Note that C++ has a <strong>time</strong> library, also. You seem to be using C, not C++, except for calling <code>std::sort</code> and <code>std::copy</code>.</p>\n<p>The other call to <code>sort</code>, I see, is:</p>\n<pre><code>bool myfunc (long i , long j){return (i<j);}\n ...\nstd::sort(array+begin,array + end, myfunc);\n</code></pre>\n<p>Passing in <code>myfunc</code> is slowing it down. Simple ascending via <code><</code> is the default, so you don't need to pass this at all. But had you actually needed to supply a comparison function, a pointer to a plain function is de-optimizing because the optimizer generally doesn't follow pointers to functions even when they are known at compile time. That is, the call to <code>myfunc</code> won't be inlined.</p>\n<p>Your function takes <code>long</code> when you are sorting <code>int</code>. The function this appears in is declaring <code>begin</code> and <code>end</code> as <code>long</code>, rather than <code>size_t</code>. It's like you spliced in parts from different programs, or forgot what types you were using.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:21:32.920",
"Id": "264323",
"ParentId": "264301",
"Score": "0"
}
},
{
"body": "<blockquote>\n<p>changes the complexity of the merge function from O(n) to O(n(log(n)) but which one can now parallelize</p>\n</blockquote>\n<p>For a merge of two sorted runs of size n, worst case for each instance of a binary search is ⌈log2(n)⌉ reads, and for larger n (>=256 or so), this will result in the parallelized binary search merge being slower than a single threaded conventional merge.</p>\n<p>A faster approach for <em>t</em> threads would be to split up the array into <em>t</em> parts, and use <em>t</em> threads to independently sort each of the <em>t</em> parts. Then merge even and odd pairs of sorted runs, the first merge using <em>t</em>/2 threads, the next merge using <em>t</em>/4 threads, and finally a single thread to merge two sorted runs. An example of this using Windows native threads is shown in this question:</p>\n<p><a href=\"https://codereview.stackexchange.com/questions/148025/multithreaded-bottom-up-merge-sort\">Multithreaded bottom up merge sort</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:49:05.497",
"Id": "522039",
"Score": "0",
"body": "The target arraysize is between 10^7 and 10^8. That means one could achieve a speed up if one merges the last array for example in parallel. We have 240 threads available. log(10^8)<27. Virtually we only have to make 27/240 10^8 =1.125 10^7 operations as opposed to 10^8 operations. So there must be a speed up if we could run the parallel code only on the first subarrays"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:02:56.350",
"Id": "522041",
"Score": "0",
"body": "@New2Math - what system can run 240 threads at the same time? I thought this was a desktop PC. The max for these is 16 to 18 cores, with double the number of threads with hyper-threading, but each pair of hyper-threads would be sharing each cores local cache. My guess is that around 12 threads on 12 cores, the process will become memory bandwidth limited, in which case more threads will not help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:45:27.527",
"Id": "522046",
"Score": "0",
"body": "we use a hpc node for an university project"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T23:08:20.677",
"Id": "522058",
"Score": "0",
"body": "@New2Math - Even with the hpc node, I suspect the program will become memory and|or cache coherency bound at well less than 240 threads, since all are writing to the same array. Worst case scenario (binary search) is probably if when data is already sorted or reverse sorted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:37:56.573",
"Id": "264324",
"ParentId": "264301",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T02:01:42.307",
"Id": "264301",
"Score": "1",
"Tags": [
"c++",
"mergesort",
"openmp"
],
"Title": "Parallezing merge step and divide step in mergesort algorithm with OpenMP"
}
|
264301
|
<p>I want to refactor this code to a better version without all this repetition, this code is working 100% the way it is right now but every refactoring effort is making it useless, any idea or can this be considered the maximum ?</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>let div = document.querySelector('.results')
if (results < 0) {
let item = `<div class="center"><p class="statmentminus">bad!</p></div>`
if (div.parentElement.querySelector('.statmentplus')) {
let toRemove = div.parentElement.querySelector('.statmentplus')
toRemove.remove()
}
if (div.parentElement.querySelector('.statmentminus')) return
div.insertAdjacentHTML("afterend", item)
}
if (results > 0) {
let item = `<div class="center"><p class="statmentplus">good!</p></div>`
if (afterDiv.parentElement.querySelector('.statmentminus')) {
let toRemove = div.parentElement.querySelector('.statmentminus')
toRemove.remove()
}
if (afterDiv.parentElement.querySelector('.statmentplus')) return
div.insertAdjacentHTML("afterend", item)
}</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:33:16.243",
"Id": "522044",
"Score": "1",
"body": "So that we can advise you properly, please provide context so that we can understand what this code accomplishes."
}
] |
[
{
"body": "<h2 id=\"reducing-source-complexity-8q1j\">Reducing source complexity</h2>\n<p>There is a rule in coding, <em>"If it works leave it alone!"</em></p>\n<p>However when developing code you should aim for simplicity in code, that includes keeping code D.R.Y. (Don't Repeat Yourself).</p>\n<p>Its way to late to write good code if you need to change working code.</p>\n<h2 id=\"drying-out-your-code-zs6u\">Drying out your code</h2>\n<p>Suggestions to reduce complexity.</p>\n<ul>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Optional chaining\"><code>?.</code> (Optional chaining)</a> when calling functions. It lets you test if the result of a query is not <code>undefined</code>/<code>null</code> before calling the function.</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Conditional operator\"><code>?</code> (Conditional operator)</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Destructuring assignment\">Destructuring assignment</a> to simplify assignments. This lets you assign to constants based on a condition which is not possible using if statements.</p>\n<p>In this case the condition is <code>result</code> is negative or not.</p>\n<p>Or with just the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Conditional operator\"><code>?</code> (Conditional operator)</a> you can select a item based on a condition.</p>\n<p>See rewrites...</p>\n</li>\n<li><p>Store repeated literals as constants <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> .</p>\n</li>\n</ul>\n<h2 id=\"rewrite-lbdh\">Rewrite</h2>\n<p>The code you provided is lacking some context meaning the rewrite must make some guesses.</p>\n<ul>\n<li><p>What is <code>result</code>? What possible values can it have? It is assumed that it is always a number. That its value is never 0</p>\n</li>\n<li><p>There are <code>return</code>s yet no function has been defined. It is unclear where other returns should be. It is assumed to be at the end.</p>\n</li>\n</ul>\n<p>Because of these points I did not check the following rewrites for syntax or correctness. They are examples of how, they are not solutions</p>\n<pre><code>const div = document.querySelector('.results'), par = div.parentElement;\nconst cn = [".statmentplus", ".statmentminus"];\nconst [remove, ignore, text] = result > 0 ? [cn[1], cn[0], "Good!"] : [cn[0], cn[1], "bad!"];\npar.querySelector(remove)?.remove();\nif (!par.querySelector(ignore)) { \n div.insertAdjacentHTML("afterend", \n `<div class="center"><p class="statmentminus">${text}</p></div>`);\n}\n</code></pre>\n<p>Or</p>\n<pre><code>const CLASS_NAMES = [".statmentplus", ".statmentminus"];\nconst div = document.querySelector('.results');\nconst [good, par] = [result > 0, div.parentElement];\npar.querySelector(CLASS_NAMES[good ? 1 : 0])?.remove();\nif (!par.querySelector(CLASS_NAMES[good ? 0 : 1])) { \n div.insertAdjacentHTML("afterend", \n `<div class="center"><p class="statmentminus">${good ? "GOOD" : "BAD"}</p></div>`);\n}\n</code></pre>\n<p>Or</p>\n<pre><code>const [CLASS_NAMES, REPLYS] = [[".statmentplus", ".statmentminus"], ["BAD", "GOOD"]];\nconst div = document.querySelector('.results'), par = div.parentElement;\nconst good = result > 0 ? 1 : 0;\npar.querySelector(CLASS_NAMES[good])?.remove();\n!par.querySelector(CLASS_NAMES[good ? 0 : 1]) && div.insertAdjacentHTML("afterend", \n `<div class="center"><p class="statmentminus">${REPLYS[good]}</p></div>`);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T05:42:58.370",
"Id": "264308",
"ParentId": "264302",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264308",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T02:59:40.640",
"Id": "264302",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "refactor multi if statements and checking for div existence in a better style"
}
|
264302
|
<h2 id="question">QUESTION:</h2>
<p>You will set up simultaneous thumb wrestling matches. In each match, two trainers will pair off to thumb wrestle. The trainer with fewer bananas will bet all their bananas, and the other trainer will match the bet. The winner will receive all of the bet bananas. You don't pair off trainers with the same number of bananas (you will see why, shortly). You know enough trainer psychology to know that the one who has more bananas always gets over-confident and loses. Once a match begins, the pair of trainers will continue to thumb wrestle and exchange bananas, until both of them have the same number of bananas. Once that happens, both of them will lose interest and go back to supervising the bunny workers, and you don't want THAT to happen!</p>
<p>For example, if the two trainers that were paired started with 3 and 5 bananas, after the first round of thumb wrestling they will have 6 and 2 (the one with 3 bananas wins and gets 3 bananas from the loser). After the second round, they will have 4 and 4 (the one with 6 bananas loses 2 bananas). At that point they stop and get back to training bunnies.</p>
<p>How is all this useful to distract the bunny trainers? Notice that if the trainers had started with 1 and 4 bananas, then they keep thumb wrestling! 1, 4 -> 2, 3 -> 4, 1 -> 3, 2 -> 1, 4 and so on.</p>
<p>Now your plan is clear. You must pair up the trainers in such a way that the maximum number of trainers go into an infinite thumb wrestling loop!</p>
<p>Write a function solution(banana_list) which, given a list of positive integers depicting the amount of bananas the each trainer starts with, returns the fewest possible number of bunny trainers that will be left to watch the workers. Element i of the list will be the number of bananas that trainer i (counting from 0) starts with.</p>
<p>The number of trainers will be at least 1 and not more than 100, and the number of bananas each trainer starts with will be a positive integer no more than 1073741823 (i.e. 2^30 -1). Some of them stockpile a LOT of bananas.</p>
<p>-- Java cases --</p>
<p>Input:
solution.solution(1,1)</p>
<p>Output:
2</p>
<p>Input:
Solution.solution([1, 7, 3, 21, 13, 19])</p>
<p>Output:
0</p>
<h2 id="my-approach">My approach:</h2>
<p>Check the GCD of the pair. For repeating loops the GCD never changes. For terminating sequences the GCD doubles at each step. However there is a third kind of loop to consider. Some have a lead in sequence than doesn’t repeat but eventually turns into a looping sequence. For these the GCD will increase each step for the non repeating lead in part of the sequence, then will become static for the repeating section. So just testing the first and second step of a sequence will not be enough.</p>
<p>We can take this a step further however. If any of the GCDs divide the sum of the pair into a power of 2 then the loop is terminating.</p>
<h2 id="my-code">MY CODE:</h2>
<pre><code>public class Solution {
public static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
static boolean isPowerOfTwo(int n)
{
if(n==0)
return false;
return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
public static int countpairs(int[] b) {
int c=0;
for(int i=0;i<b.length;i++) {
for(int j=0;j<b.length;j++)
c++;
}
return c;
}
public static int solution(int[] banana_list) {
int[] b=banana_list;
int count=countpairs(b);
for(int i=0;i<b.length;i++) {
for(int j=0;j<b.length;j++) {
if(i==j) {}
else {
int s=(b[i]+b[j])/gcd(b[i],b[j]);
if(isPowerOfTwo(s)==true)
count--;
}
}
}
if(count>b.length)
return 0;
return count;
}
public static void main(String[] args) {
int a[]= {1,1};
System.out.println("Minimum trainers: "+solution(a));
}
}
</code></pre>
<p>This code passes 2/5 Test cases.
It fails in cases where there are odd number of trainers.
<a href="https://i.stack.imgur.com/ytM5R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ytM5R.png" alt="enter image description here" /></a></p>
|
[] |
[
{
"body": "<h3 id=\"recursion-is-good-only-if-you-know-its-depth-0fve\">Recursion is good only if you know its depth</h3>\n<p>If you have a tree with maximum depth of 100 or so - recursion is normal to traverse it. But here you can get a million steps of recursion for a stupid example of gcd(1,1000000). Change it to the loop.</p>\n<h3 id=\"gcd-can-be-calculated-faster-if-you-change-subtraction-with-modulo-xnc1\">GCD can be calculated faster if you change subtraction with modulo</h3>\n<p>Because (a-b)%b === (a%b)%b, gcd persists.</p>\n<h3 id=\"power-of-two-can-be-checked-with-bitwise-logic-4zaa\">Power of two can be checked with bitwise logic</h3>\n<p>You can try shifting right until the number is odd and check if it's 1, that's faster than your solution; but there's also a trick: <code>x&(x-1)==0</code> only for powers of 2.</p>\n<h3 id=\"countpairs-is-just-a-square-of-length-5h6d\"><code>countpairs</code> is just a square of length</h3>\n<p>You don't need to loop over an array to count its elements</p>\n<h3 id=\"algorithm-6x7j\">Algorithm</h3>\n<p>To find out if the numbers are tied, you don't need GCD at all. If both numbers are equal - they are tied. If one is even, other odd - the will be no tie. If both are odd - make them fight (i.e. recalculate them by the fight rules) and repeat. If both are even - divide them by two and repeat. This will be much faster then your's GCD.</p>\n<p>Also your pairing algorithm is flawed, check {1,1,1,2} - it should return 2, but it gives 0.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:44:21.183",
"Id": "522018",
"Score": "0",
"body": "I agree with the first three points. However, when you talk about the Algorithm, you mention that \"If both numbers are even - divide them by two. If one is even, other odd - the will be no termination.\" Won't even numbers always be even when divided by 2? That is the whole concept of odd and even! I might be understanding this wrongly, I'm sorry if I am. Can you please clarify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:46:03.673",
"Id": "522019",
"Score": "0",
"body": "My algorithm is pretty basic and it works most times. However, I've noticed that I have made a mistake in the counting part of the algorithm. i.e, counting, the number of trainers who cannot make an infinite loop. This is the part I cant figure out..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T07:27:21.830",
"Id": "522113",
"Score": "0",
"body": "Nevermind the \"algorithm\" part, I'll edit the answer and remove it when I'll have time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T08:30:39.670",
"Id": "264312",
"ParentId": "264310",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T06:54:18.720",
"Id": "264310",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Google Foobar - \"Distract the Trainers\""
}
|
264310
|
<h3 id="origin-code-hf1w">origin code:</h3>
<pre><code># add this class to make the code can be a reproducible example.In acutually environment all attribute could be True or False.
class Capabilities:
def __init__(self) -> None:
self.canEditCompany = True
self.canDeleteCompany = True
self.canShareCompany = True
self.canAddFiscal = True
self.canAddCategory = True
self.canEditCategory = True
self.canGetCategory = True
self.canAddAccount = True
self.canGetAccount = True
self.canEditAccount = True
self.canAddTransaction = True
self.canAddScan = True
self.canAddTax = True
def permission_control(user_email,company):
capabilities = Capabilities()
casbin_roles = []
if capabilities.canEditCompany:
casbin_roles.append((user_email, company, 'PUT'))
if capabilities.canDeleteCompany:
casbin_roles.append((user_email, company, 'Delete'))
if capabilities.canShareCompany:
casbin_roles.append((user_email, f'{company}/sharing', 'Post'))
if capabilities.canAddFiscal:
casbin_roles.append((user_email, f'{company}/fiscal_year', 'POST'))
if capabilities.canAddCategory:
casbin_roles.append((user_email, f'{company}/fiscals/*/categories', 'Post'))
if capabilities.canEditCategory:
casbin_roles.append((user_email, f'{company}/fiscals/*/categories/*', 'PUT'))
if capabilities.canGetCategory:
casbin_roles.append((user_email, f'{company}/fiscals/*/categories', 'GET'))
if capabilities.canAddAccount:
casbin_roles.append((user_email, f'{company}/fiscals/*/accounts', 'POST'))
if capabilities.canGetAccount:
casbin_roles.append((user_email, f'{company}/fiscals/*/accounts', 'GET'))
if capabilities.canEditAccount:
casbin_roles.append((user_email, f'{company}/fiscals/*/accounts/*', 'PUT'))
if capabilities.canAddAccount:
casbin_roles.append((user_email, f'{company}/fiscals/*/account', 'POST'))
if capabilities.canAddTax:
casbin_roles.append((user_email, f'{company}/tax', 'POST'))
if capabilities.canAddScan:
casbin_roles.append((user_email, f'{company}/scan', 'POST'))
if capabilities.canAddTransaction:
casbin_roles.append((user_email, f'{company}/accounts/*', 'POST'))
return casbin_roles
</code></pre>
<h3 id="my-try-4r53">my try:</h3>
<pre><code>import functools
def permission_control(user_email,company):
def partial(attribute_name):
return functools.partial(getattr,capabilities,attribute_name)
capabilities = Capabilities()
permissions = ["canEditCompany","canDeleteCompany","canShareCompany","canAddFiscal","canAddCategory","canEditCategory","canGetCategory","canAddAccount","canGetAccount","canEditAccount","canAddAccount","canAddTax","canAddScan","canAddTransaction"]
urls = [(company, 'PUT'),(company, 'Delete'),(f'{company}/sharing', 'Post'),(f'{company}/fiscal_year', 'POST'),(f'{company}/fiscals/*/categories', 'Post'),(f'{company}/fiscals/*/categories/*', 'PUT'),(f'{company}/fiscals/*/categories', 'GET'),(f'{company}/fiscals/*/accounts', 'POST'),(f'{company}/fiscals/*/accounts', 'GET'),(f'{company}/fiscals/*/accounts/*', 'PUT'),(f'{company}/fiscals/*/account', 'POST'),(f'{company}/tax', 'POST'),(f'{company}/scan', 'POST'),(f'{company}/accounts/*', 'POST')]
return [((user_email,) + url) for permission,url in zip(permissions,urls) if partial(permission)()]
</code></pre>
<h3 id="question-9jz1">question</h3>
<ul>
<li>Any better, more pythonic way to achieve it?</li>
<li>I think my code maybe even worse than the origin code, because it is hard to understand/maintain for my co-workers. Am I right?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:01:02.683",
"Id": "522013",
"Score": "0",
"body": "This doesn't have enough contextual information. What are you actually trying to do? Where do those boolean values come from - are they hard-coded, or set from process environment variables, or what? Is the class instance expected to be immutable or will those permissions change over the lifetime of the object?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:11:33.663",
"Id": "522023",
"Score": "0",
"body": "@Reinderien The boolean values come from database. The class instance should be immutable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:13:22.937",
"Id": "522024",
"Score": "0",
"body": "Please show the querying code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:15:30.317",
"Id": "522025",
"Score": "0",
"body": "@Reinderien sorry i made a mistake, The class instance should be immutable, I already edit."
}
] |
[
{
"body": "<p>I might be inclined to do something like this:</p>\n<pre><code>class Capabilities:\n def __init__(self) -> None:\n self.canEditCompany = True\n self.canDeleteCompany = True\n self.canShareCompany = True\n self.canAddFiscal = True\n self.canAddCategory = True\n self.canEditCategory = True\n self.canGetCategory = True\n self.canAddAccount = True\n self.canGetAccount = True\n self.canEditAccount = True\n self.canAddTransaction = True\n self.canAddScan = True\n self.canAddTax = True\n\n actions_dict = {\n "canEditCompany": lambda company: (company, 'PUT'),\n "canDeleteCompany": lambda company: (company, 'Delete'),\n "canShareCompany": lambda company: (f'{company}/sharing', 'Post'),\n "canAddFiscal": lambda company: (f'{company}/fiscal_year', 'POST'),\n "canAddCategory": lambda company: (f'{company}/fiscals/*/categories', 'Post'),\n "canEditCategory": lambda company: (f'{company}/fiscals/*/categories/*', 'PUT'),\n "canGetCategory": lambda company: (f'{company}/fiscals/*/categories', 'GET'),\n "canAddAccount": lambda company: (f'{company}/fiscals/*/accounts', 'POST'),\n "canGetAccount": lambda company: (f'{company}/fiscals/*/accounts', 'GET'),\n "canEditAccount": lambda company: (f'{company}/fiscals/*/accounts/*', 'PUT'),\n "canAddAccount": lambda company: (f'{company}/fiscals/*/account', 'POST'),\n "canAddTax": lambda company: (f'{company}/tax', 'POST'),\n "canAddScan": lambda company: (f'{company}/scan', 'POST'),\n "canAddTransaction": lambda company: (f'{company}/accounts/*', 'POST')\n}\n\n\ndef permission_control(user_email, company):\n capabilities = Capabilities()\n return [(user_email, *action(company)) for capability, action in actions_dict.items() if getattr(capabilities, capability)]\n</code></pre>\n<p>I agree that your code was in some ways less readable, but I think you were heading in the right direction by taking out that awful if-tree, which definitely counts as an anti-pattern in my opinion. I think keeping the input and the result together in a dictionary is much more readable than keeping them in two separate lists, as you had them — and by using <code>lambda</code> functions, we can construct the dict in the global namespace so it doesn't have to be made afresh every time the function is called, which is what your code was doing with your two lists.</p>\n<hr />\n<p>EDIT: Following a suggestion in the comments, an even better solution would be to use <code>format-strings</code> rather than <code>lambdas</code>:</p>\n<pre><code>class Capabilities:\n def __init__(self) -> None:\n self.canEditCompany = True\n self.canDeleteCompany = True\n self.canShareCompany = True\n self.canAddFiscal = True\n self.canAddCategory = True\n self.canEditCategory = True\n self.canGetCategory = True\n self.canAddAccount = True\n self.canGetAccount = True\n self.canEditAccount = True\n self.canAddTransaction = True\n self.canAddScan = True\n self.canAddTax = True\n\nactions_dict = {\n "canEditCompany": ('{}', 'PUT'),\n "canDeleteCompany": ('{}', 'Delete'),\n "canShareCompany": ('{}/sharing', 'Post'),\n "canAddFiscal": ('{}/fiscal_year', 'POST'),\n "canAddCategory": ('{}/fiscals/*/categories', 'Post'),\n "canEditCategory": ('{}/fiscals/*/categories/*', 'PUT'),\n "canGetCategory": ('{}/fiscals/*/categories', 'GET'),\n "canAddAccount": ('{}/fiscals/*/accounts', 'POST'),\n "canGetAccount": ('{}/fiscals/*/accounts', 'GET'),\n "canEditAccount": ('{}/fiscals/*/accounts/*', 'PUT'),\n "canAddAccount": ('{}/fiscals/*/account', 'POST'),\n "canAddTax": ('{}/tax', 'POST'),\n "canAddScan": ('{}/scan', 'POST'),\n "canAddTransaction": ('{}/accounts/*', 'POST')\n}\n\n\ndef permission_control(user_email, company):\n capabilities = Capabilities()\n\n return [\n (user_email, url.format(company), method)\n for capability, (url, method) in actions_dict.items() \n if getattr(capabilities, capability)\n ]\n</code></pre>\n<hr />\n<p>SECOND EDIT: As was pointed out in the comments, the answer with format strings could be improved even more by pre-binding the <code>format</code> method of the format strings. This is slightly more performant, and constrains the strings to a single purpose.</p>\n<p>I've also changed the data structure from a <code>str: tuple[str, str]</code> dictionary to a list of <code>NamedTuples</code>. A dictionary no longer made sense at this stage. NamedTuples aren't strictly necessary as opposed to tuples, but I think using them makes the intention of the code clearer and improves readability.</p>\n<pre><code>from typing import NamedTuple, Callable, Literal\n\nclass Capabilities:\n def __init__(self) -> None:\n self.canEditCompany = True\n self.canDeleteCompany = True\n self.canShareCompany = True\n self.canAddFiscal = True\n self.canAddCategory = True\n self.canEditCategory = True\n self.canGetCategory = True\n self.canAddAccount = True\n self.canGetAccount = True\n self.canEditAccount = True\n self.canAddTransaction = True\n self.canAddScan = True\n self.canAddTax = True\n\n\nclass CapabilityTuple(NamedTuple):\n capability: str\n url_factory: Callable[[str], str]\n\n # Any reason why some of these aren't all-uppercase in your question?\n # HTTP methods are usually all-uppercase\n method: Literal['PUT', 'Delete', 'POST', 'GET', 'Post'] \n\n\nactions_list = [\n CapabilityTuple(capability, url.format, method) for capability, url, method in (\n ("canEditCompany", '{}', 'PUT'),\n ("canDeleteCompany", '{}', 'Delete'),\n ("canShareCompany", '{}/sharing', 'Post'),\n ("canAddFiscal", '{}/fiscal_year', 'POST'),\n ("canAddCategory", '{}/fiscals/*/categories', 'Post'),\n ("canEditCategory", '{}/fiscals/*/categories/*', 'PUT'),\n ("canGetCategory", '{}/fiscals/*/categories', 'GET'),\n ("canAddAccount", '{}/fiscals/*/accounts', 'POST'),\n ("canGetAccount", '{}/fiscals/*/accounts', 'GET'),\n ("canEditAccount", '{}/fiscals/*/accounts/*', 'PUT'),\n ("canAddAccount", '{}/fiscals/*/account', 'POST'),\n ("canAddTax", '{}/tax', 'POST'),\n ("canAddScan", '{}/scan', 'POST'),\n ("canAddTransaction", '{}/accounts/*', 'POST')\n )\n]\n\n\ndef permission_control(user_email, company):\n capabilities = Capabilities()\n\n return [\n (user_email, url_factory(company), method)\n for capability, url_factory, method in actions_list\n if getattr(capabilities, capability)\n ]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:02:44.657",
"Id": "522014",
"Score": "1",
"body": "This is a useful answer. One alternative to consider: format strings, which can still be defined in advance, rather than lambdas, which are a bit heavier syntax-wise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:22:52.857",
"Id": "522016",
"Score": "0",
"body": "Oh, excellent idea! I've incorporated that into my answer — it makes it much cleaner"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:17:40.470",
"Id": "522027",
"Score": "0",
"body": "Bonus: pre-bind to the `.format` method of the format strings, to further constrain their purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:30:13.100",
"Id": "522028",
"Score": "0",
"body": "@Reinderien something like this? (Just using MyPy playground because it's convenient for code-sharing) https://mypy-play.net/?mypy=latest&python=3.10&gist=865b0c5f9e0a837bdecfd9a350e90fef"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:31:18.313",
"Id": "522029",
"Score": "1",
"body": "yep exactly. There will be a very very minor performance increase, but more importantly the string is constrained to only one purpose"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:34:43.447",
"Id": "522030",
"Score": "0",
"body": "Yeah, I like it, and would never have thought of it. Will edit it in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:57:44.470",
"Id": "522032",
"Score": "0",
"body": "The `Literal` is a good idea, but these are HTTP methods - you can stick with the upper-case strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:59:46.133",
"Id": "522033",
"Score": "0",
"body": "Yeah I know, was just sticking with the brief as it was provided in the question. Any reason why you went with frozen dataclasses rather than NamedTuples in your answer btw? I thought dataclasses were meant to be much less performant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T17:15:33.140",
"Id": "522034",
"Score": "1",
"body": "Quite honestly it's because I didn't know about the new(ish) `NamedTuple` inheritance-style definition. It's nice - thanks for showing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T17:21:20.287",
"Id": "522035",
"Score": "1",
"body": "Yeah I like it much more — allows for type hints, and also makes it easy to extend the class and add your own methods — e.g. https://github.com/willmcgugan/textual/blob/main/src/textual/geometry.py. Always feels weird to me that it's in the typing module rather than collections."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T12:26:06.610",
"Id": "264320",
"ParentId": "264318",
"Score": "7"
}
},
{
"body": "<p>I'd dumb it down a little: no lambdas, no partials, no formatting (you only have suffixes and nothing else). Make your HTTP methods all-caps for uniformity, and also you can use a generator instead of a list comprehension. For your <code>Capabilities</code> you can accept boolean kwargs. Pre-register all of the possible capabilities in a constant dictionary roughly similar to Alex's <code>actions_dict</code> but with stronger typing.</p>\n<p>Also note <code>permission_control</code> is a noun where method names should be verbs, i.e. <code>control_permissions</code> or, as I've proposed, <code>.evaluate()</code></p>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>from dataclasses import dataclass\nfrom typing import Tuple, Iterable\n\nCapTuple = Tuple[\n str, # email\n str, # URL path\n str, # method\n]\n\n\n@dataclass(frozen=True)\nclass Capability:\n name: str\n method: str\n path: str\n\n\nCAPABILITIES = {\n name: Capability(name, method, path)\n for name, method, path in (\n ("canEditCompany", 'PUT', ''),\n ("canDeleteCompany", 'DELETE', ''),\n ("canShareCompany", 'POST', '/sharing'),\n ("canAddFiscal", 'POST', '/fiscal_year'),\n ("canAddCategory", 'POST', '/fiscals/*/categories'),\n ("canEditCategory", 'PUT', '/fiscals/*/categories/*'),\n ("canGetCategory", 'GET', '/fiscals/*/categories'),\n ("canAddAccount", 'POST', '/fiscals/*/accounts'),\n ("canGetAccount", 'GET', '/fiscals/*/accounts'),\n ("canEditAccount", 'PUT', '/fiscals/*/accounts/*'),\n ("canAddAccount", 'POST', '/fiscals/*/account'),\n ("canAddTax", 'POST', '/tax'),\n ("canAddScan", 'POST', '/scan'),\n ("canAddTransaction", 'POST', '/accounts/*'),\n )\n}\n\n\nclass Capabilities:\n def __init__(self, **kwargs: bool):\n self.allowed: Tuple[Capability] = tuple(\n CAPABILITIES[name]\n for name, allowed in kwargs.items()\n if allowed\n )\n\n def evaluate(self, user_email: str, company: str) -> Iterable[CapTuple]:\n for cap in self.allowed:\n yield user_email, company + cap.path, cap.method\n\n\ndef test() -> None:\n caps = Capabilities(canAddAccount=True, canEditAccount=True, canDeleteCompany=False)\n for user_email, path, method in caps.evaluate('me@here.com', 'here_inc'):\n print(user_email, path, method)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:51:39.047",
"Id": "264331",
"ParentId": "264318",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "264331",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T10:25:14.547",
"Id": "264318",
"Score": "5",
"Tags": [
"python"
],
"Title": "Assigning permissions to multiple endpoints for a user and company"
}
|
264318
|
<p>I am looking for a simpler implementation of the following question.</p>
<p>Could it get better?</p>
<p>I am expecting the new solution via DFS again. Thanks.</p>
<p>OA: Given a 2d matrix with chars and a target string.</p>
<p>Check if the matrix contains this target string</p>
<p>by only going right or down each time from the beginning point.</p>
<pre><code>public class CharsIncludesString {
static char[][] matrix = { {'a', 'b', 'c', 'd'},
{'f', 'o', 'u', 'r'} ,
{'r', 'r', 'p', 'c'} ,
{'e', 'f', 'c', 'b'} ,
{'e', 'f', 'c', 'b'} };
static int ROW = matrix.length;
static int COLUMN = matrix[0].length;
public static void main(String[] args) {
CharsIncludesString charsIncludesString = new CharsIncludesString();
String str = "orscb";
System.out.println( charsIncludesString.checkStr(matrix, str) );
}
private boolean checkStr(char[][] matrix, String str) {
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[i].length;j++){
if(matrix[i][j] == str.toCharArray()[0]){
return dfs(matrix, i, j, str.substring(1));
}
}
}
return false;
}
static class Cell
{
public int row;
public int column;
public Cell(int row, int column)
{
this.row = row;
this.column = column;
}
}
private boolean dfs(char[][] matrix, int row, int column, String str) {
if(str.length() == 1)
return true;
char[] charArray = str.toCharArray();
Boolean[][] visited = new Boolean[ROW][COLUMN];
// Initialize a stack of pairs and
// push the starting cell into it
Stack<Cell> stack = new Stack<>();
stack.push(new Cell(row, column));
while (!stack.empty())
{
Cell curr = stack.pop();
row = curr.row;
column = curr.column;
System.out.print(matrix[row][column] + " ");
// Push all the adjacent cells
char c = charArray[0];
if(matrix[row+1][column] == c)
dfs(matrix, row +1, column, str.substring(1));
else if( matrix[row][column+1] == c){
dfs(matrix, row, column+1 , str.substring(1));
}else {
return false;
}
}
return true;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What I couldn't deduce from the problem description was the definition of "going right" in the last column (usually it means "go the first cell of the next row") but here it'd might just as well be "not allowed". Same question for "going down" by symmetry.</p>\n<p>I next tried to deduce the definition from the code, but noticed that indices <code>[column+1]</code> and <code>[row+1]</code> are not guarded. Unless your code is written in some highly niche language that does auto-wraps, I'd expect it to crash if the substring is not present.</p>\n<p>Variable <code>visited</code> is not used, and neither is variable <code>stack</code>. The latter seems to be, but all it experiences during its life is one push followed by one pop. The <code>while</code> always performs exactly 1 loop, so it has no purpose.</p>\n<p>The following part is just wrong:</p>\n<pre><code>if(matrix[row+1][column] == c)\n ...\nelse if( matrix[row][column+1] == c)\n ...\n</code></pre>\n<p>If the next row matches but turns out to fail, the next column might match but it's never investigated due to the <code>else</code>.</p>\n<p>However, the code can be rescued. If you strip out the useless variables and loop, fix the <code>else</code>-mistake, and handle the "last column/row"-cases, you'll end up with something that is both simpler and actually works.</p>\n<p>PS: It all seems strange though. Your code contains the right ingredients (apart from some silly mistakes),\nbut it also contains layers upon it that don't actually do anything. I can only imagine those layers to have been added afterwards.\nI rescued one down-vote of your question by up-voting it, since I don't expect smoke-screens to be intentional.\nHowever, if you don't respond to my answer, I'll assume it was after all and act accordingly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T11:14:26.613",
"Id": "264349",
"ParentId": "264319",
"Score": "-1"
}
},
{
"body": "<p>The code in your question has some good ideas towards a solution but does not solve the problem and mixes some concepts.</p>\n<p><strong>Concept issues</strong></p>\n<p>Not sure what the purpose of the stack is there. Usually stacks could be used to mimic call stack and avoid recursion, however the code in the question uses both.</p>\n<p>Focusing only on either "DSF with stack" or "DSF with recursion" would help you to the next step.</p>\n<p><strong>Bugs</strong></p>\n<p>The nested for loop returns on the first iteration, however, it only needs to return on the first true return value of the <code>dsf()</code> call.</p>\n<p><strong>Improvements</strong></p>\n<p>In case of a recursive solution there's no need for <code>class Cell</code>.</p>\n<p>The string passed on every <code>dsf()</code> call is copied each time it is not pooled by Java. This leads to a space complexity of <code>O(n^2)</code> where n is the length of the string. A better solution is to pass on an index.</p>\n<p>With the use of static methods <code>class CharsIncludesString</code> doesn't need to be instantiated.</p>\n<p><strong>Example code with the fixes from above:</strong></p>\n<pre><code>public class CharsIncludesString {\n\n static char[][] matrix = { {'a', 'b', 'c', 'd'},\n {'f', 'o', 'u', 'r'} ,\n {'r', 'r', 'p', 'c'} ,\n {'e', 'f', 'c', 'b'} ,\n {'e', 'f', 'c', 'b'} };\n\n public static void main(String[] args) {\n String str = "orpcb";\n\n System.out.println(checkStr(matrix, str));\n\n }\n\n public static boolean checkStr(char[][] matrix, String str) {\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[i].length; j++){\n if (dfs(matrix, i, j, str, 0)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n public static boolean dfs(char[][] matrix, int row, int column, String str, int strIndex) {\n // no more chars left in str\n if (strIndex >= str.length()) {\n return true;\n }\n\n // outside of the matrix\n // or the char at [row][column] mismatches with the next char in str\n if (row >= matrix.length || column >= matrix[0].length\n || str.charAt(strIndex) != matrix[row][column]) {\n return false;\n }\n\n // go right or down\n if (dfs(matrix, row + 1, column, str, strIndex + 1)\n || dfs(matrix, row, column + 1, str, strIndex + 1)) {\n return true;\n }\n\n return false;\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T10:34:55.077",
"Id": "268142",
"ParentId": "264319",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T11:35:27.533",
"Id": "264319",
"Score": "0",
"Tags": [
"java",
"matrix",
"depth-first-search"
],
"Title": "Given a 2d matrix with chars find the target string"
}
|
264319
|
<p>Based on a previous post, <a href="https://codereview.stackexchange.com/questions/263626/accelerating-creation-of-matrices-and-finding-ways-for-optimal-scaling">Accelerating creation of matrices and finding ways for optimal scaling</a>, we managed to accelerate the way that I construct a matrix in Rcpp (inputs for example are at the end of the post). The code used is the following:</p>
<pre><code>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
int NonDiagSum(arma::mat n, int K){
int sum = 0;
for(int i=0; i<(K+1); ++i){
sum += n(i,K-i);
}
return accu(n) - sum;
}
std::random_device rd;
std::mt19937 gen(rd());
// [[Rcpp::export]]
arma::mat Generate(arma::mat n, int K, double p){
std::bernoulli_distribution distrib(p);
int N = NonDiagSum(n,K);
NumericMatrix H(N,K);
int next = 0;
for(int j=0; j<K; ++j){
for(int i=0; i<(K-j); ++i){
for(int iter=0; iter<n(i,j); ++iter){
for(int k=j; k<(K-i); ++k){
H(iter+next,k) = distrib(gen);
}
}
next += n(i,j);
}
}
return H;
}
</code></pre>
<p>The main part of the code is the function <code>Generate()</code>, which produces a matrix with <code>N</code> rows and <code>K</code> columns and each cell can take the value <code>0</code> or <code>1</code>.</p>
<p>Because <code>0</code> and <code>1</code> are generated in a probabilistic way it is expected to have rows which are entirely of zero elements. My goal, is to remove those rows, in an efficient way.</p>
<p>I think the naive way to approach this problem, is to create an additional function that will calculate the row sum of the matrix produced by the <code>Generate()</code> function, and then create a second function that will remove the rows for which the sum is equal to zero, i.e. <code>row_sum[i]==0</code>. Those function are the following (I assume that those function have the least amount of complexity and cannot be further improved??):</p>
<pre><code>// [[Rcpp::export]]
arma::vec RowSum(arma::mat H, int K){
int N=size(H)[0];
arma::vec s(N);
s.zeros();
for(int i=0; i<N; ++i){
for(int k=0; k<K; ++k){
s[i] += H(i,k);
}
}
return s;
}
// [[Rcpp::export]]
arma::mat Extract(arma::mat H, int K){
arma::vec s = RowSum( H, K);
int idx = 0;
for(int i=0; i<size(s)[0]; ++i){
if(s[i]==0){
H.shed_row(i-idx);
idx += 1;
}
}
return H;
}
</code></pre>
<p>And I could use the <code>Extract()</code> function inside the <code>Generate()</code> function as</p>
<pre><code>// [[Rcpp::export]]
arma::mat Generate(arma::mat n, int K, double p){
... //Same as before
return Extract(H,K); //Use the Extract() function on the output matrix H
}
</code></pre>
<p>which will solve my problem, but it will burden the calculations enormously.</p>
<p>However, I believe that we do not trully need the <code>RowSum()</code> function as those operations are implemented already inside the <code>Generate()</code> function. Hence, the <code>Generate()</code> function which calculates also the row sums is the following:</p>
<pre><code>// [[Rcpp::export]]
arma::mat Generate(arma::mat n, int K, double p){
std::bernoulli_distribution distrib(p);
int N = NonDiagSum(n,K);
NumericMatrix H(N,K);
NumericVector row_sum(N);
int next = 0;
for(int j=0; j<K; ++j){
for(int i=0; i<(K-j); ++i){
for(int iter=0; iter<n(i,j); ++iter){
for(int k=j; k<(K-i); ++k){
H(iter+next,k) = distrib(gen);
row_sum(iter+next) += H(iter+next,k);
}
}
next += n(i,j);
}
}
return H;
}
</code></pre>
<p>Then ideally, there are I think two approaches to remove the rows which have zero sum. The first one is to find a way for the removing zero rows after the creation of each row, i.e. after the implamentation of the code part (in <code>Generate()</code> function)</p>
<pre><code>for(int k=j; k<(K-i); ++k){
H(iter+next,k) = distrib(gen);
row_sum(iter+next) += H(iter+next,k);
}
</code></pre>
<p>which personally I cannot find a way at the momment to do that.</p>
<p>The second approach is the following, inside the <code>Generate()</code> function instead of defining <code>H</code> as a <code>NumericMatrix</code> we could define it as <code>arma::mat</code> in order to use the row removing function <code>H.shed_row()</code> function. Based on that the new <code>Generate()</code> code could be</p>
<pre><code>// [[Rcpp::export]]
arma::mat Generate(arma::mat n, int K, double p){
...//Same as before, we construct the matrix H
//Here we remove the rows with zero row_sum
int idx=0;
for(int i=0; i<N; ++i){
if(s[i]==0){
H.shed_row(i-idx);
idx += 1;
}
}
return H;
}
</code></pre>
<p>I assume that the optimal way incorporates keeping the <code>H</code> matrix as <code>NumericMatrix</code> because it avoids the comands <code>arma::mat H</code> and <code>H.zeros()</code> and that the part that we remove the rows should be right after the implementation of the code part</p>
<pre><code>for(int k=j; k<(K-i); ++k){
H(iter+next,k) = distrib(gen);
row_sum(iter+next) += H(iter+next,k);
}
</code></pre>
<p>Sorry for the length of the post, I just wanted to give all the details. If any clarification or something more needed I'm willing to help. Any suggestion would be really helpful!</p>
<p>Potential inputs that can be used for examples are the following:</p>
<pre><code>p = 0.8
K=4
n = matrix(c(0,242,0,272,9222,0,10,0,123,0,0,0,0,0,0,0,131,0,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)
n
[,1] [,2] [,3] [,4] [,5]
[1,] 0 242 0 272 9222
[2,] 0 10 0 123 0
[3,] 0 0 0 0 0
[4,] 0 131 0 0 0
[5,] 0 0 0 0 0
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Code review is normally meant to review complete and working code, not for getting answers to questions like "how should I ...?" However, since you presented code for all the alternatives you've come up with, I'll review it.</p>\n<h1 id=\"avoid-doing-things-you-have-to-fix-up-later-tpvn\">Avoid doing things you have to fix up later</h1>\n<p>First creating rows which are all zeroes and then removing them is of course more work than not creating those rows at all. So if there is a cheap way to predict that a row will be filled with all zeroes, then we can use that to avoid the work. And there is: for a series of <span class=\"math-container\">\\$n\\$</span> boolean values, each with probability <span class=\"math-container\">\\$p\\$</span> to be 1, the chance of all of them being zero is <span class=\"math-container\">\\$(1 - p)^n\\$</span>. So naively thought, you could just check this first before adding a row:</p>\n<pre><code>std::bernouilly_distribution empty_row_distrib(std::pow(1 - p, K - i - j));\n\nfor (int iter=0; iter<n(i,j); ++iter) {\n if (empty_row_distrib(gen)) {\n /* skip row */\n } else {\n /* generate row */\n }\n}\n</code></pre>\n<p>But there are some problems with the above code. First, if we get to the part where we do generate a row, we still might produce a row of all zeroes. So we'd have to check for all zeroes anyway, and to ensure we still have the correct distribution in the end, we'd have to do another attempt at generating the row, until we get one that is not all zeroes. Also, we had to generate yet another random number and compare it. So there is an overhead, and I think this approach is only going to be faster if <code>p</code> is quite small.</p>\n<p>Otherwise, I would recommend the following:</p>\n<h1 id=\"overwrite-rows-instead-of-removing-them-jdc8\">Overwrite rows instead of removing them</h1>\n<p>After adding a row, check if it is all zeroes. If so, don't increment the row index, so the next iteration will just overwrite the same row. When you are at the end, just shrink the matrix using <a href=\"http://arma.sourceforge.net/docs.html#resize_member\" rel=\"nofollow noreferrer\"><code>arma::mat::resize()</code></a> to the number of actual rows written to.</p>\n<p>This is not so different from calling <code>shed_row()</code> on individual rows, but this way we just combine everything into a single operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T11:03:46.267",
"Id": "522077",
"Score": "0",
"body": "I'm sorry that the question was out of context. And thank you very much for the ideas really helped and improved the time speed of the algorithm!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T04:10:50.357",
"Id": "522111",
"Score": "0",
"body": "This is a beautiful answer because of the practical object lesson. The two headlines alone say it all, really. A programmer is so immersed in the mushrooming minute of progressive problem puzzling that they are blinkered to the possibility of blindingly obvious faulty presuppositions. In production code I've seen of that genre, it is hard to say if the author was too smart for our own good, the opposite of that, or paid per line of code. In Dilbert, the Elbonian contractors had a complete set of incompetencies."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T16:44:00.193",
"Id": "264330",
"ParentId": "264322",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264330",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T12:59:20.203",
"Id": "264322",
"Score": "0",
"Tags": [
"c++",
"performance",
"r",
"rcpp"
],
"Title": "An efficient way for removing rows with zero elements iteratively while constructing the matrix"
}
|
264322
|
<p>I started implementing the folowing Matrix class in order to get a better understanding of templates classes in general. For now, it lacks a lot of features, it does very basic things:</p>
<ul>
<li>addition</li>
<li>multiplication (only matrix X matrix multiplication is available here)</li>
<li>transpose</li>
<li>conversion to a string</li>
</ul>
<p>Here are some points i think might be interesting</p>
<ul>
<li><p>The dimensions of the matrices can either be "static" or "dynamic". By static, i mean the number of rows / columns is not allowed to change even if the data is stored in an std::vector</p>
</li>
<li><p>When adding two matrices together, the resulting matrix's dimension is static if at least one of the two operands is static.</p>
</li>
<li><p>When multiplying two matrices together, the resulting matrix's dimension depends on the rows of the left hand side and the columns of the right hand side of the "*".</p>
</li>
<li><p>The type of data contained in the returned matrix corresponds to the implicit cast of the types of the left and right sides of the expression. If the user decided to multiply a matrix of <em>Foos</em>, with a matrix of <em>Bars</em>, it's on him.</p>
</li>
<li><p>The "changeSize" methode, when called on a static matrix will only throw if the requested change is different from the matrix size.</p>
</li>
<li><p>I did not bother for now with the type of exception i used as this is more of an exercise than something that i will use in a real application.</p>
</li>
<li><p>The reason i made it possible to instanciate Static or dynamic matrices is because i want it to be able to manage Vector X Matrix operations. As a vector is just a special case of matrices, i choose to made them into a single class. (in the style of Eigen, which my code is inspired from a used inteface point of view).</p>
</li>
</ul>
<p>Is my use of the rvalues references and move semantics correct? (that is a notion i learned about last week, any advice can help)</p>
<p>What do you think could be improved about my code?</p>
<p>Is there any notion i should learn before continuing?</p>
<p>Were any design choices in terme of template parameters good or bad?</p>
<pre><code>#ifndef UTILS_MATRIX_H_
#define UTILS_MATRIX_H_
#include <vector>
#include <stdexcept>
#include <sstream>
#include <iomanip>
namespace mat
{
constexpr size_t DYNAMIC = static_cast<size_t>(-1); // [-] No matrix can be of this size... right?
template<typename TYPE, size_t NBROWS, size_t NBCOLS>
class Matrix
{
private:
std::vector<std::vector<TYPE>> matrixData; // [-] Contents of the Matrix as a 2D array
static constexpr bool isRowStatic = NBROWS != DYNAMIC; // [-] Is the number of rows of this matrix editable at run time
static constexpr bool isColStatic = NBCOLS != DYNAMIC; // [-] Is the number of columns of this matrix editable at run time
public:
/** @brief Default constructor
*
* @return Void.
*/
Matrix() :
matrixData()
{
if ((NBROWS <= 0 and NBROWS != DYNAMIC) or (NBCOLS <= 0 and NBCOLS != DYNAMIC))
throw std::runtime_error("The number of rows and columns of a static matrix must be positive integers");
// In case of a dynamic shape, the matrix should not be instanciated
if(isRowStatic and isColStatic)
internalChangeSize(NBROWS, NBCOLS);
}
/** @brief Consutuctor for the static size matrix
* @param i_DefaultValue IN : Default value used to fill
* the matrix
*
* @return Void.
*/
Matrix(const TYPE &i_DefaultValue) :
matrixData()
{
// error handling
if (not isRowStatic or not isColStatic)
throw std::runtime_error("The default value constructor can not be called on a Matrix with at least one dynamic component");
if ((NBROWS <= 0 and NBROWS != DYNAMIC) or (NBCOLS <= 0 and NBCOLS != DYNAMIC))
throw std::runtime_error("The number of rows and columns of a static matrix must be positive integers");
internalChangeSize(NBROWS, NBCOLS, i_DefaultValue);
}
/** @brief Consutuctor for the dynamic size matrix without default value
*
* @param i_Nbrows IN : Number of rows of the matrix
* @param i_Nbcols IN : Number of columns of the matrix
*
* @return Void.
*/
Matrix(const size_t i_Nbrows,
const size_t i_Nbcols) :
matrixData()
{
// error handling
if (i_Nbrows <= 0 or i_Nbcols <= 0)
throw std::runtime_error("The number or rows and columns has to be a positive integer");
// If one dimension is static, ignore the related constructor parameters
size_t NbRows = i_Nbrows;
size_t NbCols = i_Nbcols;
if(isRowStatic)
NbRows = NBROWS;
if(isColStatic)
NbCols = NBCOLS;
internalChangeSize(NbRows, NbCols, TYPE());
}
/** @brief Consutuctor for the dynamic size matrix with default value
*
* @param i_Nbrows IN : Number of rows of the matrix
* @param i_Nbcols IN : Number of columns of the matrix
* @param i_DefaultValue IN : Default value used to fill the
* matrix
*
* @return Void.
*/
Matrix(const size_t i_Nbrows,
const size_t i_Nbcols,
const TYPE &i_DefaultValue) :
matrixData()
{
// error handling
if (i_Nbrows <= 0 or i_Nbcols <= 0)
throw std::runtime_error("The number or rows and columns has to be a positive integer");
// If one dimension is static, ignore the related constructor parameters
size_t NbRows = i_Nbrows;
size_t NbCols = i_Nbcols;
if(isRowStatic)
NbRows = NBROWS;
if(isColStatic)
NbCols = NBCOLS;
internalChangeSize(NbRows, NbCols, i_DefaultValue);
}
/** @brief Copy constructor
*
* @param i_otherMatrix IN : Matrix to be copied
*
* @return Void.
*/
Matrix(const Matrix<TYPE, NBROWS, NBCOLS>& i_otherMatrix):
matrixData()
{
if(not i_otherMatrix.isEmpty())
{
changeSize(i_otherMatrix.getNbRows(), i_otherMatrix.getNbCols());
matrixData = i_otherMatrix.matrixData;
}
}
/** @brief Move constructor
*
* @param i_otherMatrix IN : Matrix to be moved
*
* @return Void.
*/
Matrix(Matrix<TYPE, NBROWS, NBCOLS>&& i_otherMatrix):
matrixData()
{
matrixData = std::move(i_otherMatrix.matrixData);
}
/** @brief getter for the matrix data vector
*
* @return std::vector<std::vector<TYPE>>&.
*/
const std::vector<std::vector<TYPE>>& getMatrixData() const
{
return matrixData;
}
/** @brief getter for the number or rows
*
* @return size_t
*/
size_t getNbRows() const
{
return matrixData.size();
}
/** @brief getter for the number or columns
*
* @return size_t
*/
size_t getNbCols() const
{
if(matrixData.size() > 0)
return matrixData[0].size();
else
return 0;
}
/** @brief is the Matrix is empty
*
* @return bool
*/
bool isEmpty() const
{
return getNbRows() == 0 or getNbCols() == 0;
}
/** @brief function used to retrieve the shape of the matrix
* @param o_NbRows OUT : Number of rows of the matrix
* @param o_NbCols OUT : Number of columns of the matrix
*
* @return Void.
*/
std::pair<size_t, size_t> shape() const
{
return std::pair<size_t, size_t>(getNbRows(), getNbCols());
}
/** @brief function used to print the contents of the
* matrix formatted into a string
*
* @return std::string
*/
std::string toString(int i_Precision = 10) const
{
std::ostringstream SS;
// if 0 lines representation is an empty bracket
if(matrixData.size() == 0)
SS << "| |" << std::endl;
// This will align the floating point numbers
SS << std::showpoint;
SS << std::setprecision(i_Precision);
for(auto& Row : matrixData)
{
SS << "|";
for(auto& Value : Row)
{
SS << " " << Value << " ";
}
SS << "|" << std::endl;
}
return SS.str();
}
/** @brief function used to change the size of the matrix
* This method does not require a default value,
* hence it is default initialized
*
* @param i_NbRows IN : New number of rows of the matrix
* @param o_NbCols IN : New number of columns of the matrix
*
* @return Void.
*/
void changeSize(const size_t i_NbRows, const size_t i_NbCols)
{
// Error handling
if (i_NbRows <= 0 or i_NbCols <= 0)
throw std::runtime_error("The number or rows and columns has to be a positive integer");
if (isRowStatic and NBROWS != i_NbRows)
throw std::runtime_error("You cannot change the number of rows, the matrix row size is static.");
if(isColStatic and NBCOLS != i_NbCols)
throw std::runtime_error("You cannot change the number of columns, the matrix columns size is static.");
internalChangeSize(i_NbRows, i_NbCols);
}
/** @brief function used to change the size of the matrix
* This method does not require a default value,
* hence it is default initialized
*
* @param i_NewShape IN : New shape of the matrix
*
* @return Void.
*/
void changeSize(const std::pair<size_t, size_t>& i_NewShape)
{
changeSize(i_NewShape.first, i_NewShape.second);
}
/** @brief function used to change the size of the matrix
* This method requires a default value for filling
* any new row / column.
*
* @param i_NbRows IN : New number of rows of the matrix
* @param o_NbCols IN : New number of columns of the matrix
* @param DefaultValue IN : Default value used to fill the matrix
*
* @return Void.
*/
void changeSize(const size_t i_NbRows, const size_t i_NbCols, const TYPE &DefaultValue)
{
// error handling
if (i_NbRows <= 0 or i_NbCols <= 0)
throw std::runtime_error("The number or rows and columns has to be a positive integer");
if (isRowStatic and NBROWS != i_NbRows)
throw std::runtime_error("You cannot change the number of rows, the matrix columns size is static.");
if(isColStatic and NBCOLS != i_NbCols)
throw std::runtime_error("You cannot change the number of columns, the matrix columns size is static.");
internalChangeSize(i_NbRows, i_NbCols, DefaultValue);
}
/** @brief function used to change the size of the matrix
* This method requires a default value for filling
* any new row / column.
*
* @param i_NewShape IN : New shape of the matrix
* @param DefaultValue IN : Default value used to fill the matrix
*
* @return Void.
*/
void changeSize(const std::pair<size_t, size_t>& i_NewShape, const TYPE &DefaultValue)
{
changeSize(i_NewShape.first, i_NewShape.second, DefaultValue);
}
/** @brief function used to transpose the current matrix.
* If the matrix is dynamically allocated, it's shape
* might be changed by the function
*
* @return Void.
*/
void transpose()
{
// Error handlingmatrixData
if (isEmpty())
throw std::runtime_error("The transpose function can not be called on an empty matrix");
if ((isRowStatic or isColStatic) and getNbRows() != getNbCols())
throw std::runtime_error("The transpose function can not be called on a non square matrix with at least one static component");
// The transposed Matrix is built and replaces the old data
std::vector<std::vector<TYPE>> newData(getNbCols(), std::vector<TYPE>(getNbRows(), (*this)(0,0)));
for (size_t i = 0 ; i < getNbCols() ; i += 1)
for (size_t j = 0 ; j < getNbRows() ; j += 1)
newData[i][j] = (*this)(i,j);
matrixData = std::move(newData);
}
/** @brief () operator. returns a reference to
* the value at row i, column j
*
* @return const TYPE&
*/
const TYPE& operator()(size_t i_Row, size_t i_Col) const
{
try
{
return matrixData.at(i_Row).at(i_Col);
}
catch(std::out_of_range& e)
{
const auto MatrixShape = this->shape();
std::ostringstream SS;
SS << "Indexes : (" << i_Row << ", " << i_Col << ") are out of bounds of the Matrix : " << "(" << MatrixShape.first << ", " << MatrixShape.second << ")";
throw std::runtime_error(SS.str());
}
}
/** @brief () operator. returns a reference to
* the value at row i, column j
*
* @return const TYPE&
*/
TYPE& operator()(size_t i_Row, size_t i_Col)
{
try
{
return matrixData.at(i_Row).at(i_Col);
}
catch(std::out_of_range& e)
{
const auto MatrixShape = this->shape();
std::ostringstream SS;
SS << "Indexes : (" << i_Row << ", " << i_Col << ") are out of bounds of the Matrix : " << "(" << MatrixShape.first << ", " << MatrixShape.second << ")";
throw std::runtime_error(SS.str());
}
}
/** @brief = operator. It copies the right hand side
* into the left hand size Matrix. If the sizes are
* different and the left hand side is static, the copy
* fails
* @param rhs IN : Right hand side matrix
*
* @return Void.
*/
template<typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
Matrix<TYPE, NBROWS, NBCOLS>& operator=(const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs)
{
const auto LhsShape = this->shape();
const auto RhsShape = rhs.shape();
// Error handling
if ((isRowStatic and (this->getNbRows() != rhs.getNbRows())) or
(isColStatic and (this->getNbCols() != rhs.getNbCols())))
{
std::ostringstream SS;
SS << "Impossible to fit data from a matrix of size (" << rhs.getNbRows() << ", " << rhs.getNbCols() << ") into"
" a static matrix of size (" << this->getNbRows() << ", " << this->getNbCols() << ")";
throw std::runtime_error(SS.str());
}
// If both matrices are empty, we dont need to do anything
if(not(isEmpty() and rhs.isEmpty()))
{
// else, change the size only if necessary, taking a default value in one of the non empty matrices in order not to call the default constructor
if (LhsShape != RhsShape )
{
if(not isEmpty())
{
changeSize(RhsShape, (*this)(0,0));
}
else if(not rhs.isEmpty())
{
changeSize(RhsShape, rhs(0,0));
}
}
}
matrixData = rhs.getMatrixData();
return *this;
}
/** @brief move = operator. It moves the right hand side
* into the left hand size Matrix. If the sizes are
* different and the left hand side is static, the copy
* fails
* @param rhs IN : Right hand side matrix
*
* @return Void.
*/
template<typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
Matrix<TYPE, NBROWS, NBCOLS>& operator=(Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS>&& rhs)
{
const auto LhsShape = this->shape();
const auto RhsShape = rhs.shape();
// Error handling
if ((isRowStatic and (this->getNbRows() != rhs.getNbRows())) or
(isColStatic and (this->getNbCols() != rhs.getNbCols())))
{
std::ostringstream SS;
SS << "Impossible to fit data from a matrix of size (" << rhs.getNbRows() << ", " << rhs.getNbCols() << ") into"
" a static matrix of size (" << this->getNbRows() << ", " << this->getNbCols() << ")";
throw std::runtime_error(SS.str());
}
// If both matrices are empty, we dont need to resize anything
if(not(isEmpty() and rhs.isEmpty()))
{
// else, change the size only if necessary, taking a default value in one of the non empty matrices in order not to call the default constructor
if (LhsShape != RhsShape )
{
if(not isEmpty())
{
changeSize(RhsShape, (*this)(0,0));
}
else if(not rhs.isEmpty())
{
changeSize(RhsShape, rhs(0,0));
}
}
}
matrixData = std::move(rhs.matrixData);
return *this;
}
/** @brief += operator. It adds the right hand side
* into the left hand size Matrix. If the sizes are
* different the operator fails
*
* @param i_NbRows IN : New number of rows of the matrix
* @param o_NbCols IN : New number of columns of the matrix
* @param io_Matrix IN : Matrix which size will be reduced
*
* @return Void.
*/
template<typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
Matrix<TYPE, NBROWS, NBCOLS>& operator+=(const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs)
{
// Error handling
if(this->isEmpty() or rhs.isEmpty())
throw std::runtime_error("Adding empty matrices is forbidden");
if (rhs.shape() != this->shape())
throw std::runtime_error("Adding matrices of different shapes is forbidden");
for(size_t i = 0; i < getNbRows() ; i += 1)
for(size_t j = 0 ; j < getNbCols() ; j += 1)
matrixData[i][j] += rhs(i,j);
return *this;
}
/** @brief + operator. It adds both sides of the "+" sign
* and returns a static size matrix. Both sides
* have to be of the same shape, otherwise the
* operator fails.
*
* @param rhs IN : Matrix, right side of the equation
*
* @return Matrix<decltype(rhs(0,0) + (*this)(0,0)), NBROWS, NBCOLS, true>.
*/
template<typename LHSTYPE, size_t LHSNBROWS, size_t LHSNBCOLS, typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
friend auto operator+(const Matrix<LHSTYPE, LHSNBROWS, LHSNBCOLS> &lhs, const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs) ->
Matrix<decltype(lhs(0,0) + rhs(0,0)), LHSNBROWS == DYNAMIC ? RHSNBROWS : DYNAMIC,
LHSNBCOLS == DYNAMIC ? RHSNBCOLS : DYNAMIC>;
/** @brief operator* It multiplies both sides of the "*" sign
* and returns a static size matrix. Both sides
* have to have compatible sizes, (lhs.columns == rhs.cols)
* otherwise, the operator fails.
*
* @param rhs IN : Matrix, right side of the equation
*
* @return Matrix<decltype(rhs(0,0) * (*this)(0,0)), this->getNbRows(), rhs.getNbCols(), true>
*/
template<typename LHSTYPE, size_t LHSNBROWS, size_t LHSNBCOLS, typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
friend auto operator*(const Matrix<LHSTYPE, LHSNBROWS, LHSNBCOLS> &lhs, const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs) -> Matrix<decltype(rhs(0,0) * lhs(0,0)), LHSNBROWS, RHSNBCOLS>;
private:
/** @brief function used to change the size of the matrix
* This method does not require a default value,
* hence it is default initialized. It does not check if the matrix is static or not
*
* @param i_NbRows IN : New number of rows of the matrix
* @param o_NbCols IN : New number of columns of the matrix
*
* @return Void.
*/
void internalChangeSize(const size_t i_NbRows, const size_t i_NbCols)
{
// Error handling
if (i_NbRows <= 0 or i_NbCols <= 0)
throw std::runtime_error("The number or rows and columns should be a positive integer");
matrixData.resize(i_NbRows, std::vector<TYPE>(i_NbCols, TYPE()));
for (auto& row : matrixData)
row.resize(i_NbCols, TYPE());
}
/** @brief function used to change the size of the matrix
* This method requires a default value for filling
* any new row / column. It does not check if the matrix is static or not
*
* @param i_NbRows IN : New number of rows of the matrix
* @param o_NbCols IN : New number of columns of the matrix
* @param DefaultValue IN : Default value used to fill the matrix
*
* @return Void.
*/
void internalChangeSize(const size_t i_NbRows, const size_t i_NbCols, const TYPE &DefaultValue)
{
// error handling
if (i_NbRows <= 0 or i_NbCols <= 0)
throw std::runtime_error("The number or rows and columns has to be a positive integer");
matrixData.resize(i_NbRows, std::vector<TYPE>(i_NbCols, DefaultValue));
for (auto& row : matrixData)
row.resize(i_NbCols, DefaultValue);
}
};
/** @brief + operator. It adds both sides of the "+" sign
* and returns a static size matrix. Both sides
* have to be of the same shape, otherwise the
* operator fails.
*
* @param rhs IN : Matrix, right side of the equation
*
* @return Matrix<decltype(rhs(0,0) + (*this)(0,0)), NBROWS, NBCOLS, true>.
*/
template<typename LHSTYPE, size_t LHSNBROWS, size_t LHSNBCOLS, typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
auto operator+(const Matrix<LHSTYPE, LHSNBROWS, LHSNBCOLS> &lhs, const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs) ->
Matrix<decltype(lhs(0,0) + rhs(0,0)), LHSNBROWS == DYNAMIC ? RHSNBROWS : DYNAMIC,
LHSNBCOLS == DYNAMIC ? RHSNBCOLS : DYNAMIC>
{
// Error handling
if(lhs.isEmpty() or rhs.isEmpty())
throw std::runtime_error("Adding empty matrices is forbidden");
if (rhs.shape() != lhs.shape())
throw std::runtime_error("Adding matrices of different shapes is forbidden");
Matrix<decltype(lhs(0,0) + rhs(0,0)), LHSNBROWS == DYNAMIC ? RHSNBROWS : DYNAMIC,
LHSNBCOLS == DYNAMIC ? RHSNBCOLS : DYNAMIC> newMatrix(lhs.getNbRows(), lhs.getNbCols(), lhs(0,0));
for(size_t i = 0 ; i < rhs.getNbRows() ; i += 1)
for(size_t j = 0 ; j < rhs.getNbCols() ; j += 1)
newMatrix(i, j) = lhs(i,j) + rhs(i,j);
return newMatrix;
}
/** @brief operator* It multiplies both sides of the "*" sign
* and returns a static size matrix. Both sides
* have to have compatible sizes, (lhs.columns == rhs.cols)
* otherwise, the operator fails.
*
* @param rhs IN : Matrix, right side of the equation
*
* @return Matrix<decltype(rhs(0,0) * (*this)(0,0)), this->getNbRows(), rhs.getNbCols(), true>
*/
template<typename LHSTYPE, size_t LHSNBROWS, size_t LHSNBCOLS, typename RHSTYPE, size_t RHSNBROWS, size_t RHSNBCOLS>
auto operator*(const Matrix<LHSTYPE, LHSNBROWS, LHSNBCOLS> &lhs, const Matrix<RHSTYPE, RHSNBROWS, RHSNBCOLS> &rhs) -> Matrix<decltype(rhs(0,0) * lhs(0,0)), LHSNBROWS, RHSNBCOLS>
{
// error handling
if(lhs.isEmpty() or rhs.isEmpty())
throw std::runtime_error("Multiplying empty matrices is forbidden");
if(lhs.getNbCols() != rhs.getNbRows())
throw std::runtime_error("The size of the matrices is incompatible with matrix multiplication");
Matrix<decltype(rhs(0,0) * lhs(0,0)), LHSNBROWS, RHSNBCOLS> newMatrix(lhs.getNbRows(), rhs.getNbCols(), lhs(0,0));
for(size_t i = 0 ; i < lhs.getNbRows() ; i += 1)
{
for(size_t j = 0 ; j < rhs.getNbCols(); j += 1)
{
decltype(rhs(0,0) * lhs(0,0)) sum = lhs(i,0) * rhs(0,j); // Compute the first element of the sum in order not to call the default constructor
for(size_t k = 1 ; k < lhs.getNbRows() ; k += 1)
{
sum += lhs(i,k) * rhs(k,j);
}
newMatrix(i, j) = std::move(sum);
}
}
return newMatrix;
}
/** @brief operator<< outputs the Matrix into a stream
*
* @param i_Matrix IN : Matrix to output
* @param o_OS OUT : Stream in which the matrix must be fitted
*
* @return std::ostream&
*/
template <typename TYPE, size_t NBROWS, size_t NBCOLS>
std::ostream& operator<<(std::ostream& o_OS, const Matrix<TYPE, NBROWS, NBCOLS>& i_Matrix)
{
return o_OS << i_Matrix.toString();
}
} /* namespace Mat */
</code></pre>
<p><strong>[EDIT]</strong>
As requested, i have written this main in which i instanciate some matrices, add and multiply them. Some are static, some dynamic.
i have not shown the case where only one dimension of the matrix is dynamic and the other static (like in a dynamic size vector for instance), but this works the same.</p>
<p><em>I used these options when compiling when working with the class:
-std=c++11 -O0 -g -pedantic -pedantic-errors -Wall -Wextra -Werror -Wconversion -fmessage-length=0
However, for the implict conversion behavior to work in the test main, -Wconversion shall not be used.</em></p>
<pre><code>#include <iostream>
#include "Matrix.h"
int main()
{
// Test of static Matrix operations
// ==============================================
std::cout << "==============================================" << std::endl;
std::cout << "===============STATIC MATRICES================" << std::endl;
std::cout << "==============================================" << std::endl;
mat::Matrix<int, 3,2> StaticMatrix_1(21);
mat::Matrix<float, 3,2> StaticMatrix3x2(2.0);
mat::Matrix<float, 3,3> StaticMatrix3x3(2.0);
// Resizing a static matrix should throw if it changes the size of the matrix only
// should not throw
StaticMatrix_1.changeSize(3, 2);
try
{
StaticMatrix_1.changeSize(4, 5);
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
std::cout << "STATIC MATRICES USED:" << std::endl;
std::cout << StaticMatrix_1 << std::endl;
std::cout << StaticMatrix3x2 << std::endl;
std::cout << StaticMatrix3x3 << std::endl;
// test of Matrix multiplication: Should yield a 3 by 2 matrix, full of 12.0 floats
std::cout << "TEST_ADDITION FLOAT + FLOAT" << std::endl;
std::cout << StaticMatrix3x3 * StaticMatrix3x2 << std::endl;
// test of matrix addition: This should yield a matrix of floats as int + float does yield a float
std::cout << "TEST_ADDITION INT + FLOAT" << std::endl;
std::cout << StaticMatrix_1 + StaticMatrix3x2 << std::endl;
// Test of matrix addition with different sizes (should throw)
try
{
StaticMatrix3x2 + StaticMatrix3x3;
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
// This property should be commutative
std::cout << "TEST_ADDITION FLOAT + INT" << std::endl;
std::cout << StaticMatrix3x2 + StaticMatrix_1 << std::endl;
std::cout << "TEST_MATRIX_MULTIPLICATION" << std::endl;
std::cout << StaticMatrix3x3 * StaticMatrix3x2 << std::endl;
// This should throw (incompatible sizes for multiplication)
try
{
StaticMatrix3x2 * StaticMatrix3x3;
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
std::cout << std::endl << std::endl << std::endl;
std::cout << "==============================================" << std::endl;
std::cout << "===============DYNAMIC MATRICES===============" << std::endl;
std::cout << "==============================================" << std::endl;
// We use the same types, contents and sizes
mat::Matrix<int, mat::DYNAMIC, mat::DYNAMIC> DynamicMatrix_1(3, 2, 21);
mat::Matrix<float, mat::DYNAMIC, mat::DYNAMIC> DynamicMatrix3x2(3, 2, 2.0);
mat::Matrix<float, mat::DYNAMIC, mat::DYNAMIC> DynamicMatrix3x3(3, 3, 2.0);
std::cout << "DYNAMYC MATRICES USED:" << std::endl;
std::cout << DynamicMatrix_1 << std::endl;
std::cout << DynamicMatrix3x2 << std::endl;
std::cout << DynamicMatrix3x3 << std::endl;
// Resizing a dynamic matrix should throw only if the requested size is <= 0
// should not throw
DynamicMatrix_1.changeSize(1, 1);
DynamicMatrix_1.changeSize(3, 2);
try
{
DynamicMatrix_1.changeSize(0, 0);
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
// test of Matrix multiplication: Should yield a 3 by 2 matrix, full of 12.0 floats
std::cout << "TEST_ADDITION FLOAT + FLOAT" << std::endl;
std::cout << DynamicMatrix3x3 * DynamicMatrix3x2 << std::endl;
// test of matrix addition: This should yield a matrix of floats as int + float does yield a float
std::cout << "TEST_ADDITION INT + FLOAT" << std::endl;
std::cout << DynamicMatrix_1 + DynamicMatrix3x2 << std::endl;
// Test of matrix addition with different sizes (should throw)
try
{
DynamicMatrix3x2 + DynamicMatrix3x3;
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
// This property should be commutative
std::cout << "TEST_ADDITION FLOAT + INT" << std::endl;
std::cout << DynamicMatrix3x2 + DynamicMatrix_1 << std::endl;
std::cout << "TEST_MATRIX_MULTIPLICATION" << std::endl;
std::cout << DynamicMatrix3x3 * DynamicMatrix3x2 << std::endl;
// This should throw (incompatible sizes for multiplication)
try
{
DynamicMatrix3x2 * DynamicMatrix3x3;
std::cout << "Did not throw ==> problem" << std::endl;
}
catch(std::runtime_error& E)
{
}
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T18:35:58.400",
"Id": "522036",
"Score": "0",
"body": "Very well elaborated. Thank you for that. Hopefully you will get some answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:23:16.190",
"Id": "522037",
"Score": "1",
"body": "Do you have some unit tests you could add to demonstrate usage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:02:03.263",
"Id": "522068",
"Score": "1",
"body": "Do you mean real unit tests (i could write some of those using catch if you want) or a little main where i create some objects and use them?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T15:44:16.157",
"Id": "264327",
"Score": "1",
"Tags": [
"c++11",
"matrix",
"template"
],
"Title": "template Matrix class with Static or dynamic size"
}
|
264327
|
<p>I implemented the Maximum Profit in Job Scheduling algorithm in JavaScript, but I'm having performance issue.</p>
<p>The problem:
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].</p>
<p>You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.</p>
<p>If you choose a job that ends at time X you will be able to start another job that starts at time X.</p>
<p>Example 1:</p>
<pre><code>Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
</code></pre>
<p>Example 2:</p>
<pre><code>Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
</code></pre>
<p>My solution:</p>
<pre><code>var jobScheduling = function(startTime, endTime, profit) {
let possibleStarts = [];
let startProfit = [];
let curEnd = Infinity
let mapPositions = new Map();
for(let i=0; i<startTime.length; i++) {
const s = startTime[i];
const e = endTime[i];
if(s < curEnd) {
possibleStarts.push([s, e]);
startProfit.push(i);
curEnd = Math.min(curEnd, e);
}
const temp = mapPositions.get(s) || [];
temp.push(i);
mapPositions.set(s, temp);
}
let output = -Infinity;
const helper = (queue, count, profitPos) => {
const start = queue.shift();
const end = queue.shift();
count += profit[profitPos];
// get all possible next start
for(const [key, value] of mapPositions) {
if(key >= end) {
for(const v of value) {
helper([startTime[v], endTime[v]], count, v)
}
}
}
output = Math.max(output, count);
return;
}
for(let i=0; i<possibleStarts.length; i++) {
helper(possibleStarts[i], 0, startProfit[i]);
}
return output;
};
</code></pre>
<p>It works for both examples and other test cases. However it fails for the test case below due to time limit.</p>
<pre><code>startTime = [341,22,175,424,574,687,952,439,51,562,962,890,250,47,945,914,835,937,419,343,125,809,807,959,403,861,296,39,802,562,811,991,209,375,78,685,592,409,369,478,417,162,938,298,618,745,888,463,213,351,406,840,779,299,90,846,58,235,725,676,239,256,996,362,819,622,449,880,951,314,425,127,299,326,576,743,740,604,151,391,925,605,770,253,670,507,306,294,519,184,848,586,593,909,163,129,685,481,258,764]
endTime = [462,101,820,999,900,692,991,512,655,578,996,979,425,893,975,960,930,991,987,524,208,901,841,961,878,882,412,795,937,807,957,994,963,716,608,774,681,637,635,660,750,632,948,771,943,801,985,476,532,535,929,943,837,565,375,854,174,698,820,710,566,464,997,551,884,844,830,916,970,965,585,631,785,632,892,954,803,764,283,477,970,616,794,911,771,797,776,686,895,721,917,920,975,984,996,471,770,656,977,922]
profit = [85,95,14,72,17,3,86,65,50,50,42,75,40,87,35,78,47,74,92,10,100,29,55,57,51,34,10,96,14,71,63,99,8,37,16,71,10,71,83,88,68,79,27,87,3,58,56,43,89,31,16,9,49,84,62,30,35,7,27,34,24,33,100,25,90,79,58,21,31,30,61,46,36,45,85,62,91,54,28,63,50,69,48,36,77,39,19,97,20,39,48,72,37,67,72,46,54,37,53,30]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T18:50:50.457",
"Id": "522126",
"Score": "0",
"body": "@radarbob Why 400%? Do you mind showing your solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:16:13.097",
"Id": "522132",
"Score": "0",
"body": "@radarbob I think you are thinking about this as a \"real life\" problem. It's an algorithm for coding/data structure purpose."
}
] |
[
{
"body": "<p>There are some readability concerns to me:</p>\n<ul>\n<li><code>startTime</code>, <code>endTime</code>, <code>profit</code> are all arrays. The names should be plural to make this obvious.</li>\n<li><code>possibleStarts</code> consists of both start and end. It's confusing. You could instead make an array of job objects with properties start, end, profit. Then you wouldn't need the extra profit lookup either.</li>\n<li><code>helper</code> is not a good function name. It indicates that it's not entirely clear what you want it to do.</li>\n<li><code>count</code> is not a count. It is the profit</li>\n<li><code>profitPos</code> is really the job index</li>\n</ul>\n<p>Clearing these up will make it easier to understand the current solution, and therefore easier to figure out the performance as well.</p>\n<p>About performance:</p>\n<p>I think the key to this problem is to realize that <code>helper</code> will be called on the same jobs over and over again. We can exploit this by using memoization. What you need to do is to have the function return a value. If the function is given the same input we'll just return the previously calculated value instead of running them all again.</p>\n<p>You can add memoization like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const memo = new Map()\nconst helper = (queue, count, profitPos) => {\n if (memo.has(profitPos)) return memo.get(profitPos)\n const start = queue.shift();\n const end = queue.shift();\n\n let maxProfit = 0\n // get all possible next start\n for(const [key, value] of mapPositions) {\n if(key >= end) {\n for(const v of value) {\n const profit = helper([startTime[v], endTime[v]], count, v)\n maxProfit = Math.max(profit, maxProfit)\n }\n }\n }\n\n const result = profit[profitPos] + maxProfit\n memo.set(profitPos, result)\n return result\n}\n</code></pre>\n<p>which can be rewritten into this (glossing over the details):</p>\n<pre class=\"lang-js prettyprint-override\"><code>const memo = new Map()\nconst getMaxProfit = (index) => {\n if (memo.has(index)) return memo.get(index)\n const job = jobs[index]\n\n let maxSubProfit = 0\n for (let i = 0; i < jobLen; i++) {\n if (jobs[i].start < job.end) continue\n const profit = getMaxProfit(i)\n maxSubProfit = Math.max(profit, maxSubProfit)\n }\n\n const maxProfit = job.profit + maxSubProfit\n memo.set(index, maxProfit)\n return maxProfit\n}\n</code></pre>\n<p>And this will solve your test case fast enough.</p>\n<p>Since we're memoizing on the job index (profit pos), the function body will only run once for each job. In the function body we still iterate over all jobs (mapPositions). In other words, getMaxProfit is called about n times for every time the loop runs. This is a problem even with memoization since the memo map has to be called n times. The time complexity becomes O(n^2). With n=100 it works fine, but for larger inputs it gets slow again.</p>\n<p>There are some pretty clever tricks to avoid the loop involving rewriting the loop as a recursion and adding binary search. The thing to realize is that we're calling getMaxProfit more than we need to. We always "keep" the profit of the current job, and try out all the upcoming jobs. When we get to the next job, we try all jobs again, calling getMaxProfit each time. And even though it's fast, it adds up. We can solve it by realizing that we only need to check the next job:</p>\n<p>When considering a job, we can either skip the job and move on, or we can keep the job and find the next job after the current one. The reason we can just consider the next job (as opposed to ALL the possible next jobs as in the loop) is that the first option of skipping a job ensures that we explore all solutions anyway, including actually skipping the next job we found.</p>\n<p>So with this we have managed to remove the loop that calls getMaxProfit. But we have a new loop that's supposed to find the next job, and this loop is itself a problem. But it's much easier to solve, for example using binary search.</p>\n<p>The code might look something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const jobs = startTimes\n .map((start, i) => ({ start, end: endTimes[i], profit: profits[i] }))\n .sort((a, b) => a.start > b.start ? 1 : -1)\n\nconst memo = new Map()\nconst getMaxProfit = (index) => {\n if (index >= jobs.length) return 0\n if (memo.has(index)) return memo.get(index)\n\n const job = jobs[index]\n\n const nextIndex = findNextJobIndex(jobs, job.end)\n const maxProfitNext = getMaxProfit(nextIndex)\n const maxProfitSkipped = getMaxProfit(index + 1)\n\n const maxProfit = Math.max(maxProfitNext + job.profit, maxProfitSkipped)\n\n memo.set(index, maxProfit)\n return maxProfit\n}\n\nreturn getMaxProfit(0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T20:39:22.507",
"Id": "264492",
"ParentId": "264332",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "264492",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:19:07.323",
"Id": "264332",
"Score": "1",
"Tags": [
"javascript",
"performance",
"algorithm",
"time-limit-exceeded"
],
"Title": "Maximum Profit in Job Scheduling - Performance Issue"
}
|
264332
|
<p>I wrote a short function to iterate over a list starting at a given index, then flipping back and forth between left and right values.</p>
<pre class="lang-py prettyprint-override"><code>import itertools
from typing import Generator
def bidirectional_iterate(lst: list, index: int) -> Generator:
for left, right in itertools.zip_longest(reversed(lst[:index]), lst[index:]):
if right is not None:
yield right
if left is not None:
yield left
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
# 7 5 3 1 0 2 4 6 8 9 <- Expected order of iteration
print(list(bidirectional_iterate(arr, 4)))
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>[4, 3, 5, 2, 6, 1, 7, 0, 8, 9]
</code></pre>
<p>I feel like I've seen an algorithm like this before, but I couldn't find any reference to it.</p>
<p>This was the most Pythonic implementation I could come up with. The only improvement I can think to make to this implementation is a way to differentiate <code>None</code> list elements from the <code>None</code> values returned to pad <code>itertools.zip_longest()</code>.</p>
<p>Are there any better/faster ways or any libraries that can accomplish this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T00:45:33.330",
"Id": "522060",
"Score": "3",
"body": "Why is the expected output and the actual output different?"
}
] |
[
{
"body": "<p>Here's an alternative approach that requires no conditional logic and does not create intermediate sub-lists — although at the cost of using a third-party\nlibrary:</p>\n<pre><code>from more_itertools import interleave_longest\n\ndef bidirectional_iterate(xs, index):\n left = range(index - 1, -1, -1)\n right = range(index, len(xs), 1)\n return [xs[i] for i in interleave_longest(right, left)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T09:17:11.983",
"Id": "522073",
"Score": "1",
"body": "You want to return a generator in the function, surely, and then convert the result of the function to a list outside the function. Otherwise there's no option for lazy evaluation of the iterator; it all has to be built in memory whatever the use case"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T15:06:58.937",
"Id": "522084",
"Score": "2",
"body": "@AlexWaygood Depends on the situation. Either way, that detail is easily adjusted, depending on one's goals."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T20:34:38.367",
"Id": "264336",
"ParentId": "264334",
"Score": "8"
}
},
{
"body": "<p>I like your code, but I think the biggest potential issue with it is that in <em>each iteration</em> of the loop, both <code>left</code> and <code>right</code> need to be checked to see if they're not <code>None</code>. As @FMc pointed out, another issue is that your <code>reversed(lst[:index])</code> and <code>lst[index:]</code> lists both have to be built in memory before you even begin iterating. If you're dealing with very large lists, that might not be possible, and certainly won't be efficient.</p>\n<p>Here's another alternative approach, that uses makes use of the <code>roundrobin</code> recipe at the end of the <code>itertools</code> docs. Rather than checking <em>each iteration</em> whether the generator has been exhausted, <code>roundrobin</code> removes an empty generator from the sequence of generators as soon as that generator raises <code>StopIteration</code>. (If you're happy with having a third-party import, you can just import it from <code>more_itertools</code> and it saves you a few lines of code). I also used generator expressions in place of the lists that you built in memory, and tinkered a little with your type hints to make them more expressive of what the code is achieving.</p>\n<pre><code>from itertools import cycle, islice\nfrom typing import Iterator, Iterable, TypeVar, Sequence\n\nT = TypeVar("T")\n\ndef roundrobin(*iterables: Iterable[T]) -> Iterator[T]:\n "roundrobin('ABC', 'D', 'EF') --> A D E B F C"\n # Recipe credited to George Sakkis\n num_active = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n\n\ndef bidirectional_iterate(xs: Sequence[T], index: int) -> Iterator[T]:\n left = (xs[i] for i in range((index - 1), -1, -1))\n right = (xs[i] for i in range(index, len(xs)))\n yield from roundrobin(right, left)\n\narr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(list(bidirectional_iterate(arr, 4)))\n</code></pre>\n<p>Another option is to take away the function call and merge the two functions into one:</p>\n<pre><code>from itertools import cycle, islice\nfrom typing import Iterator, TypeVar, Sequence\n\nT = TypeVar("T")\n\ndef bidirectional_iterate(xs: Sequence[T], index: int) -> Iterator[T]:\n """Incorporates the 'roundrobin' recipe from the itertools docs, credited to George Sakkis"""\n left = (xs[i] for i in range((index - 1), -1, -1))\n right = (xs[i] for i in range(index, len(xs)))\n num_active = 2\n nexts = cycle(iter(it).__next__ for it in (right, left))\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n\narr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(list(bidirectional_iterate(arr, 4)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T17:49:41.440",
"Id": "522100",
"Score": "1",
"body": "This is great! Thanks so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T01:18:22.653",
"Id": "264341",
"ParentId": "264334",
"Score": "7"
}
},
{
"body": "<p>Warning: this is probably not better - the index juggling is ugly - and it may or may not be faster; I haven't tested. It's possible for you to write this with no explicit loops or conditions (with sufficiently narrow definitions for loops and conditions) and no external libraries. You can assign to a list directly, abusing Python's slicing semantics:</p>\n<pre><code>from typing import TypeVar, Sequence, List\n\nItemT = TypeVar('ItemT')\n\n\ndef bidirectional_iterate(items: Sequence[ItemT], index: int) -> List[ItemT]:\n n = len(items)\n out = [None]*n\n\n # Increasing from index to end of items\n out[: 2*(n-index): 2] = items[index: index + n//2]\n\n # Increasing from beginning of items to index\n out[2*(n-index): : 2] = items[-n: index - n*3//2]\n\n # Decreasing from index to beginning of items\n out[\n min(-1, 2*index-n-1): : -2\n ] = items[index - n*3//2: index-n]\n\n # Decreasing from end of items to index\n out[n-1: 2*index: -2] = items[index + n//2:]\n\n return out\n\n\nfor i in range(10):\n print(bidirectional_iterate(tuple(range(10)), i))\n</code></pre>\n<p>If you end up using Numpy, this stands a good chance of executing more quickly than the iterative solution. I've tested this for its correctness at n=10 for all of the shown index values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T19:20:43.957",
"Id": "264357",
"ParentId": "264334",
"Score": "3"
}
},
{
"body": "<p>Your code is good from a readability standpoint. I appreciate the type hints. My only minor suggestions are using <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == "__main__":</code></a> for your driver code and <code>lst</code> instead of <code>arr</code> (<code>arr</code> usually refers to a <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.array.html\" rel=\"nofollow noreferrer\">NumPy array</a>, but there are also <a href=\"https://docs.python.org/3/library/array.html\" rel=\"nofollow noreferrer\">builtin Python arrays</a> that aren't lists).</p>\n<p>Here's a somewhat terser suggestion that uses a <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow noreferrer\">generator expression</a> and a classic <a href=\"https://stackoverflow.com/a/952952/6243352\">iterable flattening pattern</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import zip_longest\nfrom typing import Generator\n\ndef bidirectional_iterate(lst: list, index: int) -> Generator:\n zipped = zip_longest(lst[index:], reversed(lst[:index]))\n return (x for pair in zipped for x in pair if x is not None)\n\nif __name__ == "__main__":\n lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n # 7 5 3 1 0 2 4 6 8 9 <- Expected order of iteration\n \n print(list(bidirectional_iterate(lst, 4)))\n</code></pre>\n<p>That said, it's an antipattern to return a linear-sized generator in an algorithm that needs to use linear space just to set up the generator. Returning a generator implies the algorithm uses space substantially less than the output set.</p>\n<p>Changing the generator expression to a list comprehension gives:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def bidirectional_iterate(lst: list, index: int) -> Generator:\n zipped = zip_longest(lst[index:], reversed(lst[:index]))\n return [x for pair in zipped for x in pair if x is not None]\n</code></pre>\n<p>As a bonus, the caller need not use <code>list()</code> on the return value.</p>\n<p>On the other hand, iteration algorithms are generally conducive to laziness, so it's usually a shame to throw the baby out with the bath water purely for the sake of more clever code; try to write it to keep the generator and get rid of the slices.</p>\n<p>One approach that seems worth mentioning is treating the list as a graph with neighbors <code>i - 1 if i < index else i + 1</code> running a <a href=\"https://en.wikipedia.org/wiki/Breadth-first_search\" rel=\"nofollow noreferrer\">breadth-first</a> traversal on the list.</p>\n<p>This incurs some overhead from the queue operations, so I wouldn't suggest it as categorically better than a purely index-based approach, but it's lazy, requires no dependencies and is pretty readable.</p>\n<p>If <code>q.pop(0)</code> looks scary, keep in mind the list will never have more than 3 elements, so it's constant time, probably not much slower than a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque.popleft()</code></a>, which is the normal queue in Python. Feel free to use that and benchmark it if <code>pop(0)</code> (rightfully) makes you nervous.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def bidirectional_iterate(lst: list, index: int) -> Generator:\n q = [index, index - 1, index + 1]\n\n while q:\n i = q.pop(0)\n \n if i >= 0 and i < len(lst):\n yield lst[i]\n\n if i != index:\n q.append(i - 1 if i < index else i + 1)\n</code></pre>\n<p>Having offered this as a proof of concept, as suggested above, the nature of this algorithm is such that the entire list would need to be in memory anyway because the indices don't move in a forward-only direction.</p>\n<p>Typical itertools algorithms and one-direction iteration functions like file readers seem like dramatically better fits for generators. For file readers, the input need not be fully in memory so your memory consumption can be line-by-line or even byte-by-byte.</p>\n<p>In other cases, like <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"nofollow noreferrer\"><code>itertools.permutations</code></a>, the size of the result set is dramatically (exponentially) larger than the input iterables and liable to blow up memory. Other itertools functions like <a href=\"https://docs.python.org/3/library/itertools.html#itertools.cycle\" rel=\"nofollow noreferrer\"><code>cycle</code></a> return infinite sequences, another great use case for generators.</p>\n<p>For this algorithm, I'd recommend going with the list version until you really find a critical use case for the generator. I'd be curious to hear what motivated you to pursue a generator in the first place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T23:12:44.203",
"Id": "522323",
"Score": "0",
"body": "Thanks for such a detailed response! This function is part of a larger searching algorithm that looks for the nearest point to a reference point in several pre-indexed datasets. The idea was that I could use a generator to save computing the list of all the (pointers to) the datasets when I may only need the first one or two each time. However, I had not thought about the list already being fully loaded in memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T23:15:46.773",
"Id": "522324",
"Score": "1",
"body": "Interesting, thanks. Oh yeah, if you're only using some of the items then the generator makes much more sense. Curious to hear if you wind up benchmarking anything."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:51:25.573",
"Id": "264383",
"ParentId": "264334",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264341",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T19:34:43.787",
"Id": "264334",
"Score": "6",
"Tags": [
"python",
"iterator",
"generator"
],
"Title": "Bidirectional iterate over list in Python"
}
|
264334
|
<p>Hello how can i send a token from the msg.sender to mycontract through a function inside my contract?</p>
<ol>
<li>i tried to do a transferFrom
"<code>IERC20(old_tokenAddress).transferFrom(msg.sender, address(this), query_oldBalance(msg.sender));</code>" but i get: <code> execution reverted: ERC20: transfer amount exceeds allowance</code> even if i put
the allowance to a much bigger number of what im trying to transfer,</li>
<li>if i try with a normal transfer <code>IERC20(old_tokenAddress).transfer(address(this), query_oldBalance(msg.sender));</code> i get : <code>"execution reverted: Transfer amount exceeds the maxTxAmount.</code> same here i tried to set the maxtxamount to a much bigger number than the token im trying to transfer.
Just to clarify the function <em>query_oldBalance</em> is a function that return <code>IERC20(old_tokenAddress).balanceOf(_address);</code>
Hope someone can help me, ty.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:17:36.633",
"Id": "522171",
"Score": "1",
"body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] |
[
{
"body": "<p><code>IERC20(_tokenAddress).transferFrom(msg.sender, address(this), old_balance);</code> was right but before call this func the user should approve the <strong>address</strong> of the <strong>new</strong> token <strong>ON</strong> the <strong>old</strong> token contract</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T02:00:39.393",
"Id": "264400",
"ParentId": "264337",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "264400",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T21:30:26.527",
"Id": "264337",
"Score": "-3",
"Tags": [
"solidity"
],
"Title": "Send token from addressA to addressB through contract"
}
|
264337
|
<p>So I have this piece of code that produces following error:</p>
<pre><code>cannot return value referencing local variable `key_name`
returns a value referencing data owned by the current function
</code></pre>
<p>I want it to evaluate the <code>Key</code> range and produce a map of strings, but it fails on the line <code>map</code>. I can't seem to set up the ownership right. This is what I came up with:</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
use evdev::Key;
const KEY_RANGE_START : Key = Key::KEY_ESC;
const KEY_RANGE_END : Key = Key::KEY_SLASH;
const KEY_RANGE_COUNT: u16 = KEY_RANGE_END.code() - KEY_RANGE_START.code();
use lazy_static::lazy_static;
lazy_static! {
static ref KEY_NAMES: HashMap<u16, &'static str> = {
let mut map = HashMap::new();
for index in 0..KEY_RANGE_COUNT {
let code = index+KEY_RANGE_START.code();
let key = Key::new(code);
let key_name = format!("{:?}", key);
let short_key_name = key_name.strip_prefix("KEY_").unwrap();
map.insert(code, short_key_name.clone());
}
map
};
}
</code></pre>
|
[] |
[
{
"body": "<p><code>short_key_name</code> is a <code>&str</code> that was borrowed from <code>key_name</code>, a <code>String</code> allocated inside the loop and which will be dropped at the end of each loop iteration. Thus, it is <em>not</em> a <code>&'static str</code>.</p>\n<p>You can use <code>Box::leak</code> to create an allocation that <em>will</em> stick around for the rest of the life of the program. (This is reasonable for lazy static initialization, but other uses can easily create a memory leak, as the name suggests!)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let short_key_name = &*Box::leak(Box::<str>::from(short_key_name));\nmap.insert(code, short_key_name);\n</code></pre>\n<p>This</p>\n<ol>\n<li>copies the characters of the <code>&str</code> into a <code>Box<str></code>,</li>\n<li>forgets about the existence of the box (so it is never deallocated) and creates an <code>&'static mut str</code> to its contents, and</li>\n<li>converts the <code>&'static mut str</code> to an <code>&'static str</code>, matching the type needed for the <code>HashMap</code>.</li>\n</ol>\n<p>Do not use <code>Box::leak</code> for any code that runs more than once! As the name says, it leaks!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T21:38:43.133",
"Id": "522138",
"Score": "0",
"body": "Thank you very much, mr Reid. Rust has a bit of a learning curve and you helped me significantly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T03:58:25.367",
"Id": "264342",
"ParentId": "264339",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T00:13:21.897",
"Id": "264339",
"Score": "-1",
"Tags": [
"rust"
],
"Title": "Rust: lazy_static the strings from evdev codes"
}
|
264339
|
<p>The first function will always try to correct the final result, while the second uses a conditional to know when to compensate. I think that in general the second function will be faster, but it will look a little worse than the first.</p>
<pre class="lang-c prettyprint-override"><code>int floor_mod1(int a, int b)
{
int mod = a % b;
return (mod + b) % b;
}
int floor_mod2(int a, int b)
{
int mod = a % b;
if (mod != 0 && (a ^ b) < 0) {
return mod + b;
}
return mod;
}
</code></pre>
<p>What does the condition do?<br />
There's not need to correct already calculated <code>0</code> to <code>0</code>, so we will not do anything in case when <code>mod == 0</code>. If <code>a</code> and <code>b</code> have the same sign, we will not anything, because the result is already correct.</p>
<hr />
<p>More details:<br />
And in fact, we can use <code>(mod ^ b) < 0</code> instead of <code>(a ^ b) < 0</code> to work with the old version of the language, where the modulo operator could round towards either zero or negative infinity.</p>
<p>Moreover, we can replace <code>mod != 0</code> with <code>(mod ^ b) != b</code> (not with <code>(a ^ b) != b</code>), but this will probably slow down our code, it depends on the compiler.<br />
BUT, if someone can figure out how to replace these parts (<code>(mod ^ b) != b && (mod ^ b) < 0</code>...) with fewer operations, then such implementation will probably be the best one. (keep in mind the most important facts: <code>b</code> will never be equal to <code>0</code>, for the condition to work <code>a</code> and <code>b</code> must have different signs and <code>a</code> should not be equal to <code>0</code>)</p>
<p>.. and we could probably write a better version in assembly, but it won't be as portable ..</p>
<hr />
<p>Should I return value here <code>return mod + b;</code> or use <code>mod += b</code>?<br />
Should I choose the second version because of its speed, regardless of the not-so-pretty code?<br />
Am I correct that using <code>(mod ^ b) < 0</code> instead of <code>(a ^ b) < 0</code> doesn't matter for performance?<br />
Any other comments?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T05:14:33.330",
"Id": "522067",
"Score": "2",
"body": "Personally I prefer the first version which - at least for me - is easier to read. If you one day notice that you have a performance issue in the function you can take a look at it again. Always try to write code that is easy to read, the future you and any colleagues will thank you."
}
] |
[
{
"body": "<p>You can use <a href=\"https://godbolt.org/z/1cKbnqr3n\" rel=\"nofollow noreferrer\">Godbolt</a> to play around with the C code and see if anything makes the assembly look particularly better. (Seems like Clang is strangely much better than GCC at making this code branch-free.)</p>\n<p><em>Technically</em>, <code>(a ^ b)</code> has implementation-defined behavior if you end up XORing non-zero sign bit(s) together. It's better (in terms of portability) to write <code>(a < 0) != (b < 0)</code>. Let the compiler figure out the bit-twiddling.</p>\n<p>Anyway, you're assuming that this function needs optimization... you've profiled your program and seen that it's the hot spot? So you're trying to turn two <code>idiv</code> instructions into one <code>idiv</code> instruction? Have you looked at your program's workload? Maybe you could even turn that one <code>idiv</code> into no <code>idiv</code>s... on the happy path.</p>\n<p>This exact situation is covered in Chandler Carruth's <a href=\"https://www.youtube.com/watch?v=nXaxk27zwlk\" rel=\"nofollow noreferrer\">"Tuning C++"</a> from CppCon 2015. He replaces <code>o = i % ceil;</code> with <code>o = (i >= ceil) ? i % ceil : i;</code> and the code magically gets faster. Consider whether your hot spot would benefit from similar workload analysis.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T13:58:50.963",
"Id": "524561",
"Score": "0",
"body": "Thank you very much for the good answer, the other answer had a greater impact on the result, no offense to you, but I accept it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:36:21.520",
"Id": "524591",
"Score": "0",
"body": "Quuxplusone, OP's code use `int`. `o = i % ceil;` functions differently from `o = (i >= ceil) ? i % ceil : i;` when `cell > 0, i < -cell`. If full range `i, cell` is important, getting faster is not worth the coding error."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T05:44:49.343",
"Id": "264343",
"ParentId": "264340",
"Score": "4"
}
},
{
"body": "<p><strong>Broken corner cases</strong></p>\n<p>"The first function will always try to correct the final result, " is unsupported, due to undefined behavior, when <code>mod + b</code> overflows as in <code>floor_mod1(1, INT_MAX)</code>.</p>\n<blockquote>\n<p>I think that in general the second function will be faster,</p>\n</blockquote>\n<p>Speed should be a secondary concern, get the function to work correctly for all <code>int a</code>, <code>int b</code>.</p>\n<hr />\n<p><strong>Make code functionally correct before spending much effort on speed.</strong></p>\n<p>Sample functional test harness that exhibits functional problems</p>\n<pre><code>#include <stdio.h>\n#include <limits.h>\n\nint floor_mod1(int a, int b) {\n int mod = a % b;\n return (mod + b) % b;\n}\n\nint floor_mod2(int a, int b) {\n int mod = a % b;\n if (mod != 0 && (a ^ b) < 0) {\n return mod + b;\n }\n return mod;\n}\n\n// Wider math for reference\nint floor_modR(int a, int b) {\n long long mod = (1LL * a) % b;\n return (int) ((mod + b) % b);\n}\n\nint main() {\n const int t[] = {0, 1, 2, 42, INT_MAX - 1, INT_MAX, -1, -2, INT_MIN + 1,\n INT_MIN};\n size_t n = sizeof t / sizeof t[0];\n for (size_t ia = 0; ia < n; ia++) {\n int a = t[ia];\n for (size_t ib = 0; ib < n; ib++) {\n int b = t[ib];\n if (b == 0) {\n continue;\n }\n // Better floor_mod() would handle this case too \n // Both floor_mod1(), floor_mod2() fail this case.\n if (a == INT_MIN && b == -1) {\n continue;\n }\n int m1 = floor_mod1(a, b);\n int m2 = floor_mod2(a, b);\n int mR = floor_modR(a, b);\n if (m1 != mR || m2 != mR) {\n printf("f(%d,%d) --> %d %d %d\\n", a, b, m1, m2, mR);\n fflush(stdout);\n }\n }\n }\n}\n</code></pre>\n<p>Output</p>\n<pre><code>f(1,2147483647) --> -1 1 1\nf(2,2147483646) --> -2 2 2\nf(2,2147483647) --> 0 2 2\nf(42,2147483646) --> -2147483608 42 42\nf(42,2147483647) --> -2147483607 42 42\nf(2147483646,2147483647) --> -3 2147483646 2147483646\nf(-1,-2147483648) --> 2147483647 -1 -1\nf(-2,-2147483647) --> 0 -2 -2\nf(-2,-2147483648) --> 2147483646 -2 -2\nf(-2147483647,-2147483648) --> 1 -2147483647 -2147483647\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T21:19:39.233",
"Id": "522136",
"Score": "0",
"body": "All `floor_mod`s will return `0` in case of `a == INT_MIN && b == -1`, aren't they? Perhaps it is, as @Quuxplusone said, implementation-defined behavior of `(a ^ b)`. Did you tried functionally identical version with `(a < 0) != (b < 0)` instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T22:19:09.170",
"Id": "522140",
"Score": "0",
"body": "@0dminnimda `a%b` is only defined when `a/b` is defined. Since the quotient `INT_MIN/-1` attempts a quotient more than `INT_MAX`, `INT_MIN%-1` is _undefined behavior_ (UB). I did not try `(a < 0) != (b < 0)`. Easy enough for anyone to try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T22:21:36.233",
"Id": "522141",
"Score": "0",
"body": "well, it looks like `INT_MIN % -1` itself is implementation-defined behavior, because with another compiler this results in a failure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T22:22:51.090",
"Id": "522142",
"Score": "0",
"body": "`I did not try (a < 0) != (b < 0). Easy enough for anyone to try.` this does not change anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T00:38:46.127",
"Id": "522149",
"Score": "0",
"body": "@ReinstateMonica probably some of the code of [this :) answer](https://stackoverflow.com/a/30400252/12141949) will help here. This seems to be a pretty fitting addition. What do you think? :>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T00:41:40.767",
"Id": "522150",
"Score": "0",
"body": "although it is rather unlikely that such values will be passed to the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T03:10:09.833",
"Id": "522154",
"Score": "0",
"body": "@0dminnimda \"INT_MIN % -1 itself is implementation-defined behavior\" --> it is UB. \"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.\" C17dr § 6.5.5 5. Ture that a given implementation may define a result, but it is free to leave it as UB and do whatever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T03:13:08.103",
"Id": "522155",
"Score": "0",
"body": "@0dminnimda \"unlikely that such values will be passed to the function\" is an interesting defense. Intel [tried the 1 in 9 billion](https://en.wikipedia.org/wiki/Pentium_FDIV_bug) augment. Cost $400+ million., Your call. As I try to emphasize, make certain the function is correct, then [maybe](https://stackoverflow.com/questions/385506/when-is-optimisation-premature) optimize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T03:39:10.037",
"Id": "522156",
"Score": "1",
"body": "@ReinstateMonica well, definitely I was checking some small values and it seemed to me that the implementation was correct, just forgot about over/underflow. In any case, I cannot leave undefined behaviour here, it must always match the mathematical model, so this check will eventually end up in the implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T13:57:11.677",
"Id": "524560",
"Score": "0",
"body": "Well, you made the biggest impact on the end result, although the other answer is pretty good too. Therefore, I accept your answer as the most helpful!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T17:45:55.233",
"Id": "264388",
"ParentId": "264340",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "264388",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T00:23:55.330",
"Id": "264340",
"Score": "3",
"Tags": [
"c++",
"performance",
"c"
],
"Title": "floor modulo or modulo rounding towards negative infinity"
}
|
264340
|
<p>I am trying to build a model that allows me to estimate the spread of disease in the population. The setup is similar to the SIR model, with the difference that this model includes the stochastic component.</p>
<p>I have written an algorithm to carry out the simulation, but the lead times are really high. Could you please help me optimize the code? Below is the code.</p>
<pre><code>Population = 100000
Time = 365
r_0 = 0.02
start_positive = 100
min_positive_days = 5
max_positive_days = 15
Pop_over_time <- matrix("S", ncol = Time, nrow = Population, dimnames = list(1:Population, paste0("T",1:Time)))
I0 <- sample(Population, start_positive)
for (i in I0) {
Pop_over_time[i, 1] <- "I"
nr <- trunc(runif(1, min_positive_days, max_positive_days))
Pop_over_time[i, 1:nr] <- "I"
Pop_over_time[i, (nr):(Time)] <- "R"
}
for (i in 2:Time) {
r_s <- r_0 * sqrt(2 + sin(500 + i * 2 * pi / 365)) / 2
for (j in 1:Population) {
if (Pop_over_time[j, i - 1] == "I") {
for (z in (1:k[j])) {
if (Pop_over_time[Link[j, z], i - 1] == "S") {
Pop_over_time[Link[j, z], i] <- rbinom(1, 1, r_s)
if (Pop_over_time[Link[j, z], i] == 1) {
nr <- trunc(runif(1, min_positive_days, max_positive_days))
nr_min <- min((i + nr - 1), Time)
Pop_over_time[Link[j, z], i:nr_min] <-
rep(1, length(i:nr_min))
Pop_over_time[Link[j, z], (nr_min):(Time)] <- "R"
}
}
}
}
}
Pop_over_time[, i][Pop_over_time[, i] == 1] <- "I"
Pop_over_time[, i][Pop_over_time[, i] == 0] <- "S"
}
</code></pre>
<p>In a first part I create a matrix (Link) that defines all the links within the population.
So first I define variables, then I create a matrix that saves, for each day, the situation of the population.
Then I define the first 100 cases (with a sampling) and after that the heaviest part of the code starts. r_s (the probability of contagion) is defined in a seasonal way. So, for each member of the population that I infect I generate a binomial variable for each of his contacts: if the number generated is 1 then the infection has occurred, vice versa not.</p>
<p>Here you can <a href="https://drive.google.com/file/d/18YuLBN0bsbvj8lXMaeZcq4BiC7Yi4OPw/view?usp=sharing" rel="nofollow noreferrer">download the .rdata file to run the code</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T15:28:01.370",
"Id": "522088",
"Score": "0",
"body": "Please follow our guidelines WRT titling your question: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T12:38:37.280",
"Id": "522189",
"Score": "0",
"body": "how we can read the data? `readRDS`?"
}
] |
[
{
"body": "<ol>\n<li>we should remove <code>dimnames</code> from matrix, as it slows sub-setting. They can be added after loops with: <code>dimnames(Pop_over_time) <- list(1:Population, paste0("T",1:Time))</code></li>\n<li>working with characters is slower than integers, so we can replace <code>S/I/R</code> with integers that doesn't interrupt with your current code</li>\n<li><code>rbinom</code> isn't as fast when called millions of times inside for loops. So we can move that one level up, and then in loop get relevant value. Maybe this could be improved even more...</li>\n<li>other minor changes</li>\n</ol>\n<h2 id=\"code\">Code:</h2>\n<pre><code>S = 4L\nI = 5L\nR = 6L\nPop_over_time <- matrix(S, ncol = Time, nrow = Population\n # , dimnames = list(1:Population, paste0("T",1:Time))\n)\n\nfor (i in I0) {\n Pop_over_time[i, 1] <- I\n nr <- trunc(runif(1, min_positive_days, max_positive_days))\n Pop_over_time[i, 1:nr] <- I\n Pop_over_time[i, (nr):(Time)] <- R\n}\n\nfor (i in 2:Time) {\n r_s <- r_0 * sqrt(2 + sin(500 + i * 2 * pi / 365)) / 2\n v1 <- Pop_over_time[, i - 1]\n for (j in 1:Population) {\n if (v1[j] == I) {\n rbin2 <- rbinom(k[j], 1, r_s)\n for (z in (1:k[j])) {\n x1 <- Link[j, z]\n if (v1[x1] == S) {\n Pop_over_time[x1, i] <- rbin2[z]\n if (Pop_over_time[x1, i] == 1) {\n nr <- trunc(runif(1, min_positive_days, max_positive_days))\n nr_min <- min((i + nr - 1), Time)\n Pop_over_time[x1, i:nr_min] <- rep(1, length(i:nr_min))\n Pop_over_time[x1, (nr_min):(Time)] <- R\n }\n }\n }\n }\n }\n Pop_over_time[, i][Pop_over_time[, i] == 1] <- I\n Pop_over_time[, i][Pop_over_time[, i] == 0] <- S\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T14:04:42.600",
"Id": "264418",
"ParentId": "264350",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T11:51:41.287",
"Id": "264350",
"Score": "2",
"Tags": [
"performance",
"r",
"simulation"
],
"Title": "Simulating disease spread in a population"
}
|
264350
|
<p>With my VB.Net Windows Forms application, I would like to rotate and project a 3D object. The program works so far, which is why I'm reporting here and not Stack Overflow, but it's slow.
I've already made two optimizations:</p>
<p><strong>1.)</strong> All points that are on the back of the object, i.e. that cannot be seen, are not drawn. Understandably, this effect does not occur when I look at the hemisphere from above, and with a 90° rotation around the x-axis (side view) 50% of the points are not drawn.</p>
<p><strong>2.)</strong> The calculation runs asynchronously.</p>
<p><strong>2.1)</strong> Since you cannot draw in the PictureBox from another thread, I did some research. <a href="https://stackoverflow.com/questions/53570336/c-sharp-asynchronous-drawing-on-a-panel">This</a> has shown that you draw in a bitmap and assign it to the PictureBox.</p>
<p><strong>3.)</strong> I have already removed the procedure that computes the Cartesian x, y and z and displays it to the user.</p>
<p>Overall, the program runs a little faster; but is still too slow. I would like to leave the step size when calculating the surface points for the first time at 0.5, otherwise you will see gaps. I know that results in 130,320 points on a very small area. That's why I came up with the idea not to draw the back.</p>
<p><strong>What's the point?</strong>
I wanted to code the creation and projection of the object myself, without 3rd party libraries. I also want to add a grid in the future, but for that the program has to be faster first.</p>
<p>Maybe you can help me save a few clock cycles.</p>
<p>Ah, and by the way: I've found that the percentages don't make 100% sense. As you can see here, 49.6% of all points are not drawn (instead of 50%) in the side view.
<a href="https://i.stack.imgur.com/YRh2P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YRh2P.png" alt="Debug" /></a></p>
<p><a href="https://i.stack.imgur.com/PlpEO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PlpEO.png" alt="program 1" /></a>
<a href="https://i.stack.imgur.com/NKVWa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NKVWa.png" alt="program 2" /></a>
<a href="https://i.stack.imgur.com/Ok16t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ok16t.png" alt="program 3" /></a></p>
<p>This is my code of the class</p>
<pre><code>#Disable Warning IDE1006 ' Benennungsstile
#Disable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten
#Disable Warning CA1051 ' Sichtbare Instanzfelder nicht deklarieren
#Disable Warning CA2211 ' Nicht konstante Felder dürfen nicht sichtbar sein
Imports System.Windows.Media.Media3D
Public NotInheritable Class ClassHemisphere
Private ReadOnly enGB As New System.Globalization.CultureInfo("en-GB")
Public Phi As UInt16
Public Theta As UInt16
''' <summary>
''' This list contains all vectors that point from the coordinate origin to the surface.
''' </summary>
Public ReadOnly List_with_all_the_vectors As New List(Of Vector3D)
Private ReadOnly Liste_thetas As New List(Of Double)
Public ReadOnly Liste_phis As New List(Of Double)
''' <summary>
''' The camera position on the z-axis (we look towards the +z arrow).
''' </summary>
Public Camera As Double = 1500.0
''' <summary>
''' The position of the projection window on the z-axis.
''' </summary>
Public Window As Double = 700.0
Private ReadOnly point_of_origin As New PointF(0.0F, 0.0F)
''' <summary>
''' Radius of this hemisphere
''' </summary>
Private ReadOnly Radius As Double
''' <summary>
''' It is to be drawn a 2D line to the point of the set Phi and Theta.
''' </summary>
Private projected_arrow As PointF
''' <summary>
''' in degrees
''' </summary>
Public rotation_angle_x As Double
Public Shared Buffer As System.Drawing.Bitmap
Private Camera_Vector As Vector3D
Public Sub New(ByVal radius As Double)
Me.Radius = radius
Camera_Vector = New Vector3D(0, 0, Camera)
For _phi As Double = 0.0 To 359.5 Step 0.5
For _theta As Double = 0.0 To 90.0 Step 0.5
List_with_all_the_vectors.Add(New Vector3D(
radius * Math.Cos(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),
radius * Math.Sin(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),
radius * Math.Cos(_theta * Math.PI / 180.0)))
Liste_thetas.Add(_theta)
Liste_phis.Add(_phi)
Next
Next
End Sub
Public Function getVector() As Vector3D
Dim Value As Vector3D
For i As Integer = 0 To List_with_all_the_vectors.Count - 1 Step 1
If Liste_phis(i) = CDbl(Phi) AndAlso Liste_thetas(i) = CDbl(Theta) Then
Value = List_with_all_the_vectors(i)
Return Value
End If
Next
Return Value
End Function
Private Shared Function Rotate_around_the_x_axis(ByVal vec As Vector3D, ByVal angle As Double) As Vector3D
Return New Vector3D(vec.X,
vec.Y * Math.Cos(angle * Math.PI / 180.0) - vec.Z * Math.Sin(angle * Math.PI / 180.0),
vec.Y * Math.Sin(angle * Math.PI / 180.0) + vec.Z * Math.Cos(angle * Math.PI / 180.0))
End Function
Public Sub change_Camera_height_a_little(ByVal dz As Double)
Camera += dz
Camera_Vector = New Vector3D(0, 0, Camera)
End Sub
Public Async Function calculate_Async() As Task(Of Boolean)
Return Await Task.Run(Function() Verarbeitung())
End Function
Private Function Verarbeitung() As Boolean
Buffer = Nothing
Dim Counter As Integer = 0
Using _buffer As New System.Drawing.Bitmap(FormMain.PictureBox1.Size.Width, FormMain.PictureBox1.Size.Height)
Using g As System.Drawing.Graphics = Graphics.FromImage(_buffer)
g.TranslateTransform(CSng(_buffer.Size.Width / 2.0F), CSng(_buffer.Size.Height / 2.0F))
g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBilinear
For i As Integer = 0 To List_with_all_the_vectors.Count - 1 Step 1
Dim rotated_vec As Vector3D = Rotate_around_the_x_axis(List_with_all_the_vectors(i), rotation_angle_x)
'Everything that is more than 90° from the camera direction (=back side) does not need to be drawn.
Dim angle_view_to_a_Normal As Double = Vector3D.AngleBetween(Camera_Vector, rotated_vec)
If angle_view_to_a_Normal > 90.0001 Then ' 90.0001 because the precision of a ‘double’ is finite..
Counter += 1 ' for testing purposes
Continue For
End If
Dim Angle_in_degrees As Double = Vector3D.AngleBetween(rotated_vec, New Vector3D(rotated_vec.X, rotated_vec.Y, 0.0))
If Double.IsNaN(Angle_in_degrees) Then
Continue For
End If
Dim vertical_height As Double = Radius * Math.Sin(Angle_in_degrees * Math.PI / 180.0) ' Opposite cathetus
Dim projected_Point As New PointF(
CSng((Camera - Window) / (Camera - vertical_height) * rotated_vec.X),
CSng(-(Camera - Window) / (Camera - vertical_height) * rotated_vec.Y))
Using Pen_DarkBlue As New Pen(Color.FromArgb(0, 0, 122), 1.0F)
g.DrawLine(Pen_DarkBlue, point_of_origin, projected_Point)
End Using
Next
Dim Arrow As Vector3D = Rotate_around_the_x_axis(getVector(), rotation_angle_x)
Dim Angle As Double = Vector3D.AngleBetween(Arrow, New Vector3D(Arrow.X, Arrow.Y, 0.0))
Dim vertical As Double = Arrow.Length * Math.Sin(Angle * Math.PI / 180.0)
projected_arrow = New PointF(
CSng((Camera - Window) / (Camera - vertical) * Arrow.X),
CSng(-(Camera - Window) / (Camera - vertical) * Arrow.Y))
Using Pen_DarkYellow As New Pen(Color.FromArgb(122, 122, 0), 3.0F)
g.DrawLine(Pen_DarkYellow, point_of_origin, projected_arrow)
End Using
Buffer = New Bitmap(_buffer)
End Using
End Using
Debug.WriteLine(Math.Round(Counter / CDbl(List_with_all_the_vectors.Count) * 100.0, 1).ToString(enGB) & " % of all the points are not drawn.")
Return True
End Function
End Class
#Enable Warning IDE1006 ' Benennungsstile
#Enable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten
#Enable Warning CA1051 ' Sichtbare Instanzfelder nicht deklarieren
#Enable Warning CA2211 ' Nicht konstante Felder dürfen nicht sichtbar sein
</code></pre>
<p>And this is Form1.vb</p>
<pre><code>
Public NotInheritable Class FormMain
Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE")
Private hemisphere As ClassHemisphere
Private program_has_finished_loading As Boolean
Private ReadOnly DarkBlue As Color = Color.FromArgb(0, 0, 50)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.FromArgb(160, 176, 167)
TextBox_phi.Text = My.Resources.zero
TextBox_theta.Text = My.Resources.zero
End Sub
Private Async Sub FormMain_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Await Task.Run(Sub() hemisphere = New ClassHemisphere(radius:=350.0))
program_has_finished_loading = True
TextBox_Kamera.Text = Math.Round(hemisphere.Camera, 0).ToString(Deu)
TextBox_Fenster.Text = Math.Round(hemisphere.Window, 0).ToString(Deu)
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End Sub
Private Async Sub FormMain_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyCode
Case Keys.W
If hemisphere.Theta > 0US Then
hemisphere.Theta -= 1US
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End If
Case Keys.S
If hemisphere.Theta < 90US Then
hemisphere.Theta += 1US
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End If
Case Keys.A
If hemisphere.Phi < 360US Then
hemisphere.Phi += 1US
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End If
If hemisphere.Phi = 360US Then hemisphere.Phi = 0US
Case Keys.D
If hemisphere.Phi > 0US Then
hemisphere.Phi -= 1US
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End If
Case Else
Exit Select
End Select
TextBox_theta.Text = hemisphere.Theta.ToString(Deu).PadLeft(2, "0"c) & " °"
TextBox_phi.Text = hemisphere.Phi.ToString(Deu).PadLeft(2, "0"c) & " °"
GC.Collect()
End Sub
'Private Async Sub find_Vector()
' Dim found_Vector As Vector3D = Await find_Vector_Async()
' TextBox_x.Text = Math.Round(found_Vector.X, 3).ToString(Deu)
' TextBox_y.Text = Math.Round(found_Vector.Y, 3).ToString(Deu)
' TextBox_z.Text = Math.Round(found_Vector.Z, 3).ToString(Deu)
'End Sub
'Private Async Function find_Vector_Async() As Task(Of Vector3D)
' Return Await Task.Run(Function() hemisphere.getVector())
'End Function
Private Async Sub Form1_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel
If e.Delta > 0 Then
hemisphere.change_Camera_height_a_little(10.0)
Else
hemisphere.change_Camera_height_a_little(-10.0)
End If
Await hemisphere.calculate_Async()
TextBox_Kamera.Text = Math.Round(hemisphere.Camera, 0).ToString(Deu)
End Sub
Private Sub TextBox_Kamera_TextChanged(sender As Object, e As EventArgs) Handles TextBox_Kamera.TextChanged
If hemisphere IsNot Nothing Then
TextBox_Kamera.ForeColor = If(Double.TryParse(TextBox_Kamera.Text, hemisphere.Camera), DarkBlue, Color.Red)
End If
End Sub
Private Sub TextBox_Fenster_TextChanged(sender As Object, e As EventArgs) Handles TextBox_Fenster.TextChanged
If hemisphere IsNot Nothing Then
Dim successful1 As Boolean = Double.TryParse(TextBox_Kamera.Text, hemisphere.Camera)
Dim window As Double
Dim successful2 As Boolean = Double.TryParse(TextBox_Fenster.Text, window)
If window >= hemisphere.Camera OrElse Not successful1 OrElse Not successful2 Then
TextBox_Fenster.ForeColor = Color.Red
Else
TextBox_Fenster.ForeColor = DarkBlue
hemisphere.Window = window
End If
End If
End Sub
Private Async Sub NumericUpDown_x_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown_x.ValueChanged
hemisphere.rotation_angle_x = NumericUpDown_x.Value
Await hemisphere.calculate_Async()
PictureBox1.Image = ClassHemisphere.Buffer
End Sub
End Class
</code></pre>
|
[] |
[
{
"body": "<p>I can answer my question myself today. I let Visual Studio's own performance profiler work, and it found that most of the clock cycles (93%) are used for <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawline?view=netframework-4.8\" rel=\"nofollow noreferrer\">DrawLine</a>. So, I was looking for a library that was faster. First, I found OpenTK, but had to find out that it is not <code>NET</code> compatible. Then I came across SkiaSharp. After a familiarization phase, I realized that you shouldn't use SkiaSharp's <code>DrawLine</code> here, but <code>DrawPoint</code> (Even better!) because the yellow grid is painted over when you use DrawLine.</p>\n<p>I can click the numeric up-down at normal speed and the picture barely gets stuck (maybe a few hundredths of a millisecond); where I made the grid of the surface <em>smaller</em> beforehand (see step size in the code)!</p>\n<p>Maybe SkiaSharp has a few more tricks, but for today I'm sharing this code with you guys. This is the revised class.</p>\n<pre><code>#Disable Warning IDE1006 ' Benennungsstile\n#Disable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten\n#Disable Warning CA1051 ' Sichtbare Instanzfelder nicht deklarieren\n#Disable Warning CA2211 ' Nicht konstante Felder dürfen nicht sichtbar sein\n\nImports System.Windows.Media.Media3D\nImports SkiaSharp\n\nPublic Class VecThetaPhi\n Public Vect As Vector3D\n Public Theta As Double\n Public Phi As Double\n Public GridVect As Vector3D\n Public Sub New(vec As Vector3D, the As Double, ph As Double, Grid As Vector3D)\n Vect = vec\n Theta = the\n Phi = ph\n GridVect = Grid\n End Sub\nEnd Class\n\nPublic NotInheritable Class ClassHemisphere\n \n Public Phi As UInt16\n Public Theta As UInt16\n ''' <summary>\n ''' This list contains all vectors that point from the coordinate origin to the surface.\n ''' And the related Phi and Theta angles.\n ''' </summary>\n Private ReadOnly LstVecThetaPhi As New List(Of VecThetaPhi)\n\n ''' <summary>\n ''' The camera position on the z-axis (we look towards the +z arrow). \n ''' </summary>\n Public Camera As Double = 1500.0\n ''' <summary>\n ''' The projection window position on the z-axis.\n ''' </summary>\n Public Window As Double = 700.0\n\n Private ReadOnly point_of_origin As New PointF(0.0F, 0.0F)\n ''' <summary>\n ''' Radius of this hemisphere\n ''' </summary>\n Private ReadOnly Radius As Double\n ''' <summary>\n ''' It is to be drawn a 2D line to the point of the set Phi and Theta.\n ''' </summary>\n Private projected_arrow As PointF\n ''' <summary>\n ''' in degrees\n ''' </summary>\n Public rotation_angle_x As Double\n\n Public Shared displayedBitmap As System.Drawing.Bitmap\n Public Camera_Vector As Vector3D\n\n Public Sub New(ByVal radius As Double)\n Me.Radius = radius\n Camera_Vector = New Vector3D(0, 0, Camera)\n For _phi As Double = 0.0 To 359.5 Step 0.25\n For _theta As Double = 0.0 To 90.0 Step 0.25\n Dim vec As New Vector3D(\n radius * Math.Cos(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),\n radius * Math.Sin(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),\n radius * Math.Cos(_theta * Math.PI / 180.0))\n\n Dim GridVec As Vector3D\n If CSng(_theta) = 15.0F OrElse CSng(_theta) = 30.0F OrElse CSng(_theta) = 45.0F OrElse CSng(_theta) = 60.0F Then\n GridVec = New Vector3D(\n radius * Math.Cos(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),\n radius * Math.Sin(_phi * Math.PI / 180.0) * Math.Sin(_theta * Math.PI / 180.0),\n radius * Math.Cos(_theta * Math.PI / 180.0))\n Else\n GridVec = New Vector3D(0R, 0R, 0R)\n End If\n LstVecThetaPhi.Add(New VecThetaPhi(vec, _theta, _phi, GridVec))\n Next\n Next\n End Sub\n\n Public Function getVector(ThetaValue As Double, PhiValue As Double) As Vector3D\n Dim Value As Vector3D = (From item In LstVecThetaPhi\n Where item.Theta = ThetaValue And item.Phi = PhiValue\n Select item.Vect).FirstOrDefault\n Return Value\n End Function\n\n Private Shared Function Rotate_around_the_x_axis(ByVal vec As Vector3D, ByVal angle As Double) As Vector3D\n Return New Vector3D(vec.X,\n vec.Y * Math.Cos(angle * Math.PI / 180.0) - vec.Z * Math.Sin(angle * Math.PI / 180.0),\n vec.Y * Math.Sin(angle * Math.PI / 180.0) + vec.Z * Math.Cos(angle * Math.PI / 180.0))\n End Function\n\n Public Sub change_Camera_height(ByVal dz As Double)\n Camera += dz\n Camera_Vector = New Vector3D(0, 0, Camera)\n End Sub\n\n Public Async Function calculate_Async() As Task(Of Boolean)\n Return Await Task.Run(Function() Verarbeitung())\n End Function\n\n Private Function Verarbeitung() As Boolean\n displayedBitmap = Nothing\n\n Dim imageInfo As New SKImageInfo(FormMain.PictureBox1.Size.Width, FormMain.PictureBox1.Size.Height)\n Using surface As SKSurface = SKSurface.Create(imageInfo)\n Using canvas As SKCanvas = surface.Canvas\n canvas.Translate(300.0F, 300.0F)\n\n Dim DarkBlue As New SKPaint With {\n .TextSize = 64.0F,\n .IsAntialias = True,\n .Color = New SKColor(0, 0, 122),\n .Style = SKPaintStyle.Fill\n }\n\n Dim DarkYellow As New SKPaint With {\n .TextSize = 64.0F,\n .IsAntialias = True,\n .Color = New SKColor(122, 122, 0),\n .Style = SKPaintStyle.Fill\n }\n\n Dim BrightYellow As New SKPaint With {\n .TextSize = 64.0F,\n .IsAntialias = True,\n .Color = New SKColor(255, 255, 77),\n .Style = SKPaintStyle.Fill\n }\n\n Dim Black As New SKPaint With {\n .TextSize = 64.0F,\n .IsAntialias = True,\n .Color = New SKColor(0, 0, 0),\n .Style = SKPaintStyle.Fill\n }\n\n For i As Integer = 0 To LstVecThetaPhi.Count - 1 Step 1\n\n Dim rotated_vec As Vector3D = Rotate_around_the_x_axis(LstVecThetaPhi(i).Vect, rotation_angle_x)\n\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n ' Every point that is more than 90° from the camera direction (=back side) does not need to be drawn. \n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n\n Dim angle_view_to_a_Normal As Double = Vector3D.AngleBetween(Camera_Vector, rotated_vec)\n If angle_view_to_a_Normal > 90.0001 Then ' 90.0001 because the precision of a ‘double’ is finite..\n Continue For\n End If\n\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n ' calculate position, projection, and draw the points.\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n\n Dim Angle_in_degrees As Double = Vector3D.AngleBetween(rotated_vec, New Vector3D(rotated_vec.X, rotated_vec.Y, 0.0))\n If Double.IsNaN(Angle_in_degrees) Then\n Continue For\n End If\n Dim vertical_height As Double = Radius * Math.Sin(Angle_in_degrees * Math.PI / 180.0) ' Opposite cathetus\n Dim projected_Point As New PointF(\n CSng((Camera - Window) / (Camera - vertical_height) * rotated_vec.X),\n CSng(-(Camera - Window) / (Camera - vertical_height) * rotated_vec.Y))\n\n If LstVecThetaPhi(i).GridVect.X = 0.0 AndAlso LstVecThetaPhi(i).GridVect.Y = 0.0 AndAlso LstVecThetaPhi(i).GridVect.Z = 0.0 Then\n canvas.DrawPoint(projected_Point.X, projected_Point.Y, DarkBlue)\n Else\n Dim SKPoints1 As New SKPoint(projected_Point.X + 1.0F, projected_Point.Y + 1.0F)\n Dim SKPoints2 As New SKPoint(projected_Point.X, projected_Point.Y)\n Dim SKPoints3 As New SKPoint(projected_Point.X - 1.0F, projected_Point.Y - 1.0F)\n canvas.DrawPoints(SKPointMode.Lines, {SKPoints1, SKPoints2, SKPoints3}, BrightYellow)\n End If\n\n Next\n\n\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n ' Draw the line which is showing the set Phi and Theta.\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n\n Dim Arrow As Vector3D = Rotate_around_the_x_axis(getVector(CDbl(Me.Theta), CDbl(Me.Phi)), rotation_angle_x)\n Dim Angle As Double = Vector3D.AngleBetween(Arrow, New Vector3D(Arrow.X, Arrow.Y, 0.0))\n Dim vertical As Double = Arrow.Length * Math.Sin(Angle * Math.PI / 180.0)\n projected_arrow = New PointF(\n CSng((Camera - Window) / (Camera - vertical) * Arrow.X),\n CSng(-(Camera - Window) / (Camera - vertical) * Arrow.Y))\n canvas.DrawLine(point_of_origin.X, point_of_origin.Y, projected_arrow.X, projected_arrow.Y, DarkYellow)\n\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n ' get the data into displayedBitmap because the PictureBox is only accepting an usual System.Drawing.Bitmap.\n '–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––\n\n Using image As SKImage = surface.Snapshot()\n Using data As SKData = image.Encode(SKEncodedImageFormat.Png, 100)\n Using mStream As New IO.MemoryStream(data.ToArray())\n displayedBitmap = New Bitmap(mStream, False)\n End Using\n End Using\n End Using\n\n End Using\n End Using\n\n Return True\n End Function\n\nEnd Class\n#Enable Warning IDE1006 ' Benennungsstile\n#Enable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten\n#Enable Warning CA1051 ' Sichtbare Instanzfelder nicht deklarieren\n#Enable Warning CA2211 ' Nicht konstante Felder dürfen nicht sichtbar sein\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/dIJY5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dIJY5.png\" alt=\"the program\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:45:38.313",
"Id": "264426",
"ParentId": "264354",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T15:58:36.673",
"Id": "264354",
"Score": "1",
"Tags": [
"performance",
"asynchronous",
"animation",
"vb.net"
],
"Title": "My 3D to 2D graphics algorithm is being a bit slow"
}
|
264354
|
<p>New Scala dev here. Is there a more idiomatic or efficient way to accomplish this in Scala?</p>
<p>Given a list of the following strings, I need to obtain the unique 'main parts' once any parts including and after a "-" have been removed.</p>
<p>The output should be a list of sorted strings. Also note both ";" and "," have been used as separators.</p>
<p>Input:</p>
<pre><code>val data: List[String] = List(
"W22; O21; B112-WX00BK; G211; B112-WI00BK; G11",
"W22; K122l; B112-WI00BK; O21; B112-WX00BK; G211",
"W21, V32",
"W21, N722",
"S133-VU3150; S133-SU3150; R22-VK3150; R123-VH3"
)
</code></pre>
<p>Desired Output:</p>
<pre><code>List(
B112 G11 G211 O21 W22,
B112 G211 K122l O21 W22,
V32 W21,
N722 W21,
R123 R22 S133
)
</code></pre>
<p>My solution:</p>
<pre><code>def process(input: String): String =
input.split(" ").map(word => {
if (word contains "-")
word.take(word.indexOf("-"))
else word
.replace(";", "").replace(",","")}).toSet.toList.sorted.mkString(" ")
val result: List[String] = data.map(process(_))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T23:09:45.627",
"Id": "522145",
"Score": "0",
"body": "Can you add some more context about why you're doing this? It'd be very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T03:53:49.277",
"Id": "522332",
"Score": "2",
"body": "`data.map(process)` is sufficient."
}
] |
[
{
"body": "<p>Maybe regex to the rescue?</p>\n<pre><code>val formatRegexp = "([A-Za-z0-9]+)(-.*)?[;,]?".r\ndata.map(_.split(" ").map({\n case formatRegexp(value, _*) => value\n case _ => ""\n}).sorted.distinct.mkString(" ") )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T22:54:36.417",
"Id": "522105",
"Score": "1",
"body": "Nice approach. You can use `{}` instead of `({})` for the call to `map`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T23:06:20.547",
"Id": "522144",
"Score": "0",
"body": "I think you can use `formatRegexp.findAllIn(_).group(1)` inside the second call to `map` to make it a little more concise (and hopefully more readable)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:55:33.723",
"Id": "522182",
"Score": "1",
"body": "@user, I think it depends on your personal style. In my opinion, having an explicit way of handling non-matching entries makes it a little bit more maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:20:49.043",
"Id": "522206",
"Score": "1",
"body": "This answer is a little lightweight for a real Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T16:14:53.620",
"Id": "524452",
"Score": "0",
"body": "@vvotan, I really love this solution, but had to choose the other answer. Agree with jwvh, this is a little lightweight."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T20:26:08.290",
"Id": "264358",
"ParentId": "264356",
"Score": "1"
}
},
{
"body": "<p>First of all, the formatting could be a bit better. It's odd to have the first <code>.replace</code> at the same indentation level as <code>else</code>, and you can call <code>map</code> using curly braces if you want a function with multiple statements/expressions instead of making the function result a block. You don't actually <em>need</em> curly braces, but I'd say they're used for multi-line functions more often than are parentheses.</p>\n<pre><code>def process(input: String): String =\n input\n .split(" ")\n .map { word =>\n if (word contains "-")\n word.take(word.indexOf("-"))\n else\n word\n .replace(";", "")\n .replace(",", "")\n }\n .toSet\n .toList\n .sorted\n .mkString(" ")\n</code></pre>\n<p>Using <code>.toSet.toList</code> is unnecessary - you can use <code>.distinct</code> instead. It might be a good idea to make a <code>View</code> after splitting the string to avoid making too many intermediate collections. You'll have to convert it to a <code>Seq</code> before sorting it, though, since <code>sorted</code> isn't defined for views.</p>\n<p>You can also replace <code>;</code> and <code>,</code> using the regex <code>[;,]</code>. You'll need to use <code>replaceAll</code> instead of <code>replace</code> to use regex, though. However, why not include these two when you're splitting? If you do that, each word would only have to be mapped by <code>word => word.takeWhile(_ != '-')</code>, or <code>_.takeWhile(_ != '-')</code>.</p>\n<p>Doing that, we get the following:</p>\n<pre><code>def process(input: String): String =\n input\n .split("[;,] ")\n .view\n .map(_.takeWhile(_ != '-'))\n .distinct\n .toSeq\n .sorted\n .mkString(" ")\n</code></pre>\n<p>This feels like it should do fewer operations than your original, although I'm not sure if <code>_.takeWhile(_ != '-')</code> will be faster than the regex from <a href=\"https://codereview.stackexchange.com/a/264358/222532\">vvotan's answer</a>.</p>\n<p>If your data really is that small, though, efficiency shouldn't matter much. Could you provide some more information on what you're trying to do? Your description doesn't help much, and names such as <code>data</code>, <code>result</code>, <code>input</code>, and <code>process</code> are very generic and won't help readers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T16:13:47.880",
"Id": "524450",
"Score": "0",
"body": "Thank you for the explanation of each change."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T22:59:41.467",
"Id": "264361",
"ParentId": "264356",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264361",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T18:20:42.487",
"Id": "264356",
"Score": "1",
"Tags": [
"beginner",
"strings",
"parsing",
"scala"
],
"Title": "Extracting items from comma/semicolon-delimited strings, discarding parts after a hyphen"
}
|
264356
|
<p>I have been on the C++ learning grind for the last 2 weeks using caveofprogramming videos so don't judge too hard if this seems like a dumb question.</p>
<p>My last lesson covered arrays and the assignment was to make a 10x10 times table using multidimensional arrays. I succeeded in making this times table but with my knowledge I had to type type out each integer. Is this the best way to handle this scenario or is there a way that I could calculate most of the integers without typing out 10 lines of arrays?</p>
<pre><code>#include<iostream>
#include<Windows.h>
using namespace std;
int main() {
int animals[10][10] = {
{1,2,3,4,5,6,7,8,9,10},
{2,4,6,8,10,12,14,16,18,20},
{3,6,9,12,15,18,21,24,27,30},
{4,8,12,16,20,24,28,32,36,40},
{5,10,16,20,25,30,35,40,45,50},
{6,12,18,24,30,36,42,48,54,60},
{7,14,21,28,35,42,49,56,63,70},
{8,16,24,32,40,48,56,64,72,80},
{9,18,27,36,45,54,63,72,81,90},
{10,20,30,40,50,60,70,80,90,100},
};
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << animals[i][j] << " " << flush;
}
cout << endl;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>If you're sure about the data that you want in your array, like the one you mentioned, each row is an arithmetic progression, then this can be done easily using loop.</p>\n<pre><code>int n = 10, m = 10; //you can take this as user input\nint animals[n][m];\nint indexRow, indexColumn;\nfor (indexRow = 0; indexRow < n ; indexRow++) {\n for (indexColumn = 0; indexColumn < m; indexColumn++) {\n animals[indexRow][indexColumn] = (indexRow + 1) + (indexColumn)*(indexRow + 1);\n }\n}\n</code></pre>\n<p>What we have done here is, used formula of <code>nth term</code> of an arithmetic progression while setting values for each row. As you see, first element of each <code>row</code> is <code>it's index number + 1</code>, and <code>nth</code> term in the series is <code>column's index number + 1</code> So we applied the following formula:</p>\n<pre><code>a + (n-1)d\n</code></pre>\n<p>where <code>a</code> is the first term of the series, <code>n</code> refers to the <code>nth</code> term, and <code>d</code> is the common difference.</p>\n<p>After applying the above, we can see the array as:</p>\n<pre><code>for (indexRow = 0; indexRow < n ; indexRow++) {\n for (indexColumn = 0; indexColumn < m; indexColumn++) {\n cout << animals[indexRow][indexColumn] << " " << flush;\n }\n}\n</code></pre>\n<p>which prints expected output.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T06:34:26.043",
"Id": "264368",
"ParentId": "264362",
"Score": "2"
}
},
{
"body": "<p>Even though devRabbit's answer yields the right answer, it makes more sense to me to create a times table with multiplication.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const int n = 10, m = 10;\nint animals[n][m];\nfor(int i = 0; i < n; i++)\n{\n for(int j = 0; j < m; j++)\n {\n animals[i][j] = (i + 1)*(j + 1);\n }\n}\n</code></pre>\n<p>Also, when printing, the numbers will be lined up nicely if you use a tab instead of a space to separate them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T12:18:35.190",
"Id": "522186",
"Score": "0",
"body": "That makes a lot of sense now that I see it. Thank you for the answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T05:08:03.500",
"Id": "264401",
"ParentId": "264362",
"Score": "0"
}
},
{
"body": "<p>The two previous answers create the array at run-time. I want to add the fact that you can use <code>constexpr</code> to compute it at <em>compile time</em> exactly as if you had typed it in.</p>\n<p>Also, <a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You should use just output <code>\\n</code> instead of using <code>endl</code>. And your explicit call to <code>flush</code> is not necessary and just slows it down.</p>\n<p>Don't include <code><windows.h></code> when your code only uses standard C++ and doesn't call any Windows API.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T14:51:34.073",
"Id": "264420",
"ParentId": "264362",
"Score": "1"
}
},
{
"body": "<p><code>animals</code> is an, um, <em>unconventional</em> name for a table of products.</p>\n<p>There doesn't seem to be any compelling need to have the array, though - just print out the values as you reach them:</p>\n<pre><code>for (int i = 1; i <= 10; ++i) {\n for (int j = 1; j <= 10; ++j) {\n std::cout << i * j << " ";\n }\n std::cout << '\\n';\n}\n</code></pre>\n<p>It would be nice to make the numbers line up (since it's supposed to be a <em>table</em>). We can do this using the I/O manipulator <code>std::setw()</code> (found in <code><iomanip></code>). That would give the resulting complete program:</p>\n<pre><code>#include <iomanip>\n#include <iostream>\n\nint main()\n{\n static constexpr int limit = 10;\n for (int i = 1; i <= limit; ++i) {\n for (int j = 1; j <= limit; ++j) {\n std::cout << std::setw(4)\n << i * j;\n }\n std::cout << '\\n';\n }\n}\n</code></pre>\n<p>Some other observations, incorporated above:</p>\n<ul>\n<li>Avoid <code>using namespace std</code>, especially at file scope.</li>\n<li>Returning 0 from <code>main()</code> is optional; in the main function you're allowed to run off the end, and a return value of zero is inferred. That's not allowed in any other value-returning function, of course.</li>\n<li>Prefer to use prefix <code>++</code> and <code>--</code> when the value isn't used. Although that likely doesn't affect your code applying them to <code>int</code>, it can save a costly copy with some types, so it's a good habit to cultivate.</li>\n<li>There's no need to flush the output (with <code>std::flush</code> or <code>std::endl</code>). Just let the buffering do its job.</li>\n<li>When I was at school, multiplication tables went up to 12. Perhaps that's different where/when you are, though (I guess decimal currency reduces the need to have multiples of 11 and 12 learnt by rote?). We can use a named constant so we can easily change the limit and still have a square table.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T15:21:39.187",
"Id": "264422",
"ParentId": "264362",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264368",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T01:10:40.030",
"Id": "264362",
"Score": "1",
"Tags": [
"c++",
"array"
],
"Title": "Print a 10x10 times table"
}
|
264362
|
<p>I am trying to learn Groovy and I did an attempt on implementing a simple Battleship game. Any feedback is welcome. I will start with the modal classes I have.</p>
<p><strong>Modal classes</strong></p>
<p>Coordinate.groovy</p>
<pre><code>package biz.tugay.groovyship.modal
import groovy.transform.Memoized
/**
* A Coordinate represents a certain point.
*
* <pre>
* 0,0 5,0
* .....
* .
* .
* .
* .
* .
* 0,5
* </pre>
*/
class Coordinate
{
final int column
final int row
private Coordinate(int column, int row) {
this.column = column
this.row = row
}
@Memoized
static Coordinate of(int column, int row) {
return new Coordinate(column, row)
}
}
</code></pre>
<p>Ship.groovy</p>
<pre><code>package biz.tugay.groovyship.modal
/**
* A Ship object is represented as a Map of Coordinate:Boolean where the Boolean value represents whether
* the ship coordinate has been hit by a missile or not.
* An example might be: [
* [0,0]:false,
* [1,0]:false,
* [2,0]:true
* ].
* That would be a ship floating horizontally on the first row of a board, where its last piece has been damaged.
*/
class Ship
{
def coordinateIsHitByMissileMap = [:] as Map<Coordinate, Boolean>
Ship(Coordinate... coordinates) {
coordinates.each { this.coordinateIsHitByMissileMap.put(it, false) }
}
}
</code></pre>
<p>Board.groovy</p>
<pre><code>package biz.tugay.groovyship.modal
import biz.tugay.groovyship.commons.GroovyShipConstants
class Board
{
@SuppressWarnings('GrFinalVariableAccess')
final int boardSize
Board(int boardSize) {
if (boardSize < GroovyShipConstants.MINIMUM_BOARD_SIZE) {
throw new IllegalArgumentException("Board size must at least be: $GroovyShipConstants.MINIMUM_BOARD_SIZE")
}
this.boardSize = boardSize
}
def ships = [] as Set<Ship>
def missileAttempts = [] as Set<Coordinate>
}
</code></pre>
<p>The modal classes do not have any business logic - that is on purpose. I want to be able to serialize / deserialize them as I proceed so that I can save the state of the game into a file and then load it back. Although adding methods would still be ok, I find it simpler the classes to be only data, hence my approach.</p>
<p>I also have a commons class I can put here, this class I am planning to extend as well in future.</p>
<p>GroovyShipConstant.groovy</p>
<pre><code>package biz.tugay.groovyship.commons
class GroovyShipConstants
{
public static final int MINIMUM_SHIP_LENGTH = 1
public static final int MAXIMUM_SHIP_LENGTH = 4
public static final int MINIMUM_BOARD_SIZE = 4
}
</code></pre>
<p><strong>Service Classes</strong></p>
<p>ShipService.groovy</p>
<pre><code>package biz.tugay.groovyship.service
import biz.tugay.groovyship.modal.Coordinate
import biz.tugay.groovyship.modal.Ship
import static java.lang.Math.min
import static java.util.concurrent.ThreadLocalRandom.current
import static biz.tugay.groovyship.commons.GroovyShipConstants.*
class ShipService
{
/**
* Creates a {@link biz.tugay.groovyship.modal.Ship} object depending on the board it will be placed in.
*
* The passed in {@code boardSize} ensures the ship randomly generated
* will fit in a board with a size of {@code boardSize}.
*
* @param boardSize The size of the board this ship should successfully can be placed in.
* @return The randomly generated ship.
*/
Ship newRandomShip(int boardSize) {
int shipSize = current().nextInt(MINIMUM_SHIP_LENGTH, 1 + min(boardSize, MAXIMUM_SHIP_LENGTH))
boolean isHorizontal = current().nextBoolean()
int shipCoordinateColumn
int shipCoordinateRow
// Ensure the ship does not exceed the borders of the board
if (isHorizontal) {
shipCoordinateColumn = current().nextInt(boardSize - shipSize + 1)
shipCoordinateRow = current().nextInt(boardSize)
}
else {
shipCoordinateColumn = current().nextInt(boardSize)
shipCoordinateRow = current().nextInt(boardSize - shipSize + 1)
}
// Generate the coordinates of the ship
Coordinate[] coordinates = new Coordinate[shipSize]
(0..<shipSize).each {
coordinates[it] = isHorizontal ?
Coordinate.of(shipCoordinateColumn + it, shipCoordinateRow) :
Coordinate.of(shipCoordinateColumn, shipCoordinateRow + it)
}
new Ship(coordinates)
}
/**
* As per the rule of the game, boundaries of a ship is the location of the ship itself
* and the immediate surroundings of it. A ship with a size of 1 on coordinate 1,1 would
* have boundaries: 0,0 - 0,1 - 0,2 - 1,0 - 1,1 - 1,2 - 2,0 - 2,1 - 2,2
* @param ship The ship the boundaries will be checked.
* @param coordinates The coordinates to check if any of them is in the boundaries of the ship.
* @return Whether any of the coordinates provded is in the boundaries of the ship.
*/
boolean isBoundariesOfShipInCoordinates(Ship ship, Collection<Coordinate> coordinates) {
boolean occupiesCoordinate = false
ship.coordinateIsHitByMissileMap.keySet().each { shipCoordinate ->
(-1..1).each { colIndex ->
(-1..1).each { rowIndex ->
if (coordinates.contains(Coordinate.of(shipCoordinate.column + colIndex, shipCoordinate.row + rowIndex))) {
occupiesCoordinate = true
}
}
}
}
return occupiesCoordinate
}
/**
* @param ship The ship to check.
* @param coordinate The coordinate to check.
* @return Whether a ship immediately occupies the coordinate.
*/
boolean hasPartOnCoordinate(Ship ship, Coordinate coordinate) {
ship.coordinateIsHitByMissileMap.keySet().contains(coordinate)
}
/**
* Updates the state of the ship if the missileCoordinate hits this ship.
* If this ship does not have any parts in the incoming missileCoordinate, this method
* returns false without modifying the state of the {@code ship}.
*
* @param missileCoordinate The coordinates of the incoming missile.
* @return Whether the missile hit the ship or not.
*/
boolean attemptMissileHit(Ship ship, Coordinate missileCoordinate) {
Coordinate coordinate = ship.coordinateIsHitByMissileMap.keySet().find({ it == missileCoordinate })
if (coordinate) {
ship.coordinateIsHitByMissileMap.replace(coordinate, true)
}
coordinate
}
/**
* @return Whether this ship is sank or not.
*/
boolean isSank(Ship ship) {
ship.coordinateIsHitByMissileMap.values().every { it }
}
}
</code></pre>
<p>BoardService.groovy</p>
<pre><code>package biz.tugay.groovyship.service
import biz.tugay.groovyship.modal.Board
import biz.tugay.groovyship.modal.Ship
import biz.tugay.groovyship.modal.Coordinate
class BoardService
{
ShipService shipService = new ShipService()
/**
* Attempts to add the {@code ship} to the board. As per the rules of the game, a ship cannot overlay with
* any other existing ship on the board. Ships also cannot be adjacent to each other.
*
* @param board The board the ship will be added to, potentially having ships already added.
* @param ship The new ship that is being attempted to be added.
* @return Whether ship was added to the board or not.
*/
boolean addShip(Board board, Ship ship) {
def shipCoordinates = ship.coordinateIsHitByMissileMap.keySet()
if (board.ships.any { shipService.isBoundariesOfShipInCoordinates(it, shipCoordinates) }) {
return false
}
board.ships.add(ship)
}
/**
* Sends a missile to to the board. Returns whether it hit a ship or not.
*
* @param board The board the missile be sent to
* @param column The column of the missile
* @param row The row of the missle
* @return Whether a ship was hit or not
*/
boolean missileCoordinate(Board board, int column, int row) {
def missileCoordinate = Coordinate.of(column, row)
board.missileAttempts << missileCoordinate
boolean anyHit = false
board.ships.each { { anyHit = anyHit || shipService.attemptMissileHit(it, missileCoordinate) } }
anyHit
}
/**
* @param board The board to be checked if all ships on the board sank
* @return Whether all ships on the board sank
*/
boolean allShipsSank(Board board) {
board.ships.every { it.coordinateIsHitByMissileMap.values().every { it } }
}
}
</code></pre>
<p>GameService.groovy</p>
<pre><code>package biz.tugay.groovyship.service
import biz.tugay.groovyship.modal.Board
import biz.tugay.groovyship.modal.Ship
/**
* Responsible for creating a new board with the desired size
* and desired number of ships.
*
* This is the only service that should be consumed for creating
* and interacting with the game as it exposes the required methods
* such as sendMissile and allShipsSank.
*/
class GameService
{
ShipService shipService = new ShipService()
BoardService boardService = new BoardService()
Board createNewGame(int boardSize, int numberOfShips) {
Board board = null
int numberOfAttempts = 0
while (!board && ++numberOfAttempts < 100) {
board = boardWithRandomShips(boardSize, numberOfShips)
}
return board
}
boolean sendMissile(Board board, int column, int row) {
boardService.missileCoordinate(board, column, row)
}
boolean allShipsSank(Board board) {
boardService.allShipsSank(board)
}
private Board boardWithRandomShips(int boardSize, int numberOfShips) {
int numberOfAttempts = 0
Board board = new Board(boardSize)
int numberOfShipsPlaced = 0
while (numberOfShipsPlaced < numberOfShips) {
numberOfAttempts++
Ship ship = shipService.newRandomShip(boardSize)
if (boardService.addShip(board, ship)) {
numberOfShipsPlaced++
}
// We are unable to find a way to place $numberOfShips of ships in this board the way we placed
// the existing ships so far. Return null - caller may do another attempt if it wants to.
// The way we place the first few ships will determine whether a solution can be found or not.
if (numberOfAttempts > 100) {
return null
}
}
board
}
}
</code></pre>
<p><strong>Client/Controller</strong></p>
<p>And finally I can share the command line client I have:</p>
<p>CliGameController.groovy</p>
<pre><code>package biz.tugay.groovyship.cli
import biz.tugay.groovyship.modal.Board
import biz.tugay.groovyship.service.GameService
import static java.lang.Integer.parseInt
class CliGameController
{
static GameService gameService = new GameService()
static void main(String[] args) {
Scanner scanner = new Scanner(System.in)
println "Type ng to create a new game at any time or exit to stop playing."
println "Send missile at coordinates in the format: columnIndex,rowIndex."
println "Top left corner is coordinates 0,0"
println "Type ng to start a new game now."
Board board
BoardCommandLinePrinter boardCommandLinePrinter = new BoardCommandLinePrinter()
while (true) {
if (board) {
boardCommandLinePrinter.print(board)
if (gameService.allShipsSank(board)) {
println "Congratulations, you win."
board = null
}
}
if (!board) {
println "Enter one of: ng | exit"
} else {
println "Enter coordinates: 'column,row' to send a missile, 'ng' for a new game, 'exit' to exit."
}
String userInput = scanner.nextLine()
if ("exit" == userInput) {
System.exit(1)
}
else if ("ng" == userInput) {
board = newGameQuestions(scanner)
if (!board) {
println "We could not generate a random board with the provided number of ships in the provided board."
println "Enter a bigger board and less number of ships."
}
}
else {
if (gameService.sendMissile(board, parseInt(userInput[0]), parseInt(userInput[-1]))) {
println "Hit."
} else {
println "Missed."
}
}
}
}
static Board newGameQuestions(Scanner scanner) {
println "Board size?"
int boardSize = parseInt(scanner.nextLine())
println "How many ships?"
int numberOfShips = parseInt(scanner.nextLine())
gameService.createNewGame(boardSize, numberOfShips)
}
}
</code></pre>
<p>BoardCommandLinePrinter.groovy</p>
<pre><code>package biz.tugay.groovyship.cli
import biz.tugay.groovyship.modal.Board
import biz.tugay.groovyship.modal.Coordinate
import biz.tugay.groovyship.modal.Ship
import biz.tugay.groovyship.service.ShipService
class BoardCommandLinePrinter
{
ShipService shipService = new ShipService()
void print(Board board) {
def noAttempt = ' '
def missedAttempt = '-'
def successfulAttempt = '□'
def sankShip = '◼'
print ' '
for (column in 0..<board.boardSize) {
print column + ' '
}
println ''
for (row in 0..<board.boardSize) {
print row + ' '
for (column in 0..<board.boardSize) {
Coordinate coordinate = Coordinate.of(column, row)
Ship shipOnCoordinate = board.ships.find { shipService.hasPartOnCoordinate(it, coordinate) }
if (!board.missileAttempts.contains(coordinate)) {
print noAttempt + ' '
}
else if (!shipOnCoordinate) {
print missedAttempt + ' '
}
else if (shipService.isSank(shipOnCoordinate)) {
print sankShip + ' '
}
else {
print successfulAttempt + ' '
}
}
println ''
}
}
}
</code></pre>
<p>I also have extended test coverage, but I will skip the tests I have.</p>
<p>Any feedback on what can be improved or fixed is welcome.</p>
<p>Portion of a sample run:</p>
<pre><code>Enter coordinates: 'column,row' to send a missile, 'ng' for a new game, 'exit' to exit.
21
Hit.
0 1 2 3
0 - -
1 □ □
2 -
3
Enter coordinates: 'column,row' to send a missile, 'ng' for a new game, 'exit' to exit.
31
Hit.
0 1 2 3
0 - -
1 □ □ □
2 -
3
Enter coordinates: 'column,row' to send a missile, 'ng' for a new game, 'exit' to exit.
01
Hit.
0 1 2 3
0 - -
1 ◼ ◼ ◼ ◼
2 -
3
Congratulations, you win.
Enter one of: ng | exit
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T04:33:09.287",
"Id": "264365",
"Score": "0",
"Tags": [
"groovy",
"battleship"
],
"Title": "Simple battleship game in Groovy"
}
|
264365
|
<p>I'm playing around with understanding array looping speed.
I'm trying to make the contenders equivalent and close to realistic.</p>
<ul>
<li>Is this a good approach?</li>
<li>Are there other iteration approaches to test?</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let suite = new Benchmark.Suite();
const length = 10000;
const arrayToTest = [];
for (let i = 0; i < length; i += 1) {
arrayToTest.push({
a: i,
b: i / 2,
});
}
const methods = {
forForward: (array) => {
const result = [];
for (let i = 0; i < array.length; i += 1) {
const { a, b } = array[i];
result.push(a + b);
}
return result;
},
forReverse: (array) => {
const result = [];
for (let i = array.length - 1; i > 0; i -= 1) {
const { a, b } = array[i];
result.push(a + b);
}
return result;
},
forOf: (array) => {
const result = [];
for (const { a, b } of array) {
result.push(a + b);
}
return result;
},
forEach: (array) => {
const result = [];
array.forEach(({ a, b }) => {
result.push(a + b);
});
return result;
},
map: (array) => {
const result = array.map(({ a, b }) => a + b);
return result;
},
reduce: (array) => {
const result = array.reduce((acc, { a, b }) => {
acc.push(a + b);
return acc;
}, []);
return result;
},
};
Object.entries(methods).forEach(([name, method]) => {
suite = suite.add(name, () => method(arrayToTest));
});
suite
.on('start', () => {
console.log('Running speedtests...');
})
.on('cycle', (event) => {
console.log(` ${event.target}`);
})
.on('complete', function () {
console.log(`\n ${this.filter('fastest').map('name')} is fastest.\n`);
})
.run({ async: false });</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Here are some results with a local node install. I've run them over and over. These console log screenshots are representative of the common result.</p>
<p>When looking at relative performance, I don't understand why <code>map</code> and <code>reduce</code> vary so widely. <code>map</code> is very fast in the thousands, falls off, then makes a comeback when the iterations get higher.</p>
<p>I'm sure other engines will behave differently but I definitely find it curious. Ultimately I'd like to understand this stuff more but for now I'm really wondering if this is a fair comparison test.</p>
<h2 id="iterations-and-theyre-off-everyone-has-a-fast-start">100 iterations (And they're off! Everyone has a fast start)</h2>
<p><a href="https://i.stack.imgur.com/rFj7o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rFj7o.png" alt="100" /></a></p>
<h2 id="iterations-map-takes-the-lead-reduce-blows-a-tire">1,000 iterations (map takes the lead, reduce blows a tire)</h2>
<p><a href="https://i.stack.imgur.com/VYVUW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VYVUW.png" alt="1000" /></a></p>
<h2 id="iterations-map-scrapes-the-wall-and-is-momentarily-stunned">10,000 iterations (map scrapes the wall and is momentarily stunned)</h2>
<p><a href="https://i.stack.imgur.com/fQWoe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fQWoe.png" alt="10000" /></a></p>
<h2 id="iterations-the-race-continues">100,000 iterations (the race continues)</h2>
<p><a href="https://i.stack.imgur.com/fvISK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fvISK.png" alt="100000" /></a></p>
<h2 id="iterations-map-makes-a-comeback">1,000,000 iterations (map makes a comeback)</h2>
<p><a href="https://i.stack.imgur.com/mxRvZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxRvZ.png" alt="10000000" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T12:36:29.153",
"Id": "522188",
"Score": "0",
"body": "One issue is that this isn't a fair comparison, especially the array methods. `map` is used to transform one array to another. `reduce` is for reducing an array to one value. Sure, there are other array methods that \"iterate\" (filter, find, findIndex, etc.), but that's not their purpose. Using them to just iterate is like using a hammer to drive a screw. Also, implementation and performance vary by engine. If you're to compare \"iteration\" only, then only `forEach` is a viable competitor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T17:22:50.543",
"Id": "522203",
"Score": "0",
"body": "@Joseph Thanks for commenting. Your thoughts were exactly my thinking before starting this journey. But, for example, if `map` is always faster (in the javascript engine being used) and speed is the most important factor does it matter if it's meant for a given purpose? Also, how is `forEach` is a viable competitor when it places at the bottom in every single race?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:11:34.107",
"Id": "522205",
"Score": "0",
"body": "Because that's what `forEach` is for, iterating an array of items. The other methods aren't for that purpose, regardless of whether they're faster or not. There's more to code than just speed. Speed makes no sense if a developer ends up spinning their wheels trying to understand why some code was written in a weird way. Also, if were talking about going over an array items, _recursion_ is a glaring omission."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:23:03.230",
"Id": "522207",
"Score": "0",
"body": "All points well taken. Thanks again. \nThe genesis of this question is from a place in our code-base where speed matters more than readability. If no one else chimes in here we'll just move forward with what works in our situation. Not hard to change the code later."
}
] |
[
{
"body": "<h2 id=\"the-real-world-9vr3\">The real world</h2>\n<p>You can test one style against another and learn nothing about which is the more performant.</p>\n<p>Benchmarking JS code only has meaning when you are testing an actual real world example.</p>\n<p>Why, because even the smallest seemingly inconsequential change can effect performance. Things like using a <code>const</code> or a literal, a <code>var</code> or a <code>let</code>, a zero <code>0.0</code> or a zero <code>0</code>, implied <code>!val</code> or explicit <code>val === 0</code></p>\n<p>Worse still, the next browser update can invalidate all the results of previous tests. Yesterday what was the fastest is now the slowest.</p>\n<p>To your question.</p>\n<h2 id=\"apples-and-oranges-tnvl\">Apples and oranges</h2>\n<blockquote>\n<p><em>"Is this a good approach?"</em></p>\n</blockquote>\n<p>No!</p>\n<p>Why. Because you are not testing loops, you are testing accessors. There is a difference in how destructure assignments work and rest parameters work.</p>\n<p>Variables and parameters differ and accessing them by performing operations on them are effected by how they are declared and assigned.</p>\n<p>One must also consider optimizations. Using array map lets the JS know the size of the array and thus eliminates the need to grow the array as items are added. Arrays grow by doubling in size as needed. These memory allocations as the array grows have a significant overhead, more so for small arrays than large.</p>\n<h2 id=\"what-are-you-testing-2xai\">What are you testing</h2>\n<blockquote>\n<p><em>"Are there other iteration approaches to test?"</em></p>\n</blockquote>\n<p>The question I ask is what are you testing. Going by the question's title <code>loop speeds?</code> but going by the code you are testing array copy</p>\n<p>Yes there are alternative tests but first lets change the test.</p>\n<p><strong>Note</strong> I did not use recursive solutions in any tests below because they are SO.. slow. Recursive function use the call stack and push the current function context to that stack each recursion. This is a huge overhead that is not worth benchmarking.</p>\n<h2 id=\"array-copy-5llb\">Array copy</h2>\n<p>We simplify the input array to an array of numbers, and the operation is to create a copy.</p>\n<p><strong>Note</strong> that results of the copy are used to change a global <code>soak</code>. This ensures that the optimizer does not just ignore the function call (Some browser versions do not call functions if they do not change some external state)</p>\n<p>Each method is directed through the function <code>call</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const LENGTH = 1000;\nconst data = new Array(LENGTH).fill(0).map((a,i) => i);\nvar soak = 0;\nfunction call(a, f) { soak += f(a)[Math.random() * LENGTH | 0] }\nconst methods = {\n for(array) {\nconst result = [];\nfor (let i = 0; i < array.length; i += 1) { result.push(array[i]) }\nreturn result;\n },\n forOf(array) {\nconst result = [];\nfor (const a of array) { result.push(a) }\nreturn result;\n },\n forEach(array){\nconst result = [];\narray.forEach(a => result.push(a));\nreturn result;\n },\n map(array){ return array.map(a => a) },\n filter(array) { return array.filter(() => true) },\n spread(array) { return [...array] },\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For 1,000 items</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">spread</td>\n<td style=\"text-align: right;\">0.889µs</td>\n<td style=\"text-align: right;\">±0.886µs</td>\n<td style=\"text-align: right;\">1,124,885</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">653ms</td>\n<td style=\"text-align: right;\">735,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">map</td>\n<td style=\"text-align: right;\">5.822µs</td>\n<td style=\"text-align: right;\">±1.571µs</td>\n<td style=\"text-align: right;\">171,770</td>\n<td style=\"text-align: right;\">15.27%</td>\n<td style=\"text-align: right;\">3,912ms</td>\n<td style=\"text-align: right;\">672,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">filter</td>\n<td style=\"text-align: right;\">7.890µs</td>\n<td style=\"text-align: right;\">±1.729µs</td>\n<td style=\"text-align: right;\">126,740</td>\n<td style=\"text-align: right;\">11.27%</td>\n<td style=\"text-align: right;\">5,854ms</td>\n<td style=\"text-align: right;\">742,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forEach</td>\n<td style=\"text-align: right;\">8.497µs</td>\n<td style=\"text-align: right;\">±1.800µs</td>\n<td style=\"text-align: right;\">117,686</td>\n<td style=\"text-align: right;\">10.46%</td>\n<td style=\"text-align: right;\">5,710ms</td>\n<td style=\"text-align: right;\">672,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">for</td>\n<td style=\"text-align: right;\">8.521µs</td>\n<td style=\"text-align: right;\">±1.829µs</td>\n<td style=\"text-align: right;\">117,353</td>\n<td style=\"text-align: right;\">10.43%</td>\n<td style=\"text-align: right;\">6,502ms</td>\n<td style=\"text-align: right;\">763,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forOf</td>\n<td style=\"text-align: right;\">8.582µs</td>\n<td style=\"text-align: right;\">±1.886µs</td>\n<td style=\"text-align: right;\">116,523</td>\n<td style=\"text-align: right;\">10.36%</td>\n<td style=\"text-align: right;\">5,287ms</td>\n<td style=\"text-align: right;\">616,000</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>For 100,000 items</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">spread</td>\n<td style=\"text-align: right;\">232.411µs</td>\n<td style=\"text-align: right;\">±108.000µs</td>\n<td style=\"text-align: right;\">4,302</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">848ms</td>\n<td style=\"text-align: right;\">3,650</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forOf</td>\n<td style=\"text-align: right;\">1,296.364µs</td>\n<td style=\"text-align: right;\">±874.000µs</td>\n<td style=\"text-align: right;\">771</td>\n<td style=\"text-align: right;\">17.92%</td>\n<td style=\"text-align: right;\">6,417ms</td>\n<td style=\"text-align: right;\">4,950</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">for</td>\n<td style=\"text-align: right;\">1,331.203µs</td>\n<td style=\"text-align: right;\">±770.000µs</td>\n<td style=\"text-align: right;\">751</td>\n<td style=\"text-align: right;\">17.46%</td>\n<td style=\"text-align: right;\">8,520ms</td>\n<td style=\"text-align: right;\">6,400</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forEach</td>\n<td style=\"text-align: right;\">2,731.455µs</td>\n<td style=\"text-align: right;\">±3,096.000µs</td>\n<td style=\"text-align: right;\">366</td>\n<td style=\"text-align: right;\">8.51%</td>\n<td style=\"text-align: right;\">13,521ms</td>\n<td style=\"text-align: right;\">4,950</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">map</td>\n<td style=\"text-align: right;\">3,465.654µs</td>\n<td style=\"text-align: right;\">±2,018.000µs</td>\n<td style=\"text-align: right;\">288</td>\n<td style=\"text-align: right;\">6.69%</td>\n<td style=\"text-align: right;\">18,021ms</td>\n<td style=\"text-align: right;\">5,200</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">filter</td>\n<td style=\"text-align: right;\">4,622.660µs</td>\n<td style=\"text-align: right;\">±1,122.000µs</td>\n<td style=\"text-align: right;\">216</td>\n<td style=\"text-align: right;\">5.02%</td>\n<td style=\"text-align: right;\">22,420ms</td>\n<td style=\"text-align: right;\">4,850</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>To copy an array the spread operator is an order of magnitude faster than any alternative.</p>\n<p><strong>Note</strong> that <code>Array.from(array)</code> is identical to <code>[...array]</code></p>\n<h2 id=\"iterating-rjgq\">Iterating</h2>\n<p>This time lets test the performance of iterators</p>\n<p>The setup</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const LENGTH = 1000;\nconst data = [\nnew Array(LENGTH).fill(0).map(() => Math.random()),\nnew Array(LENGTH).fill(0).map(() => Math.random()),\n];\n\nvar soak = 0;\nfunction call(a, f) { soak += f(a[Math.random() * 2 | 0]) }\nconst methods = {\nforLet(array) {\n var v = 0;\n for (let i = 0; i < array.length; i ++) { v += array[i] }\n return v;\n},\nforVar(array) {\n var v = 0, i = 0;\n for (; i < array.length; i ++) { v += array[i] }\n return v;\n},\nforOf(array) {\n var v = 0;\n for (const a of array) { v += a }\n return v;\n},\nwhile(array) {\n var v = 0, i = array.length;\n while (i-- > 0) { v += array[i] }\n return v;\n},\nforEach(array){\n var v = 0;\n array.forEach(a => v += a);\n return v;\n},\nreducer(array){ \n return array.reduce((v, a) => v + a, 0)\n},\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For 1,000 items.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">forEach</td>\n<td style=\"text-align: right;\">1.764µs</td>\n<td style=\"text-align: right;\">±2.167µs</td>\n<td style=\"text-align: right;\">566,771</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">540ms</td>\n<td style=\"text-align: right;\">306,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forVar</td>\n<td style=\"text-align: right;\">1.807µs</td>\n<td style=\"text-align: right;\">±3.300µs</td>\n<td style=\"text-align: right;\">553,311</td>\n<td style=\"text-align: right;\">97.63%</td>\n<td style=\"text-align: right;\">569ms</td>\n<td style=\"text-align: right;\">315,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">reducer</td>\n<td style=\"text-align: right;\">1.833µs</td>\n<td style=\"text-align: right;\">±3.067µs</td>\n<td style=\"text-align: right;\">545,454</td>\n<td style=\"text-align: right;\">96.24%</td>\n<td style=\"text-align: right;\">567ms</td>\n<td style=\"text-align: right;\">309,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forLet</td>\n<td style=\"text-align: right;\">1.855µs</td>\n<td style=\"text-align: right;\">±3.167µs</td>\n<td style=\"text-align: right;\">539,207</td>\n<td style=\"text-align: right;\">95.14%</td>\n<td style=\"text-align: right;\">568ms</td>\n<td style=\"text-align: right;\">306,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">while</td>\n<td style=\"text-align: right;\">2.248µs</td>\n<td style=\"text-align: right;\">±3.200µs</td>\n<td style=\"text-align: right;\">444,935</td>\n<td style=\"text-align: right;\">78.50%</td>\n<td style=\"text-align: right;\">634ms</td>\n<td style=\"text-align: right;\">282,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forOf</td>\n<td style=\"text-align: right;\">8.405µs</td>\n<td style=\"text-align: right;\">±4.967µs</td>\n<td style=\"text-align: right;\">118,972</td>\n<td style=\"text-align: right;\">20.99%</td>\n<td style=\"text-align: right;\">2,370ms</td>\n<td style=\"text-align: right;\">282,000</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><strong>Note</strong> The order (performance) does not change as the size of the arrays grow in tens above 1000 items.</p>\n<p><strong>Note</strong> that in this case <code>reducer</code> is reasonably competitive.</p>\n<h2 id=\"tiny-changes-xgjy\">Tiny changes</h2>\n<p>What does this teach us. Nothing really, let make a small change and force one array to be integers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const LENGTH = 1000;\nconst data = [\nnew Array(LENGTH).fill(0).map(() => Math.random()),\nnew Array(LENGTH).fill(0).map(() => Math.random() * 100 | 0),\n];\n\nvar soak = 0;\nfunction call(a, f) { soak += f(a) }\nconst methods = {\nforVar(array) {\n var v = 0, i = 0;\n array = array[1];\n for (; i < array.length; i ++) { v += array[i] }\n return v;\n},\nforLet(array) {\n var v = 0;\n array = array[0];\n for (let i = 0; i < array.length; i ++) { v += array[i] }\n return v;\n},\nreducer(array){ \n return array[1].reduce((v, a) => v + a, 0)\n},\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now I can select which array to process as I iterate. I want <code>forVar</code> to be the fastest so it will use the second array the others will use the first.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">Name</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">Call per sec</th>\n<th style=\"text-align: right;\">Rel performance</th>\n<th style=\"text-align: right;\">Total time</th>\n<th style=\"text-align: right;\">Calls</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">forVar</td>\n<td style=\"text-align: right;\">1.261µs</td>\n<td style=\"text-align: right;\">±0.460µs</td>\n<td style=\"text-align: right;\">793,147</td>\n<td style=\"text-align: right;\">100.00%</td>\n<td style=\"text-align: right;\">630ms</td>\n<td style=\"text-align: right;\">500,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">forLet</td>\n<td style=\"text-align: right;\">1.647µs</td>\n<td style=\"text-align: right;\">±0.560µs</td>\n<td style=\"text-align: right;\">607,241</td>\n<td style=\"text-align: right;\">76.56%</td>\n<td style=\"text-align: right;\">873ms</td>\n<td style=\"text-align: right;\">530,000</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">reducer</td>\n<td style=\"text-align: right;\">1.833µs</td>\n<td style=\"text-align: right;\">±0.560µs</td>\n<td style=\"text-align: right;\">545,560</td>\n<td style=\"text-align: right;\">68.78%</td>\n<td style=\"text-align: right;\">862ms</td>\n<td style=\"text-align: right;\">470,000</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Ok you can say the advantage is given to <code>forVar</code> integer math is always faster.</p>\n<p>Is it?? Look at the code again. <code>reducer</code> is also using the second array yet it has gained no advantage.</p>\n<p><sub><strong>NOTE</strong> All test on Chrome 92 (64bit) Win10 Laptop passive cooling.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T01:45:19.110",
"Id": "523389",
"Score": "0",
"body": "Thank you so much for your time @Blindman67. This was enlightening. One thing I've leaned is for codereview the questions should be more specific rather than the more generic wording on stackoverflow. In the real world I'm iterating on arrays of object with varying lengths between 1000-10000. Sometimes I'm adding a key or updating a value, or copying/combining. The example arrays in my code sample were to mimic that a little. Then I picked on of the things I do often \"combining\" and did it similarly for each function. All your points about array copy are well taken, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T01:52:52.777",
"Id": "524389",
"Score": "0",
"body": "As for iteration, I see now that as long as the cleaner (or more more used approach in the codebase) is best as long as it isn't a complete dog. i.e. - don't use forOf but the others are all fine. I've also found, even though Nodejs uses the V8 engine it doesn't perform the same as Chrome or Firefox and I'm sure the results will be even more different on iOS and Android javascript engines (our apps are React Native) so at the end of the day using better data structures and better Big O approaches will lead to bigger gains. I like the idea of benchmarking but see it's limited benefits now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T03:45:10.257",
"Id": "264438",
"ParentId": "264367",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T06:26:38.627",
"Id": "264367",
"Score": "2",
"Tags": [
"javascript",
"array",
"benchmarking"
],
"Title": "Is this a reasonable way to test/compare javascript loop speeds?"
}
|
264367
|
<p>I've been trying to make a rubik's cube project and it succeeds nicely . The only problem(or something like that) is that i need to optimize my code for easier understanding and more flexibility. Here's my code to optimize:</p>
<pre><code>[...]//Code for creating cubes
int main()
{
[...]//some extra codes
while (!glfwWindowShouldClose(window))
{
[...]//more extra codes
cubes.DrawCubes(view, projection);
chk:
if (rSpeed > 90)
{
rSpeed = 90;
}
if (rSpeed < 1)
{
rSpeed = 1;
}
if (90 % rSpeed != 0)
{
if (inc)
rSpeed++;
else if (dec)
rSpeed--;
goto chk;
}
if (cubes.Rot_speed != rSpeed)
{
cubes.SetCubeRotationSpeed(rSpeed);
}
if (RotateX)
{
if (rot_x < 90 / rSpeed)
{
cubes.Rotate(0);
rot_x++;
cubes.Rotating = true;
RotateY = false;
RotateZ = false;
}
else
{
rot_x = 0;
RotateX = false;
cubes.Rotating = false;
}
}
if (RotateY)
{
if (rot_y < 90 / rSpeed)
{
cubes.Rotate(1);
rot_y++;
cubes.Rotating = true;
RotateX = false;
RotateZ = false;
}
else
{
rot_y = 0;
RotateY = false;
cubes.Rotating = false;
}
}
if (RotateZ)
{
if (rot_z < 90 / rSpeed)
{
cubes.Rotate(2);
rot_z++;
cubes.Rotating = true;
RotateY = false;
RotateX = false;
}
else
{
rot_z = 0;
RotateZ = false;
cubes.Rotating = false;
}
}
[...]//more extra codes
}
}
</code></pre>
<p>where rSpeed and cubes.Rot_speed refers to angles for rotation speeds.
The places where I kept <code>[...]</code> are codes unrelated to my question. So please don't mind those .</p>
<p>On function <code>cubes.Rotate()</code>:</p>
<pre><code> void x_Cubes::Rotate(int axis)
{
if (axis == 0)
{
for (auto& mx : m_cubes)
{
if (mx.cellx == m_HCube.cellx)
mx.RotateX();
}
}
else if (axis == 1)
{
for (auto& mx : m_cubes)
{
if (mx.celly == m_HCube.celly)
mx.RotateY();
}
}
else if (axis == 2)
{
for (auto& mx : m_cubes)
{
if (mx.cellz == m_HCube.cellz)
mx.RotateZ();
}
}
}
</code></pre>
<p><code>m_cubes</code> is just a vector of cube data</p>
<p>And the last piece of code :</p>
<pre><code>
void _Rotate(glm::mat4& mat, float ang_x, float ang_y, float ang_z)
{
glm::mat4 transformX = glm::mat4(1.0f);
glm::mat4 transformY = glm::mat4(1.0f);
glm::mat4 transformZ = glm::mat4(1.0f);
transformX = glm::rotate(transformX, glm::radians(ang_x), glm::vec3(1.0f, 0.0f, 0.0f));
transformY = glm::rotate(transformY, glm::radians(ang_y), glm::vec3(0.0f, 1.0f, 0.0f));
transformZ = glm::rotate(transformZ, glm::radians(ang_z), glm::vec3(0.0f, 0.0f, 1.0f));
mat = transformX * transformY * transformZ * mat;
}
void Cube::RotateX()
{
rot_angle_X++;
if (rot_angle_X < (90.0f / rot_speed))
_Rotate(model, rot_speed, 0.0f, 0.0f);
else
{
rot_angle_X = 0.0f;
_Rotate(model, rot_speed, 0.0f, 0.0f);
}
if (rot_angle_X == 90.0f || rot_angle_X == 0.0f)
SwapCellVals(0);
}
void Cube::RotateY()
{
rot_angle_Y++;
if (rot_angle_Y < (90.0f / rot_speed))
_Rotate(model, 0.0f, rot_speed, 0.0f);
else
{
rot_angle_Y = 0.0f;
_Rotate(model, 0.0f, rot_speed, 0.0f);
}
if (rot_angle_Y == 90.0f || rot_angle_Y == 0.0f)
SwapCellVals(1);
}
void Cube::RotateZ()
{
rot_angle_Z++;
if (rot_angle_Z < (90.0f / rot_speed))
_Rotate(model, 0.0f, 0.0f, rot_speed);
else
{
rot_angle_Z = 0.0f;
_Rotate(model, 0.0f, 0.0f, rot_speed);
}
if (rot_angle_Z == 90.0f || rot_angle_Z == 0.0f)
SwapCellVals(2);
}
</code></pre>
<p>Here, <code>x_Cubes</code> is a class that has a vector for storing data of class <code>Cube</code>. The code is too long for rotation and the Booleans are too many for a rotation function. I need to reduce the codes so that i only need to call the function on the main block and flags are only in the rotate function of <code>Cube</code> . I'm using shaders for the drawing actually so i dont know how to actually show the animations properly by reducing the codes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:36:48.080",
"Id": "522122",
"Score": "1",
"body": "My compiler complains when compiling `[...]`. Could you replace it with the actual code? If it is too much to fit, at least link it somewhere else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T05:17:10.943",
"Id": "522157",
"Score": "0",
"body": "i just used `[...]` so that i dont need to add other codes for my question. the codes in `[...]` are unrelated to the question so i didn't keep those"
}
] |
[
{
"body": "<h1 id=\"use-an-enum-class-to-represent-the-axes-zaz4\">Use an <code>enum class</code> to represent the axes</h1>\n<p>Instead of using an <code>int</code>, declare an <a href=\"https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations\" rel=\"nofollow noreferrer\"><code>enum class</code></a> to represent the axes of rotation:</p>\n<pre><code>enum class Axis {X, Y, Z};\n</code></pre>\n<p>Also use <code>switch</code> statements instead of multiple <code>if</code>-statements, like so:</p>\n<pre><code>void x_Cubes::Rotate(Axis axis)\n{\n switch (axis) {\n case Axis::X:\n for (auto& mx : m_cubes)\n if (mx.cellx == m_HCube.cellx)\n mx.RotateX();\n break;\n case Axis::Y:\n ...\n break;\n case Axis::Z:\n ...\n break;\n }\n}\n</code></pre>\n<p>Compilers will be able to warn if you forgot to check for all possible values of <code>axis</code> if you write it like that.</p>\n<h1 id=\"avoid-repeating-yourself-d6iv\">Avoid repeating yourself</h1>\n<p>Having duplicate code to deal with each of the three axes is making the code longer, harder to read and harder to maintain. Ideally, you should write the code in such a way that the axis you want to manipulate is just a parameter, and the code is written in such a way that you completely avoid needing something like <code>switch (axis)</code>. For example, you want something like this to replace the three individual <code>Cube::Rotate*()</code> functions:</p>\n<pre><code>void Cube::Rotate(Axis axis)\n{\n auto index = static_cast<int>(axis);\n rot_angle[index]++;\n\n if (rot_angle[index] >= (90.0f / rot_speed)) {\n rot_angle[index] = 0.0f;\n SwapCellVals(index);\n }\n\n glm::vec3 rot_vec{};\n rot_vec[index] = rot_speed;\n _Rotate(model, rot_vec);\n}\n</code></pre>\n<p>Basically, make everything storing information about each axis indexable, for example by just storing them in an array, or using types that support indexing, like GLM's vector types do. Do this for all the other functions. For example:</p>\n<pre><code>void _Rotate(glm::mat4& mat, glm::vec3 rot_vec)\n{\n for (int i = 3; i--;)\n mat = glm::rotate(mat, glm::radians(rot_vec[i]));\n }\n}\n</code></pre>\n<p>But since you only rotate one axis at a time, the <code>for</code>-loop seems unnecessary, you can just replace it with <code>mat = glm::rotate(math, rot_vec)</code>. And then you can just do this in <code>Cube::Rotate()</code> itself, and remove <code>_Rotate()</code>.</p>\n<h1 id=\"rotation-angle-and-speed-ltqf\">Rotation angle and speed</h1>\n<p>It's a bit weird to see <code>rot_angle</code> being increased by one, and then being compared to <code>90.0f / rot_speed</code>. Why not just add <code>rot_speed</code> to <code>rot_angle</code>?</p>\n<pre><code>void Cube::Rotate(Axis axis)\n{\n auto index = static_cast<int>(axis);\n rot_angle[index] += rot_speed;\n\n if (rot_angle[index] >= 90.0f) {\n ...\n</code></pre>\n<p>Also be aware that floating point errors might accumulate over time, so repeatedly applying small rotations to <code>model</code> might eventually cause it to get into an undesired state. I suggest that when finishing a 90 degree rotation of the cube, you recalculate <code>model</code> from scratch.</p>\n<h1 id=\"use-radians-everywhere-mjve\">Use radians everywhere</h1>\n<p>You can avoid the conversion between degrees and radians by just doing everything in radians. It's really not that hard, and it will clean up your code and make it a bit more efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T02:55:51.763",
"Id": "522153",
"Score": "0",
"body": "Thanks for the suggestion . The only thing I found uneasy was the rotation speed in this . I did not increase the rotation speed with rotation angle . I used the increment function so that the numbers are divisible to 90 and I could get a proper rotation ending ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T13:44:24.543",
"Id": "264378",
"ParentId": "264369",
"Score": "2"
}
},
{
"body": "<h3 id=\"use-enumss-amy3\">Use <code>enums</code>s</h3>\n<p>I totally agree with <a href=\"https://codereview.stackexchange.com/users/129343/g-sliepen\">G. Sliepen</a>, but I should add one more detail: add also None variant, so <code>RotateX</code>/<code>RotateY</code>/<code>RotateZ</code> variables could be represented with only one variable.</p>\n<h3 id=\"dont-put-everything-in-main-function-bmcv\">Don't put everything in <code>main</code> function</h3>\n<p>You will probably need to reuse the code rotating the cube - like adding another cube of something. But when everything happens in main, it is hard to refactor. Create additional class for cube rotations and move all the rotation code there. Use <code>main</code> only to setup the application, start it and handle exit.</p>\n<h3 id=\"instead-of-two-always-opposite-bool-variables-use-one-p3lb\">Instead of two always opposite <code>bool</code> variables, use one</h3>\n<p>It looks <code>inc</code> and <code>dec</code> are designed to be always opposite, or you'll face an endless loop. Remove one of them, say <code>dec</code>; if you need to check specifically <code>dec</code>, just use <code>!inc</code>, but here just use <code>else</code>.</p>\n<h3 id=\"avoid-goto-cjpe\">Avoid <code>goto</code></h3>\n<p>Here, all you need is a loop:</p>\n<pre><code>while(true)\n{\n if (rSpeed > 90)\n {\n rSpeed = 90;\n }\n if (rSpeed < 1)\n {\n rSpeed = 1;\n }\n if (90 % rSpeed != 0)\n {\n if (inc)\n rSpeed++;\n else\n rSpeed--;\n //here we need to repeat the loop - so we'll break it on other branch\n }\n else\n {\n break;\n }\n}\n</code></pre>\n<p>but wait, can <code>rSpeed</code> change to break the margins in a loop? If it reaches 1 or 90, the loop will stop. We can move checks out of the loop, and also use <code>std::max</code> and <code>std::min</code> to prettify them:</p>\n<pre><code>rSpeed = std::min(rSpeed, 90);\nrSpeed = std::max(rSpeed, 1);\nwhile(true)\n{\n if (90 % rSpeed != 0)\n {\n if (inc)\n rSpeed++;\n else\n rSpeed--;\n }\n else\n {\n break;\n }\n}\n</code></pre>\n<p>Do you see now? <code>if</code> checks the condition for the loop to continue - so we can move it into <code>while</code> and remove <code>break</code> branch:</p>\n<pre><code>rSpeed = std::min(rSpeed, 90);\nrSpeed = std::max(rSpeed, 1);\nwhile(90 % rSpeed != 0)\n{\n if (inc)\n rSpeed++;\n else\n rSpeed--;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T08:05:27.443",
"Id": "522159",
"Score": "1",
"body": "https://en.cppreference.com/w/cpp/algorithm/clamp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:18:00.010",
"Id": "522172",
"Score": "0",
"body": "@Pavlo Slavynskyy I agree with you. If possible will you help in reducing(or making efficient) the codes in rotateX/rotateY/rotateZ flags in main function since those are the main hindrances for me right now. the suggestions you and G. Sliepen gave are nice and really helped me in reducing the codes and gave me a better understanding on making code smaller and efficient I cant seem to reduce the codes on those flags and if i do somehow, the whole program doesnt seem to work like I wanted. please help if you can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:29:41.740",
"Id": "522178",
"Score": "0",
"body": "Add the enum and rewrite the code, you will see where you can reduce it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T15:34:41.983",
"Id": "522198",
"Score": "0",
"body": "yeah i edited some places and it did seem short and still works the same. Thanks for mentioning that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T07:59:40.270",
"Id": "264406",
"ParentId": "264369",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T07:45:24.567",
"Id": "264369",
"Score": "3",
"Tags": [
"c++",
"opengl"
],
"Title": "Rubik's Cube rotation with OpenGL"
}
|
264369
|
<blockquote>
<p>The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.</p>
<p>Find the smallest cube for which exactly five permutations of its digits are cube.</p>
</blockquote>
<p>The following code can find find three permutations under a second, but it's taking very long for finding five permutations.</p>
<p>How do I improve runtime?</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python
import itertools
def is_cube(n):
return round(n ** (1 / 3)) ** 3 == n
def main():
found = False
n = 100
while not found:
n += 1
cube = n ** 3
perms = [
int("".join(map(str, a)))
for a in itertools.permutations(str(cube))
]
perms = [perm for perm in perms if len(str(perm)) == len(str(cube))]
filtered_perms = set(filter(is_cube, perms))
if len(filtered_perms) == 5:
found = True
print(filtered_perms)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<h3 id=\"tend-to-use-one-style-opt9\">Tend to use one style</h3>\n<pre><code>perm for perm in perms if len(str(perm)) == len(str(cube))\n</code></pre>\n<p>and</p>\n<pre><code>filter(is_cube, perms)\n</code></pre>\n<p>are almost the same: an iterator that applies some filter. Don't confuse the reader - use the same style for both... or even join them in one expression.</p>\n<h3 id=\"dont-create-collections-until-needed-ong2\">Don't create collections until needed</h3>\n<p><code>perms</code> is a <code>list</code> of permutations. For a 9-digit number there will be roughly 9!=362880 permutations, and they are filtered afterwards. You can use a generator, so all filters will be applied together:</p>\n<pre><code>perms = (int("".join(map(str, a)))\n for a in itertools.permutations(str(cube)))\nperms = (perm for perm in perms if len(str(perm)) == len(str(cube)))\nfiltered_perms = set(filter(is_cube, perms))\n</code></pre>\n<p>First two expressions won't actually do anything; the third will run all the actions because set needs to be populated. So you'll save some memory and allocation/deallocation operations.</p>\n<h3 id=\"use-break-keyword-instead-of-found-variable-3b2n\">Use <code>break</code> keyword instead of <code>found</code> variable</h3>\n<p>Yes, it's not structural, but makes code more readable if there's only one break (or several are located together in a long loop). Instead of setting <code>found = True</code> just <code>break</code> the loop.</p>\n<h3 id=\"use-itertools.count-lbtf\">Use <code>itertools.count </code></h3>\n<p>I think <code>for n in itertools.count(100):</code> looks better than <code>while True:</code> and all operations with n.</p>\n<h3 id=\"algorithm-g8ec\">Algorithm</h3>\n<p>As I've said, there's too many permutations. And then you do extra work because you're checking permutations you've checked again on different numbers. Instead of that, just turn every cube into a kind of fingerprint - a string of sorted digits, <code>''.join(sorted(str(n**3)))</code>, and count the times you've met each fingerprint (it a <code>dict</code> or <code>collections.Counter</code>). All permuted numbers will have the same fingerprint. The only possible problem is when you meet some fingerprint 5 times, you should also check if it won't be met the 6th time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T07:37:58.840",
"Id": "264405",
"ParentId": "264370",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264405",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T08:19:20.403",
"Id": "264370",
"Score": "0",
"Tags": [
"python-3.x",
"programming-challenge"
],
"Title": "Cubic Permutations | Project Euler #62"
}
|
264370
|
<p>This is a custom case insensitive nested dictionary class created by me, its main usage is to populate QTreeWidget and keep track of said QTreeWidget, the main incentive behind this class is to prevent case insensitive duplicates from entering the tree, and to report the indexes of the nested keys (<code>d = {'a': {'a': {'a': {}}}}</code>, <code>fun(['a', 'a', 'a'], d) -> [0, 0, 0]</code>), the three level limit is deliberate, because my tree has exactly three levels.</p>
<p>The class:</p>
<pre class="lang-py prettyprint-override"><code>def Same(one, group):
return next((i for i in group if i.lower() == one.lower()), None)
class TreeDict(dict):
def __init__(self):
super().__init__()
def add(self, arg):
same = Same(arg[0], self)
if not same:
same = arg[0]
self.update({arg[0]: dict()})
if len(arg) >= 2:
rsame = Same(arg[1], self[same])
if not rsame:
rsame = arg[1]
self[same].update({arg[1]: dict()})
if len(arg) == 3:
rrsame = Same(arg[2][0], self[same][rsame])
if not rrsame:
self[same][rsame].update({arg[2][0]: arg[2][1:]})
def getIndex(self, arg):
indexes = list()
same = Same(arg[0], self)
if same:
i = list(self).index(same)
indexes.append(i)
else:
return None
if len(arg) >= 2:
rsame = Same(arg[1], self[same])
if rsame:
j = list(self[same]).index(rsame)
indexes.append(j)
else:
return None
if len(arg) == 3:
rrsame = Same(arg[2], self[same][rsame])
if rrsame:
k = list(self[same][rsame]).index(rrsame)
indexes.append(k)
else:
return None
return indexes
def getValue(self, arg):
result = self.copy()
same = Same(arg[0], result)
if same:
result = result[same]
else:
return None
if len(arg) >= 2:
rsame = Same(arg[1], result)
if rsame:
result = result[rsame]
else:
return None
if len(arg) == 3:
rrsame = Same(arg[2], result)
if rrsame:
result = result[rrsame]
else:
return None
return result
def delete(self, arg):
same = Same(arg[0], self)
if not same:
return
if len(arg) == 1:
self.pop(same)
if len(arg) >=2:
rsame = Same(arg[1], self[same])
if not rsame:
return
if len(arg) == 2:
self[same].pop(rsame)
if len(arg) == 3:
rrsame = Same(arg[2], self[same][rsame])
if not rrsame:
return
self[same][rsame].pop(rrsame)
def treefy(self, data):
self.clear()
for i in data:
self.add([i.artist, i.album, [i.title, *(getattr(i, j) for j in fields[3:])]])
</code></pre>
<p>The last function is how the tree is filled, <code>fields</code> is a <code>list</code> of <code>str</code>s containing the attribute names of a <code>namedtuple</code> class, and <code>data</code> is a <code>list</code> of said <code>namedtuple</code>s.</p>
<p>As you can see from the code, you can also access the nested keys by inputting a list containing the keys.</p>
<p>I will provide some examples to demonstrate what it does:</p>
<pre class="lang-py prettyprint-override"><code>test1 = TreeDict()
from itertools import product
string = 'abcdABCD'
for i, j, k in product(string, repeat=3):
test1.add([i, j, [k, *map(string.index, (i, j, k))]])
</code></pre>
<p>Because the output is long (64 entries) I wouldn't post it here, and everything is working correctly, if you run the loop the second time it does nothing, and as you can see there isn't a single uppercase letter.</p>
<p>Now I package the loop in a function:</p>
<pre class="lang-py prettyprint-override"><code>def test1():
tree = TreeDict()
for i, j, k in product(string, repeat=3):
tree.add([i, j, [k, *map(string.index, (i, j, k))]])
return tree
</code></pre>
<p>Performance:</p>
<pre class="lang-py prettyprint-override"><code>%timeit test1()
2.26 ms ± 306 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>Now the same structure can be achieved by this:</p>
<pre class="lang-py prettyprint-override"><code>from collections import defaultdict
def test2():
tree = defaultdict(lambda: defaultdict(dict))
for i, j, k in product(string, repeat=3):
tree[i][j][k] = list(map(string.index, (i, j, k)))
return tree
</code></pre>
<p>As you can see, test2 returns 512 entries and contains all the upper case letters, and that is exactly why I wrote the case insensitive nested dictionary in the first place.</p>
<p>But wait, there is more:</p>
<p>The inferior method is tremendously faster than my superior approach:</p>
<pre><code>%timeit test2()
477 µs ± 23.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code></pre>
<p>From multiple tests, <code>test2</code> is approximately 75% faster than <code>test1</code> if we only count execution time, and let's not forget that test2 returns 512 entries while test1 returns only 64 entries, so test2 can add 64 entries in about 3.125% the time took test1 to complete!</p>
<p>Now let's take the tests to insane levels:</p>
<pre class="lang-py prettyprint-override"><code>from string import ascii_letters
def test1():
tree = TreeDict()
for i, j, k in product(ascii_letters, repeat=3):
tree.add([i, j, [k, *map(ascii_letters.index, (i, j, k))]])
return tree
def test2():
tree = defaultdict(lambda: defaultdict(dict))
for i, j, k in product(ascii_letters, repeat=3):
tree[i][j][k] = list(map(ascii_letters.index, (i, j, k)))
return tree
</code></pre>
<p><code>test1</code> returns only 17576 entries, and <code>test2</code> returns a grand total of 140608 entries.</p>
<p>Performance:</p>
<pre><code>%timeit test1()
1.24 s ± 19.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit test2()
150 ms ± 2.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p><code>test1</code> takes approximately 1.25s to complete, while <code>test2</code> takes approximately 0.15s to complete.</p>
<p>So test1 is approximately 1.25/0.15*140608/17576 = 66.66 times slower than test2!</p>
<p>How can my code be optimized?</p>
<hr />
<p>I have been thinking about creating another flat dictionary subclass, in which the keys are stored in a separate dictionary as values, and their keys are the lowercases of them.</p>
<p>So that I can make it add new keys only if the lowercase of the key is not found in the other dict, and modify the key that equals the value of the lower case of the key in the other dict...</p>
<p>Sort of like this:</p>
<pre><code>class something(dict):
def __init__(self):
super().__init__()
self.shadow = dict()
def update(self, ?):
if key.lower() not in self.shadow:
self.shadow.update({key.lower(): key})
self.update({key: val})
else:
k = self.shadow.get(key.lower())
self.update({k: val})
</code></pre>
<p>If I can implement it correctly, this will significantly improve performance, but I don't know how to get the keys and values from the argument, and really don't know how to properly override the methods (<code>.get()</code>, <code>.update()</code>, <code>.pop()</code> etc.)...</p>
<p>Can anyone help me?</p>
<hr />
<p>OK I will give you some more details to give you more understanding on the circumstances.</p>
<p>Long story short, I have been using a online music service, it allows users to post comments and the comments are terribly disgusting at best, they are completely off topic and blah blah blah, what makes me keep using it is its music recommendation functionality.</p>
<p>Supposedly it can recommend music for you based on your personal preferences, but in reality it misses more often than it hits, about up to a third in its daily recommendations are actually what I like, the others range from meh to disgusting, I kept using it until this year, when everything it recommends are unbearably disgusting.</p>
<p>But I have used it long enough to have so many songs in my playlists in my account there (about 4500), and I don't want to lose the songs, so I want to download them before I delete my account there.</p>
<p>And I scraped all the songs I have there and stored the entries in a MySQL database, and have found ways to programmatically download the songs...</p>
<p>But, the artist, album and song names are all user contributed, and the average English level of the Chinese contributors is below average at best, and inconsistency is abundant.</p>
<p>Same artists are credited in multiple languages, same artist's name with a typo is credited as another artist, same artist with the letters in another case? A different artist. Same artist with and without surname? Two distinct artists. Same album of the same artist with the case of one letter changed by a typo? Two albums.</p>
<p>To give you some more examples:</p>
<pre class="lang-py prettyprint-override"><code>In [1]: import json
In [2]: import mysql.connector
In [3]: import requests
In [4]: conn = mysql.connector.connect(
...: user="Estranger", password=PWD, host="127.0.0.1", port=3306, database="Music"
...: )
...: cursor = conn.cursor()
In [5]: cursor.execute('select `artist link` from songs where artist = "Alexandrov Ensemble"')
In [6]: len(cursor.fetchall())
Out[6]: 32
In [7]: cursor.execute('select distinct `artist link` from songs where artist = "Alexandrov Ensemble"')
In [8]: ex = cursor.fetchall()
In [9]: len(ex)
Out[9]: 8
In [10]: ex
Out[10]:
[('https://music.163.com/#/artist?id=46364372',),
('https://music.163.com/#/artist?id=13046141',),
('https://music.163.com/#/artist?id=34499408',),
('https://music.163.com/#/artist?id=13045063',),
('https://music.163.com/#/artist?id=13924079',),
('https://music.163.com/#/artist?id=13042166',),
('https://music.163.com/#/artist?id=12914133',),
('https://music.163.com/#/artist?id=990252',)]
In [11]: for i in ex:
...: print(json.loads(requests.get('http://music.163.com/api/artist/%s' % i[0].split('=')[1]).text)['artist']['name'])
俄罗斯军队模范亚历山德罗夫红旗歌舞团
Chœurs de l'armée sovietique
Orchestre Alexsandrov
The Red Army Choir
Les Choeurs De L'Armée Rouge
The Red Army Choir
Alexandrow-Ensemble - Chor Der Roten Armee
俄罗斯军乐团
</code></pre>
<pre class="lang-py prettyprint-override"><code>In [1]: import mysql.connector
In [2]: from collections import defaultdict
In [3]: conn = mysql.connector.connect(
...: user="Estranger", password=PWD, host="127.0.0.1", port=3306, database="Music"
...: )
...: cursor = conn.cursor()
In [4]: cursor.execute('select distinct artist from songs')
In [5]: artists = cursor.fetchall()
In [6]: len(artists)
Out[6]: 1645
In [7]: dic = defaultdict(list)
In [8]: for i in artists:
...: cursor.execute('select distinct `artist link` from songs where artist = "%s"' % i[0])
...: links = cursor.fetchall()
...: for j in links:
...: dic[i[0]].append(j)
In [9]: for i in artists:
...: if len(dic[i[0]]) > 1:
...: print(i[0])
Alex Blue
Alexandrov Ensemble
André Rieu
Chloë Agnew
Chöre der Arbeiterfestspiele
Céline Roscheck
Declan Galbraith
Dirk Reichardt
Grzegorz Mazur
Immediate Music
Les Choeurs Révolutionnaires
Martian
Nick Glennie—Smith
Tony Anderson
Various Artists
</code></pre>
<p>And the above are only about artists, and these are only the ones I have currently corrected (there are many more).</p>
<p>And there is one artist called 'SYML' with only one artist id, but credited as both 'SYML' and 'syml', and there is an album of artist 'Roberto Cacciapaglia', appeared as both 'Quarto Tempo' and 'Quarto tempo', and there are many songs with same title, album and artist because same songs got submitted by different users...</p>
<p>And I need the integer indexes because I need the coordinated to locate items in the tree, the tree is structured this way: artist\album\title, and items are located this way <code>tree.topLevelItem(0).child(0).child(0)</code>, so I need to get integer indices from the names.</p>
<p>And I need the entries unique and consistent.</p>
<p>And I plan to download them and store the songs this way:</p>
<p><code>f"{BASEFOLDER}\\{artist}\\{album}\\{artist} - {title}.mp3"</code></p>
<p>In perfect synchronization with the tree and database, and windows paths are case-insensitive, all the more reasons to make a case insensitive, duplicate not allowed, auto-correcting and ordered data class.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:03:25.320",
"Id": "522118",
"Score": "0",
"body": "`treefy` won't run; `fields` is undefined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:14:46.370",
"Id": "522119",
"Score": "4",
"body": "I'm afraid that none of this makes sense to me. If `The inferior method is tremendously faster than my superior approach`, and the \"inferior\" method is both equivalent and expressed in a fraction of the code length, then how is your approach superior?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:17:37.803",
"Id": "522120",
"Score": "0",
"body": "Why are the dictionaries nested at all? Are you just looking to have a single, triple-indexed dictionary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:22:35.553",
"Id": "522121",
"Score": "0",
"body": "And will your indexes always be one character? If not, this question is too theoretical and you need to show realistic examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T17:53:11.003",
"Id": "522124",
"Score": "0",
"body": "Also very confused. Don't understand the purpose of your `getIndex` method -- why would you ever want the index of a dictionary key? Don't understand why you would want your `add` method to leave the dictionary entirely unchanged if a key entered in `add` already exists in the dictionary. I can think of some significant speed boosts here but we need some more information..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T19:01:41.680",
"Id": "522128",
"Score": "0",
"body": "It seems like you solved your problem. Use the builtin `defaultdict` which is designed for this precise purpose (seemingly, details are unclear)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T15:10:30.110",
"Id": "522291",
"Score": "0",
"body": "Let's discuss this in https://chat.stackexchange.com/rooms/127945/python-case-insensitive-three-level-nested-dictionary"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T08:42:59.777",
"Id": "264371",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x"
],
"Title": "Python case insensitive three level nested dictionary"
}
|
264371
|
<p>Im just trying to setup my shader function in a class in a way that would make me work with it easier and in a more understandable way.</p>
<p>In Shader.h:</p>
<pre><code>#pragma once
#include"Includes.h"
#include<unordered_map>
namespace GAME
{
enum class Shader_Type
{
NONE = -1,
VERTEX = 0,
FRAGMENT = 1,
GEOMETRY = 2
};
class Shader
{
private:
std::map<Shader_Type, std::string>m_Data;
Shader_Type type;
std::unordered_map<std::string, int> m_UniformLocationCache;
public:
unsigned int Program_id;
private:
unsigned int Compiler(unsigned int type, const std::string& source);
void Check_errors(unsigned int* id, unsigned int type);
void Create_shader();
public:
Shader();
~Shader();
Shader(const Shader& e);
Shader& operator=(const Shader& e);
Shader(Shader&& e)noexcept;
Shader& operator=(Shader&& e)noexcept;
Shader* operator-> () { return this; }
operator Shader* () { return this; }
Shader* Clone() { return new Shader(*this); }
void Bind() const;
void Unbind() const;
void Reset();
void Init(std::string vertexShader = "", std::string fragmentshader = "", std::string Geometryshader = "");
unsigned int GetUniformLocation(const std::string& name);
//uniforms
void Setuniform1f(const std::string& name, float v1);
void Setuniform2f(const std::string& name, float v1, float v2);
void Setuniform3f(const std::string& name, float v1, float v2, float v3);
void Setuniform4f(const std::string& name, float v1, float v2, float v3, float v4);
void Setuniform1i(const std::string& name, int v1);
void Setuniform2i(const std::string& name, int v1, int v2);
void Setuniform3i(const std::string& name, int v1, int v2, int v3);
void Setuniform4i(const std::string& name, int v1, int v2, int v3, int v4);
void Setuniform1d(const std::string& name, double v1);
void Setuniform2d(const std::string& name, double v1, double v2);
void Setuniform3d(const std::string& name, double v1, double v2, double v3);
void Setuniform4d(const std::string& name, double v1, double v2, double v3, double v4);
void Setuniform1fv(const std::string& name, int count, glm::fvec1 v);
void Setuniform2fv(const std::string& name, int count, glm::fvec2 v);
void Setuniform3fv(const std::string& name, int count, glm::fvec3 v);
void Setuniform4fv(const std::string& name, int count, glm::fvec4 v);
void Setuniform1iv(const std::string& name, int count, glm::ivec1 v);
void Setuniform2iv(const std::string& name, int count, glm::ivec2 v);
void Setuniform3iv(const std::string& name, int count, glm::ivec3 v);
void Setuniform4iv(const std::string& name, int count, glm::ivec4 v);
void Setuniform1dv(const std::string& name, int count, glm::dvec1 v);
void Setuniform2dv(const std::string& name, int count, glm::dvec2 v);
void Setuniform3dv(const std::string& name, int count, glm::dvec3 v);
void Setuniform4dv(const std::string& name, int count, glm::dvec4 v);
void SetUniformMat2fv(const std::string& name, int count, GLboolean transpose, glm::mat2 value);
void SetUniformMat3fv(const std::string& name, int count, GLboolean transpose, glm::mat3 value);
void SetUniformMat4fv(const std::string& name, int count, GLboolean transpose, glm::mat4 value);
};
}
</code></pre>
<p><code>#include"Includes.h"</code> is the header where I kept all includes of gl and other required classes</p>
<p>In Shader.cpp:</p>
<pre><code>#include "Shader.h"
namespace GAME
{
Shader::Shader()
:Program_id(0), type(Shader_Type::NONE)
{
}
Shader::~Shader()
{
}
Shader::Shader(const Shader& e)
{
this->m_Data = e.m_Data;
this->m_UniformLocationCache = e.m_UniformLocationCache;
this->Program_id = e.Program_id;
this->type = Shader_Type(e.type);
}
Shader& Shader::operator=(const Shader& e)
{
this->m_Data = e.m_Data;
this->m_UniformLocationCache = e.m_UniformLocationCache;
this->Program_id = e.Program_id;
this->type = Shader_Type(e.type);
return *this;
}
Shader::Shader(Shader&& e) noexcept
{
this->m_Data = std::move(e.m_Data);
this->m_UniformLocationCache = std::move(e.m_UniformLocationCache);
this->Program_id =std::move( e.Program_id);
this->type = std::move(Shader_Type(e.type));
}
Shader& Shader::operator=(Shader&& e) noexcept
{
this->m_Data = std::move(e.m_Data);
this->m_UniformLocationCache = std::move(e.m_UniformLocationCache);
this->Program_id = std::move(e.Program_id);
this->type = std::move(Shader_Type(e.type));
return *this;
}
void Shader::Bind() const
{
glUseProgram(Program_id);
}
void Shader::Unbind() const
{
glUseProgram(0);
}
void Shader::Reset()
{
this->type = Shader_Type::NONE;
this->Program_id = 0;
this->m_UniformLocationCache.clear();
this->m_Data.clear();
}
void Shader::Init(std::string vertexShader, std::string fragmentshader, std::string Geometryshader)
{
m_Data[Shader_Type::VERTEX] = vertexShader;
m_Data[Shader_Type::FRAGMENT] = fragmentshader;
m_Data[Shader_Type::GEOMETRY] = Geometryshader;
Create_shader();
Unbind();
}
unsigned int Shader::GetUniformLocation(const std::string& name)
{
if (m_UniformLocationCache.find(name) != m_UniformLocationCache.end())
{
return m_UniformLocationCache[name];
}
int location = glGetUniformLocation(Program_id, name.c_str());
if (location == -1)
{
std::cout << "Warning! Uniform " << name << " is unused or not found or does no exist!" << std::endl;
}
else
m_UniformLocationCache[name] = location;
return location;
}
void Shader::Create_shader()
{
Program_id = glCreateProgram();
if (m_Data[Shader_Type::VERTEX] != "")
{
unsigned int vs = Compiler(GL_VERTEX_SHADER, m_Data[Shader_Type::VERTEX]);
glAttachShader(Program_id, vs);
glDeleteShader(vs);
}
if (m_Data[Shader_Type::FRAGMENT] != "")
{
unsigned int fs = Compiler(GL_FRAGMENT_SHADER, m_Data[Shader_Type::FRAGMENT]);
glAttachShader(Program_id, fs);
glDeleteShader(fs);
}
if (m_Data[Shader_Type::GEOMETRY] != "")
{
unsigned int gs = Compiler(GL_GEOMETRY_SHADER, m_Data[Shader_Type::GEOMETRY]);
glAttachShader(Program_id, gs);
glDeleteShader(gs);
}
glLinkProgram(Program_id);
glValidateProgram(Program_id);
}
unsigned int Shader::Compiler(unsigned int type, const std::string& source)
{
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
Check_errors(&id, type);
return id;
}
void Shader::Check_errors(unsigned int* id, unsigned int type)
{
int result;
glGetShaderiv(*id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
glGetShaderiv(*id, GL_INFO_LOG_LENGTH, &length);
char* message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(*id, length, &length, message);
std::cout << "Failed to compile ";
switch (type)
{
case GL_VERTEX_SHADER:
std::cout << "vertex";
break;
case GL_FRAGMENT_SHADER:
std::cout << "fragment";
break;
case GL_GEOMETRY_SHADER:
std::cout << "geometry";
break;
default:
std::cout << "unknown";
break;
}
std::cout << " shader!" << std::endl;
std::cout << " Error:" << message << std::endl;
glDeleteShader(*id);
id = 0;
}
}
void Shader::Setuniform1f(const std::string& name, float v1)
{
glUniform1f(GetUniformLocation(name), v1);
}
void Shader::Setuniform2f(const std::string& name, float v1, float v2)
{
glUniform2f(GetUniformLocation(name), v1, v2);
}
void Shader::Setuniform3f(const std::string& name, float v1, float v2, float v3)
{
glUniform3f(GetUniformLocation(name), v1, v2, v3);
}
void Shader::Setuniform4f(const std::string& name, float v1, float v2, float v3, float v4)
{
glUniform4f(GetUniformLocation(name), v1, v2, v3, v4);
}
void Shader::Setuniform1i(const std::string& name, int v1)
{
glUniform1i(GetUniformLocation(name), v1);
}
void Shader::Setuniform2i(const std::string& name, int v1, int v2)
{
glUniform2i(GetUniformLocation(name), v1, v2);
}
void Shader::Setuniform3i(const std::string& name, int v1, int v2, int v3)
{
glUniform3i(GetUniformLocation(name), v1, v2, v3);
}
void Shader::Setuniform4i(const std::string& name, int v1, int v2, int v3, int v4)
{
glUniform4i(GetUniformLocation(name), v1, v2, v3, v4);
}
void Shader::Setuniform1d(const std::string& name, double v1)
{
glUniform1d(GetUniformLocation(name), v1);
}
void Shader::Setuniform2d(const std::string& name, double v1, double v2)
{
glUniform2d(GetUniformLocation(name), v1, v2);
}
void Shader::Setuniform3d(const std::string& name, double v1, double v2, double v3)
{
glUniform3d(GetUniformLocation(name), v1, v2, v3);
}
void Shader::Setuniform4d(const std::string& name, double v1, double v2, double v3, double v4)
{
glUniform4d(GetUniformLocation(name), v1, v2, v3, v4);
}
void Shader::Setuniform1fv(const std::string& name, int count, glm::fvec1 v)
{
glUniform1fv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform2fv(const std::string& name, int count, glm::fvec2 v)
{
glUniform2fv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform3fv(const std::string& name, int count, glm::fvec3 v)
{
glUniform3fv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform4fv(const std::string& name, int count, glm::fvec4 v)
{
glUniform4fv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform1iv(const std::string& name, int count, glm::ivec1 v)
{
glUniform1iv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform2iv(const std::string& name, int count, glm::ivec2 v)
{
glUniform2iv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform3iv(const std::string& name, int count, glm::ivec3 v)
{
glUniform3iv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform4iv(const std::string& name, int count, glm::ivec4 v)
{
glUniform4iv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform1dv(const std::string& name, int count, glm::dvec1 v)
{
glUniform1dv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform2dv(const std::string& name, int count, glm::dvec2 v)
{
glUniform2dv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform3dv(const std::string& name, int count, glm::dvec3 v)
{
glUniform3dv(GetUniformLocation(name), count, &v[0]);
}
void Shader::Setuniform4dv(const std::string& name, int count, glm::dvec4 v)
{
glUniform4dv(GetUniformLocation(name), count, &v[0]);
}
void Shader::SetUniformMat2fv(const std::string& name, int count, GLboolean transpose, glm::mat2 value)
{
glUniformMatrix2fv(GetUniformLocation(name), count, transpose, &value[0][0]);
}
void Shader::SetUniformMat3fv(const std::string& name, int count, GLboolean transpose, glm::mat3 value)
{
glUniformMatrix3fv(GetUniformLocation(name), count, transpose, &value[0][0]);
}
void Shader::SetUniformMat4fv(const std::string& name, int count, GLboolean transpose, glm::mat4 value)
{
glUniformMatrix4fv(GetUniformLocation(name), count, transpose, &value[0][0]);
}
}
</code></pre>
<p>Is this enough for using in normal programming or do i need to make some changes to make it more usable and efficient? Any helpful review would be appreciated. Thanks in advance!!</p>
|
[] |
[
{
"body": "<p>Various suggestions:</p>\n<ul>\n<li><p>Use the OpenGL types (e.g. <code>GLuint</code>, <code>GLint</code>) for the variables that need them. It's more portable, and the purpose of the variables is clearer.</p>\n</li>\n<li><p>Don't store the shader source inside the shader. We don't need it after compiling the shader.</p>\n</li>\n<li><p>It doesn't look like the <code>type</code> member variable is actually used (and it doesn't make sense as programs are made up of shader objects of various different types).</p>\n</li>\n<li><p>The <code>Program_id</code> shouldn't be public, as the user shouldn't be able to change it directly. Add a getter function for it.</p>\n</li>\n<li><p>We should destroy the shader program with <code>glDeleteProgram</code> when we're done with it (i.e. in the destructor).</p>\n</li>\n<li><p>Copying a shader program doesn't really make sense from an OpenGL point of view... there's no way to copy OpenGL shaders or shader objects. So I'd suggest <code>=delete</code>ing the copy constructor and copy assignment operator, and only supporting move operations.</p>\n</li>\n<li><p>We don't need <code>operator-></code> or <code>operator*</code> or the <code>Clone()</code> function (and they don't really make sense).</p>\n</li>\n<li><p>I don't think there's any point in caching uniform locations in a map keyed by a <code>std::string</code>. The driver will be doing more or less the exact same look-up when <code>glGetUniformLocation()</code> is called.</p>\n</li>\n<li><p>Consider having separate "ShaderObject" and "ShaderProgram" classes. This might make loading assets easier later on (shader objects can be used by multiple programs), and it's closer to the OpenGL model.</p>\n</li>\n</ul>\n<hr />\n<p>Some other things about the code:</p>\n<pre><code> if (m_UniformLocationCache.find(name) != m_UniformLocationCache.end())\n {\n return m_UniformLocationCache[name];\n }\n</code></pre>\n<p>This does two searches. Once when calling <code>.find()</code>, and the other in <code>[name]</code>. We should use the return value of the first find call instead.</p>\n<pre><code> char* message = (char*)alloca(length * sizeof(char));\n</code></pre>\n<p>This isn't portable, as <code>alloca</code> isn't a standard library function and might not exist (or might be called something different) on a platform. Maybe creating a string of the appropriate length would be better: <code>auto message = std::string(length, '\\0');</code></p>\n<pre><code> glLinkProgram(Program_id);\n</code></pre>\n<p>After linking the shader program, we can also detach the shader objects from the program with <code>glDetachShader</code>. This doesn't affect the linked program, and allows the shader objects to be cleaned up completely by the GL.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T12:25:01.420",
"Id": "264374",
"ParentId": "264372",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T08:47:46.300",
"Id": "264372",
"Score": "0",
"Tags": [
"c++",
"opengl",
"shaders"
],
"Title": "Reviewing my shader class for efficient use"
}
|
264372
|
<pre><code>#include <iostream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <sstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/conf.h>
class Website
{
int status, sock, ssl_sock;
struct addrinfo hints;
struct addrinfo *servinfo;
SSL_CTX* ctx = NULL;
BIO *web = NULL, *out = NULL;
SSL *ssl = NULL;
long res = 1;
struct URL
{
std::string host;
std::string port;
std::string protocol;
};
URL url;
public:
Website(std::string url){
parseUrl(url);
if(Website::url.protocol == "http"){
establishConn();
std::cout << "Err\n";
} else if(Website::url.protocol == "https"){
initSSL();
initCTX();
/*
if((web = BIO_new_ssl_connect(ctx)) == NULL) throw "Error in bio ssl";
if(BIO_set_conn_hostname(web, Website::url.host.c_str()) != 1) throw "BIO hostname error";
if(BIO_set_conn_port(web, Website::url.port.c_str()) != 1) throw "BIO port error";
if(BIO_set_nbio(web, 1) != 1) throw "Error setting BIO to nonblocking";
BIO_get_ssl(web, &ssl);
if(ssl == NULL) throw "Error in ssl";*/
const char* const PREFERED_CIPHERS = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
if(SSL_set_cipher_list(ssl, PREFERED_CIPHERS) != 1) throw "Cipher error";
if(SSL_set_tlsext_host_name(ssl, Website::url.host.c_str()) != 1) throw "Hostname error";
/*if(BIO_do_connect(web) == 0) throw "Error connecting";
//if(BIO_do_handshake(web) == 0) throw "Error handshake";
X509* cert = SSL_get_peer_certificate(ssl);
if(cert) X509_free(cert);
if(cert == NULL) {ERR_print_errors_fp(stderr); throw "Error with cert";}
if(SSL_get_verify_result(ssl) != X509_V_OK) throw "Error verifying cert";*/
establishConn();
ssl_sock = SSL_get_fd(ssl);
if(SSL_set_fd(ssl, sock) == 0) throw "Error setting fd";
int SSL_status = SSL_connect(ssl);
switch(SSL_get_error(ssl,SSL_status)){
case SSL_ERROR_NONE:
//No error, do nothing
break;
case SSL_ERROR_ZERO_RETURN:
throw "Peer has closed connection";
break;
case SSL_ERROR_SSL:
ERR_print_errors_fp(stderr);
SSL_shutdown(ssl);
throw "Error in SSL library";
break;
default:
ERR_print_errors_fp(stderr);
throw "Unknown error";
break;
}
std::cout << "Ssl connection using " << SSL_get_cipher(ssl) << "\n";
}
}
std::string get(std::string loc, int maxsize){
std::string request = "GET "+ loc + "\r\n\r\n";
char *recvBuf = new char[maxsize];
memset(recvBuf, 0, strlen(recvBuf));
Website::sendToSite(request);
Website::recvFromSite(recvBuf, maxsize);
std::string reply(recvBuf);
return reply;
}
~Website(){
if(Website::url.protocol =="http"){
close(sock);
freeaddrinfo(servinfo);
}else if(Website::url.protocol == "https"){
SSL_free(ssl);
SSL_CTX_free(ctx);
}
}
private:
void sendToSite(std::string request){
if(Website::url.protocol == "http"){
if (send(sock, request.c_str(), strlen(request.c_str()), 0) == -1) throw "Error sending message";
} else if(Website::url.protocol == "https"){
int len = SSL_write(ssl, request.c_str(), strlen(request.c_str()));
if(len < 0) throw "Error sending ssl packet";
}
}
void recvFromSite(char buf[], int maxsize){
if(Website::url.protocol == "http"){
if (recv(sock, buf, maxsize, 0) == -1) throw "Error receving message";
} else if(Website::url.protocol == "https"){
int amountRead = 0;
while(amountRead < maxsize){
int readPart = SSL_read(ssl, buf, maxsize - amountRead);
if(readPart < 0) throw "Error reccieving message";
amountRead += readPart;
}
}
}
//Setting up the SSL
void initSSL(void){
SSL_library_init();
}
void initCTX(){
const SSL_METHOD* method = TLS_method();
if((ctx = SSL_CTX_new(method)) == NULL) throw "Could not create CTX";
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 4);
SSL_CTX_set_options(ctx, SSL_OP_ALL);
if(SSL_CTX_set_default_verify_paths(ctx) == 0) throw "Couldn't se default verify paths";
if((ssl = SSL_new(ctx)) == NULL) throw "Couldn't create SSL";
}
void establishConn(){
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((status = getaddrinfo(Website::url.host.c_str(), Website::url.port.c_str(), &hints, &servinfo)) != 0) throw "Something wrong with getaddrinfo";
if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) throw "Something wrong with creating socket";
if((connect(sock, servinfo->ai_addr, servinfo->ai_addrlen)) != 0) throw "Error in connecting to website";
}
//Filles struct Website::url with host as first argument and path as second
void parseUrl(std::string url){
// Check wether url is http or https
if(url.rfind("http://", 0) == 0){
Website::url.port = "80";
Website::url.host = url.substr(7);
Website::url.protocol = "http";
} else if (url.rfind("https://", 0) == 0){
Website::url.port = "443";
Website::url.host = url.substr(8);
Website::url.protocol = "https";
} else {
throw "Invalid url, must start with http:// or https://";
}
}
};/*
int verify_callback(int preverify, X509_STORE_CTX* x509_ctx){
int depth = X509_STORE_CTX_get_error_depth(x509_ctx);
int err = X509_STORE_CTX_get_error(x509_ctx);
X509* cert = X509_STORE_CTX_get_current_cert(x509_ctx);
X509_NAME* iname = cert ? X509_get_issuer_name(cert) : NULL;
X509_NAME* sname = cert ? X509_get_subject_name(cert) : NULL;
std::cout << "Issuer (cn)" << (char *)iname;
std::cout << "Subject (cn)"<<(char *) sname;
return preverify;
}*/
</code></pre>
<p>This is a C++ library that sends data through the web using SSL or HTTP. I would like some help with making my code more readable and efficient</p>
|
[] |
[
{
"body": "<h2 id=\"first-impression-hnhx\">First impression</h2>\n<p>Well I spend some time and while still there many issues left lets get to the most urgent ones:</p>\n<p>The most important rules in software development are divide&conquer, you have one monolith class that is doing every thing which makes things buggy, slow and hard to read. Minimise coupling while keeping a high cohesion, between the parts of you code. Doing this over member variables i.e. globals is bad, return values and parameters are key.</p>\n<h2 id=\"bugs-etgz\">Bugs</h2>\n<p>When I tried to use your class, it was hard to find what is the supposed interface. Also I got an <strong>infinite loop</strong> when using TLS, since you are using <code>SSL_read</code> wrong: Return codes of 0 also indicates an error. <a href=\"https://www.openssl.org/docs/man1.1.1/man3/SSL_read.html\" rel=\"nofollow noreferrer\">See</a></p>\n<blockquote>\n<p><= 0\nThe read operation was not successful, because either the connection was closed, an error occurred or action must be taken by the calling process. Call SSL_get_error(3) with the return value ret to find out the reason.</p>\n</blockquote>\n<p>Same <strong>bug</strong> for <code>SSL_write</code>, you should check for <code><= 0</code> not <code>< 0</code>.</p>\n<p>Also dead commented code is clutter that should be erased, if you fear you need it later, then your source control system lite <a href=\"https://git-scm.com\" rel=\"nofollow noreferrer\">git</a> is to the rescue.\nFurthermore don't comment the obvious, use <a href=\"https://www.doxygen.nl/index.html\" rel=\"nofollow noreferrer\">doxygen</a> syntax to just write a line what the class or function intends to do and its assumptions. To know how it's implemented, you have to read the code either way.</p>\n<h2 id=\"proposal-code-icki\">Proposal code</h2>\n<p>So I have taken the liberty to make a suggestion which tackles the first most urgent concerns:</p>\n<p>website.hpp</p>\n<pre><code>#ifndef WEBSITE_HPP\n#define WEBSITE_HPP\n\n#include <iostream>\n\n#include <sstream>\n#include <memory>\n#include <netdb.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <vector>\n#include <string>\n\nnamespace myWeb {\n\nclass Website {\npublic:\n Website() = delete;\n Website(std::string url);\n std::string get(std::string loc, int maxsize);\n ~Website();\n\nprivate:\n struct SSLHelper;\n std::unique_ptr<SSLHelper> sslHelper;\n\n int status, sock;\n struct addrinfo hints;\n struct addrinfo *servinfo;\n\n\n long res = 1;\n\n struct URL {\n std::string host;\n std::string port;\n std::string protocol;\n };\n URL url;\n void sendToSite(std::string request);\n void recvFromSite(char buf[], int maxsize);\n void establishConn();\n void parseUrl(std::string url);\n\n};\n\n}\n\n#endif\n</code></pre>\n<p>website.cpp</p>\n<pre><code>#include <lib_name/lib_name.hpp>\n\n#include <openssl/x509.h>\n#include <openssl/x509_vfy.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n\n#include <openssl/ssl.h>\n#include <openssl/err.h>\n#include <openssl/bio.h>\n#include <openssl/conf.h>\n\nnamespace myWeb {\n\nstruct Website::SSLHelper {\n SSL_CTX *ctx = nullptr;\n BIO *web = nullptr, *out = nullptr;\n SSL *ssl = nullptr;\n int ssl_sock{};\n\n SSLHelper(std::string hostName) {\n SSL_library_init();\n\n const SSL_METHOD *method = TLS_method();\n if ((ctx = SSL_CTX_new(method)) == NULL) throw "Could not create CTX";\n SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n SSL_CTX_set_verify_depth(ctx, 4);\n SSL_CTX_set_options(ctx, SSL_OP_ALL);\n if (SSL_CTX_set_default_verify_paths(ctx) == 0) throw "Couldn't se default verify paths";\n if ((ssl = SSL_new(ctx)) == NULL) throw "Couldn't create SSL";\n const char *const PREFERED_CIPHERS = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";\n if (SSL_set_cipher_list(ssl, PREFERED_CIPHERS) != 1) throw "Cipher error";\n if (SSL_set_tlsext_host_name(ssl, hostName.c_str()) != 1) throw "Hostname error";\n }\n void upgrade_ssl(int sock) {\n ssl_sock = SSL_get_fd(ssl);\n if (SSL_set_fd(ssl, sock) == 0) throw "Error setting fd";\n int SSL_status = SSL_connect(ssl);\n switch (SSL_get_error(ssl, SSL_status)) {\n case SSL_ERROR_NONE:\n//No error, do nothing\n break;\n case SSL_ERROR_ZERO_RETURN:\n throw "Peer has closed connection";\n break;\n case SSL_ERROR_SSL:\n ERR_print_errors_fp(stderr);\n SSL_shutdown(ssl);\n\n throw "Error in SSL library";\n break;\n\n default:\n ERR_print_errors_fp(stderr);\n throw "Unknown error";\n break;\n\n }\n std::cout << "Ssl connection using " << SSL_get_cipher(ssl) << "\\n";\n }\n ~SSLHelper(){\n SSL_free(ssl);\n SSL_CTX_free(ctx);\n }\n};\n\nWebsite::Website(std::string url){\n parseUrl(url);\n if (Website::url.protocol == "http") {\n establishConn();\n std::cout << "Err\\n";\n } else if (Website::url.protocol == "https") {\n this->sslHelper = std::make_unique<SSLHelper>(this->url.host);\n\n establishConn();\n sslHelper->upgrade_ssl(this->sock);\n }\n}\n\nstd::string Website::get(std::string loc, int maxsize) {\n std::string request = "GET " + loc + "\\r\\n\\r\\n";\n char *recvBuf = new char[maxsize];\n memset(recvBuf, 0, strlen(recvBuf));\n Website::sendToSite(request);\n Website::recvFromSite(recvBuf, maxsize);\n std::string reply(recvBuf);\n return reply;\n}\n\nWebsite::~Website() {\n close(sock);\n freeaddrinfo(servinfo);\n}\n\nvoid Website::sendToSite(std::string request){\n if(Website::url.protocol == "http"){\n if (send(sock, request.c_str(), strlen(request.c_str()), 0) == -1) throw "Error sending message";\n } else if(Website::url.protocol == "https"){\n int len = SSL_write(sslHelper->ssl, request.c_str(), strlen(request.c_str()));\n if(len < 0) throw "Error sending ssl packet";\n }\n}\n\nvoid Website::recvFromSite(char buf[], int maxsize){\n if(Website::url.protocol == "http"){\n if (recv(sock, buf, maxsize, 0) == -1) throw "Error receving message";\n } else if(Website::url.protocol == "https"){\n int amountRead = 0;\n while(amountRead < maxsize){\n int readPart = SSL_read(sslHelper->ssl, buf, maxsize - amountRead);\n if(readPart < 0) throw "Error reccieving message";\n amountRead += readPart;\n\n }\n }\n}\n\nvoid Website::establishConn(){\n memset(&hints, 0, sizeof hints);\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n if((status = getaddrinfo(Website::url.host.c_str(), Website::url.port.c_str(), &hints, &servinfo)) != 0) throw "Something wrong with getaddrinfo";\n if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) throw "Something wrong with creating socket";\n if((connect(sock, servinfo->ai_addr, servinfo->ai_addrlen)) != 0) throw "Error in connecting to website";\n}\n//Filles struct Website::url with host as first argument and path as second\nvoid Website::parseUrl(std::string url){\n // Check wether url is http or https\n if(url.rfind("http://", 0) == 0){\n Website::url.port = "80";\n Website::url.host = url.substr(7);\n Website::url.protocol = "http";\n } else if (url.rfind("https://", 0) == 0){\n Website::url.port = "443";\n Website::url.host = url.substr(8);\n Website::url.protocol = "https";\n } else {\n throw "Invalid url, must start with http:// or https://";\n }\n}\n\n}\n</code></pre>\n<p>What I have done first was to stream line the user facing header. Now the interface and internals of <code>Website</code> is much clearer, and even the SSL dependency is not viral to the user of your library. Also I refactored the SSL/TLS concerns in a separate class. It's not perfect but a start, that should make using the SSL simpler and clearer. Patterns that relate to this are the PIMPL pattern and RAII.</p>\n<p>If you wonder how to get to the header/include, I suggest using CMake, how to use it is a bit beyond this scope, but I modified a project template of mine, you can find what I actually used here: <a href=\"https://github.com/Superlokkus/spielwiese/tree/code_review_the_masked_rebel\" rel=\"nofollow noreferrer\">https://github.com/Superlokkus/spielwiese/tree/code_review_the_masked_rebel</a> . Please note that I was a bit lazy so <code>lib_name</code> should be replaced my your library's name.</p>\n<p>The important things are that OpenSSL can be linked privately thanks to the .cpp via <code>target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::SSL)</code></p>\n<h2 id=\"conclusion-wxtz\">Conclusion</h2>\n<p>In the end I assume you are a beginner, and so does you code look, but to reach out to get feedback and post you code to review, is something very positive and professional! Keep iterating, don't forget to commit&push, and this will get good in no time. Although for non educational purposes I would refer to <a href=\"https://www.boost.org/doc/libs/release/doc/html/boost_asio.html\" rel=\"nofollow noreferrer\">boost asio</a> or boost beast.\nThe next steps would be: Correct OpenSSL usage and throw the SSL error. Then stuffing the non SSL code into another class, with both the SSL and non SSL class sharing a common interface. This can be done via virtual abstract functions for runtime or at compile time via <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">CRTP</a>, so that the Website class don't even care which one is used. Don't use C-style buffers, use <code>std::vector<std::uint8_t></code> or <code>std::array<std::uint8_t></code>, with iterators. Also double check your SSL code, my proposal is not checked for TLS/OpenSSL correctness.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:40:12.760",
"Id": "264413",
"ParentId": "264375",
"Score": "1"
}
},
{
"body": "<p>I notice you have a lot of lines like<br />\n<code>if(Website::url.protocol =="http")</code><br />\nthat is, comparing the <code>string</code> against a literal. First of all, don't qualify the members with the current class. You are writing code for the body of a function in <code>Website</code> so you don't need to put <code>Website::</code> everywhere!</p>\n<p>Anyway, my real point is that this string comparison is slow, and repetitive. You keep checking the same thing. I suggest making an enumeration type for the supported protocols, and parsing it <em>once</em>.</p>\n<p>All the differences though are not about the individual protocols, but just whether TLS is selected or not. Make a separate function that checks for that.</p>\n<p>You actually have different code for http vs https in every member, including the destructor and which member data gets used (<code>sock</code> vs <code>ssl</code> etc.). So, these should really be different classes. Make a base class, and separate derived classes for each case, using virtual functions.</p>\n<p>Don't use the C macro <code>NULL</code>. C++ has a keyword <code>nullptr</code>.</p>\n<p>In C++, you don't need to put <code>struct</code> in front of structure type names; e.g. <code>struct addrinfo hints;</code> should just be <code>addrinfo hints;</code>. You probably copied socket sample code from C examples.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:56:17.513",
"Id": "524445",
"Score": "1",
"body": "Note that the \"don't need to put `struct`\" is not always true. Notoriously, the `struct stat` is required because we also have a `stat()` function..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T15:07:10.597",
"Id": "264421",
"ParentId": "264375",
"Score": "1"
}
},
{
"body": "<p>One of the beauties of C++ is <a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII</a>. Without it, you get many leaks unless you pay very close attention to a lot of details. I tried that old C-like method many times, but I can tell you that 99.9% of the time, you get it wrong. So always use RAII if you do not want to leak all over the place.</p>\n<p>What happens in your code?</p>\n<pre><code>...\nssl = SSL_new(ctx);\n...\nswitch(SSL_get_error(ssl,SSL_status))\n{\ncase SSL_ERROR_ZERO_RETURN:\n throw "Peer has closed connection";\n...\n</code></pre>\n<p>This is in the constructor. What you are saying is: let's allocate an SSL <em>socket</em>, then you see an error occurred and you throw. You just <em>leaked</em> that socket.</p>\n<p>The solution is to place the socket in a smart pointer. On a throw, the socket will be closed. Not only that, use that smart pointer in your class definition and you don't even need a destructor. Everything will be deallocated automatically.</p>\n<p>I have such an implementation in my <a href=\"https://github.com/m2osw/eventdispatcher/blob/main/eventdispatcher/tcp_bio_client.cpp\" rel=\"nofollow noreferrer\">eventdispatcher</a>. The SSL <em>socket</em> is actually a pointer, so that one is easy. You can directly use a <code>shared_ptr<SSL_>()</code>. For the plain socket, though, you have to use the <code>close()</code> function to close it. That makes things a bit more complicated. I use my <a href=\"https://github.com/m2osw/snapdev/blob/main/snapdev/raii_generic_deleter.h\" rel=\"nofollow noreferrer\"><code>raii_generic_deleter.h</code></a> for such resources (however, note that in my implementation I use the same BIO interface: when you don't add the SSL layer, then it works like a plain socket).</p>\n<p>Now you can freely throw anywhere / anytime.</p>\n<p>By the way, if you call a C++ function, the likelihood that it throws is rather high. So without RAII your code would have to take care of that too. Something like:</p>\n<pre><code>auto a = new SomeClass(); // this can throw std::bad_alloc\n</code></pre>\n<p>is not valid if you don't use RAII. Instead you need:</p>\n<pre><code>SomeClass * a = nullptr;\ntry\n{\n a = new SomeClass()\n}\ncatch(...)\n{\n // do any clean up of anything allocated before `a`\n ...\n throw;\n}\n</code></pre>\n<p>As I mentioned above. This is a lot of work. That's why RAII is your friend. The C++ compiler automatically handles all your resources cleanup.</p>\n<hr />\n<p>As a side note, for your exceptions, at a minimum, use <code>std::exception()</code>:</p>\n<pre><code>throw std::exception("message");\n</code></pre>\n<p>Better yet, get acquainted with the <a href=\"https://en.cppreference.com/w/cpp/error\" rel=\"nofollow noreferrer\">various error types</a>; to get started, I suggest the following two:</p>\n<pre><code>throw std::logic_error("review your code, something went wrong");\nthrow std::runtime_error("the socket couldn't be allocated");\n</code></pre>\n<p>If you use those two, at least you convey a strong message. Others are useful too, but 90% of my code uses just these and I'm good most of the time. (Well, really I have my own exceptions deriving from those two and once in a while from <code>std::range_error</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T15:22:52.873",
"Id": "265521",
"ParentId": "264375",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T12:51:10.297",
"Id": "264375",
"Score": "2",
"Tags": [
"c++",
"http",
"https"
],
"Title": "A C++ library that sends and receives data using HTTPS or HTTP"
}
|
264375
|
<p>This question is complicated (at least for me who is new in machine learning and image processing).</p>
<p>I need help in understanding, why my iterative process is minimising the ratio of inter-class scatter by intra-class scatter after Fisher-Rao discrimination, rather than maximising it.</p>
<p>Background:</p>
<p>I am implementing following old paper.</p>
<p><a href="https://ieeexplore.ieee.org/document/5746646/" rel="nofollow noreferrer">https://ieeexplore.ieee.org/document/5746646/</a></p>
<p>The logic of the code where I am facing problem, is in Table 1 (iterative fisher-Rao optimization), of the paper.</p>
<p>My code is in <a href="https://github.com/Sujata018/Image-Processing/blob/main/P2/classification/lda.py" rel="nofollow noreferrer">https://github.com/Sujata018/Image-Processing/blob/main/P2/classification/lda.py</a></p>
<p>In that iteration, it is supposed to maximise J, but I am getting following output, which looks like minimising it :</p>
<pre><code>iteration 1 J= 11.083135263169856 Jnew = 5.968339819774404
iteration 2 J= 5.968339819774404 Jnew = 4.657109480685861
iteration 3 J= 4.657109480685861 Jnew = 4.291975621553885
iteration 4 J= 4.291975621553885 Jnew = 4.170759974802839
iteration 5 J= 4.170759974802839 Jnew = 4.127241042274884
iteration 6 J= 4.127241042274884 Jnew = 4.11233043402457
iteration 7 J= 4.11233043402457 Jnew = 4.108385230771005
iteration 8 J= 4.108385230771005 Jnew = 4.108419371607428
Converged at J= 4.108419371607428
</code></pre>
<p>I need help in understanding, what is wrong here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T21:23:12.270",
"Id": "522137",
"Score": "0",
"body": "https://cs.stackexchange.com/q/142640/755"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T13:16:02.363",
"Id": "264376",
"Score": "0",
"Tags": [
"python",
"machine-learning"
],
"Title": "Ratio of intra-class scatter by inter-class scatter is getting minimised by linear discrimination process"
}
|
264376
|
<p>I have a csv file that looks like this:</p>
<pre><code> time, price
0 2021-07-23T20:00:00.000221421Z 368.06
1 2021-07-23T20:00:00.001131397Z 368.06
2 2021-07-23T20:00:00.008030544Z 368.06
3 2021-07-23T20:00:00.00807574Z 368.06
4 2021-07-23T20:00:00.008084129Z 368.06
... ... ...
32435 2021-07-23T23:59:46.272261376Z 367.84
32436 2021-07-23T23:59:53.782418944Z 367.84
32437 2021-07-23T23:59:56.24058112Z 367.84
32438 2021-07-23T23:59:58.981374464Z 367.84
32439 2021-07-23T23:59:58.981374464Z 367.84
32440 rows × 2 columns
</code></pre>
<p>I'm trying to merge the rows into 0.10 OHLC price range intervals, so that the end result looks like this:</p>
<pre><code>time, open, high, low, close
0 2021-07-23T20:00:00.000221421Z 368.06 368.06 367.96 367.96
1 2021-07-23T20:00:00.337192Z 367.95 368.04 367.94 368.04
2 2021-07-23T20:00:11.632994Z 368.05 368.06 367.96 368.06
3 2021-07-23T20:00:39.91849344Z 368.07 368.08 367.98 367.98
4 2021-07-23T20:01:04.188584192Z 367.97 368.04 367.94 367.94
</code></pre>
<p>Here's my attempt, which works but it seems quite slow:</p>
<pre><code>import pandas
print('time, open, high, low, close', file = open(file = 'range.csv', mode = 'a'))
dataframe = pandas.read_csv(filepath_or_buffer = 'quotes.csv')
bar = [{'time': dataframe.iloc[0, 0], 'open': dataframe.iloc[0, 1], 'high': dataframe.iloc[0, 1], 'low': dataframe.iloc[0, 1], 'close': dataframe.iloc[0, 1]}]
cycle = [0]
while cycle[-1] < len(dataframe.index):
high = float(bar[-1]['high'])
low = float(bar[-1]['low'])
price = float(dataframe.iloc[cycle[-1], 1])
time = dataframe.iloc[cycle[-1], 0]
if price < high - 0.10 or price > low + 0.10:
bar.append({'time': time, 'open': price, 'high': price, 'low': price})
bar[-2]['close'] = dataframe.iloc[cycle[-2], 1]
print(bar[-2]['time'], ',', bar[-2]['open'], ',', bar[-2]['high'], ',', bar[-2]['low'], ',', bar[-2]['close'], file = open(file = 'range.csv', mode ='a'))
if price > high:
bar[-1]['high'] = price
if price < low:
bar[-1]['low'] = price
cycle.append(cycle[-1] + 1)
</code></pre>
<p>I'm a novice coder at best, and so my question is this the correct/"pythonic" way of achieving this result, or is there a better way? I haven't found a way of implementing pandas.DataFrame.resample to achieve this result. Thanks in advance for your time!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T13:16:54.170",
"Id": "264377",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "pandas.DaraFrame resample OHLC based on a non-time value"
}
|
264377
|
<p><strong>Problem:</strong>
Given two csv files <code>science_courses.csv</code> and <code>other_courses.csv</code>, which has students name and their respective course points. Calculate the CGPA and sort by the same (highest to lowest CGPA).</p>
<p>sample file content:</p>
<pre><code>science_courses.csv:
Name,Physics,Chemistry
Susan,6.0,5.5
James,4.7,8.5
Linda,4.5,6.3
Mathew,7.7,5.4
-----------------------
other_courses.csv
Name,History,Math,Arts
Linda,8.3,7.4,6.9
James,6.3,7.5,5.9
Mathew,5.8,8.9,4.9
Susan,8.8,9.0,5.9
</code></pre>
<p><strong>Approach:</strong></p>
<ol>
<li>Open both files in and make a dictionary. ex:<code>{studentA:[mark-1,mark-2..mark-n],studentB:[mark-1...mark-n]}</code></li>
<li>Iterate through the dictionary of the list and calculate CGPA and store in a dictionary. ex:<code>{studentA:cgpa, studentB:cgpa}</code></li>
<li>Sort the results by cgpa (highest to lowest) and print</li>
</ol>
<p><strong>solution:</strong></p>
<pre><code>def get_all_courses(a,b):
all_courses = {}
with open(a, 'r') as sci, open(b, 'r') as othr:
next(sci)
for i in sci:
sc = i.strip('\n').split(',')
all_courses[sc[0]] = sc[1:]
for j in othr:
ot = j.strip('\n').split(',')
name = ot[0]
if name in all_courses:
all_courses[name] = all_courses.get(name) + ot[1:]
return all_courses
def get_results():
avg_marks = {}
result = get_all_courses('science_courses.csv','other_courses.csv')
for k,v in result.items():
total = sum(map(float, v))
avg = round(total/len(v),2)
avg_marks[k] = avg
for i in sorted(avg_marks.items(), key=lambda x: x[1], reverse=True): print i
get_results()
</code></pre>
<p><strong>Please suggest</strong> better alternatives to:</p>
<ol>
<li>simplify the book keeping of the marks extracted from files</li>
<li>simplify/optimise the calculation and sorting based on cgpa.</li>
</ol>
|
[] |
[
{
"body": "<p>First of all: don't use Python2, it's end of life. The telltale sign that you're using it is the lack of parentheses to the print function.</p>\n<p>Since Python has a built-in library for reading CSV files, it would make sense to use it. The parsing would be more elegant and straightforward.</p>\n<p>Your function <code>get_all_courses</code> expects exactly two arguments. It would be more flexible to use only one argument, but call the function as many times as necessary. Or use a list of files as parameter.</p>\n<p>As for the aggregation, I think your logic is fairly to the point.</p>\n<p>The next step is to write a function that reads from a single file (given as parameter) and returns a dict-like structure. Which you did. But I'd rather return the file data with as little transformation as possible and instead delegate the consolidation to another function to better separate concerns.</p>\n<p>My implementation follows below. I wouldn't call it superior, because there are actually more steps involved. It is more for demonstration purposes of the features available in Python.</p>\n<p>For more flexibility I have added a delimiter parameter in the csv reader routine, in case you have to parse files that are not comma-delimited.</p>\n<p>My example returns a list of dictionaries from each file, like:</p>\n<pre>\n[{'Name': 'Susan', 'Physics': '6.0', 'Chemistry': '5.5'}, {'Name': 'James', 'Physics': '4.7', 'Chemistry': '8.5'}, {'Name': 'Linda', 'Physics': '4.5', 'Chemistry': '6.3'}, {'Name': 'Mathew', 'Physics': '7.7', 'Chemistry': '5.4'}]\n</pre>\n<p>The idea is to <strong>merge</strong> those lists into one single list, hence the extend method.</p>\n<p>Finally, we need to apply some form of "group by" to the results and calculate averages. We want to group by name. For this we use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\">itertools.groupby</a> function. There is one caveat though: the dataset must be <strong>sorted</strong> by whatever column(s) shall be used as the grouping key.\nTherefore we sort our list of dict by name beforehand.</p>\n<p>We end up with something like this:</p>\n<pre>\nJames : [{'Name': 'James', 'Physics': '4.7', 'Chemistry': '8.5'}, {'Name': 'James', 'History': '6.3', 'Math': '7.5', 'Arts': '5.9'}]\nLinda : [{'Name': 'Linda', 'Physics': '4.5', 'Chemistry': '6.3'}, {'Name': 'Linda', 'History': '8.3', 'Math': '7.4', 'Arts': '6.9'}]\nMathew : [{'Name': 'Mathew', 'Physics': '7.7', 'Chemistry': '5.4'}, {'Name': 'Mathew', 'History': '5.8', 'Math': '8.9', 'Arts': '4.9'}]\nSusan : [{'Name': 'Susan', 'Physics': '6.0', 'Chemistry': '5.5'}, {'Name': 'Susan', 'History': '8.8', 'Math': '9.0', 'Arts': '5.9'}]\n</pre>\n<p>At this point the rest is easy, we simply read the dict values for each student and compute averages while ignoring the 'Name' key. (Actually I am not completely satisfied with this attempt, and there are countless approaches possible).</p>\n<hr />\n<pre><code>import csv\nfrom itertools import groupby\nfrom operator import itemgetter\nfrom functools import reduce\nfrom statistics import mean\n\n\ndef get_data_from_file(filepath: str, delimiter: str = ",") -> list:\n """Read a CSV file and return a list of dict eg:\n Return a list of dict eg:\n [\n {'Name': 'Susan', 'Physics': '6.0', 'Chemistry': '5.5'},\n ...\n ]\n\n Default field delimiter is a comma\n """\n with open(filepath) as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=delimiter)\n return list(csv_reader)\n\n\nall_courses = []\nall_courses.extend(get_data_from_file(filepath='science_courses.csv'))\nall_courses.extend(get_data_from_file(filepath='other_courses.csv'))\n\n# the dataset must be sorted before we apply groupby\nall_courses = sorted(all_courses, key=itemgetter('Name'))\n\n# group by Name\nfor key, group in groupby(all_courses, lambda x: x["Name"]):\n\n # get all points for this student\n student_points = list(group)\n\n # merge the dicts - source: https://stackoverflow.com/a/16048368\n student_points = reduce(lambda a, b: dict(a, **b), student_points)\n\n # drop the "Name" key\n del student_points["Name"]\n\n # compute average of points for student\n points_average = mean([float(value) for value in student_points.values()])\n print(f"Student: {key}, average: {points_average}")\n</code></pre>\n<hr />\n<p>The bottom line is that parsing the CSV file can be streamlined with the built-in library. Python provides a number of functions/libs for aggregating results, such as groupby, or statistics.</p>\n<p>PS: for more complex usage <a href=\"https://pandas.pydata.org/\" rel=\"nofollow noreferrer\">Pandas</a> is very popular among python programmers. In fact the same task could have been achieved with Pandas instead, and more likely in a more efficient way.</p>\n<hr />\n<h2 id=\"useful-links\">Useful links</h2>\n<ul>\n<li><a href=\"https://realpython.com/python-csv/\" rel=\"nofollow noreferrer\">Reading and Writing CSV Files in Python</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:41:03.973",
"Id": "526442",
"Score": "0",
"body": "+1 for `import csv`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:57:01.283",
"Id": "264395",
"ParentId": "264379",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T14:47:43.523",
"Id": "264379",
"Score": "2",
"Tags": [
"python",
"csv"
],
"Title": "Calculate students' GPAs and sort them, based on two CSV input files"
}
|
264379
|
<p>I'm learning PHP and try to write some scripts as I go along. I wrote this script and it worked. I would like to know if this script can be improved.</p>
<p>The purpose of the script below is to prompt the user to input the version of the backup file, and proceed to make a backup fo the Nextcloud directory.</p>
<p>Thanks in advance.</p>
<pre><code>#!/usr/bin/php
<?php
# prerequisites packages: apt-get install php7.4-cli php-zip
$today = date('m-d-Y');
$WWWpath = "/config/www";
$NCpath = "/config/www/nextcloud";
$user = 'xfs';
$file = 'nextcloud.zip';
chdir($NCpath);
echo "Current working directory is: " . getcwd();
echo "\n";
class Prompt
{
protected function input()
{
$prompt = readline('Would you like to make a backup of the current Nextcloud ? [y|n] ' );
echo "You selected '$prompt'\n";
return $prompt;
}
public function archive()
{
// declare global variables
global $WWWpath, $NCpath, $backup_version;
$ask = $this->input();
if(!empty($ask))
{
switch ($ask)
{
case "y":
case "Y":
$backup_version = readline('Please enter a version of Nextcloud you want to backup: ');
echo "You input: $backup_version\n";
$verify = readline("Is this the correct version ? [y|n]: '{$backup_version}' ");
echo "You selected '$verify'.\n";
switch($verify)
{
case "y":
case "Y":
echo "Backup version: 'nextcloud-old_${backup_version}'\n";
echo "Backing up current Nextcloud directory...";
echo "\n";
$cp = ("cp -r $NCpath ${WWWpath}/'nextcloud-old_${backup_version}'");
$status = shell_exec("$cp");
$status = rtrim($status);
// check file copy status
print ((int)$status == "0") ? "File copied successfully !\n" : "Failed to copy file !\n";
break;
case "n":
case "N":
break;
}
case "n":
case "N":
break;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T23:39:50.033",
"Id": "522224",
"Score": "0",
"body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>Just one quick remark: as per the <a href=\"https://www.php.net/manual/en/function.shell-exec.php\" rel=\"nofollow noreferrer\">docs</a> shell_exec returns the complete output as a string. And:</p>\n<blockquote>\n<p>This function can return null both when an error occurs or the program\nproduces no output. It is not possible to detect execution failures\nusing this function. exec() should be used when access to the program\nexit code is required.</p>\n</blockquote>\n<p>If you want to retrieve the return code <a href=\"https://www.php.net/manual/en/function.exec.php\" rel=\"nofollow noreferrer\">exec</a> should be used then. And it can also return the output from execution.</p>\n<p>The variables $WWWpath, $NCpath, $backup_version should not be defined as global in your <code>archive</code> function. Instead they should be function arguments.</p>\n<p>The switch block should be outside the <code>archive</code> function. Get the user response first, and if the response is yes then call this function with appropriate parameters.</p>\n<p>Misc:</p>\n<ul>\n<li>I don't see the point of a class here, a function would be sufficient.</li>\n<li>chdir is not required, just use full paths</li>\n<li>you should verify that backup_version is not blank and is an appropriate value - what would happen if the user just types <kbd>Enter</kbd> ?</li>\n<li>a switch statement is not really needed in this case, a simple if/else will do because the answer is either yes or no and you can just cast the answer to lowercase so that Y = y</li>\n<li>you define a number of variables on top of your code like file, user that don't seem to be used</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:44:20.737",
"Id": "522134",
"Score": "0",
"body": "Hello, I'm using declare the global variables so I can use them for my 2nd part of the script. I want to use the class so the functions can be grouped together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T00:58:26.157",
"Id": "522151",
"Score": "0",
"body": "Thanks for the suggestions; I'd revised the script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:54:36.533",
"Id": "522252",
"Score": "0",
"body": "and `empty()` is inappropriate when a variable is guaranteed to be declared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T23:48:14.760",
"Id": "522389",
"Score": "0",
"body": "I wrote it as not empty: !empty()"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:39:14.133",
"Id": "264392",
"ParentId": "264380",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:16:52.320",
"Id": "264380",
"Score": "1",
"Tags": [
"php"
],
"Title": "backup file script in PHP"
}
|
264380
|
<p>My goal is to write code that picks several random numbers from a range without repeating any previously chosen numbers.
I figured out a functional solution for my problem but it seems very bulky and there must be a way to do this in fewer lines. Mine feels brute force and not very elegant and becomes super unwieldy if stretched to larger ranges and repetitions. Would love any suggestions for cleaning up what I already have.</p>
<pre><code>import random
key1 = random.randint(1, 4)
while True:
key2 = random.randint(1, 4)
if key2 != key1:
break
while True:
key3 = random.randint(1, 4)
if key3 != key1 and key3 != key2:
break
while True:
key4 = random.randint(1, 4)
if key4 != key1 and key4 != key2 and key4 != key3:
break
key_order = [key1, key2, key3, key4]
print(key_order)
</code></pre>
<p>If it means totally taking my code apart and rebuilding it, that is fine. I am here to learn.</p>
|
[] |
[
{
"body": "<ul>\n<li>\n<blockquote>\n<p>if key4 != key1 and key4 != key2 and key4 != key3:</p>\n</blockquote>\n<p>If you append to <code>key_order</code> upon picking a non-duplicate value you can just use <code>in</code> instead.</p>\n</li>\n<li><p>You can then more simply use a for loop to select the number of keys to output.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = []\nfor _ in range(4):\n while True:\n key = random.randint(1, 4)\n if key not in key_order:\n key_order.append(key)\n break\n</code></pre>\n<hr />\n<ul>\n<li>You can just use <a href=\"https://docs.python.org/3/library/random.html#random.sample\" rel=\"noreferrer\"><code>random.sample</code></a> or <a href=\"https://docs.python.org/3/library/random.html#random.shuffle\" rel=\"noreferrer\"><code>random.shuffle</code></a> and follow Python's "batteries included" ethos.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = random.sample(range(1, 5), 4)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = random.shuffle(range(1, 5))\n</code></pre>\n<hr />\n<p>Your algorithm is known as the naive shuffle, because the algorithm is very simple but also very slow. If you want to implement the shuffle yourself <a href=\"https://bost.ocks.org/mike/shuffle/\" rel=\"noreferrer\">there's a very clear visual explanation on how the Fisher-Yates shuffle works</a>.</p>\n<p>Whatever you do you should remove the <code>while</code> loop by only picking a random number from the values you have left. You can do so by building a list of options to pick from by <a href=\"https://docs.python.org/3/library/stdtypes.html#typesseq-mutable\" rel=\"noreferrer\"><code>list.pop</code>ing</a> when you <code>key_order.append(key)</code>.</p>\n<p>Whilst <code>pop</code> is less expensive then your while loop when shuffling, <code>pop</code> is still expensive. So we can change <code>append</code> and <code>pop</code> to a swap operation. For the first selection we swap <code>0</code> with <code>random.randrange(0, 4)</code>, then for the second selection <code>1</code> with <code>random.randrange(1, 4)</code>... Getting the Fisher-Yates shuffle.</p>\n<pre class=\"lang-py prettyprint-override\"><code>values = [0, 1, 2, 3]\nfor i in range(len(values)):\n j = random.randrange(i, len(values))\n values[i], values[j] = values[j], values[i]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T00:29:46.760",
"Id": "522329",
"Score": "0",
"body": "This was incredibly informative (and practical). I greatly appreciate your feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T16:10:45.663",
"Id": "264385",
"ParentId": "264382",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "264385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T15:43:50.663",
"Id": "264382",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"random"
],
"Title": "Python code for eliminating options for random intergers as they get picked"
}
|
264382
|
<p>I have this Python code:</p>
<pre class="lang-py prettyprint-override"><code>def main() -> None:
print("Welcome To UltiList!")
lst = []
len_of_list = int(input("Enter the len of the list: "))
while len(lst) <= len_of_list:
print(">> ", end="")
args = input().strip().split(" ")
if args[0] == "append":
lst.append(int(args[1]))
elif args[0] == "insert":
lst.insert(int(args[1]), int(args[2]))
elif args[0] == "remove":
lst.remove(int(args[1]))
elif args[0] == "pop":
lst.pop()
elif args[0] == "sort":
lst.sort()
elif args[0] == "reverse":
lst.reverse()
elif args[0] == "print":
print(lst)
elif args[0] == "exit":
print("Bye!")
exit()
else:
print("That's not a valid command!")
if __name__ == "__main__":
main()
</code></pre>
<p>But I thinks is very repetitive,Eg: In JavaScript I could do something like:</p>
<blockquote>
<pre class="lang-javascript prettyprint-override"><code>
const commands = {
append: (arg)=>lst.append(arg),
remove: (arg)=>lst.remove(arg),
...
}
// This would go in the while loop
commands[`${args[0]}`](args[1])
</code></pre>
</blockquote>
<p>And I would no longer have to make any comparison, this will make it more readable and shorter in my opinion.</p>
<p>What can be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:01:32.940",
"Id": "522245",
"Score": "0",
"body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 2 → 1."
}
] |
[
{
"body": "<p>Your 'switch statement' is bad because you've chosen to not use the same algorithm as your JavaScript example:</p>\n<blockquote>\n<pre class=\"lang-js prettyprint-override\"><code>const commands = {\n append: (arg)=>lst.append(arg),\n remove: (arg)=>lst.remove(arg),\n ...\n}\n</code></pre>\n</blockquote>\n<p>Converted into Python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>commands = {\n "append": lambda arg: lst.append(arg),\n "remove": lambda arg: lst.remove(arg),\n}\n\ncommands[f"{args[0]}"](args[1])\n</code></pre>\n<p>Python has no equivalent to JavaScript's <code>() => {...}</code> lambdas.\nSo you can abuse class if you need them.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Commands:\n def append(arg):\n lst.append(arg)\n\n def exit(arg):\n print("bye")\n exit()\n\ngetattr(Commands, f"{args[0]}")(args[1])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T18:38:03.350",
"Id": "522125",
"Score": "0",
"body": "`lambda arg:lst.append(arg)` is just a closure `lst.append`. F-string is an overkill, non-str aguments would not be found in dict keys. Else/default option can be done with `commands.get(args[0], None)` and adding `None:lambda print(...)` to `commands`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T18:54:23.920",
"Id": "522127",
"Score": "1",
"body": "@PavloSlavynskyy 1. The point is to show `lambda` exists in Python, not to cut characters. 2. I'm just copying the JS example in the question. 3. Yes, or you could just do `default = lambda arg: print(...)` `commands.get(args[0], default)(args[1])`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T16:46:38.440",
"Id": "264386",
"ParentId": "264384",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264386",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T16:06:48.483",
"Id": "264384",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python program to manipulate a list based on user input"
}
|
264384
|
<p>This is a problem from Daily Coding Problem. I have implemented it in Java.
For a function <code>f</code> I have used <code>Runnable</code> interface.</p>
<p>Problem:</p>
<p>This problem was asked by Apple.</p>
<p>Implement a job scheduler which takes in a function <code>f</code> and an integer <code>n</code>, and calls <code>f</code> after <code>n</code> milliseconds.</p>
<p>Solution:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
class Ideone {
interface JobScheduler {
void schedule(final Runnable f, int n);
}
static class JobSchedulerImpl implements JobScheduler {
private final AtomicInteger idValue = new AtomicInteger(0);
private final Map<Integer, Thread> jobs = new ConcurrentHashMap<>();
private int getNextId() {
return idValue.incrementAndGet();
}
@Override
public void schedule(final Runnable f, final int n) throws IllegalArgumentException {
if (n < 0) {
throw new IllegalArgumentException("n cannot be nagative");
}
int id = getNextId();
Thread job = new Thread() {
@Override
public void run() {
try {
Thread.sleep(n);
f.run();
jobs.remove(id);
} catch (InterruptedException e) {
jobs.remove(id);
}
}
};
jobs.put(id, job);
job.start();
}
}
public static void main(String[] args) {
JobScheduler jobScheduler = new JobSchedulerImpl();
jobScheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job1 launched at: " + System.currentTimeMillis());
}
}, 10000);
jobScheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job2 launched at: " + System.currentTimeMillis());
}
}, 1000);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2 id=\"basics\">Basics</h2>\n<p>First of all, you've got the basics right, being naming conventions, indentation, and a rather sane OOP structure. But you ask for review, so here I go.</p>\n<h2 id=\"reinventing-the-wheel\">Reinventing the wheel</h2>\n<p>You probably know the <code>Timer</code> class, doing exactly what you implemented.</p>\n<p>So I guess, your program is meant as an exercise.</p>\n<h2 id=\"use-proper-names\">Use proper names</h2>\n<p>Your class is named <code>Ideone</code>, and that's terrible. You didn't create a kind of IDE. [If this class name is somehow mandated by your environment, move away from that as fast as possible.]</p>\n<p>User a proper package name. Placing code into the unnamed (top-level) package is a bad idea, as it invites name collisions with others.</p>\n<pre><code>void schedule(final Runnable f, int n);\n</code></pre>\n<p>Single-letter variable names tell nothing about their meaning. A better naming would be</p>\n<pre><code>void schedule(final Runnable job, int millisecondsFromNow);\n</code></pre>\n<p>You use the variable name <code>job</code> for the thread waiting for and later executing the function, which I'd call <code>jobExecutionThread</code> instead.</p>\n<h2 id=\"dont-use-wildcard-imports\">Don't use wildcard imports</h2>\n<pre><code>import java.util.*;\n</code></pre>\n<p>This can create problems in the long run. Imagine the Java stewards to include a new class into the <code>java.util</code> package in some future version, one that collides with some other class name you reference. The effect can be that your code will no longer compile with this future Java version.</p>\n<p>You can easily avoid that by having your IDE manage the imports for you (and disallow any wildcard imports in the IDE settings, if necessary).</p>\n<h2 id=\"interface-jobscheduler\">Interface <code>JobScheduler</code></h2>\n<p>You create an inner interface <code>JobScheduler</code> inside you class <code>Ideone</code>, and that way, it's useless.</p>\n<p>If you want to allow for more implementations of <code>JobScheduler</code> (although I don't see a point in it), move it to top-level.</p>\n<p>For its current use, just inside the top-level class <code>Ideone</code> with exactly one implementation, I'd simply use the implementing class, and get rid of the interface.</p>\n<h2 id=\"the-jobs-management\">The jobs management</h2>\n<p>You invested quite some effort into naming the jobs with a synthetic integer <code>id</code> and maintaining a map of the jobs. What for?</p>\n<p>You only use the <code>id</code> in</p>\n<pre><code>jobs.remove(id);\n</code></pre>\n<p>For removing an object from a collection, you don't need this integer, you can just maintain a Collection and remove the thread itself</p>\n<pre><code>private final Collection<Thread> jobs = ...;\n\njobs.remove(this);\n</code></pre>\n<p>But why maintain such a collection at all? Currently, there's nothing you do with it. It would make sense if you had an info call returning a list of pending jobs or something like that. But as long as this doesn't exist, get rid of the jobs management stuff.</p>\n<p>And, regarding integer ids generally: to me, that's remains from ancient times when the only way to machine-identify an object was thought to be by numbering. First of all, objects have an identity of their own (in Java supported by <code>equals()</code> and <code>hashCode()</code> methods, if necessary), and if something additional is necessary, using numbers often creates more problems than necessary. See for example the internet. Nobody would try to use integers as web resource identities, the URL strings do a much better job.</p>\n<h2 id=\"javadoc\">Javadoc</h2>\n<p>Get into the habit of documenting important aspects of your code, especially interfaces, classes, and public methods. Your team colleagues (and your future self after one year) will really appreciate that. Follow the Javadoc style for these comments, as it's well supported in IDEs and other tools.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T08:28:57.903",
"Id": "522258",
"Score": "0",
"body": "Thank you very much. This is a very thorough review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:02:53.160",
"Id": "264410",
"ParentId": "264387",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T17:37:10.203",
"Id": "264387",
"Score": "1",
"Tags": [
"java",
"multithreading",
"scheduled-tasks"
],
"Title": "Daily coding problem: Job scheduler invoking a function after specific time"
}
|
264387
|
<p>I have implemented a simple XOR encryption in Python. However I am not sure this is the right implementation or it can be further improved ?</p>
<pre><code>from math import ceil
from random import uniform
from numpy import array, repeat, vectorize
#---------- HELPER FUNCTIONS ----------#
def addtrailingzero(byte):
"""
Adding trailing zero's if the length of the byte is less then 0.
Example:
addtrailingzero('110110')
>>>00110110
"""
while len(byte) != 8:
byte = '0' + byte
return byte
def byteArray(text):
"""
Turning the given text into an array, where each element contains the binary representation
of each text element.
Args:
text [str]: It can be either a message or a key
Returns:
[array]: an array that contains the byte information of each string element
Example:
byteArray('12')
>>>['00110001' '00110010']
byteArray('hey')
>>>['01101000' '01100101' '01111001']
"""
binary_text = array([bin(ord(char))[2:] for char in text])
vectorizeF = vectorize(addtrailingzero)
byteArray_text = vectorizeF(binary_text)
return byteArray_text
def resizeKey(message, key):
"""
Resizing the length of the key, in order to perform XOR operations easily.
Args:
message [str]: The input message that is going to be encrypted
key [str]: The key that generated randomly, or entered by the user
"""
byteArray_key = byteArray(key)
messageLength = len(message)
keyLength = len(key)
r = ceil(messageLength/keyLength)
resize_byteArray_key = repeat(byteArray_key, r)
resize_byteArray_key = resize_byteArray_key[:messageLength]
return resize_byteArray_key
def binaryArraytoString(binary_array):
"""
Turning any binary array into a string
Args:
binary_array [list]: An array consists of series of bits
Example:
binaryArraytoString('011001100110111101101111')
>>> 'foo'
"""
lenBinArray = len(binary_array)
return ''.join([chr(int(binary_array[i:i+8], 2)) for i in range(0, lenBinArray, 8)])
#----------------------------#
def encryptXOR(message, key):
"""
Encrypting the message for a given key
Args:
message [str]: The input message that is going to be encrypted
key [str]: The key that generated randomly, or entered by the user
Returns:
Encrypted message
"""
byteArray_message = byteArray(message)
byteArray_key = resizeKey(message, key)
binaryArray_message = ''.join(byteArray_message)
binaryArray_key = ''.join(byteArray_key)
encryptedBinary_message = ''
for (i, j) in list(zip(binaryArray_message, binaryArray_key)):
# performing the XOR operation
encryptedBinary_message += str(int(i) ^ int(j))
encrypted_message = binaryArraytoString(encryptedBinary_message) # recovering the encrypted message from the binary array
return encrypted_message
def generateKey(key_length):
"""
Generating random keys for a given length
"""
binary_key = ''
for i in range(key_length * 8):
if uniform(0, 1) < 0.5:
binary_key += '1'
else:
binary_key += '0'
randomKey = binaryArraytoString(binary_key)
return randomKey
def decryptXOR(encrypted_message, key):
"""
Encrypting the message for a given key
Args:
encrypted_message [str]: The encrypted message
key [str]: The key that generated randomly, or entered by the user
Returns:
Encrypted message
"""
byteArray_message = byteArray(encrypted_message)
byteArray_key = resizeKey(encrypted_message, key)
binaryArray_message = ''.join(byteArray_message)
binaryArray_key = ''.join(byteArray_key)
decryptedBinary_message = ''
for (i, j) in list(zip(binaryArray_message, binaryArray_key)):
# performing the XOR operation
decryptedBinary_message += str(int(i) ^ int(j))
decrypted_message = binaryArraytoString(decryptedBinary_message) # recovering the encrypted message from the binary array
return decrypted_message
encrypted_text = encryptXOR('I have a dream', '12p')
decrypted_text = decryptXOR(encrypted_text, '12p')
print(encrypted_text)
print(decrypted_text)
</code></pre>
|
[] |
[
{
"body": "<p>You're converting your text to ASCII ordinals (good-ish) but then converting those ordinals to binary-formatted strings (deeply ungood). A change of thinking is needed: rather than managing a string where every single character is either an ASCII "1" or an ASCII "0", you need to understand that byte arrays such as</p>\n<pre><code>b'I have a dream'\n</code></pre>\n<p>equivalent to the output of</p>\n<pre><code>'I have a dream'.encode()\n</code></pre>\n<p><em>are already binary</em> in memory. Each character here maps to one byte, which takes up eight bits in memory. Exclusive-or bitwise operations can and should operate on these bytes directly. It's doubtful that Numpy will be of any benefit here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T01:53:37.070",
"Id": "264399",
"ParentId": "264390",
"Score": "7"
}
},
{
"body": "<h2>Code review</h2>\n<pre><code>def addtrailingzero(byte):\n</code></pre>\n<p>Trailing zero's are generally thought of as being at the right hand side; English is read from left to right. You are left-padding the bits with zeros; the name should reflect that.</p>\n<hr />\n<pre><code>binary_text = array([bin(ord(char))[2:] for char in text])\nvectorizeF = vectorize(addtrailingzero)\nbyteArray_text = vectorizeF(binary_text)\n</code></pre>\n<p>This is hugely inefficient: first creating an array of a dynamic size, then adding each byte value and then reiterating over it. Instead, you should perform the operation on each byte before adding it to the array. In this case you should however simply use <code>format(ord('M'), "0>8b")</code>, which uses formatting with <code>0</code> as padding character, right aligning <code>></code> the binary encoding <code>b</code> of the given integer returned by <code>ord</code>.</p>\n<hr />\n<pre><code> def resizeKey(message, key):\n</code></pre>\n<p>Please note that repeating key values is completely insecure; it is called a "many-time pad" (as compared to the secure one-time pad) and can be broken almost instantly. And you don't have to resize the key at all; you can just using modular indexing (<code>key_index = index % key_size</code>) on the key length.</p>\n<hr />\n<pre><code>resize_byteArray_key = repeat(byteArray_key, r)\nresize_byteArray_key = resize_byteArray_key[:messageLength]\n</code></pre>\n<p>I know that Python is a higher level language; but please note that creating an array of the right size and then filling the array is much more performant. As it is, you would be winding up rewriting the application if you need it to perform well. If you use your constructs right then Python can be <em>concise and performant</em>.</p>\n<hr />\n<pre><code>if uniform(0, 1) < 0.5:\n</code></pre>\n<p>There is one thing that cryptographers don't like in their code: floating point. The reason for this is that floating point usually introduces rounding errors. Rounding errors may create bias, and bias in XOR means that the ciphertext may be biased as well. Biased output is <a href=\"https://en.wikipedia.org/wiki/Ciphertext_indistinguishability\" rel=\"nofollow noreferrer\">can be distinguished from random</a>.</p>\n<p><code>uniform</code> also isn't cryptographically secure. Using a non-secure random number generator is a complete no-go in cryptography. Instead you should be using <code>random.SystemRandom().randrange(2)</code> from the build in <code>random</code> module. If you look into that module you will also find methods for generating random bits and even bytes. However, while we are at it, you could just use <a href=\"https://docs.python.org/3/library/secrets.html#secrets.token_bytes\" rel=\"nofollow noreferrer\">secrets.token_bytes()</a>.</p>\n<p>Always beware of using deprecated methods. From the Numpy API documentation:</p>\n<blockquote>\n<p>New code should use the uniform method of a default_rng() instance instead; please see the Quick Start.</p>\n</blockquote>\n<hr />\n<pre><code>def decryptXOR(encrypted_message, key):\n</code></pre>\n<p>One of the nice things of the XOR cipher is that encryption is identical to decryption. When implemented correctly, you should be able to use only one place where you do the XOR. If you still want an <code>encrypt</code> and <code>decrypt</code> function then that's fine: just call a <code>crypt</code> function from both of them.</p>\n<h2>Shorter and better (spoiler alert!)</h2>\n<p>Here is code that:</p>\n<ul>\n<li>creates an actual, cryptographically secure key</li>\n<li>uses Pythoneske method names</li>\n<li>uses a generator to cycle over the characters of the key</li>\n<li>performs explicit ASCII encoding to go from text to binary</li>\n<li>but otherwise generates as few strings / byte arrays as possible</li>\n</ul>\n<p><strong>Python 3 version</strong></p>\n<pre><code>from secrets import token_bytes\n\ndef crypt_xor(message, key):\n result = bytearray(message)\n for i, k in enumerate(cycle(key, len(message))):\n result[i] ^= k\n return result\n\ndef cycle(s, max):\n n = len(s)\n return (s[i % n] for i in range(max))\n\nkey = bytes(token_bytes(3))\nencrypted_text = crypt_xor('I have a dream'.encode('ascii'), key)\ndecrypted_text = crypt_xor(encrypted_text, key)\nprint(decrypted_text.decode('ascii'))\n</code></pre>\n<p>Note that that the module <code>itertools</code> also contains a <code>cycle</code> method, but it caches the whole string, because it doesn't know that the iterable that it takes as input can be reset to the start again.</p>\n<p><strong>One liner in Python 3</strong></p>\n<p>OK, put it in a function, let's not overdo it.</p>\n<pre><code>def crypt_xor(message, key):\n return bytes(m ^ key[i % len(key)] for i, m in enumerate(message))\n</code></pre>\n<p><strong>Python 2 version</strong></p>\n<pre><code>from os import urandom\n\ndef crypt_xor(message, key):\n result = ''\n for (m, k) in zip(message, cycle(key, len(message))):\n result += chr(ord(m) ^ ord(k))\n return result\n\ndef cycle(s, max):\n n = len(s)\n return (s[i % n] for i in range(max))\n\nkey = urandom(3)\nencrypted_text = crypt_xor(b'I have a dream', key)\ndecrypted_text = crypt_xor(encrypted_text, key)\nprint(decrypted_text)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:43:37.607",
"Id": "524791",
"Score": "0",
"body": "This is more like a code review, but please note that I wholeheartely agree with [this answer about using actual bits instead of the characters `'0'` and `'1'`](https://codereview.stackexchange.com/a/264399/9555)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:39:59.580",
"Id": "265698",
"ParentId": "264390",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T19:37:51.510",
"Id": "264390",
"Score": "3",
"Tags": [
"python",
"encryption"
],
"Title": "Is this a true implementation of XOR in python?"
}
|
264390
|
<p>I am new to python, and even more new to vectorization. I have attempted to vectorize a custom similarity function that should return a matrix of pairwise similarities between each row in an input array.</p>
<p><strong>IMPORTS:</strong></p>
<pre><code>import numpy as np
from itertools import product
from numpy.lib.stride_tricks import sliding_window_view
</code></pre>
<p><strong>INPUT</strong>:</p>
<pre><code>np.random.seed(11)
a = np.array([0, 0, 0, 0, 0, 10, 0, 0, 0, 50, 0, 0, 5, 0, 0, 10])
b = np.array([0, 0, 5, 0, 0, 10, 0, 0, 0, 50, 0, 0, 10, 0, 0, 5])
c = np.array([0, 0, 5, 1, 0, 20, 0, 0, 0, 30, 0, 1, 10, 0, 0, 5])
m = np.array((a,b,c))
</code></pre>
<p><strong>OUTPUT:</strong></p>
<pre><code>custom_func(m)
array([[ 0, 440, 1903],
[ 440, 0, 1603],
[1903, 1603, 0]])
</code></pre>
<p><strong>FUNCTION:</strong></p>
<pre><code>def custom_func(arr):
diffs = 0
max_k = 6
for n in range(1, max_k):
arr1 = np.array([np.sum(i, axis = 1) for i in sliding_window_view(arr, window_shape = n, axis = 1)])
# this function uses np.maximum and np.minimum to subtract the max and min elements (element-wise) between two rows and then sum up the entire of that subtraction
diffs += np.sum((np.array([np.maximum(arr1[i[0]], arr1[i[1]]) for i in product(np.arange(len(arr1)), np.arange(len(arr1)))]) - np.array([np.minimum(arr1[i[0]], arr1[i[1]]) for i in product(np.arange(len(arr1)), np.arange(len(arr1)))])), axis = 1) * n
diffs = diffs.reshape(len(arr), -1)
return diffs
</code></pre>
<p>The function is quite simple, it sums up the element-wise differences between max and minimum of rows in N sliding windows. This function is much faster than what I was using before finding out about vectorization today (for loops and pandas dataframes yay).</p>
<p>My first thought is to figure out a way to find both the minimum and maximum of my arrays in a single pass since I currently THINK it has to do two passes, but I was unable to figure out how. Also there is a for loop in my current function because I need to do this for multiple N sliding windows, and I am not sure how to do this without the loop.</p>
<p>Any help is appreciated!</p>
<p>EDIT 1: There was a suggestion of removing the first list comprehension in my function with <code>arr1 = sliding_window_view(arr, window_shape = n, axis = 1).sum(axis=2)</code> but that actually slowed the function down significantly on larger datasets for some reason.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-25T20:40:09.753",
"Id": "264393",
"Score": "2",
"Tags": [
"python",
"numpy",
"vectorization"
],
"Title": "Vectorizing a working custom similarity function further using numpy"
}
|
264393
|
<h1 id="benchmark-0438">Benchmark</h1>
<p>An optimised 4x4 double precision matrix multiply using intel AVX intrinsics. Two different variations.</p>
<p><a href="https://gist.github.com/juliuskoskela/1a5ce40794325b2dac4a2a072ce5d404" rel="nofollow noreferrer">Gist</a></p>
<p>For quick benchmark (with a compatible system) copy paste the command below. Runs tests on clang and gcc on optimisation levels 0 -> 3. Runs a naive matrix multiplication NORMAL as a reference.</p>
<pre><code>curl -OL https://gist.githubusercontent.com/juliuskoskela/2381831c86041eb2ebf271011db7b2bf/raw/cebbcec5f2f02ac75c36e9346776cd97bf1e68a5/run.sh
bash run.sh >> M4X4D_BENCHMARK_RESULTS.txt
cat M4X4D_TEST_RESULTS.txt
</code></pre>
<p>Quick result Linux AMD Ryzen 3 3100 4-Core:</p>
<pre><code>(best)NORMAL
gcc -O1 -march=native -mavx
time: 0.168030
(best)AVX MUL + FMADD
clang -O1 -march=native -mavx
time: 0.033416
</code></pre>
<p>Results indicate that there is some discrepancy in optimisation between gcc and clang and on Linux and Mac OS. On Mac OS neither compiler is able to properly optimise the normal version. On Linux clang still didn't know how to optimise further, but gcc Managed to find the same speeds as we hit with the intrinsics version BUT only on -O1 and -O2 and NOT on -O3.</p>
<h1 id="code-cs3w">Code</h1>
<p>Version of the matrix multiplication which uses one multiply and
one multiply + add instruction in the inner loop. Inner loop is unrolled
and with comments.</p>
<pre class="lang-c prettyprint-override"><code>typedef union u_m4d
{
__m256d m256d[4];
double d[4][4];
} t_m4d;
// Example matrices.
//
// left[0] (1 2 3 4) | right[0] (4 1 1 1)
// left[1] (2 2 3 4) | right[1] (3 2 2 2)
// left[2] (3 2 3 4) | right[2] (2 3 3 3)
// left[3] (4 2 3 4) | right[3] (1 4 4 4)
static inline void m4x4d_avx_mul(
t_m4d *restrict dst,
const t_m4d *restrict left,
const t_m4d *restrict right)
{
__m256d ymm0;
__m256d ymm1;
__m256d ymm2;
__m256d ymm3;
// Fill registers ymm0 -> ymm3 with a single value
// from the i:th column of the left
// hand matrix.
//
// left[0] (1 2 3 4) -> ymm0 (1 1 1 1)
// left[1] (2 2 3 4) -> ymm1 (2 2 2 2)
// left[2] (3 2 3 4) -> ymm2 (3 3 3 3)
// left[3] (4 2 3 4) -> ymm3 (4 4 4 4)
ymm0 = _mm256_broadcast_sd(&left->d[0][0]);
ymm1 = _mm256_broadcast_sd(&left->d[0][1]);
ymm2 = _mm256_broadcast_sd(&left->d[0][2]);
ymm3 = _mm256_broadcast_sd(&left->d[0][3]);
// Multiply vector at register ymm0 with right row[0]
//
// 1 1 1 1 <- ymm0
// *
// 4 2 3 4 <- right[0]
// ----------
// 4 2 3 4 <- ymm0
ymm0 = _mm256_mul_pd(ymm0, right->m256d[0]);
// Multiply vector at register ymm1 with right hand
// row[1] and add at each multiply add the corresponding
// value at ymm0 tp the result.
//
// 2 2 2 2 <- ymm1
// *
// 3 2 3 4 <- right[1]
// +
// 4 2 3 4 <- ymm0
// ----------
// 10 6 9 12 <- ymm0
ymm0 = _mm256_fmadd_pd(ymm1, right->m256d[1], ymm0);
// We repeat for ymm2 -> ymm3.
//
// 3 3 3 3 <- ymm2
// *
// 2 2 3 4 <- right[2]
// ----------
// 6 6 9 12 <- ymm2
//
// 2 2 2 2 <- ymm3
// *
// 3 2 3 4 <- right[3]
// +
// 6 6 9 12 <- ymm2
// ----------
// 10 14 21 28 <- ymm2
ymm2 = _mm256_mul_pd(ymm2, right->m256d[2]);
ymm2 = _mm256_fmadd_pd(ymm3, right->m256d[3], ymm2);
// Sum accumulated vectors at ymm0 and ymm2.
//
// 10 6 9 12 <- ymm0
// +
// 10 14 21 28 <- ymm2
// ----------
// 20 20 30 40 <- dst[0] First row!
dst->m256d[0] = _mm256_add_pd(ymm0, ymm2);
// Calculate dst[1]
ymm0 = _mm256_broadcast_sd(&left->d[1][0]);
ymm1 = _mm256_broadcast_sd(&left->d[1][1]);
ymm2 = _mm256_broadcast_sd(&left->d[1][2]);
ymm3 = _mm256_broadcast_sd(&left->d[1][3]);
ymm0 = _mm256_mul_pd(ymm0, right->m256d[0]);
ymm0 = _mm256_fmadd_pd(ymm1, right->m256d[1], ymm0);
ymm2 = _mm256_mul_pd(ymm2, right->m256d[2]);
ymm2 = _mm256_fmadd_pd(ymm3, right->m256d[3], ymm2);
dst->m256d[1] = _mm256_add_pd(ymm0, ymm2);
// Calculate dst[2]
ymm0 = _mm256_broadcast_sd(&left->d[2][0]);
ymm1 = _mm256_broadcast_sd(&left->d[2][1]);
ymm2 = _mm256_broadcast_sd(&left->d[2][2]);
ymm3 = _mm256_broadcast_sd(&left->d[2][3]);
ymm0 = _mm256_mul_pd(ymm0, right->m256d[0]);
ymm0 = _mm256_fmadd_pd(ymm1, right->m256d[1], ymm0);
ymm2 = _mm256_mul_pd(ymm2, right->m256d[2]);
ymm2 = _mm256_fmadd_pd(ymm3, right->m256d[3], ymm2);
dst->m256d[2] = _mm256_add_pd(ymm0, ymm2);
// Calculate dst[3]
ymm0 = _mm256_broadcast_sd(&left->d[3][0]);
ymm1 = _mm256_broadcast_sd(&left->d[3][1]);
ymm2 = _mm256_broadcast_sd(&left->d[3][2]);
ymm3 = _mm256_broadcast_sd(&left->d[3][3]);
ymm0 = _mm256_mul_pd(ymm0, right->m256d[0]);
ymm0 = _mm256_fmadd_pd(ymm1, right->m256d[1], ymm0);
ymm2 = _mm256_mul_pd(ymm2, right->m256d[2]);
ymm2 = _mm256_fmadd_pd(ymm3, right->m256d[3], ymm2);
dst->m256d[3] = _mm256_add_pd(ymm0, ymm2);
}
</code></pre>
<p>Version of the matrix multiplication which uses two multiplies and and add in the inner loop.</p>
<pre class="lang-c prettyprint-override"><code>static inline void m4x4d_avx_mul2(
t_m4d *restrict dst,
const t_m4d *restrict left,
const t_m4d *restrict right)
{
__m256d ymm[4];
for (int i = 0; i < 4; i++)
{
ymm[0] = _mm256_broadcast_sd(&left->d[i][0]);
ymm[1] = _mm256_broadcast_sd(&left->d[i][1]);
ymm[2] = _mm256_broadcast_sd(&left->d[i][2]);
ymm[3] = _mm256_broadcast_sd(&left->d[i][3]);
ymm[0] = _mm256_mul_pd(ymm[0], right->m256d[0]);
ymm[1] = _mm256_mul_pd(ymm[1], right->m256d[1]);
ymm[0] = _mm256_add_pd(ymm[0], ymm[1]);
ymm[2] = _mm256_mul_pd(ymm[2], right->m256d[2]);
ymm[3] = _mm256_mul_pd(ymm[3], right->m256d[3]);
ymm[2] = _mm256_add_pd(ymm[2], ymm[3]);
dst->m256d[i] = _mm256_add_pd(ymm[0], ymm[2]);
}
}
</code></pre>
<p>Comparison matrix multiply that doesn't use intrinsics.</p>
<pre class="lang-c prettyprint-override"><code>static inline void m4x4d_mul(double d[4][4], double l[4][4], double r[4][4])
{
d[0][0] = l[0][0] * r[0][0] + l[0][1] * r[1][0] + l[0][2] * r[2][0] + l[0][3] * r[3][0];
d[0][1] = l[0][0] * r[0][1] + l[0][1] * r[1][1] + l[0][2] * r[2][1] + l[0][3] * r[3][1];
d[0][2] = l[0][0] * r[0][2] + l[0][1] * r[1][2] + l[0][2] * r[2][2] + l[0][3] * r[3][2];
d[0][3] = l[0][0] * r[0][3] + l[0][1] * r[1][3] + l[0][2] * r[2][3] + l[0][3] * r[3][3];
d[1][0] = l[1][0] * r[0][0] + l[1][1] * r[1][0] + l[1][2] * r[2][0] + l[1][3] * r[3][0];
d[1][1] = l[1][0] * r[0][1] + l[1][1] * r[1][1] + l[1][2] * r[2][1] + l[1][3] * r[3][1];
d[1][2] = l[1][0] * r[0][2] + l[1][1] * r[1][2] + l[1][2] * r[2][2] + l[1][3] * r[3][2];
d[1][3] = l[1][0] * r[0][3] + l[1][1] * r[1][3] + l[1][2] * r[2][3] + l[1][3] * r[3][3];
d[2][0] = l[2][0] * r[0][0] + l[2][1] * r[1][0] + l[2][2] * r[2][0] + l[2][3] * r[3][0];
d[2][1] = l[2][0] * r[0][1] + l[2][1] * r[1][1] + l[2][2] * r[2][1] + l[2][3] * r[3][1];
d[2][2] = l[2][0] * r[0][2] + l[2][1] * r[1][2] + l[2][2] * r[2][2] + l[2][3] * r[3][2];
d[2][3] = l[2][0] * r[0][3] + l[2][1] * r[1][3] + l[2][2] * r[2][3] + l[2][3] * r[3][3];
d[3][0] = l[3][0] * r[0][0] + l[3][1] * r[1][0] + l[3][2] * r[2][0] + l[3][3] * r[3][0];
d[3][1] = l[3][0] * r[0][1] + l[3][1] * r[1][1] + l[3][2] * r[2][1] + l[3][3] * r[3][1];
d[3][2] = l[3][0] * r[0][2] + l[3][1] * r[1][2] + l[3][2] * r[2][2] + l[3][3] * r[3][2];
d[3][3] = l[3][0] * r[0][3] + l[3][1] * r[1][3] + l[3][2] * r[2][3] + l[3][3] * r[3][3];
};
</code></pre>
<p>Main method and utils</p>
<pre class="lang-c prettyprint-override"><code>///////////////////////////////////////////////////////////////////////////////
//
// Main and utils for testing.
t_v4d v4d_set(double n0, double n1, double n2, double n3)
{
t_v4d v;
v.d[0] = n0;
v.d[1] = n1;
v.d[2] = n2;
v.d[3] = n3;
return (v);
}
t_m4d m4d_set(t_v4d v0, t_v4d v1, t_v4d v2, t_v4d v3)
{
t_m4d m;
m.m256d[0] = v0.m256d;
m.m256d[1] = v1.m256d;
m.m256d[2] = v2.m256d;
m.m256d[3] = v3.m256d;
return (m);
}
int main(int argc, char **argv)
{
t_m4d left;
t_m4d right;
t_m4d res;
t_m4d ctr;
if (argc != 2)
return (printf("usage: avx4x4 [iters]"));
left = m4d_set(
v4d_set(1, 2, 3, 4),
v4d_set(2, 2, 3, 4),
v4d_set(3, 2, 3, 4),
v4d_set(4, 2, 3, 4));
right = m4d_set(
v4d_set(4, 2, 3, 4),
v4d_set(3, 2, 3, 4),
v4d_set(2, 2, 3, 4),
v4d_set(1, 2, 3, 4));
size_t iters;
clock_t begin;
clock_t end;
double time_spent;
// Test 1
m4x4d_mul(ctr.d, left.d, right.d);
iters = atoi(argv[1]);
begin = clock();
for (size_t i = 0; i < iters; i++)
{
m4x4d_mul(res.d, left.d, right.d);
// To prevent loop unrolling with optimisation flags.
__asm__ volatile ("" : "+g" (i));
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\nNORMAL\n\ntime: %lf\n", time_spent);
// Test 2
m4x4d_avx_mul(&ctr, &left, &right);
iters = atoi(argv[1]);
begin = clock();
for (size_t i = 0; i < iters; i++)
{
m4x4d_avx_mul(&res, &left, &right);
__asm__ volatile ("" : "+g" (i));
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\nAVX MUL + FMADD\n\ntime: %lf\n", time_spent);
// Test 3
m4x4d_avx_mul2(&ctr, &left, &right);
iters = atoi(argv[1]);
begin = clock();
for (size_t i = 0; i < iters; i++)
{
m4x4d_avx_mul2(&res, &left, &right);
__asm__ volatile ("" : "+g" (i));
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\nAVX MUL + MUL + ADD\n\ntime: %lf\n", time_spent);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T08:20:33.483",
"Id": "522161",
"Score": "0",
"body": "You've clearly done your homework, but can you explain a bit about the expected usage patterns? For example, it makes a difference whether the operands/result are always expected to be in memory (not from the point of view of C, but in reality), or might have preferred to be in registers (eg when \"chaining\" multiplications). It's fine if it's supposed to be general purpose too, but if it isn't then I can avoid making recommendations that are inappropriate for your use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T08:37:14.917",
"Id": "522162",
"Score": "1",
"body": "I don’t have a clear use case for this. The project was born out of just curiosity. I was thinking it could be one step in calculating a bigger matrix for example, possibly in a multithreaded way. Any speculation as to the strenghts and weaknessess of the approach is welcome. I should also update the benchmarks. Need to tag the functions with __attribute__((noinline)) to get proper results. When the compiler isn’t able to inline test loop I get a more reasonable result with the AVX methdo being clearly superior."
}
] |
[
{
"body": "<p>It looks pretty good to me. I still have some notes to make.</p>\n<p>Let's start with, there are 5 arithmetic operations (per row) to do the work that 4 FMAs could do. How good or bad is that? Well basically not bad at all in the context of just a simple 4x4 multiplication, because there are also 8 loads for those 5 arithmetic operations, so the problem is the loads. OTOH there is also no advantage of "splitting" the calculation in that case, because having the FMAs of a single row all in a dependent chain wouldn't matter in that context. That picture can change though. For example in next example with 3 matrices, the second half of the code still has 5 arithmetic operations per row but only 4 loads in the good case. But chaining also means that the latency of calculating a row matters, and therefore splitting up the dependency chain into more of a tree the way you did becomes increasingly more interesting as you chain more multiplications .. but how interesting exactly, given that the calculations for different rows are independent, I couldn't say. So how does it balance? Who knows, try it.</p>\n<p>Here's an odd thing about this code: let's compare which order to multiply 3 matrices in, (AB)C or A(BC)</p>\n<p>Like (AB)C:</p>\n<pre><code>void m4x4d_avx_mul3(\n t_m4d *restrict dst,\n const t_m4d *restrict A,\n const t_m4d *restrict B,\n const t_m4d *restrict C)\n{\n t_m4d tmp;\n m4x4d_avx_mul(&tmp, A, B);\n m4x4d_avx_mul(dst, &tmp, C);\n}\n</code></pre>\n<p>(<a href=\"https://godbolt.org/z/5xM8ananb\" rel=\"nofollow noreferrer\">on godbolt</a>)</p>\n<p>Or like A(BC):</p>\n<pre><code>void m4x4d_avx_mul3(\n t_m4d *restrict dst,\n const t_m4d *restrict A,\n const t_m4d *restrict B,\n const t_m4d *restrict C)\n{\n t_m4d tmp;\n m4x4d_avx_mul(&tmp, B, C);\n m4x4d_avx_mul(dst, A, &tmp);\n}\n</code></pre>\n<p>(<a href=\"https://godbolt.org/z/sj4v64evv\" rel=\"nofollow noreferrer\">on godbolt</a>)</p>\n<p>Algebraically that's the same thing, but perhaps surprisingly, the second way works out better: that way, <code>tmp</code> is <em>not</em> actually written to scratch space on the stack, it is created in vector registers and those registers are then used as input for the second multiply. That cannot happen in the first implementation, because then <code>tmp</code>'s individual entries are broadcasted from. OK actually it could happen, but GCC didn't do it and it would have to use shuffles to make it happen, which aren't that cheap.</p>\n<p>It's not necessarily bad that it works out like this, but something to keep in mind.</p>\n<p>You've mentioned in the comments that you could use this as part of multiplying larger matrices. That is possible, but it wouldn't be as good as it could be, by a significant margin. The problem with that is that 4x4 is too small, which causes two issues. First, it makes the ratio of loads to arithmetic too high. There are 8 loads to 4 FMAs here, but the ratio should be 1:1 or less, to avoid bottlenecking on loads (most modern hardware can execute two of each per cycle, except that loads tend to be slower on average due to various factors so you should even below 1:1). For actual 4x4 matrices there is no hope of achieving that, but for larger matrices there is, namely by using a bigger "small matrix".</p>\n<p>For example using a 6x8 matrix as the base (6 rows deep, 2 vectors wide) would give you an inner loop with:</p>\n<ul>\n<li>2 vector loads</li>\n<li>6 broadcasted scalar loads</li>\n<li>12 FMAs</li>\n</ul>\n<p>That still does not exceed the vector register budget, which is 16 on x64. Unfortunately a nice round 8x8 <em>would</em> exceed the register budget and introduce spilling, which rules out that strategy.</p>\n<p>By the way I counted only FMAs and no muls, not only because they are equivalent in cost anyway, but also because if you add tiling (which is essentially mandatory for multiplying big matrices) then you will be starting with a non-zero destination matrix and adding more products into it.</p>\n<p>Another issue with basing large matrix multiplication on the multiplication of 4x4 matrices is that it would either (when multiplying a bunch of independent 4x4 matrices, ie the products aren't summed) force a lot of stores (which is not great) or (when accumulating several products before storing them) it would run into the high latency-throughput product of FMA on typical hardware (commonly ranging from 8 to even 10). If the latency-throughput product is 8 (for example a latency of 4 and a throughput of 2/cycle) then that means there must be at least 8 independent FMAs simultaneously in the pipeline to keep it full, and a 4x4 matrix normally only has 4 independent FMAs at any time. It <em>does</em> have 8 if you decouple it like you did, but that also costs more work, so at a large scale it's better to get those independent FMAs by Going Big and not doing that decoupling.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:24:26.367",
"Id": "522177",
"Score": "0",
"body": "Thanks for the great insights! Good point that I should look into rectangular divisions of the matrix as well when scaling the algorithm. Btw. I updated the tests so that the functions wouldn't be inlined into the main loop on higher O levels. Now I'm seeing a more consistent gain across the board and also the MUL + FMADD edging slightly ahead of MUL + MUL + ADD."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:56:44.743",
"Id": "264409",
"ParentId": "264397",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T00:31:32.057",
"Id": "264397",
"Score": "4",
"Tags": [
"performance",
"c",
"assembly",
"graphics",
"x86"
],
"Title": "4x4 double precision matrix multiply using AVX intrinsics (inc. benchmarks)"
}
|
264397
|
<p>i have created an object orientated Calculator without GUI.</p>
<p>i have provided only the most important parts of the code. I want to add another review question for those parts (especially: <code>MathResult</code> and <code>Operands</code>)</p>
<h2 id="interface-calculator">Interface Calculator</h2>
<pre><code>public interface Calculator {
MathResult<?> calculate(String operation);
}
</code></pre>
<h2 id="interface-operationparser">Interface OperationParser</h2>
<pre><code>public interface OperationParser<T> {
boolean matches(String operation);
Operation<T> getOperation();
}
</code></pre>
<h2 id="example-implementation-simplecalculator">example-implementation: SimpleCalculator</h2>
<pre><code>public class SimpleCalculator implements Calculator {
private final List<OperationParser<?>> operationParsers = new ArrayList<>();
public SimpleCalculator(){
operationParsers.add(new SimpleInfixArithmeticOperationParser(MathContext.DECIMAL64));
operationParsers.add(new SimpleTrigonometricOperationParser());
}
@Override
public MathResult<?> calculate(String input) {
Optional<OperationParser<?>> parser = operationParsers.stream().filter(ip -> ip.matches(input)).findAny();
if(parser.isPresent()){
System.out.println("calculating "+parser.get().getOperation());
return parser.get().getOperation().calculate();
}else {
throw new IllegalArgumentException("no valid parser for input '"+input+"' found");
}
}
}
</code></pre>
<h2 id="math-result">Math Result</h2>
<pre><code>public class MathResult<T> {
private final T t;
public MathResult(T t) {
this.t = t;
}
@Override
public String toString() {
String type = t == null ? "null" : t.getClass().getSimpleName();
return "MathResult{" + type + ':' + t + '}';
}
}
</code></pre>
<h2 id="operation">Operation</h2>
<pre><code>public class Operation<T> {
public final Operands<T> operands;
public final String operationSymbol;
public final Function<Operands<T>, MathResult<T>> function;
public Operation(Operands<T> operands,String operationSymbol, Function<Operands<T>, MathResult<T>> function){
this.operands = operands;
this.operationSymbol = operationSymbol;
this.function = function;
}
public MathResult<T> calculate() {
return function.apply(operands);
}
}
</code></pre>
<h2 id="operands">Operands</h2>
<pre><code>public class Operands<T> {
private final T first;
private final T second;
public Operands(T single) {
this(single, null);
}
public Operands(T first, T second) {
if (first == null) {
throw new IllegalArgumentException("first (single) operand must be set");
}
this.first = first;
this.second = second;
}
public T get() {
return getFirst();
}
public T getFirst() {
return first;
}
public T getSecond() {
if (second == null) {
throw new IllegalArgumentException("second Operand does not exist");
}
return second;
}
}
</code></pre>
<h2 id="main-class">main Class</h2>
<pre><code>public class CalculatorApp {
public static void main(String[] args){
final Calculator calculator = new SimpleCalculator();
final Scanner scanner = new Scanner(System.in);
final Pattern exitPattern = Pattern.compile("[eE][xX][iI][tT]");
while (true) {
String line = scanner.nextLine();
if(exitPattern.matcher(line).matches()){
break;
}
try {
MathResult<?> result = calculator.calculate(line);
System.out.println("result: " + result);
}catch (Exception e){
System.out.println("error: " + e);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:00:14.643",
"Id": "522163",
"Score": "1",
"body": "I'd like to comment about the classes/interfaces architecture, but you've left out too many classes/interfaces to do that, e.g. `Operation`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:00:16.843",
"Id": "522164",
"Score": "0",
"body": "i found https://codereview.stackexchange.com/questions/224467/object-oriented-calculator?rq=1 tio be similar - this question didn't pop up when i was submitting my code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:01:24.757",
"Id": "522165",
"Score": "0",
"body": "@RalfKleberhoff: I will open a new Question providing those, just after lunch (it`s 11°° right now)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:02:54.100",
"Id": "522166",
"Score": "2",
"body": "Please, include all interfaces, and at least one implementation of every interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:06:44.180",
"Id": "522167",
"Score": "0",
"body": "i will add those asap, sorry, i^m at work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:13:12.100",
"Id": "522168",
"Score": "0",
"body": "@RalfKleberhoff i have added all execpt the Parser Implementation"
}
] |
[
{
"body": "<h2 id=\"naming\">Naming</h2>\n<p>What you call "operation", in most cases I'd rename to be an "expression".</p>\n<h2 id=\"documentation\">Documentation</h2>\n<p>You create a quite complex set of classes and interfaces, and the only hint about their usage is in the class and method names. You should add Javadoc comments at least to public classes, interfaces and methods.</p>\n<h2 id=\"interface-operationparser\">Interface OperationParser</h2>\n<pre><code>public interface OperationParser<T> {\n boolean matches(String operation);\n Operation<T> getOperation();\n}\n</code></pre>\n<p><code>getOperation()</code> doesn't have parameters, so where does it get its input (expression text form) from? Probably, you rely on it being called only after a <code>matches()</code> call, and save the expression internally in some field. This goes against the expectations of callers, and will make any multi-threaded use of the parser impossible.</p>\n<h2 id=\"generics\">Generics</h2>\n<p>You often use a type variable <code>T</code>, but it's not clear what it's meant to be (for lack of Javadoc). My best guess is that it might be the number type you deal with, expecting e.g. <code>Integer</code> or <code>Double</code>, and then I'd recomment to specify that like <code><T extends Number></code>.</p>\n<p>In the <code>Operation</code> class, you assume both operands as well as the result to be of the same type. What about dviding two integers? In math (as opposed to many programming languages), this gives a rational number, and generally not an integer.</p>\n<h2 id=\"user-interface\">User interface</h2>\n<p>In the <code>SimpleCalculator.calculate()</code> method, you print to <code>System.out</code>. If that's meant for debugging, use some logging framework instead (a basic one comes with the JRE: the <code>java.util.logging</code> package).</p>\n<p>If it's really meant for the user, restructure your code. It's not some <code>calulate()</code> method's responsibility to tell something to a user. A <code>calulate()</code> method should calculate things and return the calculation results to the caller.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T04:21:23.687",
"Id": "522231",
"Score": "0",
"body": "the `OperationParser` Interface indeed violates the contract, that felt already bad when i was writing it! thank you, this is indeed not a good design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T04:23:52.173",
"Id": "522232",
"Score": "0",
"body": "`Operation` indeed is of `Double` precision for trigonometric operations, its of precision `BigDecimal` for arithmetic operations and of `Boolean` for bool operations... depending on the input - i am also thinking of a `HexNumber` for a Base16 calculator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T06:12:22.950",
"Id": "522237",
"Score": "0",
"body": "That was a very insightful Review - thank you very Much (+1 & accept)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:55:00.810",
"Id": "264415",
"ParentId": "264403",
"Score": "3"
}
},
{
"body": "<h1>Naming</h1>\n<p><em><code>MathResult</code></em>; I was wondering why the prefix <code>Math</code> in <code>MathResult</code> is important. Are there other types of results? If not, we can keep it simple and only name it <code>Result</code>.</p>\n<p><em><code>Operation</code></em>; As <a href=\"https://codereview.stackexchange.com/users/145549/ralf-kleberhoff\">@Ralf Kleberhoff</a> already points out, would <code>Expression</code> a better fit. The grouping of operations and operands is an <em>expression</em>, where an <em>operation</em> is a function such as addition, subtraction and so on, and an operand is a number.</p>\n<p><em><code>OperationParser</code></em>; A better fit would be <code>ExpressionParser</code>, like described in <code>Operation</code>.</p>\n<h1>Generics</h1>\n<p>In addition to <a href=\"https://codereview.stackexchange.com/users/145549/ralf-kleberhoff\">@Ralf Kleberhoff</a>, I would like to point out that operands can only have the same type. The Expression <code>1 + 1.5</code> is not possible.</p>\n<p><em>(Every operand could be a <code>Double</code> and to display an <code>Integer</code> can be the work of the UI-Logic)</em></p>\n<h1>The Calculator</h1>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Calculator {\n MathResult<?> calculate(String operation);\n}\n</code></pre>\n</blockquote>\n<p>The calculator is bound to <code>String</code>. Instead, you can use a custom data type that abstracts <code>String</code>. The abstraction is already in your code: <code>Operation</code> (which we will call <code>Expression</code>):</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Calculator {\n Result calculate(Expression expression);\n}\n</code></pre>\n<p>This method signature makes more sense: <em>A calculator calculates a result based on an expression.</em></p>\n<h1>The Simple Calculator</h1>\n<p>After we changed the method signature of <code>Calculator</code> the <code>SimpleCalculator</code> will change, too.</p>\n<p>Without the change the <code>SimpleCalculator</code> has four responsibilities:</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>MathResult<?> calculate(String input) { \n Optional<OperationParser<?>> parser = // 1. Parse the string input\n if(parser.isPresent()){\n System.out.println(/* 2. print message */)\n return // 3. calculate the result\n }else {\n // 4. handle wrong input\n }\n}\n</code></pre>\n</blockquote>\n<p>Just as a hint, we could use the methods on <code>Optional</code> to get a code like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>MathResult<?> calculate(String input) { \n Result result = operationParsers.stream()\n .filter(ip -> ip.matches(input))\n .findAny()\n .map(parser -> parser.getOperation().calculate())\n .orElseThrow(() -> new IllegalArgumentException("no valid parser for input '"+input+"' found"));\n System.out.println("calculating" + result.getOperation())\n}\n</code></pre>\n<p>With the change of the method signature (from The Calculator) we can reduce the number of responsibilities to two:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Result calculate(Expression expression) { \n System.out.println(/* 1. print message */)\n return // 2. calculate the result\n}\n</code></pre>\n<p>If you want to go further, we can even divide these responsibilities with the help of the <a href=\"https://refactoring.guru/design-patterns/decorator\" rel=\"nofollow noreferrer\">Decorator Pattern</a>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class SimpleCalculator implements Calculator {\n Result calculate(Expression expression) { \n return expression.calculate();\n }\n}\n\nclass LogCalculationDecorator implements Calculator {\n private final Calculator calculator;\n\n Result calculate(Expression expression) { \n System.out.println(/* ... */)\n return calculator.calculate(expression);\n }\n}\n\n// in main or else where\nvar calculator = new LogCalculationDecorator(new SimpleCalculator());\ncalculator.calculate(expression);\n</code></pre>\n<p>We can even add a Decorator to validate the expression; for example, to ensure that it is not a division with 0:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class ValidateCalculationDecorator implements Calculator {\n private final Calculator calculator;\n\n Result calculate(Expression expression) { \n if(/* is division by zero*/) {\n throw new // exception;\n }\n \n return calculator.calculate(expression);\n }\n}\n\n// in main or else where\nvar calculator = new ValidateCalculationDecorator(\n new LogCalculationDecorator(\n new SimpleCalculator()));\ncalculator.calculate(expression);\n</code></pre>\n<p>It is not necessary to use the Decorator, I just want to mention that it would fit. Instead we can even simply use Dependency Injection:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class SimpleCalculator implements Calculator {\n private final Validator validator;\n private final Logger logger;\n\n Result calculate(Expression expression) { \n validator.throwIfNotValid(expression)\n logger.log(expression);\n return expression.calculate();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:20:03.240",
"Id": "524584",
"Score": "0",
"body": "i had the same idea when i first tried to implement the calculator: using a predefined `Operation` (well ok, `Expression` i might **really** take up that point) - But after my first implementation i moved back to String to allow any input, just as a calculator should do. If the input is valid, the calculator delivers an result, if it is not a valid input then you´ll get an error message"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:21:50.900",
"Id": "524585",
"Score": "0",
"body": "The generic part is for handling different types of input... not just numbers, it might also be booleans .... but i had even further ideas, where you would provide functions (f(x) = y) which would result in another function)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:24:01.950",
"Id": "524586",
"Score": "0",
"body": "about the four responsibilities - i accidently hat that System.out. call - that should definitly be removed. and using streams is definitely the right idea, which i should follow up!! thanks for that clearing here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:27:24.593",
"Id": "524587",
"Score": "0",
"body": "the Operation is responsible to handle mathematical incorrct input - and throw an exception, when calculated - this is intended to happen there - and it would be an overkill to manually check the input. what comes after div/zero? taking root from negative? ups, having irrational numbers? tl'dr: **the operation (expression) handles that**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:29:55.083",
"Id": "524588",
"Score": "0",
"body": "**THANK YOU VERY MUCH** for your Review - you showed a bunch of ideas that are valuabe and worth following! and a good eye on what is not so good on my approach! please keep up reviewing - your review is inspiring!!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:49:00.410",
"Id": "265560",
"ParentId": "264403",
"Score": "1"
}
},
{
"body": "<p>I want to add to the other answers and provide a different more drastic suggestion and a more generic and (I think) clean approach.</p>\n<p>This is the perfect example where a nice class hierarchy shines.</p>\n<p>This is also the perfect example where to use visitors.</p>\n<p>I think in this case everything should be an expression.</p>\n<p>First, the problem can be broken down in separate blocks:</p>\n<ul>\n<li><strong>Representation of the expression in memory</strong>: The Expression class hierarchy</li>\n<li><strong>Building the expressions from strings</strong>: The parser for infix notation</li>\n<li><strong>Evaluating the expressions</strong>: evaluate() method on Expression interface (or ExpressionEvaluator visitor)</li>\n<li><strong>Printing the expressions</strong>: toString() method on Expression interface (or ExpressionWriter visitor)</li>\n</ul>\n<p>Get rid of MathResult and Operands. Everything can be an Expression.</p>\n<pre><code>interface Expression {\n Expression evaluate();\n String toString();\n}\n</code></pre>\n<p>MathResult should be a Literal->Expression just like inputs, a Literal is just a number. You can also define different literals for different types if you want to be more generic (BooleanLiteral, Stringliteral, etc..)</p>\n<pre><code>class Int->Literal->Expression {\n int value;\n Expression evaluate() {return this};\n String toString() {\n return intToString(value);\n }\n}\n</code></pre>\n<p>Operation is an expression, you will have to add classes for each operation:</p>\n<pre><code>abstract class BinaryExpression {\n Expression left;\n Expression right;\n}\n\npublic class Addition->BinaryExpression {\n int value;\n Expression evaluate() {\n Expression r = right.evaluate();\n Expression l = left.evaluate()\n if (l and r are Int)\n return new Int( l.value() + r.value())\n else\n return new Addition(l, r);\n };\n\n String toString() {\n return left.toString() + " + " + right.toString();\n }\n}\n</code></pre>\n<p><strong>The Parser</strong></p>\n<p>The parser will turn strings into expression hierarchy, e.g:</p>\n<pre><code>"1 + 2" -> new Add(new Int(1), new Int(2))\n</code></pre>\n<p>A more complex parser might be able to read and create more complex expressions, e.g:</p>\n<pre><code>"1 * (2 + 4)" -> new Mul(Int(1),Add(Int(2),Int(4)))\n</code></pre>\n<p>There are software that helps you create parsers e.g.: javaCC</p>\n<p>And then to use it:</p>\n<pre><code>Expression e = ExpressionInfixParser.parse("2 + 4");\nprint(e.toString()) //prints "2 + 4"\nprint(e.evaluate().toString()) //prints "6"\n</code></pre>\n<p>As you can see the class hierarchy is very generic and can represent many different expressions as long as you implement the operations you are interested in and the parser can read them. The interfaces are also very simple.</p>\n<p>You can move the evaluate and toString code to separate <strong>visitors</strong> if you want to separate the representations from the logic. This can be useful, for example, if you want to be able to print your expression with different notations you can have different visitors that share a lot of code: ExpressionPrefixWriter, ExpressionInfixWriter, ExpressionPostfixWriter.</p>\n<p>You can also easily extend the functionality with additional classes, e.g. you can have a Variable class that represent generic variables:</p>\n<pre><code>class Variable->Expression {\n String name;\n String toString() {\n return name;\n }\n Expression evaluate( Context context ) {\n if (context.contains(name))\n return context[name];\n else\n return this;\n }\n}\n</code></pre>\n<p>And then evaluate expression in different contexts, a context can be as simple as:</p>\n<pre><code>class Context -> Map<String, Expression> {}\n</code></pre>\n<p>Example:</p>\n<pre><code>Expression e = ExpressionInfixParser.parse("a * ( 2 * 2 ) + b");\n\nprint(e.toString()) //prints "a * ( 2 * 2 ) + b"\n\nprint(e.evaluate().toString()) //prints "a * 4 + b"\n\nContext c = {{"a", new Int(5)}}\nprint(e.evaluate(c).toString()) //prints "20 + b"\n\nContext c = {{"a", Int(2)}, {"b", Int(9)}}\nprint(e.evaluate(c).toString()) //prints "17"\n</code></pre>\n<p>Sorry for the code syntax, it is more of a pseudocode.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T06:06:09.043",
"Id": "524608",
"Score": "0",
"body": "using a class hierarchy instead of generics is really worth a look! might simplify some more thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T06:07:44.723",
"Id": "524609",
"Score": "0",
"body": "the parser part is a bit more bloated than the calculator - i want to make a separate review about the parsers later. i will notify you when it's online!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T06:08:41.257",
"Id": "524610",
"Score": "0",
"body": "Thank you for the Review you provided a nice aspekt on the `Operation` (ehm: `Expression`) !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:21:48.923",
"Id": "524683",
"Score": "0",
"body": "If your parser becomes too complex and you want to expand the functionalities (e.g. parse functions calls, variables, etc..) you should consider using a parser generator: JavaCC or ANTLR or one of the many others."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T21:07:17.927",
"Id": "265588",
"ParentId": "264403",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264415",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T06:30:02.730",
"Id": "264403",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"reinventing-the-wheel"
],
"Title": "Java OOP Calculator (no GUI)"
}
|
264403
|
<p>I would like to ask you to verify the following implementation of the <a href="https://en.cppreference.com/w/cpp/language/pimpl" rel="nofollow noreferrer">PIMPL</a> idiom. In this dummy implementation the stream is read into a string.</p>
<p>X.h</p>
<pre><code>#ifndef X_H
#define X_H
#include <memory>
#include <istream>
namespace mynamespace
{
class X
{
class XImplementation;
std::unique_ptr<XImplementation> _implementation;
X();
void swap(X& other);
public:
X(std::istream& stream);
X(const X& copyFrom);
X& operator=(const X& copyFrom);
X(X&& moveFrom);
X& operator=(X&& moveFrom);
~X();
std::string get_info();
}
}
#endif // X_H
</code></pre>
<p>X.cpp</p>
<pre><code>#include "X.h"
using namespace mynamespace;
class X::XImplementation
{
std::string _contents;
public:
XImplementation(std::istream& stream)
: _contents(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()) { }
std::string get_info()
{
return _contents;
}
};
X::X() = default;
void X::swap(X& other)
{
std::swap(_implementation, other._implementation);
}
X::X(std::istream& stream) : _implementation(new X::XImplementation(stream)) { }
X::X(const X& copyFrom) : _implementation(new XImplementation(*copyFrom._implementation)) { };
X& X::operator=(const X& copyFrom)
{
X temp(copyFrom);
swap(temp);
return *this;
}
X::X(X&& moveFrom)
{
swap(moveFrom);
}
X& X::operator=(X&& moveFrom)
{
swap(moveFrom);
return *this;
}
X::~X() = default;
std::string X::get_info()
{
return _implementation->get_info();
}
</code></pre>
<p>I tried my best to use <a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom">copy-and-swap</a> idiom to implement all the constructors. I wanted to make sure that X can be passed by value correctly. I am mostly wandering about this part, because I used a private method to implement the swap and <a href="https://stackoverflow.com/questions/5695548/public-friend-swap-member-function">here</a> a public friend function is suggested.</p>
<p>I will appreciate any suggestions and critiques.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T15:43:50.940",
"Id": "522200",
"Score": "0",
"body": "`mynamespace::X` doesn't look like __real code__ from a project you wrote or maintain, so isn't within scope for Code Review. See [help centre](/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T17:59:06.247",
"Id": "522204",
"Score": "1",
"body": "Does not really implement the PIMP pattern, does it. You are just asking if you have correctly implemented the Copy/Move semantics of an object with an owned pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:45:36.130",
"Id": "522208",
"Score": "0",
"body": "@TobySpeight yes, you are correct, this is not the real code. I apologize, I didn't know this rule and I will need to accept if you decide to close/downvote this question. I will try to take care about that rule in the future. I would like to say that the accepted answer has helped me and I am grateful for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:50:30.477",
"Id": "522209",
"Score": "0",
"body": "@MartinYork could you elaborate what would be a PIMPL pattern? I have to admit that I had biggest issues with the copy/move semantics, but I thought that forwarding the method call to the implementation is the PIMPL pattern as demonstrated by the `get_info` method. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T21:28:42.607",
"Id": "522218",
"Score": "2",
"body": "https://www.bfilipek.com/2018/01/pimpl.html The pimple pattern uses one class to implement the interface and another class that holds an object to that implementation and forwards any calls. But both of these classes have the same interface. Are you saying that your interface is `get_info()` sure."
}
] |
[
{
"body": "<pre><code> X();\n</code></pre>\n<p>Since we specify a value constructor, the compiler won't generate the default constructor. So we don't need to declare it <code>private</code> to prevent its use.</p>\n<hr />\n<p>The move operators can declared <code>= default</code>:</p>\n<pre><code> X(X&& moveFrom) = default;\n X& operator=(X&& moveFrom) = default;\n</code></pre>\n<p>You actually appear to have two copy assignment operators instead of a move assignment operator!</p>\n<hr />\n<pre><code>std::swap(_implementation, other._implementation);\n</code></pre>\n<p>The best way to call <code>swap</code> is like so:</p>\n<pre><code>using std::swap;\nswap(a, b);\n</code></pre>\n<p>This means that a swap function declared in the same namespace as the type being swapped will be found first. If there isn't one we'll fall back to using <code>std::swap</code>.</p>\n<hr />\n<p>A public friend function is a common way to implement swap. Obviously a private function can't be called externally.</p>\n<p>Note that we don't actually <em>have</em> to implement a swap function at all. The unspecialized version of <code>std::swap</code> will work for us, using our move constructor and move assignment operators.</p>\n<hr />\n<pre><code>namespace mynamespace ...\n</code></pre>\n<p>The class <code>X</code> is in this namespace, but the function implementations aren't?</p>\n<hr />\n<p>Please check that your code compiles, runs, and behaves as desired before posting it for review!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T12:27:37.433",
"Id": "522187",
"Score": "0",
"body": "I would like to apologize for not compiling the code, I have corrected and try to highlight the differences. Thank you for the response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:44:58.160",
"Id": "264414",
"ParentId": "264407",
"Score": "6"
}
},
{
"body": "<p>An important point of the PIMPL is that it helps you hide details that you do not want to leak out to the public.</p>\n<p>This means your header <code>#include</code> list is not expected to have more than the bare minimum and at times even no <code>#include</code> at all (although this last case is really rare).</p>\n<p>Any class, struct, etc. used in your header file has to be declared in some way. For <code>std::string</code>, you can just do <code>#include <string></code>. However, if you are implementing a class which access some Unix headers such as <code>#include <sys/stat.h></code>, but your class definition doesn't need to present that part to the end user, then the PIMPL can be useful.</p>\n<pre><code>#include <sys/stat.h>\n\nnamespace mynamespace\n{\nclass X::Implementation\n{\n struct stat st = {};\n...\n</code></pre>\n<p>Now your class has a <code>stat</code> object in its implementation, but from the outside you don't have direct access. Maybe you have functions such as <code>is_dir()</code> which return true if the file represents a directory. All of that without leaking the <code>S_ISDIR()</code> and similar macros offered by <code><sys/stat.h></code>.</p>\n<p>If you do not have such <code>#include</code> in your .cpp file as a result, then your PIMPL is probably not useful. You can as well put all the fields you need in your main class (<code>X</code> in your case) and avoid having to duplicate all the functions.</p>\n<p>That being said, in your case you have a <code>swap()</code> function which can make it useful to have a PIMPL just so you can easily implement that one function. I rarely see people doing that, but I think it's a valid case too.</p>\n<hr />\n<p>As a side note, although you just don't need to declare the <code>X()</code> constructor, if you do not want people to use such, since C++11, we use the delete keyword like so:</p>\n<pre><code>class X\n{\npublic:\n X() = delete;\n ...\n</code></pre>\n<p>If you use effective C++ warnings in g++ (i.e. <code>g++ -Weffc++</code>), then it is often required to delete the copy constructor and operators if (1) not necessary and (2) you have bare pointers in your class. The delete syntax is the best way to get rid of those two functions and as a result, the warnigs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:45:40.367",
"Id": "265518",
"ParentId": "264407",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264414",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:35:32.133",
"Id": "264407",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "An implementation of the PIMPL idiom"
}
|
264407
|
<p>This is the first time I have recoded in C for several years and I would like to know how clean my code is.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#define EXIT_SUCCESS 0
void fizzbuzz(int n) {
char result[9] = ""; // strlen("fizzbuzz") + 1 == 9
if (n % 3 == 0) strcat(result, "fizz");
if (n % 5 == 0) strcat(result, "buzz");
if (!*result) sprintf(result, "%d", n);
printf("%s\n", result);
}
int main() {
for (int i = 1; i <= 100; i++) fizzbuzz(i);
return EXIT_SUCCESS;
}
</code></pre>
<p>I know that I could include <code>stdlib</code> so as not to have to define <code>EXIT_SUCCESS</code> myself, but as I only needed this constant, it's a little clearer and more efficient to do this I think.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T09:21:40.827",
"Id": "522264",
"Score": "1",
"body": "C/C++ are particularly unforgiving languages. It's your responsibility to abide by the rules or face the consequences. This is why, even in trivial cases, I would rather not deliberately violate a rule, even as simple as redefining a reserved constant. You'll get away with it more often that not, but you might be very sorry the day you won't. Besides, C compilation is very fast, including a couple more headers should make no noticeable difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T23:54:05.303",
"Id": "522326",
"Score": "0",
"body": "@kuroineko Re: compare return values in pre C99 return 0 or 1: see [Any C compiler where “==” evaluates to larger than one?](https://stackoverflow.com/q/10632237/2410359)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T23:58:50.573",
"Id": "522327",
"Score": "0",
"body": "Oh, good to know. I didn't realize even the K&R defined the return value of these operators. Anyway, I shied from the printf hair-splitting tedium. Pissing contests are not my thing, and who cares about the 1.000.000th variant of fizzbuzz anyway?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T05:39:22.713",
"Id": "524400",
"Score": "0",
"body": "@kuroineko It's worth pointing out that K&R-style C is hardly modern though. The C standard changed a bit since '89 as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T06:00:07.967",
"Id": "524402",
"Score": "0",
"body": "Seriously, give me a break. K&R style was already a thing of the past in the 90's. Knowing when the return value of == was first defined is just an amusing bit of lore, with zero practical value."
}
] |
[
{
"body": "<blockquote>\n<pre><code> #define EXIT_SUCCESS 0\n</code></pre>\n</blockquote>\n<p>You are not permitted to define standard library names yourself. So just include <code><stdlib.h></code>, or omit the <code>return</code> from <code>main()</code> (remember, C will provide a success return if you don't provide one).</p>\n<blockquote>\n<pre><code>void fizzbuzz(int n) {\n</code></pre>\n</blockquote>\n<p>We could give that internal linkage:</p>\n<pre><code>static void fizzbuzz(int n) {\n</code></pre>\n<blockquote>\n<pre><code>char result[9] = ""; // strlen("fizzbuzz") + 1 == 9\n</code></pre>\n</blockquote>\n<p>Instead of manually calculating, we could use <code>sizeof "fizzbuzz"</code> to let the compiler do that for us.</p>\n<blockquote>\n<pre><code> if (!*result) sprintf(result, "%d", n);\n</code></pre>\n</blockquote>\n<p>We should be using <code>snprintf()</code> here, as the decimal representation of <code>n</code> can be longer than <code>result</code> has capacity for (even on common platforms with 32-bit <code>int</code>).</p>\n<p>I would avoid writing to <code>result</code> in this case - we can format directly to <code>stdout</code>:</p>\n<pre><code> if (*result) {\n puts(result);\n } else {\n printf("%d\\n", n);\n }\n</code></pre>\n<p><code>main</code> should be specific about its arguments:</p>\n<pre><code> int main(void)\n</code></pre>\n<hr />\n<h1 id=\"modified-code-op7b\">Modified code</h1>\n<pre><code>#include <stdio.h>\n#include <string.h>\n\nvoid fizzbuzz(int n)\n{\n char result[sizeof "fizzbuzz"] = "";\n if (n % 3 == 0) { strcat(result, "fizz"); }\n if (n % 5 == 0) { strcat(result, "buzz"); }\n if (*result) {\n puts(result);\n } else {\n printf("%d\\n", n);\n }\n}\n\nint main(void)\n{\n for (int i = 1; i <= 100; ++i) {\n fizzbuzz(i);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:45:02.377",
"Id": "522179",
"Score": "0",
"body": "Thank you for your answer but there are a few things I am not sure I understand correctly. \"You are not permitted to define standard library names yourself.\" Even with all the compiler options enabled, I don't get an error, not permitted by whom? And also is the implicit return only valid for certain compilers? I seem to remember that. Thank you again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:49:55.047",
"Id": "522180",
"Score": "4",
"body": "Not permitted by the C standard (it's undefined behaviour, IIRC). Compilers are not obliged to detect that you do so, and you probably get away with it in most cases. Default return from `main()` (and only from `main()`) is standard C, since C99 I think. So all compliant compilers in 2021 should accept that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:53:56.267",
"Id": "522181",
"Score": "0",
"body": "Technically it isn't redefining since I did not import stdlib? Anyway I appreciate your answer, I accepted it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T11:03:32.567",
"Id": "522183",
"Score": "1",
"body": "I'll try and find a reference for that. However, be aware that the standard library headers are allowed to include each other (e.g. `<stdio.h>` is allowed to transitively include `<stdlib.h>`) so you cannot say for definite what's not included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T11:08:55.303",
"Id": "522184",
"Score": "0",
"body": "Oh I didn't think about that, it's a fair point. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:48:33.840",
"Id": "522216",
"Score": "2",
"body": "@Toby In C++, headers may include any additional header they want. C doesn't have (nor really need) that provision."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T08:50:45.220",
"Id": "522260",
"Score": "2",
"body": "_\"Even with all the compiler options enabled, I don't get an error, not permitted by whom?\"_ - If that's your attitude, you're in for a world of pain with C ;) - There's _lots_ of things in C that won't trigger a compiler error (or even warning), but are still prohibited and lead to hard to debug problems. Most Undefined Behavior pitfalls fall in this category."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T08:59:41.653",
"Id": "522261",
"Score": "1",
"body": "One good thing you've done \"silently\" is to put braces round every conditionally-executed section. To the OP: This is considered good practise under every coding standard I'm aware of, because a common error is to start with a single-line conditionally-executed statement, then need to add a second line and forget to put both lines within braces. The result if you do that is that the first line is conditionally executed (depending on the \"if\" statement or whatever), but the second line isn't covered by the condition and is always executed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T10:31:42.827",
"Id": "522270",
"Score": "0",
"body": "@Graham, where I work, we currently do not require those braces. However, we require code to have been formatted with clang-format, so this mitigates the problem that you describe. (And I actually remember falling into this trap when adding a debug output to see whether a branch was taken, only to achieve that now that conditional statement was always executed.)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:26:42.193",
"Id": "264412",
"ParentId": "264408",
"Score": "11"
}
},
{
"body": "<ol>\n<li><p>If you can include the appropriate header, do that. Redefining yourself is error-prone even where allowed. This is C not C++, headers are simple enough it doesn't significantly influence compile-time.</p>\n</li>\n<li><p>If you add the origin of a constant in a comment, try to instead let the compiler determine it from the true source for you.</p>\n<pre><code> char result[9] = ""; // strlen("fizzbuzz") + 1 == 9\n</code></pre>\n<p>becomes the simpler and shorter</p>\n<pre><code> char result[sizeof "fizzbuzz"] = "";\n</code></pre>\n</li>\n<li><p>If you can, avoid copying strings around. Your pattern has period 3*5==15, so use an array. You can even compress it if you want, though that is overkill.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code> since C99. While <code>return EXIT_SUCCESS;</code> might be a <em>different</em> successful execution, afaik there is no implementation which differentiates.</p>\n</li>\n</ol>\n<p><a href=\"//coliru.stacked-crooked.com/a/8eca6a28ceade410\" rel=\"nofollow noreferrer\">This is what it looks like when you pander to the little tin god, without completely loosing your head:</a></p>\n<pre><code>#include <stdio.h>\n\nvoid fizzbuzz(unsigned n) {\n#define Z "\\n\\0"\n#define F "fizz"\n#define X "%u" Z\n const char* text = X F Z F "buzz\\n";\n static const char index[] = {\n sizeof(X F Z), 1, 1, sizeof(X), 1,\n sizeof(X F Z F), sizeof(X), 1, 1, sizeof(X),\n sizeof(X F Z F), 1, sizeof(X), 1, 1,\n };\n#undef X\n#undef F\n#undef Z\n printf(text + index[n % 15] - 1, n);\n}\n\nint main() {\n for (unsigned i = 1; i < 100; ++i)\n fizzbuzz(i);\n}\n</code></pre>\n<p>Or after <a href=\"//wandbox.org/permlink/7LcNL8QK06CPmzmQ\" rel=\"nofollow noreferrer\">encoding data and offsets with a custom program</a> (we are now far beyond overkill), it <a href=\"//coliru.stacked-crooked.com/a/6b43f66857cb401f\" rel=\"nofollow noreferrer\">becomes this</a>:</p>\n<pre><code>#include <stdio.h>\n\nvoid fizzbuzz(unsigned n) {\n const char* p = "\\31\\17\\17\\23\\17\\35\\23\\17\\17\\23\\35\\17\\23"\n "\\17\\17%u\\n\\0fizz\\n\\0fizzbuzz\\n";\n printf(p + p[n % 15], n);\n}\n\nint main() {\n for (unsigned i = 1; i < 100; ++i)\n fizzbuzz(i);\n}\n</code></pre>\n<p>The difficult part was converting the calculated string into a valid short source-code literal. Trickier than one might think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T01:43:55.440",
"Id": "522225",
"Score": "0",
"body": "I was worried that `printf(\"fizz\\n\", 3);` might be undefined behaviour, but [it is not](https://stackoverflow.com/a/3579752/1270789)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T04:20:11.297",
"Id": "522230",
"Score": "0",
"body": "I am not familiar with the idiom \"pander to the little tin god\"; what does this mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:39:46.027",
"Id": "522250",
"Score": "0",
"body": "Think of what can be accomplished with all that performance gain!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T09:19:34.587",
"Id": "522263",
"Score": "0",
"body": "@CodyGray The little tin god means that in the end, it takes far more prominence than deserved. And in this case, it is obviously the little tin god of efficiency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T09:28:22.650",
"Id": "522266",
"Score": "0",
"body": "@t_d_milan That was obviously never the point."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T12:38:13.123",
"Id": "264416",
"ParentId": "264408",
"Score": "1"
}
},
{
"body": "<p><strong>Re-use</strong></p>\n<blockquote>\n<p>could include stdlib so as not to have to define EXIT_SUCCESS myself, but as I only needed this constant, it's a little clearer and more efficient to do this</p>\n</blockquote>\n<p>Consider someone uses your good code as part of a larger task and does include <code><stdlib.h></code>, then the compiler may warn about the redefinition. Now the next coder needs to spend time sorting this out.</p>\n<p>Tip: plan for code re-use and consider the next guy. Avoid re-implementing the standard library.</p>\n<hr />\n<p><strong>Buffer too small</strong></p>\n<p><code>char result[9] .... sprintf(result, "%d", n)</code> --> <code>result</code> too small for all <code>int</code>. Be more generous.</p>\n<p>Various ways to pre-calculate buffer needs.</p>\n<pre><code> #define INT_STRING_N (sizeof(int)*CHAR_BIT/3 + 3)\n #define FIZZBUZZ_STRING_N 9\n #define BUFF_N (INT_STRING_N > FIZZBUZZ_STRING_N ? INT_STRING_N : FIZZBUZZ_STRING_N)\n\n char result[BUFF_N];\n</code></pre>\n<p>I favor using 2x buffers (twice the expected max needed size) and <code>snprintf()</code> for less controlled cases.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:51:25.203",
"Id": "264459",
"ParentId": "264408",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264412",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T09:54:30.847",
"Id": "264408",
"Score": "7",
"Tags": [
"c",
"fizzbuzz"
],
"Title": "Fizzbuzz in C lang"
}
|
264408
|
<p>This is a Python case insensitive dictionary that is ordered and has integer indexes for the keys and values.</p>
<p>I just wrote it today.</p>
<p>It is ordered because I am using Python 3.9.6 and plain <code>dict</code> is already ordered by default.</p>
<p>It prevents case insensitive duplicate keys from entering the dictionary (e.g. if 'Adele' is already in the dictionary, there can't be another key named 'adele'), and access the keys case insensitively, and updates existing key with same lowercase if found, preserves the cases of the keys when they are first inserted, and finally, it uses lists to index the keys and values.</p>
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>class UDict(dict):
@staticmethod
def _key(k):
return k.lower() if isinstance(k, str) else k
@classmethod
def fromkeys(cls, keys, val=None):
dic = cls()
for i in keys:
dic[i] = val
return dic
def __init__(self, *args, **kwargs):
super(UDict, self).__init__(*args, **kwargs)
self.KEYS = dict()
self.Keys = list()
self.Values = list()
if self.keys():
for k in list(self.keys()):
v = super(UDict, self).pop(k)
self.__setitem__(k, v)
def _delete(self, key):
k = UDict._key(key)
self.KEYS.pop(k)
i = self.Keys.index(k)
self.Keys.pop(i)
self.Values.pop(i)
def _get_key(self, key):
k = UDict._key(key)
if k in self.KEYS:
key = self.KEYS[k]
return key
def _process(self, key, val, modify=True):
k = UDict._key(key)
if k not in self.KEYS:
self.KEYS.update({k: key})
self.Keys.append(k)
self.Values.append(val)
else:
key = self.KEYS[k]
if modify:
i = self.Keys.index(k)
self.Values[i] = val
return key
def __contains__(self, key):
key = self._get_key(key)
return super(UDict, self).__contains__(key)
def __delitem__(self, key):
key = self._get_key(key)
if key in self:
self._delete(key)
super(UDict, self).__delitem__(key)
def __getitem__(self, key):
key = self._get_key(key)
if key in self:
return super(UDict, self).__getitem__(key)
def __setitem__(self, key, val):
key = self._process(key, val)
super(UDict, self).__setitem__(key, val)
def at(self, i: int):
if i not in range(len(self)):
return None
k = self.Keys[i]
key = self.KEYS[k]
val = self.Values[i]
return (key, val)
def clear(self):
super(UDict, self).clear()
self.KEYS.clear()
self.Keys.clear()
self.Values.clear()
def copy(self):
return UDict(self.items())
def get(self, key, *args, **kwargs):
key = self._get_key(key)
if key in self:
return super(UDict, self).get(key, *args, **kwargs)
return None
def index(self, key):
k = UDict._key(key)
if k not in self.KEYS:
return None
return self.Keys.index(k)
def key_at(self, i: int):
if i not in range(len(self)):
return None
k = self.Keys[i]
return self.KEYS[k]
def multiget(self, keys=None):
if not keys:
return None
return [self.get(i) for i in keys]
def multipop(self, keys):
if not keys:
return None
for i in keys:
self.pop(i)
def pop(self, key, *args, **kwargs):
key = self._get_key(key)
if key in self:
self._delete(key)
return super(UDict, self).pop(key, *args, **kwargs)
return None
def popitem(self):
self.KEYS.popitem()
self.Keys.pop(-1)
self.Values.pop(-1)
return super(UDict, self).popitem()
def setdefault(self, key, val=None):
key = self._process(key, val, False)
return super(UDict, self).setdefault(key, val)
def update(self, obj=None):
if not obj:
return None
if isinstance(obj, dict):
obj = obj.items()
for key, val in obj:
key = self._process(key, val)
super(UDict, self).update({key: val})
def value_at(self, i: int):
if i not in range(len(self)):
return None
return self.Values[i]
</code></pre>
<p>I have properly overridden all key related methods to make it behave exactly as I wanted it to, everything works as intended and I do need to get integer indexes.</p>
<p>Actually I implemented a function to get keys from values, by using the index of value in the <code>Values</code> list, but since values can be non-unique and Python lists only return indexes of first occurrences I removed it.</p>
<p>It is fully functional but performance wise it is considerably slower than plain <code>dict</code>s.</p>
<p>How can it be faster?</p>
<hr />
<p>Update: Bugfix, because using <code>type()</code> on an object of <code>UDict</code> will probably return <code>__main__.UDict</code>, therefore it isn't <code>dict</code> and passing <code>UDict</code> object as argument to <code>.update()</code> method and my code will not work properly (though I seriously don't know why anyone would do that), by using <code>isinstance(obj, dict)</code> UDict objects will be treated as dict, though I really don't understand why isinstance succeeds in identifying UDict as dict.</p>
<p>And isinstance is somewhat faster than type, then I considered the possibility of someone subclassing str...</p>
<hr />
<h2 id="update-ccsf">Update</h2>
<p>I implemented a case-insensitive <code>str</code> subclass and a dictionary subclass that automatically converts strings to case-insensitive <code>str</code>:</p>
<pre class="lang-py prettyprint-override"><code>class IStr(str):
def __hash__(self):
return hash(self.lower())
def __eq__(self, other):
if isinstance(other, str):
return self.lower() == other.lower()
return NotImplemented
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
if isinstance(other, str):
return self.lower() < other.lower()
return NotImplemented
def __ge__(self, other):
return not (self < other)
def __gt__(self, other):
if isinstance(other, str):
return self.lower() > other.lower()
return NotImplemented
def __le__(self, other):
return not (self > other)
def __contains__(self, other: str):
return other.lower() in self.lower()
class IDict(dict):
@staticmethod
def _key(k):
return IStr(k) if isinstance(k, str) else k
@classmethod
def fromkeys(cls, keys, val=None):
dic = cls()
for i in keys:
dic[i] = val
return dic
def __init__(self, *args, **kwargs):
super(IDict, self).__init__(*args, **kwargs)
if self.keys():
for k in list(self.keys()):
v = super(IDict, self).pop(k)
self.__setitem__(k, v)
def __contains__(self, key):
key = IDict._key(key)
return super(IDict, self).__contains__(key)
def __delitem__(self, key):
key = IDict._key(key)
if key in self:
super(IDict, self).__delitem__(key)
def __getitem__(self, key):
key = IDict._key(key)
if key in self:
return super(IDict, self).__getitem__(key)
def __setitem__(self, key, val):
key = IDict._key(key)
super(IDict, self).__setitem__(key, val)
def at(self, i: int):
if i not in range(len(self)):
return None
key = list(self.keys())[i]
val = list(self.values())[i]
return (key, val)
def copy(self):
return IDict(self.items())
def get(self, key, *args, **kwargs):
key = IDict._key(key)
if key in self:
return super(IDict, self).get(key, *args, **kwargs)
return None
def index(self, key):
k = IDict._key(key)
if k not in self:
return None
return list(self.keys()).index(k)
def key_at(self, i: int):
if i not in range(len(self)):
return None
k = list(self.keys())[i]
return k
def multiget(self, keys=None):
if not keys:
return None
return [self.get(i) for i in keys]
def multipop(self, keys):
if not keys:
return None
for i in keys:
self.pop(i)
def pop(self, key, *args, **kwargs):
key = IDict._key(key)
if key in self:
return super(IDict, self).pop(key, *args, **kwargs)
return None
def setdefault(self, key, val=None):
key = IDict._key(key)
return super(IDict, self).setdefault(key, val)
def update(self, obj=None):
if not obj:
return None
if isinstance(obj, dict):
obj = obj.items()
for key, val in obj:
key = IDict._key(key)
super(IDict, self).update({key: val})
def value_at(self, i: int):
if i not in range(len(self)):
return None
return list(self.values())[i]
</code></pre>
<p>To give you some examples:</p>
<pre class="lang-py prettyprint-override"><code>from string import ascii_letters
UDict(zip(ascii_letters, range(52)))
IDict(zip(ascii_letters, range(52)))
dict(zip(map(IStr, ascii_letters), range(52)))
dict(zip(ascii_letters, range(52)))
</code></pre>
<p>The first three all give the wanted result, and the last one gives exactly what made me implement case insensitivity in the first place.</p>
<p>But performance wise, from multiple tests, the last one takes only about 3 microseconds to complete, while the other three, from last to first, take 30, 80 and 90 microseconds respectively.</p>
<p>I don't know why the custom classes are slower than <code>dict</code>, how can it be optimized?</p>
<hr />
<p>And why I need a case insensitive dictionary?</p>
<p>This is an example:</p>
<pre class="lang-py prettyprint-override"><code>ex = [('Various Artists', 78),
('Two Steps From Hell', 75),
('Blake Neely', 60),
('Audiomachine', 59),
('Bandari', 56),
('Murray Gold', 46),
('Secret Garden', 45),
('Herbert von Karajan', 42),
('Connie Talbot', 38),
('Really Slow Motion', 35),
('Florian Bur', 33),
('Hans Zimmer', 33),
('Alexandrov Ensemble', 32),
('Kevin Kern', 28),
('Thomas Bergersen', 28),
('Brand X Music', 25)]
def fun(cls):
dic = cls()
for k, v in ex:
dic[k] = v
dic[k.upper()] = v
dic[k.lower()] = v
dic[k.title()] = v
dic[k.swapcase()] = v
return dic
</code></pre>
<p>The strings in the tuples are artist names, the numbers are how many times they occur in the data(how many songs of them in my list).</p>
<p>Just run <code>fun(IDict)</code> and <code>fun(dict)</code> and you will understand.</p>
<p>In actual use, the dictionary will be nested, and under the artist keys are album keys and under album keys are song keys which hold the actual data (values).</p>
<p>The cases of the names are often inconsistent, sometimes they are in TitleCase, sometimes UPPERCASE and sometimes lowercase and only iNVALIDCASE isn't encountered, and I need the dictionary to recognize the names as same regardless of what case they are in.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T14:31:50.253",
"Id": "522193",
"Score": "3",
"body": "Why is this needed? Show the code that uses it and some example contents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:51:35.860",
"Id": "522210",
"Score": "0",
"body": "Does your collection (dict) have to be case insensitive? You can use case insensitive keys (custom str type) and nuke your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T10:28:24.373",
"Id": "522269",
"Score": "0",
"body": "I agree with @Peilonrayz why not just use [`lower`](https://www.w3schools.com/python/ref_string_lower.asp) when comparing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T11:29:10.417",
"Id": "522274",
"Score": "1",
"body": "\"I don't know why the custom classes are slower than `dict`\". Python slow, C fast (which `dict` is written in)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T15:00:40.173",
"Id": "522287",
"Score": "2",
"body": "I'm going to level with you - both this question and your previous one have both code quality and question quality issues preventing meaningful review. This one in particular still doesn't demonstrate how you're actually using your song database, and is fairly theoretical. I'm not convinced that a case-insensitive, nested custom dictionary is called for, and nothing you've shown really justifies the need for custom data structure classes."
}
] |
[
{
"body": "<p><strong>How can I make a custom data structure as fast as <code>dict</code>?</strong></p>\n<p>You can't (at least, not in CPython). CPython's <code>dict</code> is written in C, as are other <code>dict</code> variants in the standard library such as <code>collections.defaultdict</code>. If you want to write custom data structures approaching the speed of a <code>dict</code>, go write it in C, Rust, or run your Python script using PyPy. Anything subclassing a <code>dict</code> becomes an object implemented in Python rather than C, so will not run nearly as fast as a <code>dict</code>.</p>\n<p><strong>How can I make my code better?</strong></p>\n<p>Your code at the moment is extremely confusing. Here are some of the reasons why:</p>\n<ol>\n<li><em>You don't have any docstrings.</em> It's really hard, as an outside reader, to understand what's going on in your code if you don't say what a specific function is for, and what its expected behaviour is. Type hints are also very helpful in this regard.</li>\n<li><em>You don't have any inline comments.</em> Similar to point (1). There's all sorts of things going on in your code <em>inside</em> functions that are frankly a little head-scratching. There's probably a really good reason for a lot of them -- so if there's something that isn't self-explanatory happening inside a function, tell us why it's happening!</li>\n<li><em>It's really unclear why so many of your methods are private.</em> What's the specific reason that the <code>_key</code> method is a private method? What would be so terrible about exposing that detail to other users? You have a <em>lot</em> of private methods, and the general expectation in Python is that a method should be public unless there's a good reason why.</li>\n<li><em>Your attributes are very confusingly named.</em> Your UDict class has one instance attribute <code>self.Keys</code>, one instance attribute <code>self.KEYS</code>, one instance method <code>self.keys()</code>, and one instance method <code>self._key()</code>. This would be bad even if they recorded similar kinds of information, but they don't! One is a <code>list</code>, one is a <code>dict</code>, one is a method that returns a <code>KeysView</code>, and one is a method that transforms an "unprocessed" key into a "processed" one. How can anybody be expected to remember the difference between all of these?! There's really nothing wrong with being a bit more verbose and giving your attributes and methods more helpful, descriptive names. Your second attempt in your question improves on this a little, but not much. Why are your classes called <code>IString</code> and <code>IDict</code>? How can anybody be expected to know what they do from their names?</li>\n<li><em>The motivation for your class still seems a little unclear</em>. You say it's a case-insensitive dict. Fine. But you <em>also</em> have added methods that will return the "integer index" of a key or value. It's unclear why these are necessary for this use case. Ditto for your <code>multiget</code> and <code>multipop</code> methods -- what are these <em>for</em>? And it's unclear why you would implement <code>multiget</code> and <code>multipop</code>, but <em>not</em> <code>multisetdefault</code> and <code>multipopitem</code>. What's the rationale here?</li>\n</ol>\n<p>In addition to the above critiques, I would have started in a different place when it comes to solving this problem. My general attitude is that subclassing <code>dict</code> directly works great for when you're <em>extending</em> a <code>dict</code> -- just adding new features onto it, for a specialised purpose. But if you start <em>overriding</em> all sorts of <code>dict</code> dunder methods, I would generally look at inheriting from <code>collections.abc.MutableMapping</code> instead. The great thing about inheriting from <code>MutableMapping</code> is that by implementing just a few <code>abstractmethods</code> that <code>MutableMapping</code> has, you get a whole host of normal <code>dict</code> methods for free. In my example code below, I haven't had to override <code>.setdefault()</code>, <code>.pop()</code>, <code>.popitem()</code>, <code>.get()</code>, <code>.keys()</code>, <code>.values()</code>, <code>.items()</code>, <code>.clear()</code>, <code>.update()</code>, <code>__contains__()</code> or <code>.__eq__()</code>. They all come "for free" because I'm inheriting from <code>MutableMapping</code>. It just ends up being a lot cleaner, in my opinion.</p>\n<p>I've also implemented a helper-class, to deal with some of the implementation-logic regarding case-insensitivity. There was just too much going on in your class, in my opinion; it made sense to shunt some of that code elsewhere.</p>\n<p>I don't think there's a great deal of speed improvement in my refactoring below. I think in a few situations, my refactoring is a little faster than yours, but I haven't rigorously tested performance.</p>\n<p>My code comes out as being a fair bit longer than yours, but I think the main reason for that is simply because I have a lot more comments and docstrings than you did...</p>\n<pre><code>from __future__ import annotations\nfrom typing import Any, TypeVar, Optional, Union, NoReturn\nfrom collections.abc import Mapping, MutableMapping, Iterator, Sequence\nfrom abc import abstractmethod\nfrom functools import cache\n\n\n# For mapping keys and values\n_K = TypeVar('_K')\n_V = TypeVar('_V')\n\n# Any subclass of _DictBoilerplateBase\n_T = TypeVar('_T', bound='_DictBoilerplateBase[Any, Any]')\n\n# For .get() defaults\n_D = TypeVar('_D')\n\n\nclass _DictBoilerplateBase(MutableMapping[_K, _V]):\n """Base class for the mapping objects _KeyMapperDict and CaseInsensitiveDict.\n\n Inheriting from MutableMapping\n means the following methods are auto-implemented,\n both for this base class\n and for all classes inheriting from it:\n - .setdefault()\n - .pop()\n - .popitem()\n - .get()\n - .keys()\n - .values()\n - .items()\n - .clear()\n - .update()\n - .__contains__()\n - .__eq__()\n\n The following abstractmethods need to be implemented by all subclasses of this class:\n - .__init__()\n - .__getitem__()\n - .__setitem__()\n - .__delitem__()\n """\n\n __slots__ = 'data'\n \n data: dict[_K, _V] # For type-checkers\n\n @abstractmethod\n def __init__(\n self,\n data: Optional[Mapping[_K, _V]] = None,\n /,\n **kwargs\n ) -> None:\n \n if data is not None:\n self.update(data)\n if kwargs:\n self.update(kwargs)\n\n @classmethod\n def fromkeys(\n cls: type[_T],\n keys: Sequence[_K],\n default: Optional[_V] = None,\n /\n ) -> _T:\n """Standard alternative constructor for python mapping objects"""\n return cls({key: default for key in keys})\n \n def __iter__(self, /) -> Iterator[_K]:\n return iter(self.data.keys())\n \n def __len__(self, /) -> int:\n return len(self.data)\n\n def __repr__(self, /) -> str:\n return f'{type(self).__qualname__}({self.data!r})'\n\n def __str__(self, /) -> str:\n return f'{type(self).__name__}({self.data})'\n\n def __or__(self: _T, other: Mapping[_K, _V], /) -> _T:\n # (Dicts from python 3.9+ support the union operator)\n return type(self)({**self, **other})\n\n def __ror__(self: _T, other: Mapping[_K, _V], /) -> _T:\n # (Dicts from python 3.9+ support the union operator)\n return type(other)({**other, **self})\n\n def __ior__(self: _T, other: Mapping[_K, _V], /) -> _T:\n # (Dicts from python 3.9+ support the union operator)\n self.update(other)\n return self\n\n def copy(self: _T, /) -> _T:\n """Return a shallow copy of the mapping"""\n return type(self)(self)\n\n\nclass _KeyMapperDict(_DictBoilerplateBase[_K, _K]):\n """Helper class for the CaseInsensitiveDict class.\n\n Maps lowercase keys to the original case\n in which they were entered in the CaseInsensitiveDict.\n \n Also keeps the processed keys in a separate list,\n so that the integer index can be retrieved.\n\n This class knows NOTHING about the values\n in the CaseInsensitiveDict.\n\n All dunder methods expect to receive preprocessed keys.\n """\n\n __slots__ = 'keys_list'\n\n def __init__(\n self,\n data: Optional[Mapping[_K, _K]] = None,\n /,\n **kwargs\n ) -> None:\n # A map of lowercase-to-originalcase-keys\n self.data: dict[_K, _K] = {}\n \n # A list of the processed keys, for integer indexing\n self.keys_list: list[_K] = []\n\n super().__init__(data, **kwargs)\n\n @staticmethod\n @cache\n def process_key(key: _K, /) -> _K:\n """Normalise a key to allow for case-insensitivity when dealing with strings.\n Keys that are not strings are returned unchanged.\n """\n return key.lower() if isinstance(key, str) else key # type: ignore[return-value]\n\n def register_key(\n self,\n unprocessed_key: _K,\n /\n ) -> Union[tuple[_K, int], tuple[None, None]]:\n """Determine whether a key is in the mapping, return its integer index if so.\n\n Parameters\n ----------\n unprocessed_key, _K:\n A key that has not yet been normalised\n according to this class's process_key method.\n\n Return\n ------\n If some version of the key is already in the mapping, returns (_K, int),\n a tuple consisting of:\n - The key in the form it was in\n when it was first entered in the CaseInsensitiveDict.\n - The integer index of the key in the mapping.\n\n If the key was not already in the mapping,\n returns:\n - (None, None)\n\n Examples\n --------\n >>> d = _KeyMapperDict({'spam': 'SPAM', 'eggs': 'eGgS'})\n >>> d.register_key('SPAM')\n ('SPAM', 0)\n >>> d.register_key('Eggs')\n ('eGgS', 1)\n >>> d.register_key('bacon')\n (None, None)\n """\n # This method is essentially a helper method\n # for the __setitem__ of the CaseInsensitiveDict.\n \n processed_key = self.process_key(unprocessed_key)\n \n try:\n return self[processed_key], self.keys_list.index(processed_key)\n except KeyError as err:\n self[processed_key] = unprocessed_key\n return None, None\n\n def __setitem__(\n self,\n processed_key: _K,\n unprocessed_key: _K,\n /\n ) -> None:\n # This method is the mirror image of __delitem__\n self.data[processed_key] = unprocessed_key\n self.keys_list.append(processed_key)\n\n def get_original_key(self, unprocessed_key: _K, /) -> _K:\n """Return the original key, as it was first inputted into the mapping.\n\n Parameters\n ----------\n unprocessed_key, _K:\n A key that has not yet been normalised\n according to this class's process_key method.\n\n Return\n ------\n original_key, _K:\n The equivalent key to the inputted value,\n as it was originally inputted into the mapping.\n\n Raises\n ------\n KeyError if no equivalent\n for the inputted key exists in this mapping.\n\n Example\n -------\n >>> d = _KeyMapperDict({'spam': 'SPAM', 'eggs': 'eGgS'})\n >>> d.get_original_key('SPAM')\n 'SPAM'\n >>> d.get_original_key('Eggs')\n 'eGgS'\n >>> d.get_original_key('bacon')\n Traceback (most recent call last):\n KeyError: 'bacon'\n """\n return self[self.process_key(unprocessed_key)]\n \n def __getitem__(self, processed_key: _K, /) -> _K:\n return self.data[processed_key]\n\n def remove_key(self, unprocessed_key: _K, /) -> int:\n """Delete the key from the mapping, return the index where the key used to be.\n\n Example\n -------\n >>> d = _KeyMapperDict({'spam': 'SPAM', 'eggs': 'eGgS', 'bacon': 'bacon'})\n >>> d.remove_key('EGGS')\n 1\n >>> d\n _KeyMapperDict({'spam': 'SPAM', 'bacon': 'bacon'})\n >>> d.remove_key('Spam')\n 0\n >>> d\n _KeyMapperDict({'bacon': 'bacon'})\n """\n \n # This method is essentially a helper method\n # for the __delitem__ of the CaseInsensitiveDict\n processed_key = self.process_key(unprocessed_key)\n index = self.keys_list.index(processed_key)\n del self[processed_key]\n return index\n \n def __delitem__(self, processed_key: _K, /) -> None:\n # This method is the mirror image of __setitem__\n del self.data[processed_key]\n self.keys_list.remove(processed_key)\n\n def index_of_key(self, unprocessed_key: _K, /) -> Optional[int]:\n """Return the "integer index" of a certain key in the keys_list.\n\n Parameters\n ----------\n unprocessed_key, _K:\n A key that may or may not be in the keys_list,\n and may or may not be of the same case as it was\n originally entered into the mapping.\n\n Return\n ------\n index, int or None:\n Either the integer index of the key in the keys_list,\n or None if the key is not in the keys_list.\n\n Example\n -------\n >>> d = _KeyMapperDict({'spam': 'SPAM', 'eggs': 'eGgS'})\n >>> d.index_of_key('SPAM')\n 0\n >>> d.index_of_key('spam')\n 0\n >>> d.index_of_key('eggs')\n 1\n >>> d.index_of_key('bacon') is None\n True\n """\n processed_key = self.process_key(unprocessed_key)\n\n try:\n return self.keys_list.index(processed_key)\n except ValueError:\n return None\n\n def original_key_at_index(self, index: int, /) -> Optional[_K]:\n """Return the key at a certain integer index in the keys_list.\n\n Return the key as it was originally entered into the mapping,\n rather than the normalised version of the key.\n \n The keys as they were originally entered\n into the CaseInsensitiveDict\n are stored as this mapping's values.\n\n\n Parameters\n ----------\n index, int:\n An index that may or may not be valid.\n\n Return\n ------\n key, _K or None:\n Either the object at that integer index in the keys_list,\n or None if the integer index isn't valid.\n\n Example\n -------\n >>> d = _KeyMapperDict({'spam': 'SPAM', 'eggs': 'eGgS'})\n >>> d.original_key_at_index(0)\n 'SPAM'\n >>> d.original_key_at_index(1)\n 'eGgS'\n >>> d.original_key_at_index(5) is None\n True\n """\n try:\n return self.data[self.keys_list[index]]\n except IndexError:\n return None\n\n\nclass CaseInsensitiveDict(_DictBoilerplateBase[_K, _V]):\n """A case-insensitive dict.\n\n Where `c = CaseInsensitiveDict()`,\n `c['Adele']` returns the same value as `c['adele']` or `c['AdElE']`.\n The dict also records the integer index of the keys and values.\n\n The dict preserves the original case\n of the first time the key was entered into the mapping.\n E.g., it will remember that "Adele"\n as first entered into the mapping as "Adele",\n even if the value associated with "Adele" in the mapping\n is updated using the code `c['adele'] = '21'`.\n """\n\n __slots__ = 'keys_map', 'values_list'\n \n def __init__(\n self,\n data: Optional[Mapping[_K, _V]] = None,\n /,\n **kwargs\n ) -> None:\n \n # This is where the actual data is stored\n # It maps the UNPROCESSED keys to the values\n self.data: dict[_K, _V] = {}\n\n # A map of PROCESSED keys to the ORIGINAL keys\n self.keys_map: _KeyMapperDict[_K] = _KeyMapperDict()\n\n # A list of the key values, for integer indexing\n self.values_list: list[_V] = []\n\n super().__init__(data, **kwargs)\n\n def __setitem__(self, unprocessed_key: _K, value: _V, /) -> None:\n # (original_key, index) will be (_K, int)\n # if the key's already in the mapping.\n # Else (None, None) \n original_key, index = self.keys_map.register_key(unprocessed_key)\n\n # Better to check the index,\n # as None can plausibly be used as a dictionary key\n if index is None:\n self.values_list.append(value)\n self.data[unprocessed_key] = value\n else:\n self.values_list[index] = value\n self.data[original_key] = value # type: ignore[index]\n \n def __getitem__(self, unprocessed_key: _K, /) -> _V:\n # Catch KeyErrors and reraise them,\n # to make for a more logical traceback.\n try:\n processed_key = self.keys_map.get_original_key(unprocessed_key)\n except KeyError as err:\n raise KeyError(*err.args) from err\n else:\n return self.data[processed_key] \n \n def __delitem__(self, unprocessed_key: _K, /) -> None:\n # Catch KeyErrors and reraise them,\n # to make for a more logical traceback.\n try:\n original_key = self.keys_map.get_original_key(unprocessed_key)\n except KeyError as err:\n raise KeyError(*err.args) from err\n else:\n del self.data[original_key]\n # the original_key is not processed -\n # the _KeyMapperDict does that for us\n self.values_list.pop(self.keys_map.remove_key(original_key))\n\n def index_of_key(self, unprocessed_key: _K, /) -> Optional[int]:\n """Return the integer index of a certain key in the mapping.\n\n This method is effectively delegated\n to the instance's `keys_map` attribute,\n which is of type `_KeyMapperDict`.\n\n Parameters\n ----------\n unprocessed_key, _K:\n A key that may or may not be in the mapping.\n\n Return\n ------\n index, int or None:\n Either the integer index of the key in the mapping,\n or None if the key is not in the mapping.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n >>> d.index_of_key('A')\n 0\n >>> d.index_of_key('a')\n 0\n >>> d.index_of_key('b')\n 1\n >>> d.index_of_key('c') is None\n True\n """\n return self.keys_map.index_of_key(unprocessed_key)\n\n def index_of_value(self, *args: Any, **kwargs: Any) -> NoReturn:\n """Raise NotImplementedError.\n\n Example\n -------\n >>> d = d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n >>> d.index_of_value('spam')\n Traceback (most recent call last):\n NotImplementedError: index_of_value \\\nis deliberately not implemented as a method. \\\nMultiple values can exist in a dictionary \\\nthat are all the same, therefore it does not make sense \\\nto request the index of a dictionary value.\n """\n raise NotImplementedError(\n "index_of_value is deliberately not implemented as a method. "\n "Multiple values can exist in a dictionary that are all the same, "\n "therefore it does not make sense "\n "to request the index of a dictionary value."\n )\n\n def index_of_item(self, *args: Any, **kwargs: Any) -> NoReturn:\n """Raise NotImplementedError.\n\n Example\n -------\n >>> d = d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n \n >>> d.index_of_item('a', 'spam')\n Traceback (most recent call last):\n NotImplementedError: index_of_item is deliberately not implemented. \\\nUse index_of_key instead.\n\n >>> d.index_of_item(('a', 'spam'))\n Traceback (most recent call last):\n NotImplementedError: index_of_item is deliberately not implemented. \\\nUse index_of_key instead.\n\n """\n raise NotImplementedError(\n "index_of_item is deliberately not implemented. "\n "Use index_of_key instead."\n )\n\n def key_at_index(self, index: int, /) -> Optional[_K]:\n """Return the key at a certain integer index in the mapping.\n\n Return the key as it was originally entered into the mapping,\n not the normalised version of the key.\n\n This method is effectively delegated\n to the instance's `keys_map` attribute,\n which is of type `_KeyMapperDict`.\n\n Parameters\n ----------\n index, int:\n An index that may or may not be valid.\n\n Return\n ------\n key, _K or None:\n Either the key at that integer index in the mapping,\n or None if the integer index isn't valid.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n >>> d.key_at_index(0)\n 'a'\n >>> d.key_at_index(1)\n 'b'\n >>> d.key_at_index(2) is None\n True\n """\n return self.keys_map.original_key_at_index(index)\n\n def value_at_index(self, index: int, /) -> Optional[_V]:\n """Return the value at a certain integer index in the mapping.\n\n Parameters\n ----------\n index, int:\n An index that may or may not be valid.\n\n Return\n ------\n value, _V or None:\n Either the value at that integer index in the mapping,\n or None if the integer index isn't valid.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n >>> d.value_at_index(0)\n 'spam'\n >>> d.value_at_index(1)\n 'eggs'\n >>> d.value_at_index(5) is None\n True\n """\n try:\n return self.values_list[index]\n except IndexError:\n return None\n\n def item_at_index(self, index: int, /) -> Optional[tuple[_K, _V]]:\n """Return the (key, value) pair at a certain integer index in the mapping.\n\n Parameters\n ----------\n index, int:\n An index that may or may not be valid.\n\n Return\n ------\n item, (_K, _V) or None:\n Either the (key, value) pair\n at that integer index in the mapping,\n or None if the integer index isn't valid.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 'spam', 'b': 'eggs'})\n >>> d.item_at_index(0)\n ('a', 'spam')\n >>> d.item_at_index(1)\n ('b', 'eggs')\n >>> d.item_at_index(2) is None\n True\n """\n key = self.key_at_index(index)\n return None if key is None else (key, self[key])\n\n def multiget(\n self,\n /,\n *key_sequence: _K,\n default: Optional[_D] = None\n ) -> list[Union[_V, _D, None]]:\n """Return a list of values corresponding to an arbitrary sequence of keys.\n\n If any item in key_sequence is not a valid key,\n the default value goes in the list.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 1, 'c': 2})\n >>> d.multiget('a', 'b', 'c', default='spam')\n [1, 'spam', 2]\n >>> d\n CaseInsensitiveDict({'a': 1, 'c': 2})\n """\n # The type-hint for the default is _D rather than _V,\n # as dict.get() does not update the mapping at all.\n # Therefore the default does not need to be the same type\n # as the mapping's values.\n return [self.get(k, default) for k in key_sequence]\n\n def multipop(self, /, *key_sequence: _K) -> list[_V]:\n """Return a list of values corresponding to an arbitrary sequence of keys.\n Remove said keys from the mapping.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 1, 'c': 2})\n >>> d.multipop('a', 'c')\n [1, 2]\n >>> d\n CaseInsensitiveDict({})\n """\n return [self.pop(k) for k in key_sequence]\n\n def multipopitem(self, n: int, /) -> list[tuple[_K, _V]]:\n """Return a list, of length `n`, of (key, value) pairs, popped from the beginning of the mapping.\n\n NOTE: classes inheriting from collections.abc.MutableMapping\n pop mapping items in "first-in-first-out" (FIFO) order.\n This is the opposite order to python's builtin `dict`,\n `collections.OrderedDict` and `collections.Counter`,\n all of which use "last-in-first-out" (LIFO).\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})\n >>> d.multipopitem(3)\n [('a', 1), ('b', 2), ('c', 3)]\n >>> d\n CaseInsensitiveDict({'d': 4})\n """\n return [self.popitem() for _ in range(n)]\n\n def multisetdefault(\n self,\n /,\n *key_sequence: _K,\n default: Optional[_V] = None\n ) -> list[Optional[_V]]:\n """Return a list of values corresponding to an arbitrary sequence of keys.\n\n If any item in key_sequence is not a valid key,\n the default value goes in the list.\n\n Additionally, the mapping will be updated\n such that the key is added to the mapping,\n with this function's `default` parameter\n as the associated value.\n\n Example\n -------\n >>> d = CaseInsensitiveDict({'a': 1, 'c': 2})\n >>> d.multisetdefault('a', 'b', 'c', default='spam')\n [1, 'spam', 2]\n >>> d\n CaseInsensitiveDict({'a': 1, 'c': 2, 'b': 'spam'})\n """\n return [self.setdefault(k, default) for k in key_sequence] # type: ignore[arg-type]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T21:28:59.583",
"Id": "264460",
"ParentId": "264411",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264460",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T10:17:59.500",
"Id": "264411",
"Score": "0",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x"
],
"Title": "Python case insensitive dictionary"
}
|
264411
|
<p>Im currently working on a filtering keywords. I have two lists which I called positive and negative.</p>
<p>Scenarios:</p>
<ol>
<li>if <code>POSITIVE</code> matches and <strong>NOT</strong> <code>NEGATIVE</code>matches = <strong>True</strong></li>
<li>if <code>POSITIVE</code> matches and <code>NEGATIVE</code>matches = <strong>False</strong></li>
<li>if NOT <code>POSITIVE</code>(Then no need to check <code>NEGATIVE</code>) = <strong>False</strong>.</li>
</ol>
<p>I have done something like this:</p>
<pre class="lang-py prettyprint-override"><code>import re
from typing import List
# In the future it will be a longer list of keywords
POSITIVE: List[str] = [
"hello+world",
"python",
"no"
]
# In the future it will be a longer list of keywords
NEGATIVE: List[str] = [
"java",
"c#",
"ruby+js"
]
def filter_keywords(string) -> bool:
def check_all(sentence, words):
return all(re.search(r'\b{}\b'.format(word), sentence) for word in words)
if not any(check_all(string.lower(), word.split("+")) for word in POSITIVE) or \
any(check_all(string.lower(), word.split("+")) for word in NEGATIVE):
filtered = False
else:
filtered = True
print(f"Your text: {string} is filtered as: {filtered}")
return filtered
filter_keywords("Hello %#U&¤AU(1! World ¤!%!java")
filter_keywords("Hello %#U&¤AU(1! World ¤!%!")
filter_keywords("I love Python more than ruby and js")
filter_keywords("I love Python more than myself!")
</code></pre>
<p>Regarding the <code>+</code> in the list, that means that if <code>hello</code> and <code>world</code> is in the string then its a positive match</p>
<p>It does work of course, but I do believe I am doing too many "calculations" and I believe it could be shorted, I wonder if there is a possibility of it?</p>
|
[] |
[
{
"body": "<p>That's a <em>lot</em> of regexes to compute. I'm going to suggest that you only run one regex, to split the string up into words; and from there represent this as a series of set operations.</p>\n<p>If I understand it correctly, you basically have two different cases in your filter words:</p>\n<ul>\n<li>A single word, which produces a match</li>\n<li>Multiple words, which - regardless of the order found - <em>all</em> need to be present to produce a match</li>\n</ul>\n<p>In the second case, I don't think it's a good idea to include a magic plus-sign to indicate string separation in static application data. Just write the separation in yourself, as represented by a multi-element set.</p>\n<p>The single-word match case is going to execute much more quickly than what you have now, because it takes only one set disjoint check for each of the positive and negative terms. If such a match is found, the multi-word case will be short-circuited away and will not be computed. The multi-word case is slower because every sub-set needs to be checked, but I still expect it to be faster than the iterative-regex approach.</p>\n<p>Also note that you should remove your boolean variable and print statement in your function, and simplify your boolean expression by applying <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">De Morgan's Law</a> to switch up your <code>True</code> and <code>False</code> and produce a single return expression.</p>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>import re\nfrom typing import Tuple, Iterable, Set\n\n\n# In the future it will be a longer list of keywords\nSINGLE_POSITIVE: Set[str] = {\n "python",\n "no",\n}\nMULTI_POSITIVE: Tuple[Set[str], ...] = (\n {"hello", "world"},\n)\n\n# In the future it will be a longer list of keywords\nSINGLE_NEGATIVE: Set[str] = {\n "java",\n "c#",\n}\nMULTI_NEGATIVE: Tuple[Set[str], ...] = (\n {"ruby", "js"},\n)\n\n\nfind_words = re.compile(r'\\w+').findall\n\n\ndef filter_keywords(string: str) -> bool:\n words = {word.lower() for word in find_words(string)}\n\n def matches(single: Set[str], multi: Iterable[Set[str]]) -> bool:\n return (\n (not words.isdisjoint(single))\n or any(multi_word <= words for multi_word in multi)\n )\n\n return (\n matches(SINGLE_POSITIVE, MULTI_POSITIVE) and not\n matches(SINGLE_NEGATIVE, MULTI_NEGATIVE)\n )\n\n\ndef test() -> None:\n for string in (\n "Hello %#U&¤AU(1! World ¤!%!java",\n "Hello %#U&¤AU(1! World ¤!%!",\n "I love Python more than ruby and js",\n "I love Python more than myself!",\n "I love Python more than js",\n ):\n filtered = filter_keywords(string)\n print(f"Your text: {string} is filtered as: {filtered}")\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Your text: Hello %#U&¤AU(1! World ¤!%!java is filtered as: False\nYour text: Hello %#U&¤AU(1! World ¤!%! is filtered as: True\nYour text: I love Python more than ruby and js is filtered as: False\nYour text: I love Python more than myself! is filtered as: True\nYour text: I love Python more than js is filtered as: True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T21:51:30.133",
"Id": "522219",
"Score": "0",
"body": "Why do you keep always chock me?! You are awesome dude. The reason I used the `+` is that in the future I would like to use postgresql for storing the keywords in the database and I was not sure if the database would like to store with spaces so I thought it would be better idea to replace space with + but I guess not. What would you suggest if I would like to store it to the database? To have multiple tables, one for multiple words and one for single words?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T03:36:40.887",
"Id": "522228",
"Score": "3",
"body": "The approach will be very different. You'll want to run the word matching query entirely in the database rather than doing it on the application side with sets or regexes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T10:38:37.163",
"Id": "522272",
"Score": "0",
"body": "Cool! I will have to investigate it abit more, but that is abit off topic for now! Thanks once again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:29:14.717",
"Id": "264430",
"ParentId": "264419",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T14:07:41.413",
"Id": "264419",
"Score": "1",
"Tags": [
"python-3.x"
],
"Title": "Filtering string by given keywords"
}
|
264419
|
<pre><code>class RadarChecker:
def __init__(self) -> None:
self._issues = set()
@property
def issues(self) -> Set[str]:
return self._issues
@property
def _checkers(self) -> Iterable[Callable]:
return (
self._check_1,
self._check_2,
self._check_3,
)
def check(self) -> None:
for checker in self._checkers:
ok, issue = checker()
if not ok:
self._issues.add(issue)
</code></pre>
<p>The current interface of the <code>RadarChecker</code> class consists of two methods: <code>check</code> and <code>issues</code>. The whole purpose of the check method is that it triggers computation of the issues that are returned by the issues method. So, all users of <code>RadarChecker</code> call issues eventually:</p>
<pre><code>checker = RadarChecker()
checker.check()
for issue in checker.issues:
# process issue
</code></pre>
<p>Is it possible to provide the same functionality with a simpler interface?</p>
<p>I'm thinking about defining the <code>RadarIssues</code> class that implements the <code>Iterable[str]</code> interface. We provide the same info to <code>RadarIssues</code> that we do to <code>RadarChecker</code> but instead of calling <code>issues</code> to get the issues, the users would simply iterate over the instance of <code>RadarIssues</code>. This would look roughly as follows:</p>
<pre><code>radar_issues = RadarIssues()
for issue in radar_issues:
# process issue
</code></pre>
<p>Is it better? I will appreciate criticism and other ideas.</p>
|
[] |
[
{
"body": "<p>In this case, I would really keep it simple. I would drop the OOP and just write a simple function that validates the radar and returns a list of issues. To be clear:</p>\n<pre><code>def check_radar(radar: Radar) -> Set[str]:\n return {\n *_check_1(radar),\n *_check_2(radar),\n ...\n }\n\ndef _check_1(radar: Radar) -> Set[str]:\n # perform check and return set() or {"issue"}\n</code></pre>\n<p>The example above is just an idea for the implementation, you can then implement the internals as you wish, for instance by defining a list of checker functions and iterating and appending to the list as you're doing in your sample code. The issues could be <code>str</code> or some more complicated object, depending on your needs.</p>\n<p>This not only avoids having to write and maintain a class that in the end has just a single method kind of an unusual interface, but also writing a class that behaves like an <code>Iterable[str]</code> and which make the API harder to understand.</p>\n<p>Another note: instead of <code>ok, issue = checker()</code> you could just return <code>None</code> when there's no issue, which would simplify early returns from the checker functions.</p>\n<p>I know it's not really OOP, but there's no need to use OOP everywhere if another pattern solves the problem more intuitively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:06:16.677",
"Id": "264427",
"ParentId": "264425",
"Score": "1"
}
},
{
"body": "<p>What you have is neither crazy nor terrible.</p>\n<p>You've started some type hinting (good!) but it's incomplete. For instance</p>\n<pre><code>self._issues: Set[str] = set()\n</code></pre>\n<p>and</p>\n<pre><code>@property\ndef checkers(self) -> Tuple[\n Callable[\n [], \n Tuple[bool, str],\n ], ...\n]:\n</code></pre>\n<p>Note that it's good practice to add hints accepting the most generic possible type and return the most specific possible type, so <code>Tuple</code> instead of <code>Iterable</code>.</p>\n<p>There's not a whole lot of win in having <code>_issues</code> as a private with a public accessor, because private is only a suggestion in Python and users can still get to that member. You might as well just have a public <code>issues</code> set. However, the better thing to do is make this class stateless - keep your <code>checkers</code> (which can be made public - again, private is kind of a lost cause in Python); do not store <code>issues</code> on the class; and yield issues as a generator from <code>check()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T06:44:47.067",
"Id": "522242",
"Score": "0",
"body": "Thanks! Could you please provide an implementation for `check` with generators? Not really sure how it will look like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:02:03.200",
"Id": "522246",
"Score": "0",
"body": "def check(self) -> Iterable[str]:\n for checker in self._checkers:\n ok, issue = checker()\n if not ok:\n yield issue"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:51:43.923",
"Id": "264432",
"ParentId": "264425",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264432",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T18:28:35.330",
"Id": "264425",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Simple interface for collecting issues after a list of validations"
}
|
264425
|
<p>I have recently been learning Haskell, and wrote a minesweeper project as an exercise. Here is <a href="https://github.com/saxocellphone/minehask/blob/main/src/Game.hs" rel="nofollow noreferrer">link</a> to the project.</p>
<p>Basically the code is separated into two parts, the pure part (no monads) and impure part (deals with random and IO). Since I'm pretty new, I'm a little iffy about the whole setup. Any advice would be appreciated.</p>
<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE LambdaCase #-}
module Game where
import Data.List
import Data.Maybe
import Data.List.Split
import Control.Monad.Random
import Control.Monad.IO.Class
import Control.Monad.Reader
data Square = Square Bool SquareStatus | NumberedSquare Int
data SquareStatus = Untouched | LostMine | Flagged
data Pos = Pos Int Int deriving (Eq)
data Env = Env {
getInitPos :: Pos,
getWidth :: Int,
getHeight :: Int,
getNumMines :: Int
}
type Board = [[Square]]
type Game a = ReaderT Env IO a
instance Show Square where
show (Square _ Untouched) = "."
show (Square _ LostMine) = "x"
show (Square _ Flagged) = "f"
show (NumberedSquare num) = if num > 0 then show num else " "
infixl 6 |+|
Pos a b |+| Pos c d = Pos (a+c) (b+d)
---------------
-- Game Control
---------------
play :: Int -> Int -> Int -> IO ()
play w h numMines = do
initPos <- readInput
board <- runReaderT createRandomBoard $ Env initPos w h numMines
play' board initPos
play' :: Board -> Pos -> IO ()
play' board initPos = case expand board [initPos] of
Just nextBoard -> do
printBoard nextBoard
if checkWin nextBoard then
print "You won!"
else do
nextPos <- readInput
play' nextBoard nextPos
Nothing -> do
print "You Lost :("
printBoard $ markBoard board
readInput :: IO Pos
readInput = do
pos <- do
putStrLn "Make a move: (Format Int Int)"
getLine
let [initX, initY] = splitOn " " pos
return $ Pos (read initX - 1) (read initY - 1)
--------------
--Impure Stuff
--------------
createRandomBoard :: Game Board
createRandomBoard = do
width <- asks getWidth
height <- asks getHeight
randomLayout <- randMines
let field = take height $ chunksOf width $ genField randomLayout $ width * height
lift $ return field
randMines :: Game [Int]
randMines = do
width <- asks getWidth
height <- asks getHeight
pos <- asks getInitPos
n <- asks getNumMines
randomSample n $ delete (posToIndex pos width height) [0..width*height-1]
randomSample :: Int -> [a] -> Game [a]
randomSample 0 list = pure []
randomSample k list = do
i <- getRandomR (0, length list - 1)
let (a, xs) = splitAt i list
l <- if not (null xs) then randomSample (k-1) (a ++ tail xs) else lift $ return []
pure $ if not (null xs) then head xs : l else l
----------------
--Pure Functions
----------------
genField :: [Int] -> Int -> [Square]
genField mines = genField' (sort mines) 0
where
genField' [] index size = replicate (size - index) (Square False Untouched)
genField' mines@(x:xs) index size
| x == index = Square True Untouched : genField' xs (index+1) size
| otherwise = Square False Untouched : genField' mines (index+1) size
getSquare :: Board -> Pos -> Maybe Square
getSquare b (Pos x y)
| x >= length b || x < 0 = Nothing
| y >= length (head b) || y < 0 = Nothing
| otherwise = Just (b !! x !! y)
getNearMines :: Board -> Pos -> Int
getNearMines b pos =
let
d = [-1, 0, 1]
dirs = (|+|) <$> [Pos a b| a <- d, b <- d] <*> [pos]
in
foldl (\acc p -> case getSquare b p of
Just (Square True _) -> acc + 1
_ -> acc) 0 dirs
getExpansions :: Board -> Pos -> [Pos]
getExpansions b pos =
case getSquare b pos of
Nothing -> []
Just (Square True _) -> []
Just _ -> expansions
where
isZero = getNearMines b pos == 0
ds = if isZero then
[Pos a b | a <- [-1, 0, 1], b <- [-1, 0, 1]]
else
[Pos a b | (a,b) <- [(-1, 0), (0, -1), (1, 0), (0, 1), (0, 0)]]
dirs = (|+|) <$> ds <*> [pos]
bounded_dirs = filter (\(Pos x y) -> x >= 0 && y >= 0) dirs
filtered_dirs = if isZero then
bounded_dirs
else
filter (\n -> n == pos || getNearMines b n == 0) bounded_dirs
expansions = foldl (\acc p -> case getSquare b p of
Just s@(Square False Untouched) -> p : acc
_ -> acc) [] filtered_dirs
expand :: Board -> [Pos] -> Maybe Board
expand b p = do
let expansions = concat $ mapMaybe (expand' b) p
let newboard = foldr (\(ri, row) r ->
foldr (\(ci, s) c ->
if Pos ri ci `elem` expansions then
NumberedSquare (getNearMines b $ Pos ri ci) : c
else
s : c
) [] (zip [0..] row) : r
) [] (zip [0..] b)
let removeCur = filter (`notElem` p) expansions
if not $ lost b p then
if null removeCur then
return newboard
else
expand newboard removeCur
else
Nothing
where
expand' :: Board -> Pos -> Maybe [Pos]
expand' b' p' =
case getSquare b' p' of
Nothing -> Nothing
Just (Square True _ ) -> Nothing
_ -> Just (getExpansions b' p')
lost :: Board -> [Pos] -> Bool
lost _ [] = False
lost b' (x:xs) =
case getSquare b' x of
Just (Square True _) -> True
_ -> lost b' xs
checkWin :: Board -> Bool
checkWin b =
all (==True) $
fmap (all (==True) .
fmap (\case
Square False Untouched -> False
_ -> True)) b
-----------
--Utilities
-----------
indexToPos :: Int -> Int -> Int -> Pos
indexToPos index w h = Pos (mod index w) (index `div` w)
posToIndex :: Pos -> Int -> Int -> Int
posToIndex (Pos x y) w h = y * w + x
printBoard :: Board -> IO ()
printBoard b = do
let width = length $ head b
putStrLn $ replicate (width * 2) '-'
mapM_ (putStrLn . unwords . fmap show) b
putStrLn $ replicate (length b * 2) '-'
markBoard :: Board -> Board
markBoard b =
foldr (\(ri, row) r ->
foldr (\(ci, s) c ->
case s of
Square False _ -> NumberedSquare (getNearMines b $ Pos ri ci) : c
Square True _ -> Square True LostMine : c
_ -> s : c
) [] (zip [0..] row) : r
) [] (zip [0..] b)
</code></pre>
|
[] |
[
{
"body": "<h1 id=\"incomplete-player-interface\">Incomplete player interface</h1>\n<p>There is no way for a player to mark a square as mined. Technically, you can beat the game without, but that is not the point here?</p>\n<h1 id=\"missing-entry-point\">Missing entry point</h1>\n<p>You did not state an entry point, from the linked project:</p>\n<pre><code>main :: IO ()\nmain = do\n args <- getArgs\n let [w, h, numMines] = args\n play (read w) (read h) (read numMines)\n</code></pre>\n<p>Can be done as</p>\n<pre><code> [w, h, mineCount] <- map read <$> getArgs\n play w h mineCount\n</code></pre>\n<h1 id=\"data-structures\">Data structures</h1>\n<p>I do not need many comments, but your data definition would certainly benefit:</p>\n<pre><code>data Square = Square Bool SquareStatus | NumberedSquare Int\n</code></pre>\n<p>So what does the Bool stand for? How is a mine represented? Took me a while to figure it out.</p>\n<p>The name <code>NumberedSquare</code> is about the view, not the model/business logic. My taste here is different than yours.</p>\n<p>Generally in haskell it is recommended to either have only one data constructor with the same name as the type or different constructor names, e.g.</p>\n<pre><code>data Tile = Closed Bool PlayerMarking | Opened Int\n</code></pre>\n<p>In my professional experience, the term <em>status</em> is overused and lost meaning. I'd rename <code>SquareStatus</code> to <code>PlayerMarking</code>.</p>\n<p>From the later code I see that you calculate the neighboring mines once a square is opened. I think your code can be made easier if you calculate it in advance and have:</p>\n<pre><code>data Square = Square { isMined :: Bool\n , neighboringMines :: Int\n , playerMarking :: PlayerMarking\n , opened :: Bool\n } deriving ...\n</code></pre>\n<p>You might want to split the mutable state <code>openend</code> and <code>playerMarking</code> from the pre-computed <code>isMined</code> and <code>opened</code>, but I have no idea at this time.</p>\n<p>So now you have a function <code>isMined :: Square -> Bool</code>. Even if you refactor the data structure (e.g. the just mentioned split), you might be able the write your own <code>isMined</code>.</p>\n<p>You use the environment <code>data Env = Env</code> only in the generation of the Board. Environment is another word that does not carry much meaning. How about <code>BoardGenerationParameters</code> or simply <code>Difficulty</code>?</p>\n<h1 id=\"show-instance\">Show instance</h1>\n<p>The <code>Show</code> typeclass <code>instance Show Square where</code> should not be used for pretty-printing, as documented in the <a href=\"https://hackage.haskell.org/package/base-4.15.0.0/docs/Prelude.html#t:Show\" rel=\"nofollow noreferrer\">Prelude</a>.\nJust have a function <code>prettyPrint</code>, no need for a typeclass or instance.</p>\n<p>And do you want to let your player count rows and columns? Coordinates are needed for input. Include those in pretty-printing.</p>\n<h1 id=\"type-declaration-for-operators\">Type declaration for operators</h1>\n<pre><code>infixl 6 |+|\nPos a b |+| Pos c d = Pos (a+c) (b+d)\n</code></pre>\n<p>Where is <code>(|+|) :: Pos -> Pos -> Pos</code>? I presume you once made <code>Pos</code> an instance of <code>Num</code> and then took it back (good)?!</p>\n<p>Anyway, <code>Pos</code> and indices can be mostly avoided.</p>\n<h1 id=\"did-you-step-on-a-mine\">Did you step on a mine?</h1>\n<p>It becomes hard to follow the logic in <code>play</code>. Why do you expand the Board into <code>Nothing</code> if you open a mine field? Just check right after getLine if it is a mine, boom!</p>\n<h1 id=\"board-generation\">Board generation</h1>\n<p>You take all board indices, take out the initial click, the take a random sample of <code>NumMines</code> and then iterate over all board indices again to generate [Square], which is then handed over to <code>chunksOf</code>. Took me a while to figure that out. I expect a rather easy chain with function composition. Where is it? Ah:</p>\n<pre><code>let field = take height $ chunksOf width $ genField randomLayout $ width * height\nlift $ return field\n</code></pre>\n<p>More idiomatic as</p>\n<pre><code>lift . return . take height . chunksOf width $ genField randomLayout\n</code></pre>\n<p>But the logic of <code>genField</code> and the index can be made simpler (Arguably).\nInstead of a random sample, I'd start with a list of Bools</p>\n<pre><code>replicate numMines True ++ replicate (w*h - numMines) False\n</code></pre>\n<p>and treat this as a deck of cards. Now you can just shuffle it with <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates</a>. Unfortunately, hoogle did not give me a simple result, i.e. one that works in <code>IO</code> or with <a href=\"https://hackage.haskell.org/package/random-1.2.0/docs/System-Random.html#t:RandomGen\" rel=\"nofollow noreferrer\">RandomGen</a>\nAfter the shuffle of <code>[Bool]</code>, just do the <code>chunksOf</code>. This way you can avoid the indices.\nYou lose the logic of "first opened square is never is mine", but you can start with <code>w*h - 1</code> cards and insert a false after shuffling.</p>\n<h1 id=\"foldl-and-simpler-functions\">Foldl and simpler functions</h1>\n<p>I try to avoid folds, simply because I cannot remember their signature. Instead of</p>\n<pre><code>getNearMines b pos = -- ...\n foldl (\\acc p -> case getSquare b p of\n Just (Square True _) -> acc + 1\n _ -> acc) 0 dirs\n</code></pre>\n<p>you can use <code>filter</code> and <code>length</code>:</p>\n<pre><code> length . filter isMined $ dirs\n</code></pre>\n<p>Even without the recommended <code>isMined</code> predicate, here is a trick I learned in golfing. (Food for thought, not a real improvement, but closer to your fold)</p>\n<pre><code> sum [ 1 | (Just (Square True _)) <- dirs ]\n</code></pre>\n<p>in a list comprehension, you can pattern match, so all neighbors from <code>dirs</code> that don't match are discarded.</p>\n<h1 id=\"binary-operators-in-applicatives\">Binary operators in Applicatives</h1>\n<p>For an operator <code>#</code>, a common way of writing <code>(#) <$> a <*> b</code> is <code>a <#> b where (<#>) = liftA2 (#)</code>, so</p>\n<pre><code>dirs = (|+|) <$> [Pos a b| a <- d, b <- d] <*> [pos]\n</code></pre>\n<p>could be</p>\n<pre><code>dirs = [Pos a b| a <- d, b <- d] <+> [pos]\n where (<+>) = liftA2 (|+|)\n</code></pre>\n<p>but here, that does not look better. In both instances where you use <code>|+|</code> you could use it as simple functor (actually just <code>map</code>) with operator section</p>\n<pre><code>dirs = map (|+| pos) [Pos a b| a <- d, b <- d]\n</code></pre>\n<h1 id=\"checkwin\">checkWin</h1>\n<p><code>all (==True)</code> is simply <code>and :: [Bool] -> Bool</code> (ignoring Foldable for now) and <code>all (==True) . fmap p</code> is just <code>all p</code> Edit: the latter can be done twice. Add an eta reduction and it becomes</p>\n<pre><code>checkWin = all (all (\\case\n Square False Untouched -> False\n _ -> True))\n</code></pre>\n<p>But it is more readable as</p>\n<pre><code>checkWin = all minelessSquareOpened . concat where\n minelessSquareOpened (Square False Untouched) = False\n minelessSquareOpened _ = True\n</code></pre>\n<p><code>minelessSquareOpened</code> can be called better, I just considered <code>unminedImpliesOpen</code> to be worse.</p>\n<h1 id=\"foldr-vs-map\">foldr vs map</h1>\n<p>those <code>foldr</code>s in <code>markBoard</code> and <code>expand</code> can be written as simple <code>map</code>s.</p>\n<h1 id=\"indices-and\">indices and <code>!!</code></h1>\n<p>The use of list indices and <code>!!</code> is not regarded as idiomatic haskell, and here, you can do mostly without.\n(Mostly? It is inevitable for the player input.)</p>\n<p>To count the neighbors without using indices, you can use something like</p>\n<pre><code>\\board -> zip3 \n (emptyLine ++ init board)\n board\n (tail board ++ emptyLine)\n</code></pre>\n<p>to group one row with the preceeding and following row and do the same for columns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T15:38:06.270",
"Id": "522362",
"Score": "0",
"body": "Wow thank you so much for the comprehensive review! I can definitely see the flaws in my code. I am now confusing myself with some of the choices I've made early on, which just goes to show that I need to work on writing in a clearer way. I think I still have lots of imperative programming \"bad habits\" that I need to get rid of when programming in haskell, which explains the amount of folds that I use."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T08:46:13.197",
"Id": "264467",
"ParentId": "264429",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264467",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T19:26:46.327",
"Id": "264429",
"Score": "4",
"Tags": [
"haskell",
"minesweeper"
],
"Title": "Minesweeper in haskell"
}
|
264429
|
<p>I wanted to make a bounded slider since the ranged slider wxwidgets includes isnt very useful for my use case. I wanted a left and right bounded slider to control a dynamic way to control a graph or plot x-range.</p>
<p>I got a good head start from a person who made a library in Python and ended up creating my own version in C++. I would appreciate any feedback on how I can improve my code or any errors I might have missed.</p>
<p>Using the widget requires wxWidgets 3.1.4; code can be found here <a href="https://github.com/georgeplusplus/wxWidgets-Custom-Ranged-Slider" rel="nofollow noreferrer">https://github.com/georgeplusplus/wxWidgets-Custom-Ranged-Slider</a></p>
<p>It is just two files; RangeSlider.cpp and RangeSlider.h. This file has two classes - the RangeSlider itself, and SliderThumb, which is responsible for the two nubs. I would like some feedback on how I handled my mouse inputs and calculating positioning of the drawing of the widget elements and general structure. I think others could benefit from this widget since I havnt seen one in C++ so I would like to make sure its the best it can be to share.</p>
<h2 id="mainwindow-n5e1">Mainwindow</h2>
<pre><code>#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif // !WX_PRECOMP
#include "include/MainWindow.h"
#include "include/RangeSlider.h"
MainWindow::MainWindow(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name) :
wxFrame(parent, id, title, pos, size, style, name)
{
SetSize(300, 100);
wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
SetSizer(mainSizer);
RangeSlider* range_slider = new RangeSlider(this);
mainSizer->Add(range_slider, 1, wxEXPAND | wxALL, 6);
}
</code></pre>
<h2 id="rangeslider.h-acam">RangeSlider.h</h2>
<pre><code>#pragma once
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif // !WX_PRECOMP
#include <wx/dcbuffer.h>
enum ThumbType
{
LOW,
HIGH,
};
class SliderThumb;
class RangeSlider : public wxPanel
{
public:
explicit RangeSlider(wxWindow* parent,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxSL_HORIZONTAL,
const wxString& name = wxPanelNameStr);
void PaintEvent(wxPaintEvent& event);
void Render(wxDC& dc);
int GetMax() { return max_value; };
int GetMin() { return min_value; };
void OnMouseDown(wxMouseEvent& event);
void OnMouseUp(wxMouseEvent& event);
void OnMouseLost(wxMouseCaptureLostEvent& event);
void OnMouseMotion(wxMouseEvent& event);
void OnMouseEnter(wxMouseEvent& event);
void OnMouseLeave(wxMouseEvent& event);
void OnResize(wxSizeEvent& event);
const int border_width = 8;
wxVector<SliderThumb> thumbs;
private:
SliderThumb* selected_thumb = nullptr;
int min_value = 0;
int max_value = 10000;
wxColor slider_background_color = wxColor(231, 234, 234);
wxColor slider_outline = wxColor(14, 14, 14);
wxColor selected_range_color = wxColor(0, 120, 215);
wxColor selected_range_outline = wxColor(0, 120, 215);
};
class SliderThumb
{
public:
SliderThumb(RangeSlider& parent, int value, ThumbType type);
bool IsMouseOver(wxPoint& click_pos);
void Render(wxDC& dc);
wxPoint GetPosition();
void SetPosition(wxPoint mouse_position);
const int GetThumbValue() const { return value_; };
const ThumbType GetType() const { return type_; };
const wxSize GetSize() const { return size_; };
int GetMin();
int GetMax();
bool mouse_over = false;
private:
RangeSlider* parent_;
float value_ = 0.0;
ThumbType type_;
wxSize size_;
wxPoint thumb_poly[5] = { wxPoint(0,0), wxPoint(0,13), wxPoint(5,18), wxPoint(10,13), wxPoint(10,0) };
wxPoint thumb_shadow_poly[4] = { wxPoint(0,14), wxPoint(4,18), wxPoint(6,18), wxPoint(10,14) };
wxColor normal_color = wxColor(0, 120, 215);
wxColor normal_shadow = wxColor(120, 180, 228);
wxColor dragged_color = wxColor(204, 204, 204);
wxColor dragged_shadow = wxColor(222, 222, 222);
wxColor mouse_over_color = wxColor(100, 100, 100);
wxColor mouse_over_shadow = wxColor(132, 132, 132);
};
</code></pre>
<h2 id="rangeslider.cpp-ob91">RangeSlider.cpp</h2>
<pre><code>#include "RangeSlider.h"
#include <wx/dcbuffer.h>
#include <algorithm>
float fraction_to_value(float fraction, int min_value, int max_value)
{
return (max_value - min_value) * fraction + min_value;
}
float value_to_fraction(float value, int min_value, int max_value)
{
return float(value - min_value) / (max_value - min_value);
}
RangeSlider::RangeSlider(wxWindow* parent, wxWindowID id,const wxPoint& pos ,const wxSize& size ,long style ,const wxString& name)
: wxPanel(parent, id, pos,size, style, name)
{
SetMinSize(wxSize(std::max({50, size.GetX()}), std::max({26, size.GetY()})));
SliderThumb low_thumb(*this, min_value, ThumbType::LOW);
SliderThumb high_thumb(*this, max_value, ThumbType::HIGH);
thumbs.push_back(low_thumb);
thumbs.push_back(high_thumb);
Bind(wxEVT_LEFT_DOWN, &RangeSlider::OnMouseDown, this, wxID_ANY);
Bind(wxEVT_LEFT_UP, &RangeSlider::OnMouseUp, this, wxID_ANY);
Bind(wxEVT_MOTION, &RangeSlider::OnMouseMotion, this, wxID_ANY);
Bind(wxEVT_MOUSE_CAPTURE_LOST, &RangeSlider::OnMouseLost, this, wxID_ANY);
Bind(wxEVT_ENTER_WINDOW, &RangeSlider::OnMouseEnter, this, wxID_ANY);
Bind(wxEVT_LEAVE_WINDOW, &RangeSlider::OnMouseLeave, this, wxID_ANY);
Bind(wxEVT_PAINT, &RangeSlider::PaintEvent, this, wxID_ANY);
Bind(wxEVT_SIZE, &RangeSlider::OnResize, this, wxID_ANY);
}
void RangeSlider::PaintEvent(wxPaintEvent& event)
{
// depending on your system you may need to look at double-buffered dcs
wxBufferedPaintDC dc(this);
Render(dc);
event.Skip();
}
void RangeSlider::Render(wxDC& dc)
{
auto background_brush = wxBrush(GetBackgroundColour(), wxBRUSHSTYLE_SOLID);
dc.SetBackground(background_brush);
dc.Clear();
int track_height = 12;
auto w = GetSize().GetX();
auto h = GetSize().GetY();
dc.SetPen(wxPen(slider_outline, 1, wxPENSTYLE_SOLID));
dc.SetBrush(wxBrush(slider_background_color, wxBRUSHSTYLE_SOLID));
dc.DrawRectangle(border_width, (h - track_height) / 2, w - 2 * border_width, track_height);
if (IsEnabled())
{
dc.SetPen(wxPen(selected_range_outline, 1, wxPENSTYLE_SOLID));
dc.SetBrush(wxBrush(selected_range_color, wxBRUSHSTYLE_SOLID));
}
else
{
dc.SetPen(wxPen(slider_outline, 1, wxPENSTYLE_SOLID));
dc.SetBrush(wxBrush(slider_outline, wxBRUSHSTYLE_SOLID));
}
auto low_thumb_pos = thumbs[0].GetPosition().x;
auto high_thumb_pos = thumbs[1].GetPosition().x;
dc.DrawRectangle(low_thumb_pos, h / 2 - track_height / 4, high_thumb_pos - low_thumb_pos, track_height / 2);
for (auto& thumb : thumbs)
{
thumb.Render(dc);
}
}
void RangeSlider::OnMouseDown(wxMouseEvent& event)
{
if (!IsEnabled())
{
return;
}
auto click_pos = event.GetPosition();
for (auto& thumb : thumbs)
{
if (thumb.IsMouseOver(click_pos))
{
selected_thumb = &thumb;
break;
}
}
CaptureMouse();
Refresh();
}
void RangeSlider::OnMouseUp(wxMouseEvent& event)
{
if (!IsEnabled())
{
return;
}
selected_thumb = nullptr;
if (HasCapture())
{
ReleaseMouse();
}
}
void RangeSlider::OnMouseLost(wxMouseCaptureLostEvent& event)
{
event.Skip();
}
void RangeSlider::OnMouseMotion(wxMouseEvent& event)
{
if (!IsEnabled())
{
return;
}
bool refresh_needed = false;
wxPoint mouse_position = event.GetPosition();
if(selected_thumb)
{
if (selected_thumb->GetType() == ThumbType::LOW)
{
if(mouse_position.x + selected_thumb->GetSize().x > thumbs[1].GetPosition().x)
{
// Then Mouse position equals the last known good thumb pos.
mouse_position = selected_thumb->GetPosition();
}
}
else
{
if (mouse_position.x - selected_thumb->GetSize().x < thumbs[0].GetPosition().x)
{
// Then Mouse position equals the last known good thumb pos.
mouse_position = selected_thumb->GetPosition();
}
}
selected_thumb->SetPosition(mouse_position);
refresh_needed = true;
}
else
{
for (auto& thumb : thumbs)
{
bool old_mouse_over = thumb.mouse_over;
thumb.mouse_over = thumb.IsMouseOver(mouse_position);
if (old_mouse_over != thumb.mouse_over)
{
refresh_needed = true;
}
}
}
if (refresh_needed)
{
Refresh();
}
}
void RangeSlider::OnMouseEnter(wxMouseEvent& event)
{
event.Skip();
}
void RangeSlider::OnMouseLeave(wxMouseEvent& event)
{
if (!IsEnabled())
{
return;
}
for (auto& thumb : thumbs)
{
thumb.mouse_over = false;
}
Refresh();
}
void RangeSlider::OnResize(wxSizeEvent& event)
{
Refresh();
}
SliderThumb::SliderThumb(RangeSlider& parent, int value, ThumbType type)
{
parent_ = &parent;
value_ = value;
type_ = type;
size_ = wxSize(10, 18);
}
void SliderThumb::Render(wxDC& dc)
{
wxColor thumb_color;
wxColor thumb_shadow_color;
if (!parent_->IsEnabled())
{
thumb_color = dragged_color;
thumb_shadow_color = dragged_shadow;
}
else if (mouse_over)
{
thumb_color = mouse_over_color;
thumb_shadow_color = mouse_over_shadow;
}
else
{
thumb_color = normal_color;
thumb_shadow_color = normal_shadow;
}
auto thumb_pos = GetPosition();
dc.SetBrush(wxBrush(thumb_shadow_color, wxBRUSHSTYLE_SOLID));
dc.SetPen(wxPen(thumb_shadow_color, 1, wxPENSTYLE_SOLID));
dc.DrawPolygon(WXSIZEOF(thumb_shadow_poly), thumb_shadow_poly, thumb_pos.x - size_.x / 2, thumb_pos.y - size_.y / 2);
dc.SetBrush(wxBrush(thumb_color, wxBRUSHSTYLE_SOLID));
dc.SetPen(wxPen(thumb_color, 1, wxPENSTYLE_SOLID));
dc.DrawPolygon(WXSIZEOF(thumb_poly), thumb_poly, thumb_pos.x - size_.x / 2, thumb_pos.y - size_.y / 2);
}
wxPoint SliderThumb::GetPosition()
{
auto min_x = GetMin();
auto max_x = GetMax();
auto parent_size = parent_->GetSize();
auto min_value = parent_->GetMin();
auto max_value = parent_->GetMax();
auto fraction = value_to_fraction(value_, min_value, max_value);
wxPoint pos(fraction_to_value(fraction, min_x, max_x), parent_size.GetY() / 2 + 1);
return pos;
}
bool SliderThumb::IsMouseOver(wxPoint& click_pos)
{
auto pos = GetPosition();
auto boundary_low = pos.x - size_.x / 2;
auto boundary_high = pos.x + size_.x / 2;
mouse_over = (click_pos.x >= boundary_low && click_pos.x <= boundary_high);
return mouse_over;
}
void SliderThumb::SetPosition(wxPoint mouse_position)
{
auto pos_x = mouse_position.x;
pos_x = std::min(std::max(pos_x, GetMin()), GetMax());
auto fraction = value_to_fraction(pos_x, GetMin(), GetMax());
value_ = fraction_to_value(fraction, parent_->GetMin(), parent_->GetMax());
}
int SliderThumb::GetMin()
{
return parent_->border_width + size_.x / 2;
}
int SliderThumb::GetMax()
{
auto parent_size = parent_->GetSize();
return (parent_size.GetX() - parent_->border_width - size_.x / 2);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/UpCf9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UpCf9.png" alt="enter image description here" /></a></p>
|
[] |
[
{
"body": "<h1 id=\"move-class-sliderthumb-into-class-rangeslider-wer0\">Move <code>class SliderThumb</code> into <code>class RangeSlider</code></h1>\n<p>A <code>SliderThumb</code> is just an implementation detail of a <code>RangeSlider</code>, so you can nest it inside <code>class RangeSlider</code>. You can then also rename it to just <code>Thumb</code>, to avoid having to repeat the <code>Slider</code>. Here is what it looks like:</p>\n<pre><code>class RangeSlider : public wxPanel {\n class Thumb {\n ...\n };\n\npublic:\n ...\n wxVector<Thumb> thumbs;\n ...\n};\n</code></pre>\n<h1 id=\"make-more-member-variables-private-99ux\">Make more member variables <code>private</code></h1>\n<p>Avoid making member variables public if they should not be part of the public API. Also consider whether you want raw variables to be exposed, or whether it is better to add getter/setter functions for them. I would make <code>border_width</code> a <code>private</code> variable, and add a <code>GetBorderWidth()</code> function.</p>\n<p>The vector <code>thumbs</code> should definitely be made <code>private</code>, nothing should be able to modify that vector except <code>SliderThumb</code>'s own member functions.</p>\n<h1 id=\"make-thumbtype-an-enum-class-inside-class-thumb-blkl\">Make <code>ThumbType</code> an <code>enum class</code> inside <code>class Thumb</code></h1>\n<p>Make <code>ThumbType</code> an <a href=\"https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations\" rel=\"nofollow noreferrer\"><code>enum class</code></a> for some extra type safety. Also, since the type of a thumb is just an implementation detail of a thumb, move this inside <code>class Thumb</code>:</p>\n<pre><code>class RangeSlider : public wxPanel {\n class Thumb {\n public:\n enum class Type {\n LOW,\n HIGH,\n };\n\n Thumb(RangeSlider& parent, int value, Type type);\n ...\n };\n ...\n};\n</code></pre>\n<h1 id=\"store-the-two-thumbs-in-a-stdarray-2qvs\">Store the two thumbs in a <code>std::array</code></h1>\n<p>You always have exactly two thumbs, so it doesn't make sense to store them in a <code>wxVector</code>. Just use <code>std::array</code> for this. You also don't have to push items to the array in the constructor, you can just initialize it where you declare the array:</p>\n<pre><code>class RangeSlide : public wxPanel {\n ...\n std::array<Thumb, 2> thumbs = {{\n {*this, min_value, Thumb::Type::LOW},\n {*this, max_value, Thumb::Type::HIGH},\n }};\n ...\n};\n</code></pre>\n<p>The double braces are <a href=\"https://stackoverflow.com/a/8192275/5481471\">necessary</a>.</p>\n<h1 id=\"make-constants-static-constexpr-where-possible-bsvb\">Make constants <code>static constexpr</code> where possible</h1>\n<p>There are several constants or variables that are effectively constant in your code, like <code>border_width</code>, <code>min_value</code>, <code>max_value</code>, and the colors. If they are really meant to be constant, make them <code>static constexpr</code>.</p>\n<h1 id=\"fix-quick-motions-making-the-slider-look-stucked-crzw\">Fix quick motions making the slider look stucked</h1>\n<p>If I grab the right thumb and quickly move the mouse left past the left thumb, the right thumb hasn't moved all the way left, but is stuck somehwere halfway. You should fix the logic in <code>OnMouseMotion()</code> to ensure you always update <code>mouse_position</code>, but limit it such that you cannot make the two thumbs cross each other:</p>\n<pre><code>switch (selected_thumb->GetType()) {\ncase Thumb::Type::LOW: \n mouse_position.x = std::min(mouse_position.x, thumbs[1].GetPosition().x);\n break;\ncase Thumb::Type::HIGH: \n mouse_position.x = std::max(mouse_position.x, thumbs[0].GetPosition().x);\n break;\n}\n\nselected_thumb->SetPosition(mouse_position);\n</code></pre>\n<p>The above allows both thumbs to overlap each other completely, but you can easily modify it to prevent that by adding/subtracting the size from <code>thumbs[?].GetPosition().x</code>.</p>\n<h1 id=\"use-stdclamp-if-possible-vkp5\">Use <code>std::clamp()</code> if possible</h1>\n<p>I see you want to limit some values to be between a minimum and maximum value, and you are nesting <code>std::min()</code> and <code>std::max()</code>. Since C++17, you can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/clamp\" rel=\"nofollow noreferrer\"><code>std::clamp()</code></a> to do that in an easier way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T11:44:45.397",
"Id": "264475",
"ParentId": "264431",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T20:45:08.877",
"Id": "264431",
"Score": "2",
"Tags": [
"c++",
"gui"
],
"Title": "Custom C++ wxWidget Ranged Slider"
}
|
264431
|
<p>I recently tried to solve the first non-repeating character problem. Please tell me if my solution is valid. I'm aiming for O(n) with a single loop.</p>
<p>My thinking is, it would be easy to tell you what the last non repeated character is, just:</p>
<pre class="lang-none prettyprint-override"><code>loop each char
if map[char] doesn't exist
output = char
store char in map
</code></pre>
<p>So if you can get the last non repeated character, wouldn't you be able to run the same algorithm to get the first one, if the loop went through the string backwards? Here's my (python) code:</p>
<pre class="lang-py prettyprint-override"><code>def firstNonRepeater(s):
smap = {}
out = ''
for i in range(len(s)-1, -1, -1):
if s[i] not in smap:
out = s[i]
if s[i] in smap:
smap[s[i]] += 1
else:
smap[s[i]] = 1
if smap[out] > 1:
return None
return out
</code></pre>
<p>There is some extra code to catch when there are no unique chars.</p>
<p>This seems to work, am I missing something?</p>
<h4 id="edit-cxuv">EDIT:</h4>
<p>@Alex Waygood has raised that my solution has an oversight, in that it will return None if it encounters a repeating character, where all instances are before the first non-repeater. See his in-depth explanation below.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T22:04:25.507",
"Id": "522221",
"Score": "0",
"body": "Also, what are the constraints here? Are you aiming for a solution that just uses builtin types, or are solutions that use `collections`/`itertools` etc okay?"
}
] |
[
{
"body": "<h2 id=\"style-7dcp\">Style</h2>\n<p>From <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8</a>, function names should be lowercase and use underscores to separate words:</p>\n<pre><code>def first_non_repeater(s):\n ...\n</code></pre>\n<h2 id=\"implementation-3w4y\">Implementation</h2>\n<p>In Python 3.6+ <a href=\"https://stackoverflow.com/a/39980744/11659881\">dictionaries maintain insertion order</a> and if you're using an earlier version, <a href=\"https://www.python.org/dev/peps/pep-0372/\" rel=\"noreferrer\">PEP 372</a> adds <code>collections.OrderedDict</code>. If <code>collections.Counter</code> used an <code>OrderedDict</code>, you could solve this problem with that, but it doesn't so we will do that work instead:</p>\n<pre><code>from collections import OrderedDict\n\ndef first_non_repeater(s):\n smap = OrderedDict()\n for char in s:\n if char in smap:\n smap[char] += 1\n else:\n smap[char] = 1\n for char, count in smap.items():\n if count == 1:\n return char\n return None\n</code></pre>\n<p>In the best case, this is O(N), worst case it is O(2N), and average case you would expect O(3N/2), all of which is just O(N).</p>\n<p>The room for improvement here would be to eliminate this:</p>\n<pre><code>for char, count in smap.items():\n if count == 1:\n return char\n</code></pre>\n<p>But removing this requires more complicated code and makes it more bug-prone with little benefit. As pointed out by @AJNeufeld, your code won't work for <code>"xxyzz"</code> and many other cases. Avoiding a second pass through the characters in your text will add a considerable amount of complexity to your code, and might not even make the solution faster as it will require extra checks in your initial <code>for</code> loop, and in the best case it still doesn't change the complexity from O(N).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T08:57:48.430",
"Id": "524406",
"Score": "0",
"body": "O(N), O(2N), and O(3N/2) are technically all the same... It doesn't make much sense to use Big-O this way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T23:11:32.703",
"Id": "264435",
"ParentId": "264433",
"Score": "8"
}
},
{
"body": "<p>Python has a <code>Counter</code> data structure that is handy whenever you are ...\ncounting things. Since strings are directly iterable, you can easily get a\ndict-like tally for how many times each character occurs in a string. And since\nmodern Python dicts keep track of insertion order, you can just iterate over\nthat tally, returning the first valid character.</p>\n<pre><code>from collections import Counter\n\ndef first_non_repeater(s):\n for char, n in Counter(s).items():\n if n == 1:\n return char\n return None\n\nprint(first_non_repeater("xxyzz")) # y\nprint(first_non_repeater("xxyzzy")) # None\nprint(first_non_repeater("xxyzazy")) # a\n</code></pre>\n<p>And if you don't want to use <code>Counter</code>, just add your\nown counting logic to the function:</p>\n<pre><code>tally = {}\nfor char in s:\n try:\n tally[char] += 1\n except KeyError:\n tally[char] = 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T06:32:53.150",
"Id": "522239",
"Score": "2",
"body": "Even shorter: `def first_non_repeater(s): return next((char for char, n in Counter(s).items() if n == 1), None)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:24:54.863",
"Id": "522249",
"Score": "2",
"body": "This is a great solution, pythons Counter seems very elegant here. I also had no idea that later python versions maintained insertion order in dicts, so I wasn't aware that writing your own tally was an option(since I thought there is no way to check the first occurrence). Thanks for your help. Although your answer doesn't mention that my algorithm is flawed(feel free to update), I'll accept it because I like the solution best."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T23:40:14.143",
"Id": "264436",
"ParentId": "264433",
"Score": "16"
}
},
{
"body": "<p>As has been pointed out in the comments and @Kraigolas's answer, the existing algorithm doesn't work. Here's why.</p>\n<p>In the string <code>"xxy"</code>:</p>\n<ol>\n<li>The algorithm first considers the third character, <code>"y"</code>. It finds it has not encountered it before, so records it as a preliminary <code>out</code> value. It adds it to <code>smap</code> with value <code>1</code>.</li>\n<li>The algorithm next considers the second character, <code>"x"</code>. It finds it has not encountered this character before, either. It discards its previous preliminary <code>out</code> value, <code>"y"</code>, and adopts <code>"x"</code> as its new preliminary <code>out</code> value. It adds <code>"x"</code> to <code>smap</code> with value <code>1</code>.</li>\n<li>The algorithm now moves on to the first character, <code>"x"</code>. It realises that it has seen this one before, so adds <code>1</code> to the associated value in <code>smap</code>.</li>\n<li>The algorithm has now finished iterating through the loop. Its current <code>out</code> value is <code>"x"</code>, but when it looks it up in <code>smap</code>, it finds it has encountered <code>"x"</code> more than once. As a result, it assumes that there are 0 characters that it has seen only once, and returns <code>None</code>.</li>\n</ol>\n<p>It is impossible to fix the current implementation of the algorithm while keeping to the condition that there should be "only a single loop". If you were to relax this restriction, you could "fix" your current algorithm like this:</p>\n<pre><code>def first_non_repeater(string):\n smap = {}\n\n for char in string:\n if char in smap:\n smap[char] += 1\n else:\n smap[char] = 1\n\n return next((k for k, v in smap.items() if v == 1), None)\n</code></pre>\n<p>Though it's generally both more idiomatic and more efficient, in python, to "ask for forgiveness" rather than "ask for permission":</p>\n<pre><code>def first_non_repeater(string):\n smap = {}\n\n for char in string:\n try:\n smap[char] += 1\n except KeyError:\n smap[char] = 1\n\n return next((k for k, v in smap.items() if v == 1), None)\n</code></pre>\n<p>And you can get there more cleanly by just using a <code>defaultdict</code>:</p>\n<pre><code>from collections import defaultdict\n\ndef first_non_repeater(string):\n smap = defaultdict(int)\n\n for char in string:\n smap[char] += 1\n\n return next((k for k, v in smap.items() if v == 1), None)\n</code></pre>\n<p>And I like @FMc's answer using <code>collections.Counter</code> more than any of these three — I think using <code>Counter</code> is probably the most pythonic way of doing this.</p>\n<p>But at I say, all of these solutions break the condition that only one loop is allowed (whether that's the key concern when it comes to an efficient algorithm in python is another question).</p>\n<p>The following would be my attempt at a solution that only uses builtin data structures (nothing from <code>collections</code>), and that only uses a single loop. The solution only works on python 3.6+, as it relies on <code>dict</code>s being ordered. Feedback welcome:</p>\n<pre><code>from typing import TypeVar, Union, Optional\n\nT = TypeVar('T')\n\ndef first_non_repeating_char(\n string: str,\n default: Optional[T] = None\n) -> Union[str, T, None]:\n """Return the first non-repeating character in a string.\n \n If no character in the string occurs exactly once,\n return the default value.\n\n Parameters\n ----------\n string: str\n The string to be searched.\n default: Any, optional\n The value to be returned if there is no character \n in the string that occurs exactly once.\n By default, None.\n\n Returns\n -------\n Either a string of length 1, or the default value.\n """\n \n # Using a dictionary as an ordered set,\n # for all the characters we've seen exactly once.\n # The values in this dictionary are irrelevant.\n uniques: dict[str, None] = {}\n \n # a set for all the characters\n # that we've already seen more than once\n dupes: set[str] = set() \n \n for char in string:\n if char in dupes:\n continue\n\n try:\n del uniques[char]\n except KeyError:\n uniques[char] = None\n else:\n dupes.add(char)\n\n # return the first key in the dictionary\n # if the dictionary isn't empty.\n # If the dictionary is empty,\n # return the default.\n return next(iter(uniques), default)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T01:48:10.983",
"Id": "522226",
"Score": "1",
"body": "Using `return next((k for k in uniques.keys()), default)` would allow you to skip the `try … except`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T02:00:04.323",
"Id": "522227",
"Score": "0",
"body": "Nice! Forgot about that @AJNeufeld — have edited it into my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T03:43:23.150",
"Id": "522229",
"Score": "1",
"body": "@AJNeufeld I guess? But you don't need a generator to do that; just call `iter`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T10:03:01.940",
"Id": "522267",
"Score": "0",
"body": "Could you please follow the Python style standards here on Code Review? Regarding your code: - There should be no blank line before the docstring. - The first line (summary) should be in imperative mood. - Etc. https://www.python.org/dev/peps/pep-0257/ http://www.pydocstyle.org/en/stable/error_codes.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T12:44:46.293",
"Id": "522275",
"Score": "1",
"body": "I have edited my docstring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T03:16:52.023",
"Id": "522331",
"Score": "1",
"body": "@Reinderien Yes, `iter(uniques)` is sufficient; you don't need the `.keys()`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T00:19:35.633",
"Id": "264437",
"ParentId": "264433",
"Score": "9"
}
},
{
"body": "<p>The main issue I see with this code is the lack of any unit tests. It's quite simple to invoke the test framework at the end of the module:</p>\n<pre><code>if __name__ == "__main__":\n import doctest\n doctest.testmod()\n</code></pre>\n<p>Now, just add some test cases:</p>\n<pre><code>def firstNonRepeater(s):\n """\n Returns the first character in the input string\n which is not repeated later in the string\n\n >>> firstNonRepeater('')\n \n >>> firstNonRepeater('a')\n 'a'\n >>> firstNonRepeater('aa')\n \n >>> firstNonRepeater('ab')\n 'a'\n >>> firstNonRepeater('aab')\n 'b'\n >>> firstNonRepeater('aba')\n 'b'\n """\n</code></pre>\n<p>Even this small set of tests reveals problems that need to be fixed:</p>\n<pre class=\"lang-none prettyprint-override\"><code>**********************************************************************\nFile "264433.py", line 8, in __main__.firstNonRepeater\nFailed example:\n firstNonRepeater('')\nException raised:\n Traceback (most recent call last):\n File "/usr/lib/python3.9/doctest.py", line 1336, in __run\n exec(compile(example.source, filename, "single",\n File "<doctest __main__.firstNonRepeater[0]>", line 1, in <module>\n firstNonRepeater('')\n File "264433.py", line 32, in firstNonRepeater\n if smap[out] > 1:\n KeyError: ''\n**********************************************************************\nFile "264433.py", line 16, in __main__.firstNonRepeater\nFailed example:\n firstNonRepeater('aab')\nExpected:\n 'b'\nGot nothing\n**********************************************************************\n1 items had failures:\n 2 of 6 in __main__.firstNonRepeater\n***Test Failed*** 2 failures.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T13:56:58.287",
"Id": "264447",
"ParentId": "264433",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264436",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T21:34:33.090",
"Id": "264433",
"Score": "10",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"strings",
"array"
],
"Title": "First non-repeating Character, with a single loop in Python"
}
|
264433
|
<p>I've just started to learn C++.</p>
<p>I have this class and I don't know where to put the following two lines because of the catch:</p>
<pre><code>delete[] chost;
delete[] cport;
</code></pre>
<p>I think they are in the right place, but I have doubts because in C++ doesn't exist <code>finally</code>.</p>
<p>Header:</p>
<pre><code>#pragma once
#include <string>
#include "TelnetClient.h"
class Ephemeris
{
public:
Ephemeris();
~Ephemeris();
bool Connect(std::string host, std::string port);
private:
TelnetClient* telnet = nullptr;
};
</code></pre>
<p>CPP:</p>
<pre><code>#include "Ephemeris.h"
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
Ephemeris::Ephemeris()
{
}
Ephemeris::~Ephemeris()
{
if (telnet != nullptr)
delete telnet;
}
bool Ephemeris::Connect(std::string host, std::string port)
{
bool result = false;
// Convert std::string host to char* host.
size_t host_length = host.length() + 1;
char* chost = new char[host_length];
strcpy_s(chost, host_length, host.c_str());
// Convert std::string port to char* port.
size_t port_length = port.length() + 1;
char* cport = new char[port_length];
strcpy_s(cport, port_length, port.c_str());
try
{
boost::asio::io_service io_service;
// Resolve the host name and port number to an iterator that can be used to
// connect to the server.
tcp::resolver resolver(io_service);
tcp::resolver::query query(chost, cport);
tcp::resolver::iterator iterator = resolver.resolve(query);
// Create a Telnet client
telnet = new TelnetClient(io_service, iterator);
// Run the IO service as a separate thread, so the main thread can block on standard input
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
result = true;
}
catch (std::exception& e)
{
if (telnet != nullptr)
delete telnet;
result = false;
}
// Free resources.
delete[] chost;
delete[] cport;
return result;
}
</code></pre>
<p>If you have any suggestions, related or not with my doubt, please, tell me.</p>
<p>The original code is this one, "<a href="https://lists.boost.org/boost-users/att-40895/telnet.cpp" rel="nofollow noreferrer">Boost Telnet Client</a>". I'm adapting it to my own needs.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T14:21:39.657",
"Id": "522285",
"Score": "0",
"body": "In addition to my answer, I'd recommend [my Code Project article](https://www.codeproject.com/Tips/5249485/The-Most-Essential-Cplusplus-Advice)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T17:33:16.577",
"Id": "522295",
"Score": "2",
"body": "`C++ doesn't exist finally.` True we have a better technique called destructors that are guaranteed to be called even when exceptions are thrown."
}
] |
[
{
"body": "<blockquote>\n<pre><code>Ephemeris::Ephemeris()\n{\n}\n</code></pre>\n</blockquote>\n<p>No need for a constructor if it does nothing.</p>\n<blockquote>\n<pre><code>Ephemeris::~Ephemeris()\n{\n if (telnet != nullptr)\n delete telnet;\n}\n</code></pre>\n</blockquote>\n<p>The test here is pointless, since <code>delete</code> works fine with a null argument. We can improve on this by making <code>telnet</code> a smart pointer (probably <code>std::unique_ptr<TelnetClient></code>), so that a default destructor is sufficient.</p>\n<p>Changing to smart pointer also means we don't need to override or delete the copy constructor and assignment operator, which we have failed to do (meaning that after copying, one object's destructor would delete the other's data).</p>\n<blockquote>\n<pre><code>bool Ephemeris::Connect(std::string host, std::string port)\n</code></pre>\n</blockquote>\n<p>Do we really need modifiable copies of <code>host</code> and <code>port</code>? It looks like we should be fine with const references:</p>\n<pre><code>bool Ephemeris::Connect(const std::string& host, const std::string& port)\n</code></pre>\n<blockquote>\n<pre><code>size_t host_length = host.length() + 1;\nchar* chost = new char[host_length];\nstrcpy_s(chost, host_length, host.c_str());\n</code></pre>\n</blockquote>\n<p>Is there a need to <em>copy</em> the string from <code>host</code>? We're going to pass this to the <code>resolver::query</code> constructor, which accepts a <code>const std::string&</code>, so it's completely pointless to copy the characters to create a new string. We can simply pass our existing strings:</p>\n<pre><code> tcp::resolver::query query(host, port);\n</code></pre>\n<blockquote>\n<pre><code> telnet = new TelnetClient(io_service, iterator);\n</code></pre>\n</blockquote>\n<p>We have a memory leak here, as we have not freed the previous value of <code>telnet</code> before assigning this new one. A smart pointer takes care of that for us.</p>\n<blockquote>\n<pre><code> boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));\n</code></pre>\n</blockquote>\n<p><code>boost:thread</code> is not declared - I recommend including <code><boost/thread.hpp></code> to get a definition in scope.</p>\n<blockquote>\n<pre><code> }\n</code></pre>\n</blockquote>\n<p>It's a bad idea to destruct a running joinable thread. If we really want it to continue in the background we should <code>detach()</code> it first.</p>\n<blockquote>\n<pre><code> catch (std::exception& e)\n</code></pre>\n</blockquote>\n<p>It's generally a bad idea to catch all kinds of exception like this. It's probably better to allow our function to throw exceptions, rather than returning a status code that the caller could forget to examine.</p>\n<blockquote>\n<pre><code> if (telnet != nullptr)\n delete telnet;\n</code></pre>\n</blockquote>\n<p>That's risky. We now have a dangling pointer to the deleted <code>telnet</code> object. The smart pointer helps here, because we can clear it, which both deletes the object and changes the pointer to a null pointer.</p>\n<blockquote>\n<pre><code> return result;\n</code></pre>\n</blockquote>\n<p>With proper destructors, there's no need to store the return value - we can return immediately and let C++ clean up our objects.</p>\n<hr />\n<h1 id=\"modified-code-17w3\">Modified code</h1>\n<pre><code>#include <memory>\n#include <string>\n\nclass Ephemeris\n{\npublic:\n void Connect(const std::string& host, const std::string& port);\n\nprivate:\n std::unique_ptr<TelnetClient> telnet = {};\n};\n</code></pre>\n\n<pre><code>#include <boost/array.hpp>\n#include <boost/asio.hpp>\n#include <boost/thread.hpp>\n\nusing boost::asio::ip::tcp;\n\nvoid Ephemeris::Connect(const std::string& host, const std::string& port)\n// may throw boost::thread_resource_error or boost::system::system_error\n{\n boost::asio::io_service io_service;\n // Resolve the host name and port number to an iterator that can\n // be used to connect to the server.\n tcp::resolver resolver{io_service};\n tcp::resolver::query query{host, port};\n tcp::resolver::iterator iterator = resolver.resolve(query);\n\n try {\n // Create a Telnet client\n telnet = std::make_unique<TelnetClient>(io_service, iterator);\n\n // Run the IO service as a separate thread, so the main thread\n // can block on standard input\n boost::thread t{boost::bind(&boost::asio::io_service::run, &io_service)};\n t.detach();\n } catch (...) {\n telnet.reset();\n throw;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T06:49:57.333",
"Id": "522244",
"Score": "0",
"body": "Wow, I'm thinking about how many time I will need to know everything you know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:15:34.477",
"Id": "522247",
"Score": "0",
"body": "I think you have to add `#include \"TelnetClient.h\"` in the header file of the modified code. Or maybe, I'm wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:22:21.143",
"Id": "522248",
"Score": "0",
"body": "You said: *\"With proper destructors, there's no need to store the return value - we can return immediately and let C++ clean up our objects.\"*. But, there is no destructor in `MyClass`. What destructors are you talking about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T07:42:37.693",
"Id": "522251",
"Score": "1",
"body": "I have no idea what `MyClass` is - that's not in the code here. I was talking about the (implicit) destructor in `Ephemeris` as one example - because `telnet` is a smart pointer, it will get cleaned up for us. Oh, I just noticed that you reset `telnet` when the thread can't be created - I'll adjust my replacement code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T08:01:02.700",
"Id": "522254",
"Score": "0",
"body": "Sorry, `MyClass` is `Ephemeris`. My apologies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T08:04:11.167",
"Id": "522255",
"Score": "0",
"body": "By the way, my code comes from this example, https://lists.boost.org/boost-users/att-40895/telnet.cpp. I'm adapting it to my own needs. Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:47:38.560",
"Id": "522309",
"Score": "0",
"body": "The in-class-initializer for the sole member is pretty useless... Also, let's hope the service runs fast enough `io_service` is no longer needed when it gets destroyed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:12:06.870",
"Id": "522311",
"Score": "0",
"body": "The \"useless\" initializer keeps `gcc -Weffc++` happy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:18:52.197",
"Id": "522314",
"Score": "0",
"body": "@Deduplicator, you're probably right about the lifetime of `io_service` - that part does look decidedly racy. I don't know the Boost libraries well enough to comment, but if that were `std::thread` I'd be worried. And they are not so different..."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T06:36:00.673",
"Id": "264442",
"ParentId": "264440",
"Score": "9"
}
},
{
"body": "<p>I agree with everything Toby Speight wrote. I'd like to add:</p>\n<h1 id=\"name-things-according-to-what-they-represent-0a1j\">Name things according to what they represent</h1>\n<p>You have this line of code:</p>\n<pre><code>tcp::resolver::iterator iterator = resolver.resolve(query);\n</code></pre>\n<p>But while <code>iterator</code> is indeed an iterator, that's not what is important about this variable. What really is important is that it is the result of the DNS query. So I would write this instead:</p>\n<pre><code>auto query_result = resolver.resolve(query);\n</code></pre>\n<p>Alternatively, you could also name it <code>addresses</code>, as the query result is the resolved list of addresses for the given hostname and port combination.</p>\n<h1 id=\"prefer-the-standard-library-over-boost-17r2\">Prefer the standard library over Boost</h1>\n<p>Boost is very nice, but depending on it has a cost: it adds dependencies and there is a compile-time overhead. Furthermore, the standard library is evolving as well, and many features that were once only available in external libraries like Boost are now available in the STL. So instead of:</p>\n<pre><code>boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));\n</code></pre>\n<p>I would prefer to write this:</p>\n<pre><code>std::thread t(&boost::asio::io_service::run, &io_service);\n</code></pre>\n<h1 id=\"remove-unused-include-directives-tixp\">Remove unused <code>#include</code> directives</h1>\n<p>I see <code>#include <boost/array.hpp></code>, but no <code>boost::array</code>s are used anywhere. Remove the <code>#include</code> to avoid an unnecessary dependency and compile-time overhead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T09:18:53.917",
"Id": "264443",
"ParentId": "264440",
"Score": "4"
}
},
{
"body": "<p>If you just started learning C++, I suggest reading through (and bookmarking) the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"nofollow noreferrer\">C++ Core Guidelines</a>. One example that pops out, from your opening remarks, is C.149, R.11, and P.9.</p>\n<p>That is, rather than being puzzled as to where to put the <code>delete[]</code> statements due to exception handling, you should not be writing explicit calls to <code>delete</code> in your code.</p>\n<hr />\n<pre><code>#pragma once\n#include <string>\n#include "TelnetClient.h"\n\nclass Ephemeris\n{\npublic:\n Ephemeris();\n\n ~Ephemeris();\n\n bool Connect(std::string host, std::string port);\n\nprivate:\n TelnetClient* telnet = nullptr;\n};\n</code></pre>\n<p>Just looking at this header:</p>\n<ol>\n<li>You are passing <code>std::string</code> arguments <strong>by value</strong>.</li>\n<li>Your destructor is declared but not defined in the header... so it must do something complex I suppose. But the only data in the class is one (raw) pointer. I'm guessing that what this class does is allow you to have an <code>std::optional<TelnetClient></code>? That is, what's it do beyond simply using the <code>TelnetClient</code> directly?</li>\n<li>I'm supposing that <code>telnet</code> ought to be a <code>std::unique_ptr</code>. Then you don't need to write the destructor explicitly.</li>\n<li>You didn't write a copy constructor or copy assignment operator, and the defaults won't work right. Use the <strong>rule of 3/5/0</strong>. If you used a <code>std::unique_ptr</code> the copying would be automatically disabled and you would not have to deal with it.</li>\n</ol>\n<p>Looking at the implementation now...</p>\n<pre><code>Ephemeris::Ephemeris()\n{\n}\n</code></pre>\n<p>Just don't. Literally, don't write an empty constructor because it doesn't add anything over <code>=default</code> <em>and</em> it prevents the compiler from understanding just how trivial the class is and optimizing better. If you did need a (very simple) constructor, you should put it in the header directly in the class. In this case, you don't need to define it at all since the compiler automatically supplies it.</p>\n<pre><code>Ephemeris::~Ephemeris()\n{\n if (telnet != nullptr)\n delete telnet;\n}\n</code></pre>\n<p>Again, put very simple destructors in the header so they can be inlined.<br />\n<code>delete</code> already does a null-check, so don't repeat it.<br />\nYou should be using a <code>std::unique_ptr</code> which already has the destructor tightly wrapped around a pointer, so you don't need to write a destructor for this class. Don't use <code>new</code>/<code>delete</code> directly in your own code, unless you are writing a container or resource manager of some kind.</p>\n<p>Basically, this class doesn't do anything. You want a free function <code>Connect</code> that returns a <code>std::unique_ptr<TelnetClient></code>.</p>\n<hr />\n<pre><code>// Convert std::string host to char* host.\n size_t host_length = host.length() + 1;\n char* chost = new char[host_length];\n strcpy_s(chost, host_length, host.c_str());\n\n // Convert std::string port to char* port.\n size_t port_length = port.length() + 1;\n char* cport = new char[port_length];\n strcpy_s(cport, port_length, port.c_str());\n</code></pre>\n<p>Why? Why can't <code>query</code> take the <code>port.c_str()</code> directly? I see you're never deleting <code>cport</code> and <code>chost</code>, so does the Boost class take ownership? I find that bizarre, since Boost is a C++ library and would be using <code>std::string</code> to keep ownership of a string.</p>\n<p>If you did need to do this for some reason, <strong>don't repeat yourself</strong>. You have identical code except for the parameters, so this is very simple to make into a function.</p>\n<p>In fact, isn't <code>strdup</code> already a standard C function?</p>\n<p>Again, if you used <code>std::unique_ptr</code> you would not need to write a <code>try</code>/<code>catch</code> block in <code>Connect</code>. Your resource (the pointer) is not wrapped tightly enough and you're forced to handle it in this function which has more stuff going on. By wrapping resources tightly, you avoid dealing with them in the enclosing code. This is a very important principle to learn.</p>\n<pre><code>// Free resources.\n delete[] chost;\n delete[] cport;\n</code></pre>\n<p>OK, you do this at the end. So <strong>why</strong> did you make a copy of the string data in this manner? Clearly you know how to get the <code>const char*</code> nul-terminated string from the <code>std::string</code> class, since you actually call <code>.c_str()</code> in order to make the copy.\nAs you already know, you're not freeing the data if an exception happens, and you should not need to be doing this (even if you did need to make a copy) directly.</p>\n<hr />\n<h1 id=\"postscript-6kbo\">Postscript</h1>\n<p>I would further improve Toby's rewrite by not having the <code>Ephemeris</code> class at all; just a free function:</p>\n<pre><code>unique_ptr<TelnetClient> Connect (const std::string& host, const std::string& port);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:16:56.030",
"Id": "522313",
"Score": "2",
"body": "`strdup()` is a POSIX function, but not part of the standard C or C++ library."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T14:21:12.850",
"Id": "264449",
"ParentId": "264440",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264442",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T05:52:11.343",
"Id": "264440",
"Score": "3",
"Tags": [
"c++",
"c++11",
"boost"
],
"Title": "Connect to telnet server"
}
|
264440
|
<p>I have a python script to archive some data (export from mongo to a local json file and then upload it to s3)</p>
<p>Is there a better way to implement/improve the current flow? Each step should be be retried in case of failure and if the step is still failing after the set no of retries it shouldn't run the other steps but continue with the archiving for the other records.</p>
<pre><code> archived = 0
flow_status = False
for metadata_id in metadata_ids:
logging.info("Archiving snapshot with metadata_id %s", metadata_id)
# Export snapshot to a temp JSON file
for retry in range(0, 3):
flow_status = dump_snapshot(mongo, database, collection, str(metadata_id), folder_path, dry_run)
if not flow_status:
logging.info("Failed to export snapshot %s to json file. Retry no %s", str(metadata_id), retry)
else:
logging.info("Successfully exported snapshot %s to json file.", str(metadata_id))
break
if not flow_status:
logging.error("Snapshot archiving flow failed for %s. Failed to export to json file. ", str(metadata_id))
continue
# Save the temp file to S3
file_path = folder_path + '/' + database + '/' + collection + '/' + str(metadata_id) + '.json'
aws_path = "archived_snapshots/" + database + '/' + collection + '/' + str(metadata_id) + '.json'
for retry in range(0, 3):
flow_status = aws.upload_file(file_path, aws_path, dry_run)
if not flow_status:
logging.info("Failed to save snapshot file %s to s3. Retry no %s", str(metadata_id), retry)
else:
logging.info("Successfully saved snapshot %s to s3.", str(metadata_id))
break
if not flow_status:
logging.error("Snapshot archiving flow failed for %s. Failed to saved file to s3. ", str(metadata_id))
continue
# Validate the file exists on S3 and has the correct checksum
if not aws.check_file_exists(aws_path) or not aws.validate_s3_obj(file_path, aws_path):
logging.error("Snapshot archiving flow failed for %s. Failed to validate file. ", str(metadata_id))
continue
# Delete temp file
if not dry_run:
delete_file(file_path)
# Set the archive_status to "ArchivedToPurge" in the MongoDB metadata collection
metadata_collection = collection + "_metadata"
for retry in range(0, 3):
flow_status = update_archive_status(mongo.client[database][metadata_collection], metadata_collection,
metadata_id, archiving_status.ArchivedToPurge.name, dry_run)
if not flow_status:
logging.info("Failed to update snapshot metadata for %s to %s. Retry no %s", metadata_collection +
"/" + str(metadata_id), archiving_status.ArchivedToPurge.name, retry)
else:
logging.info("Updated snapshot metadata for %s to %s", metadata_collection + "/" + str(metadata_id),
archiving_status.ArchivedToPurge.name)
break
if not flow_status:
logging.error("Snapshot archiving flow failed for %s. Failed to update metadata to %s", str(metadata_id),
archiving_status.ArchivedToPurge.name)
continue
# Delete the documents in MongoDB
logging.info("Deleting snapshots with metadata_id %s from collection %s", str(metadata_id), collection)
for retry in range(0, 3):
if dry_run:
break
records_count = mongo_count(mongo.client[database][collection], match={"metadata_id": metadata_id})
deleted_count = mongo_delete(mongo.client[database][collection], {"metadata_id": metadata_id})
flow_status = deleted_count == records_count
if not flow_status:
logging.info("Failed to delete all records of snapshot with metadata_id %s. Deleted %s out of %s "
"records", str(metadata_id), deleted_count, records_count)
else:
logging.info("Deleted %s records of snapshot with metadata_id %s from collection %s",
deleted_count, str(metadata_id), collection)
break
if not flow_status:
logging.error("Snapshot archiving flow failed for %s. Failed to delete all snapshot records.",
str(metadata_id))
continue
# Set the archive_status to "ArchivedAndPurged" in the MongoDB metadata collection.
for retry in range(0, 3):
flow_status = update_archive_status(mongo.client[database][metadata_collection], metadata_collection,
metadata_id, archiving_status.ArchivedAndPurged.name, dry_run)
if not flow_status:
logging.info("Failed to update snapshot metadata for %s to %s. Retry no %s", metadata_collection +
"/" + str(metadata_id), archiving_status.ArchivedToPurge.name, retry)
else:
logging.info("Updated snapshot metadata for %s to %s", metadata_collection + "/" + str(metadata_id),
archiving_status.ArchivedToPurge.name)
break
if not flow_status:
logging.error("Snapshot archiving flow failed for %s. Failed to update metadata to %s.", str(metadata_id),
archiving_status.ArchivedAndPurged.name)
continue
</code></pre>
<p>Any tips/advice?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T14:48:00.273",
"Id": "522286",
"Score": "1",
"body": "Without definitions for `metadata_ids`, `dump_snapshot`, etc. this is going to be difficult to meaningfully review."
}
] |
[
{
"body": "<p>Nice code.</p>\n<h3 id=\"in-python-for-has-else-clause-aci5\">In Python, <code>for</code> has <code>else</code> clause</h3>\n<p>And I think it fits here perfectly. In</p>\n<pre><code>for retry in range(3):\n if ...:\n break\nelse:\n #else-part\n</code></pre>\n<p>the <code>else-part</code> will be executed if there was no break. So:</p>\n<pre><code> for retry in range(0, 3):\n if dump_snapshot(mongo, database, collection, str(metadata_id), folder_path, dry_run):\n logging.info("Successfully exported snapshot %s to json file.", str(metadata_id))\n else:\n logging.info("Failed to export snapshot %s to json file. Retry no %s", str(metadata_id), retry)\n break\n else:\n logging.error("Snapshot archiving flow failed for %s. Failed to export to json file. ", str(metadata_id))\n continue\n</code></pre>\n<p>The code gets rid of <code>flow_status</code> and extra checks.</p>\n<p>Other options are to make a class hierarchy for actions and use exception instead of continue (very short code in the loop and very long outside) or to make a retry function with lambda for the action and all log messages in arguments. The first is long, the second has somewhat bad readability, like:</p>\n<pre><code>retry(3,\n lambda: dump_snapshot(mongo, database, collection, str(metadata_id), folder_path, dry_run),\n "Successfully exported snapshot {} to json file.".format(str(metadata_id)),\n "Failed to export snapshot {} to json file. Retry no %d".format(str(metadata_id)),\n "Snapshot archiving flow failed for {}. Failed to export to json file. ".format(str(metadata_id)) )\n\ndef retry(count, f, success, fail_attempt, fail):\n for attempt in range(count):\n if f():\n logging.info(success)\n return\n else:\n logging.info(fail_attempt, retry)\n raise RetryFailedExeption(fail)\n</code></pre>\n<p>Well, it's not too bad after all. But it needs a default value for count and keywords for log messages, to make the call like this:</p>\n<pre><code>retry(lambda: dump_snapshot(mongo, database, collection, str(metadata_id), folder_path, dry_run),\n #count = 3 - skipped\n success = "Successfully exported snapshot {} to json file.".format(str(metadata_id)),\n fail = "Failed to export snapshot {} to json file. Retry no %d".format(str(metadata_id)),\n failure = "Snapshot archiving flow failed for {}. Failed to export to json file. ".format(str(metadata_id)) )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T13:58:46.437",
"Id": "264448",
"ParentId": "264445",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264448",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T13:22:53.313",
"Id": "264445",
"Score": "1",
"Tags": [
"python",
"error-handling",
"mongodb",
"amazon-web-services"
],
"Title": "Archiving MongoDB data to S3, with retryable steps"
}
|
264445
|
<p>In general my page is slow and has several points in the code that I believe can be improved, even in relation to the structure used. Anyway, the biggest problem is:</p>
<p>The page I'm creating is very simple. The problem is that I created the entire first section - i.e. <code><div class="column ..."></code> but then I had to use the famous <code>Ctrl + C</code> and <code>Ctrl + V</code> to create the other <code><div class="column ..."></code> because I don't know how to group scripts - this is making page load slower.</p>
<p>The <code><select></code> elements for example is created from script's. They told me that there is a way to make the 4 scripts (one in each <code><div class="column ..."></code>) become one using looping, decreasing the loading the page, but I don't know how to make this improvement.</p>
<p>I was also told about the risk of using so many equal headers, as I use the <code><script src="https://d3js.org/d3.v4.js"></script></code> four times but how I need it for the 4 scripts, I don't know how I could place it only once unless I merge the 4 scripts into one.</p>
<p><em><strong>References for code citations:</strong></em></p>
<p>Scripts to <code><select></code> creation:</p>
<pre><code><script id="script-da-caixa-de-selecao-suspensa-1">
<script id="script-da-caixa-de-selecao-suspensa-2">
<script id="script-da-caixa-de-selecao-suspensa-3">
<script id="script-da-caixa-de-selecao-suspensa-4">
</code></pre>
<p>Example of the <code>.csv</code> file (<code>"Lista_de_Jogos.csv"</code>) that is used to create dropdown selection boxes:</p>
<pre><code>label,value
,
Oriente Petrolero v Aurora,http://sports.williamhill.com/bet/pt/betting/e/21185256/Oriente+Petrolero+v+Aurora.html
Pereira v Alianza Petrolera,http://sports.williamhill.com/bet/pt/betting/e/21150687/Pereira+v+Alianza+Petrolera.html
Tijuana (Women) v Toluca (Women),http://sports.williamhill.com/bet/pt/betting/e/21193317/Tijuana+%28Women%29+v+Toluca+%28Women%29.html
Cruz Azul v Mazatlan,http://sports.williamhill.com/bet/pt/betting/e/21090457/Cruz+Azul+v+Mazatlan.html
</code></pre>
<p>Screenshot to drop down box created by <code><script></code>:</p>
<p><a href="https://i.stack.imgur.com/tzmh1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tzmh1.png" alt="screenshot of drop-down boxes" /></a></p>
<p><em><strong>There are other improvements that can be made to shorten the code and speed up the page, but my knowledge is still very small and I need help both to learn and produce results. Thank you in advance for your attention and help!</strong></em></p>
<p>My Code:</p>
<pre><code><html>
<head>
<style>
{
box-sizing: border-box;
}
.column {
text-align:center;
float: left;
width: 355;
border: 1px solid white;
border-collapse: collapse;
}
.row:after {
content: "";
display: table;
clear: both;
}
.button {
background-color: #33ccff;
color: black;
font-weight: bold;
}
body {
overflow: hidden;
}
</style>
<script id="auto-update-images">
let interval_images
window.addEventListener('DOMContentLoaded', () => {
interval_images = setInterval(refresh_images, 500); // refresh every 0.5 secs
})
function refresh_images() {
if (!document.images) return;
document.images['grafico-betfair-1'].src = document.getElementById('barra-de-texto-para-grafico-1').value;
document.images['grafico-betfair-2'].src = document.getElementById('barra-de-texto-para-grafico-2').value;
document.images['grafico-betfair-3'].src = document.getElementById('barra-de-texto-para-grafico-3').value;
document.images['grafico-betfair-4'].src = document.getElementById('barra-de-texto-para-grafico-4').value;
}
</script>
<script id="auto-update-csv">
let interval_csv
window.addEventListener('DOMContentLoaded', () => {
interval_csv = setInterval(refresh_csv, 60000); // refresh every 60 secs
})
function refresh_csv() {
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_1(data)});
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_2(data)});
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_3(data)});
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_4(data)});
}
</script>
</head>
<body style="background-color:black;">
<div class="row">
<div class="column left">
<form action="" method="post" id="formulario-radar-1">
<div id="caixa-suspensa-1">
<button class="button" id="botao-do-radar-1" onclick="funcao_radar_1()">Radar 1</button>
<input type="text" id="barra-de-texto-para-radar-1" style="width: 283px;">
</div>
</form>
<iframe id="iframe-do-radar-1" width="100%" height="282" frameBorder="0" src="">
</iframe>
<script src="https://d3js.org/d3.v4.js"></script>
<script id="script-da-caixa-de-selecao-suspensa-1">
var select_1 = d3.select("#caixa-suspensa-1")
.append("select")
.attr("id","select-box-1")
.style("width","100%");
function caixa_suspensa_1(data) {
select_1
.on("change", function(d) {
var value_1 = d3.select(this).property("value");
document.querySelector('#barra-de-texto-para-radar-1').value = value_1;
document.getElementById('botao-do-radar-1').click();
});
let update_1 = select_1.selectAll("option")
.data(data);
update_1.exit().remove();
update_1.enter().append("option").merge(update_1)
.attr("value", function (d) { return d.value; })
.text(function (d) { return d.label; });
}
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_1(data)});
</script>
<script id="script-para-ativar-iframe-1">
function funcao_radar_1() {
"use strict";
var url_setter = document.getElementById('formulario-radar-1'), url = document.getElementById('barra-de-texto-para-radar-1'), the_iframe = document.getElementById('iframe-do-radar-1');
url_setter.onsubmit = function (event) {
try {
let link = document.getElementById("barra-de-texto-para-radar-1").value;
let valor_da_barra_de_texto_1 = link.split("OB_EV")[1];
valor_da_barra_de_texto_1 = valor_da_barra_de_texto_1.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_1;
} catch (e) {
try {
let link = document.getElementById("barra-de-texto-para-radar-1").value;
let valor_da_barra_de_texto_1 = link.split("betting/e/")[1];
valor_da_barra_de_texto_1 = valor_da_barra_de_texto_1.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_1;
} catch (e) {
event.preventDefault();
the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
}
}
};
}
</script>
<form action="" method="post" id="formulario-grafico-1">
<div>
<input type="text" id="barra-de-texto-para-grafico-1" style="width: 100%;">
</div>
</form>
<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-1">
<form action="" method="post" id="formulario-para-limpar-texto-1">
<div>
<button class="button" style="width: 100%;" id="botao-de-limpar-texto-1" onclick="limpar_texto_1()">Limpar Tudo <br/>1</button>
</div>
</form>
<script id="script-para-limpar-dados-1">
function limpar_texto_1() {
var btn = document.getElementById('formulario-para-limpar-texto-1');
btn.onclick = function(e){
e.preventDefault();
document.getElementById('barra-de-texto-para-grafico-1').value="";
document.getElementById('barra-de-texto-para-radar-1').value="";
document.getElementById('botao-do-radar-1').click();
document.getElementById("select-box-1").selectedIndex = "0";
};
}
</script>
</div>
<div class="column middle1">
<form action="" method="post" id="formulario-radar-2">
<div id="caixa-suspensa-2">
<button class="button" id="botao-do-radar-2" onclick="funcao_radar_2()">Radar 2</button>
<input type="text" id="barra-de-texto-para-radar-2" style="width: 283px;">
</div>
</form>
<iframe id="iframe-do-radar-2" width="100%" height="282" frameBorder="0" src="">
</iframe>
<script src="https://d3js.org/d3.v4.js"></script>
<script id="script-da-caixa-de-selecao-suspensa-2">
var select_2 = d3.select("#caixa-suspensa-2")
.append("select")
.attr("id","select-box-2")
.style("width","100%");
function caixa_suspensa_2(data) {
select_2
.on("change", function(d) {
var value_2 = d3.select(this).property("value");
document.querySelector('#barra-de-texto-para-radar-2').value = value_2;
document.getElementById('botao-do-radar-2').click();
});
let update_2 = select_2.selectAll("option")
.data(data);
update_2.exit().remove();
update_2.enter().append("option").merge(update_2)
.attr("value", function (d) { return d.value; })
.text(function (d) { return d.label; });
}
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_2(data)});
</script>
<script id="script-para-ativar-iframe-2">
function funcao_radar_2() {
"use strict";
var url_setter = document.getElementById('formulario-radar-2'), url = document.getElementById('barra-de-texto-para-radar-2'), the_iframe = document.getElementById('iframe-do-radar-2');
url_setter.onsubmit = function (event) {
try {
let link = document.getElementById("barra-de-texto-para-radar-2").value;
let valor_da_barra_de_texto_2 = link.split("OB_EV")[1];
valor_da_barra_de_texto_2 = valor_da_barra_de_texto_2.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_2;
} catch (e) {
try {
let link = document.getElementById("barra-de-texto-para-radar-2").value;
let valor_da_barra_de_texto_2 = link.split("betting/e/")[1];
valor_da_barra_de_texto_2 = valor_da_barra_de_texto_2.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_2;
} catch (e) {
event.preventDefault();
the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
}
}
};
}
</script>
<form action="" method="post" id="formulario-grafico-2">
<div>
<input type="text" id="barra-de-texto-para-grafico-2" style="width: 100%;">
</div>
</form>
<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-2">
<form action="" method="post" id="formulario-para-limpar-texto-2">
<div>
<button class="button" style="width: 100%;" id="botao-de-limpar-texto-2" onclick="limpar_texto_2()">Limpar Tudo <br/>2</button>
</div>
</form>
<script id="script-para-limpar-dados-2">
function limpar_texto_2() {
var btn = document.getElementById('formulario-para-limpar-texto-2');
btn.onclick = function(e){
e.preventDefault();
document.getElementById('barra-de-texto-para-grafico-2').value="";
document.getElementById('barra-de-texto-para-radar-2').value="";
document.getElementById('botao-do-radar-2').click();
document.getElementById("select-box-2").selectedIndex = "0";
};
}
</script>
</div>
<div class="column middle2">
<form action="" method="post" id="formulario-radar-3">
<div id="caixa-suspensa-3">
<button class="button" id="botao-do-radar-3" onclick="funcao_radar_3()">Radar 3</button>
<input type="text" id="barra-de-texto-para-radar-3" style="width: 283px;">
</div>
</form>
<iframe id="iframe-do-radar-3" width="100%" height="282" frameBorder="0" src="">
</iframe>
<script src="https://d3js.org/d3.v4.js"></script>
<script id="script-da-caixa-de-selecao-suspensa-3">
var select_3 = d3.select("#caixa-suspensa-3")
.append("select")
.attr("id","select-box-3")
.style("width","100%");
function caixa_suspensa_3(data) {
select_3
.on("change", function(d) {
var value_3 = d3.select(this).property("value");
document.querySelector('#barra-de-texto-para-radar-3').value = value_3;
document.getElementById('botao-do-radar-3').click();
});
let update_3 = select_3.selectAll("option")
.data(data);
update_3.exit().remove();
update_3.enter().append("option").merge(update_3)
.attr("value", function (d) { return d.value; })
.text(function (d) { return d.label; });
}
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_3(data)});
</script>
<script id="script-para-ativar-iframe-3">
function funcao_radar_3() {
"use strict";
var url_setter = document.getElementById('formulario-radar-3'), url = document.getElementById('barra-de-texto-para-radar-3'), the_iframe = document.getElementById('iframe-do-radar-3');
url_setter.onsubmit = function (event) {
try {
let link = document.getElementById("barra-de-texto-para-radar-3").value;
let valor_da_barra_de_texto_3 = link.split("OB_EV")[1];
valor_da_barra_de_texto_3 = valor_da_barra_de_texto_3.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_3;
} catch (e) {
try {
let link = document.getElementById("barra-de-texto-para-radar-3").value;
let valor_da_barra_de_texto_3 = link.split("betting/e/")[1];
valor_da_barra_de_texto_3 = valor_da_barra_de_texto_3.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_3;
} catch (e) {
event.preventDefault();
the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
}
}
};
}
</script>
<form action="" method="post" id="formulario-grafico-3">
<div>
<input type="text" id="barra-de-texto-para-grafico-3" style="width: 100%;">
</div>
</form>
<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-3">
<form action="" method="post" id="formulario-para-limpar-texto-3">
<div>
<button class="button" style="width: 100%;" id="botao-de-limpar-texto-3" onclick="limpar_texto_3()">Limpar Tudo <br/>3</button>
</div>
</form>
<script id="script-para-limpar-dados-3">
function limpar_texto_3() {
var btn = document.getElementById('formulario-para-limpar-texto-3');
btn.onclick = function(e){
e.preventDefault();
document.getElementById('barra-de-texto-para-grafico-3').value="";
document.getElementById('barra-de-texto-para-radar-3').value="";
document.getElementById('botao-do-radar-3').click();
document.getElementById("select-box-3").selectedIndex = "0";
};
}
</script>
</div>
<div class="column right">
<form action="" method="post" id="formulario-radar-4">
<div id="caixa-suspensa-4">
<button class="button" id="botao-do-radar-4" onclick="funcao_radar_4()">Radar 4</button>
<input type="text" id="barra-de-texto-para-radar-4" style="width: 283px;">
</div>
</form>
<iframe id="iframe-do-radar-4" width="100%" height="282" frameBorder="0" src="">
</iframe>
<script src="https://d3js.org/d3.v4.js"></script>
<script id="script-da-caixa-de-selecao-suspensa-4">
var select_4 = d3.select("#caixa-suspensa-4")
.append("select")
.attr("id","select-box-4")
.style("width","100%");
function caixa_suspensa_4(data) {
select_4
.on("change", function(d) {
var value_4 = d3.select(this).property("value");
document.querySelector('#barra-de-texto-para-radar-4').value = value_4;
document.getElementById('botao-do-radar-4').click();
});
let update_4 = select_4.selectAll("option")
.data(data);
update_4.exit().remove();
update_4.enter().append("option").merge(update_4)
.attr("value", function (d) { return d.value; })
.text(function (d) { return d.label; });
}
d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_4(data)});
</script>
<script id="script-para-ativar-iframe-4">
function funcao_radar_4() {
"use strict";
var url_setter = document.getElementById('formulario-radar-4'), url = document.getElementById('barra-de-texto-para-radar-4'), the_iframe = document.getElementById('iframe-do-radar-4');
url_setter.onsubmit = function (event) {
try {
let link = document.getElementById("barra-de-texto-para-radar-4").value;
let valor_da_barra_de_texto_4 = link.split("OB_EV")[1];
valor_da_barra_de_texto_4 = valor_da_barra_de_texto_4.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_4;
} catch (e) {
try {
let link = document.getElementById("barra-de-texto-para-radar-4").value;
let valor_da_barra_de_texto_4 = link.split("betting/e/")[1];
valor_da_barra_de_texto_4 = valor_da_barra_de_texto_4.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_4;
} catch (e) {
event.preventDefault();
the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
}
}
};
}
</script>
<form action="" method="post" id="formulario-grafico-4">
<div>
<input type="text" id="barra-de-texto-para-grafico-4" style="width: 100%;">
</div>
</form>
<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-4">
<form action="" method="post" id="formulario-para-limpar-texto-4">
<div>
<button class="button" style="width: 100%;" id="botao-de-limpar-texto-4" onclick="limpar_texto_4()">Limpar Tudo <br/>4</button>
</div>
</form>
<script id="script-para-limpar-dados-4">
function limpar_texto_4() {
var btn = document.getElementById('formulario-para-limpar-texto-4');
btn.onclick = function(e){
e.preventDefault();
document.getElementById('barra-de-texto-para-grafico-4').value="";
document.getElementById('barra-de-texto-para-radar-4').value="";
document.getElementById('botao-do-radar-4').click();
document.getElementById("select-box-4").selectedIndex = "0";
};
}
</script>
</div>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:10:08.453",
"Id": "524721",
"Score": "0",
"body": "By “_In general my page is slow_” in which ways is it slow? Slow to load all of the HTML, slow in having the JS operate? Slow to modify the code because of how large it is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:24:13.693",
"Id": "524722",
"Score": "0",
"body": "Hi @SᴀᴍOnᴇᴌᴀ good Morning. The page itself loads quickly, I meant that the script is very long because there is a lot that I used copy and paste, for example, there are 4 columns that are totally the same, scripts that import the same data and do pretty much the same thing, and already me they warned that there is a way to summarize a lot, but I don't know how to proceed, so I believe there are ways to unite a lot that I believe can take away so much repetition, making it too big, ugly and complicated to update any details that I need to update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:26:00.700",
"Id": "524723",
"Score": "0",
"body": "I apologize for my English, it's pretty flawed! Any questions you can ask, I', here to answer."
}
] |
[
{
"body": "<h2>Copy-Pasted code</h2>\n<p>As you disclosed, the code has a lot of code that is copied and pasted. This violates the <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle </a>.</p>\n<blockquote>\n<p>I was also told about the risk of using so many equal headers, as I use the <code><script src="https://d3js.org/d3.v4.js"></script></code> four times but how I need it for the 4 scripts, I don't know how I could place it only once unless I merge the 4 scripts into one.</p>\n</blockquote>\n<blockquote>\n<pre><code><script src="https://d3js.org/d3.v4.js"></script>\n</code></pre>\n</blockquote>\n<p>This does not need to appear more than once, since the browser will only load it once. Just have it once and the browser will load it. It could be moved to the <code><head></code> tag instead of the <code><body></code>.</p>\n<p>And all of the contents of the <code><script></code> tags - e.g. with id values <code>auto-update-images</code>, <code>auto-update-csv</code>, <code>script-da-caixa-de-selecao-suspensa-1</code>, etc. can be combined into a single element or moved to an external javascript file.</p>\n<h2>Abstracting common functionality</h2>\n<p>Loops can really help with repeated code - for example - these repeated lines in <code>refresh_images</code>:</p>\n<blockquote>\n<pre><code>document.images['grafico-betfair-1'].src = document.getElementById('barra-de-texto-para-grafico-1').value;\ndocument.images['grafico-betfair-2'].src = document.getElementById('barra-de-texto-para-grafico-2').value;\ndocument.images['grafico-betfair-3'].src = document.getElementById('barra-de-texto-para-grafico-3').value;\ndocument.images['grafico-betfair-4'].src = document.getElementById('barra-de-texto-para-grafico-4').value;\n</code></pre>\n</blockquote>\n<p>Can be simplified with a loop:</p>\n<pre><code>for (let i = 1; i < 5; i++) {\n document.images['grafico-betfair-' + i].src = document.getElementById('barra-de-texto-para-grafico-' + i).value;\n } \n</code></pre>\n<p>After considering what that function does it looks like it is constantly looking for changes to the <code><input></code> elements - like here:</p>\n<pre><code><form action="" method="post" id="formulario-grafico-2">\n <div>\n <input type="text" id="barra-de-texto-para-grafico-2" style="width: 100%;">\n </div>\n</form>\n<img src="https://sited...1e839c" name="grafico-betfair-2">\n \n</code></pre>\n<p>Instead of having to constant check those values, a class name could be applied to the <code><form></code> element - e.g.</p>\n<pre><code><form action="" method="post" class="imageSrcInputForm">\n</code></pre>\n<p>Then in the Javascript look for those elements:</p>\n<pre><code>const imageSrcInputForms = document.getElementsByClassName('imageSrcInputForm');\n[...imageSrcInputForms].forEach(form => {\n form.querySelector('img').addEventListener('change', event => {\n form.nextElementSibling.src = event.target.value;\n });\n}];\n</code></pre>\n<p>There may not even really be a need to have a <code><form></code> just to wrap the <code><input></code> element.</p>\n<p>You may be able to eliminate the redundancy on the repeated functions -e.g. <code>funcao_radar_1</code>, <code>funcao_radar_2</code>... using loop over elements with class names. And instead of traversing the DOM tree to find elements there could be associations with elements using <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\">data attributes</a>.</p>\n<h2>Simplifying one line functions</h2>\n<p>The d3 selector lines have lines like this:</p>\n<blockquote>\n<pre><code>.attr("value", function (d) { return d.value; })\n.text(function (d) { return d.label; });\n</code></pre>\n</blockquote>\n<p>Just as the event listeners for the DOM-content loaded event use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a>, those lines can be simplified as well:</p>\n<pre><code>.attr("value", d => d.value)\n.text(d => d.label);\n</code></pre>\n<h2>CSS- units</h2>\n<p>The ruleset for <code>.column</code> contains <code>width: 355;</code> The default unit is pixels - i.e. <code>px</code> but it should be declared for clarity. Apparently <a href=\"https://stackoverflow.com/q/45636797/1575353\">~4 years ago</a> popular browsers treated this as invalid<sup><a href=\"https://stackoverflow.com/q/45636797/1575353\">1</a></sup> however in FF and Chrome today I see it treated as 355 pixels.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T17:11:53.010",
"Id": "524733",
"Score": "1",
"body": "Hi Sam, Vast content for my learning, thank you very much! If I have any questions regarding the nominations, can I ask you as an additional?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T17:09:00.403",
"Id": "265669",
"ParentId": "264446",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265669",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T13:27:35.750",
"Id": "264446",
"Score": "1",
"Tags": [
"javascript",
"html",
"ecmascript-6",
"event-handling",
"d3.js"
],
"Title": "list of games to open radar match in iframe on for drop-down controls"
}
|
264446
|
<p>I'm trying to write something like an adjusted run-length encoding for row-wise bit matrices. Specifically I want to "collapse" runs of 1s into the number of 1s in that run while maintaining the same number of 0s as original (right-padding as necessary). For example:</p>
<pre><code>input_v = np.array([
[0, 1, 0, 0, 1, 1, 0, 1],
[0, 0, 1, 0, 1, 1, 1, 0]
])
expected_v = np.array([
[0, 1, 0, 0, 2, 0, 1],
[0, 0, 1, 0, 3, 0, 0]
])
</code></pre>
<p>My current attempt works after padding, but is slow:</p>
<pre class="lang-py prettyprint-override"><code>def count_neighboring_ones(l):
o = 0
for i in l:
if i == 0:
return o
o += 1
def f(l):
out = []
i = 0
while i < len(l):
c = count_neighboring_ones(l[i:])
out.append(c)
i += (c or 1)
return out
</code></pre>
<p>Are there some vectorization techniques I can use to operate on the entire matrix to reduce row-wise operations and post-padding?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T18:54:55.590",
"Id": "522300",
"Score": "0",
"body": "Why are you doing this? What are the dimensions of typical data you hope to compress in this way? Can you not just use Numpy's built-in sparse matrix support?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:13:23.923",
"Id": "522302",
"Score": "0",
"body": "I'm doing this because I need to pass the result to library code I don't control. It's normally small dims but it happens many times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:14:32.593",
"Id": "522303",
"Score": "0",
"body": "What is the library you're passing to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:15:31.890",
"Id": "522304",
"Score": "0",
"body": "I don't think it matters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:17:42.703",
"Id": "522305",
"Score": "0",
"body": "I think it does, if you want a review. But hey, it's your life"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:18:28.970",
"Id": "522306",
"Score": "0",
"body": "I'm specifically asking about how to vectorize _this_ code, not code outside the scope. It's an MVCE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:18:54.650",
"Id": "522307",
"Score": "0",
"body": "MVCEs are for StackOverflow, not Code Review. Code Review explicitly requires full context."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T16:30:25.723",
"Id": "264451",
"Score": "0",
"Tags": [
"python",
"numpy",
"matrix"
],
"Title": "Vectorized code to find the position and length of runs of 1s in a bit matrix"
}
|
264451
|
<p>Code is meant to be used in Windows .NET (tested with dotnet5.0) to dynamically load C library and return delegate of given function</p>
<p>Code lower is result of my attempt to rewrite the <code>[DllImport]</code> annotations based header file, that was provided by 3rd party along with the DLL library itself, when multiple instances of given DLL must be used in parallel, which is impossible with DllImport</p>
<p>Given the nature of the library, the solution was required to work only on Windows, but could be extended to support multiple platforms (loading platform-specific library, eg. .dylib / .so / .dll)</p>
<p><strong>FunctionLoader.cs</strong></p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.InteropServices;
/// <summary>
/// Helper function to dynamically load DLL contained functions on Windows only
/// </summary>
class FunctionLoader
{
[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr LoadLibrary(string path);
[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
/// <summary>
/// Map String (library name) to IntPtr (reference from LoadLibrary)
/// </summary>
private static ConcurrentDictionary<String, IntPtr> LoadedLibraries { get; } = new ConcurrentDictionary<string, IntPtr>();
/// <summary>
/// Load function (by name) from DLL (by name) and return its delegate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dllPath"></param>
/// <param name="functionName"></param>
/// <returns></returns>
public static T LoadFunction<T>(string dllPath, string functionName)
{
// normalize
if (!Path.IsPathFullyQualified(dllPath))
{
dllPath = Path.GetFullPath(dllPath);
}
// Get preloaded or load the library on-demand
IntPtr hModule = LoadedLibraries.GetOrAdd(
dllPath,
valueFactory: (string dllPath) => {
IntPtr loaded = LoadLibrary(dllPath);
if (loaded == IntPtr.Zero) {
throw new DllNotFoundException(String.Format("Library not found in path {0}", dllPath));
}
return loaded;
}
);
// Load function
var functionAddress = GetProcAddress(hModule, functionName);
if (functionAddress == IntPtr.Zero)
{
throw new EntryPointNotFoundException(String.Format("Function {0} not found in {1}", functionName, dllPath));
}
// Return delegate, casting is hack-ish, but simplifies usage
return (T)(object)(Marshal.GetDelegateForFunctionPointer(functionAddress, typeof(T)));
}
}
</code></pre>
<p>Expected usage then follows this pattern</p>
<p><strong>Library.cs</strong></p>
<pre class="lang-csharp prettyprint-override"><code>public class Library {
// This is the only file that is needed in base distribution of the application, all other copies/instances will be created on-demand by Library constructor
public string DefaultLibrarySource { get; } = "DLL\\1\\ExternalLibrary.dll";
public string LibrarySourceTemplate { get; } = "DLL\\{0}\\ExternalLibrary.dll";
public delegate Int32 T_externalFunction(Int32 numArgument, out Int32 outNumArgument);
public T_externalFunction externalFunction;
public Library(int InstanceNo)
{
// reference correct DLL file per instance ID
var LibraryName = String.Format(LibrarySourceTemplate, InstanceNo);
// ensure the dir with library exists
var dirName = Path.GetDirectoryName(LibraryName);
if (!Directory.Exists(dirName))
{
Directory.CreateDirectory(dirName);
}
// ensure the library itself is in place
if (!File.Exists(LibraryName))
{
Console.WriteLine(String.Format("Copy {0} to {1}", DefaultLibrarySource, LibraryName));
File.Copy(DefaultLibrarySource, LibraryName);
}
// load each individual function that needs to be available later
externalFunction = FunctionLoader.LoadFunction<T_externalFunction>(LibraryName, "externalFunction");
}
}
</code></pre>
<p><strong>Program.cs</strong></p>
<pre class="lang-csharp prettyprint-override"><code>public class Program {
static void Main(string[] args)
{
// get instance number 2 of DLL
var lib = new Library(2);
// call DLL function obtain both return and out variables
var result = lib.externalFunction(12345, out Int32 outVar);
// ...
}
}
</code></pre>
<p>What I hope was achieved correctly:</p>
<ol>
<li>Avoid loading the DLL (LoadLibrary) or the function (GetProcAddress) multiple times, if caller requests the same DLL name or function name</li>
<li>Relative simplicity of use</li>
</ol>
<p>What bothers me currently with this code is</p>
<ol>
<li>To define the function interface (delegate) and accessible function the type (<code>T_externalFunction</code>) is currently defined separately from the function accessor (<code>externalFunction</code>), where with <code>DllImport</code> this could be done with single declaration</li>
<li>Each function must be loaded manually in <code>Library</code> object constructor (or on-access), which would be way better with some kind of Attribute and processor/hook, that would automatically do the binding</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T07:18:36.987",
"Id": "522337",
"Score": "0",
"body": "*Avoid loading the DLL or the function multiple times, if caller requests the same DLL name or function name* then why don't you use `ConcurrentDictionary` to avoid loading the same thing multiple times from different threads?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T10:03:29.727",
"Id": "522341",
"Score": "0",
"body": "@PeterCsala thank you, that's good point, should I do some kind of mutex/lock synchronization in LoadFunction or will the ConcurrentDictionary itself suffice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T12:08:25.190",
"Id": "522345",
"Score": "1",
"body": "[Please read the paragraph after the code sample](https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/how-to-add-and-remove-items)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T12:33:03.157",
"Id": "522348",
"Score": "1",
"body": "@PeterCsala thank you, i've updated the code in question with ConcurrentDictionary usage"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T12:45:03.253",
"Id": "522349",
"Score": "0",
"body": "I *think* that the dictionary is unnecessary: `LoadLibrary` *internally* maintains a cache of loaded libraries, your additional caching layer is therefore redundant. All it does is save one (cheap) P/Invoke call, at the cost of additional cross-thread synchronisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T13:21:19.957",
"Id": "522352",
"Score": "0",
"body": "@KonradRudolph could you please point out where the \"caching in LoadLibrary (kernel32.dll)\" is documented, as that would indeed simplify the solution a lot. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T14:14:14.717",
"Id": "522354",
"Score": "2",
"body": "@MarekSebera It’s implied [in the documentation](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya): “The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count.”; and, “If the specified module is a DLL that is not already loaded for the calling process, the system calls the DLL's DllMain function”."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T16:45:10.973",
"Id": "264452",
"Score": "1",
"Tags": [
"c#",
".net"
],
"Title": "Simplify LoadLibrary/GetProcAddress helper for dynamic parallel DLL instantiation"
}
|
264452
|
<p>I had this as a project last school year and decided to try and optimize it. I'm curious to see how much I have learned; is this a good way of doing it?</p>
<pre><code>import os
dict = {
# "empId": ["title", name]
"000001": ["ceo", "joe", "smith"],
"000002": ["co", "bob", "konn"],
"000003": ["lead designer", "koss", "klan"],
}
dict2 = {
}
def searchEmpId(empID):
key = empID
if key in dict:
print(" Name: {} {}\n Position: {}\n Employee ID: {}".format(dict[key][1], dict[key][2], dict[key][0], key))
print("\n")
input("Press enter to return to main menu")
menu()
def searchName(Name):
for x in range(1, len(dict)):
key = str("0"*(6-len(str(x)))) + str(x)
if Name in dict[key]:
print(" Name: {} {}\n Position: {}\n Employee ID: {}".format(dict[key][1], dict[key][2], dict[key][0], key))
print("\n")
input("Press enter to return to main menu")
menu()
def add(Position, First, Last):
dict.update({str(str("0"*(6-len(str(len(dict)+1)))) + str(len(dict)+1)): [Position, First, Last]})
print("\n")
input("Press enter to return to main menu")
menu()
def reset():
dict2.update(dict.copy())
dict.clear()
for x in range(0, len(dict2)):
res = list(dict2.keys())[0]
add(dict2[res][0], dict2[res][1], dict2[res][2])
dict2.pop(res)
def remove(empID):
dict.pop(empID)
reset()
print("\n")
input("Press enter to return to main menu")
menu()
def listDict():
os.system("clear")
for x in range(1, len(dict)+1):
key = list(dict.keys())[x-1]
print(" Name: {} {}\n Position: {}\n Employee ID: {} \n".format(dict[key][1], dict[key][2], dict[key][0], key))
input("Press enter to return to main menu")
menu()
def menu():
os.system("clear")
print("Welcome to the employee dictionary")
print('\n To search for an employee by id type "1" ')
print(' To search for an employee by name type "2" ')
print(' To add an employee type "3" ')
print(' To remove an employee type "4" ')
print(' To list the dictionary type "5" \n')
selection = input(">> ")
if selection == "1":
os.system("clear")
searchEmpId(str(input("Employee ID: ")))
if selection == "2":
os.system("clear")
searchName(str(input("First name or last name(but not both): ")))
if selection == "3":
os.system("clear")
add(str(input("Position: ")), str(input("First name: ")), str(input("Last Name: ")))
if selection == "4":
os.system("clear")
remove(str(input("Employee ID: ")))
if selection == "5":
listDict()
menu()
</code></pre>
|
[] |
[
{
"body": "<p>Starting with the last line:</p>\n<blockquote>\n<pre><code>menu()\n</code></pre>\n</blockquote>\n<p>Standard practice is to put this in a "main guard", so that the file is usable from other programs:</p>\n<pre><code>if __name__ == '__main__':\n menu()\n</code></pre>\n<hr />\n<p>This bit looks fragile:</p>\n<blockquote>\n<pre><code> key = str("0"*(6-len(str(x)))) + str(x)\n</code></pre>\n</blockquote>\n<p>There's an assumption there that all employee ids are 6 digits (and that's a convoluted way to format - much simpler would be <code>key = f'{x:06u}'</code>).</p>\n<hr />\n<p>Recursively calling <code>menu()</code> as the last action of each user function means that we constantly recurse into that function. Simply looping is more memory-efficient.</p>\n<hr />\n<blockquote>\n<pre><code> os.system("clear")\n</code></pre>\n</blockquote>\n<p>That's risky. We're using whatever <code>PATH</code> we inherited, which might not include a <code>clear</code> command - or worse, it might include one that does something completely unexpected.</p>\n<hr />\n<p>What's the <code>reset()</code> function for? It seems to replace <code>dict</code> with a copy of itself, but changing the employee numbers. I don't think that's something you would really want to do in a real organisation where they are used as identifiers in databases such as payroll, expenses, access tokens, etc. If it really is necessary, perhaps a better name might be <code>rekey()</code>? Even then it ought to have a comment explaining what it's for.</p>\n<hr />\n<blockquote>\n<pre><code>if selection == "1":\n ⋮\nif selection == "2":\n ⋮\nif selection == "3":\n ⋮\nif selection == "4":\n ⋮\nif selection == "5":\n ⋮\n</code></pre>\n</blockquote>\n<p>This kind of <code>switch</code>/<code>case</code> is normally represented in Python using an action dictionary. If you really want to use <code>if</code>, it's better to use <code>elif</code> to skip the conditions following the match.</p>\n<hr />\n<blockquote>\n<pre><code>for x in range(1, len(dict)+1):\n key = list(dict.keys())[x-1]\n</code></pre>\n</blockquote>\n<p>Why offset everything by 1? We could as easily write <code>for x in range(0, len(dict)</code> and then simply use <code>x</code> rather than <code>x-1</code>. But in any case <code>for x in range()</code> is a code smell; here we just want to iterate over all of <code>dict</code>'s elements:</p>\n<pre><code>for key,value in dict.items():\n print(f" Name: {value[1]} {value[2]}\\n Position: {value[0]}\\n Employee ID: {key} \\n")\n</code></pre>\n<hr />\n<p>This is a partial review; I ran out of time here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:57:09.240",
"Id": "522319",
"Score": "1",
"body": "\"Recursively calling menu() as the last action of each user function means that we constantly recurse into that function.\" I killed one of my first projects by using recursion when I should have used loops. I'd recommend you, Histic, to really listen to this one so you don't make the same mistake I did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T21:15:32.653",
"Id": "522321",
"Score": "0",
"body": "the reset is for when you remove someone the number are still all in order to instead of 000001 000003 and such but if the real world i suppose you wouldn't do that but just did that for this ill take into account useing a loop instead that actually makes more sense now that you said that and the key part ive nerver seen that so thanks and i was using clear as on linux its just the terminal clear command and dont know a better solution then just printing \"\\n\" a hundred times which seems like a worse idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T05:58:34.523",
"Id": "522334",
"Score": "0",
"body": "Really, for platform-independent and terminal-independent screen handling, you'll want to be using Python's [`curses`](https://docs.python.org/3/howto/curses.html) module. Clearing the screen is then done using [`curses.window.clear()`](https://docs.python.org/3/library/curses.html#curses.window.clear)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T06:49:56.827",
"Id": "522335",
"Score": "0",
"body": "Ah, the `reset()` method does _renumbering_ - perhaps that suggests a better name for the function? It does seem an odd thing to do, as the employee number is (in database terms) the primary key, so changing it would break every employee reference in the company (e.g. payroll, access tokens, .... - it's a long list!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:30:32.040",
"Id": "522368",
"Score": "0",
"body": "yea i had just did it as to see if i can but yeah it wouldnt be done in the real world"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:50:18.020",
"Id": "264458",
"ParentId": "264454",
"Score": "5"
}
},
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby Speight</a> on recursion, id and <code>reset</code> issues, but also I should mention:</p>\n<h3 id=\"name-consistency-39st\">Name consistency</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends snake_lower_case for variable and function names. Of course, you can use something else, like lowerCamelCase for variables and functions and UpperCamelCase for arguments; but don't mix styles, you're puzzling the reader - and yourself in a first place. <code>Position</code> and <code>empID</code> shouldn't be used together.</p>\n<h3 id=\"os.systemclear-is-bad-3ofx\"><code>os.system("clear")</code> is bad</h3>\n<p>First, it works only on some OSes (in Windows it should be <code>os.system("cls")</code>). Second, it has a security flaw mentioned by <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby Speight</a>. Third, it uses some very complex OS mechanics - more complex than all other code here. My advice: if you want to make a beautiful cross-platform application, you should use GUI; if you want to make it console, use <code>curses</code>; and if you're only learning - just accept that it would be a bit ugly and add two new lines instead of <code>os.system("clear")</code>.</p>\n<h3 id=\"group-same-code-together-and-get-rid-of-it-ny0g\">Group same code together (and get rid of it)</h3>\n<p>All selections call <code>os.system("clear")</code> before actual work, mostly on <code>menu()</code>, but <code>listDict</code> has it inside; all of them prompt <code>input("Press enter to return to main menu")</code> after work. You can call <code>os.system("clear")</code> once before <code>if</code>s and, after you get read of recursion, prompt for <code>enter</code> once after <code>if</code>s.</p>\n<h3 id=\"dict-is-a-built-in-name-gw9e\"><code>dict</code> is a built-in name</h3>\n<p>Don't redefine built-ins if you aren't sure what are you doing. Rename <code>dict</code> into something else - like <code>employees</code>.</p>\n<h3 id=\"dict2-is-used-only-in-one-function-b39b\"><code>dict2</code> is used only in one function</h3>\n<p>Declare it inside that function as a local variable, don't clog the global namespace.</p>\n<h3 id=\"use-proper-collections-kwse\">Use proper collections</h3>\n<p><code>list</code> is intended to keep many values, processed in a uniform way. A group of several values of different meaning should be kept in a <code>tuple</code> with <code>namedtuple</code>, <code>object</code> and even <code>dict</code> for more advanced ways to store data like that. I don't see anything like</p>\n<pre><code>for s in dict[0]:\n process(s)\n</code></pre>\n<p>in the code, but you're addressing different parts of employee data in different manner. It should be a <code>tuple</code>:</p>\n<pre><code>dict = {\n "000001": ("ceo", "joe", "smith") ...\n</code></pre>\n<h3 id=\"make-use-of-loops-over-collections-and-destructuring-un0l\">Make use of loops over collections and destructuring</h3>\n<p>Check out this way of listing all employees (assuming using <code>tuples</code> and renaming <code>dict</code>):</p>\n<pre><code>for id, (position, first, last) in employees.items():\n print(" Name: {} {}\\n Position: {}\\n Employee ID: {} \\n".format(first, last, position, id))\n</code></pre>\n<p>or with f-strings:</p>\n<pre><code>for id, (position, first, last) in employees.items():\n print(f" Name: {first} {last}\\n Position: {position}\\n Employee ID: {id}\\n")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T08:49:24.563",
"Id": "522340",
"Score": "0",
"body": "Good continuation of my answer - thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T17:13:05.717",
"Id": "522370",
"Score": "0",
"body": "for this part of your response ```for id, (position, first, last) in employees.items():\n print(\" Name: {first} {last}\\n Position: {position}\\n Employee ID: {id}\\n\")``` im confused what id is suppose to equal cause it just prints out {first} instead of the name also whats wrong with position and empID or is it just because of imporper naming"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T17:42:07.547",
"Id": "522372",
"Score": "0",
"body": "also im not sure about do gui or curses but if i were to go with gui what do you recomend"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:02:31.897",
"Id": "522378",
"Score": "0",
"body": "dict.items() returns tuples of (key, value). RTM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:03:20.173",
"Id": "522379",
"Score": "0",
"body": "My recommendation is not to go for beauty while learning basics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:29:36.593",
"Id": "522381",
"Score": "0",
"body": "i understand that dict.items returns a tuple didnt know why it printed {first} instead of the name like .format does as it prints the name like im assuming {first} should"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T05:12:40.217",
"Id": "524399",
"Score": "0",
"body": "Sorry, my fault. Fixed."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T08:44:06.220",
"Id": "264466",
"ParentId": "264454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:03:07.137",
"Id": "264454",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Employee directory"
}
|
264454
|
<p>I've built a very simple personal website, everything is in a single file because it is very straightforward, but I think the JS script could be better structured. All it does is fetch some repos from the GitHub API and displays them in a horrible format.</p>
<p>This is it (index.html):</p>
<pre class="lang-js prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="The successful warrior is the average man, with laser-like focus."
/>
<title>Mauricio Robayo</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap"
rel="stylesheet"
/>
<style>
:root {
font-size: 14px;
}
* {
margin: 0;
color: gainsboro;
}
body {
font-family: "IBM Plex Mono", monospace;
background-color: darkblue;
padding: 0.5rem;
}
h1,
h2,
h4 {
font-size: 1rem;
}
h1 {
margin-bottom: 2rem;
}
h2 {
font-weight: 400;
}
h4 {
margin-top: 1rem;
}
ul {
list-style: none;
list-style-position: inside;
padding-left: 0rem;
}
.error,
.error a {
color: red;
}
section {
margin: 2rem 0;
}
.repo-loader {
margin-right: 0.5rem;
}
.meta {
color: darkgray;
}
.repo-header > *:not(:last-child) {
margin-right: 1rem;
}
@media screen and (min-width: 768px) {
:root {
font-size: 16px;
}
body {
padding: 1rem;
}
.repo-header {
display: flex;
align-items: flex-end;
}
}
</style>
</head>
<body>
<h1>Mauricio Robayo</h1>
<ul>
<li>
<a
href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;"
>&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a
>
</li>
<li>
<a href="https://www.linkedin.com/in/mauriciorobayo"
>https://www.linkedin.com/in/mauriciorobayo</a
>
</li>
</ul>
<section id="recent-projects"></section>
<section id="starred-projects"></section>
<footer>
<p>No frameworks were harmed in the making of this site.</p>
<p>Analytics and bloatware free.</p>
<p>
Updated:
<a href="https://youtu.be/dQw4w9WgXcQ?autoplay=1">27 July 1987</a>.
</p>
</footer>
<script>
loadProjects(document.getElementById("recent-projects"), "updated", 3, [
"language",
"updated_at",
]);
loadProjects(document.getElementById("starred-projects"), "stars", 3, [
"language",
"stargazers_count",
]);
function loadProjects(projectsContainer, sort, limit, meta) {
const url = `https://api.github.com/search/repositories?q=user:MauricioRobayo&sort=${sort}&per_page=${limit}`;
const projectsTitle = document.createElement("h2");
const projectsBody = document.createElement("div");
const loader = document.createElement("span");
const link = document.createElement("a");
const cacheStatus = document.createElement("p");
const cacheExpirationTime = document.createElement("p");
const cacheKey = `projects-${sort}`;
projectsBody.classList.add("projects-body");
loader.classList.add("repo-loader");
link.href = url;
link.textContent = url;
const loaderSymbols = ["\\", "|", "/", "—"];
let i = 0;
loader.textContent = loaderSymbols[i % loaderSymbols.length];
const interval = setInterval(() => {
i++;
loader.textContent = loaderSymbols[i % loaderSymbols.length];
}, 500);
const cache = JSON.parse(localStorage.getItem(cacheKey));
projectsTitle.append(
loader,
"Fetching ",
link,
cacheStatus,
cacheExpirationTime
);
projectsContainer.append(projectsTitle, projectsBody);
if (cache?.expirationTime > Date.now()) {
cacheStatus.textContent = "localStorage cache hit";
cacheExpirationTime.textContent = `Expires: ${cache.expirationTime}`;
loadContent({ repos: cache.repos, projectsBody, loader, meta });
clearInterval(interval);
} else {
cacheStatus.textContent = "localStorage cache miss";
fetch(url, {
headers: {
accept: "application/vnd.github.v3+json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error(
`${response.status ? response.status : ""} ${
response.statusText ? response.statusText : ""
}`
);
}
const rateLimitElements = Array.from(response.headers)
.filter(([key]) => key.toLowerCase().startsWith("x-ratelimit"))
.map((header) => {
const headerElement = document.createElement("p");
headerElement.textContent = header.join(": ");
return headerElement;
});
projectsBody.append(...rateLimitElements);
return response.json();
})
.then(({ items: repos }) => {
localStorage.setItem(
cacheKey,
JSON.stringify({
repos,
expirationTime: Date.now() + 60 * 60 * 1000,
})
);
loadContent({ repos, projectsBody, loader, meta });
})
.catch((err) => {
loader.textContent = "✗";
projectsContainer.append(err);
projectsContainer.classList.add("error");
})
.finally(() => {
clearInterval(interval);
});
}
}
function loadContent({ repos, projectsBody, loader, meta }) {
const reposContainers = repos.map(
({
name,
description,
html_url,
language,
stargazers_count,
updated_at,
}) => {
const repoContainer = document.createElement("div");
const metaFields = { language, stargazers_count, updated_at };
repoContainer.innerHTML = `
<div class="repo-header">
<h4><a href="${html_url}">${name}</a></h4>
${buildMeta(
Object.fromEntries(
Object.entries(metaFields).filter(([key]) => meta.includes(key))
)
)}
</div>
<div class="repo-body">
<p>${description ? description : ""}</p>
</div>
`;
return repoContainer;
}
);
loader.textContent = "✔";
projectsBody.append(...reposContainers);
}
function buildMeta(meta) {
const rtf1 = new Intl.RelativeTimeFormat("en", { style: "narrow" });
return Object.entries(meta)
.map(([key, value]) => {
if (key === "updated_at") {
const updatedDate = new Date(value);
const millisecondsDiff = updatedDate.getTime() - Date.now();
const daysDiff = Math.floor(
millisecondsDiff / 1000 / 60 / 60 / 24
);
const relativeTime = rtf1.format(daysDiff, "day");
return `<span class="meta">updated ${relativeTime}</span>`;
}
if (key === "stargazers_count") {
return `<span class="meta">${value} stars</span>`;
}
return `<span class="meta">${value}</span>`;
})
.join("");
}
</script>
</body>
</html>
</code></pre>
<p>I would appreciate any input on the JS script to make it more readable, clean, and maintainable, although any feedback regarding the CSS and the HTML (better structure, semantic markup, accessibility, etc) would also be great.</p>
|
[] |
[
{
"body": "<p>First of all, kudos for making a single simple file!</p>\n<p>It was relatively straightforward to read as well, though I think mostly because of the well known api and that there isn't much code. Formatting was nice as well.</p>\n<p>Here's what I think could improve it:</p>\n<ul>\n<li>Since you're already using const, promise, arrow functions, etc, I think you could benefit from using async/await as well.</li>\n<li>loadProjects does basically everything. When I then saw "loadContent" I was expecting to see something similar, but in fact it was just rendering. Then I got to "buildMeta" which was also rendering, except it was not outputing to DOM. The names confuse me, and it's probably because there is no real attempt at abstraction/separation of concerns. More on that below.</li>\n<li>loadProjects does many things. I would look to separate these:\n<ul>\n<li>rendering / dom</li>\n<li>loading state + interval</li>\n<li>fetching + transformation of result</li>\n<li>caching</li>\n<li>error handling</li>\n</ul>\n</li>\n<li>loadContent inserts itself to the dom. There's really no need. It's easier to read and understand if the dom generating code just returns dom (pure functions)</li>\n<li>Do you really need to display rate limiting errors?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T20:25:58.533",
"Id": "264457",
"ParentId": "264455",
"Score": "2"
}
},
{
"body": "<h2 id=\"good-things-m2z6\">Good things</h2>\n<p>The code appears to make good use of ES-6 features like template literals, arrow functions, etc., as well as functional techniques like <code>.map()</code>, <code>.filter()</code>, etc. Indentation appears to be consistent.</p>\n<p>I agree with Magnus - the ES8 features <code>async</code>/<code>await</code> could help simplify the callbacks. There are just a few suggestions I have to add - see the next section.</p>\n<h2 id=\"suggestions-yaiy\">Suggestions</h2>\n<h3 id=\"pre-fix-increment-7gcl\">Pre-fix increment</h3>\n<p>The interval function to update the loader could be simplified from:</p>\n<blockquote>\n<pre><code>const interval = setInterval(() => {\n i++;\n loader.textContent = loaderSymbols[i % loaderSymbols.length];\n}, 500);\n</code></pre>\n</blockquote>\n<p>to this - using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#prefix_increment\" rel=\"nofollow noreferrer\">prefix increment</a></p>\n<pre><code>const interval = setInterval(() => {\n loader.textContent = loaderSymbols[++i % loaderSymbols.length];\n}, 500);\n</code></pre>\n<h2 id=\"micro-optimization-spread-operator-mxw5\">Micro-optimization: spread operator</h2>\n<p>When creating an array from the response headers:</p>\n<blockquote>\n<pre><code>const rateLimitElements = Array.from(response.headers) \n</code></pre>\n</blockquote>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> could be used since the headers are <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol\" rel=\"nofollow noreferrer\">iterable</a> - which requires one less function call and is slightly shorter to write:</p>\n<pre><code>const rateLimitElements = [...response.headers] \n</code></pre>\n<h2 id=\"ternary-simplification-hldp\">Ternary simplification</h2>\n<p>When checking for the description:</p>\n<blockquote>\n<pre><code><p>${description ? description : ""}</p>\n</code></pre>\n</blockquote>\n<p>This could be simplified with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR\" rel=\"nofollow noreferrer\">Logical OR operator <code>||</code></a>:</p>\n<pre><code><p>${description || ""}</p>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T23:04:02.660",
"Id": "264461",
"ParentId": "264455",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264457",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-27T19:56:46.677",
"Id": "264455",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"ajax"
],
"Title": "JS script fetching GitHub API for personal website"
}
|
264455
|
<p>I am very new to <strong>Vue.js</strong>, I just stumbled on a very hard thing to do (at least for me) where Vue was complaining about mutating a prop (children shouldn't change parent props apparently). I was about to give up at 8~ hour mark, but then it worked! Then not only that, I came with another solution. Here are the two solutions:</p>
<p>Using <code>watch</code>:</p>
<pre><code>const VueNavDrawerComp={
props : ["childSideNav", "menuItems"],
template :
/*html*/
`
<div>
<v-navigation-drawer v-model="otherVar" absolute temporary>
...
</v-navigation-drawer>
</div>
`,
data(){
return {
otherVar : this.childSideNav
};
},
watch : {
childSideNav : function(newValue){
this.otherVar=newValue;
},
otherVar : function(newValue){
if(!newValue){
this.$emit("ev-toggle-drawer");
}
}
}
};
</code></pre>
<p>Using <code>computed</code>:</p>
<pre><code>const VueNavDrawerComp={
props : ["childSideNav", "menuItems"],
template :
/*html*/
`
<div>
<v-navigation-drawer v-model="computedSideNav" absolute temporary>
...
</v-navigation-drawer>
</div>
`,
data(){
return {};
},
computed : {
computedSideNav : {
get(){
return this.childSideNav;
},
set(newValue){
if(!newValue){
this.$emit("ev-toggle-drawer");
}
}
}
}
};
</code></pre>
<p>Anyway, I fiddled around with some console logs, to try to see if things were firing the correct amount of times, and things like that, but I have no idea to how to find out which of the two is more optimized or have better "code taste" as the Linux guy would say.</p>
<p>Anyone experienced <strong>Vue.js</strong> can enlighten me in which is better option or if some corrections/improvements can be done?.</p>
<p>To clarify a bit, <code>v-navigation-drawer</code> is a <strong>Vuetify</strong> component. A Boolean is passed to affect the visibility of the Drawer. When the event listener is executed, it will toggle a common shared Boolean across more components and this Boolean must be in sync with all of them.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T07:52:43.457",
"Id": "522339",
"Score": "1",
"body": "Is `v-navigation-drawer` a component from Vuetify? What kind of property is `childSideNav`? When the event is emitted, what does the parent do about it? What happens exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T15:20:28.540",
"Id": "522360",
"Score": "0",
"body": "@SimonForsberg yes component of Vuetify (did not find a tag in this site), a Boolean is passed to show or hide the Drawer, the event toggles the Boolean to hide it. There are other components that can also toggle the visibility of the Drawer (like the collapsed menu button in mobile) and they all must share a commun Boolean."
}
] |
[
{
"body": "<h2>One-Way Data Flow</h2>\n<blockquote>\n<p><em>(children shouldn't change parent props apparently)</em></p>\n</blockquote>\n<p>Yes- this is explained in the documentation section for <a href=\"https://vuejs.org/v2/guide/components-props.html\" rel=\"nofollow noreferrer\"><strong>Components In-Depth</strong> > Props</a></p>\n<blockquote>\n<h3><a href=\"https://vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow\" rel=\"nofollow noreferrer\">One-Way Data Flow</a></h3>\n<p>All props form a <strong>one-way-down binding</strong> between the child property and\nthe parent one: when the parent property updates, it will flow down to\nthe child, but not the other way around. This prevents child\ncomponents from accidentally mutating the parent’s state, which can\nmake your app’s data flow harder to understand.</p>\n<p>In addition, every time the parent component is updated, all props in\nthe child component will be refreshed with the latest value. This\nmeans you should not attempt to mutate a prop inside a child\ncomponent. If you do, Vue will warn you in the console.</p>\n</blockquote>\n<hr />\n<h2>Computed properties vs. watchers</h2>\n<blockquote>\n<p><em>Anyone experienced <strong>Vue.js</strong> can enlighten me in which is better option or if some corrections/improvements can be done?</em></p>\n</blockquote>\n<p>The <a href=\"https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods\" rel=\"nofollow noreferrer\">documentation for Computed caching vs Methods</a> contains this fragment:</p>\n<blockquote>\n<p>... <strong>computed properties are cached based on their reactive dependencies</strong>. A computed property will only re-evaluate when some of its reactive dependencies have changed.</p>\n</blockquote>\n<p>If <code>computed</code> can be used instead of <code>watch</code> then it is the better option for that reason.</p>\n<hr />\n<h3>whitespace</h3>\n<p>The usage of whitespace doesn't match much of the idiomatic JavaScript I have seen - e.g.</p>\n<blockquote>\n<pre><code>const VueNavDrawerComp={\n</code></pre>\n</blockquote>\n<p>most style guides (e.g. <a href=\"https://google.github.io/styleguide/jsguide.html#formatting-whitespace\" rel=\"nofollow noreferrer\">Google</a>, <a href=\"https://github.com/airbnb/javascript#whitespace\" rel=\"nofollow noreferrer\">AirBnB</a>) recommend a space on either side of operators like <code>=</code></p>\n<blockquote>\n<pre><code>watch : {\n</code></pre>\n</blockquote>\n<p>The space following the colon is typical but not the space before. Even <a href=\"https://vuejs.org/v2/guide/index.html#Declarative-Rendering\" rel=\"nofollow noreferrer\">the examples in the VueJS documentation</a> follow this pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:42:12.680",
"Id": "524741",
"Score": "0",
"body": "that makes sense, thanks!. Also not that I disagree with the whitespace preference, but I completely don't get lured into those battles (if style is important somewhere, I will use whatever pretifier config.) I totally try to add spaces around `=` when posting to SO or SE sites in general, this time I forgot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T18:27:28.077",
"Id": "265672",
"ParentId": "264464",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265672",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T06:38:46.557",
"Id": "264464",
"Score": "1",
"Tags": [
"javascript",
"comparative-review",
"vue.js"
],
"Title": "Which of these two Vuetify Navigation Drawer prevent prop mutation workarounds seem better?"
}
|
264464
|
<p>I have a program that uses pandas to read csv files and then generates and saves graphical charts. I have been trying to follow the SOLID principles so I have tried to seperate responsibilities.
So far the project has the structure of</p>
<pre><code>GUI
├─ Service
│ ├─ Business Logic
│ │ ├─ DataReader
│ │ ├─ ChartGenerator
</code></pre>
<p>The GUI makes calls to the Service which holds instances of the DataReader and ChartGenerator</p>
<p><strong>ChartService.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from matplotlib.pyplot import title
from ChartGenerator import ChartGenerator
import DataReader
from enum import Enum
class Chart(Enum):
kW = 'kW'
kWH = 'kWH'
Hum = 'Humidity'
Temp = 'Temperature'
lineColours = [
'blue',
'green',
'red',
'black',
'cyan',
'magenta',
'yellow'
]
class ChartService:
def __init__(self, dataPath) -> None:
self.dataPath = dataPath
def GetClients(self) -> list:
self.clientDict = DataReader.GetCustomerRacks(self.dataPath)
return list(self.clientDict.keys())
def GenClient(self,
client,
savePath,
combineCharts,
charts={
Chart.kW: True,
Chart.kWH: True,
Chart.Hum: True,
Chart.Temp: True
},
options={
'chartFileNames': {
'kW': 'kW.png',
'kWH': 'kWH.png',
'Hum': 'Humidity.png',
'Temp': 'Temperature.png'
},
'chartNames': {
'kW': 'kW',
'kWH': 'kWH',
'Hum': 'Humidity',
'Temp': 'Temperature'
},
"chartGen":{
"chartSizeX": 5,
"chartSizeY": 5,
"subPlotSizeX": 2,
"subPlotSizeY": 2
}
},
):
if(not combineCharts):
if charts[Chart.kW]:
chartGenerator = ChartGenerator(options['chartGen'])
axis = chartGenerator.PlotChart(None, '', '')
for rack, colour in zip(self.clientDict[client], lineColours):
data = DataReader.GetRackkWData(self.dataPath, rack)
chartGenerator.PlotChart(data, 'Date', 'kW', xAxisLabel='Date', yAxisLabel='kW', lineColour=colour, axis=axis)
fileName = options['chartNames']['kW']
chartGenerator.SaveChart(
f"{savePath}/{client}{fileName}")
if charts[Chart.kWH]:
chartGenerator = ChartGenerator(options['chartGen'])
axis = chartGenerator.PlotChart(None, '', '')
for rack, colour in zip(self.clientDict[client], lineColours):
data = DataReader.GetRackkWHourData(self.dataPath, rack)
chartGenerator.PlotChart(data, 'Date', 'kWH', xAxisLabel='Date', yAxisLabel='kWH', lineColour=colour, axis=axis)
fileName = options['chartNames']['kWH']
chartGenerator.SaveChart(
f"{savePath}/{client}{fileName}")
if charts[Chart.Hum]:
data = DataReader.GetHumidityData(self.dataPath)
chartGenerator = ChartGenerator(options['chartGen'])
chartGenerator.PlotChart(data, 'DateTime', 'Hum', xAxisLabel='Date', yAxisLabel='Humidity')
fileName = options['chartNames']['Hum']
chartGenerator.SaveChart(f"{savePath}/{client}{fileName}")
if charts[Chart.Temp]:
data = DataReader.GetTemperatureData(self.dataPath)
chartGenerator = ChartGenerator(options['chartGen'])
chartGenerator.PlotChart(data, 'DateTime', 'Temp', xAxisLabel='Date', yAxisLabel='Temperature')
fileName = options['chartNames']['Temp']
chartGenerator.SaveChart(f"{savePath}/{client}{fileName}")
else:
chartGenerator = ChartGenerator()
if charts[Chart.kW]:
# Get empty axis
axis = chartGenerator.PlotChart(None, '', '')
#Loop over axis with each rack
for rack, colour in zip(self.clientDict[client], lineColours):
data = DataReader.GetRackkWData(self.dataPath, rack)
chartGenerator.PlotChart(data, 'Date', 'kW', xAxisLabel='Date', yAxisLabel='kW', lineColour=colour, axis=axis)
fileName = options['chartNames']['kW']
chartGenerator.SaveChart(
f"{savePath}/{client}{fileName}")
if charts[Chart.kWH]:
axis = chartGenerator.PlotChart(None, '', '')
for rack, colour in zip(self.clientDict[client], lineColours):
data = DataReader.GetRackkWHourData(self.dataPath, rack, axis=axis)
chartGenerator.PlotChart(data, 'Date', 'kWH', xAxisLabel='Date', yAxisLabel='kWH', lineColour=colour, axis=axis)
fileName = options['chartNames']['kWH']
chartGenerator.SaveChart(
f"{savePath}/{client}{fileName}")
if charts[Chart.Hum]:
data = DataReader.GetHumidityData(self.dataPath)
chartGenerator.PlotChart(data, 'DateTime', 'Hum', xAxisLabel='Date', yAxisLabel='Humidity')
if charts[Chart.Temp]:
data = DataReader.GetTemperatureData(self.dataPath)
chartGenerator.PlotChart(data, 'DateTime', 'Temp', xAxisLabel='Date', yAxisLabel='Temperature')
chartGenerator.SaveChart(f"{savePath}/{client}.png")
</code></pre>
<p>This service is initiated by the GUI with a path of where to read the data from. It makes calls to the ChartGenerator, I have designed ChartGenerator so that any "plots" that are done on an instance of ChartGenerator will generate on the same image (or "figure").</p>
<p><strong>ChartGenerator.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
class ChartGenerator:
def __init__(
self,
options={
"chartSizeX": 5,
"chartSizeY": 5,
"subPlotSizeX": 2,
"subPlotSizeY": 2
}
) -> None:
self.fig = plt.figure(figsize=(options['chartSizeX'],
options['chartSizeY']))
self.subPlotSizeX = options["subPlotSizeX"]
self.subPlotSizeY = options["subPlotSizeY"]
self.axes = []
def PlotChart(
self,
data,
xAxis,
yAxis,
axis=None,
xAxisLabel=None,
yAxisLabel=None,
lineStyle='--',
lineColour='blue',
chartTitle=None,
) -> plt.axis:
'''
Plots a Line chart with data from Pandas Dataframe.
Returns axis which plot was drawn on
Arguments
----------
data is Dataframe to read from.
xAxis, yAxis are names of columns to plot onto graph.
axis (Default = None) can be given if wanting to plot onto an existing graph. If no axis is given then a new axis is created as a subplot.
xAxisLabel, yAxisLabel are labels that can be printed onto the sides of the graph
linestyle is the style of the line on the graph
chartTitle is text above the chart
'''
### NOTE: Should be implemented with function as argument to call
if (not axis):
axis = self.fig.add_subplot(self.subPlotSizeX, self.subPlotSizeY,
len(self.axes) + 1)
self.axes.append(axis)
axis.set_title(chartTitle)
axis.set_ylabel(yAxisLabel)
axis.set_xlabel(xAxisLabel)
axis.plot(data[xAxis], data[yAxis], linestyle=lineStyle, figure=self.fig)
return axis
def SaveChart(self, path, title=None, showChart=False) -> None:
'''
Saves generated graph as image to path provided
Arguments
----------
path is the path of the file to be saved
title (Default=None) is text that will be printed at the top of the image
showChart (Default = False) when True will display the graph before finishing
'''
self.fig.suptitle(title, fontsize=40)
self.fig.autofmt_xdate()
self.fig.tight_layout()
if showChart:
self.fig.show()
self.fig.savefig(path)
plt.close(self.fig)
</code></pre>
<p>Problems arise when trying to implement an option to let the charts be all generated on one image or all seperately.</p>
<p>The current process for generating all charts on one image is:</p>
<pre class="lang-none prettyprint-override"><code>Create ChartGenerator instance
[
Plot all of the charts
]
Save Image
</code></pre>
<p>vs the process for generating them seperately:</p>
<pre class="lang-none prettyprint-override"><code>[
Create ChartGenerator instance
Plot one chart
Save Image
] Repeat for all charts
</code></pre>
|
[] |
[
{
"body": "<p>I managed to find a solution I found that worked well for this case, I'm sure it's not the cleanest or most optimal but it worked for my case.</p>\n<p>Since the main problem was that generating seperate graphs required a new instance of the ChartGenerator class I made a class which would return a new instance if the option was enabled.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def ReturnGenerator(combine, generator) -> ChartGenerator:\n '''\n If combine is false returns a new ChartGenerator\n '''\n if (not combine):\n generator = ChartGenerator()\n</code></pre>\n<p>That way I would be able to assign generator for each graph.</p>\n<pre class=\"lang-py prettyprint-override\"><code>combineChartGenerator = ChartGenerator()\n\nif charts[Chart.kW]:\n kWGenerator = ReturnGenerator(combineCharts, combineChartGenerator)\n axis = kWGenerator.InitialiseAxis(Axis(yAxisLabel='kW'))\n # Loop over each rack\n for rack in self.clientDict[client]:\n data = DataReader.GetRackkWData(self.dataPath, rack)\n kWGenerator.PlotChart(data['Date'], data['kW'], xAxisLabel='Date', yAxisLabel='kW', axis=axis, plotName=rack)\n\n # Save Image\n if (not combineCharts):\n fileName = options['chartFileNames']['kW']\n kWGenerator.SaveChart(\n f"{savePath}/{client}{fileName}"\n )\n\n</code></pre>\n<p>Also notice in that example I manually created the axis since I need to reference it multiple times over the loop. Since the ChartGenerator needs to be aware of all the axes I pass it to the <code>InitialiseAxis</code> function which adds the axis to the <code>axes</code> array in <code>ChartGenerator</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T03:50:05.970",
"Id": "265687",
"ParentId": "264469",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T09:33:14.707",
"Id": "264469",
"Score": "5",
"Tags": [
"python",
"csv",
"pandas",
"tkinter",
"matplotlib"
],
"Title": "GUI that reads data and generates/ saves charts"
}
|
264469
|
<p>I am trying to find the "Number of trailing zeros of N!" (N factorial).
In the python code I am trying to find the factorial first and then the number of trailing zeros. However, I am getting "Execution Timed Out" error.</p>
<ol>
<li>Why is this code giving the error? Is there anyway to optimize the code to decrease the execution time?</li>
<li>Can this code be shortened in terms of lines of code?</li>
</ol>
<pre><code>def zeros(n):
fact=1
if n==1 or n==0:
return 1
elif n<0:
return 0
else:
while n>1:
fact=n*fact
n=n-1
count = 0
while fact >= 1:
if fact%10==0:
count+=1
fact=fact//10
else:
break
return count
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:47:52.547",
"Id": "524443",
"Score": "3",
"body": "Coding problems like this are almost always challenging you to find a more clever solution than the obvious iteration/recursion. That's why they have execution time limits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T16:14:51.923",
"Id": "524451",
"Score": "2",
"body": "This is integer sequence [A027868](https://oeis.org/A027868) and you can find a wealth of reading (including two different Python implementations) on its OEIS page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T22:23:46.347",
"Id": "524463",
"Score": "0",
"body": "Skip finding the factorial first, and just find the number of trailing zeroes. The number of trailing zeroes is equal to the number of powers of ten in the factorial, which is equal to the number of the prime factors of ten that appear in the factorial, or rather, whichever of the prime factors is less numerous..."
}
] |
[
{
"body": "<blockquote>\n<pre><code>if n==1 or n==0:\n return 1\n</code></pre>\n</blockquote>\n<p>That looks incorrect. 0! and 1! are both equal to 1, which has <em>no</em> trailing zeros, so we should be returning 0 there. If we had some unit tests, this would be more apparent.</p>\n<hr />\n<p>We don't need to carry all the trailing zeros with us as we multiply; we can divide by ten whenever we have the opportunity, rather than waiting until the end:</p>\n<pre><code> count = 0\n while n > 1:\n fact *= n\n n -= 1\n while fact % 10 == 0:\n count += 1\n fact = fact // 10\n</code></pre>\n<hr />\n<p>However, this only gets us a small gain. The real problem is that we have chosen <strong>a very inefficient algorithm</strong>. We're multiplying by all the numbers in 2..n, but some mathematical insight helps us find a faster technique.</p>\n<p>Observe that each trailing zero means a factor of 10, so we just need the lesser count of 2s or 5s in the prime factors of the factorial (which is the count of all 2s or 5s in all the numbers 1..n). We know there will be more 2s than 5s, since even numbers are much more common than multiples of 5, so we just need a way to count how many fives are in the factorial.</p>\n<p>At first glance, that would appear to be n÷5, since every 5th number is a multiple of 5. But we would undercount, because 25, 50, 75, ... all have two 5s in their prime factorisation, and 125, 250, 375, ... have three 5s, and so on.</p>\n<p>So a simpler algorithm would be to start with n÷5, then add n÷25, n÷125, n÷625, ... We can do that recursively:</p>\n<pre><code>def zeros(n):\n if n < 5:\n return 0\n return n // 5 + zeros(n // 5)\n</code></pre>\n<p>We can (and should) unit-test our function:</p>\n<pre><code>def zeros(n):\n """\n Return the number of trailing zeros in factorial(n)\n >>> zeros(0)\n 0\n >>> zeros(4)\n 0\n >>> zeros(5)\n 1\n >>> zeros(24)\n 4\n >>> zeros(25)\n 6\n >>> zeros(625) - zeros(624)\n 4\n """\n if n < 5:\n return 0\n return n // 5 + zeros(n // 5)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:26:55.787",
"Id": "522366",
"Score": "1",
"body": "I express my deep sense of gratitude for writing a detailed answer and explaining it so beautifully."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T18:36:46.520",
"Id": "522375",
"Score": "1",
"body": "Great, except that I think both “infinite set of even numbers” and “infinite set of multiples of 5” are countably infinite and thus technically have the same cardinality :) it seems true, OTOH, that in any given finite set 1..n, the smaller of the two subsets is the multiples of 5"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:01:52.850",
"Id": "522377",
"Score": "0",
"body": "@D.BenKnoble If n>1. If n=1 then each subset has zero elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:50:30.580",
"Id": "522382",
"Score": "0",
"body": "@D.BenKnoble, you're right, and I saw the smiley too. Just trying to keep the explanation at the right level for the code, rather than mathematically rigorous!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T20:59:42.783",
"Id": "522385",
"Score": "0",
"body": "I ran into exactly the inverse problem: I scripted a factorial calculator (using `awk | dc`) and assumed it was rounding somewhere because of the abundance of trailing zeros. Took me a while to spot the pattern. The corollary, of course, is that the value before the trailing zeros is divisible by the remaining power of two."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T10:16:46.533",
"Id": "264471",
"ParentId": "264470",
"Score": "17"
}
},
{
"body": "<h3 id=\"review-dw34\">Review</h3>\n<p>You don't need <code>else</code> after <code>return</code>, but it can be there if it improves readability. Removing the last <code>else</code> will bring the code one level down.</p>\n<p>Declare variables right before you use them, you can move <code>fact=1</code> down to first <code>while</code> statement.</p>\n<p>There are <code>math.factorial</code> and <code>divmod</code> functions, you can use them to speed the code up a bit (but I'm sure still not enough).</p>\n<h3 id=\"better-idea-z16f\">Better idea</h3>\n<p>A trailing zero means divisibility by 10, you got it right; but the next step is to realize that <span class=\"math-container\">\\$10=2*5\\$</span>, so you need just count the number of factors of 2 and 5 in a factorial, not to calculate the factorial itself. Any factorial have much more even factors then divisible by 5, so we can just count factors of 5. A range from 1 to n (including) will have exactly <code>n//5</code> factors of 5 (no loop, just one division!), but some of them will be factors of <span class=\"math-container\">\\$25=5*5\\$</span>, <span class=\"math-container\">\\$125=5*5*5\\$</span> etc. That, I think, is the most confusing thing in this problem, still easily solved.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T10:19:33.143",
"Id": "264472",
"ParentId": "264470",
"Score": "3"
}
},
{
"body": "<p>Recursion adds overhead, especially in memory but also in time, compared to this purely iterative version:</p>\n<pre><code>def zeros(n):\n z = 0\n while n >= 5:\n n = n//5\n z = z+n\n return z\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T16:11:06.763",
"Id": "524449",
"Score": "5",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]. Just saying that \"it's quicker\" - without any explanation about _what_ makes it quicker - doesn't help the asker advance their abilities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T09:28:11.093",
"Id": "524542",
"Score": "0",
"body": "what is this function doing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T09:29:04.463",
"Id": "524543",
"Score": "0",
"body": "I need number of zeros, for input 120, i m getting 28, what is 28?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T20:34:37.017",
"Id": "525123",
"Score": "0",
"body": "28 is the number of trailing zeros in the decimal expansion of 120! (as I just checked using Python math.factorial); is that not what you seek?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:32:39.013",
"Id": "265517",
"ParentId": "264470",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "264471",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T09:48:43.290",
"Id": "264470",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Find the number of trailing zeros in factorial"
}
|
264470
|
<p>I have created common function for CRUD operations.</p>
<hr />
<ol>
<li>I am using Sequelize JS, I have created all models in Sequelize</li>
<li>I have written stored procedures in mysql for CRUD operations for each module/tables I have</li>
</ol>
<ul>
<li><code>GetItems</code></li>
<li><code>GetItemById</code></li>
<li><code>CreateItem</code></li>
<li><code>UpdateItem</code></li>
<li><code>Deleteitem</code></li>
</ul>
<ol start="3">
<li>Then I have created Common CRUD function in Utilities which has below functions.</li>
</ol>
<ul>
<li>Get All Data</li>
</ul>
<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>exports.getAllData = (spname, res, next) => {
sequelize
.query(
spname,
Sequelize.QueryTypes.SELECT)
.then(result => {
res.status(200).json({
message: "data Fetched from database",
statusCode: 200,
result: result,
});
})
.catch(error => {
if (!error.statusCode) {
error.statusCode = 500;
}
next(error);
});
}</code></pre>
</div>
</div>
</p>
<ul>
<li>Get Data by ID</li>
</ul>
<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>exports.getDataById = (spname, parameter, res, next) => {
sequelize.query(
spname,
{
replacements: parameter
},
Sequelize.QueryTypes.SELECT
)
.then(result => {
res.status(200).json({
message: "data Fetched from database",
statusCode: 200,
result: result,
});
})
.catch(error => {
if (!error.statusCode) {
error.statusCode = 500;
}
next(error);
});
}</code></pre>
</div>
</div>
</p>
<ul>
<li>Create Item</li>
</ul>
<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>exports.postData = (spname, parameters, res, next) => {
sequelize.query(
spname,
{
replacements: parameters
},
Sequelize.QueryTypes.INSERT
)
.then(result => {
res.status(200).json({
message: "data added to database",
statusCode: 200,
result: result,
});
})
.catch(error => {
if (!error.statusCode) {
error.statusCode = 500;
}
next(error);
});
}</code></pre>
</div>
</div>
</p>
<ol start="4">
<li>Call that functions in Controller functions</li>
</ol>
<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 Category = require("../models/category");
const crud = require('../utility/crud');
exports.getAllCategories = (req, res, next) => {
crud.getAllData('call USP_GetAllCategories()', res, next);
}
exports.getCategoryById = (req, res, next) => {
let parameter = {
categoryId: req.params.id
}
crud.getDataById('CALL USP_GetCategoryById(:categoryId)', parameter, res, next);
}
exports.addCategory = (req, res, next) => {
let parameter = {
name: req.body.name,
image: req.body.image,
createdBy: req.body.createdBy
}
let query = 'CALL USP_CreateCategory(:name,:image,:createdBy)';
crud.postData(query, parameter, res, next);
}</code></pre>
</div>
</div>
</p>
<hr />
<p>I have below questions about it.</p>
<ol>
<li>Is it good approach to create stored procedures and call them in application with / without using Sequelize?</li>
<li>Is it good practice to create common function for CRUD? or should go with writing function for each module ?(I checked on internet, I never found any good satisfactory solution about this)</li>
<li>Could you please help to review code so I can make it more better ?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T23:06:14.983",
"Id": "524700",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<p>Your first two questions:</p>\n<ul>\n<li>You don't appear to be using almost a single feature of sequelize, so I can't understand why you would use it.</li>\n<li>What you have done is to put all your logic in the database, and have an application that's just a proxy for the database. If your application needs to evolve even a little bit, this can quickly fall apart. Stored procedures can be a pain to refactor. Often you don't know where and how they are used. Also, oftentimes there is no version control. So what happens is that they grow bigger, or workarounds are added elsewhere, further cementing the spaghetti. Even worse, there are many things you just cannot do with stored procedures. It won't take long before you will add some logic to the application, and then you have it split between the application and database, making it even harder to work with.</li>\n<li>"Is it good practice to create common function for CRUD" - If you KNOW that EVERY single case, now and in the future, will be the EXACT same, then yes. Otherwise, it's a much better idea to create good abstractions from the get-go, and accept some boilerplate. It often turns out that cases that look the same are in fact not the same, and then it's much easier to adjust the already separate cases than to add conditionals to the crud god class.</li>\n</ul>\n<p>Review:</p>\n<ul>\n<li>The crud module exposes spname as a parameter. It appears this is the query to call a stored procedure. It's a pretty leaky abstraction.. why does the controller need to know anything about the stored procedure? Personally I would not use stored procedures like this, but if I had to I would at least limit the exposure to a named resource and its parameters.</li>\n<li>The crud module mixes controller and database logic. Evolving such an abstraction is hell. A few years of features and you'll have a pile of conditionals to take care of all the cases you haven't thought about yet.</li>\n<li>All error status codes are set to 500. What about NOT FOUND errors?</li>\n<li>Where's the validation?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T02:13:24.773",
"Id": "524604",
"Score": "0",
"body": "Thank you for your comments - For not found, I have added at stored procedure level - I am checking id passed to parameter, that record is exists or not.. if not exists then I am showing message as \"Record with mentioned Id does not exists\" \n\n\nand for validation, I am handing validations in routers using \"express-validator\" for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T02:19:38.570",
"Id": "524605",
"Score": "0",
"body": "how should I call store procedure from controller?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T17:33:16.363",
"Id": "265583",
"ParentId": "264473",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T10:40:48.853",
"Id": "264473",
"Score": "1",
"Tags": [
"node.js",
"express.js"
],
"Title": "Common CRUD function in node js using Express"
}
|
264473
|
<p>I've been trying to learn a bit of JavaScript over the last few weeks, and inspired by <a href="https://codereview.stackexchange.com/questions/264433/first-non-repeating-character-with-a-single-loop-in-python">this current hot network question</a>, I tried creating a function for finding the first non-repeating character in a string. Is my approach a decent one, and is there any obvious improvements which can be made?</p>
<pre><code>function firstNonRepeatingCharacter(inData) {
var dict = {};
var key;
for (var i = 0; i < inData.length; i++) {
key = inData.charAt(i);
if (key in dict) {
dict[key] += 1;
} else {
dict[key] = 1;
}
}
for (var v in dict) {
if (dict[v] === 1) {
return v;
}
}
return undefined;
}
console.log(firstNonRepeatingCharacter("axxyzz"))
</code></pre>
|
[] |
[
{
"body": "<p>that's my post! I'm glad you were inspired by it.</p>\n<p>As far as logic goes, this is a great and quite commonly agreed upon way to solve the problem in O(n) time, as long as the language you write it in maintains the order of insertion of a dictionary(which JS does). Well done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T21:35:01.400",
"Id": "522387",
"Score": "0",
"body": "Answers are reserved for Review's only. Please use comments for general code related remarks. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T00:04:43.513",
"Id": "522390",
"Score": "0",
"body": "Thanks for the feedback, though as @Blindman67 says, maybe you should have used a comment :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T13:31:18.137",
"Id": "264478",
"ParentId": "264474",
"Score": "0"
}
},
{
"body": "<h2 id=\"define-the-task-la6w\">Define the task</h2>\n<p>I am assuming the task is to find first single instance of a character in the string as this is what the code does. <em>"Repeating"</em> could imply sequential instances of an item.</p>\n<p>When defining coding tasks always try to avoid any possible ambiguity.</p>\n<h2 id=\"code-style-khl7\">Code style</h2>\n<p>General points regarding code style.</p>\n<ul>\n<li><p>The variable <code>dict</code> and <code>key</code> can be constants.</p>\n</li>\n<li><p>There is no need to ever add <code>undefined</code> to a <code>return</code>. The default return is <code>undefined</code> thus <code>return undefined</code> and <code>return</code> are identical.</p>\n</li>\n<li><p>Functions return automatically. Unless you have something to return there is no need to add a <code>return</code> to the last line of your function.</p>\n</li>\n<li><p>When using <code>var</code> to declare variables do so at the top of the function. Eg the <code>var i</code> in the for loop should be declared at the top of the function or use <code>let i</code></p>\n</li>\n<li><p>JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String\">String</a> are array like and can be indexed using bracket notation (strings are immutable thus its read only). eg <code>key = inData.charAt(i)</code> is the same as <code>key = inData[i]</code></p>\n</li>\n<li><p>JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String\">String</a> are also iterable <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Iteration protocols\">Iteration_protocols</a> thus you can test each character using <code>for(const key of inData)</code> rather than the <code>for;;</code> and then indexing the character.</p>\n</li>\n<li><p>Naming is rather poor. Avoid, when possible, naming variables by type or usage pattern, name them for what they contain.</p>\n<p>Some name change suggestions...</p>\n<ul>\n<li><code>dict</code> could be <code>charCounts</code></li>\n<li><code>inData</code> could be <code>text</code>, <code>str</code> or <code>string</code></li>\n<li><code>key</code> better as <code>char</code>, <code>letter</code>, or <code>character</code></li>\n</ul>\n</li>\n</ul>\n<h3 id=\"rewrite-6vna\">Rewrite</h3>\n<p>A general rewrite using the points above.</p>\n<p><strong>Note</strong> that using <code>for (const char of str) {</code> makes the rewrite ~2% slower than your original code.</p>\n<pre><code>function firstNonRepeat(str) {\n const counts = {}; \n for (const char of str) {\n if (char in counts) { counts[char] += 1 }\n else { counts[char] = 1 } \n } \n for (const char in counts) {\n if (counts[char] === 1) { return char }\n }\n}\n</code></pre>\n<h2 id=\"performance-2a2b\">Performance</h2>\n<p>End users are the ultimate judges of our code, they are also the ones that pay the bills. End users when asked to rate two identical applications the more performant app is always rated as the better product.</p>\n<p>Your code has some performance anti-styles and that is why I have added a performance review and rewrites. Though that said your code's time and space\ncomplexity is as good as it can be <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p>Specifically performance points are string handling, and how you use a dictionary (hash map)</p>\n<p>This task is at best <span class=\"math-container\">\\$O(n)\\$</span> (time and space) and as you have achieved this any performance gain will be under an order of magnitude.</p>\n<p>Performance should not be a coding after thought, performance code should be your default style.</p>\n<h3 id=\"performance-tips-gx1c\">Performance tips</h3>\n<ul>\n<li><p>In JS <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Number\">Number</a> are much quicker than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String\">String</a> (even single characters)</p>\n</li>\n<li><p>We can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String charCodeAt\">String.charCodeAt</a>` to handle a character as a number.</p>\n</li>\n<li><p>With the character as a number the character dictionary can be replaced with an array. Even though the array will be a <a href=\"https://stackoverflow.com/a/614255/3877726\">sparse array</a>, indexing a sparse array is quicker than indexing an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a> (even if the indexing is via Numbers).</p>\n</li>\n<li><p>To track the first occurrence we don't need to count any characters that occurred more than once.</p>\n<p>We can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> to hold character codes when we first see a character, if we see the character a second time we delete it <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/delete\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set delete\">Set.delete</a> from set of once only characters. If we see a character a 3rd or more times we ignore it. This lets us avoid many of the expensive hashing function calls required when accessing the set.</p>\n<p>Using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> that contains only single occurrences also means that we don't need to iterate the dictionary to find the character with a count 1, we know that the first item in the dictionary (Set) is the one we want. Thus we can return the character that is represented by the first character code in that set.</p>\n<p>EG assuming that <code>once</code> has items <code>return String.fromCharCode(once.values().next())</code></p>\n<p>Using iterator <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set values\">Set.values</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String fromCharCode\">String.fromCharCode</a></p>\n</li>\n</ul>\n<p>Generally any of these changes will have very little effect when the input string in only a dozen or two characters long, but over 100 characters and the gain is a worth while three fold increase in throughput (Something end users will notice)</p>\n<h3 id=\"performance-rewrites-ny9j\">Performance rewrites</h3>\n<p>There are two rewrites addressing performance</p>\n<ul>\n<li><p>The first uses a more idiomatic style.</p>\n</li>\n<li><p>The second is a totally performance oriented style</p>\n</li>\n</ul>\n<h3 id=\"idiomatic-performance-style-e0q1\">Idiomatic performance style</h3>\n<pre><code>function firstNonRepeat(str) {\n const counts = [], once = new Set();\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n if (counts[code] === 1) {\n counts[code] = 2;\n once.delete(code);\n } else if (!counts[code]) {\n counts[code] = 1;\n once.add(code);\n }\n }\n return once.size > 0 ? \n String.fromCharCode(once.values().next().value) : \n undefined;\n}\n</code></pre>\n<h3 id=\"performance-style-u5er\">Performance style</h3>\n<p>This style gains about 3-5% over the above rewrite across all input string sizes.</p>\n<p>I have added comments to explain why code is different than above.</p>\n<p><strong>Note</strong> that the <code>for (; i < str.length;)</code> is not faster than <code>for (i; i < str.length; i++)</code> but is just a compact source style to aid readability. I would normally use a <code>while</code> loop (eg <code>while(i < LEN) {</code>) but recent changes (Chrome) have impacted the relative performance of <code>for</code> and <code>while</code> loops to favor for loops.</p>\n<pre><code>function firstNonRepeat(str) {\n const counts = [], once = new Set(), ONE = 1, TWO = 2;\n var i = 0;\n for (; i < str.length ;) { // avoids the block scope overhead generated when using let.\n const code = str.charCodeAt(i++);\n const count = counts[code]; // to reduce the number of times we index the sparse array\n if (count === ONE) { // local scoped Constants are quicker than literals\n counts[code] = TWO; // local scoped Constant\n once.delete(code);\n } else if (count === undefined) { // to avoid the type coercion that !count has\n counts[code] = ONE; // local scoped Constant\n once.add(code);\n }\n }\n\n // To return the first item when it is not known if there are any entries\n // the following has the advantage over testing size and using .next().value\n // And I find the line below cleaner than the return in previous example.\n for (const code of once) { return String.fromCharCode(code) }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T21:29:43.127",
"Id": "264494",
"ParentId": "264474",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264494",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T10:57:40.157",
"Id": "264474",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "First non-repeating character in string"
}
|
264474
|
<p>I'm writing a web crawler, and want to store the parts of a URL to a database using Entity Framework.</p>
<p>Instead of trying to parse a URL into its component parts myself, I thought I could inherit from the <code>System.Uri</code> class and add a BaseEntity Id for the Entity Framework. But VS Code complains with a message like</p>
<blockquote>
<p>'<code>Hyperlink.<Class Field></code>' hides inherited member '<code>Uri.<Class Field></code>'. Use the <code>new</code> keyword if hiding was intended."</p>
</blockquote>
<p>The code works, and all the URL parts are saved to a database table. Should I be concerned with the VS Code message? Is this a good solution?</p>
<pre><code>public interface IBaseEntity {
[Key]
public int Id { get; set; }
}
</code></pre>
<pre><code>using System;
public class Hyperlink : Uri, IBaseEntity {
public int Id { get; set; }
public string OriginalString {
get {
return base.OriginalString;
}
private set {}
}
public string AbsolutePath {
get {
return base.AbsolutePath;
}
private set {}
}
public string Authority {
get {
return base.Authority;
}
private set {}
}
public string DnsSafeHost {
get {
return base.DnsSafeHost;
}
private set {}
}
public string Fragment {
get {
return base.Fragment;
}
private set {}
}
public string Host {
get {
return base.Host;
}
private set {}
}
public string HostNameType {
get {
return base.HostNameType.ToString();
}
private set {}
}
public string IdnHost {
get {
return base.IdnHost;
}
private set {}
}
public bool IsAbsoluteUri {
get {
return base.IsAbsoluteUri;
}
private set {}
}
public bool IsDefaultPort {
get {
return base.IsDefaultPort;
}
private set {}
}
public bool IsFile {
get {
return base.IsFile;
}
private set {}
}
public bool IsLoopback {
get {
return base.IsLoopback;
}
private set {}
}
public bool IsUnc {
get {
return base.IsUnc;
}
private set {}
}
public string LocalPath {
get {
return base.LocalPath;
}
private set {}
}
public string PathAndQuery {
get {
return base.PathAndQuery;
}
private set {}
}
public int Port {
get {
return base.Port;
}
private set {}
}
public string Query {
get {
return base.Query;
}
private set {}
}
public string Scheme {
get {
return base.Scheme;
}
private set {}
}
public string Segments {
get {
return String.Join(",", base.Segments);
}
private set {}
}
public bool UserEscaped {
get {
return base.UserEscaped;
}
private set {}
}
public string UserInfo {
get {
return base.UserInfo;
}
private set {}
}
private Hyperlink():base(""){}
public Hyperlink(string uriString) : base(uriString){}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:29:50.810",
"Id": "522367",
"Score": "1",
"body": "To me this feels... odd. I'd rather have some kind of factory class or whatever to convert a `Uri` into a `Hyperlink`. Also: how does this even work when you retrieve data from the DB?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T22:03:50.473",
"Id": "522388",
"Score": "0",
"body": "@BCdotWEB Actually, it doesn't work when retrieving data, just when saving it. I should've tested that before posting. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T07:22:48.310",
"Id": "524404",
"Score": "0",
"body": "@matt-in-the-hat Why don't you just simply store the Uri itself? `public class Hyperlink: IBaseEntity { public int Id { get; set; } public Uri SiteUri { get; set; } }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T12:00:31.403",
"Id": "524486",
"Score": "1",
"body": "@PeterCsala Thank you. I ended up doing just that. I was over complicating it"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T13:18:29.813",
"Id": "264477",
"Score": "0",
"Tags": [
"c#",
"entity-framework-core"
],
"Title": "Decompose URL components and store into a database"
}
|
264477
|
<p>I wrote a program for Conway's Game Of Life in Java. Are there any improvements I could make?</p>
<p>main class:</p>
<pre><code>package main;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
public class GameOfLife {
static Board board;
static Window window;
static Input input = new Input();
static BufferStrategy bs;
//board and window setup
public static void start() {
window = new Window("game", 800, 500);
board = new Board(window.getCanvas().getWidth(), window.getCanvas().getHeight());
board.setUp();
}
//renders the board
public static void render() {
bs = window.getCanvas().getBufferStrategy();
if(bs == null) {
window.getCanvas().createBufferStrategy(2);
}
bs = window.getCanvas().getBufferStrategy();
window.getCanvas().setBackground(Color.black);
window.requestFocusInWindow();
Graphics2D g2d = (Graphics2D) bs.getDrawGraphics();
g2d.clearRect(0, 0, window.getCanvas().getWidth(), window.getCanvas().getHeight());
g2d.setColor(Color.white);
for (int i = 0; i < board.getBoard().length; i++) {
for (int j = 0; j < board.getBoard()[0].length; j++) {
if (board.getState(i, j, board.getBoard())) {
g2d.fillRect(i * board.getCellSize(), j * board.getCellSize(), board.getCellSize(),
board.getCellSize());
}
}
}
g2d.dispose();
bs.show();
}
//timing for framerate
public static void pause(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//main loop
public static void main(String[] args) {
start();
while(true) {
long start = System.nanoTime();
if(!input.getPaused()) {
board.updateBoard();
}
render();
long deltatime = (System.nanoTime() - start) / 1000000;
if((16 - deltatime) >= 0) {
pause(16 - deltatime);
}
}
}
}
</code></pre>
<p>board class:</p>
<pre><code>package main;
import java.util.Random;
public class Board {
private boolean[][] board;
private boolean[][] newboard;
int cellsize = 4;
Random random = new Random();
public Board(int width, int height) {
board = new boolean[width/cellsize][height/cellsize];
newboard = new boolean[width/cellsize][height/cellsize];
}
//getters and setters
public boolean[][] getBoard() {
return this.board;
}
public boolean getState(int x, int y, boolean[][] board) {
if(x < 0 || y < 0 || x > board.length-1 || y > board[0].length-1) {
return false;
}
return board[x][y];
}
public int getCellSize() {
return this.cellsize;
}
//counts number of alive cells next to cell
public int countNeighbours(int x, int y) {
int count = 0;
for(int i = x-1; i <= x+1; i++) {
for(int j = y-1; j <= y+1; j++) {
if(i != x || j != y) {
if (getState(i, j, board)) {
count++;
}
}
}
}
return count;
}
//returns state of cell in the next generation
public boolean getNewState(int x, int y) {
int count = countNeighbours(x, y);
boolean state = getState(x, y, board);
if(state && count > 1 && count < 4) {
return true;
}
else if(!state && count == 3) {
return true;
}
return false;
}
//changes states to those of the next generation
public void updateBoard() {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
newboard[i][j] = getNewState(i, j);
}
}
for(int x = 0; x < newboard.length; x++) {
for(int y = 0; y < newboard[x].length; y++) {
board[x][y] = getState(x, y, newboard);
}
}
}
//assigns every cell a random state
public void setUp() {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
board[i][j] = random.nextBoolean();
}
}
}
}
</code></pre>
<p>window class:</p>
<pre><code>package main;
import java.awt.Canvas;
import java.awt.Point;
import javax.swing.JFrame;
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private Canvas canvas;
static Input input = new Input();
//window setup
public Window(String title, int width, int height) {
setSize(width, height);
setTitle(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocation(new Point(0, 0));
setVisible(true);
canvas = new Canvas();
canvas.setSize(width, height);
canvas.setFocusable(true);
add(canvas);
addKeyListener(input);
}
//getters and setters
public Canvas getCanvas() {
return canvas;
}
public void setCanvas(Canvas canvas) {
this.canvas = canvas;
}
}
</code></pre>
<p>input class:</p>
<pre><code>package main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Input implements KeyListener {
private static boolean paused;
public Input() {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
paused = !paused;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
//getters and setters
public boolean getPaused() {
return paused;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to the site! This looks good so far, here's a couple of smaller tips:</p>\n<h2 id=\"board.java-vrms\">Board.java</h2>\n<ul>\n<li><p>The cellsize doesn't change, so why not make it a constant like this:<br />\n<code>public static final int CELLSIZE = 4;</code><br />\nThis also makes the getter obsolete, as you can access that field using <code>Board.CELLSIZE</code></p>\n</li>\n<li><p><code>getNewState()</code> uses a boolean <code>state</code>. Renaming that to something like <code>isAlive</code> makes the if-clauses a bit easier to read.</p>\n</li>\n<li><p>You only use the <code>Random</code> for the board setup, so there's no reason for it to be a (package-private) attribute of <code>Board</code>. Move it into <code>setUp()</code>.</p>\n</li>\n</ul>\n<h2 id=\"input.java-din8\">Input.java</h2>\n<ul>\n<li><p>Boolean getters are almost always called <code>isX()</code> instead of <code>getX()</code>, so <code>getPaused()</code> should be renamed to <code>isPaused()</code></p>\n</li>\n<li><p>Make <code>isPaused()</code> a static method. This way, you can access the method using <code>Input.isPaused()</code> in <code>GameOfLife.java</code> without having to do <code>static Input input = new Input();</code> This also removes the unnecessary static member and the instance of <code>Input</code>.</p>\n</li>\n</ul>\n<h2 id=\"window.java-fefl\">Window.java</h2>\n<ul>\n<li><p><code>setLocation</code> can also be called with two <code>int</code>s instead of a <code>Point</code>. This looks a bit more clean and saves the import</p>\n</li>\n<li><p>Tip: you can center the window on the screen using <code>setLocationRelativeTo(null)</code></p>\n</li>\n<li><p><code>setVisible(true)</code> is usually the last method called in the constructor. If you had a slower PC or a more complicated GUI, making the window visibile too early results in the user seeing the window build itself up and/or move around/resize.</p>\n</li>\n<li><p><code>input</code> doesn't need to be a static attribute of the <code>Window</code> class. Writing<br />\n<code>addKeyListener(new Input());</code><br />\nworks just as well.</p>\n</li>\n</ul>\n<h2 id=\"gameoflife.java-81ut\">GameOfLife.java</h2>\n<ul>\n<li>Move the <code>BufferStrategy</code>-related things into <code>start()</code>. I don't think that you need to call these every frame. I'd write something like this:</li>\n</ul>\n<pre><code> public static void start() {\n ...\n board.setUp();\n \n if(window.getCanvas().getBufferStrategy() == null) {\n window.getCanvas().createBufferStrategy(2);\n }\n bs = window.getCanvas().getBufferStrategy();\n }\n</code></pre>\n<ul>\n<li><p><code>(16 - deltatime) >= 0</code> is a bit weird to read, <code>deltatime <= 16</code> is more intuitive. Also, if <code>deltatime == 16</code>, you'll sleep for 0 seconds; I'd put a <code><</code> instead of a <code><=</code> there.</p>\n</li>\n<li><p>16 is a magic number. Don't use these, instead consider doing something that's more descriptive:</p>\n</li>\n</ul>\n<pre><code>private static final int FPS = 60\nprivate static final int FRAMETIME_MS = 1000/FPS;\n</code></pre>\n<h2 id=\"general-tip-5c67\">General tip</h2>\n<p>Consider the visibility of your attributes. Make everything <code>private</code> that doesn't need to be seen or has a getter and setter. Also consider the scope: Does this variable need to be an attribute or do you only need it for one method? If so, move it in there.</p>\n<p>Something about the Board/Window classes seems a bit off to me. I think that some things like the <code>window.getCanvas(). ...</code> could be cleaned up by making <code>Board</code> extend <code>Canvas</code> or making <code>Board</code> an attribute of <code>Window</code>, or even both. Perhaps I'll look at it again later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:35:05.043",
"Id": "265505",
"ParentId": "264481",
"Score": "1"
}
},
{
"body": "<p><code>Input</code> doesn't need to be a separate source file when you can use an anonymous inner class that implements <code>KeyListener</code>. When you do this, it becomes easier to put the variable <code>paused</code> where it belongs (i.e. not in the class handling the input). See my edits below for how to do it.</p>\n<p>Similar thing with <code>Window</code> - it doesn't need to be a separate file, and we don't even need to keep a reference to the <code>JFrame</code> for the moment, though we might want to later.</p>\n<p>You can move the cell size out of the <code>Board</code> class - the class with the game logic shouldn't be concerned with how it gets drawn. In fact, <code>Board</code> is actually the game logic itself, maybe that class should be renamed to <code>GameOfLife</code> and your main class renamed something else.</p>\n<p>Though the code still does mostly the exact same stuff, I have made a bunch of other simplifying changes, so read through my version carefully if you are interested.</p>\n<pre class=\"lang-java prettyprint-override\"><code>package main;\n\nimport java.awt.Canvas;\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\nimport java.awt.image.BufferStrategy;\n\nimport javax.swing.JFrame;\n\npublic class GameOfLifeDemo {\n\n private static final long FRAME_TIME = 1000 / 24;\n\n GameOfLife game;\n boolean paused = false;\n\n Canvas canvas = new Canvas();\n BufferStrategy bufferStrategy;\n int cellSize;\n\n GameOfLifeDemo(String title, int width, int height, int cellSize) {\n this.cellSize = cellSize;\n this.game = new GameOfLife(width / cellSize, height / cellSize);\n\n canvas.setBackground(Color.black);\n canvas.setSize(height, width);\n canvas.setFocusable(true);\n canvas.addKeyListener(new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n if (e.getKeyCode() == KeyEvent.VK_SPACE) {\n paused = !paused;\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n }\n });\n\n JFrame window = new JFrame();\n window.setSize(width, height);\n window.setTitle(title);\n window.setResizable(false);\n window.add(canvas);\n window.setVisible(true);\n\n canvas.createBufferStrategy(2);\n bufferStrategy = canvas.getBufferStrategy();\n canvas.requestFocusInWindow();\n }\n\n private void render() {\n Graphics graphics = bufferStrategy.getDrawGraphics();\n graphics.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());\n graphics.setColor(Color.white);\n for (int i = 0; i < game.getWidth(); i++) {\n for (int j = 0; j < game.getHeight(); j++) {\n if (game.getState(i, j)) {\n graphics.fillRect(i * cellSize, j * cellSize, cellSize, cellSize);\n }\n }\n }\n graphics.dispose();\n bufferStrategy.show();\n }\n\n public void run() throws InterruptedException {\n while (true) {\n long start = System.nanoTime();\n if (!paused) {\n game.tick();\n render();\n }\n long deltatime = (System.nanoTime() - start) / 1000000;\n\n if ((FRAME_TIME - deltatime) > 0) {\n Thread.sleep(FRAME_TIME - deltatime);\n }\n }\n }\n\n public static void main(String[] args) throws InterruptedException {\n new GameOfLifeDemo("Game o' life", 800, 600, 4).run();\n }\n\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>package main;\n\nimport java.util.Random;\n\npublic class GameOfLife {\n\n private final static Random RANDOM = new Random();\n\n private final int height;\n private final int width;\n private boolean[][] board;\n private boolean[][] nextboard;\n\n public GameOfLife(int width, int height) {\n this.height = height;\n this.width = width;\n board = new boolean[width][height];\n nextboard = new boolean[width][height];\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n board[i][j] = RANDOM.nextBoolean();\n }\n }\n }\n\n public int getWidth() {\n return width;\n }\n\n public int getHeight() {\n return height;\n }\n\n public boolean getState(int x, int y) {\n return board[x][y];\n }\n\n private int countNeighbours(int x, int y) {\n int count = 0;\n for (int i = x - 1; i <= x + 1; i++) {\n for (int j = y - 1; j <= y + 1; j++) {\n if (i == x && j == y) {\n continue;\n }\n if (i < 0 || i >= width || j < 0 || j >= height) {\n continue;\n }\n if (board[i][j]) {\n count++;\n }\n }\n }\n return count;\n }\n\n private boolean nextCellState(int x, int y) {\n int neighbourCount = countNeighbours(x, y);\n if (board[x][y] && neighbourCount > 1 && neighbourCount < 4) {\n return true;\n } else if (!board[x][y] && neighbourCount == 3) {\n return true;\n }\n return false;\n }\n\n public void tick() {\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[i].length; j++) {\n nextboard[i][j] = nextCellState(i, j);\n }\n }\n\n /*\n * Just swap the references to start using the newboard arrays as the current\n * board arrays. The old arrays will be used to construct the next iteration.\n */\n boolean[][] temp = board;\n board = nextboard;\n nextboard = temp;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T16:08:58.640",
"Id": "524448",
"Score": "0",
"body": "+1 especially for recommending to move the cell size out of the game logic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:56:32.607",
"Id": "265515",
"ParentId": "264481",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T14:40:24.040",
"Id": "264481",
"Score": "4",
"Tags": [
"java",
"game-of-life"
],
"Title": "Game Of Life program in Java"
}
|
264481
|
<p>I have a dataframe which contains information of programmers like: country, programming languages. etc:</p>
<pre class="lang-py prettyprint-override"><code>COUNTRY PROGRAMMING_LANGUAGE
usa javascript
uk python;swift;kotlin
india python;ruby
usa c++;c;assembly;python
canada java;php;golang;ruby
angola python;c#
india c;java
brazil javascript;php
canada php;sql
india c#;java
brazil java;javascript
russia java;kotlin
china javascript
usa python;c;c++
india ruby
australia javascrit
india php;java
china swift;kotlin
russia php;sql
brazil firebase;kotlin
uk sql;firebase
canada python;c
portugal python;php
</code></pre>
<p>My program should display on a dataframe:</p>
<ul>
<li>All countries;</li>
<li>How many people from each country use python;</li>
</ul>
<pre class="lang-py prettyprint-override"><code>COUNTRY KNOWS_PYTHON
usa 2
uk 1
india 1
angola 1
canada 1
portugal 1
russia 0
brazil 0
australia 0
china 0
</code></pre>
<p>Please share your opinion about my algorithm, in any possible way to improve it:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
</code></pre>
<pre class="lang-py prettyprint-override"><code>pd.set_option('display.max_columns',100)
pd.set_option('display.max_rows',100)
</code></pre>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
"PROGRAMMER":np.arange(0,25),
"AGE":np.array([22,30,np.nan,25,19,27,28,26,33,18,14,np.nan,29,35,19,30,29,24,21,52,np.nan,24,np.nan,18,25],dtype=np.float16),
"COUNTRY":['uSa','Uk','india','usa','Canada','AngOla','India','braZil','canada','india','brazil','russia','china','usa','india',np.nan,'Australia','india','China','russia','brazil','uk','canada','portugal','ChiNa'],
"PROGRAMMING_LANGUAGE":['JAVASCRIPT','python;swift;kotlin','python;ruby','c++;c;assembly;python','java;php;golang;ruby','python;c#','c;java','javascript;php','php;sql','c#;java','java;javascript','java;kotlin','javascript','python;c;c++','ruby',np.nan,'javascrit','php;java','swift;kotlin','php;sql','firebase;kotlin','sql;firebase','python;C','python;php',np.nan],
"GENDER":['male','female','male','male','female','female',np.nan,'male','female','male','male','female','female',np.nan,'female','male','male','male','female','male',np.nan,'male','female','male','male'],
"LED_ZEPPELIN_FAN":['yes','YES','yes','yes','yes','yes','yes','yes','yes','yes','yes','yes','yes',np.nan,'yes','yes','yes','yes','yes','yes','yes','yes','yes','yes','yes'],
})
</code></pre>
<pre class="lang-py prettyprint-override"><code>#Replacing NaN value as 'missing'
df = df.fillna("missing")
</code></pre>
<pre class="lang-py prettyprint-override"><code>filt = (df['COUNTRY'] != "missing") & (df['PROGRAMMING_LANGUAGE'] != "missing")
</code></pre>
<pre class="lang-py prettyprint-override"><code>table = df.loc[filt,['COUNTRY','PROGRAMMING_LANGUAGE']]
</code></pre>
<pre class="lang-py prettyprint-override"><code>table = table.applymap(str.lower)
table
</code></pre>
<pre class="lang-py prettyprint-override"><code>#This is just a list with all countries(without duplicates), and it will be used later
total_countries = list(set(table['COUNTRY']))
</code></pre>
<pre class="lang-py prettyprint-override"><code>#Filter rows that contain python as programming language
filt = table['PROGRAMMING_LANGUAGE'].str.contains('python',na=False)
</code></pre>
<pre class="lang-py prettyprint-override"><code>table_python = table.loc[filt,['COUNTRY','PROGRAMMING_LANGUAGE']]
</code></pre>
<pre class="lang-py prettyprint-override"><code>#Getting all countries that have programmers that use python(without duplicates)
countries = table_python['COUNTRY'].value_counts().index.tolist()
</code></pre>
<pre class="lang-py prettyprint-override"><code>#Getting the number of programmers from each country that use python(including duplicates from each country)
quantities = []
for i in range(0,len(countries)):
quantities.append(table_python['COUNTRY'].value_counts()[i])
</code></pre>
<pre class="lang-py prettyprint-override"><code>#Comparing the list that contains all countries, with a list of countries that use python.
#If there is a country that doesn't have programmers that use python, these will be added to final with 0 as one of the values
for i in total_countries:
if i not in countries:
countries.append(i)
quantities.append(0)
</code></pre>
<pre class="lang-py prettyprint-override"><code>table_python = pd.DataFrame({"COUNTRY":countries,"KNOWS_PYTHON":quantities})
</code></pre>
<pre class="lang-py prettyprint-override"><code>table_python.set_index('COUNTRY',inplace=True)
</code></pre>
<pre class="lang-py prettyprint-override"><code>table_python
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The construction of your dataframe could be improved; your <code>PROGRAMMER</code> column looks like it should be the index, and <code>np.float16</code> is not a good representation for what looks to be integer data.</li>\n<li>Not a good idea to <code>fillna</code> with a string and then compare to that string; instead operate on the NaN values directly</li>\n<li>Should not be doing your own <code>list</code>, <code>set</code> or <code>loops</code>; this problem is fully vectorizable</li>\n<li>Your <code>df['PROGRAMMING_LANGUAGE'] != "missing"</code> is counterproductive; rather than filtering away one country with a missing programming language, you'd want to count it as "0"</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame({\n "PROGRAMMER": np.arange(0, 25),\n "AGE": np.array(\n [\n 22, 30, np.nan, 25, 19, 27, 28, 26, 33, 18, 14, np.nan, 29, 35, 19, 30, 29, 24, 21, 52,\n np.nan, 24, np.nan, 18, 25,\n ],\n dtype=np.float16,\n ),\n "COUNTRY": [\n 'uSa', 'Uk', 'india', 'usa', 'Canada', 'AngOla', 'India', 'braZil', 'canada', 'india',\n 'brazil', 'russia', 'china', 'usa', 'india', np.nan, 'Australia', 'india', 'China',\n 'russia', 'brazil', 'uk', 'canada', 'portugal', 'ChiNa',\n ],\n "PROGRAMMING_LANGUAGE": [\n 'JAVASCRIPT', 'python;swift;kotlin', 'python;ruby', 'c++;c;assembly;python',\n 'java;php;golang;ruby', 'python;c#', 'c;java', 'javascript;php', 'php;sql', 'c#;java',\n 'java;javascript', 'java;kotlin', 'javascript', 'python;c;c++', 'ruby', np.nan, 'javascrit',\n 'php;java', 'swift;kotlin', 'php;sql', 'firebase;kotlin', 'sql;firebase', 'python;C',\n 'python;php', np.nan,\n ],\n "GENDER": [\n 'male', 'female', 'male', 'male', 'female', 'female', np.nan, 'male', 'female', 'male',\n 'male', 'female', 'female', np.nan, 'female', 'male', 'male', 'male', 'female', 'male',\n np.nan, 'male', 'female', 'male', 'male',\n ],\n "LED_ZEPPELIN_FAN": [\n 'yes', 'YES', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes',\n np.nan, 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes',\n ],\n})\n\n# Get rid of all columns we don't care about for the final sum\ndf.drop(['PROGRAMMER', 'AGE', 'GENDER', 'LED_ZEPPELIN_FAN'], axis=1, inplace=True)\n\n# Don't count countries that are undefined\ndf = df[df.COUNTRY.notna()]\n\n# Standard case for both string columns\ndf['PROGRAMMING_LANGUAGE'] = df.PROGRAMMING_LANGUAGE.str.casefold()\ndf['COUNTRY'] = df.COUNTRY.str.title()\n\n# Add a boolean column we'll use to apply a grouped sum\ndf['KNOWS_PYTHON'] = df.PROGRAMMING_LANGUAGE.str.contains('python', na=False)\n\nsums = df.groupby(['COUNTRY']).sum()\nsums.sort_values(by=['KNOWS_PYTHON'], ascending=False, inplace=True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T20:32:48.597",
"Id": "524529",
"Score": "1",
"body": "https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T03:43:21.683",
"Id": "265533",
"ParentId": "264482",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T15:23:30.683",
"Id": "264482",
"Score": "1",
"Tags": [
"python-3.x",
"pandas",
"jupyter"
],
"Title": "Filtering data on a dataframe, Pandas-Jupyter"
}
|
264482
|
<p>The code below works, but it seems it could be done better. Is there a better/more efficient way to do this?</p>
<p>Given:</p>
<ol>
<li>All days off ("relief days") will be consecutive.</li>
<li>Relief days will be imported as a string. Days of week are represented by their first letter. "S" can represent Saturday or Sunday, "T" can represent Tuesday or Thursday. I.e., someone with Sat/Sun off would be "SS", someone with Tue/Wed/Thu off would be "TWT".</li>
<li>Depending on how many hours a day they work, they'll either have 2, 3, or 4 days off.</li>
</ol>
<p>The existing code:</p>
<pre><code> public static String getReliefDays(){
Map<String, String> user = new HashMap<>(); //test example user
user.put("name", "Schmoe, Joe");
user.put("employeeNo", "123456");
user.put("startTime", "0800");
user.put("endTime", "1700");
user.put("reliefDays", "TF");
String rd = (String) user.get("reliefDays");
int rdLength = rd.length();
String reliefDays = "";
String fl = rd.substring(0, 1); //first letter in the days off string
String sl = rd.substring(1, 2); //second letter in the days off string
switch (fl) {
case "S":
if (sl.equalsIgnoreCase("M")) {
reliefDays = "SUN MON";
if (rdLength == 3) {
reliefDays += " TUE";
}
if (rdLength == 4) {
reliefDays += " WED";
}
}else{
reliefDays = "SAT SUN";
if (rdLength == 3) {
reliefDays += " MON";
}
if (rdLength == 4) {
reliefDays += " TUE";
}
}
break;
case "M":
reliefDays = "MON TUE";
if (rdLength == 3) {
reliefDays += " WED";
}
if (rdLength == 4) {
reliefDays += " THU";
}
break;
case "T":
if (sl.equalsIgnoreCase("W")) {
reliefDays = "TUE WED";
if (rdLength == 3) {
reliefDays += " THU";
}
if (rdLength == 4) {
reliefDays += " FRI";
}
} else {
reliefDays = "THU FRI";
if (rdLength == 3) {
reliefDays += " SAT";
}
if (rdLength == 4) {
reliefDays += " SUN";
}
}
break;
case "W":
reliefDays = "WED THU";
if (rdLength == 3) {
reliefDays += " FRI";
}
if (rdLength == 4) {
reliefDays += " SAT";
}
break;
case "F":
reliefDays = "FRI SAT";
if (rdLength == 3) {
reliefDays += "SUN";
}
if (rdLength == 4) {
reliefDays += " MON";
}
break;
}
return reliefDays;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:40:19.897",
"Id": "522369",
"Score": "0",
"body": "Do you have a method header for this? It's best to show complete, runnable code, perhaps with a few test cases in a `main` to help clarify the behavior at a glance -- I'm not sure what format `String rd` is or what the output should be for different inputs. How are you supposed to differentate between Tu/Th and Sa/Su if `rd` is single-letter abbreviations? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T17:38:29.423",
"Id": "522371",
"Score": "0",
"body": "@ggorlen From the conditions, rd will never be a single character and will be consecutive days. I'm kind of at the mercy of the data I'm being sent, and SMTWTFS is the format that I'm sent for days of the week. I've updated the question to make the code snippet a method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T18:58:05.297",
"Id": "522376",
"Score": "0",
"body": "This still doesn't fit site standards. Obviously you would never use this method for anything. It has its test data hard coded inside it. You claim that the code \"works\" but it's obvious that it doesn't do anything. What we would want to see is how the code would actually be called (apparently not written yet) and how the results would be used (apparently not written yet). As written, a better way to write the current code would be `return \"SAT SUN\";` which seems rather useless (not to mention probably wrong, as \"THU FRI\" would seem a more likely result)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:28:29.263",
"Id": "522380",
"Score": "0",
"body": "@mdfst13: I saw the error I had for Thursday. Valid point, good catch, thank you. As for the rest of your comment, I was looking for a more efficient or condensed way to rewrite the ~80 lines of code in a project with ~8000 lines of code. I can add the code that generates the HTML that the function is used in and the servlet that delivers said html and the database code that pulls data from three disparate databases, but that seemed excessive...so I just put the function that I needed help with on here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T21:29:39.857",
"Id": "522386",
"Score": "0",
"body": "But this isn't the actual function (called methods in Java). It's a modified version with test code added. For what you are attempting, the thing to do would be to write unit tests for the code. That would both help (because unit tests verify functionality in the face of changes) and make it easier for us to understand what you are doing. But a larger problem here is that both the input and output representations are not best practices. In particular, why do you want output like `\"SAT SUN MON TUE\"`? As opposed to `[DaysOfWeek.SATURDAY, 4]` or something else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T05:43:27.220",
"Id": "524401",
"Score": "0",
"body": "Is this code really working correctly and posted the way it was written? The indentation for the `\"S\"` case is weird, and the `\"W\"` case flows through to `\"T\"` without a `break`."
}
] |
[
{
"body": "<p>Your indentation has gone wrong here, and it's confusing:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (sl.equalsIgnoreCase("M")) {\n reliefDays = "SUN MON";\n if (rdLength == 3) {\n reliefDays += " TUE";\n }\n if (rdLength == 4) {\n reliefDays += " WED";\n }\n }\n</code></pre>\n<p>Let your IDE help and auto-format your code as you work.</p>\n<p>Other than that, you can get better feedback when you post not only the code you want feedback on but also the surrounding context, so that you can get feedback on how you are applying OOP and using the correct signatures.</p>\n<p>My version is below, see how I've divided up the logic.</p>\n<p>I figured that this job of creating a <code>String</code> with the weekday short names would belong to the <code>User</code> so I put it there.</p>\n<p>I also thought that a <code>Weekday</code> class might know how to deal with the problem of disambiguating weekdays as single letters in a <code>String</code> that represents week days. But I can also see the argument for this to belong to <code>User</code> since that sort of <code>String</code> is known to be specifically used when creating <code>User</code>s. In the end, I decided that <code>Weekday</code> would expose the logic, and <code>User</code> will expose <code>setReliefDays</code> taking a <code>String</code>, which would delegate to the logic in <code>Weekday</code>, but then this can easily be changed if the implementation of <code>User</code> needs to change.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ReliefDays {\n\n public static void main(String[] args) {\n User joe = new User();\n joe.name = "Schmoe, Joe";\n joe.employeeNo = "123456";\n joe.startTime = "0800";\n joe.endTime = "1700";\n joe.setReliefDays("TFSS");\n System.out.println(joe.reliefDaysShortNames());\n }\n\n static class User {\n String name;\n String employeeNo;\n String startTime;\n String endTime;\n Weekday[] reliefDays;\n\n /**\n * Returns a string containing the short names of this user's relief days\n * seperated by spaces.\n * \n * For example, "SAT SUN MON".\n */\n public String reliefDaysShortNames() {\n StringBuilder shortDays = new StringBuilder();\n for (int i = 0; i < reliefDays.length - 1; i++) {\n shortDays.append(reliefDays[i].shortName);\n shortDays.append(" ");\n }\n shortDays.append(reliefDays[reliefDays.length - 1].shortName);\n return shortDays.toString();\n }\n\n /**\n * Set this user's relief days based on a string of characters representing\n * consecutive days.\n * \n * For example, when days is "MT", this user's relief days are set to\n * {Weekday.MONDAY, Weekday.TUESDAY}.\n */\n public void setReliefDays(String days) {\n reliefDays = Weekday.parseWeekdays(days);\n }\n }\n\n static enum Weekday {\n MONDAY('M', "MON"),\n TUESDAY('T', "TUE"),\n WEDNESDAY('W', "WED"),\n THURSDAY('T', "THU"),\n FRIDAY('F', "FRI"),\n SATURDAY('S', "SAT"),\n SUNDAY('S', "SUN");\n\n char letter;\n String shortName;\n\n Weekday(char letter, String shortName) {\n this.letter = letter;\n this.shortName = shortName;\n }\n\n /**\n * Given at least two characters representing consecutive week days, returns an\n * array of those weekdays of the same size and in the same order.\n */\n public static Weekday[] parseWeekdays(String s) {\n Weekday[] weekDays = new Weekday[s.length()];\n Weekday currentDay = firstWeekdayOfPair(s.substring(0, 2));\n Weekday nextDay;\n\n weekDays[0] = currentDay;\n for (int i = 1; i < s.length(); i++) {\n nextDay = currentDay.nextWeekday();\n if (s.charAt(i) != nextDay.letter) {\n throw new IllegalArgumentException("Unexpected sequence of days: "\n + currentDay.letter + s.charAt(i));\n }\n weekDays[i] = nextDay;\n currentDay = nextDay;\n }\n return weekDays;\n }\n\n private static Weekday firstWeekdayOfPair(String s) {\n switch (s) {\n case "MT":\n return MONDAY;\n case "TW":\n return TUESDAY;\n case "WT":\n return WEDNESDAY;\n case "TF":\n return THURSDAY;\n case "FS":\n return FRIDAY;\n case "SS":\n return SATURDAY;\n case "SM":\n return SUNDAY;\n default:\n throw new IllegalArgumentException("Unexpected weekday pair: " + s);\n }\n }\n\n private Weekday nextWeekday() {\n switch (this) {\n case MONDAY:\n return TUESDAY;\n case TUESDAY:\n return WEDNESDAY;\n case WEDNESDAY:\n return THURSDAY;\n case THURSDAY:\n return FRIDAY;\n case FRIDAY:\n return SATURDAY;\n case SATURDAY:\n return SUNDAY;\n case SUNDAY:\n return MONDAY;\n default:\n throw new IllegalArgumentException("Unexpected day: " + this.toString());\n }\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:21:57.147",
"Id": "524413",
"Score": "1",
"body": "Nice solution. One remark is that `nextWeekday` can be replaced by playing with the ordinal value of the enum. Something like; `values[this.ordinal()>values.length?0:this.ordinal()+1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:36:34.037",
"Id": "524420",
"Score": "0",
"body": "THIS is what I was looking for. Much thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T23:35:07.217",
"Id": "264496",
"ParentId": "264483",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264496",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T15:34:53.717",
"Id": "264483",
"Score": "0",
"Tags": [
"java",
"datetime"
],
"Title": "Interpreting abbreviations for days of the week such that they are consecutive days"
}
|
264483
|
<p>I created this sample and wanted any advice on how to make this code; cleaner, more effective, just overall better! I need to add the key word <code>and</code> only if the NegativeScheduleCalendar enum is before the ScheduleCalendar enum. The only way I was able to do this was to loop the list and checking if they are after each other. So the data has this <code>on Days - 7 and -1</code> and there is a ScheduleCalendar enum with data like this <code>on Days 1 - 21 and 25</code> the code below will add the <code>and</code> word.</p>
<pre class="lang-cs prettyprint-override"><code>int x = 0;
foreach (SentencePartTextHolder name in compiledSentenceParts)
{
if (name.Type == SentencePartType.NegativeScheduleCalendar)
{
x = x + 1;
if (x == 2)
{
string Text = string.Format("{0} {1}", NegativePositiveScheduleCalendarDelimiter, name.Text);
name.Text = Text;
}
}
else if (name.Type == SentencePartType.ScheduleCalendar)
{
x = x + 1;
if (x == 2){
string Text = string.Format("{0} {1}", NegativePositiveScheduleCalendarDelimiter, name.Text);
name.Text = Text;
}
}
else
{
x = 0;
}
}
</code></pre>
<p>Sample project
<a href="https://dotnetfiddle.net/mCpBI9" rel="nofollow noreferrer">https://dotnetfiddle.net/mCpBI9</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:24:28.727",
"Id": "522365",
"Score": "0",
"body": "Why do you use `string.Format`? Why do `string Text =` instead of simply assigning directly? Why write `x = x + 1`?"
}
] |
[
{
"body": "<ul>\n<li><p>You differentiate between 3 cases, but two of them do exactly the same thing. Instead, use a logical OR (<code>||</code> in C#) to combine the two conditions.</p>\n</li>\n<li><p>Use string interpolation instead of <code>String.Format</code>.</p>\n</li>\n<li><p>You can eliminate the temp variable <code>Text</code>.</p>\n</li>\n<li><p>Use the increment operator <code>++</code> to increment <code>x</code>.</p>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>int x = 0;\n\nforeach (SentencePartTextHolder name in compiledSentenceParts)\n{\n Console.WriteLine(name);\n\n if (name.Type == SentencePartType.NegativeScheduleCalendar ||\n name.Type == SentencePartType.ScheduleCalendar)\n {\n x++;\n if (x == 2)\n {\n name.Text = $"{NegativePositiveScheduleCalendarDelimiter} {name.Text}";\n }\n }\n else\n {\n x = 0;\n }\n}\n</code></pre>\n<hr />\n<p>If you are using C# 9.0, you can use pattern matching to simplify the condition:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (name.Type is SentencePartType.NegativeScheduleCalendar or\n SentencePartType.ScheduleCalendar)\n</code></pre>\n<p>Note that you can switch to it like this in framework versions earlier than .NET 5: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version\" rel=\"nofollow noreferrer\">C# language versioning</a>.</p>\n<p>Yet another possibility is to use a switch statement:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>switch (name.Type)\n{\n case SentencePartType.NegativeScheduleCalendar:\n case SentencePartType.ScheduleCalendar:\n x++;\n if (x == 2)\n {\n name.Text = $"{NegativePositiveScheduleCalendarDelimiter} {name.Text}";\n }\n break;\n default:\n x = 0;\n break;\n}\n</code></pre>\n<hr />\n<p>Incrementing <code>x</code> and then testing it can be combined by using the pre-increment operator</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (++x == 2)\n</code></pre>\n<p>Note that the <code>++</code> must be placed before the <code>x</code>, so that the already incremented <code>x</code> will be tested. If you write <code>if (x++ == 2)</code> then first <code>x</code> is compared to <code>2</code> and then only it is incremented.</p>\n<hr />\n<p><strong>My final solution</strong></p>\n<p>An alternative to counting the lines is to store the last <code>SentencePartType</code> and to compare it with the current one. Let us declare a little helper function:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static bool IsCalendarType(SentencePartType type)\n{\n return type is SentencePartType.NegativeScheduleCalendar or\n SentencePartType.ScheduleCalendar;\n}\n</code></pre>\n<p>Of course, you can also use the traditional Boolean logic here if you are working with a version prior to C# 9.0.</p>\n<p>Now, we can rewrite the loop as</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var lastType = SentencePartType.Undefined;\nforeach (SentencePartTextHolder name in compiledSentenceParts)\n{\n if (IsCalendarType(lastType) && IsCalendarType(name.Type))\n {\n name.Text = $"{NegativePositiveScheduleCalendarDelimiter} {name.Text}";\n }\n lastType = name.Type;\n}\n</code></pre>\n<p>This looks much cleaner and is easier to understand. The expression <code>IsCalendarType(lastType) && IsCalendarType(name.Type)</code> expresses exactly what we are looking for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T16:37:43.953",
"Id": "264486",
"ParentId": "264484",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "264486",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T15:45:55.087",
"Id": "264484",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Compare enum's and adding key word"
}
|
264484
|
<p>I am trying to improve my file upload handler filter.</p>
<h2 id="environment-gfny">Environment</h2>
<p>Since any client-side validation is easily circumvented, there is none in this code, for ease of testing. Not even an <code>accept="image/*"</code> on the <code><input></code> element. Production code will include some client side validation.</p>
<p>The upload handler is set up to first check that the standard php file upload criteria are met, and then goes on to validate that the upload file is an image and can be saved.</p>
<p>The Error handler is simplifiedl</p>
<h2 id="inspiration-gpui">Inspiration</h2>
<p>I realized that my handler was vulnerable after completing <a href="https://tryhackme.com/room/uploadvulns" rel="nofollow noreferrer">the upload vulnerabilities room in tryhackme</a> since I originally only checked the extension and the mime type.</p>
<h2 id="known-possible-pitfalls-znaq">Known possible pitfalls:</h2>
<ul>
<li>non-image files like<code>.php</code> can still be uploaded with null char in name <code>.php%00.png</code> with a spoofed header (e.g. <code>image/png</code> instead of <code>application/x-php</code>), but must have correct magic number.</li>
<li>No check of whether the header matches the extension.
<ul>
<li>Fix1: scan for strings like <code>/bin/bash</code> and <code><?php</code>?</li>
<li>check for null bytes in file names?</li>
</ul>
</li>
</ul>
<p>I put the code on <a href="https://github.com/JoSSte/phpFileUploadHandler" rel="nofollow noreferrer">github</a> as well...</p>
<pre class="lang-php prettyprint-override"><code>function is_image($filename) {
// PNG, GIF, JFIF JPEG, EXIF JPEF (respectively)
$allowed = array('89504E47', '47494638', 'FFD8FFE0', 'FFD8FFE1');
$handle = fopen($filename, 'r');
$bytes = strtoupper(bin2hex(fread($handle, 4)));
fclose($handle);
return in_array($bytes, $allowed);
}
$resize = filter_input(INPUT_POST, "resize", FILTER_SANITIZE_STRING);
$resize = (boolean) $resize;
//flag to indicate whether we would have saved the file...
$file_ok = false;
$preliminary_check = true;
//Preliminary check of basic PHP file handling
if ($_FILES["inageFile"]["error"] != 0) {
switch ($_FILES["inageFile"]["error"]) {
case UPLOAD_ERR_INI_SIZE: //1
error_log("File is too big. uploaded: " . $_FILES["inageFile"]["size"] . ")");
$preliminary_check = false;
break;
case UPLOAD_ERR_FORM_SIZE: //2
error_log("Form is too big, " . $_FILES["inageFile"]["size"] . ")");
$preliminary_check = false;
break;
case UPLOAD_ERR_PARTIAL: //3
error_log("Partial Error");
$preliminary_check = false;
break;
case UPLOAD_ERR_NO_FILE: //4
error_log("No file uploaded");
$preliminary_check = false;
break;
default:
error_log("Unknown error " . $_FILES["inageFile"]["error"]);
$preliminary_check = false;
break;
}
}
//if no errors, continue
if ($preliminary_check) {
echo "PASSED preliminary check\n";
if (substr($_FILES["inageFile"]["type"], 0, 6) == "image/") {
if (is_image($_FILES["inageFile"]["tmp_name"])) {
$im["filename"] = str_replace(" ", "-", $_FILES["inageFile"]["name"]); //replace spaces with hyphens
$im["size"] = $_FILES["inageFile"]["size"];
list($im["width"], $im["height"], $im["type"], $tempattr) = getimagesize($_FILES["inageFile"]["tmp_name"]);
$im["type"] = $_FILES["inageFile"]["type"];
if (!file_exists($uploadfile)) {
error_log($_FILES["inageFile"]["name"] . " will not overwrite existing Logo. Would be saved.");
//if (move_uploaded_file($_FILES["inageFile"]["tmp_name"], $uploadfile)) {
error_log($_FILES["inageFile"]["name"] . " has been confirmed to be an image and would have been saved on the server.");
$file_ok = true;
//} else {
// error_log("Error in file upload. " . $_FILES["inageFile"]["tmp_name"] . " cannot be moved to $uploadfile");
//}
} else {
error_log("filename exists already");
}
} else{
error_log($_FILES["inageFile"]["type"] . " does not match magic number");
}
} else {
error_log("Mime/type is not an image - received: " . $_FILES["inageFile"]["type"]);
}
if($file_ok) {
echo "FILE WOULD HAVE BEEN UPLOADED AND SAVED";
}else {
echo "FAILED image check";
}
} else {
echo "FAILED preliminary check";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:08:14.073",
"Id": "525207",
"Score": "0",
"body": "I fail to see where do you checking the extension. Also, I'd like to see how that try to hack me thing is hacked with the extension check in place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:28:41.253",
"Id": "525225",
"Score": "0",
"body": "oh good point. apparently my weeding out of non-relevant code removed the extension check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:33:04.060",
"Id": "525226",
"Score": "0",
"body": "`fUpload.php%00.png` would be matched to a png file, but when writing the file some OSes will see the null byte as a string terminator, saving the file as `fUpload.php` which will then be callable."
}
] |
[
{
"body": "<p>One way to be almost 100% secure against upload vulnerabilities is to convert the image yourself, maybe using a libary like <a href=\"https://imagemagick.org/script/convert.php\" rel=\"nofollow noreferrer\">ImageMagick</a>.</p>\n<p>That way it would be very difficult to add code to the file that actually could be executed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:08:46.803",
"Id": "525208",
"Score": "0",
"body": "Time to learn about EXIF"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T07:30:34.333",
"Id": "265875",
"ParentId": "264487",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T18:15:35.863",
"Id": "264487",
"Score": "-1",
"Tags": [
"php",
"file"
],
"Title": "Image upload filter for PHP"
}
|
264487
|
<p>I decided to learn a little about AutoHotKey, to practice a little and learn about classes.</p>
<p>I ended up writting a basic ini file parser.</p>
<pre><code>Class Ini {
ini_file := ""
ini_data := {}
__New(ini_file)
{
if ini_file
{
this.ini_file := ini_file
Try
{
FileGetAttrib, attrs, %ini_file%
}
catch e
{}
If (attrs) and (!InStr(attrs, "D"))
{
this.ini_data := new Ini.IniData(ini_file)
}
else if attrs
{
Throw, "Please specify a file name, not a directory"
}
else
{
this.ini_data := new Ini.IniData("")
}
}
else
{
this.ini_data := new Ini.IniData("")
}
}
IniFile()
{
return this.ini_file
}
LoadString(ini_text)
{
data := InI.IniParser.ParseFromString(ini_text)
this.ini_data.LoadData(data)
}
Save()
{
if this.ini_file
{
return InI.IniWriter.Write(this.ini_file, this.ini_data)
}
else
{
Throw, "Please use SaveFile(ini_file) instead"
}
}
SaveFile(ini_file)
{
if ini_file
{
return InI.IniWriter.Write(ini_file, this.ini_data)
}
else
{
return this.Save()
}
}
Get(value_name, section_name, default_value)
{
if !value_name
{
Throw, "Value name can't be empty."
}
if this.ini_data.HasValue(value_name, section_name)
{
return this.ini_data.GetValue(value_name, section_name)
}
else
{
return default_value
}
}
Set(value_name, section_name, value)
{
if !value_name
{
Throw, "Value name can't be empty."
}
this.ini_data.SetValue(value_name, value, section_name)
}
Delete(value_name, section_name)
{
if value_name
{
this.ini_data.DeleteValue(value_name, section_name)
}
else
{
this.DeleteSection(section_name)
}
}
DeleteSection(section_name)
{
this.ini_data.DeleteSection(section_name)
}
Exists(value_name, section_name)
{
return this.ini_data.HasValue(value_name, section_name)
}
ExistsSection(section_name)
{
return this.ini_data.HasSection(section_name)
}
Sections()
{
return this.ini_data.ListSections()
}
class IniData {
data := {}
__New(ini_file)
{
if(ini_file)
{
this.LoadData(Ini.IniParser.Parse(ini_file))
}
}
LoadData(data)
{
this.data := data
}
ListSections()
{
sections := []
for key, value in this.data
{
sections.Push(key)
}
return sections
}
HasSection(section_name)
{
return this.data.HasKey(section_name)
}
CreateSection(section_name)
{
if !this.HasSection(section_name)
{
this.data[section_name] := {}
}
}
GetSection(section_name)
{
if !this.HasSection(section_name)
{
return []
}
return this.data[section_name]
}
DeleteSection(section_name)
{
if this.HasSection(section_name)
{
this.data[section_name].Remove()
}
}
ListValues(section_name)
{
values := []
for key, value in this.GetSection(section_name)
{
values.Push(key)
}
return values
}
HasValue(value_name, section_name)
{
return ((this.HasSection(section_name)) and (this.data[section_name].HasKey(value_name)))
}
SetValue(value_name, value, section_name)
{
if !this.HasSection(section_name)
{
this.CreateSection(section_name)
}
this.data[section_name][value_name] := value
}
GetValue(value_name, section_name)
{
if !this.HasValue(value_name, section_name)
{
this.SetValue(value_name, "", section_name)
}
return this.data[section_name][value_name]
}
DeleteValue(value_name, section_name)
{
if this.HasValue(value_name, section_name)
{
this.data[section_name][value_name].Remove()
}
}
}
class IniParser {
Parse(ini_file)
{
data := {}
section_name := ""
Loop, read, %ini_file%
{
if !A_LoopReadLine ; empty line - must ignore
{
Continue
}
parsed_line := InI.IniParser.ParseLine(A_LoopReadLine, section_name)
if !parsed_line
{
continue
}
section_name := parsed_line.section
if !data[section_name]
{
data[section_name] := {}
}
data[section_name] := InI.IniParser.ParsedLineIntoData(parsed_line, data[section_name])
}
return data
}
ParseFromString(ini_text)
{
data := {}
section_name := ""
Loop, parse, ini_text, `n, `r
{
if !A_LoopField ; empty line - must ignore
{
Continue
}
parsed_line := InI.IniParser.ParseLine(A_LoopField, section_name)
if !parsed_line
{
continue
}
section_name := parsed_line.section
if !data[section_name]
{
data[section_name] := {}
}
data[section_name] := InI.IniParser.ParsedLineIntoData(parsed_line, data[section_name])
}
return data
}
ParsedLineIntoData(parsed_line, data)
{
if !parsed_line.name
{
return {}
}
data[parsed_line.name] := parsed_line.value
return data
}
ParseLine(ini_line, current_section_name)
{
; can't have values with newlines
line := StrReplace(RegExReplace(ini_line, "^\s+|\s+$"), "`r`n", " ")
char := SubStr(line, 1, 1)
if (char == "[") ; section identified - needs parenthesis
{
section_name := InI.IniParser.ParseSection(line)
return {"section": section_name, "name": "", "value": ""}
}
else
{
; otherwise, must be a value
value := InI.IniParser.ParseValue(line)
return {"section": current_section_name, "name": value[1], "value": value[2]}
}
}
ParseSection(line)
{
; goal - trim the [] from the line
return RegExReplace(line, "^\[|\]$")
}
ParseValue(line)
{
; only want to split once, to preserve any values
values := StrSplit(line, [" = ", " =", "= ", "="], " `t", 2)
return values
}
}
class IniWriter {
Write(ini_file, ini_data)
{
Try
{
file := FileOpen(ini_file, "w")
; everything without a section is to be stored at the top
if ini_data.HasSection("")
{
file.Write(InI.IniWriter.MakeValues(ini_data.GetSection("")) . "`r`n")
}
for key, section_name in ini_data.ListSections()
{
; skips the "" section, since it was added before
if !section_name
{
continue
}
section := ini_data.GetSection(section_name)
if section
{
line := "[" . section_name . "]`r`n" . InI.IniWriter.MakeValues(section) . "`r`n"
file.Write(line)
}
}
file.Close()
return True
}
catch e
{
return False
}
}
MakeValues(data)
{
ini_text := ""
for key, value in data
{
ini_text .= key . "=" . value . "`r`n"
}
return ini_text
}
}
}
</code></pre>
<hr>
<p>The idea is to write a basic and simple to use parser, as an alternative to spamming multiple <a href="https://www.autohotkey.com/docs/commands/IniRead.htm" rel="nofollow noreferrer"><code>IniRead</code></a> and <a href="https://www.autohotkey.com/docs/commands/IniWrite.htm" rel="nofollow noreferrer"><code>IniWrite</code></a> to save/read settings.</p>
<hr>
<h2>Usage:</h2>
<p>The idea is to simply set the file name in the contructor and everything happens.</p>
<p>An example:</p>
<pre><code>ini := new Ini(A_ScriptDir . "\a.ini")
ini.Set("ticks", "settings", A_TickCount)
ini.Save()
</code></pre>
<p>Opens the file <code>a.ini</code>, parses it, sets <code>A_TickCount</code> in the <code>ticks</code> value in the <code>[settings]</code> section.</p>
<p>This generates an ini file that looks like this:</p>
<pre><code>[settings]
ticks = 123456789
</code></pre>
<p>You can get values, get a list of all sections, remove values and sections and even load contents from a string.</p>
<p>You can also include this file with an <code>#include</code>.</p>
<p>This parser supports no sections (the section name will be an empty string), but doesn't support comments.<br />
Comment support isn't something I'm considering.</p>
<hr>
<p>I've tested reading and writting back with a few files, and everything seems to be working fine.</p>
<p>Currently, the code feels like a massive mess, and if possible, I would like some additional tips on cleaning up a little.</p>
<p>Anything else I should consider, to improve this code?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T19:53:44.480",
"Id": "264490",
"Score": "1",
"Tags": [
"parsing",
"autohotkey"
],
"Title": "Yet another .ini parser for AutoHotKey"
}
|
264490
|
<p>This is LeetCode question 387 if anyone is interested. The task is to accept a string and find the first char that appears only once, and return its index. If no char appears only once then return -1. Examples are:</p>
<pre><code>input: "leetcode"
output: 0
input: "loveleetcode"
output: 2
input: "aabb"
output: -1
</code></pre>
<p>In the first example, <code>'l'</code> is the first char that appears once, in the second example, <code>'v'</code> is the first unique char. Here is the code I have:</p>
<pre><code>public int FirstUniqChar(string s)
{
for (int i = 0; i < s.Length; i++)
{
bool success = Dup(s, s[i], i);
if (success){
return i;
}
continue;
}
return -1;
}
bool Dup(string s, char temp, int index)
{
for (int i = 0; i < s.Length; i++){
if (s[i] == temp && i != index)
return false;
}
return true;
}
</code></pre>
<p>My biggest question about improving this code is, is there a way to enter the <code>Dup</code> function without iterating through the entire string again in <code>Dup</code>? Should I completely get rid of <code>Dup</code>? Inside of <code>Dup</code> I tried starting the loop at index and continuing but that would return a wrong response if the repeating chars happened to be back to back.</p>
<p>Let me know if this is better than using a double <code>for</code> loop. I believe this should be as a nested loop would make it 0(n^2) and I'm curious what this would be as it will return the correct value as soon as it is found rather than looping through every value and then determining.</p>
<p>Any suggestions are appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T00:40:54.877",
"Id": "522391",
"Score": "0",
"body": "I noticed there is another question asked on here today, I hope it is still appropriate to ask mine considering it is a different language and our logic is different. I am not using a Dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T03:30:21.073",
"Id": "524392",
"Score": "0",
"body": "You can make it `O(n)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T03:38:27.967",
"Id": "524393",
"Score": "0",
"body": "Making it 0(n), would that require a dictionary or hashmap and looping through adding each item to the dictionary and looping through again to find the value with the count of 1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T04:02:15.270",
"Id": "524394",
"Score": "0",
"body": "Yes, it would require a dictionary. I guess that means `O(2n)` then... :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T04:12:33.677",
"Id": "524395",
"Score": "0",
"body": "Is mine currently 0(n^2) since I technically could loop through every item in the string twice assuming the last char is the unique char? Or is it something other than 0(n^2)? I have seen it done with a Dictionary I am wondering if it would be possible to make it 0(n)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T04:42:06.353",
"Id": "524396",
"Score": "0",
"body": "Yes. Looping twice is `O(n^2)`. However, you stop early if you find a duplicated letter at least twice in the array, so `O(n^2)` is really only your maximum (and since you skip the position at `index`, it's really `O(n × (n - 1))`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T04:48:39.427",
"Id": "524397",
"Score": "0",
"body": "Yes, that makes sense, max is 0(n^2) average is likely 0(n*(n-1)). do you see potential for improvement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T05:01:15.217",
"Id": "524398",
"Score": "1",
"body": "Well I guess that technically 0(2n) would be an improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T07:31:42.987",
"Id": "524405",
"Score": "0",
"body": "@stupidQuestions I know it sounds a bit silly, but try to use better naming, like: `FirstUniqChar` >> `GetTheIndexOfTheFirstUniqueCharacter`; `Dup` >> `IsDuplicate` (BTW your implementation returns information about uniqueness, so the your naming is misleading); `success` >> `isUnique` / `hasDuplicates` (depending on the `Dup` implementation); `s` >> `input` / `source` / etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T17:28:55.983",
"Id": "524453",
"Score": "0",
"body": "It would make sense to rename Dup but FirstUniqueChar was the name that leetcode gave so I saw no point in renaming that"
}
] |
[
{
"body": "<p>Other than applying the suggested variable and method naming changes for code clarity, you could store the duplicated characters in a hashset so that you can avoid evaluating those.</p>\n<p>In addition, this also enables evaluating only the remaining part of the string from the index you are currently on, instead of going through the whole thing every time.</p>\n<pre><code>int GetTheIndexOfTheFirstUniqueCharacter(string s)\n{\n var repeatedCharacters = new HashSet<char>();\n\n for (int i = 0; i < s.Length; i++)\n {\n if (!repeatedCharacters.Contains(s[i]))\n {\n if (IsUnique(s, s[i], i))\n {\n return i;\n }\n else\n {\n repeatedCharacters.Add(s[i]);\n }\n }\n }\n\n return -1;\n}\n\nbool IsUnique(string s, char temp, int index)\n{\n for (int i = (index + 1); i < s.Length; i++)\n {\n if (s[i] == temp)\n {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T09:35:00.603",
"Id": "265541",
"ParentId": "264495",
"Score": "0"
}
},
{
"body": "<p>With LINQ you can achieve the same with the following fairly concise query:</p>\n<pre><code>int GetTheIndexOfTheFirstUniqueCharacter(string input)\n{\n char? firstUnique = input\n .ToCharArray()\n .GroupBy(character => character)\n .FirstOrDefault(charGroup => charGroup.Count() == 1)\n ?.Key;\n\n return firstUnique.HasValue ? input.IndexOf(firstUnique.Value) : -1;\n}\n</code></pre>\n<ul>\n<li>We are converting the string to a character array to able to use LINQ</li>\n<li>Then we group the characters in the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?redirectedfrom=MSDN&view=net-5.0#System_Linq_Enumerable_GroupBy__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__\" rel=\"nofollow noreferrer\">same order as they appear in the input</a></li>\n</ul>\n<blockquote>\n<p>The <code>IGrouping<TKey,TElement></code> objects are yielded in an order based on the order of the elements in source that produced the first key of each <code>IGrouping<TKey,TElement></code>. Elements in a grouping are yielded in the order they appear in source.</p>\n</blockquote>\n<ul>\n<li>We retrieve the first group where the group contains only a single element</li>\n<li>If there is such then <code>firstUnique</code> will have a value otherwise it will be <code>null</code>\n<ul>\n<li>If <code>firstUnique</code> has value then we can find the related index with the <code>IndexOf</code></li>\n<li>Otherwise we return with <code>-1</code></li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>Obviously, this is not the most performant solution, but it's simple and easy to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T07:36:01.987",
"Id": "265622",
"ParentId": "264495",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-28T21:44:39.360",
"Id": "264495",
"Score": "-1",
"Tags": [
"c#",
"strings"
],
"Title": "Find first non repeating char in a string"
}
|
264495
|
<p>I'm fairly new to time series databases in general and Influx in particular.</p>
<p>My objective is to build a simple and general-use API that will allow me to write and read data from an Influx Database.</p>
<p>I used Influx on a previous project and I found that building the API for the database was pretty mechanical, so I decided to create a general API.</p>
<p>I divided my code into 3 modules:</p>
<ul>
<li>Main.py where I will run FastAPI</li>
<li>Database.py where I connect with the database and I set the writing and reading actions.</li>
<li>Model.py where I create the pydantic model for the API.</li>
</ul>
<h2>Main.py</h2>
<pre><code>from fastapi import FastAPI
import uvicorn
import yaml
from yaml.loader import SafeLoader
from Model.Model import WritingData, ReadingData
from Database.Database import InfluxDataBase
with open("config.yaml", "r") as ymlfile:
cfg = yaml.load(ymlfile,Loader=SafeLoader)
server_URL=cfg["InfluxDB"]["server_URL"]
token=cfg["InfluxDB"]["token"]
org=cfg["InfluxDB"]["org"]
Influx = InfluxDataBase(server_URL,token,org)
app = FastAPI()
@app.post('/write/')
async def call_writing_influx(data: WritingData):
Influx.write_data(data)
@app.post('/read/')
async def call_reading_influx(data: ReadingData):
return Influx.read_data(data)
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000, reload=True)
</code></pre>
<h2>Database</h2>
<pre><code>from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
import json
class InfluxDataBase:
def __init__(self,server_URL,token,org) -> None:
self.client=InfluxDBClient(server_URL, token=token, org=org)
self.write_api=self.client.write_api(write_options=SYNCHRONOUS)
self.query_api=self.client.query_api()
self.server_URL=server_URL
self.token=token
self.org=org
def write_data(self,data) -> None:
executable_code='Point(data.measurement)'
n_fields=len(data.field)
n_tag=len(data.tag)
for i in range(n_tag):
executable_code=executable_code+'.tag(list(data.tag.keys())[{}],list(data.tag.values())[{}])'.format(i,i)
for i in range(n_fields):
executable_code=executable_code+'.field(list(data.field.keys())[{}],list(data.field.values())[{}])'.format(i,i)
if data.timestamp is not None:
executable_code=executable_code+'.time(data.timestamp)'
Data=eval(executable_code)
self.write_api.write(bucket=data.bucket_name, record=Data)
def read_data(self,data):
query = f'''
from(bucket: "{data.bucket_name}")'''+ '''
|> range(start: -{}h, stop: now())'''.format(data.time_interval)+f'''
|> filter(fn:(r) => r["_measurement"] == "{data.measureament_name}")'''
for i in range(len(data.tag)):
if i==0:
query=query+f'''|> filter(fn:(r) => r["{list(data.tag.keys())[i]}"] == "{list(data.tag.values())[i]}" '''
elif i<len(data.tag):
query=query+f''' or r["{list(data.tag.keys())[i]}"] == "{list(data.tag.values())[i]}"'''
query=query+')'
if data.field[0]=='All':
pass
else:
for i in range(len(data.field)):
if i==0:
query=query+f'''|> filter(fn:(r) => r["_field"] == "{data.field[i]}" '''
elif i<len(data.field):
query=query+f''' or r["_field"] == "{data.field[i]}"'''
query=query+')'
result = self.query_api.query(org=self.org, query=query)
results={}
for table in result:
for record in table.records:
results[record.get_field()]=record.get_value()
return results
</code></pre>
<h2>Model.py</h2>
<pre><code>from pydantic import BaseModel
from typing import List,Dict,Optional
from datetime import datetime
class WritingData(BaseModel):
bucket_name: str
measurement: str
tag: Dict[str,str]
field: Dict[str,float]
timestamp: Optional[datetime] = None
class ReadingData(BaseModel):
bucket_name: str
time_interval: int
measureament_name: str
tag: Dict[str,str]
field: List[str]
</code></pre>
<p>My current code works fine, It does what is intended to do.</p>
<p>There is any good practice politics I'm breaking?</p>
<p>Do you have any suggestions to improve it?</p>
<p>Edit: I updated the read_data() function in Database.py because I realized I didn't implemented the Flux code properly.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T02:44:55.893",
"Id": "524466",
"Score": "0",
"body": "By politics do you perhaps mean policies?"
}
] |
[
{
"body": "<ul>\n<li><code>Influx</code> should not be capitalized as it's a variable name</li>\n<li>None of this code:</li>\n</ul>\n<pre><code>with open("config.yaml", "r") as ymlfile:\n cfg = yaml.load(ymlfile,Loader=SafeLoader)\nserver_URL=cfg["InfluxDB"]["server_URL"]\ntoken=cfg["InfluxDB"]["token"]\norg=cfg["InfluxDB"]["org"]\n\nInflux = InfluxDataBase(server_URL,token,org)\n</code></pre>\n<p>should be done at the global level; but I don't know FastAPI and its Starlette backend well enough to suggest a sane global context alternative. This will take some research on your part.</p>\n<ul>\n<li>Lines like <code>def __init__(self,server_URL,token,org) -> None:</code> have a return typehint but no hints on the parameters; you should add these.</li>\n<li>Run a linter. Among other things it will tell you to add spaces around the <code>=</code> on statements like <code>self.org=org</code></li>\n</ul>\n<p>Moving on:</p>\n<h2>The root of all eval</h2>\n<p>Take a deep breath. Step away from the keyboard for a moment. This code:</p>\n<pre><code> executable_code='Point(data.measurement)'\n n_fields=len(data.field)\n n_tag=len(data.tag)\n for i in range(n_tag):\n executable_code=executable_code+'.tag(list(data.tag.keys())[{}],list(data.tag.values())[{}])'.format(i,i)\n for i in range(n_fields):\n executable_code=executable_code+'.field(list(data.field.keys())[{}],list(data.field.values())[{}])'.format(i,i)\n if data.timestamp is not None:\n executable_code=executable_code+'.time(data.timestamp)'\n\n Data=eval(executable_code)\n</code></pre>\n<p>is a true nightmare. It's wholly possible to construct your fluent-interface expression dynamically, using loops, something like (untested)</p>\n<pre><code>expr = Point(data.measurement)\nn_fields = len(data.field)\nn_tags = len(data.tag)\n\nfor i in range(n_tags):\n expr = expr.tag(\n tuple(data.tag.keys())[i],\n tuple(data.tag.values())[i],\n )\n</code></pre>\n<p>and so on. But the way you're casting a dictionary to an indexed sequence there and elsewhere in your code is <s>patently insane</s> non-advisable; just call <code>items</code>:</p>\n<pre><code>expr = Point(data.measurement)\n\nfor key, value in data.tag.items():\n expr = expr.tag(key, value)\n\nfor key, value in data.field.items():\n expr = expr.field(key, value)\n\nif data.timestamp is not None:\n expr = expr.time(data.timestamp)\n\nself.write_api.write(bucket=data.bucket_name, record=expr)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T14:20:31.893",
"Id": "524497",
"Score": "0",
"body": "Thank you so much!!!!!! Just what I was looking for, I knew my code was ugly and there must be a cleaner way of doing it. Thank you for the insights!!!! By the way, you mentioned that a piece of my code shouldn't be done at a global level, can you explain me why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T12:44:21.580",
"Id": "524555",
"Score": "1",
"body": "Global code like this makes it more difficult to unit test, for one thing. Also, what if you wanted two separate in-process FastAPI instances, each with a different database?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T03:02:08.470",
"Id": "265532",
"ParentId": "264498",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T00:28:49.347",
"Id": "264498",
"Score": "3",
"Tags": [
"python",
"performance",
"beginner",
"api",
"database"
],
"Title": "Data API with Influx-DB and FastAPI"
}
|
264498
|
<p>Need a <code>ThrottledStream</code> for a project, created the following class (still not tested), wouldn't mind some opinions on the code and suggestions on how it can be improved:</p>
<pre><code>public class ThrottledStream : Stream
{
private const int OneSecond = 1000; // 1000 milliseconds
private readonly Stream _baseStream;
private static readonly Stopwatch Stopwatch = new();
public ThrottledStream(Stream stream) => _baseStream = stream;
public int MaxBytesPerSecond { get; set; }
public override bool CanRead => _baseStream.CanRead;
public override bool CanSeek => _baseStream.CanSeek;
public override bool CanWrite => _baseStream.CanWrite;
public override long Length => _baseStream.Length;
public override long Position
{
get => _baseStream.Position;
set => _baseStream.Position = value;
}
public override void Flush() => _baseStream.Flush();
public override int Read(byte[] buffer, int offset, int count)
{
var readBytes = 0;
while (readBytes != count)
{
var newOffset = readBytes + offset;
var bytesToRead = count - readBytes > MaxBytesPerSecond ? MaxBytesPerSecond : count - readBytes;
var throttledReadBytes = Throttle(() => _baseStream.Read(buffer, newOffset, bytesToRead));
if (throttledReadBytes == 0) // Reached end of stream
return readBytes;
readBytes += throttledReadBytes;
}
return readBytes;
}
public override long Seek(long offset, SeekOrigin origin) => _baseStream.Seek(offset, origin);
public override void SetLength(long value) => _baseStream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count)
{
var writtenBytes = 0;
while (writtenBytes != count)
{
var newOffset = writtenBytes + offset;
var bytesToWrite = count - writtenBytes > MaxBytesPerSecond ? MaxBytesPerSecond : count - writtenBytes;
Throttle(() =>
{
_baseStream.Write(buffer, newOffset, bytesToWrite);
return true;
});
writtenBytes += bytesToWrite;
}
}
private static T Throttle<T>(Func<T> func)
{
var start = GetElapsedMilliseconds();
var result = func.Invoke();
var finish = GetElapsedMilliseconds();
var timeToSleep = OneSecond - (finish - start);
if (timeToSleep > 0)
Thread.Sleep((int) timeToSleep);
return result;
}
private static long GetElapsedMilliseconds()
{
if (!Stopwatch.IsRunning)
Stopwatch.Start();
return Stopwatch.ElapsedMilliseconds;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:43:01.120",
"Id": "524414",
"Score": "0",
"body": "Using `Thread.Sleep` is inefficient. I would suggest `Task.Delay`. Accordingly, the code should be asynchronous."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:44:34.550",
"Id": "524415",
"Score": "0",
"body": "Look at the [Channels](https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:58:36.353",
"Id": "524424",
"Score": "0",
"body": "@AlexanderPetrov can't use Task.Delay exactly because the code has to be synchronous: I inherit `Stream` which only contains abstract Read/Write/Seek methods ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:59:01.887",
"Id": "524425",
"Score": "0",
"body": "@AlexanderPetrov also how do you think think that Channels would improve this? I don't need to buffer anything"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T08:35:36.190",
"Id": "265498",
"Score": "0",
"Tags": [
"c#",
".net"
],
"Title": "ThrottledStream"
}
|
265498
|
<p>I asked the same question on StackOverflow but was told to instead ask here since it was better suited. I have a function that I implemented. It is doing a lot of heavy lifting. I would like to optimise it or in other words try to find repeating code and simplify it a little bit. I'll show my implementation below:</p>
<pre><code>setModifiedPaths(limit, assetTypeIndex, categoryIndex, subCategoryIndex = '', subSubCategoryIndex = '') {
const { modified, deleted, typeObj, typeObjCopy } = this.state;
let [modifiedArr, oldAssetTypeObj, oldCategoryObj, oldSubcategoryObj, oldSubSubCategoryObj, newAssetTypeObj, newCategoryObj, newSubCategoryObj,
newSubSubCategoryObj, oldAssetSubSubCategoryPath, newAssetSubSubCategoryPath, oldAssetSubCategoryPath,
newAssetSubCategoryPath, oldAssetCategoryPath, newAssetCategoryPath] = Array(6).fill('');
modifiedArr = modified;
oldAssetTypeObj = typeObjCopy[assetTypeIndex];
oldCategoryObj = typeObjCopy[assetTypeIndex].category[categoryIndex];
newAssetTypeObj = typeObj[assetTypeIndex];
newCategoryObj = typeObj[assetTypeIndex].category[categoryIndex];
if (!_.isEmpty(subCategoryIndex) && _.has(typeObjCopy[assetTypeIndex].category[categoryIndex], "subCategories")) {
oldSubcategoryObj = typeObjCopy[assetTypeIndex].category[categoryIndex].subCategories[subCategoryIndex];
newSubCategoryObj = typeObj[assetTypeIndex].category[categoryIndex].subCategories[subCategoryIndex]
}
if (!_.isEmpty(subSubCategoryIndex) && _.has(typeObjCopy[assetTypeIndex].category[categoryIndex].subCategories[subCategoryIndex], "subSubCategories")) {
oldSubSubCategoryObj = typeObjCopy[assetTypeIndex].category[categoryIndex].subCategories[subCategoryIndex].subSubCategories[subSubCategoryIndex];
newSubSubCategoryObj = typeObj[assetTypeIndex].category[categoryIndex].subCategories[subCategoryIndex].subSubCategories[subSubCategoryIndex];
}
switch (limit) {
case 'subSubCategory':
if (!!oldSubSubCategoryObj && !_.isEmpty(oldSubSubCategoryObj.label) && !_.isEmpty(newSubCategoryObj.label) && !_.isEmpty(newCategoryObj)) {
oldAssetSubSubCategoryPath = oldAssetTypeObj.label + "." + oldCategoryObj.label + "." + oldSubcategoryObj.label + "." + oldSubSubCategoryObj.label;
newAssetSubSubCategoryPath = oldAssetTypeObj.label + "." + oldCategoryObj.label + "." + oldSubcategoryObj.label;
modifiedArr = this.rejectSameFromModifiedArr(modifiedArr);
if (!_.isEmpty(newSubSubCategoryObj.label)) {
newAssetSubSubCategoryPath = newAssetSubSubCategoryPath + "." + newSubSubCategoryObj.label;
modifiedArr.push({ oldPath: oldAssetSubSubCategoryPath, newPath: newAssetSubSubCategoryPath });
} else {
deleted.push(oldAssetSubSubCategoryPath);
this.setState({ deleted })
}
}
break;
case 'subCategory':
if (!!oldSubcategoryObj && !_.isEmpty(oldSubcategoryObj.label) && !_.isEmpty(newCategoryObj.label) && !_.isEmpty(newAssetTypeObj)) {
oldAssetSubCategoryPath = oldAssetTypeObj.label + "." + oldCategoryObj.label + "." + oldSubcategoryObj.label;
newAssetSubCategoryPath = oldAssetTypeObj.label + "." + oldCategoryObj.label;
modifiedArr = _.reject(modifiedArr, (obj) => {
return obj.oldPath === oldAssetSubCategoryPath;
});
if (!_.isEmpty(newSubCategoryObj.label)) {
newAssetSubCategoryPath = newAssetSubCategoryPath + "." + newSubCategoryObj.label;
modifiedArr.push({ oldPath: oldAssetSubCategoryPath, newPath: newAssetSubCategoryPath });
} else {
deleted.push(oldAssetSubCategoryPath);
this.setState({ deleted });
}
}
break;
case 'category':
if (!!oldCategoryObj && !_.isEmpty(oldCategoryObj.label) && !_.isEmpty(newAssetTypeObj)) {
oldAssetCategoryPath = oldAssetTypeObj.label + "." + oldCategoryObj.label;
newAssetCategoryPath = oldAssetTypeObj.label;
modifiedArr = _.reject(modifiedArr, (obj) => {
return obj.oldPath === oldAssetCategoryPath
});
if (!_.isEmpty(newCategoryObj.label)) {
newAssetCategoryPath = newAssetCategoryPath + "." + newCategoryObj.label;
modifiedArr.push({ oldPath: oldAssetCategoryPath, newPath: newAssetCategoryPath });
} else {
deleted.push(oldAssetCategoryPath);
this.setState({ deleted });
}
}
break;
default:
if (!!oldAssetTypeObj && !_.isEmpty(oldAssetTypeObj.label)) {
let oldAssetTypePath = oldAssetTypeObj.label;
let newAssetTypePath = newAssetTypeObj.label;
modifiedArr = _.reject(modifiedArr, (obj) => {
return obj.oldPath === oldAssetTypePath
})
if (!_.isEmpty(newAssetTypePath)) {
modifiedArr.push({ oldPath: oldAssetTypePath, newPath: newAssetTypePath });
} else {
deleted.push(oldAssetTypePath);
this.setState({ deleted });
}
}
break;
}
return modifiedArr;
}
</code></pre>
<p>The variables <em><strong>deleted</strong></em> and <em><strong>modified</strong></em> are empty arrays. The variable <em><strong>typeObjCopy</strong></em> is a deeply cloned copy of <em><strong>typeObj</strong></em>. Let me show a little bit of the contents of <em><strong>typeObj</strong></em> for reference:</p>
<pre><code>[
{
"label": "testType",
"categories": [
{
"label": "testCatType",
"subCategories": [
{
"label": "testSubCat",
"subSubCategories": [
{
"label": "testSubSubCat1"
},
{
"label": "testSubSubCat2"
}
]
}
]
}
]
},
{
"label": "newType",
"categories": [
{
"label": "newCat10",
"subCategories": [
{
"label": "newCatSub1",
"subSubCategories": [
{
"label": "bingo11"
},
{
"label": "bingo12"
},
{
"label": "bingo15"
}
]
}
]
}
]
},
{
"label": "displacement",
"categories": []
},
{
"label": "imperfection",
"categories": [
{
"label": "metal",
"subCategories": [
{
"label": "clean",
"subSubCategories": []
},
{
"label": "scratched",
"subSubCategories": []
}
]
},
{
"label": "dust",
"subCategories": []
},
{
"label": "leakage",
"subCategories": []
},
{
"label": "wipe mark",
"subCategories": []
},
{
"label": "fingerprint",
"subCategories": []
},
{
"label": "grunge",
"subCategories": []
},
{
"label": "other",
"subCategories": []
},
{
"label": "rubber",
"subCategories": []
},
{
"label": "grain",
"subCategories": []
},
{
"label": "stone",
"subCategories": []
},
{
"label": "stain",
"subCategories": []
}
]
},
{
"label": "surface",
"categories": [
{
"label": "metal",
"subCategories": [
{
"label": "bare",
"subSubCategories": []
},
{
"label": "corroded",
"subSubCategories": []
},
{
"label": "corrugated",
"subSubCategories": []
},
{
"label": "gun",
"subSubCategories": []
},
{
"label": "painted",
"subSubCategories": []
},
{
"label": "sheet",
"subSubCategories": []
},
{
"label": "treated",
"subSubCategories": []
}
]
},
{
"label": "wood",
"subCategories": [
{
"label": "board",
"subSubCategories": []
},
{
"label": "log",
"subSubCategories": []
},
{
"label": "other",
"subSubCategories": []
},
{
"label": "parquet",
"subSubCategories": []
},
{
"label": "plank",
"subSubCategories": []
},
{
"label": "veneer",
"subSubCategories": []
}
]
},
{
"label": "fabric",
"subCategories": [
{
"label": "carpet",
"subSubCategories": []
},
{
"label": "leather",
"subSubCategories": []
},
{
"label": "pattern",
"subSubCategories": []
},
{
"label": "plain",
"subSubCategories": []
}
]
},
{
"label": "grass",
"subCategories": [
{
"label": "artificial",
"subSubCategories": []
},
{
"label": "dried",
"subSubCategories": []
},
{
"label": "lawn",
"subSubCategories": []
},
{
"label": "patchy",
"subSubCategories": []
},
{
"label": "wild",
"subSubCategories": []
}
]
},
{
"label": "concrete",
"subCategories": [
{
"label": "cast in situ",
"subSubCategories": []
},
{
"label": "damaged",
"subSubCategories": []
},
{
"label": "dirty",
"subSubCategories": []
},
{
"label": "painted",
"subSubCategories": []
},
{
"label": "rough",
"subSubCategories": []
},
{
"label": "slab",
"subSubCategories": []
},
{
"label": "smooth",
"subSubCategories": []
}
]
},
{
"label": "sand",
"subCategories": [
{
"label": "beach",
"subSubCategories": []
},
{
"label": "desert",
"subSubCategories": []
}
]
},
{
"label": "stone",
"subCategories": [
{
"label": "castle",
"subSubCategories": []
},
{
"label": "cobblestone",
"subSubCategories": []
},
{
"label": "floor",
"subSubCategories": []
},
{
"label": "mosaic",
"subSubCategories": []
},
{
"label": "terrazzo",
"subSubCategories": []
},
{
"label": "wall",
"subSubCategories": []
}
]
},
{
"label": "plaster",
"subCategories": [
{
"label": "damaged",
"subSubCategories": []
},
{
"label": "fresh",
"subSubCategories": []
},
{
"label": "old",
"subSubCategories": []
},
{
"label": "painted",
"subSubCategories": []
}
]
},
{
"label": "soil",
"subCategories": [
{
"label": "clay",
"subSubCategories": []
},
{
"label": "mud",
"subSubCategories": []
},
{
"label": "mulch",
"subSubCategories": []
},
{
"label": "sandy",
"subSubCategories": []
}
]
},
{
"label": "rock",
"subCategories": [
{
"label": "cliff",
"subSubCategories": []
},
{
"label": "granite",
"subSubCategories": []
},
{
"label": "jagged",
"subSubCategories": []
},
{
"label": "lava",
"subSubCategories": []
},
{
"label": "mossy",
"subSubCategories": []
},
{
"label": "rough",
"subSubCategories": []
},
{
"label": "smooth",
"subSubCategories": []
}
]
},
{
"label": "moss",
"subCategories": [
{
"label": "ground",
"subSubCategories": []
},
{
"label": "rock",
"subSubCategories": []
}
]
},
{
"label": "debris",
"subCategories": [
{
"label": "construction",
"subSubCategories": []
},
{
"label": "nature",
"subSubCategories": []
}
]
},
{
"label": "brick",
"subCategories": [
{
"label": "modern",
"subSubCategories": []
},
{
"label": "mortar",
"subSubCategories": []
},
{
"label": "painted",
"subSubCategories": []
},
{
"label": "rough",
"subSubCategories": []
}
]
},
{
"label": "tile",
"subCategories": [
{
"label": "ceramic",
"subSubCategories": []
},
{
"label": "grout",
"subSubCategories": []
},
{
"label": "pavestone",
"subSubCategories": []
},
{
"label": "sidewalk",
"subSubCategories": []
}
]
},
{
"label": "asphalt",
"subCategories": [
{
"label": "fine",
"subSubCategories": []
},
{
"label": "rough",
"subSubCategories": []
},
{
"label": "torn",
"subSubCategories": []
}
]
},
{
"label": "other",
"subCategories": [
{
"label": "climber",
"subSubCategories": []
},
{
"label": "creature",
"subSubCategories": []
},
{
"label": "dirt road",
"subSubCategories": []
},
{
"label": "edible",
"subSubCategories": []
},
{
"label": "fur",
"subSubCategories": []
},
{
"label": "paper",
"subSubCategories": []
},
{
"label": "various",
"subSubCategories": []
}
]
},
{
"label": "snow",
"subCategories": [
{
"label": "mixed",
"subSubCategories": []
},
{
"label": "pure",
"subSubCategories": []
}
]
},
{
"label": "bark",
"subCategories": [
{
"label": "beech",
"subSubCategories": []
},
{
"label": "birch",
"subSubCategories": []
},
{
"label": "oak",
"subSubCategories": []
},
{
"label": "other",
"subSubCategories": []
},
{
"label": "palm",
"subSubCategories": []
},
{
"label": "pine",
"subSubCategories": []
},
{
"label": "willow",
"subSubCategories": []
}
]
},
{
"label": "gravel",
"subCategories": [
{
"label": "construction",
"subSubCategories": []
},
{
"label": "natural",
"subSubCategories": []
},
{
"label": "pebbledash",
"subSubCategories": []
}
]
},
{
"label": "marble",
"subCategories": [
{
"label": "polished",
"subSubCategories": []
},
{
"label": "rough",
"subSubCategories": []
},
{
"label": "tile",
"subSubCategories": []
}
]
},
{
"label": "ground",
"subCategories": [
{
"label": "forest",
"subSubCategories": []
},
{
"label": "jungle",
"subSubCategories": []
},
{
"label": "other",
"subSubCategories": []
},
{
"label": "roots",
"subSubCategories": []
}
]
},
{
"label": "roofing",
"subCategories": [
{
"label": "new",
"subSubCategories": []
},
{
"label": "old",
"subSubCategories": []
}
]
},
{
"label": "antique",
"subCategories": [
{
"label": "asian",
"subSubCategories": []
},
{
"label": "medieval",
"subSubCategories": []
},
{
"label": "middle-eastern",
"subSubCategories": []
},
{
"label": "roman",
"subSubCategories": []
}
]
},
{
"label": "coal",
"subCategories": [
{
"label": "brick",
"subSubCategories": []
},
{
"label": "debris",
"subSubCategories": []
}
]
}
]
},
{
"label": "brush",
"categories": [
{
"label": "blood",
"subCategories": []
},
{
"label": "damage",
"subCategories": []
},
{
"label": "grunge",
"subCategories": []
},
{
"label": "leakage",
"subCategories": []
},
{
"label": "print",
"subCategories": []
},
{
"label": "spatter",
"subCategories": []
},
{
"label": "sponge",
"subCategories": []
},
{
"label": "spray",
"subCategories": []
},
{
"label": "stain",
"subCategories": []
},
{
"label": "traditional",
"subCategories": []
}
]
}
]
</code></pre>
<p>As you can see it has grown pretty out of proportion and I would like it to be more readable. Before this implementation, the previous implementation was even more convoluted and I have so far been able to compress it to this logic.</p>
<p>Would really appreciate any help and suggestions!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T10:39:56.233",
"Id": "524409",
"Score": "2",
"body": "What does the code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T10:45:36.023",
"Id": "524410",
"Score": "0",
"body": "@MagnusJeffsTovslid so I have mapped the **typeObj** values as input fields and when someone changes those field values, I track what is being changes. I have to send an array to the backend containing new and old paths formed because of those changes. So an example output of this function would be:\n`[\n {\n newPath: \"testType.categoryTypeChanged\"\n oldPath: \"testType.testCatType\"\n }\n]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T10:57:31.743",
"Id": "524411",
"Score": "0",
"body": "I think I need a lot more context and info to understand what this is supposed to do. Is it just checking if a value inside some path has changed? If so, I would think you could simplify this greatly by having the same \"type\" of object all the way down. E.g. not call it subcategory and subsubcategory, but just category all the way. Then you could make a simple recursive algorithm to traverse it. But like I said, I would need more info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:04:57.837",
"Id": "524412",
"Score": "0",
"body": "@MagnusJeffsTovslid so I have to keep the nomenclature intact because if you see the structure of **typeObj** it is a nested object. So the parent key is considered an _asset type_. Each _asset type_ can have multiple _categories_. each _category_ can have multiple _sub categories_. Each _sub category_ can have multiple _sub sub categories_. And so let's say I changed the value of a _sub sub category_ belonging to a _sub category_, I need to construct the **modifiedArr** collection containing info about _newPath_ and _oldPath_. I hope I am making some sense here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:53:12.557",
"Id": "524418",
"Score": "2",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T11:24:42.513",
"Id": "524483",
"Score": "0",
"body": "In the code you have object property `category`, and in the data it is `categories`. Because of that, I can't see how the code can work."
}
] |
[
{
"body": "<p>I'm gonna guess that the code is really trying to find the diff between two tree structures. Futher, I'm assuming from the name "typeObjCopy" that the two trees have identical structure, just different labels. I.e. no added categories allowed. Hopefully this will still be helpful for you even if I'm not entirely correct about this.</p>\n<p>When I saw the "typeObj" object with categories and sub categories etc, I immediately expected a recursive solution. It is a bit hampered by the fact that each level in the tree have a different name for the children. But other than that, we have only labels to deal with. So to avoid all the repeating code it would be extremely helpful to rewrite this into a recursion, imo.</p>\n<p>To see how the current solution is repetitive is a little bit annoying with the way it is written. For example, you declare a bunch of variables at the top which are only used for one of the cases each. This requires that the variables have unique names, which makes them look different. If you instead declare those variables inside of each case, you can make them have the same name in all of the cases, and the duplication is obvious. To sum up: declare variables as close to the usage as possible.</p>\n<p>I would also try to separate this type of complex logic from react state handling. In this case it's pretty easy to make it a pure function, and then it is very easy to test as well.</p>\n<p>Below is an example of a recursive solution. I'm not sure if it solves your problem exactly, but I think something like this is what you're looking for.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const childrenByLevel = {\n 0: 'categories',\n 1: 'subCategories',\n 2: 'subSubCategories'\n}\n\nfunction diff(nodesOld, nodesNew, prevOldPath = '', prevNewPath = '', level = 0) {\n const modified = []\n const deleted = []\n\n for (let i = 0; i < nodesOld.length; i++) {\n const nodeOld = nodesOld[i]\n const nodeNew = nodesNew[i]\n\n const oldPath = [prevOldPath, nodeOld.label].filter(x => !!x).join('.')\n const newPath = [prevNewPath, nodeNew.label].filter(x => !!x).join('.')\n\n if (!nodeNew.label) {\n deleted.push(oldPath)\n } else {\n if (nodeOld.label !== nodeNew.label) {\n modified.push({ oldPath, newPath })\n }\n\n const childrenOld = nodeOld[childrenByLevel[level]]\n const childrenNew = nodeNew[childrenByLevel[level]]\n\n if (!childrenOld || !childrenNew) continue\n\n const result = diff(childrenOld, childrenNew, oldPath, newPath, level + 1)\n\n modified.push(...result.modified)\n deleted.push(...result.deleted)\n }\n }\n\n return { modified, deleted }\n}\n\nconsole.log(diff(typeObj, typeObjNew))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T18:11:45.117",
"Id": "265526",
"ParentId": "265501",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T10:33:07.263",
"Id": "265501",
"Score": "-1",
"Tags": [
"javascript",
"performance",
"functional-programming",
"react.js"
],
"Title": "Simplifying and optimising function logic"
}
|
265501
|
<p>I am trying to pack around 50 files from a folder to zip file using PHP ZipArchive. Actually, only at most five files are ever changing. Others remain same static files. Should I zip the folder for every request or just replace those five files? Which one would be better for memory consumption and performance?</p>
<pre><code><?php
$zip = new ZipArchive();
$zip->open('example.zip', ZipArchive::CREATE);
$srcDir = "/folderTobeZipped/";
$files= scandir($srcDir);
unset($files[0],$files[1]);
foreach ($files as $file) {
$zip->addFile("{$file}");
}
$zip->close();
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T02:27:28.257",
"Id": "525090",
"Score": "0",
"body": "“_Should I zip the folder for every request or just replace those five files?_” do you have easy acccess to determine which five files changed, or would it have to be calculated from an existing zip?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T08:45:03.010",
"Id": "525927",
"Score": "0",
"body": "Five big files? Small files? The obvious thing to do is to test this with the real files. Then you will have your answer."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:02:44.467",
"Id": "265503",
"Score": "0",
"Tags": [
"performance",
"php"
],
"Title": "Create ZipArchive from a directory of files"
}
|
265503
|
<p>The task is:</p>
<blockquote>
<p>Given an array of integers, return the minimum required increment to
make each element unique.</p>
<p>Sample Input 1: [3, 4, 2, 2, 6]</p>
<p>Sample Output 1: 3 (One of the 2s should be incremented to 5)</p>
<p>Sample Input 2: [3, 4, 5]</p>
<p>Sample Output 2: 0 (There is no duplicate)</p>
</blockquote>
<p>My code works by shifting all numbers even if there is only one duplicate in a whole array. I guess this could be written more efficiently (e.g., in each duplicate, looking at the minimum number that does not exist in the array and shifting one of the duplicates to that number), but I couldn't manage it.</p>
<pre><code>def getMinimumCoins(arr):
sumBefore = sum(arr)
arr.sort()
previous = arr[0]
for i in range(1, len(arr)):
if arr[i] <= previous:
arr[i] = previous + 1
previous = arr[i]
return sum(arr) - sumBefore
</code></pre>
<p>Besides, in the way I proposed above, decremental operations also could be possible. I mean, in my code, if the input is [3,3,3], the resulting array would be [3,4,5] with total increment equals 3. However, in the new algorithm, it could be possible to obtain a resulting array of [1,2,3] with a total decrement equals to -3.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:45:02.727",
"Id": "524416",
"Score": "5",
"body": "\"My code works in the linear time since\". \"`arr.sort()`\" does not run in linear time, so your code is not linear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:50:38.877",
"Id": "524417",
"Score": "0",
"body": "Timsort runs in logarithmic time as you have said, but the loop below works in the linear time. Therefore, in the worst case, it is linear. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:35:44.407",
"Id": "524419",
"Score": "1",
"body": "Timsort is \\$O(n\\sqrt{n})\\$ your loop is \\$O(n)\\$. \\$O(n\\sqrt{n} + n) = O(n(\\sqrt{n} + 1)) = O(n\\sqrt{n})\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:56:13.290",
"Id": "524423",
"Score": "1",
"body": "Sorry, Timsort is \\$O(n \\log n)\\$ not \\$O(n\\sqrt{n})\\$ however the math and conclusion are roughly the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T13:18:30.783",
"Id": "524427",
"Score": "1",
"body": "What is the expected output for arr `[3, 3, 6]`? You could get there by one increment (`arr[1] += 1 -> 4`) and one decrement (`arr[2] -= 1 -> 5`). Is the expected output `0`, because one increment and one decrement \"cancel each other out\"? Or `2` (1 increment of value `1`, plus 1 decrement of value `1`)? Or perhaps `(1, 1)`, indicating the sum of all required increments is `1`, and the sum of all required decrements is also `1`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T13:22:47.130",
"Id": "524428",
"Score": "0",
"body": "@AlexWaygood For [3,3,6], the output is 1 ([3,4,6]) in my algorithm. I only proposed another idea which includes also decremental operation. My first purpose to ask this question was to optimize my code. Then, I proposed an alternative that includes decremental operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T13:27:28.980",
"Id": "524430",
"Score": "0",
"body": "@Peilonrayz sorry for my mistake. Yes, the worst-case complexity is O(nlogn), but cannot I change the way of the loop to make it slightly better? I mean, instead of shifting all elements, maybe it can only alter the duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T13:35:42.300",
"Id": "524431",
"Score": "0",
"body": "Understood, but consider a different example. Say `arr = [5, 5, 6, 7, 7]`. The smallest changes required here to achieve an array of unique integers would be to subtract `1` from `arr[0]` and add `1` to `arr[4]`, leading to `[4, 5, 6, 7, 8]`. You *could* add `1` to `arr[1]`, `2` to `arr[2]`, `2` to `arr[3]` and `3` to `arr[4]` -> result of `8`, but this is arguably not the *minimum increment required* if the algorithm is allowed to consider decrements. So for a situation where the algorithm is allowed to consider decrements, how should that result be expressed if the operations cancel out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T21:21:37.003",
"Id": "524460",
"Score": "0",
"body": "In case of decremental operations are allowed, we can traverse the array one by one, and if we see a duplicate, we can check what is the minimum positive integer that does not exist in the array, and change the current element with that integer. The problem is, how can we do this in an efficient way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T12:37:45.893",
"Id": "524489",
"Score": "2",
"body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>As already mentioned by Peilonrayz, your algorithm's time complexity is <span class=\"math-container\">\\$\\mathcal{O}(n\\log{n})\\$</span>, because of <a href=\"https://en.wikipedia.org/wiki/Timsort#Analysis\" rel=\"noreferrer\"><code>sort()</code></a>. You also process the input array three times: once to sort, once to increment elements as necessary to ensure there are duplicates, and once to calculate how much you incremented. To get the best performance, you want to have a sorting function that is better than <code>sort()</code>, and use as few loops over the input as possible to get the answer.</p>\n<p>Since the input is an array of integers, you can use <a href=\"https://en.wikipedia.org/wiki/Radix_sort\" rel=\"noreferrer\">radix sort</a> to sort the input in <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time. Then you should be able to loop over the the result and increment where necessary, and keep track of how much you incremented at the same time.</p>\n<p>A big caveat is that a better time complexity does not guarantee better performance unless your input is very large. Python's built-in <code>sort()</code> is highly optimized and implemented in C, so up to a certain size of the input it might still be faster than an <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> implementation you wrote in pure Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T21:07:15.997",
"Id": "524459",
"Score": "0",
"body": "I totally agree with your comment about sorting. Probably Timsort would be the most optimal one. Actually, my intention is to change the algorithm for better performance. In this version, all elements should be shifted. However, it could be written in a more efficient way (e.g., in each duplicate, looking at the minimum number that does not exist in the array and shifting one of the duplicates to that number), but I couldn't manage it. Do you have any idea about this? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T21:35:21.377",
"Id": "524461",
"Score": "2",
"body": "Doing that is probably not going to be faster. Finding something in a sorted set is \\$O(\\log n)\\$, or if you want to make it \\$O(1)\\$ to find the next free integer, it's probably going to be at least \\$O(\\log n)\\$ extra work per element visited so far to maintain the necessary information to do that. It might be an interesting question for the [Computer Science](https://cs.stackexchange.com/) site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T15:47:59.640",
"Id": "524500",
"Score": "0",
"body": "Radix sort works only if the set of integers is bounded. In Python, there is no such bound on integers. But even if we limit input to 32-bit or 64-bit unsigned integers, I'm sceptical that an optimized radix sort would be faster (in wall time) than an optimized Timsort. Any benchmarks (in any programming language) to share?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:20:45.517",
"Id": "524504",
"Score": "0",
"body": "@pts Radix sort *will* be faster with a *large enough* input, regardless of how optimized it is compared to Timsort. However, complexity analysis doesn't tell you how large that input has to be. Benchmarks in other languages than OP uses might not be useful for the OP. But this might be interesting to watch: [The Sorting Algorithm Olympics](https://www.youtube.com/watch?v=FNAUuYmkMPE)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T17:45:26.937",
"Id": "524515",
"Score": "1",
"body": "@bbasaran Maybe we could use [union-find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure), with streaks of consecutive numbers being the components, and an extra dict mapping values to their streaks so that for a value x, you can look up existing streaks that include x-1, x or x+1 (in order to find the \"edges\" connecting the nodes/streaks).. Then unite overlapping/touching streaks. Could be O(nα(n)), i.e., practically O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T21:48:58.660",
"Id": "524532",
"Score": "1",
"body": "They use `sum` twice, so process the input array *four* times. I wonder how fast these four times are. Even for large inputs, I can imagine the `sort` being faster than their loop part (and `sum` probably be fastest). I.e., the `sort` already not being the problem here."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:51:17.433",
"Id": "265513",
"ParentId": "265504",
"Score": "7"
}
},
{
"body": "<p>The algorithm is good, but...</p>\n<ul>\n<li>Use a better function name than <code>getMinimumCoins</code>. The task isn't about coins.</li>\n<li>Python prefers <code>snake_case</code> and four-space indentation.</li>\n<li>If the list is empty, you crash instead of returning zero.</li>\n<li>No need to actually perform the increments in the array, and <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"noreferrer\"><code>itertools.accumulate</code></a> can help:</li>\n</ul>\n<pre><code>from itertools import accumulate\n\ndef minimum_increments(arr):\n arr.sort()\n return sum(accumulate(arr, lambda prev, curr: max(prev + 1, curr))) - sum(arr)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:47:11.363",
"Id": "524478",
"Score": "0",
"body": "Hello Kelly, thank you for your valuable input. I have just learned a new concept thanks to you. I could not fully comprehend how this module unpacks elements in the array for the lambda function. The lambda function works on two elements (prev, curr), but the elements in the array are integers, not tuples. I could not find anything about this. My wild guess is: if the function is operator.add, it fetches 0 and the first element at the beginning, and in the rest, previous element and the current element. If the function is mul, it fetches 1 and the first element at the beginning and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T11:12:49.347",
"Id": "524482",
"Score": "0",
"body": "I don't know why, but the first algorithm works slightly faster (by 40 ms difference on average)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T12:05:00.007",
"Id": "524487",
"Score": "0",
"body": "@bbasaran Not quite. First `prev` is the first element, not 0 or 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T12:56:54.273",
"Id": "524490",
"Score": "0",
"body": "What is the first curr then? It cannot be the first element as well, because when I tried this: accumulate([1,3,5], lambda prev, curr: prev+curr), it returns [1, 4, 9], not [2, 4, 9]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:11:33.313",
"Id": "524492",
"Score": "0",
"body": "The second element. Try for example `accumulate([1,3,5], print)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:14:21.710",
"Id": "524495",
"Score": "0",
"body": "In such a case, the result should be [4, 9] instead of [1, 4, 9]. Isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:15:00.563",
"Id": "524496",
"Score": "0",
"body": "I don't know why you think so."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T02:13:16.917",
"Id": "265529",
"ParentId": "265504",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T11:22:27.513",
"Id": "265504",
"Score": "5",
"Tags": [
"python",
"performance",
"algorithm"
],
"Title": "Given an array of integers, return the minimum required increment to make each element unique"
}
|
265504
|
<p>I'm using Spring-WebFlux with Spring-Security and I need to save data depending on the currently registered user. In order to do so, in my controller, I need to retrieve the data sent from both the frontend and the principal.</p>
<p>After searching for a solution to my problem on the internet, I didn't find any clear way to do what I wanted, so I did my own stuff but I don't know whether it's correct.</p>
<p>Here's what I did:</p>
<pre><code>public Mono<Order> createOrder(@Valid @RequestBody Mono<OrderViewModel> orderViewModel, Mono<Principal> principal) {
return principal.flatMap(userPrincipal ->
orderViewModel.flatMap(order -> this.orderService.save(order, userPrincipal))
);
}
</code></pre>
<p>As you can see, I have two <code>Mono</code> objects in my controller. Then, I kind of nest them one in the other by performing two <code>flatMap()</code> calls in order to return my <code>Mono</code> response.</p>
<p>Well, it works fine but I'm a beginner with WebFlux and I really don't know if this solution is "dirty" or valid. If you guys have any better approach I'll be happy to discuss it. Otherwise I hope this code fragment can help those with similar problems. :)</p>
|
[] |
[
{
"body": "<p>There is no problems at all with the supplied code.</p>\n<p>Nesting multiple <code>Mono</code>s is no problems and <code>flatMap</code>ing over them in a nested fashion is somewhat common.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:23:36.837",
"Id": "265509",
"ParentId": "265506",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:14:55.657",
"Id": "265506",
"Score": "0",
"Tags": [
"spring"
],
"Title": "Spring-WebFlux code to save per-user data"
}
|
265506
|
<p>I am new to web development and I am making a small "About Me" website using html/css .
I managed to do this layout : <a href="https://imgur.com/a/Kb0xPQA" rel="nofollow noreferrer">https://imgur.com/a/Kb0xPQA</a></p>
<p>Although it did the job done, I am just concerned that with this layout/code will affect the future ones</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-css lang-css prettyprint-override"><code>.container {
transform: translate( 0, 150px);
display: block;
margin: 0 auto;
align-items: center;
background-color: black;
width: 80%;
height: 100vh;
border-radius: 20px;
border: 2px solid white;
}
.pfp {
width: 30px;
margin: 0 auto;
float: left;
padding: 60px;
}
.pfpp {
width : 250px;
border-radius: 20px;
}
.textt {
margin: 0 auto;
text-align: center;
}
.txtdesign {
color: white;
transform: translate(250px, 150px);
float: left;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="AboutMe">
<div class="container">
<div class="pfp">
<img src="https://via.placeholder.com/150/0000FF/808080?text=my%20face" class="pfpp">
</div>
<div class="textt">
<h1 class="txtdesign">Hi! My name is...</h1>
</div>
</div>
</section></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:18:34.050",
"Id": "524438",
"Score": "4",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p><strong>You can do something like this:</strong></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-css lang-css prettyprint-override\"><code>*{margin:0;padding:0;}\n\n.item1{grid-area:pfp;}\n.item2{grid-area:text;}\n\n.container{\n display:grid;\n grid-template-columns: 150px auto;\n width:80%;\n background-color:black;\n margin:0 auto;\n margin-top:10vh;\n padding:30px 30px 30px 30px;\n height:90%;\n border-radius:10px;\n min-height:600px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><section id=\"AboutMe\">\n\n <div class=\"container\">\n \n <div class=\"pfp\">\n <img src=\"https://via.placeholder.com/150/0000FF/808080?text=my%20face\">\n </div> \n \n <div class=\"text\" style=\"padding:5px 20px 5px 20px;\"> \n <h1 class=\"txtdesign\" style=\"color:white\">Hi! My name is...</h1>\n </div>\n \n </div>\n\n</section></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Note:</strong> this css uses grid layout, you can read more about it <a href=\"https://www.w3schools.com/css/css_grid.asp\" rel=\"nofollow noreferrer\">here</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:57:16.697",
"Id": "524479",
"Score": "1",
"body": "Thank you so much its much better now :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:57:42.230",
"Id": "524480",
"Score": "0",
"body": "I apologize I cannot upvote this answer because my reputation is too low, but thank you so much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T11:29:22.120",
"Id": "524484",
"Score": "0",
"body": "There are cool features in CSS that allow you to do complex things with simple code. It's good to learn different approaches, because CSS codes can become really dirty and unpleasant."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:39:01.630",
"Id": "265544",
"ParentId": "265508",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265544",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:23:04.277",
"Id": "265508",
"Score": "-1",
"Tags": [
"html",
"css"
],
"Title": "Is there a correct way to do this layout in HTML/CSS"
}
|
265508
|
<p>I have this watcher in my <code>app.vue</code> that makes sure the right theme <code>attribute</code> is set on the <code>html</code> tag. I have a nested if/else loop, and as you can see in the code below I have two different conditions but two times the same statements.</p>
<p>Is there some way to code this is a more reusable way? I can imagine in some cases there are going to be more conditions with maybe the same statements.</p>
<pre><code> created() {
const media = window.matchMedia("(prefers-color-scheme: dark)");
this.$store.watch(
(state) => {
return state.settings.colorSettings.automatic;
},
(currentAutomaticValue) => {
if (currentAutomaticValue) {
media.addEventListener("change", this.setTheme);
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? setThemeAttribute(themes.dark) // 1
: setThemeAttribute(themes.default); // 2
} else {
media.removeEventListener("change", this.setTheme);
this.colorSettings.darkMode
? setThemeAttribute(themes.dark) // 1
: setThemeAttribute(themes.default); // 2
}
},
{ immediate: true }
);
},
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:41:48.777",
"Id": "524441",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:47:38.740",
"Id": "524442",
"Score": "0",
"body": "What does the method `setThemeAttribute` do?"
}
] |
[
{
"body": "<p>So you have a boolean, and from this boolean you go with either <code>themes.dark</code> or <code>themes.default</code>. Easy, extract a method that takes a boolean and properly calls <code>setThemeAttribute</code>.</p>\n<pre><code>function setThemeBoolean(bool) {\n setThemeAttribute(bool ? themes.dark : themes.default);\n}\n...\nif (currentAutomaticValue) {\n media.addEventListener("change", this.setTheme);\n setThemeBoolean(window.matchMedia &&\n window.matchMedia("(prefers-color-scheme: dark)").matches);\n} else {\n media.removeEventListener("change", this.setTheme);\n setThemeBoolean(this.colorSettings.darkMode);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:51:59.947",
"Id": "524444",
"Score": "0",
"body": "This is the best answer I could come up with, but I'd recommend posting more context next time. I just have a feeling that you're not doing things in the most optimal way. I suspect the whole `this.$store.watch` might not be necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T06:26:20.947",
"Id": "524469",
"Score": "0",
"body": "Modern JS?? `matchMedia` has full support https://caniuse.com/matchmedia so no need to predicate its existence, you should use the optional chaining operator if needing to call an unknown. EG `matchMedia?.(\"foo\").matches`, and `window` is the default `globalThis` so its use is almost always redundant. Thus the split line becomes `setThemeBoolean(matchMedia(\"foo\").matches)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T12:20:07.710",
"Id": "524488",
"Score": "0",
"body": "@Blindman67 I just addressed the main question, I'd recommend you post your findings in another answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:50:47.067",
"Id": "265519",
"ParentId": "265510",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:31:04.457",
"Id": "265510",
"Score": "-1",
"Tags": [
"javascript",
"vue.js"
],
"Title": "JS - Same recurring statements in if-else"
}
|
265510
|
<p>I'm trying to create a function to check multiple conditions of data.
The function will return a list if the data is errors.</p>
<p>Here is my idea:</p>
<pre><code>error_lists = []
def check(A, B, C, D, E):
check condition 1 for A
if there is a error -> error_list.append(1)
check condition 2 for B
if there is a error -> error_list.append(2)
check condition 3 for C
if there is a error -> error_list.append(3)
check condition 4 for D
if there is a error -> error_list.append(4)
check condition 5 for E
if there is a error -> error_list.append(5)
return error_list
</code></pre>
<p>If A, B, C do not meet the requirement, the function will return the error_list: [1,2,3]. Likewise, the function will return [2,5] if only B or E do not meet the requirement</p>
<p>Actually I've already written the code, however I feel that it need to be improved.</p>
<pre><code>P_list = [35000, 50000, 80000, 120000, 150000, 180,000]
def data_check(Staff_id, A ,B, x, y, z, t, u, D):
error_list = []
wh = x + y
tot = z + t
C = [x, y, z, t, u]
"""First condition"""
if A not in P_list:
print(f"Error type 1 in the data of {staff_id} {A} is not True")
error_list.append(1)
"""Second condition"""
if B >= 48:
print(f"Error type 2 in the data of {staff_id} {B} is not True")
error_list.append(2)
"""Third condition"""
for k in C:
if k < 0:
print(f"Error type 3 in the data of {staff_id} {k} is less than 0")
error_list.append(3)
"""Fourth condition"""
if D >= 3000000:
print(f"Error type 4 in the data of {staff_id} D is not true")
error_list.append(4)
"""Fifth condition"""
if tot >= wh:
print(f"Error type 5 in the data of {staff_id} E is not true")
error_list.append(5)
return print(error_list)
data_check("1a88s2s", 50000 ,71, 23, 28, 3,5, 12, 3500000)
</code></pre>
<p>Does anybody has any suggestion ?</p>
<p>Many thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T18:32:40.357",
"Id": "524456",
"Score": "1",
"body": "Welcome to Code Review! It appears there is a slight flaw with the code: \"_NameError: name 'staff_id' is not defined_\" - it can be fixed by changing the case on the argument."
}
] |
[
{
"body": "<ul>\n<li><code>P_list</code> should be a set, not a list, based on its usage; it's only used for membership checks. You can also pre-bind to the <code>__contains__</code> member to get a function reference you can call, constraining the set to one purpose.</li>\n<li>Add PEP484 type hints</li>\n<li><code>C</code> should be a tuple based on its usage since it's immutable</li>\n<li>Your <code>print</code> statements should not be mixed in with your logic, and should be separated to another method</li>\n<li>Consider representing your errors not as free integers, but as constrained enumeration values</li>\n<li>Use an <code>any</code> generator for your <code>C</code> negative check</li>\n<li><code>180,000</code> is likely incorrect and should be <code>180_000</code></li>\n<li><code>return print</code> is meaningless and will always return <code>None</code>; instead consider returning your error values or yielding them as a generator</li>\n<li><code>staff_id</code> shouldn't be passed into <code>data_check</code> at all; it's only used for formatting error messages which again can exist in a separate method</li>\n<li>Your letter-salad variable names are helping no one. You need to spell out what these actually mean.</li>\n<li>Moving your intermediate error-checking variables <code>C</code>, <code>wh</code> and <code>tot</code> closer to where they're used is, I think, clearer</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import enum\nfrom enum import Enum\nfrom typing import Iterable\n\nin_p_list = frozenset((35_000, 50_000, 80_000, 120_000, 150_000, 180_000)).__contains__\n\n\n@enum.unique\nclass ErrorType(Enum):\n REJECTED_A = 1\n B_TOO_HIGH = 2\n NEGATIVE_C = 3\n D_TOO_HIGH = 4\n TOTAL_TOO_HIGH = 5\n\n\ndef data_check(\n A: int,\n B: int,\n x: int,\n y: int,\n z: int,\n t: int,\n u: int,\n D: int,\n) -> Iterable[ErrorType]:\n if not in_p_list(A):\n yield ErrorType.REJECTED_A\n\n if B >= 48:\n yield ErrorType.B_TOO_HIGH\n\n C = (x, y, z, t, u)\n if any(k < 0 for k in C):\n yield ErrorType.NEGATIVE_C\n\n if D >= 3_000_000:\n yield ErrorType.D_TOO_HIGH\n\n wh = x + y\n tot = z + t\n if tot >= wh:\n yield ErrorType.TOTAL_TOO_HIGH\n\n\ndef print_errors(staff_id: str, errors: Iterable[ErrorType]) -> None:\n for error in errors:\n print(\n f'Error type {error.value} in the data of {staff_id}: {error.name}'\n )\n\n\ndef test() -> None:\n print_errors("1a88s2s", data_check(50000, 71, 23, 28, 3, 5, 12, 3500000))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Output</h2>\n<pre><code>Error type 2 in the data of 1a88s2s: B_TOO_HIGH\nError type 4 in the data of 1a88s2s: D_TOO_HIGH\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:12:00.230",
"Id": "524493",
"Score": "0",
"body": "Thank you so much for your response @Reinderien!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T02:37:12.147",
"Id": "265531",
"ParentId": "265511",
"Score": "3"
}
},
{
"body": "<h3>Adhere to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a></h3>\n<p>Like keep the style of identifiers consistent. <code>data_check, Staff_id, A ,B, x, y, z, t, u, D</code> - what style is common for all those names?</p>\n<h3>You can pass a list as an argument</h3>\n<p>No need to write so many arguments and gather them in a list - you can gather them when you call your function and pass only one <code>c</code> argument. The call will look like</p>\n<pre><code>data_check(staff_id, A, B, [x, y, z, t, u], D)\n</code></pre>\n<p>Also you can gather all trailing arguments in a list with * (the call whouln't change).</p>\n<h3>Use the loop</h3>\n<p>All the conditions are simple (one expression), all the messages are almost uniform. Thus, you can use the loop like this:</p>\n<pre><code>def data_check(staff_id, *args):\n conditions = [lambda x: x not in P_list,\n lambda x: x>=48, #are you trying to compare with '0'?\n lambda x: any(i<0 for i in x),\n ...\n ]\n result = []\n for i, (condition, arg) in enumerate(zip(conditions, args), 1):\n if not condition(arg):\n result.append(i)\n printf(f"Error type {i} in the data of {staff_id}: {arg} failed")\n return result\n</code></pre>\n<p>You can change lambdas to local functions; this can make the code more readable (with correct names):</p>\n<pre><code>def data_check(staff_id, *args):\n def not_in_p_list(x):\n return x not in P_list\n def greater_then_48(x):\n return x>48\n def any_less_then_0(x):\n return any(i<0 for i in x)\n conditions = [not_in_p_list,\n greater_then_48,\n any_less_then_0,\n ...\n ]\n</code></pre>\n<p>Of course, you can (and should) give conditions more informative names, like <code>not_listed_in_registry</code> or <code>negative_weight</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:12:40.133",
"Id": "524494",
"Score": "0",
"body": "Thank you so much for your response @PavloSlavynskyy !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T05:58:34.277",
"Id": "265535",
"ParentId": "265511",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:38:58.820",
"Id": "265511",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Create a function in Python to check for the data errors"
}
|
265511
|
<p>I have a Asp.Net API (.NET Framework 4.7.2). We recently updated Autofac to version 6.2.0. Autofac does not like some of our classes that don't have a public constructor.</p>
<p>Example class:</p>
<pre><code>public sealed class User
{
private static readonly Lazy<User> Lazy = new Lazy<User>(() => new User());
public static User Instance => Lazy.Value;
private User()
{
}
public DateTime UserDate { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Theme { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsLoggedIn { get; set; }
public PrismApplication LoggedInTo {get;set;}
}
</code></pre>
<p>I put in a work around to exclude these classes for the Autofac ContainerBuilder in <code>Global.asax.cs</code>:</p>
<pre><code> ...
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var targetAssembly = typeof(SalesDocumentCommandHandler).GetTypeInfo().Assembly;
var _skippedTypes = new HashSet<Type>();
_skippedTypes.Add(typeof(User));
_skippedTypes.Add(typeof(ReportClass));
_skippedTypes.Add(typeof(PrismApplication));
_skippedTypes.Add(typeof(OutboundEmailType));
_skippedTypes.Add(typeof(OEDataset.OERow));
_skippedTypes.Add(typeof(OEDataset.OESOPUserDefinedRow));
_skippedTypes.Add(typeof(OEDataset.OESOPPOLinkRow));
_skippedTypes.Add(typeof(OEDataset.OELineCommentRow));
_skippedTypes.Add(typeof(OEDataset.OEHeaderCommentRow));
_skippedTypes.Add(typeof(OEDataset.SOPTaxBreakupRow));
_skippedTypes.Add(typeof(OEDataset.OEHDetailRow));
_skippedTypes.Add(typeof(OEDataset.OEHHeaderRow));
_skippedTypes.Add(typeof(OEDataset.OEDetailRow));
_skippedTypes.Add(typeof(OEDataset.OEHeaderRow));
builder.RegisterAssemblyTypes(targetAssembly).Where(x => !_skippedTypes.Contains(x))
.As(type => type.GetInterfaces()
.Where(interfacetype => interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))
|| interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))
.AsSelf()
.InstancePerDependency();
targetAssembly = typeof(SalesDocumentCreatedEvent).GetTypeInfo().Assembly;
builder.RegisterAssemblyTypes(targetAssembly).Where(x => !_skippedTypes.Contains(x))
.As(type => type.GetInterfaces()
.Where(interfacetype => interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))
|| interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))
.AsSelf()
.InstancePerDependency().PublicOnly();
...
</code></pre>
<p>Isn't there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T14:41:37.000",
"Id": "524440",
"Score": "2",
"body": "https://stackoverflow.com/a/67643119/648075"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T03:29:36.920",
"Id": "524467",
"Score": "1",
"body": "In general if you want any DI solution to work nowadays you should use public constructors."
}
] |
[
{
"body": "<p>Generally speaking, classes with private-only constructors are irrelevant in terms of DI. It makes no sense to include them in your container because the container can't do anything with them.</p>\n<p>The only exception here is when you register the specific instance of a type with the container, which only really makes sense in scope of a singleton, e.g. something like:</p>\n<pre><code>builder.Register(c => User.Instance).As<User>().SingleInstance();\n</code></pre>\n<p>However, since you are clearly dealing with <em>multiple</em> of these classes, and you're trying to iteratively handle these, this custom-tailored-per-type approach seems out of scope for your intentions.</p>\n<p>The question all boils down to <em>"How do I find all of these types that I don't want to register?"</em>, which for your case means filling in <code>_skippedTypes</code> without needing to manually write down each class.</p>\n<p>The easiest way to do so is to use a marker interface and reflection.</p>\n<p>A marker interface is an empty interface:</p>\n<pre><code>public interface IUnmapped {}\n</code></pre>\n<p>Which your intended classes then implement:</p>\n<pre><code>public class User : IUnmapped\n{\n // ...\n}\n</code></pre>\n<p>And then you can use reflection to find all of the types that implement this interface:</p>\n<pre><code>var type = typeof(IUnmapped);\nvar skippedTypes = AppDomain.CurrentDomain\n .GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => type.IsAssignableFrom(p));\n</code></pre>\n<p>Which in turn leads to being able to refactor the initial code:</p>\n<pre><code>var type = typeof(IUnmapped);\n\nbuilder\n .RegisterAssemblyTypes(targetAssembly)\n .Where(x => !type.IsAssignableFrom(x))\n .As(type => \n type.GetInterfaces()\n .Where(interfacetype => \n interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))\n || interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))\n .AsSelf()\n .InstancePerDependency();\n</code></pre>\n<hr />\n<p>Some further notes:</p>\n<ul>\n<li>When using marker interfaces, I'd be more inclined to use a positive marker, i.e. <code>IMapped</code> to indicate the types that you <em>do</em> want to add to the container. The only difference in your reflection logic is inverting the Where:</li>\n</ul>\n\n<pre><code>var type = typeof(IMapped);\nvar skippedTypes = AppDomain.CurrentDomain\n .GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => !type.IsAssignableFrom(p));\n</code></pre>\n<p>Or when refactoring the old code:</p>\n<pre><code>var type = typeof(IMapped);\n\nbuilder\n .RegisterAssemblyTypes(targetAssembly)\n .Where(x => type.IsAssignableFrom(x))\n .As(type => \n type.GetInterfaces()\n .Where(interfacetype => \n interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))\n || interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))\n .AsSelf()\n .InstancePerDependency();\n</code></pre>\n<ul>\n<li>You can cut out the middle man marker interface, and use reflection to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.type.getconstructors?view=net-5.0\" rel=\"nofollow noreferrer\">look up each type's public constructors</a>, and then pick the ones that don't have any. However, I am unsure how much of a performance hit this might entail.</li>\n</ul>\n\n<pre><code>var skippedTypes = AppDomain.CurrentDomain\n .GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => !p.GetConstructors().Any());\n</code></pre>\n<p>I think I'd still prefer the marker interface, <em>even though I generally dislikee marker interfaces</em>, simply because it means you're able to also skip a type that has a public constructor when there is an ulterior reason to want to skip it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:22:42.120",
"Id": "525746",
"Score": "0",
"body": "Marker interface is not really good solution, because you are polluting your core code with implementation specific stuff. This is not how you build extensible and maintable systems"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:57:17.663",
"Id": "525748",
"Score": "0",
"body": "@ViktorLova: I agree, and I'm also not a fan of marker interfaces to boot. But given the constraints set by OP, there's little other recourse other than redesigning the domain from scratch, which I don't have the necessary information for (and is IMO out of scope). Marker interfaces are an easy way to avoid having to hand-craft this list of excluded types. There are other ways to do this via reflection, but it's all just a matter of picking the indicator that you prefer (namespace, class name, interface implementation, ...) and your feedback would apply equally to all of those indicators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T11:00:28.913",
"Id": "525749",
"Score": "0",
"body": "@ViktorLova: To be fair, Autofac is partly to blame here. I don't like broad-sweeping registration logic (barring specific use cases) specifically because any exception to the broad rule becomes cumbersome to (manually) manage. I'm much more a fan of explicit registration (again, barring certain use cases) which, while requiring a bit more typing, gives you much more direct control over the container."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T11:30:41.780",
"Id": "525750",
"Score": "0",
"body": "well, the problem is that author tries to register all types in assembly, including DTO. See my answer for details."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:01:12.603",
"Id": "266158",
"ParentId": "265512",
"Score": "1"
}
},
{
"body": "<p>Let's take a look on your code:</p>\n<pre><code> builder.RegisterAssemblyTypes(targetAssembly).Where(x => !_skippedTypes.Contains(x))\n .As(type => type.GetInterfaces()\n .Where(interfacetype => interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))\n || interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))\n .AsSelf()\n .InstancePerDependency();\n</code></pre>\n<p>What it says:</p>\n<ul>\n<li>register all types in assembly, except skipped types</li>\n<li>and if type implements <code>ICommandHandler<></code>/<code>IEventHandler<></code>, then make it available as <code>ICommandHandler<></code>/<code>IEventHandler<></code></li>\n<li>and also register type available as themselves</li>\n</ul>\n<p>Why do you need to register all types in assembly? I don't believe that you need it.</p>\n<p>That's what's wrong with the registration of <code>User</code> class. It's not related to having a non-public constructor. You simply don't need to inject it! So you don't need to register it.</p>\n<p>It's much better to do the next thing:</p>\n<ol>\n<li>Automate registration of repetitive things. Only for cases when the rule is suitable for every class.\n<ul>\n<li>And use sugar <code>.AsClosedTypesOf()</code>. See <a href=\"https://autofac.readthedocs.io/en/latest/register/scanning.html\" rel=\"nofollow noreferrer\">Assembly scanning</a></li>\n</ul>\n</li>\n<li>Register manually each type</li>\n</ol>\n<p>Sample of code:</p>\n<pre><code>builder.RegisterAssemblyTypes(targetAssembly)\n .AsClosedTypesOf(typeof(ICommandHandler<>));\n\nbuilder.RegisterAssemblyTypes(targetAssembly)\n .AsClosedTypesOf(typeof(IEventHandler<>));\n\nbuilder.RegisterType<MyCustomService>();\n</code></pre>\n<p>If sugar <code>AsClosedTypesOf</code> is not available or not suitable, you can do next:</p>\n<pre><code>builder.RegisterAssemblyTypes(targetAssembly)\n .Where(x => type.GetInterfaces()\n .Any(interfaceType => interfaceType.IsAssignableFrom(typeof(ICommandHandler<>))))\n .As(type => type.GetInterfaces()\n .Where(interfaceType => interfaceType.IsAssignableFrom(typeof(ICommandHandler<>))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T11:28:22.367",
"Id": "266160",
"ParentId": "265512",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266158",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T12:40:22.750",
"Id": "265512",
"Score": "0",
"Tags": [
"c#",
"autofac"
],
"Title": "Should I get Autofac to include classes that don't have a public constructor?"
}
|
265512
|
<p>I was implementing the AAN algorithm for computing the 2D Discrete Cosine Transform on an 8*8 array. I perform both the forward and inverse AAN algorithms.</p>
<p>My code is extremely fast compared to the naive DCT algorithm but I feel that my implementation could be faster. How can I improve the performance of my transforms?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
/*
File: dct.c
Summary: 2D AAN implementation of Discrete Cosine transform
Code for Forward and Inverse DCT using AAN method
Sources: Forward DCT inspired by // https://unix4lyfe.org/dct-1d/
Inverse DCT inspired by (Everything you need to know about jpeg Youtube Playlist) https://www.youtube.com/watch?v=sb8CQ9knDgI&list=PLpsTn9TA_Q8VMDyOPrDKmSJYt1DLgDZU4
Input : float array of 64 elements representing 8 * 8 block
*Note I use a 1-dimensional array to represent 2d data
*/
//Compute forward dct
void ForwardDCTComponent(float *component)
{
/*Forward DCT constants*/
const float a1 = 0.707;
const float a2 = 0.541;
const float a3 = 0.707;
const float a4 = 1.307;
const float a5 = 0.383;
const float s0 = 0.353553;
const float s1 = 0.254898;
const float s2 = 0.270598;
const float s3 = 0.300672;
const float s4 = s0;
const float s5 = 0.449988;
const float s6 = 0.653281;
const float s7 = 1.281458;
/*Forward DCT constants*/
for(int i = 0; i < 8; i++)
{
const float b0 = component[0*8 + i] + component[7*8 + i];
const float b1 = component[1*8 + i] + component[6*8 + i];
const float b2 = component[2*8 + i] + component[5*8 + i];
const float b3 = component[3*8 + i] + component[4*8 + i];
const float b4 =-component[4*8 + i] + component[3*8 + i];
const float b5 =-component[5*8 + i] + component[2*8 + i];
const float b6 =-component[6*8 + i] + component[1*8 + i];
const float b7 =-component[7*8 + i] + component[0*8 + i];
const float c0 = b0 + b3;
const float c1 = b1 + b2;
const float c2 =-b2 + b1;
const float c3 =-b3 + b0;
const float c4 =-b4 - b5;
const float c5 = b5 + b6;
const float c6 = b6 + b7;
const float c7 = b7;
const float d0 = c0 + c1;
const float d1 =-c1 + c0;
const float d2 = c2 + c3;
const float d3 = c3;
const float d4 = c4;
const float d5 = c5;
const float d6 = c6;
const float d7 = c7;
const float d8 = (d4+d6) * a5;
const float e0 = d0;
const float e1 = d1;
const float e2 = d2 * a1;
const float e3 = d3;
const float e4 = -d4 * a2 - d8;
const float e5 = d5 * a3;
const float e6 = d6 * a4 - d8;
const float e7 = d7;
const float f0 = e0;
const float f1 = e1;
const float f2 = e2 + e3;
const float f3 = e3 - e2;
const float f4 = e4;
const float f5 = e5 + e7;
const float f6 = e6;
const float f7 = e7 - e5;
const float g0 = f0;
const float g1 = f1;
const float g2 = f2;
const float g3 = f3;
const float g4 = f4 + f7;
const float g5 = f5 + f6;
const float g6 = -f6 + f5;
const float g7 = f7 - f4;
component[0*8 + i] = g0 * s0;
component[4*8 + i] = g1 * s4;
component[2*8 + i] = g2 * s2;
component[6*8 + i] = g3 * s6;
component[5*8 + i] = g4 * s5;
component[1*8 + i] = g5 * s1;
component[7*8 + i] = g6 * s7;
component[3*8 + i] = g7 * s3;
}
for(int i = 0; i < 8; i++)
{
const float b0 = component[i*8 + 0] + component[i*8 + 7];
const float b1 = component[i*8 + 1] + component[i*8 + 6];
const float b2 = component[i*8 + 2] + component[i*8 + 5];
const float b3 = component[i*8 + 3] + component[i*8 + 4];
const float b4 =-component[i*8 + 4] + component[i*8 + 3];
const float b5 =-component[i*8 + 5] + component[i*8 + 2];
const float b6 =-component[i*8 + 6] + component[i*8 + 1];
const float b7 =-component[i*8 + 7] + component[i*8 + 0] ;
const float c0 = b0 + b3;
const float c1 = b1 + b2;
const float c2 =-b2 + b1;
const float c3 =-b3 + b0;
const float c4 =-b4 - b5;
const float c5 = b5 + b6;
const float c6 = b6 + b7;
const float c7 = b7;
const float d0 = c0 + c1;
const float d1 =-c1 + c0;
const float d2 = c2 + c3;
const float d3 = c3;
const float d4 = c4;
const float d5 = c5;
const float d6 = c6;
const float d7 = c7;
const float d8 = (d4+d6) * a5;
const float e0 = d0;
const float e1 = d1;
const float e2 = d2 * a1;
const float e3 = d3;
const float e4 = -d4 * a2 - d8;
const float e5 = d5 * a3;
const float e6 = d6 * a4 - d8;
const float e7 = d7;
const float f0 = e0;
const float f1 = e1;
const float f2 = e2 + e3;
const float f3 = e3 - e2;
const float f4 = e4;
const float f5 = e5 + e7;
const float f6 = e6;
const float f7 = e7 - e5;
const float g0 = f0;
const float g1 = f1;
const float g2 = f2;
const float g3 = f3;
const float g4 = f4 + f7;
const float g5 = f5 + f6;
const float g6 = -f6 + f5;
const float g7 = f7 - f4;
component[i*8 + 0] = g0 * s0;
component[i*8 + 4] = g1 * s4;
component[i*8 + 2] = g2 * s2;
component[i*8 + 6] = g3 * s6;
component[i*8 + 5] = g4 * s5;
component[i*8 + 1] = g5 * s1;
component[i*8 + 7] = g6 * s7;
component[i*8 + 3] = g7 * s3;
}
}
void InverseDCTComponent(float *component)
{
const float m0 = 2.0 * cos(1.0/16.0 * 2.0 * M_PI);
const float m1 = 2.0 * cos(2.0/16.0 * 2.0 * M_PI);
const float m3 = 2.0 * cos(2.0/16.0 * 2.0 * M_PI);
const float m5 = 2.0 * cos(3.0/16.0 * 2.0 * M_PI);
const float m2 = m0-m5;
const float m4 = m0+m5;
const float s0 = cos(0.0/16.0 *M_PI)/sqrt(8);
const float s1 = cos(1.0/16.0 *M_PI)/2.0;
const float s2 = cos(2.0/16.0 *M_PI)/2.0;
const float s3 = cos(3.0/16.0 *M_PI)/2.0;
const float s4 = cos(4.0/16.0 *M_PI)/2.0;
const float s5 = cos(5.0/16.0 *M_PI)/2.0;
const float s6 = cos(6.0/16.0 *M_PI)/2.0;
const float s7 = cos(7.0/16.0 *M_PI)/2.0;
for(int i = 0; i < 8; i++)
{
const float g0 = component[0*8 + i] * s0;
const float g1 = component[4*8 + i] * s4;
const float g2 = component[2*8 + i] * s2;
const float g3 = component[6*8 + i] * s6;
const float g4 = component[5*8 + i] * s5;
const float g5 = component[1*8 + i] * s1;
const float g6 = component[7*8 + i] * s7;
const float g7 = component[3*8 + i] * s3;
const float f0 = g0;
const float f1 = g1;
const float f2 = g2;
const float f3 = g3;
const float f4 = g4 - g7;
const float f5 = g5 + g6;
const float f6 = g5 - g6;
const float f7 = g4 + g7;
const float e0 = f0;
const float e1 = f1;
const float e2 = f2 - f3;
const float e3 = f2 + f3;
const float e4 = f4;
const float e5 = f5 - f7;
const float e6 = f6;
const float e7 = f5 + f7;
const float e8 = f4 + f6;
const float d0 = e0;
const float d1 = e1;
const float d2 = e2 * m1;
const float d3 = e3;
const float d4 = e4 * m2;
const float d5 = e5 * m3;
const float d6 = e6 * m4;
const float d7 = e7;
const float d8 = e8 * m5;
const float c0 = d0 + d1;
const float c1 = d0 - d1;
const float c2 = d2 - d3;
const float c3 = d3;
const float c4 = d4 + d8;
const float c5 = d5 + d7;
const float c6 = d6 - d8;
const float c7 = d7;
const float c8 = c5 - c6;
const float b0 = c0 + c3;
const float b1 = c1 + c2;
const float b2 = c1 - c2;
const float b3 = c0 - c3;
const float b4 = c4 - c8;
const float b5 = c8;
const float b6 = c6 - c7;
const float b7 = c7;
component[0 * 8 + i] = b0 + b7;
component[1 * 8 + i] = b1 + b6;
component[2 * 8 + i] = b2 + b5;
component[3 * 8 + i] = b3 + b4;
component[4 * 8 + i] = b3 - b4;
component[5 * 8 + i] = b2 - b5;
component[6 * 8 + i] = b1 - b6;
component[7 * 8 + i] = b0 - b7;
}
for(int i = 0 ; i < 8; i++)
{
const float g0 = component[i*8 + 0] * s0;
const float g1 = component[i*8 + 4] * s4;
const float g2 = component[i*8 + 2] * s2;
const float g3 = component[i*8 + 6] * s6;
const float g4 = component[i*8 + 5] * s5;
const float g5 = component[i*8 + 1] * s1;
const float g6 = component[i*8 + 7] * s7;
const float g7 = component[i*8 + 3] * s3;
const float f0 = g0;
const float f1 = g1;
const float f2 = g2;
const float f3 = g3;
const float f4 = g4 - g7;
const float f5 = g5 + g6;
const float f6 = g5 - g6;
const float f7 = g4 + g7;
const float e0 = f0;
const float e1 = f1;
const float e2 = f2 - f3;
const float e3 = f2 + f3;
const float e4 = f4;
const float e5 = f5 - f7;
const float e6 = f6;
const float e7 = f5 + f7;
const float e8 = f4 + f6;
const float d0 = e0;
const float d1 = e1;
const float d2 = e2 * m1;
const float d3 = e3;
const float d4 = e4 * m2;
const float d5 = e5 * m3;
const float d6 = e6 * m4;
const float d7 = e7;
const float d8 = e8 * m5;
const float c0 = d0 + d1;
const float c1 = d0 - d1;
const float c2 = d2 - d3;
const float c3 = d3;
const float c4 = d4 + d8;
const float c5 = d5 + d7;
const float c6 = d6 - d8;
const float c7 = d7;
const float c8 = c5 - c6;
const float b0 = c0 + c3;
const float b1 = c1 + c2;
const float b2 = c1 - c2;
const float b3 = c0 - c3;
const float b4 = c4 - c8;
const float b5 = c8;
const float b6 = c6 - c7;
const float b7 = c7;
component[i * 8 + 0] = b0 + b7;
component[i * 8 + 1] = b1 + b6;
component[i * 8 + 2] = b2 + b5;
component[i * 8 + 3] = b3 + b4;
component[i * 8 + 4] = b3 - b4;
component[i * 8 + 5] = b2 - b5;
component[i * 8 + 6] = b1 - b6;
component[i * 8 + 7] = b0 - b7;
}
}
void Print(float *array, int length)
{
for(int i = 0; i < 64; i++)
{
if(i > 0 && i % 8 == 0)
{
putchar('\n');
}
printf("%.1f ", array[i]);
}
putchar('\n');
}
int main()
{
//Create Sample Array
float *component = malloc(64 * sizeof(int));
for(int i = 0; i < 64; i++)
{
component[i] = 255;
}
//Print Sample Array
Print(component,64);
//Perform forward DCT
ForwardDCTComponent(component);
putchar('\n');
//Print results of forward dct
Print(component,64);
//Perform inverse DCT
InverseDCTComponent(component);
putchar('\n');
//Print results of inverse dct
Print(component,64);
free(component);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T07:08:11.360",
"Id": "524471",
"Score": "1",
"body": "What sort of things are in scope for improving the performance? Maybe SIMD? Fixed-point approximations?"
}
] |
[
{
"body": "<p><strong>Performance</strong></p>\n<blockquote>\n<p>How can I improve the performance of my transforms?</p>\n</blockquote>\n<p>So far, only some small ideas.</p>\n<p><strong><code>float</code> vs. <code>double</code> math</strong></p>\n<p>Do not call run-time <code>double</code> functions and constants for <code>float</code> math. A lot of time can be spent up and down converting.</p>\n<pre><code>// const float s1 = cos(1.0/16.0 * M_PI)/2.0;\ndefine M_PIf 3.14159265f\nconst float s1 = cosf(1.0f/16.0f * M_PIf)/2.0f;\n</code></pre>\n<p>On the other hand, even better to pre-calculate with high precision and then ...</p>\n<p><strong>Use constants</strong></p>\n<p>Some compilers will form compile time constants values involving constant equations with well known functions at compile time, others calculate at run-time. Simple coding the value is fastest. Some issues apply concerng how many digits to code. I reccomend at least 9 for <code>float</code> and OK to have many more. Pedantic code would use 17+ in case <code>float</code> has same precision as <code>double</code>. Your call.</p>\n<pre><code>// const float s0 = cos(0.0/16.0 *M_PI)/sqrt(8);\nconst float s0 = 0.353553391f // cos(0.0/16.0 *M_PI)/sqrt(8);\n</code></pre>\n<p><strong><code>static</code></strong></p>\n<p>Depending on the compiler, a <code>const</code> object may get re-loaded in a function.</p>\n<p><code>static</code> will certainly prevent that.</p>\n<pre><code>// const float s0 = 0.353553391f // cos(0.0/16.0 *M_PI)/sqrt(8);\nstatic const float s0 = 0.353553391f // cos(0.0/16.0 *M_PI)/sqrt(8);\n</code></pre>\n<p><strong>Micro optimization</strong></p>\n<p>Might save a tick or two</p>\n<pre><code> //for(int i = 0 ; i < 8; i++)\n // ... i*8 ...\n // ... i*8 ...\n for(int i = 0 ; i < 64; i+=8)\n ... i ...\n ... i ...\n</code></pre>\n<p><strong>Save coding time</strong></p>\n<p>This is a saving of your valuable coding time.</p>\n<p><code>void Print(float *array, int length)</code> does not use <code>length</code>. With a well enabled compiler, that would have generated a warning. Yet since it is there, it implies all warnings were not enabled.</p>\n<p>Save time, enable all warnings to guide you to better code.</p>\n<hr />\n<p><strong>Correctness</strong></p>\n<p><strong>Coding <code>float</code> vs. <code>double</code> constants</strong></p>\n<pre><code>// const float s0 = 0.353553;\nconst float s0 = 0.353553f;\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/q/66631288/2410359\">When does appending an 'f' change the value of a floating constant when assigned to a <code>float</code>?</a></p>\n<p><strong>Suspicious values</strong></p>\n<p>For <code>a1, a2, ...</code>, why only 3 significant digits constants? Perhaps <code>float a1 = 0.707106781f;</code> is better?</p>\n<p><strong>Assessing</strong></p>\n<p>To judge the correctness of a <code>float</code>, avoid using <code>"%.1f"</code> as that takes the <em>floating</em> out of floating point. Wee values are all <code>0.0</code> and large values have excessive digits.</p>\n<pre><code>// printf("%.1f ", array[i]);\nprintf("%.*g ", FLT_DECIMAL_DIG, array[i]);\n</code></pre>\n<hr />\n<p><strong>Latent Bug</strong></p>\n<p><code>float</code> and <code>int</code> are not specified to have the same size.</p>\n<p>Avoid sizing errors. Size to the referenced object, not type. Easier to code right, review and maintain.</p>\n<pre><code>// float *component = malloc(64 * sizeof(int)); // int ???\nfloat *component = malloc(sizeof *component * 64);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T04:50:13.763",
"Id": "265534",
"ParentId": "265527",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265534",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T19:21:23.693",
"Id": "265527",
"Score": "4",
"Tags": [
"performance",
"c",
"image"
],
"Title": "Faster AAN algorithm for calculating Discrete Cosine Transform"
}
|
265527
|
<p>I'm developing a notepad with virtual keyboard integration. The purpose is to provide a free tool to type the Latin letters with diacritics. I came this far, but due my limitation and lack of coding knowledge I think will need partners to improve the app.</p>
<p>I really appreciate your inputs and suggestions. Further collaboration is open. As a tribute, I will include you in the list of contributors to this application.</p>
<p><a href="https://i.stack.imgur.com/eNxsz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eNxsz.png" alt="enter image description here" /></a></p>
<p>I found some problems:</p>
<ol>
<li>Backspace jumps to the end of the whole text.</li>
<li>save & save as function seems not working well.</li>
<li>keyboard binding problems</li>
</ol>
<p>More features will be added later.</p>
<p>Here is the code:</p>
<pre><code>import tkinter as tk
import tkinter.scrolledtext as scrolledtext
import tkinter.messagebox
import webbrowser
from tkinter.font import Font
from tkinter import *
from tkinter.filedialog import asksaveasfilename, askopenfilename
from tkinter import ttk
root = Tk()
root.title("Citralekha 1.0 (Beta)")
#root.iconbitmap(r'keyboard.ico')
root.resizable(0,0)
root.geometry()
file_path = ''
global selected
selected = False
# font setting
text_font = Font(
size=12,
family="Helvetica")
# button functions
def select(value):
global text
if value=="⌫":
txt = TextArea.get(1.0,END)
val = len(txt)
TextArea.delete(1.0,END)
TextArea.insert(1.0,txt[:val-2])
elif value == "↵":
TextArea.insert(INSERT,"\n")
elif value=="Spasi":
TextArea.insert(INSERT," ")
elif value == "⇥":
TextArea.insert(INSERT," ")
elif value =="⇧":
caps_buttons = ['|', '‖','Ø','°','ᴗ','/','\\','(',')','[',']','§','-','—','=','+',
'A','Ā', 'Â','Å', 'B','C','D','Ḍ','E','É','Ә','Ê','⌫','1','2','3',
'F', 'G','H','Ḥ','I','Ī','Î','J','Ē','Ĕ','Ə̄','Ě','↵','4','5','6',
'K','Ḳ','L', 'Ḷ','L̥','M', 'Ṁ', 'Ṃ','N','Ṇ','Ṅ','Ŋ','⇥','7','8','9',
'O','Ö', 'P','Q','R','Ṛ','R̥','Ṙ','S','Ś','Ṣ','Ñ','⬆','0','{','}',
'T','Ṭ','U','Ū','Û','V','W','X','Y','Z','Ẓ','Ż','#','*','<', '>',
'Spasi','M̐','˜','’','‘','\'','"','.','·',';',':','!','?'
]
varrow = 2
varcolumn = 0
for button in caps_buttons:
command = lambda x=button:select(x)
if button !='Spasi':
Button(button_frame, font=text_font, text=button,width=2,bg='black',fg='white',activebackground="white",activeforeground='black', relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=varrow,column=varcolumn)
if button =='Spasi':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black', relief='raised',padx=62,pady=2,bd=4,command=command).grid(row=8,columnspan=4)
if button =='⌫':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=3,column=12)
if button =='↵':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=4,column=12)
if button =='⇥':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=5,column=12)
if button =='⬆':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=6,column=12)
varcolumn+=1
if varcolumn > 15 and varrow==2:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==3:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==4:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==5:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==6:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==7:
varcolumn=3
varrow+=1
elif value =="⬆":
varrow = 2
varcolumn = 0
for button in buttons:
command = lambda x=button:select(x)
if button !='Spasi':
Button(button_frame, font=text_font, text=button,width=2,bg='black',fg='white',activebackground="white",activeforeground='black', relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=varrow,column=varcolumn)
if button =='Spasi':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black', relief='raised',padx=62,pady=2,bd=4,command=command).grid(row=8,columnspan=4)
if button =='⌫':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=3,column=12)
if button =='↵':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=4,column=12)
if button =='⇥':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=5,column=12)
if button =='⇧':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=6,column=12)
varcolumn+=1
if varcolumn > 15 and varrow==2:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==3:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==4:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==5:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==6:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==7:
varcolumn=3
varrow+=1
else:
TextArea.insert(INSERT,value)
# Menu bar fungtions 'berkas' (file)
def set_file_path(path):
global file_path
file_path = path
def open_file(e):
path = askopenfilename(filetypes=[('Berkas Teks', '*.txt')])
with open(path, 'r') as file:
code = file.read()
TextArea.delete('1.0', END)
TextArea.insert('1.0', code)
# set_file_path(path)
def save_as():
path = asksaveasfilename(filetypes=[('Berkas Teks', '*.txt')])
with open(path, 'w') as file:
code = TextArea.get('1.0', END)
file.write(code)
set_file_path(path)
def save_file(e):
if file_path == 'path':
path = asksaveasfilename(filetypes=[('Berkas Teks', '*.txt')])
else:
path = file_path
with open(path, 'w') as file:
code = TextArea.get('1.0', END)
file.write(code)
set_file_path(path)
def endProgram():
root.destroy()
## Edit bar functions (sunting)
def cut_text(e):
global selected
if e:
selected = root.clipboard_get()
else:
if TextArea.selection_get():
selected = TextArea.selection_get()
TextArea.delete("sel.first", "sel.last")
root.clipboard_clear()
root.clipboard_append(selected)
def copy_text(e):
global selected
if e:
selected = root.clipboard_get()
if TextArea.selection_get():
selected = TextArea.selection_get()
root.clipboard_clear()
root.clipboard_append(selected)
def paste_text(e):
global selected
if e:
selected = root.clipboard_get()
else:
if selected:
position = TextArea.index(INSERT)
TextArea.insert(position, selected)
def clear_text():
TextArea.delete('1.0', END)
def select_all_text(event=None):
TextArea.tag_add('sel', '1.0', 'end')
return "break"
def find_text(event=None):
search_toplevel = Toplevel(root)
search_toplevel.title('Pencarian')
search_toplevel.transient(root)
Label(search_toplevel, text="Teks:").grid(row=0, column=0, sticky='e')
search_entry_widget = Entry(
search_toplevel, width=25)
search_entry_widget.grid(row=0, column=1, padx=2, pady=2, sticky='we')
search_entry_widget.focus_set()
ignore_case_value = IntVar()
Checkbutton(search_toplevel, text='Abaikan huruf kapital', variable=ignore_case_value).grid(
row=1, column=1, sticky='e', padx=2, pady=2)
Button(search_toplevel, text="Cari", underline=0,
command=lambda: search_output(
search_entry_widget.get(), ignore_case_value.get(),
TextArea, search_toplevel, search_entry_widget)
).grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=2)
def close_search_window():
TextArea.tag_remove('match', '1.0', END)
search_toplevel.destroy()
search_toplevel.protocol('WM_DELETE_WINDOW', close_search_window)
return "break"
def search_output(needle, if_ignore_case, TextArea,
search_toplevel, search_box):
TextArea.tag_remove('sesuai', '1.0', END)
ditemukan = 0
if needle:
start_pos = '1.0'
while True:
start_pos = TextArea.search(needle, start_pos,
nocase=if_ignore_case, stopindex=END)
if not start_pos:
break
end_pos = '{}+{}c'.format(start_pos, len(needle))
TextArea.tag_add('sesuai', start_pos, end_pos)
ditemukan += 1
start_pos = end_pos
TextArea.tag_config(
'sesuai', foreground='red', background='yellow')
search_box.focus_set()
search_toplevel.title('{} ditemukan'.format(ditemukan))
def open_guide():
webbrowser.open('https://kairaga.com/keyboard/citralekha',new=1)
#def open_angket():
# webbrowser.open('https://kairaga.com/keyboard/citralekha/masukan',new=2)
def about_window():
about_window = Toplevel(root)
about_window.geometry("450x180")
about_window.title("Tentang Citralekha")
about_window.resizable(False, False)
lbl = Label(about_window, text="Citralekha 1.0 (Beta) \n\n Program keyboard visual ini dikembangkan untuk membantu pengetikan huruf Latin dengan diakritik dalam proses transliterasi naskah dan prasasti di Nusantara. \n\n (c) 2021 Ilham Nurwansah \n\n GNU General Public License v3.0 ", wraplength=400, justify="center")
lbl.pack()
def supported_convention():
convention_window = Toplevel(root)
convention_window.geometry("400x300")
convention_window.title("Tentang Citralekha")
convention_window.resizable(False, False)
lbl = Label(convention_window, text="Keyboard ini mendukung sistem transliterasi berikut: \n \nInternational Alphabet of Sanskrit Transliteration (IAST) \nOld Javanese - English Dictionary \nDHARMA \nJavanese General System of Transliteration (JGST) \nPanduan transliterasi Arab-Latin Kementerian Agama RI \n\nSistem transkripsi: \nBahasa Sunda (Palangeran Éjahan Basa Sunda) \nBahasa Jawa (PUJL) \nBahasa Aceh", wraplength=370, justify="left")
lbl.pack()
# Root Widgets......
# Menu Bar
menu_bar = Menu(root)
# File bars
file_bar = Menu(menu_bar, tearoff=0)
# file.add_command(label='New File', command=new_file)
file_bar.add_command(label='Buka', command=lambda: open_file(False), accelerator="Ctrl+o")
file_bar.add_command(label='Simpan', command=lambda:save_file(False), accelerator="Ctrl+s")
file_bar.add_command(label='Simpan sebagai', command=save_as)
file_bar.add_separator()
file_bar.add_command(label="Keluar", command=endProgram)
menu_bar.add_cascade(label="Berkas", menu=file_bar)
# Edit Bars
edit_bar = Menu(menu_bar, tearoff=0)
#edit_bar.add_command(label="Undo", command="")
#edit_bar.add_command(label="Redo", command="")
#edit_bar.add_separator()
edit_bar.add_command(label="Potong", command=lambda: cut_text(False), accelerator="Ctrl+x")
edit_bar.add_command(label="Salin", command=lambda: copy_text(False), accelerator="Ctrl+c")
edit_bar.add_command(label="Tempel", command=lambda: paste_text(False), accelerator="Ctrl+v")
edit_bar.add_command(label="Pilih semua", command=lambda: select_all_text(False), accelerator="Ctrl+a")
edit_bar.add_separator()
edit_bar.add_command(label="Cari teks", command=lambda: find_text(False), accelerator="Ctrl+f")
edit_bar.add_separator()
edit_bar.add_command(label="Bersihkan teks", command=clear_text)
menu_bar.add_cascade(label="Sunting", menu=edit_bar)
# Help Bar
help_bar = Menu(menu_bar, tearoff=0)
help_bar.add_command(label="Dokumentasi", command=open_guide)
help_bar.add_command(label="Sistem Transliterasi", command=supported_convention)
#help_bar.add_command(label="[Beri Masukan]", command=open_angket)
help_bar.add_command(label="Tentang", command=about_window)
menu_bar.add_cascade(label="Bantuan", menu=help_bar)
# Print bar
# print_bar = Menu(menu_bar, tearoff=0)
# menu_bar.add_cascade(label="Print", menu=print_bar, command="")
# Text Frame
text_frame = Frame(root)
text_frame.grid(row=0,columnspan=16,padx=1, pady=1)
TextArea = Text(undo=True)
TextArea = scrolledtext.ScrolledText(text_frame, width=65,height=18, wrap=WORD,borderwidth=1,relief=RIDGE)
TextArea.configure(font=text_font)
TextArea.grid(row=0,columnspan=156)
# Button Frame
button_frame = Frame(root)
button_frame.grid(row=1, columnspan=16, padx=1, pady=1)
buttons = ['|', '‖','Ø','°','ᴗ','/','\\','(',')','[',']','§','-','—','=','+',
'a','ā', 'â','å','b','c','d','ḍ','e','é','ә','ê','⌫','1','2','3',
'f', 'g','h','ḥ','i','ī','î','j','ē','ĕ','ə̄','ě','↵','4','5','6',
'k','ḳ','l', 'ḷ','l̥', 'm', 'ṁ', 'ṃ','n','ṇ','ṅ','ŋ','⇥','7','8','9',
'o','ö', 'p','q','r', 'ṛ','r̥', 'ṙ','s','ś','ṣ','ñ','⇧','0','{','}',
't','ṭ','u','ū','û','v','w','x','y','z','ẓ','ż','#','*','<', '>',
'Spasi', 'm̐','˜', '’', '‘', '\'', '"','.' ,'·',';',':','!','?']
varrow = 2
varcolumn = 0
# Button functions
for button in buttons:
command = lambda x=button:select(x)
if button !='Spasi':
Button(button_frame, font=text_font, text=button,width=2,bg='black',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=varrow,column=varcolumn)
if button =='Spasi':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=62,pady=2,bd=4,command=command).grid(row=8,columnspan=4)
if button =='⌫':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=3,column=12)
if button =='↵':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=4,column=12)
if button =='⇥':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=5,column=12)
if button =='⇧':
Button(button_frame,text=button,width=2,bg='brown',fg='white',activebackground="white",activeforeground='black',
relief='raised',padx=4,pady=2,bd=4,command=command).grid(row=6,column=12)
varcolumn+=1
if varcolumn > 15 and varrow==2:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==3:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==4:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==5:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==6:
varcolumn=0
varrow+=1
if varcolumn > 15 and varrow ==7:
varcolumn=3
varrow+=1
# Keyboard Shortcut functions (Bindings)
root.bind('<Control-Key-x>', cut_text)
root.bind('<Control-Key-c>', copy_text)
root.bind('<Control-Key-v>', paste_text)
root.bind('<Control-Key-a>', select_all_text)
root.bind('<Control-Key-f>', find_text)
root.bind('<Control-Key-o>', open_file)
root.bind('<Control-Key-s>', save_file)
root.config(menu=menu_bar)
root.mainloop()
</code></pre>
<p>I also put the code on Github: <a href="https://github.com/Ilhamkang/Citralekha-visualKeyboard" rel="nofollow noreferrer">https://github.com/Ilhamkang/Citralekha-visualKeyboard</a></p>
<p>Thank you in advance!</p>
|
[] |
[
{
"body": "<p>This is already a fairly large program. Before expanding it further you're going to want to go back and clean up a collection of minor and major things:</p>\n<p>This program is written for a specific locale. It would be a good idea to be explicit about this locale:</p>\n<pre><code>from locale import setlocale, LC_ALL\n\nindonesian_bcf47 = 'id_ID'\nsetlocale(LC_ALL, (indonesian_bcf47, 'UTF-8'))\n</code></pre>\n<p>As is very typical for beginner Python UI programs, this relies too much on global state and global control references, and has too much global code. Side-effects include higher difficulty of unit testing, namespace pollution, etc. There are various solutions, the easiest typically being to move to a class system.</p>\n<p>Consider adding PEP484 type hints, i.e.</p>\n<pre><code>def find_text(event: Optional[Event] = None) -> str:\n</code></pre>\n<p><code>TextArea</code> is not a good name for a variable and should instead be <code>text_area</code>.</p>\n<p><code>open_file</code> has a bug - it doesn't notice when the user presses 'cancel', and crashes when the path is then an empty string.</p>\n<p><code>endProgram</code> should be <code>end_program</code> by PEP8.</p>\n<p>Your find code has a bug - when you find a match and the editor string is highlighted, that highlighting seems to be permanent and the user can add substrings within the highlighted area that will also be highlighted. A typical design would un-highlight the substring as soon as it's edited and no longer matches.</p>\n<p>I find</p>\n<pre><code> Checkbutton(search_toplevel, text='Abaikan huruf kapital', variable=ignore_case_value).grid(\n row=1, column=1, sticky='e', padx=2, pady=2)\n</code></pre>\n<p>to be more legible formatted as</p>\n<pre><code> Checkbutton(\n search_toplevel, text='Abaikan huruf kapital', variable=ignore_case_value,\n ).grid(\n row=1, column=1, sticky='e', padx=2, pady=2\n )\n</code></pre>\n<p>For the most part you've been very good at keeping your locale-specific content in strings, and keeping your code in English; but there's at least one miss (ditemukan).</p>\n<p><code>global text</code> seems to be dead code since that variable doesn't exist.</p>\n<p>A light refactor accommodating some of the above - but not going far enough to eliminate global references - is:</p>\n<pre><code>from locale import setlocale, LC_ALL\nfrom tkinter import scrolledtext\nimport webbrowser\nfrom tkinter.font import Font\nfrom tkinter import *\nfrom tkinter.filedialog import asksaveasfilename, askopenfilename\nfrom tkinter.scrolledtext import ScrolledText\nfrom typing import Optional\n\nroot = Tk()\nfile_path = ''\n\nglobal selected\nselected = False\n\n# font setting\ntext_font = Font(size=12, family="Helvetica")\n\n\n# button functions\n\ndef select(value: str) -> None:\n if value == "⌫":\n txt = TextArea.get(1.0, END)\n val = len(txt)\n TextArea.delete(1.0, END)\n TextArea.insert(1.0, txt[:val - 2])\n elif value == "↵":\n TextArea.insert(INSERT, "\\n")\n elif value == "Spasi":\n TextArea.insert(INSERT, " ")\n elif value == "⇥":\n TextArea.insert(INSERT, " ")\n elif value == "⇧":\n caps_buttons = ['|', '‖', 'Ø', '°', 'ᴗ', '/', '\\\\', '(', ')', '[', ']', '§', '-', '—', '=', '+',\n 'A', 'Ā', 'Â', 'Å', 'B', 'C', 'D', 'Ḍ', 'E', 'É', 'Ә', 'Ê', '⌫', '1', '2', '3',\n 'F', 'G', 'H', 'Ḥ', 'I', 'Ī', 'Î', 'J', 'Ē', 'Ĕ', 'Ə̄', 'Ě', '↵', '4', '5', '6',\n 'K', 'Ḳ', 'L', 'Ḷ', 'L̥', 'M', 'Ṁ', 'Ṃ', 'N', 'Ṇ', 'Ṅ', 'Ŋ', '⇥', '7', '8', '9',\n 'O', 'Ö', 'P', 'Q', 'R', 'Ṛ', 'R̥', 'Ṙ', 'S', 'Ś', 'Ṣ', 'Ñ', '⬆', '0', '{', '}',\n 'T', 'Ṭ', 'U', 'Ū', 'Û', 'V', 'W', 'X', 'Y', 'Z', 'Ẓ', 'Ż', '#', '*', '<', '>',\n 'Spasi', 'M̐', '˜', '’', '‘', '\\'', '"', '.', '·', ';', ':', '!', '?'\n ]\n varrow = 2\n varcolumn = 0\n\n for button in caps_buttons:\n command = lambda x=button: select(x)\n if button != 'Spasi':\n Button(button_frame, font=text_font, text=button, width=2, bg='black', fg='white',\n activebackground="white", activeforeground='black', relief='raised', padx=4, pady=2, bd=4,\n command=command).grid(row=varrow, column=varcolumn)\n if button == 'Spasi':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black', relief='raised', padx=62, pady=2, bd=4, command=command).grid(row=8,\n columnspan=4)\n if button == '⌫':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=3, column=12)\n if button == '↵':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=4, column=12)\n if button == '⇥':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=5, column=12)\n if button == '⬆':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=6, column=12)\n varcolumn += 1\n if varcolumn > 15 and varrow == 2:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 3:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 4:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 5:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 6:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 7:\n varcolumn = 3\n varrow += 1\n\n elif value == "⬆":\n varrow = 2\n varcolumn = 0\n\n for button in buttons:\n command = lambda x=button: select(x)\n if button != 'Spasi':\n Button(button_frame, font=text_font, text=button, width=2, bg='black', fg='white',\n activebackground="white", activeforeground='black', relief='raised', padx=4, pady=2, bd=4,\n command=command).grid(row=varrow, column=varcolumn)\n if button == 'Spasi':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black', relief='raised', padx=62, pady=2, bd=4, command=command).grid(row=8,\n columnspan=4)\n if button == '⌫':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=3, column=12)\n if button == '↵':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=4, column=12)\n if button == '⇥':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=5, column=12)\n if button == '⇧':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=6, column=12)\n\n varcolumn += 1\n if varcolumn > 15 and varrow == 2:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 3:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 4:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 5:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 6:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 7:\n varcolumn = 3\n varrow += 1\n\n else:\n TextArea.insert(INSERT, value)\n\n\n# Menu bar functions 'berkas' (file)\ndef set_file_path(path) -> None:\n global file_path\n file_path = path\n\n\ndef open_file(e: bool) -> None:\n path = askopenfilename(filetypes=[('Berkas Teks', '*.txt')])\n if path:\n with open(path, 'r') as file:\n code = file.read()\n TextArea.delete('1.0', END)\n TextArea.insert('1.0', code)\n\n\ndef save_as() -> None:\n path = asksaveasfilename(filetypes=[('Berkas Teks', '*.txt')])\n with open(path, 'w') as file:\n code = TextArea.get('1.0', END)\n file.write(code)\n set_file_path(path)\n\n\ndef save_file(e: bool) -> None:\n if file_path == 'path':\n path = asksaveasfilename(filetypes=[('Berkas Teks', '*.txt')])\n else:\n path = file_path\n with open(path, 'w') as file:\n code = TextArea.get('1.0', END)\n file.write(code)\n set_file_path(path)\n\n\ndef endProgram() -> None:\n root.destroy()\n\n\n## Edit bar functions (sunting)\n\ndef cut_text(e: Event) -> None:\n global selected\n if e:\n selected = root.clipboard_get()\n else:\n if TextArea.selection_get():\n selected = TextArea.selection_get()\n TextArea.delete("sel.first", "sel.last")\n root.clipboard_clear()\n root.clipboard_append(selected)\n\n\ndef copy_text(e: Event) -> None:\n global selected\n if e:\n selected = root.clipboard_get()\n\n if TextArea.selection_get():\n selected = TextArea.selection_get()\n root.clipboard_clear()\n root.clipboard_append(selected)\n\n\ndef paste_text(e: Event) -> None:\n global selected\n if e:\n selected = root.clipboard_get()\n elif selected:\n position = TextArea.index(INSERT)\n TextArea.insert(position, selected)\n\n\ndef clear_text() -> None:\n TextArea.delete('1.0', END)\n\n\ndef select_all_text(event: Optional[Event] = None) -> str:\n TextArea.tag_add('sel', '1.0', 'end')\n return "break"\n\n\ndef find_text(event: Optional[Event] = None) -> str:\n search_toplevel = Toplevel(root)\n search_toplevel.title('Pencarian')\n search_toplevel.transient(root)\n\n Label(search_toplevel, text="Teks:").grid(row=0, column=0, sticky='e')\n\n search_entry_widget = Entry(\n search_toplevel, width=25)\n search_entry_widget.grid(row=0, column=1, padx=2, pady=2, sticky='we')\n search_entry_widget.focus_set()\n ignore_case_value = IntVar()\n Checkbutton(\n search_toplevel, text='Abaikan huruf kapital', variable=ignore_case_value,\n ).grid(\n row=1, column=1, sticky='e', padx=2, pady=2\n )\n Button(\n search_toplevel, text="Cari", underline=0,\n command=lambda: search_output(\n search_entry_widget.get(), ignore_case_value.get() == 1,\n TextArea, search_toplevel, search_entry_widget,\n )\n ).grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=2)\n\n def close_search_window() -> None:\n TextArea.tag_remove('match', '1.0', END)\n search_toplevel.destroy()\n\n search_toplevel.protocol('WM_DELETE_WINDOW', close_search_window)\n return "break"\n\n\ndef search_output(\n needle: str, if_ignore_case: bool, text_area: ScrolledText,\n search_toplevel: Toplevel, search_box: Entry,\n) -> None:\n text_area.tag_remove('sesuai', '1.0', END)\n ditemukan = 0\n if needle:\n start_pos = '1.0'\n while True:\n start_pos = text_area.search(\n needle, start_pos, nocase=if_ignore_case, stopindex=END,\n )\n if not start_pos:\n break\n end_pos = '{}+{}c'.format(start_pos, len(needle))\n text_area.tag_add('sesuai', start_pos, end_pos)\n ditemukan += 1\n start_pos = end_pos\n text_area.tag_config(\n 'sesuai', foreground='red', background='yellow')\n search_box.focus_set()\n search_toplevel.title('{} ditemukan'.format(ditemukan))\n\n\ndef open_guide() -> None:\n webbrowser.open('https://kairaga.com/keyboard/citralekha', new=1)\n\n\n# def open_angket():\n# webbrowser.open('https://kairaga.com/keyboard/citralekha/masukan',new=2)\n\ndef about_window() -> None:\n about_window = Toplevel(root)\n about_window.geometry("450x180")\n about_window.title("Tentang Citralekha")\n about_window.resizable(False, False)\n lbl = Label(about_window,\n text="Citralekha 1.0 (Beta) \\n\\n Program keyboard visual ini dikembangkan untuk membantu pengetikan huruf Latin dengan diakritik dalam proses transliterasi naskah dan prasasti di Nusantara. \\n\\n (c) 2021 Ilham Nurwansah \\n\\n GNU General Public License v3.0 ",\n wraplength=400, justify="center")\n lbl.pack()\n\n\ndef supported_convention() -> None:\n convention_window = Toplevel(root)\n convention_window.geometry("400x300")\n convention_window.title("Tentang Citralekha")\n convention_window.resizable(False, False)\n lbl = Label(convention_window,\n text="Keyboard ini mendukung sistem transliterasi berikut: \\n \\nInternational Alphabet of Sanskrit Transliteration (IAST) \\nOld Javanese - English Dictionary \\nDHARMA \\nJavanese General System of Transliteration (JGST) \\nPanduan transliterasi Arab-Latin Kementerian Agama RI \\n\\nSistem transkripsi: \\nBahasa Sunda (Palangeran Éjahan Basa Sunda) \\nBahasa Jawa (PUJL) \\nBahasa Aceh",\n wraplength=370, justify="left")\n lbl.pack()\n\n\nmenu_bar = Menu(root)\nfile_bar = Menu(menu_bar, tearoff=0)\nedit_bar = Menu(menu_bar, tearoff=0)\nhelp_bar = Menu(menu_bar, tearoff=0)\ntext_frame = Frame(root)\nTextArea = scrolledtext.ScrolledText(text_frame, width=65, height=18, wrap=WORD, borderwidth=1, relief=RIDGE)\nbutton_frame = Frame(root)\n\nbuttons = ['|', '‖', 'Ø', '°', 'ᴗ', '/', '\\\\', '(', ')', '[', ']', '§', '-', '—', '=', '+',\n 'a', 'ā', 'â', 'å', 'b', 'c', 'd', 'ḍ', 'e', 'é', 'ә', 'ê', '⌫', '1', '2', '3',\n 'f', 'g', 'h', 'ḥ', 'i', 'ī', 'î', 'j', 'ē', 'ĕ', 'ə̄', 'ě', '↵', '4', '5', '6',\n 'k', 'ḳ', 'l', 'ḷ', 'l̥', 'm', 'ṁ', 'ṃ', 'n', 'ṇ', 'ṅ', 'ŋ', '⇥', '7', '8', '9',\n 'o', 'ö', 'p', 'q', 'r', 'ṛ', 'r̥', 'ṙ', 's', 'ś', 'ṣ', 'ñ', '⇧', '0', '{', '}',\n 't', 'ṭ', 'u', 'ū', 'û', 'v', 'w', 'x', 'y', 'z', 'ẓ', 'ż', '#', '*', '<', '>',\n 'Spasi', 'm̐', '˜', '’', '‘', '\\'', '"', '.', '·', ';', ':', '!', '?']\n\n\ndef main() -> None:\n indonesian_bcf47 = 'id_ID'\n setlocale(LC_ALL, (indonesian_bcf47, 'UTF-8'))\n\n root.title("Citralekha 1.0 (Beta)")\n root.resizable(0, 0)\n root.geometry()\n\n # file.add_command(label='New File', command=new_file)\n file_bar.add_command(label='Buka', command=lambda: open_file(False), accelerator="Ctrl+o")\n file_bar.add_command(label='Simpan', command=lambda: save_file(False), accelerator="Ctrl+s")\n file_bar.add_command(label='Simpan sebagai', command=save_as)\n file_bar.add_separator()\n file_bar.add_command(label="Keluar", command=endProgram)\n menu_bar.add_cascade(label="Berkas", menu=file_bar)\n\n # edit_bar.add_command(label="Undo", command="")\n # edit_bar.add_command(label="Redo", command="")\n # edit_bar.add_separator()\n edit_bar.add_command(label="Potong", command=lambda: cut_text(False), accelerator="Ctrl+x")\n edit_bar.add_command(label="Salin", command=lambda: copy_text(False), accelerator="Ctrl+c")\n edit_bar.add_command(label="Tempel", command=lambda: paste_text(False), accelerator="Ctrl+v")\n edit_bar.add_command(label="Pilih semua", command=lambda: select_all_text(False), accelerator="Ctrl+a")\n edit_bar.add_separator()\n edit_bar.add_command(label="Cari teks", command=lambda: find_text(False), accelerator="Ctrl+f")\n edit_bar.add_separator()\n edit_bar.add_command(label="Bersihkan teks", command=clear_text)\n menu_bar.add_cascade(label="Sunting", menu=edit_bar)\n\n help_bar.add_command(label="Dokumentasi", command=open_guide)\n help_bar.add_command(label="Sistem Transliterasi", command=supported_convention)\n # help_bar.add_command(label="[Beri Masukan]", command=open_angket)\n help_bar.add_command(label="Tentang", command=about_window)\n menu_bar.add_cascade(label="Bantuan", menu=help_bar)\n\n # Print bar\n # print_bar = Menu(menu_bar, tearoff=0)\n # menu_bar.add_cascade(label="Print", menu=print_bar, command="")\n\n # Text Frame\n text_frame.grid(row=0, columnspan=16, padx=1, pady=1)\n\n TextArea.configure(font=text_font)\n TextArea.grid(row=0, columnspan=156)\n\n # Button Frame\n button_frame.grid(row=1, columnspan=16, padx=1, pady=1)\n\n varrow = 2\n varcolumn = 0\n\n # Button functions\n for button in buttons:\n command = lambda x=button: select(x)\n if button != 'Spasi':\n Button(button_frame, font=text_font, text=button, width=2, bg='black', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=varrow, column=varcolumn)\n if button == 'Spasi':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=62, pady=2, bd=4, command=command).grid(row=8, columnspan=4)\n if button == '⌫':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=3, column=12)\n if button == '↵':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=4, column=12)\n if button == '⇥':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=5, column=12)\n if button == '⇧':\n Button(button_frame, text=button, width=2, bg='brown', fg='white', activebackground="white",\n activeforeground='black',\n relief='raised', padx=4, pady=2, bd=4, command=command).grid(row=6, column=12)\n\n varcolumn += 1\n if varcolumn > 15 and varrow == 2:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 3:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 4:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 5:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 6:\n varcolumn = 0\n varrow += 1\n if varcolumn > 15 and varrow == 7:\n varcolumn = 3\n varrow += 1\n\n # Keyboard Shortcut functions (Bindings)\n\n root.bind('<Control-Key-x>', cut_text)\n root.bind('<Control-Key-c>', copy_text)\n root.bind('<Control-Key-v>', paste_text)\n root.bind('<Control-Key-a>', select_all_text)\n root.bind('<Control-Key-f>', find_text)\n root.bind('<Control-Key-o>', open_file)\n root.bind('<Control-Key-s>', save_file)\n\n root.config(menu=menu_bar)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T04:47:22.520",
"Id": "524707",
"Score": "0",
"body": "Thank you, Reinderien! This is helpful. I will try to tidy up the variable names and using class system."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T23:38:23.247",
"Id": "265570",
"ParentId": "265538",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T07:11:24.073",
"Id": "265538",
"Score": "2",
"Tags": [
"python"
],
"Title": "Virtual keyboard for typing Latin with diacritics characters"
}
|
265538
|
<p>I want to:</p>
<ol>
<li>Hide areas of my template after search click.</li>
<li>Return its original state with the cleaning of the input related to each button.</li>
</ol>
<p>I don't know if my code exploits all the resources of angular or js and looks clear/clean.
To my mind it sounds repetitive.</p>
<p>No forms of any kind are being used.</p>
<h2>My .ts component:</h2>
<pre><code>export class PolicySearchComponent {
policyId: string = '';
requestNumber: string = '';
documentationNumber: string = '';
submitOpt: boolean = false;
onClick(clicked) {
this.submitOpt = true;
if (clicked == 'pid') {
(<HTMLInputElement>document.getElementById('rn-container')).classList.add('hidden');
(<HTMLInputElement>document.getElementById('doc-container')).classList.add('hidden');
} else if (clicked == 'rn') {
(<HTMLInputElement>document.getElementById('pid-container')).classList.add('hidden');
(<HTMLInputElement>document.getElementById('doc-container')).classList.add('hidden');
} else if (clicked == 'doc') {
(<HTMLInputElement>document.getElementById('pid-container')).classList.add('hidden');
(<HTMLInputElement>document.getElementById('rn-container')).classList.add('hidden');
}
}
onClickBack(clicked) {
this.submitOpt = false;
if (clicked == 'pid') {
this.policyId = '';
(<HTMLInputElement>document.getElementById('rn-container')).classList.remove('hidden');
(<HTMLInputElement>document.getElementById('doc-container')).classList.remove('hidden');
} else if (clicked == 'rn') {
this.requestNumber = '';
(<HTMLInputElement>document.getElementById('pid-container')).classList.remove('hidden');
(<HTMLInputElement>document.getElementById('doc-container')).classList.remove('hidden');
} else if (clicked == 'doc') {
this.documentationNumber = '';
(<HTMLInputElement>document.getElementById('pid-container')).classList.remove('hidden');
(<HTMLInputElement>document.getElementById('rn-container')).classList.remove('hidden');
}
}
}
</code></pre>
<h2>My .html template:</h2>
<pre><code><div class="row pl-15 pr-15">
<div id="pid-container" class="row">
<div class="col-3 pl-0">
<mat-form-field>
<input matInput id="police-id" [(ngModel)]="policyId">
</mat-form-field>
</div>
<div class="col-1 align-self-center">
<button mat-raised-button class="main" (click)="onClickSearch('pid')">
Search
</button>
</div>
<div *ngIf="policyId != '' && submitOpt">
<app-policies-list [searchValue]="policyId"></app-policies-list>
<div class="row">
<div class="col text-align-right">
<button mat-raised-button class="main" (click)="onClickBack('pid')">
Back
</button>
</div>
</div>
</div>
</div>
<div id="rn-container" class="row">
<div class="col-3 pl-0">
<mat-form-field appearance="outline" class="formfield">
<input matInput id="request-number" [(ngModel)]="requestNumber">
</mat-form-field>
</div>
<div class="col-1 align-self-center">
<button mat-raised-button class="main" (click)="onClickSearch('rn')">
Search
</button>
</div>
<div *ngIf="requestNumber != '' && submitOpt">
<app-policies-list [searchValue]="policyId"></app-policies-list>
<div class="row">
<div class="col text-align-right">
<button mat-raised-button class="main" (click)="onClickBack('rn')">
Back
</button>
</div>
</div>
</div>
</div>
<div class="row" id="doc-container">
<div class="col-3 pl-0">
<mat-form-field appearance="outline" class="formfield">
<input matInput id="documentation" [(ngModel)]="documentationNumber">
</mat-form-field>
</div>
<div class="col-1 align-self-center">
<button mat-raised-button class="main" (click)="onClickSearch('doc')">
Search
</button>
</div>
<div *ngIf="documentationNumber != '' && submitOpt">
<app-policies-list [searchValue]="policyId"></app-policies-list>
<div class="row">
<div class="col text-align-right">
<button mat-raised-button class="main" (click)="onClickBack('doc')">
Back
</button>
</div>
</div>
</div>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>Simple solve. Create elems with flags.</p>\n<p>lets create object of elements with default settings. let be <code>true</code> by. default. And create 1 method for change state of elems.</p>\n<p>...</p>\n<pre><code>public elems = {\npid: true,\ndoc: true,\nrn: true\n}\n....\n\n toggle(elem, state) {\n this.submitOpt = state;\n elem = state;\n for(const item in this.elems) {\n this.elems[item] = !state;\n }\n }\n</code></pre>\n<p>in template will use *ngIf and click change state of flags elems</p>\n<pre><code><div class="row pl-15 pr-15">\n <div class="row" *ngIf="elems.pid">\n <div class="col-3 pl-0">\n <mat-form-field>\n <input matInput id="police-id" [(ngModel)]="policyId" (input)="!policyId.trim().length ? toggle(elems.pid,false): ''">\n </mat-form-field>\n </div>\n <div class="col-1 align-self-center">\n <button mat-raised-button class="main" (click)="toggle(elems.pid,true)">\n Search\n </button>\n </div>\n <div *ngIf="policyId != '' && submitOpt">\n <app-policies-list [searchValue]="policyId"></app-policies-list>\n <div class="row">\n <div class="col text-align-right">\n <button mat-raised-button class="main" (click)="toggle(elems.pid,false)">\n Back\n </button>\n </div>\n </div>\n </div>\n </div>\n<div class="row" *ngIf="elems.rn">\n <div class="col-3 pl-0">\n <mat-form-field appearance="outline" class="formfield">\n <input matInput id="request-number" [(ngModel)]="requestNumber">\n </mat-form-field>\n </div>\n <div class="col-1 align-self-center">\n <button mat-raised-button class="main" (click)="toggle(elems.rn, true)"\n Search\n </button>\n </div>\n <div *ngIf="requestNumber != '' && submitOpt">\n <app-policies-list [searchValue]="policyId"></app-policies-list>\n <div class="row">\n <div class="col text-align-right">\n <button mat-raised-button class="main" (click)="toggle(elems.rn, false)">\n Back \n </button>\n </div>\n </div>\n </div>\n</div>\n<div class="row" *ngIf="elems.doc">\n <div class="col-3 pl-0">\n <mat-form-field appearance="outline" class="formfield">\n <input matInput id="documentation" [(ngModel)]="documentationNumber">\n </mat-form-field>\n </div>\n <div class="col-1 align-self-center">\n <button mat-raised-button class="main" (click)="toggle(elems.doc,true)">\n Search\n </button>\n </div>\n <div *ngIf="documentationNumber != '' && submitOpt">\n <app-policies-list [searchValue]="policyId"></app-policies-list>\n <div class="row">\n <div class="col text-align-right">\n <button mat-raised-button class="main" (click)="toggle(elems.doc,false)">\n Back\n </button>\n </div>\n </div>\n </div>\n</div>\n</code></pre>\n<p>You shouldn't use classes. General is use variables in Angular. In fact, we got rid of two big methods and moved the display logic to the template</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:21:38.837",
"Id": "524590",
"Score": "0",
"body": "Ok, great change. But it would not fulfill the tow cases indicated in the question"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T09:57:48.917",
"Id": "265542",
"ParentId": "265539",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T08:35:57.760",
"Id": "265539",
"Score": "1",
"Tags": [
"javascript",
"html",
"angular-2+"
],
"Title": "Hidden html elements after search click"
}
|
265539
|
<p>I wrote a Logistic Regression model that classifies MNIST digits.</p>
<p>I used tensorflow & keras only for import the dataset.</p>
<pre><code>from tensorflow import keras
import time
import numpy as np
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
</code></pre>
<p>I sliced the dataset for binary classification.</p>
<pre><code># generate the indices
idx_digit_0 = np.argwhere(y_train == 0)
idx_digit_0 = idx_digit_0.flatten()
idx_digit_1 = np.argwhere(y_train == 1)
idx_digit_1 = idx_digit_1.flatten()
idx_test_digit_0 = np.argwhere(y_test == 0).flatten()
idx_test_digit_1 = np.argwhere(y_test == 1).flatten()
# slicing digit 0 and 1
y_train_digit_0 = y_train[idx_digit_0]
x_train_digit_0 = x_train[idx_digit_0]
y_train_digit_1 = y_train[idx_digit_1]
x_train_digit_1 = x_train[idx_digit_1]
y_test_digit_0 = y_test[idx_test_digit_0]
y_test_digit_1 = y_test[idx_test_digit_1]
x_test_digit_0 = x_test[idx_test_digit_0]
x_test_digit_1 = x_test[idx_test_digit_1]
# generate the dataset
y_train_mnist = np.concatenate((y_train_digit_0, y_train_digit_1), axis=0)
x_train_mnist = np.concatenate((x_train_digit_0, x_train_digit_1), axis=0)
y_test_mnist = np.concatenate((y_test_digit_0, y_test_digit_1), axis=0)
x_test_mnist = np.concatenate((x_test_digit_0, x_test_digit_1), axis=0)
# normalization
x_train_mnist = x_train_mnist/255.
x_test_mnist = x_test_mnist/255.
# flatten
x_train_mnist = x_train_mnist.reshape(len(x_train_mnist), -1)
x_test_mnist = x_test_mnist.reshape(len(x_test_mnist), -1)
def sigmoid(z):
s = 1 / (1 + np.exp(-z))
return s
class LogisticRegressionM3:
def __init__(self, eta=.05, n_epoch=10, model_w=np.full(784, .5), model_b=.0):
self.eta = eta
self.n_epoch = n_epoch
self.model_w = model_w
self.model_b = model_b
self.zz = []
def activation(self, x):
z = np.dot(x, self.model_w) + self.model_b
return sigmoid(z)
def predict(self, x):
a = self.activation(x)
if a >= 0.5:
return 1
else:
return 0
def fit(self, x, y, verbose=False):
idx = np.arange(len(x))
batch_size = 10
for i in range(self.n_epoch):
n_batches = int(len(x_train_mnist)/batch_size)
batches = np.split(idx[:batch_size*n_batches], n_batches)
for batch in batches:
a = self.activation(x[batch])
dz = a - y[batch]
dw = np.dot(dz, x[batch])/batch_size
self.model_w -= self.eta * dw
self.model_b -= self.eta * np.mean(dz)
start_time = time.time()
w_mnist = np.random.uniform(size=784)
classifier_mnist = LogisticRegressionM3(.1, 1, w_mnist)
classifier_mnist.fit(x_train_mnist, y_train_mnist)
print('model trained {:.5f} s'.format(time.time() - start_time))
y_prediction = np.array(list(map(classifier_mnist.predict, x_train_mnist)))
acc = np.count_nonzero(y_prediction==y_train_mnist)
print('train accuracy {:.5f}'.format(acc/len(y_train_mnist)))
y_prediction = np.array(list(map(classifier_mnist.predict, x_test_mnist)))
acc = np.count_nonzero(y_prediction==y_test_mnist)
print('test accuracy {:.5f}'.format(acc/len(y_test_mnist)))
</code></pre>
<p><a href="https://github.com/albert10jp/deep-learning/blob/main/LogisticRegression_MNIST_batch.ipynb" rel="nofollow noreferrer">Here</a> is the code and results</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T17:51:32.007",
"Id": "525182",
"Score": "0",
"body": "It's almost always preferred to include all relevant code in the question itself (as opposed to linking to github). Also, be explicit about what currently dissatisfies you about your code, or how you imagine it might be improved."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:06:20.357",
"Id": "265543",
"Score": "0",
"Tags": [
"python",
"machine-learning"
],
"Title": "Logistic Regression for MNIST binary classification"
}
|
265543
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.