body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>i've implemented a waiter service in Angular for syncronice multiple calls to one async function and i want to know if there exists a simplier way of atchiving the same result or if it's over engineered</p>
<p>the code</p>
<pre><code>import {Injectable} from '@angular/core';
export class PromiseRef {
resolve: (any?: any) => any;
reject: (any?: any) => any;
}
class ExecutionQueue {
promises = new Set<PromiseRef>();
lock: boolean = false;
constructor() {
}
hasPromises(): boolean {
return !!this.promises.size;
}
clearQueue() {
this.lock = false;
this.promises.clear();
}
add(promiseRef: PromiseRef) {
this.promises.add(promiseRef);
}
remove(promiseRef: PromiseRef) {
this.promises.delete(promiseRef);
}
}
@Injectable({providedIn: 'root'})
export class WaiterService {
private executionQueues = new Map<string, ExecutionQueue>();
constructor() {
}
isLocked(queueName: string): boolean {
return this.getQueue(queueName).lock;
}
lockQueue(queueName: string): Promise<PromiseRef> {
return new Promise<PromiseRef>(
(resolve, reject) => {
const queue = this.getQueue(queueName);
const promiseRef = new PromiseRef();
promiseRef.resolve = resolve;
promiseRef.reject = reject;
if (!queue.lock) {
queue.lock = true;
promiseRef.resolve(promiseRef);
} else {
this.addToExecutionQueue(queueName, promiseRef);
}
}
);
}
async unlockQueue(queueName: string) {
const queue = this.getQueue(queueName);
queue.lock = false;
const iterator = queue.promises.values();
const nextValue = iterator.next();
if (nextValue.done) {
return;
}
const promiseRef = nextValue.value;
queue.remove(promiseRef);
const newRef = await this.lockQueue(queueName);
promiseRef.resolve(newRef);
}
addToExecutionQueue(queueName: string, promiseRef: PromiseRef) {
const queue = this.getQueue(queueName);
queue.add(promiseRef);
}
private getQueue(queueName: string) {
let queue = this.executionQueues.get(queueName);
if (!queue) {
queue = new ExecutionQueue();
this.executionQueues.set(queueName, queue);
}
return queue;
}
}
</code></pre>
<p>then you should use it like this</p>
<pre><code>async someFn() {
await this.waiterService.lockQueue('a_queue');
try {
// do async stuff
} finally {
this.waiterService.unlockQueue('a_queue');
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T21:57:20.643",
"Id": "253062",
"Score": "0",
"Tags": [
"asynchronous",
"thread-safety",
"typescript",
"async-await",
"angular-2+"
],
"Title": "Angular Typescript Async queue service"
}
|
253062
|
<p>I am working on an online newspaper/blogging application with <strong>CodeIgniter 3.1.8</strong> and <strong>Twig</strong>. I use the Twig template engine for the front-end views.</p>
<p>I have put together this simple contact form which uses a controller, a view, and no model.</p>
<p>The controller:</p>
<pre><code>class Contact extends CI_Controller {
public function __construct()
{
parent::__construct();
}
private $headers = "";
private $to = 'example@yahoo.com';
private $email_address = '';
private $name = '';
private $subject = '';
private $message = '';
private $body = '';
private $message_success = false;
private $message_fail = false;
public function index(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
$this->form_validation->set_error_delimiters('<p class="form-error">', '</p>');
if($this->form_validation->run() === FALSE) {
$data['errors'] = validation_errors();
$this->displayForm();
} else {
//Prepare mail
$this->subject = "Website Contact Form: " . $this->input->post('subject');
$this->name = $this->input->post('name');
$this->email_address = $this->input->post('email');
$this->message = $this->input->post('message');
$this->body = "You have received a new message from your website contact form. Here are the details:\n\nName: $this->name\n\nEmail: $this->email_address\n\nMessage:\n$this->message";
$this->headers = "From: noreply@yourdomain.com\n";
$this->headers .= "Reply-To: $this->email_address";
//Send mail
$this->send_mail();
$this->displayForm();
}
}
public function displayForm() {
$data = $this->Static_model->get_static_data();
$data['base_url'] = base_url("/");
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['tagline'] = "Contact us";
$data['errors'] = validation_errors();
$data['message_success'] = $this->message_success;
$data['message_fail'] = $this->message_fail;
$this->twig->addGlobal('contactForm',"themes/{$data['theme_directory']}/templates/contact.twig");
$this->twig->display("themes/{$data['theme_directory']}/layout", $data);
}
//mail sender method
public function send_mail() {
if (mail($this->to, $this->subject, $this->body, $this->headers)) {
$this->message_success = true;
} else {
$this->message_fail = true;
}
}
}
</code></pre>
<p>The <code>contact.twig</code> view:</p>
<pre><code><div class="wrapper style1">
<div class="content">
<div class="contact image fit flush">
<img src="{{base_url}}themes/caminar/assets/images/woman-with-laptop.jpg" alt="Contact">
</div>
<h2>Contact us</h2>
{% if message_success == true %}
<div class="alert alert-success alert-dismissible text-center">
<button type="button" class="close" data-dismiss="alert">&times;</button>
Your message was sent. We will reply as soon as possible.
</div>
{% endif %}
{% if message_fail == true %}
<div class="alert alert-danger alert-dismissible text-center">
<button type="button" class="close" data-dismiss="alert">&times;</button>
Something went wrong while sending your message.
</div>
{% endif %}
<div id="msgContainer" class="alert alert-hidden alert-success mb-4"></div>
<form name="contactForm"
id="ajaxForm"
action="{{base_url}}contact"
method="post"
data-successmsg="Your message was sent. We will reply as soon as possible."
data-failmsg="Sorry, we could not deliver your message"
novalidate>
<div class="row uniform">
<div class="form-controll 12u$">
<input type="text" class="form-control px-1 {{ form_error('name') ? 'error' }}" placeholder="Name" name="name" id="name" value="{{set_value('name' )}}" data-rule-required="true">
{{ form_error('name') ? form_error('name') }}
</div>
<div class="form-controll 12u$">
<input type="email" class="form-control px-1 {{ form_error('email') ? 'error' }}" placeholder="Email" name="email" id="email" value="{{set_value('email' )}}" data-rule-required="true">
{{ form_error('email') ? form_error('email') }}
</div>
</div>
<div class="row uniform">
<div class="form-controll 12u$">
<input type="text" class="form-control px-1 {{ form_error('subject') ? 'error' }}" placeholder="Subject" name="subject" id="subject" value="{{set_value('subject' )}}" data-rule-required="true">
{{ form_error('subject') ? form_error('subject') }}
</div>
<div class="form-controll 12u$">
<textarea rows="5" class="form-control px-1 {{ form_error('message') ? 'error' }}" placeholder="Message" name="message" id="message" data-rule-required="true">{{set_value('message')}}</textarea>
{{ form_error('message') ? form_error('message') }}
</div>
<div class="12u$">
<button type="submit" class="button special fit" id="sendMessageButton">Send</button>
</div>
</div>
</form>
</div>
</div>
</code></pre>
<p>The error and success messages at the top of the above view play a role only if JavaScript is disabled in the browser, otherwise the messages are delivered via jQuery Ajax:</p>
<pre><code>(function($) {
// Add comments via AJAX
$("#ajaxForm").validate({
rules: {
email: {
email: true
}
},
submitHandler: function(form) {
var form = $("#ajaxForm"),
$fields = form.find('input[type="text"],input[type="email"],textarea'),
$succesMsg = form.data('successmsg'),
$failMsg = form.data('failmsg'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function() {
$('#msgContainer').text($succesMsg).slideDown(250).delay(2500).slideUp(250);
$fields.val('');
},
error: function() {
$('#msgContainer').removeClass('alert-success').addClass('alert-danger')
.text($failMsg).slideDown(250).delay(2500).slideUp(250);
}
});
}
});
})(jQuery);
</code></pre>
<p>The form is validated with the <em>jQuery Validation Plugin</em>.</p>
<p>The script above is designed to "fit" multiple forms as long as they have an attribute <code>id="ajaxForm"</code>.</p>
<h3>Concerns:</h3>
<ol>
<li>Does the contact form have security weaknesses?</li>
<li>Is the lack of a model an issue?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T08:12:12.730",
"Id": "498916",
"Score": "0",
"body": "@mickmackusa I made a new, simpler one. This one above."
}
] |
[
{
"body": "<ul>\n<li><p>Method declarations <a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=The%20opening%20brace%20MUST%20go%20on%20its%20own%20line\" rel=\"nofollow noreferrer\">PSR-12: The opening brace MUST go on its own line</a></p>\n</li>\n<li><p>Get into the habit of declaring argument types and return types whenever possible throughout your application -- it will help you to maintain good, stable code. <a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=When%20you%20have%20a%20return%20type%20declaration%20present,between%20the%20two%20characters.\" rel=\"nofollow noreferrer\">PSR-12: When you have a return type declaration present, there MUST be one space after the colon followed by the type declaration. The colon and declaration MUST be on the same line as the argument list closing parenthesis with no spaces between the two characters.</a></p>\n</li>\n<li><p>I recommend consistently using camelcase versus snake_case throughout your application. This would serve as an indicator in many instances whether an entity is <em>your</em> work or someone elses (CI's entity or PHP's entity). This is in regards to <code>send_mail()</code>, <code>$email_address</code>, <code>get_pages()</code>, etc. The exception that I make to this is when declaring <code>data-</code> attributes in the markup -- I use all lowercase.</p>\n</li>\n<li><p>I see <code>index()</code> doing two things, but I would rather see it have a single responsibility - displaying the form. I was going to later advise that <code>send_mail()</code> should be a protected method, because it seems highly unlikely that you would call that method directly. However, I think it would be best to declare a public <code>ajaxMail()</code> method which can only be accessed <a href=\"https://stackoverflow.com/q/11687180/2943403\">when the incoming request is from ajax</a> AND contains valid form data.</p>\n</li>\n<li><p>When you are merging associative arrays to form <code>$data</code> use the union operator to DRY your code.</p>\n<pre><code>$data = $this->Static_model->get_static_data()\n + [\n 'base_url' => base_url("/");\n 'pages' => $this->Pages_model->get_pages(),\n 'categories' => $this->Categories_model->get_categories(),\n 'tagline' => "Contact us",\n 'errors' => validation_errors();\n 'message_success' => $this->message_success,\n 'message_fail' => $this->message_fail\n ];\n</code></pre>\n</li>\n<li><p>I recommend (and only use) <a href=\"https://stackoverflow.com/q/1268012/2943403\">PHPMailer versus native <code>mail()</code></a>.</p>\n</li>\n<li><p>After splitting the <code>index()</code> method and creating the <code>ajaxMail()</code> method, it will be easy and clear to see the new method will always end by printing a json_encoded string as the response data. This eliminates the need to declare class level properties private <code>$message_success</code> and <code>$message_fail</code> (which are unconditionally declared when the class is instantiated) that only one method will use. The same can be said of the other mail-related properties -- they'll only be used by one method, so keep them isolated there.</p>\n</li>\n<li><p>As a consequence of this major refactor, <code>index()</code> will only be calling <code>$this->displayForm();</code>, so there isn't much sense in abstracting the functionality into its own method. Pull that logic into <code>index()</code> and omit the <code>displayForm()</code> method. Now your class has two methods that do two specific, singular things: <code>index()</code> loads the view, and <code>ajaxMail()</code> processes all mail sending requests.</p>\n</li>\n<li><p>In the jquery, you are immediately overwriting <code>form</code> at <code>submitHandler: function(form) {</code>, so just omit the argument from the call.</p>\n</li>\n<li><p><code>$fields</code> is a single-use variable, so simply don't declare it.</p>\n<pre><code>form.find('input[type="text"],input[type="email"],textarea').val('');\n</code></pre>\n<p>Actually, it will be cleaner if you target the form fields by their common class.</p>\n<pre><code>$('.form-control').val('');\n</code></pre>\n</li>\n<li><p><code>url = form.attr('action')</code> and <code>data = form.serialize()</code> are also single-use declarations; just write the values directly into the ajax object.</p>\n</li>\n<li><p>I would be receiving the response json passed back from <code>ajaxMail()</code> in <code>success: function(response) {</code>. If there was an <code>error</code>, you won't be receiving the json data because something fatal happens (or you can pass a header() declaration ahead of the json response to force the collection of your json in the <code>error</code> handler.</p>\n</li>\n<li><p>I don't know if the lack of a model is a problem, but I'd probably engage PHPMailer as a library.</p>\n</li>\n<li><p>Are there vulnerabilities? Well, is this feature behind a password-protected wall? You are unconditionally dispatching these emails, are you happy that there is no limiting logic in your code? You have implemented validations, but no sanitizations. You aren't stripping any potential html markup from the user's message, so if you are concerned that folks might be sending dodgy messages, you should probably strip html tags and consider html encoding characters.</p>\n</li>\n</ul>\n<p>Okay, I typed this all up on my mobile and now I am cross-eyed. Good luck with whatever pieces of this review that you decide to implement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T09:23:42.290",
"Id": "499042",
"Score": "0",
"body": "Thanks a lot for all the code and explanations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:20:42.373",
"Id": "499047",
"Score": "1",
"body": "And no, the contact form is NOT is NOT behind a password-protected wall. Because every visitor has to be able to contact me by email if she/he wants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T12:16:30.513",
"Id": "504658",
"Score": "0",
"body": "Hi, Mick! Please have a look at **[this](https://stackoverflow.com/q/66079120/4512005)** question. The answer I already have is unsatisfactory (it does not work). Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:27:15.167",
"Id": "253099",
"ParentId": "253064",
"Score": "3"
}
},
{
"body": "<p>You can improve your security of your project, implementing XSS and CSRF configuration below.</p>\n<p>On application/config/config.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>$config['global_xss_filtering'] = TRUE;\n$config['csrf_protection'] = TRUE;\n</code></pre>\n<p>This is very important for forms.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T15:16:25.587",
"Id": "499301",
"Score": "0",
"body": "Great. Yet, if I do this, my Ajax forms won't work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T14:59:27.903",
"Id": "253218",
"ParentId": "253064",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253099",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T22:15:38.490",
"Id": "253064",
"Score": "3",
"Tags": [
"php",
"ajax",
"codeigniter",
"twig"
],
"Title": "A contact form with CodeIgniter and Twig"
}
|
253064
|
<p>I've posted a similar question on: <a href="https://codereview.stackexchange.com/questions/253038/improving-a-filter-array-function-to-match-elements-and-conditions/253055?noredirect=1#comment498903_253055">Link</a></p>
<p>With the help of the other users, I was able to improve the code, but I don't think is the "ultimate" form.</p>
<p>Thats my code now, any help?</p>
<p>Conditions entries example:</p>
<pre><code>[1,2],
[9,6,4],
[3]
[7,1,5,2,3]
private filterElements(userSelectedConditions: Set<number>): Element[]{
const meetConditions: Element[] = [];
this.arrayWithAllElements.forEach(element => {
let isPossibility: boolean = true;
for (let ev of userSelectedConditions ) {
if( !element.condition_matrix.includes( ev ) ){
isPossibility = false;
break;
}
}
if(isPossibility){
meetConditions.push(element);
}
});
if(meetConditions.length === 0){
meetConditions.push( { <a_filler_object> } );
}
return meetConditions;
}
</code></pre>
<p>The user select some conditions, and this code has to iterate on the full elements list, filter the elements that meets all the conditions passes. So if the user selects ONE condition, every element with that condition should be filtered. IF the user selects THREE conditions, every element that meet those conditions should be filtered, if they don't match ALL the selected conditions, they should be out of the list.</p>
<p>this.selectedConditions is already maped by ID</p>
<p>Elements list example:</p>
<pre><code>elements: [
{
name: 'el1',
condition_matrix: [1,2]
},
{
name: 'el2',
condition_matrix: [2,3]
},
{
name: 'el3',
condition_matrix: [2,1]
}
]
</code></pre>
<p>Conditions list example:</p>
<pre><code>conditions: [
{
id: 1
name: 'cond1'
},
{
id: 2
name: 'cond2'
},
{
id: 3
name: 'cond3'
}
]
</code></pre>
|
[] |
[
{
"body": "<p>The <code>Array</code> methods <a href=\"https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>filter()</code></a> and <a href=\"https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\"><code>every()</code></a> come in very handy here. First you could define a function to check wheter a given element matches all conditions:</p>\n<pre><code>function meetsAll(element, conditions) {\n return conditions.every(c => element.condition_matrix.includes(c));\n}\n</code></pre>\n<p>Now it's almost trivial to filter out the matching elements using <code>Array.filter()</code>:</p>\n<pre><code>const meetConditions = this.arrayWithAllElements.filter(\n element => meetsAll(element, userSelectedConditions)\n);\n</code></pre>\n<p>I recommend you also have a look at the other functional methods defined on <code>Array</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T12:23:41.437",
"Id": "253126",
"ParentId": "253066",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T23:50:48.167",
"Id": "253066",
"Score": "0",
"Tags": [
"javascript",
"array"
],
"Title": "Improving a filter array function with Set and objects, to match elements and conditions"
}
|
253066
|
<p>I made this FizzBuzz game for my college class and it's kind of ridiculous, but is suppose to demonstrate chain of command so writing it in a little forloop was out of the question. In case you don't know the game, this program counts numbers 1-100 printing them to the console but replace any multiple of 3 with the word Fizz, multiples of 5 with the word Buzz, and multiples of 3 and 5 with the word FizzBuzz. There's actually more I'd like to do to it, but I've already been "spoken to" about adding extra features that he didn't ask for so I'm trying to keep this simple. I'll take any critique though because I tried new things like declaring string as constants and not using curly braces when my if statements only had one line. I have another version with user inputs and the ability to restart, and I'm thinking about making it go backwards, use letters, and add options for other multiples.</p>
<pre><code>public class Main {
public static void main(String[] args) {
int startNum = 1;
int endNum = 100;
GameMgr.Start(startNum, endNum);
}
}
</code></pre>
<pre><code>public abstract class GameMgr {
// THESE ARE THE MESSAGES THAT WILL BE PRINTED
// IF THE CURRENT NUMBER IS DIVISIBLE WITH THE
// CURRENT OBJECTS DIVISOR
final String FIFTEEN = "FizzBuzz";
final String THREE = "Fizz";
final String FIVE = "Buzz";
// THESE HOLD THE CURRENT NUMBER BEING
// EVALUATED AS WELL AS THE NUMBER THAT
// INDICATES THE END
static int currNum;
static int endNum;
//DEFAULT CONSTRUCTOR
public GameMgr(){}
// FILLS THE VALUES TO BE EVALUATED AND
// STARTS THE CHAIN OF COMMAND
public static void Start(int a, int b){
currNum = a;
endNum = b;
new BuzzFizz();
}
// CALCULATES THE CURRENT VALUE WITH THE
// CURRENT OBJECTS DIVISOR
protected boolean isDivisible(int divisor){
return currNum % divisor == 0;
}
// CHECKS IF THE SYSTEM HAS EXCEEDED THE
// ENDPOINT. IF NOT, VALUE IS INCREASED
// AND CHAIN OF COMMAND IS RESTARTED
protected void ProcessNext(){
currNum++;
if (currNum <= endNum)
GameMgr.Start(currNum, endNum);
else
System.exit(0);
}
// METHOD IS IMPLEMENTED IN THE CHILD CLASSES
// TO EVALUATE THE CURRENT WITH WITH THEIR
// RESPECTIVE DIVISOR
public abstract String Eval();
}
</code></pre>
<pre><code>public class BuzzFizz extends GameMgr {
// SPECIFIC DIVISOR FOR THIS CHILD
int divisor = 15;
// CALLS THE EVALUATION METHOD DETERMINES
// WHETHER TO CONTINUE CHAIN OR RESTART
// THE CHAIN
public BuzzFizz(){
System.out.println(Eval());
if (Eval() != null)
ProcessNext();
}
// CHECKS IF THE CURRENT NUMBER IS DIVISIBLE
// WITH THIS OBJECTS DIVISOR RETURNS MESSAGE
// TO PRINT TO CONSOLE IF TRUE, CREATES
// NEXT OBJECT IN THE CHAIN IF FALSE
@Override
public String Eval(){
if (isDivisible(divisor))
return FIFTEEN;
new Fizz();
return "";
}
}
</code></pre>
<pre><code>public class Fizz extends GameMgr {
// SPECIFIC DIVISOR FOR THIS CHILD
int divisor = 3;
// CALLS THE EVALUATION METHOD DETERMINES
// WHETHER TO CONTINUE CHAIN OR RESTART
// THE CHAIN
public Fizz(){
System.out.println(Eval());
if (Eval() != null)
ProcessNext();
}
// CHECKS IF THE CURRENT NUMBER IS DIVISIBLE
// WITH THIS OBJECTS DIVISOR RETURNS MESSAGE
// TO PRINT TO CONSOLE IF TRUE, CREATES
// NEXT OBJECT IN THE CHAIN IF FALSE
@Override
public String Eval(){
if (isDivisible(divisor))
return THREE;
new Buzz();
return "";
}
}
</code></pre>
<pre><code>public class Buzz extends GameMgr {
// SPECIFIC DIVISOR FOR THIS CHILD
int divisor = 5;
// CALLS THE EVALUATION METHOD DETERMINES
// WHETHER TO CONTINUE CHAIN OR RESTART
// THE CHAIN
public Buzz(){
System.out.println(Eval());
if (Eval() != null)
ProcessNext();
}
// CHECKS IF THE CURRENT NUMBER IS DIVISIBLE
// WITH THIS OBJECTS DIVISOR RETURNS MESSAGE
// TO PRINT TO CONSOLE IF TRUE, CREATES
// NEXT OBJECT IN THE CHAIN IF FALSE
@Override
public String Eval(){
if (isDivisible(divisor))
return FIVE;
new BasicNum();
return "";
}
}
</code></pre>
<pre><code>public class BasicNum extends GameMgr {
// PRINTS THE CURRENT NUMBER AND
// RESTARTS THE CHAIN
public BasicNum(){
System.out.println(currNum);
ProcessNext();
}
// SINCE THIS IS THE END OF THE
// CHAIN, THIS METHOD DOESN'T NEED
// TO DO ANYTHING
@Override
public String Eval(){
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I may come back with a more detailed critique, but some initial thoughts are</p>\n<ol>\n<li>Don't do significant processing in your constructors. It can be done, but goes against many developers' expectations.</li>\n<li>Don't use global data. Pass arguments.</li>\n<li>I don't think BUZZ etc should be subclasses of GameMgr. They don't seem to me to be the same sorts of things.</li>\n<li>BUZZ etc hold no real state, so could be singletons, or enum members.</li>\n</ol>\n<p>Update: I said I may come back...</p>\n<p>I'm also concerned that the BUZZ etc classes have more than one responsibility - I don't think they should deal with incrementing the number...</p>\n<p>I'd call BUZZ etc "handlers" - they should have a single method "handle(int)" and either return the appropriate string or pass the integer on.</p>\n<p>I'm not sure we need as much in these classes as eric's answer suggests, and I'm far from convinced we need closures...</p>\n<p>Here's a quick and fairly short enum-based solution.</p>\n<pre><code>public class FBChain {\n static enum Handler {\n FIZZBUZZ(15), BUZZ(5), FIZZ(3), //\n\n PLAIN_NUMBER(0) {\n // Override the method for this special-case\n @Override\n protected String handle(int candidate) {\n return Integer.toString(candidate);\n }\n };\n \n final int divisor;\n Handler nextHandler = null;\n\n Handler(int divisor) {\n this.divisor = divisor;\n }\n\n protected String handle(int candidate) {\n if ((candidate % divisor) == 0) {\n return name();\n }\n return nextHandler.handle(candidate);\n }\n\n static {\n FIZZBUZZ.nextHandler = BUZZ;\n BUZZ.nextHandler = FIZZ;\n FIZZ.nextHandler = PLAIN_NUMBER;\n }\n\n public static String chainHandle(int candidate) {\n return FIZZBUZZ.handle(candidate);\n }\n }\n\n public static void main(String[] args) {\n for (int candidate = 1; candidate <= 50; candidate++) {\n System.out.println(Handler.chainHandle(candidate));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:10:24.780",
"Id": "499219",
"Score": "0",
"body": "The problem with baking the chain into the enum is that now all clients must use the same chain. Letting clients define and order their own links is a more flexible approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T08:26:43.667",
"Id": "499271",
"Score": "0",
"body": "@EricStein I can see your point of view, but I follow the You Ain't Gonna Need It principle, and the task in front of me was to implement FizzBuzz using a Chain of Command pattern, not implement a generalised Chain of Command framework.\nI like that the whole definition of FizzBuzz is in the one class, rather than having a generalised handler which is then \"customised\" elsewhere, but it's a difference of philosophies and tastes, I'd say. (Also I'm conditioned to older Java and don't find closures natural yet :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T09:07:38.543",
"Id": "253073",
"ParentId": "253067",
"Score": "2"
}
},
{
"body": "<p>In no particular order:</p>\n<p>In Java, constants must be <code>final</code>. Otherwise they can be reassigned, making them not, er, constant. :)</p>\n<p>In Java, methods always start with a lowercase letter.</p>\n<p>You're calling <code>eval()</code> twice in each constructor, rather than performing the computation once and remembering the value in a variable.</p>\n<p>Abstract class methods should almost always be either <code>abstract</code> (part of the contract) or <code>final</code> (part of the implementation). You probably don't want subclasses able to redefine what <code>processNext()</code> does.</p>\n<p>Your're defining the FizzBuzz Strings in <code>GameMgr</code>, but the divisors in the subclasses. The Strings should be private instance variables in the subclasses with the divisors.</p>\n<p>There's no reason for <code>currNum</code> and <code>endNum</code> to be static.</p>\n<p>Optional curly braces aren't. They should always be used to improve readability and prevent errors.</p>\n<p>In Java there is whitespace between a <code>)</code> and a <code>{</code>.</p>\n<p>Most of your abbreviations hurt readability. It's helpful to spell out words unless there's a compelling reason to abbreviate them.</p>\n<p>The <code>divisor</code> instance variables should be <code>private</code>. Always make everything as tightly scoped as you can.</p>\n<p><code>GameMgr</code> trying to both loop through all the values and being a parent of the implementations is a violation of the Single Responsibility Principle. Classes should have one job.</p>\n<p>Why is your class called "BuzzFizz" instead of "FizzBuzz"?</p>\n<p>Your design decision to do all the work in the constructors is questionable. You're not constructing meaningful objects, but rather using the constructors to perform business logic that would be better suited for a method. This implementation choice also suggests that you haven't fully grokked how a <code>Chain of Responsibility</code> is supposed to work. The idea is to create a list of objects, where each object may either handle an input or pass it on to the next link in the chain. The chain of objects exists as a reusable entity.</p>\n<p>So, let's try to do better:</p>\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n AbstractHandler buzzFizz = new BuzzFizz();\n AbstractHandler fizz = new Fizz();\n AbstractHandler buzz = new Buzz();\n AbstractHandler basicNumber = new BasicNumber();\n\n buzzFizz.setNext(fizz);\n fizz.setNext(buzz);\n buzz.setNext(basicNumber);\n\n /* now we have a chain buzzFizz -> fizz -> buzz -> basicNumber\n * we can reuse this chain later, or pass it to another method\n * by sending the head of the chain as an argument, like\n * doSomethingWith(buzzFiz). That other code can call\n * buzzFizz.handle() and it will go down the chain, even though it\n * only sees the head.\n */ \n\n for (int i = 1; i <= 100; i++) {\n buzzFizz.handle(i);\n }\n }\n}\n</code></pre>\n<p>.</p>\n<pre><code>public abstract class AbstractHandler {\n\n private final int divisor;\n private AbstractHandler next;\n\n public AbstractHandler(int divisor) {\n this.divisor = divisor;\n }\n\n public final void setNext(AbstractHandler next) {\n this.next = next;\n }\n\n public final void handle(int value) {\n if ((value % divisor) == 0) {\n System.out.println(displayValue(value));\n return;\n }\n if (next != null) {\n next.handle(value);\n }\n }\n\n protected abstract String displayValue(int value);\n\n}\n</code></pre>\n<p>.</p>\n<pre><code>public class BuzzFizz extends AbstractHandler {\n\n public BuzzFizz() {\n super(15);\n }\n\n @Override\n protected String displayValue(int value) {\n return "FizzBuzz";\n }\n\n}\n</code></pre>\n<p>.</p>\n<pre><code>public class BasicNumber extends AbstractHandler {\n\n public BasicNumber() {\n super(1);\n }\n\n @Override\n protected String displayValue(int value) {\n return Integer.toString(value);\n }\n\n}\n</code></pre>\n<p>So this is better, but still not great. We'd really like to separate out our public API into an interface, and keep the implementation details to ourselves. If we did that, and we notice that the only difference between the FizzBuzz, Fizz, and Buzz handlers is the numbers, we can cut it down to two implementations:</p>\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n Handler buzzFizz = new FizzBuzzHandler(15, "FizzBuzz");\n Handler fizz = new FizzBuzzHandler(3, "Fizz");\n Handler buzz = new FizzBuzzHandler(5, "Buzz");\n Handler basicNumber = new BasicNumberHandler();\n\n buzzFizz.setNext(fizz);\n fizz.setNext(buzz);\n buzz.setNext(basicNumber);\n\n for (int i = 1; i <= 100; i++) {\n buzzFizz.handle(i);\n }\n }\n}\n</code></pre>\n<p>.</p>\n<pre><code>public interface Handler {\n\n void setNext(Handler next);\n\n void handle(int value);\n}\n</code></pre>\n<p>.</p>\n<pre><code>public final class FizzBuzzHandler implements Handler {\n\n private final int divisor;\n private final String displayValue;\n private Handler next;\n\n public FizzBuzzHandler(int divisor, String displayValue) {\n this.divisor = divisor;\n this.displayValue = displayValue;\n }\n\n @Override\n public final void setNext(Handler next) {\n this.next = next;\n }\n\n @Override\n public final void handle(int value) {\n if ((value % divisor) == 0) {\n System.out.println(displayValue);\n return;\n }\n if (next != null) {\n next.handle(value);\n }\n }\n\n}\n</code></pre>\n<p>.</p>\n<pre><code>public final class BasicNumberHandler implements Handler {\n\n public BasicNumberHandler() {\n super();\n }\n\n @Override\n public void setNext(Handler next) {\n throw new UnsupportedOperationException("This is a terminal handler.");\n }\n\n @Override\n public void handle(int value) {\n System.out.println(value);\n }\n\n}\n</code></pre>\n<p>Can we do better? We can, if we use a little black magic. Java allows us to pass methods as a type of variable. We can get away with just one class which gets the acceptance test and the output injected into it:</p>\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n Handler buzzFizz = new Handler(value -> value % 15 == 0, value -> System.out.println("FizzBuzz"));\n Handler fizz = new Handler(value -> value % 3 == 0, value -> System.out.println("Fizz"));\n Handler buzz = new Handler(value -> value % 5 == 0, value -> System.out.println("Buzz"));\n Handler basicNumber = new Handler(value -> true, value -> System.out.println(value));\n\n buzzFizz.setNext(fizz);\n fizz.setNext(buzz);\n buzz.setNext(basicNumber);\n\n for (int i = 1; i <= 100; i++) {\n buzzFizz.handle(i);\n }\n }\n}\n</code></pre>\n<p>.</p>\n<pre><code>import java.util.function.Consumer;\nimport java.util.function.Predicate;\n\npublic final class Handler {\n\n private final Predicate<Integer> predicate;\n private final Consumer<Integer> consumer;\n\n private Handler next;\n\n public Handler(Predicate<Integer> predicate, Consumer<Integer> consumer) {\n this.predicate = predicate;\n this.consumer = consumer;\n }\n\n public final void setNext(Handler next) {\n this.next = next;\n }\n\n public final void handle(int value) {\n if (predicate.test(value)) {\n consumer.accept(value);\n return;\n }\n\n if (next != null) {\n next.handle(value);\n }\n }\n\n}\n</code></pre>\n<p>This is a chain with exactly one type of link. It might be preferable to keep the idea of an interface <code>Handler</code> with one implementation type, just in case you needed to add a new implementation type later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:08:56.157",
"Id": "499218",
"Score": "0",
"body": "I'm not going to go back and edit the code, but note that it would have been much more correct to have `handle()` return the String to be displayed rather than printing it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T02:02:23.703",
"Id": "253109",
"ParentId": "253067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253109",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T04:57:08.817",
"Id": "253067",
"Score": "5",
"Tags": [
"java",
"beginner",
"inheritance",
"fizzbuzz"
],
"Title": "FizzBuzz game, open to any critiques"
}
|
253067
|
<p>I am a beginner programmer and have made a tic tac toe program in c++. I need some help with my memory management can anyone review and help me. This is my code</p>
<pre><code>// This is a trial for tic tac toe in C++
#include <iostream>
using namespace std;
char *squares = new char[9]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};
void play();
void getBoard();
int checkWin();
int main()
{
char *playAgain = new char;
do
{
play();
cout << "Do you want to play again(y/n): ";
cin >> *playAgain;
} while (tolower(*playAgain) == 'y');
delete squares, playAgain;
cin.get();
return 0;
}
//Play the game
void play()
{
int *i = new int;
int player = 1;
int *choice = new int;
char *mark = new char;
do
{
getBoard();
player = (player%2) ? 1 : 2;
cout << "Enter your choice: ";
cin >> *choice;
*mark = (player == 1) ? 'X' : 'O';
if (squares[0] == '1' && *choice == 1)
{
squares[0] = *mark;
}
else if (squares[1] == '2' && *choice == 2)
{
squares[1] = *mark;
}
else if (squares[2] == '3' && *choice == 3)
{
squares[2] = *mark;
}
else if (squares[3] == '4' && *choice == 4)
{
squares[3] = *mark;
}
else if (squares[4] == '5' && *choice == 5)
{
squares[4] = *mark;
}
else if (squares[5] == '6' && *choice == 6)
{
squares[5] = *mark;
}
else if (squares[6] == '7' && *choice == 7)
{
squares[6] = *mark;
}
else if (squares[7] == '8' && *choice == 8)
{
squares[7] = *mark;
}
else if (squares[8] == '9' && *choice == 9)
{
squares[8] = *mark;
}
else
{
cout << "Invalid move ";
player--;
cin.ignore();
cin.get();
}
*i = checkWin();
player++;
} while (*i == -1);
getBoard();
if (*i == 1)
{
cout << "\aPlayer " << --player << " Wins" << endl;
delete mark, choice, i;
}
else
{
cout << "\aGame Draw" << endl;
delete mark, choice, i;
}
}
// Print the board
void getBoard()
{
cout << "\n\n\tTic Tac Toe\n\n";
cout << "Player 1 (X) - Player 2 (O)" << endl
<< endl;
cout << endl;
cout << " | | " << endl;
cout << " " << squares[0] << " | " << squares[1] << " | " << squares[2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << squares[3] << " | " << squares[4] << " | " << squares[5] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << squares[6] << " | " << squares[7] << " | " << squares[8] << endl;
cout << " | | " << endl
<< endl;
}
/**********************************************************************************************************
Return 1 if some one wins
Return 0 if draw
Return -1 if the game is not over
***********************************************************************************************************/
int checkWin()
{
if (squares[0] == squares[1] && squares[1] == squares[2])
{
return 1;
}
else if (squares[0] == squares[3] && squares[3] == squares[6])
{
return 1;
}
else if (squares[0] == squares[4] && squares[4] == squares[8])
{
return 1;
}
else if (squares[3] == squares[4] && squares[4] == squares[5])
{
return 1;
}
else if (squares[1] == squares[4] && squares[4] == squares[7])
{
return 1;
}
else if (squares[6] == squares[4] && squares[4] == squares[2])
{
return 1;
}
else if (squares[6] == squares[7] && squares[7] == squares[8])
{
return 1;
}
else if (squares[2] == squares[5] && squares[5] == squares[8])
{
return 1;
}
else if (squares[0] != '1' && squares[1] != '2' && squares[2] != '3' && squares[3] != '4' && squares[4] != '5' && squares[5] != '6' && squares[6] != '7' && squares[7] != '8' && squares[8] != '9')
{
return 0;
}
else
{
return -1;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T07:35:08.713",
"Id": "498914",
"Score": "0",
"body": "it does work i forgot to remove the `TODO` and as i use only visual studio code i did not know about it"
}
] |
[
{
"body": "<h2><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><strong>Try not to <code>using namespace std</code></strong></a></h2>\n<p>It is considered a bad practice. This is because namespaces were introduced as a way to avoid name collisions, i.e Multiple objects with the same name. The <code>std</code> namespace is <strong>HUGE</strong> and has hundreds of common identifiers that can interfere with yours.</p>\n<p>By doing <code>using namespace std</code> you now have no idea what function is a part of the <code>std</code> library, and what isn't.</p>\n<h1>The use of <code>new</code></h1>\n<p>I think you have misunderstood the use of the <code>new</code> operator in C++. What is the use of dynamic memory allocation here? I fail to see a good reason to not simply create your variables on the stack. The problem here is you cannot forget to <code>delete</code>. If you do, you expose your program to memory leaks - Horrible.</p>\n<p>You can use <code>new</code> when:</p>\n<ul>\n<li>You don't want an object to be destroyed until you call <code>delete</code></li>\n<li>When your object is <strong>very large</strong></li>\n</ul>\n<p>In short, there is no need to use the <code>new</code> operator here. It just introduces complications.</p>\n<p><a href=\"https://stackoverflow.com/questions/679571/when-to-use-new-and-when-not-to-in-c\"><strong>When to use the 'new' operator</strong></a></p>\n<hr />\n<h1>Use an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\"><code>enum</code></a></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>/**********************************************************************************************************\nReturn 1 if some one wins\nReturn 0 if draw\nReturn -1 if the game is not over\n***********************************************************************************************************/\n</code></pre>\n<p>the numbers 1, 0, -1 are known as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, your comment helps but one would have to keep referring back to know their meaning. Using an <code>enum</code> here will clear a lot</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Result { Win , Draw , OnGoing };\n\nreturn Result::Win;\n</code></pre>\n<p>That way you can declare your function as</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Result checkWin();\n</code></pre>\n<p>And instead of</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>return (number which means nothing)\n</code></pre>\n<p>You do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>return Result::Win;\n</code></pre>\n<p>The values 0, 1, and 2 are automatically assigned to <code>Win</code>, <code>Draw</code>, <code>Ongoing</code> respectively. Now that we have the names for these numbers, we use them instead of the raw numbers. That means</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>return Result::Win;\n</code></pre>\n<p>Is the same as</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>return 0;\n</code></pre>\n<hr />\n<h1><code>checkWin()</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>int checkWin()\n{\n if (squares[0] == squares[1] && squares[1] == squares[2])\n {\n return 1;\n }\n else if (squares[0] == squares[3] && squares[3] == squares[6])\n {\n return 1;\n }\n else if (squares[0] == squares[4] && squares[4] == squares[8])\n {\n return 1;\n }\n else if (squares[3] == squares[4] && squares[4] == squares[5])\n {\n return 1;\n }\n else if (squares[1] == squares[4] && squares[4] == squares[7])\n {\n return 1;\n }\n else if (squares[6] == squares[4] && squares[4] == squares[2])\n {\n return 1;\n }\n else if (squares[6] == squares[7] && squares[7] == squares[8])\n {\n return 1;\n }\n else if (squares[2] == squares[5] && squares[5] == squares[8])\n {\n return 1;\n }\n \n}\n</code></pre>\n<p>A more readble way to do this would be to store the patterns in an array, and everytime you want to check for a winner, you iterate through the array and use them.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr int winPatterns[8][3]{\n {0, 1, 2}, // first row\n {3, 4, 5}, // second row\n\n //...\n};\n\n</code></pre>\n<p>Now when you want to check for a winner</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (int i = 0;i < 8;i++){\n auto const& line = winPatterns[i];\n const int a = squares[line[0]];\n const int b = squares[line[1]];\n const int c = squares[line[2]];\n if ( a == b and b == c ) return a;\n}\n</code></pre>\n<hr />\n<h1>Checking for draw</h1>\n<p>Instead of checking whether each and every cell is occupied, use an <code>int</code> which is initially set to <code>0</code>. Keep incrementing it after every turn. That way you can get the result like so</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool checkDraw(){\n return (checkWin() != Result::Win and counter == 9 );\n}\n</code></pre>\n<p>It is simple. If the counter reaches 9 and no one has won yet, it is a draw because all the cells are occupied without a winner.</p>\n<hr />\n<h1>Printing the board</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>cout << "\\n\\n\\tTic Tac Toe\\n\\n";\n\n cout << "Player 1 (X) - Player 2 (O)" << endl\n << endl;\n cout << endl;\n\n cout << " | | " << endl;\n cout << " " << squares[0] << " | " << squares[1] << " | " << squares[2] << endl;\n\n cout << "_____|_____|_____" << endl;\n cout << " | | " << endl;\n\n cout << " " << squares[3] << " | " << squares[4] << " | " << squares[5] << endl;\n\n cout << "_____|_____|_____" << endl;\n cout << " | | " << endl;\n\n cout << " " << squares[6] << " | " << squares[7] << " | " << squares[8] << endl;\n\n cout << " | | " << endl\n << endl;\n</code></pre>\n<p>You can use <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">string literals</a> here.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const char* Heading = R"(\n Tic Tac Toe\n\nPlayer 1 (X) - Player 2 (O)\n\n)";\n\nstd::cout << Heading;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:30:29.163",
"Id": "498929",
"Score": "0",
"body": "i do not see why we cant use `new` and `delete` here as some save in memory is better and also could you explain the `enum` thing to me Thank you for the review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:31:10.453",
"Id": "498930",
"Score": "0",
"body": "i used `using namespace std;` because i was not going to imlememnt any other library here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:45:07.717",
"Id": "498933",
"Score": "0",
"body": "@VedantMatanhelia it is not about why you can't use, it is just that `new` just makes your program more complicated. It has no advantage here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:49:03.993",
"Id": "498934",
"Score": "1",
"body": "@VedantMatanhelia What do you mean \" save in memory is better? \" What do you think is happening with `new`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:52:27.827",
"Id": "498935",
"Score": "0",
"body": "@VedantMatanhelia Reading the link I provided will give more clarity on why it is considered bad practice. There has to be a reason why both the reviews you got have the same point :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:59:11.110",
"Id": "498936",
"Score": "1",
"body": "@VedantMatanhelia Read: [Why should C++ programmers minimize use of `new`?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new#:~:text=You%20can%20create%20objects%20by,thinking%20like%20a%20Java%20programmer.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T13:01:18.363",
"Id": "498937",
"Score": "3",
"body": "@VedantMatanhelia In short, automatic allocations are faster, less code to type, and not prone to memory leaks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T13:15:23.147",
"Id": "498938",
"Score": "0",
"body": "Ok Thank you @AryanParekh"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:54:46.160",
"Id": "499078",
"Score": "1",
"body": "@AryanParekh That `line[0] == line[1] and line[1] == line[2]` bit doesn't mean what it looks like it means. You forgot to index `squares`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:23:44.683",
"Id": "499108",
"Score": "0",
"body": "@wizzwizz4 Good catch, sorry about that, fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T10:18:17.847",
"Id": "499133",
"Score": "1",
"body": "And even in those cases, `std::make_unique()` and friends are probably more appropriate."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T08:21:53.837",
"Id": "253069",
"ParentId": "253068",
"Score": "12"
}
},
{
"body": "<h2>Avoid <code>using namespace std</code></h2>\n<p>I cannot emphasize enough on how bad this can be, avoid it now. You might not feel its effect now, but it becomes a headache when the size of the codebase increases. Imagine this, you have a class that defines a method <code>cout</code>, this might seem trivia, who would define a method with <code>cout</code>?. But you should know, there are numerous good and reasonable names that are already taken by the standard libary, what good name can you come up for <code>sin</code>, <code>cos</code> or <code>tan</code>. Doing this makes the compiler confused and results to undefined behaviors. Not only that, you pollute everywhere with irrelevant stuff you aren't using. Prefer</p>\n<pre><code>std::cout << "Hello World\\n"\n</code></pre>\n<p>or</p>\n<pre><code>using std::cout\ncout << "Hello World\\n"\n</code></pre>\n<p>in the latter, the effect is localized to just <code>std::cout</code></p>\n<h2>Avoid GLOBALS!!!!</h2>\n<p>Just one global might seem reasonable to the <code>programmer</code>, but it leads to many subtle bugs and makes the code dependent on those globals.</p>\n<pre><code>char *squares = new char[9]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};\n</code></pre>\n<p>could be defined in <code>main()</code> and passed as an argument to other functions.</p>\n<h2>Builtins are never implicitly defined in a local scope</h2>\n<p>Builtins like Integral types and floating-point types are never initialized implicitly,</p>\n<pre><code>int a;\n</code></pre>\n<p>This above snippet is uninitialized and is a source of hard to track bugs, avoid it, when in doubt, explicitly initialize your variables. This means, the above code snippet becomes</p>\n<pre><code>int a{}\n</code></pre>\n<p>Here a is initialized to 0.</p>\n<h2>Bad delete</h2>\n<pre><code>delete mark, choice, i;\n</code></pre>\n<p>Ok, you want to free the memory allocated to those variables, but oops, what have you done, you succeeded in deleting just <code>mark</code>. <code>choice</code> and <code>i</code> are never deleted. A good compiler should warn against, this emphasizes that you should make the compiler your friend, do not let warnings pass implicitly, take care of them or they might hurt you later.</p>\n<pre><code>delete mark;\ndelete choice;\ndelete i;\n</code></pre>\n<p>Now, this is better, we made it explicit what we want to do.</p>\n<h2>Detour</h2>\n<ol>\n<li><p><code>getBoard()</code> is a misleading name, variable naming is the heart of programming and must carry its intent as unambiguous as possible, a first glance at <code>getBoard()</code>, I would be expecting an array of board as a return value, but it suprisingly prints a board to the <code>stdout</code>, a better name would be <code>printBoard</code> or <code>displayBoard</code>, this is so clear to a reader like me.</p>\n</li>\n<li><p>Right now, after a game is over, a user might want to play again, but your game does not reset itself, you might want to fix that subtle bug.</p>\n</li>\n<li><p>Some parts of your code are really messy, I would highlight just a few of them. Right now, you have a lot of checks just to place a mark at a location. You can simplify things by having an <code>isValid()</code> function like this</p>\n</li>\n</ol>\n<pre><code>bool isValid(int loc)\n return loc > 0 && loc <= MAX_SIZE;\n</code></pre>\n<p>Then placing a mark is as simple as saying</p>\n<pre><code>squares[*choice-1] = *mark;\n</code></pre>\n<p>[EDIT]\n<code>isValid()</code> checks if a user's input is within the range of the <code>squares</code> for example <code>1</code> is valid because it is greater than <code>0</code> and less than <code>9</code>(The size of the squares).\n<code>-1</code> is invalid because it is not greater than <code>0</code> though it is less than <code>9</code>.\nIf <code>isValid()</code> returns true, we can offset it by 1 to give the location in <code>squares</code>, so a value of <code>1</code> means an index of <code>0 </code>in <code>squares.</code></p>\n<p>This greatly reduces the code size, you might want to consider the same approach for <code>checkwin()</code>.</p>\n<h2>Side Note</h2>\n<p>When you have multiple if-else statements, consider refactoring your code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:26:47.880",
"Id": "498928",
"Score": "0",
"body": "I was initially using a for loop to put the mark but there was a subtle bug and so i changed it and also some other things like the `isValid()` function you made is a little unclear to me could you please help me and explain that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:38:53.223",
"Id": "498932",
"Score": "0",
"body": "Can you explain the `isValid()` function a little. Thank you for the review. It helped me a lot and i did not know about the error in `delete` as my compiler was not showing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T13:44:31.060",
"Id": "498940",
"Score": "0",
"body": "@VedantMatanhelia I edited my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T17:42:08.527",
"Id": "498963",
"Score": "0",
"body": "Thanks for the explanation but how is the MAX_SIZE = sqaures length"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T18:30:24.713",
"Id": "498968",
"Score": "0",
"body": "I avoided constant literals, MAX_SIZE can be declared to hold the size of the array, which happens to be 9."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T08:35:38.070",
"Id": "253071",
"ParentId": "253068",
"Score": "8"
}
},
{
"body": "<p>The other answers have some very good advice.\nI would just like to add a few opinions.</p>\n<h2>Separation of concerns</h2>\n<p>The data structure <code>squares</code> has been given two very different jobs:</p>\n<ul>\n<li>Keep track of what happens in the game.</li>\n<li>Keep track of what to display to the user after each move.</li>\n</ul>\n<p>These are two different concerns. It's usually good to separate the <em>display</em> of what happens in a program from the actual data and algorithms of a program.</p>\n<p>In this particular case, you have the very wordy and repetitious logic of</p>\n<p><code>if (squares[0] == '1' && *choice == 1)</code></p>\n<p>and the other eight similar checks because you are using the symbol that will be <em>displayed</em> in each square to decide what has actually <em>happened</em> in each square.\nAs far as the game mechanics go, it would be simpler to have one way to indicate that a square is empty, so you could replace the nine different checks for the contents of the square with one. You could have code something like this:</p>\n<pre><code>if (1 <= choice && choice <= 9)\n{\n if (squares[choice - 1] == EMPTY_SQUARE)\n {\n isValidMove = true;\n squares[choice - 1] = mark;\n }\n else\n {\n std::cout << "That square has already been played.\\n";\n }\n}\nelse\n{\n std::cout << "Your move must be a number between 1 and 9 inclusive.\\n";\n}\n</code></pre>\n<p>(Note that I've assumed you also took the advice to declare variables on the stack rather than using pointers.)</p>\n<p>Note that you could combine the two <code>if</code> conditions together, but a bonus of stating them separately is that you can display more informative error messages to the user depending on which error they make.</p>\n<p>The function that displays the board would then have the sole responsibility for deciding what to show in the empty squares.\nThis would admittedly make its job slightly more complicated, since you cannot just display <code>squares[0]</code> in the upper left square, but you can delegate that job to a subroutine:</p>\n<pre><code>char contentsForDisplay(char* squares, int index)\n{\n static const char* emptyText = "123456789";\n if (squares[index] == EMPTY_SQUARE)\n {\n return emptyText[index];\n }\n else\n {\n return squares[index];\n }\n}\n</code></pre>\n<h2>Less confusing use of data</h2>\n<p>Separation of concerns will help with this in the case of the <code>squares</code> array.\nBut let's also consider the variable <code>player</code>.</p>\n<p>We start out simply enough with <code>int player = 1;</code>,\nbut then we have <code>player = (player%2) ? 1 : 2;</code>,\nlater <code>player++</code>, and yet elsewhere <code>player--</code> and <code>--player</code>.\nIf we were to trace the values the player variable is set to,\nit would sometimes be 3 (after player 2's turn and before we get to\n<code>player = (player%2) ? 1 : 2;</code> in player 1's turn) and\nsometimes 0 (after player 1 attempts an illegal move).</p>\n<p>Even an experienced programmer will have difficulty keeping track of this.\nYou'd better hope nobody has to make any modifications to the code later\n(or that if they do, they have the time to test the living daylights out of it),\nbecause this is an open invitation for bugs to be introduced.</p>\n<p>I also notice that you never say whose turn it is. The first time that the user interface ever uses the numbers 1 or 2 to identify a player is when it says who wins.\nPerhaps you might have noticed this if you didn't have to expend so much mental effort to get the correct player number in the first place.</p>\n<p>Below, I'll suggest some ways to tame this particular variable.</p>\n<p>Now what is this variable named <code>i</code>?\nThat's a typical name for a loop variable, for example in something like this where the only use of <code>i</code> is inside the loop, which is a small chunk of code so that we never have to look very far from where <code>i</code> is used to see how <code>i</code> is defined:</p>\n<pre><code>for (int i = 0; i < NUMBER_OF_SQUARES; ++i)\n{\n squares[i] = EMPTY_SQUARE;\n}\n</code></pre>\n<p>I strongly advise using a more descriptive name such as <code>gameStatus</code> (which also isn't great, but you've overloaded this one poor little variable with having to say whether the game is still going and if it is not still going, whether it's a win or a draw, so it's hard to come up with a short, fully descriptive name).</p>\n<h2>Declare variables closer to where they are used</h2>\n<p>This is related to less confusing use of data.\nYou don't have a lot of opportunities to declare variables more locally in the existing design of your program, but you could at least do this rather than declaring <code>mark</code> where you do:</p>\n<pre><code>char mark = (player == 1) ? 'X' : 'O';\n</code></pre>\n<h2>More functions</h2>\n<p>You could use a few more functions to perform certain tasks within the program.\nI already suggested the function <code>contentsForDisplay</code>.</p>\n<p>A good candidate for a somewhat larger role is a function to perform one move for one player.\nHere is a declaration of one that assumes you have also used an enumeration to describe the mark each player makes in a square:</p>\n<pre><code>void waitForValidMove(PlayerMarker player, int* squares);\n</code></pre>\n<p>This function would prompt the player for a move and continue running (with an internal loop) until the player made a valid response.\nThis means no trickery is required to keep your outer loop playing the correct player (such as decrementing <code>player</code> from 1 to 0 after a illegal move by player 1 so that <code>++player</code> doesn't cause player 2's turn to start).</p>\n<p>This gives you another option to handle the alternation of players:</p>\n<pre><code>GameStatus status = CONTINUE_PLAYING;\nwhile (status == CONTINUE_PLAYING)\n{\n waitForValidMove(FIRST_PLAYER, squares);\n status = checkWin(squares);\n if (status == CONTINUE_PLAYING)\n {\n waitForValidMove(SECOND_PLAYER, squares);\n }\n}\n</code></pre>\n<p>Alternatively, you could do just one player's turn per iteration of the main loop, but use a function to tell whose turn it is:</p>\n<pre><code>enum PlayerMarker getNextPlayer(PlayerMarker currentPlayer)\n{\n return (currentPlayer == FIRST_PLAYER ? SECOND_PLAYER : FIRST_PLAYER);\n}\n</code></pre>\n<p>This is more wordy than just writing <code>player = (player%2) ? 1 : 2;</code>, but it's clearer, and it's more self-documenting than even just writing\n<code>player = (player == FIRST_PLAYER ? SECOND_PLAYER : FIRST_PLAYER);</code> in-line.</p>\n<p>Another candidate might be a function to decide whether a particular winning set of squares has been taken by one player:</p>\n<pre><code>bool squaresAreWon(const char* squares, int index1, int index2, int index3)\n{\n return (squares[index1] == squares[index2] && squares[index2] == squares[index3]);\n}\n</code></pre>\n<p>This may seem trivial, but it lets you write code that is more compact and self-documenting:</p>\n<pre><code>if (squaresAreWon(squares, 0, 1, 2)\n || squaresAreWon(squares, 3, 4, 5)\n || squaresAreWon(squares, 6, 7, 8)\n ... etc. ...\n</code></pre>\n<p>(But note that an alternative to an additional function is to implement an additional data structure such as the <code>winPatterns</code> array recommended in another answer.)</p>\n<h2>Use objects</h2>\n<p>The main thing that's supposed to distinguish C++ from C (at least the way I heard it years ago) is that C++ is object-oriented.\nThat's a debatable proposition, but it is a fact that C++ has convenient syntax (the <code>class</code> syntax) for defining types of "objects".</p>\n<p>This particular program is so simple that classes/objects might be overkill, but for someone experienced with C++ classes it's tempting to create a <code>Board</code> class to contain the record of what has been played in each square, in which case <code>Board</code> could have a public function\n<code>bool checkWin() const;</code>\nso that any subroutines that function uses could be made private functions of <code>Board</code>.</p>\n<p>Actually, with a <code>Board</code> class you could have the function of <code>Board</code> that records a player's move also immediately determine whether the game is still going, a win, or a draw, and set member variables of the <code>Board</code> object accordingly, so that you can simply call <code>bool</code>-valued functions of <code>Board</code> to find out whether you need to keep playing (during the loop) and whether someone has won (after the loop). This would solve the problem of what kind of reasonably descriptive name to give to your variable <code>i</code> -- you would no longer need to declare that variable at all.</p>\n<p>To be honest, however, it might be better to wait until you have a problem where creating some classes will really help with the implementation,\nunless you have a particular desire to make <em>this</em> project the one in which you move beyond using C++ as a fancy version of C.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:37:41.460",
"Id": "499111",
"Score": "0",
"body": "Good review, but don't you think using classes over here would be an overkill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T12:56:41.293",
"Id": "499151",
"Score": "1",
"body": "@AryanParekh Yes, that's why I said \"might be overkill\" and \"might be better to wait\". Frankly I hesitated a bit about including that section at all, and that's why it's at the end. It's certainly possible to make entirely too many classes to solve a simple problem, as shown hilariously at https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:04:32.717",
"Id": "253143",
"ParentId": "253068",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253069",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T06:00:01.887",
"Id": "253068",
"Score": "9",
"Tags": [
"c++",
"beginner",
"memory-management",
"tic-tac-toe",
"c++14"
],
"Title": "A Tic Tac Toe game in C++"
}
|
253068
|
<p>I've produced some JavaScript code for a Video Player, but my experience in coding is with C# and the differences between the languages and my lack of experience has made me wonder I'm not following the correct guidelines.</p>
<p>I'm just wondering if anyone doing a once-over would have any good criticisms and pointers they could offer. I've commented the code to explain my thinking.</p>
<pre><code>let activateDisc = false;
let playingDisc = false;
let animatingDisc = false;
let volumeOn = true;
//Get the elements on the page.
let page = document.querySelector("#page");
let cover = document.querySelector("#videocover");
let disc = document.querySelector("#disc");
let playIcon = document.querySelector("#playicon");
let pauseIcon = document.querySelector("#pauseicon");
let volumeOnIcon = document.querySelector("#volumeon");
let volumeOffIcon = document.querySelector("#volumeoff");
let videoContainer = document.querySelector("#videocontainer");
let video = document.querySelector("video");
let volumeButton = document.querySelector("#volume");
let videoSlider = document.querySelector("#videoslider");
//Set it up so clicking the disc will start the video and the video ending will eject the disc.
disc.onclick = function() {insertDisc();}
video.onended = function() {ejectDisc();}
//Attach each element to their equivalent function.
document.querySelector("#restart").onclick = function() {resetVideo();}
document.querySelector("#rewind").onclick = function() {rewindVideo();}
document.querySelector("#skip").onclick = function() {skipVideo();}
document.querySelector("#end").onclick = function() {ejectDisc();}
//For play if the disc isn't in, we want to insert it.
document.querySelector("#play").onclick = function() {
if (!activateDisc) {
window.scrollTo(0, 0);
insertDisc();
}
else {
//Then we want to check either pause or play the video.
if (!playingDisc){
playVideo();
}
else {
pauseVideo();
}
}
}
//The volume button checks if the volume is on and calls the correct method.
volumeButton.onclick = function() {
if (volumeOn){
turnVolumeOff();
}
else {
turnVolumeOn();
}
}
//Every time the current playing position of the video updates we'll set the slider accordingly.
video.ontimeupdate = function() {
//The slide is set as the current time in the video over the total length of the video multiplied by the max slider value.
videoSlider.value = video.currentTime / video.duration * videoSlider.max;
}
//When the mouse is over the video we want to show the video slider and volume button.
videoContainer.addEventListener('mouseover', function() {
videoSlider.style.opacity = 1;
volumeButton.style.opacity = 1;
},false);
//When the mouse leaves the video we want to hide the video slider and volume button.
videoContainer.addEventListener('mouseout', function() {
videoSlider.style.opacity = 0;
volumeButton.style.opacity = 0;
},false);
//When the slider value is changed we want to set the video time to the slider value.
videoSlider.addEventListener("input", function() {
//The current time in the video is set as the slider value over the max slider value multiplied by the total length of the video.
video.currentTime = videoSlider.value / videoSlider.max * video.duration;
}, false);
//Inserting the disc.
function insertDisc() {
//If the disc is already in eject it.
if (!activateDisc){
//If the disc is already animating we return and do nothing.
if (animatingDisc) return;
animatingDisc = true;
activateDisc = true;
disc.style.animation = "playdisc 1s linear";
//Wait for the disc to be fully inserted and play the video.
setTimeout(() => {
playDiscAnimation();
scrollToWithOffset(disc, -80);
hideElement(cover);
video.style.animation = "flicker 500ms infinite alternate-reverse";
playVideo();
}, 1000);
}
else {
ejectDisc();
}
}
//Ejecting the disc.
function ejectDisc() {
//If the disc is in we can eject it.
if (activateDisc){
if (animatingDisc) return;
animatingDisc = true;
//Reset the video back to its original state and eject it.
pauseVideo();
resetVideo();
turnVolumeOn();
video.style.animation = "";
showElement(cover);
ejectDiscAnimation();
window.scrollTo(0, 0);
//Replay the disc bouncing animation.
setTimeout(() => {
disc.style.animation = "bounce 300ms infinite alternate-reverse";
activateDisc = false;
}, 1000);
}
}
//Play the video.
function playVideo() {
if (!activateDisc) return;
playTvAnimations();
playingDisc = true;
video.play();
}
//Pause the video.
function pauseVideo() {
if (!activateDisc) return;
pauseTvAnimations();
playingDisc = false;
video.pause();
}
//Reset the video back to zero.
function resetVideo() {
if (!activateDisc) return;
video.currentTime = 0;
}
//Rewind the video 5 milliseconds.
function rewindVideo() {
if (!activateDisc) return;
video.currentTime -= 5;
}
//Skip 5 milliseconds in the video.
function skipVideo() {
if (!activateDisc) return;
video.currentTime += 5;
}
//Turn the volume on.
function turnVolumeOn() {
video.volume = 1;
hideElement(volumeOffIcon);
showElement(volumeOnIcon);
volumeOn = true;
}
//Turn the volume off.
function turnVolumeOff() {
video.volume = 0;
hideElement(volumeOnIcon);
showElement(volumeOffIcon);
volumeOn = false;
}
//Play the disc insertion and playing animations.
function playDiscAnimation() {
disc.style.animation = "spindisc 300ms infinite linear";
page.style.backgroundColor = "#333030";
animatingDisc = false;
}
//Play the disc ejection animation.
function ejectDiscAnimation() {
disc.style.animation = "playdisc 1s reverse";
disc.style.animationPlayState = "running";
page.style.backgroundColor = "#b8c9dd";
animatingDisc = false;
}
//Play the tv animation.
function playTvAnimations() {
disc.style.animationPlayState = "running";
hideElement(playIcon);
showElement(pauseIcon);
}
//Pause the tv animations.
function pauseTvAnimations() {
disc.style.animationPlayState = "paused";
hideElement(pauseIcon);
showElement(playIcon);
}
//Show an element by setting its display to block.
function showElement(element) {
element.style.display = "block";
}
//Hide an element by setting its display to none.
function hideElement(element) {
element.style.display = "none";
}
//Scroll towards an element with a Y offset.
function scrollToWithOffset(element, yOffset = 0){
var scrollY = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo(0, scrollY);
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, congrats on readable code. It's not at all hard to follow what's happening, and seems like it would be easy for someone else to comprehend.</p>\n<p>I have a few suggestions for you. Mostly these will just make your JavaScript more idiomatic, but there are some quality improvements possible too.</p>\n<p><strong>Let vs Const vs Var</strong></p>\n<p>In modern JavaScript, you probably don't want to use <code>var</code>. It makes your variable declarations subject to <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Hoisting\" rel=\"nofollow noreferrer\">hoisting</a>, which can create unpredictable behavior by making the variable name available in places you don't expect it to be, especially when coming from another language.</p>\n<p>My suggestion is to always use <code>const</code>, unless you know you're going to be reassigning the variable, then use <code>let</code>. This implies that the variable name within a block will always refer to the same object/value in the case of <code>const</code>, or that you might reassign it, in the case of <code>let</code>. Either choice is a signal to the next person reading the code and can help with maintainability. Also, if you're linting your project, your code quality tools can warn you if you try to unintentionally reassign a <code>const</code>. More <a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#:%7E:text=%60const%60%20is%20a%20signal%20that,always%20the%20entire%20containing%20function.\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Most of your uses of <code>let</code> should be <code>const</code>. Same with what appears to be your only use of <code>var</code>.</p>\n<p><strong>Single Line If-Then</strong></p>\n<p>I'm going to suggest you don't do this:</p>\n<pre><code>if (!activateDisc) return;\n</code></pre>\n<p>People think it's short and nifty, but it's a case where shortcuts can cause problems later. Use block scoping for the body of your <code>if-then</code> statements to avoid the hazards of <a href=\"https://2ality.com/2011/05/semicolon-insertion.html\" rel=\"nofollow noreferrer\">automatic semicolon insertion</a>, like so:</p>\n<pre><code>if (!activateDisc) {\n return;\n}\n</code></pre>\n<p><strong>Name Your Event Handlers</strong></p>\n<p>In the browser, you want to be able to remove event handlers if they're no longer needed. If you don't, things can happen that you don't expect. For that reason,\n<em>and</em> because it simply isn't necessary, you shouldn't wrap your event handler functions in anonymous functions. You should probably use <code>addEventListener</code> instead of assigning to <code>onclick</code>, so you can assign more than one event handler to the click event if required. Using a named function instead of an anonymous one will give you a reference so you can remove the handler later.</p>\n<p>EG, this:</p>\n<pre><code>document.querySelector("#restart").onclick = function() {resetVideo();}\n</code></pre>\n<p>should be:</p>\n<pre><code>document.querySelector("#restart").addEventListener("click", resetVideo);\n</code></pre>\n<p>That way, you can later do this if you need to:</p>\n<pre><code>document.querySelector("#restart").removeEventListener("click", resetVideo);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T21:56:46.667",
"Id": "498990",
"Score": "0",
"body": "To give the beginner a bit of orientation, you should be more specific about what _can cause problems later_ and _things can happen_ mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T12:00:43.893",
"Id": "499050",
"Score": "0",
"body": "This helps! Event handling is something I wasn't aware of, makes sense to use it. I'm sure it'll help when making websites for mobile and pc as I can switch up which of the events call each method, as I'm sure `mouseover` isn't available on mobile. As for the rest I'll try and apply your guidelines. Cheers!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T15:29:47.093",
"Id": "253084",
"ParentId": "253070",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T08:34:59.183",
"Id": "253070",
"Score": "1",
"Tags": [
"javascript",
"beginner"
],
"Title": "JavaScript video player"
}
|
253070
|
<p>I am trying to implement a <strong>thread-safe</strong> LRU cache algorithm, please review my code and would really appreciate some criticism or suggestion.</p>
<p>Some assumptions:</p>
<ol>
<li>capacity will be larger than 0</li>
</ol>
<p>Some questions I have:</p>
<ol>
<li><p>I know it is better to encapsulate variables in a class and declare them private, but since DDLNode is simply a data class, is it acceptable to make the variables public ?</p>
</li>
<li><p>I am considering to extract the following block of code (inside <code>put</code>) into a function (something like <code>addEntry(key, value</code>)</p>
<pre><code>DDLNode<K, V> node = new DDLNode<>(key, value);
addNode(node);
entries.put(key, node);
</code></pre>
<p>do you think it's neccesary? or the original code is self-explanatory enough?</p>
</li>
</ol>
<p>Here is the code, Thanks in advance!!</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
interface CacheAlgorithm<K, V> {
public V get(K key);
public void put(K key, V value);
}
class DDLNode<K, V> {
public V value;
public K key;
public DDLNode<K, V> prev;
public DDLNode<K, V> next;
public DDLNode() {}
public DDLNode(K key, V value) {
this.key = key;
this.value = value;
}
}
public class LRU<K, V> implements CacheAlgorithm<K, V> {
private final ReentrantLock lock;
private final int capacity;
private final Map<K, DDLNode<K, V>> entries;
private final DDLNode<K, V> head;
private final DDLNode<K, V> tail;
public LRU(int capacity) {
this.capacity = capacity;
lock = new ReentrantLock();
head = new DDLNode<>();
tail = new DDLNode<>();
entries = new HashMap<>(capacity);
head.next = tail;
tail.prev = head;
}
@Override
public V get(K key) {
lock.lock();
try {
if (!entries.containsKey(key)) {
return null;
}
DDLNode<K, V> node = entries.get(key);
moveToMostRecent(node);
return node.value;
} finally {
lock.unlock();
}
}
@Override
public void put(K key, V value) {
lock.lock();
try {
if (entries.containsKey(key)) {
DDLNode<K, V> node = entries.get(key);
node.value = value;
moveToMostRecent(node);
} else {
if (entries.size() == capacity) {
removeLeastRecentEntry();
}
DDLNode<K, V> node = new DDLNode<>(key, value);
addNode(node);
entries.put(key, node);
}
} finally {
lock.unlock();
}
}
private void removeLeastRecentEntry() {
entries.remove(tail.prev.key);
removeNode(tail.prev);
}
private void moveToMostRecent(DDLNode<K, V> node) {
removeNode(node);
addNode(node);
}
private void removeNode(DDLNode<K, V> node) {
DDLNode<K, V> prev = node.prev;
DDLNode<K, V> next = node.next;
prev.next = next;
next.prev = prev;
}
private void addNode(DDLNode<K, V> node) {
DDLNode<K, V> headNext = head.next;
head.next = node;
node.prev = head;
headNext.prev = node;
node.next = headNext;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I like the codestyle!</p>\n<p><strong>Code organization tips</strong>:</p>\n<ul>\n<li><p>Its better to move <code>DDLNode</code> into <code>LRU</code> and make it static, because sole purpose of this class is to be used by <code>LRU</code> class.</p>\n</li>\n<li><p>If you are not going to expose <code>DDLNode</code> to outside world, then it make sense to make it also <code>private</code>. Keeping its fields as public is fine here.</p>\n</li>\n<li><p>If you want to expose <code>DDLNode</code> to outside world (for example, in iterator), you should think more thoroughly about field access. You can get inspiration from <code>HashMap.Node</code> class, for example: fields here have default access, so <code>HashMap</code> itself can manipulate them without using getter or setters. Also note, that there is no <code>setKey()</code> method for outside world, because if we change the key on the node it will break the map.</p>\n</li>\n<li><p>Maybe you just put all the classes into 1 file to make it easies for us to read , but if not - its bad practice to have more than 1 class/interface in 1 file.</p>\n</li>\n</ul>\n<p><strong>Optimization tips</strong>:</p>\n<ul>\n<li><p>In <code>get()</code> you are doing unnecessary <code>.containsKey()</code> call, because just <code>.get(key)</code> is enough: if key if present, it will find it; if not, then it will return null and you can then just return from method.</p>\n</li>\n<li><p>Unnecessary <code>containsKey()</code> call in <code>put()</code> as well: you can just check <code>.get(key) == null</code> instead.</p>\n</li>\n<li><p>head and tail will always occupy memory, event if map is empty. They could be removed, although then you should be more careful will null checks.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T14:38:57.527",
"Id": "498951",
"Score": "0",
"body": "Thanks a lot for your comments! Appreciated it.Some followup to your comment: \n1. The DDLNode class is actually gonna be used if other classes ( I actually have another cache algo class MRU), how can the HashMap.Node design be applied in that case? 2.if DDLNode is used by mutlipled classes, you think i can still keep the fields public? (I do know it's an anti-pattern but also think using setter and getter function everywhere is quite messy :p, need a second opinion) Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T17:13:22.753",
"Id": "499211",
"Score": "0",
"body": "@yploo First of all, what this DDLNode? Abbreviations, especially not widely known, are confusing. My guess is that its DoublyLinkedListNode (which is DLLNode - even more confusing name). \nAnyways, if you are going to implement Most recently used cache - you can just use this class for both - the only difference will be in `removeLeast/MostRecentEntry()` method. In this case keeping `Node` class as private static makes total sense.\n\nMy example about HashMap.Node was to show that if you want to expose those nodes, you should be careful what getters/setters you expose"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T13:24:41.860",
"Id": "253079",
"ParentId": "253072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T09:03:07.150",
"Id": "253072",
"Score": "1",
"Tags": [
"java",
"multithreading",
"concurrency",
"cache"
],
"Title": "Thread-safe LRU Cache Implementation in Java"
}
|
253072
|
<p>I am a newbie in programming, but I do have potential, I am using PowerShell to hone my skills, I have written a simple function to sort strings consisted of numbers humanly (i.e. in a order like 1 2 10 25 32 123), using the basic concept of padding, I would like to see it be expanded so that it can sort strings containing numbers like "a12b3 c14","a10b5 c12","a5b1 c2" alphanumerically(according to the value of numbers rather than single digits), it is currently above my level, for now, so I want someone more experienced than me to help me expand my code, I will post it below so you can review it:</p>
<pre><code> function Sort-Num {
PARAM (
[Parameter(ValueFromPipeline=$true)]
[System.String]$String
)
Process {
$array = $String.Split( )
$padnum = @()
$sorted = @()
$numbers = @()
$length=0
foreach ($arra in $array) {
while ($arra.Length -gt $length) {
$length=$arra.Length
}
}
foreach ($arra in $array) {
$padded = "{0:D$length}" -f [int64]$arra
$padnum +=$padded
}
$sorted = $padnum | Sort-Object
foreach ($sorte in $sorted) {
$number=[int64]$sorte
$numbers+=$number
}
$numbers
}
}
</code></pre>
<p>Edit: My idea is: first split the string by space and create an array of the substrings, then use regex match to find letters and numbers in the substrings, remember their respective position, creating an array of [PSCustomObject], then split the substrings in the first array into substrings of letters and numbers based on regex match recursively, foreach iteration of substrings of substrings create an [PSCustomObject] of the substring according to the order identified in second step, like: [PSCustomObject]@{letter="a";number=12;letter="b";number=3...}
then find the longest number in each column and pad other numbers in the same column to the same length, and then sort the second array and then eliminate the leading zeroes and then rejoin the substrings of the second array and add them to a third array...</p>
<p>Maybe this sounds complex in natural language but this would be much simpler in code, I just haven't figured out how to implement my idea in code, yet...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T10:48:16.157",
"Id": "498923",
"Score": "0",
"body": "Your question seems to be [off-topic](https://codereview.stackexchange.com/help/on-topic) here (syntax errors). Code Review aims to help improve **working** code; ask on [Stack Overflow](https://stackoverflow.com/help/on-topic) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T10:57:14.280",
"Id": "498924",
"Score": "0",
"body": "@JosefZ, what sort of syntax errors? I have tested my code on Windows 10 x64 PowerShell PSCore 7.1 and it is really working, I wouldn't post it if I didn't test it, maybe you used a lower version of powershell or windows? I don't guarantee my code will work on lower versions of PowerShell..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:22:46.363",
"Id": "498925",
"Score": "0",
"body": "Edit: for those who even greener than me, here is a simple guide on how to use my code; First, make sure your operating system is Windows 7 and above, PowerShell 5.1 and above, PSCore6 and above prefered, I recommend Windows 10 x64 and PowerShell 7.1 x64 because they are what I used when I tested my code, these thing are extremely important because the softwares aren't forward compatible, when the outdated softwares were written the newer syntaxes of PowerShell programming language haven't been invented, so there might be syntax errors as the commenter noticed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:23:00.150",
"Id": "498926",
"Score": "0",
"body": "Now if you do have up-to-date software, just copy my code and open PowerShell and right click and press Enter, now you can invoke my function by typing Sort-Num, the usage of my function is like this: Sort-Num \"123456789 23456789 3456789 456789 56789 6789 789 89 9\", first type Sort-Num and then type a string consisting entirely of numbers seperated by spaces enclosed in two double quotation marks, take the above as an example and it will correctly output in the reversed order of the order they are inputed;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T12:23:15.083",
"Id": "498927",
"Score": "0",
"body": "Or if you prefer using files, open Notedpad++ and paste my code into a new file, and press enter and input \"$string=Read-Host\" without the quotation marks and press enter and input \"Sort-Num $string\" without the quotation marks and save it as *.ps1 and open PowerShell and cd to where you saved the script and .*.ps1...(there should be a backward slash symbol between the dot and asterisk that somehow isn't displayed, the asterisk is a wildcard character representing everything, here it means your file name, don't use an actual asterisk though...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T18:05:29.420",
"Id": "498966",
"Score": "1",
"body": " Thank you for thorough guide . Tried `Sort-Num -String \"a12b3 c14\"` (had overlooked that it's your _future_ goal, sorry). Please be at least as thorough in formulating your questions. Your script does the same as `[int64[]]\"123456789 23456789 3456789 456789 56789 6789 789 89 9\".Split() | Sort-Object`. And keep in mind that _codereview_ isn't a free code-writing service so your demand _\"to help me expand my code\"_ is definitely off-topic here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:50:59.427",
"Id": "499266",
"Score": "1",
"body": "A natural sort *trick* picked up [here](https://gist.github.com/markwragg/e2a9dc05f3464103d6998298fb575d4e) applied to your inputs: `$NaturalSort = {[regex]::Replace($_, '\\d+', { $args[0].Value.PadLeft(20) })};@('a12b3', 'c14', 'a10b5', 'c12', 'a5b1', 'c2') | sort-object $NaturalSort`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T09:19:25.303",
"Id": "253074",
"Score": "1",
"Tags": [
"beginner",
"sorting",
"powershell"
],
"Title": "PowerShell - Sort strings containing numbers numerically"
}
|
253074
|
<p>For something I'm working on, I need a function that takes in a one-dimensional array <code>vec</code> of integers and returns a boolean array of the same shape indicating where the <code>n</code> largest entries of <code>vec</code> are located.</p>
<p>For example,</p>
<ul>
<li><code>nlargest([0, 1, 3, 5], 2)</code> should yield <code>[0, 0, 1, 1]</code>.</li>
<li><code>nlargest([0, 0, 4, 0, 3, 6], 2)</code> should yield <code>[0, 0, 1, 0, 0, 1]</code>.</li>
<li><code>nlargest([2, 1, 4, 3], 1)</code> should yield <code>[0, 0, 1, 0]</code>.</li>
</ul>
<p>I have decided it's worthwhile to write my own function to do this, because the input data in this case has a few "nice" properties:</p>
<ul>
<li><code>n</code> is always strictly smaller than the number of nonzero entries in <code>vec</code> and greater than zero</li>
<li>The nonzero entries are all positive integers and there are no ties among them</li>
</ul>
<p>Here is a working Julia function that does this:</p>
<pre><code>function nlargest(vec, n)
# Boolean vector shaped like input indicating n largest entries
inp = copy(vec)
out = zeros(Bool, length(vec))
for i in 1:n
am = argmax(inp)
out[am] = true
inp[am] = -1
end
return out
end
</code></pre>
<p><strong>I am more interested in the design of the algorithm itself than the specific Julia implementation</strong>, so here is equivalent pseudocode:</p>
<ul>
<li>Initialize: <code>out</code> ← a array of boolean <code>0</code>s shaped like <code>vec</code></li>
<li>Repeat <code>n</code> times:
<ul>
<li><code>j</code> ← <code>argmax(vec)</code></li>
<li>Set the <code>j</code>th entry of <code>out</code> to <code>1</code></li>
<li>Set the <code>j</code>th entry of <code>vec</code> to <code>-1</code> (*)</li>
</ul>
</li>
<li>Return <code>out</code></li>
</ul>
<p>(*) is taking advantage of the fact that all the nonzero entries are positive, but it feels like a bit of a hack to me. An alternative idea I had for this step was to "pop" the <code>j</code>th entry out of <code>vec</code> so that <code>argmax(vec)</code> has shorter input on the next loop. But it seems to me that the time savings there are offset by then having to adjust subsequent <code>j</code> values based on the new length of <code>vec</code>. <strong>Is this reasoning sound, or is there something clever I can do here?</strong></p>
<p><strong>Have I taken full advantage of the structure of my input data?</strong> Can I do better than the default <code>argmax()</code> function?</p>
<p>Of course, feedback on the Julia implementation is also welcome.</p>
|
[] |
[
{
"body": "<p>The algorithm you described has complexity <code>O(n * m)</code>, where <code>m</code> is the size of the input array, since you run a full <code>argmax</code> at every one of the <code>n</code> iterations.</p>\n<p>You can achieve the same thing by collecting the indices of the <code>n</code> largest values once, and then set only those indices to <code>1</code> in the result array. For finding of the <code>n</code> largest values, you could use a <a href=\"https://en.wikipedia.org/wiki/Heap_(data_structure)\" rel=\"nofollow noreferrer\">heap</a>, but Julia makes this easier with <a href=\"https://docs.julialang.org/en/v1/base/sort/#Base.Sort.partialsortperm\" rel=\"nofollow noreferrer\"><code>partialsortperm</code></a>:</p>\n<pre><code>function nlargest(v, n; rev=true)\n result = falses(size(v))\n result[partialsortperm(v, 1:n; rev=rev)] .= true\n return result\nend\n</code></pre>\n<p>This uses a <code>BitArray</code> for storage; if <code>n << m</code>, even a sparse array might pay off. It should have complexity <code>O(m + n log n)</code>, unless I'm misjudging <code>partialsortperm</code>. Note that sorting algorithms in Julia work ascending by default, so you have to use <code>rev=true</code> to get the equivalent of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T05:50:15.067",
"Id": "500258",
"Score": "0",
"body": "Once again I am pleasantly surprised to find a Julia builtin for something I had been coding my way around. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T14:30:53.527",
"Id": "253662",
"ParentId": "253080",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T13:31:38.577",
"Id": "253080",
"Score": "2",
"Tags": [
"algorithm",
"julia"
],
"Title": "Return n largest nonzero entries of an array"
}
|
253080
|
<p>This is a <a href="https://www.codewars.com/kata/5539fecef69c483c5a000015/java" rel="noreferrer">challenge on Codewars</a> I took years ago. Task is to find all prime numbers that are also a prime number when reversed, i.e. 13 -> 31 is such a number.
This is still the answer with the most upvotes in the categories 'Best practice' as well as in 'Clever'.
Any improvements or thoughts about this piece of code? Please keep in mind in code challenges like this I always try to code as concise as possible.</p>
<p>Examples in => output :</p>
<pre><code> backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]
backwardsPrime(501, 599) => []
</code></pre>
<p>code:</p>
<pre><code>public class BackWardsPrime {
public static String backwardsPrime(long start, long end) {
StringBuilder sb = new StringBuilder();
while(start <= end){
long rev = Long.parseLong(new StringBuilder(
String.valueOf(start)).reverse().toString());
if(start > 12 && isPrime(rev) && isPrime(start) && start != rev)
sb.append(start + " ");
start++;
}
return sb.toString().trim();
}
static boolean isPrime(long n) {
if(n % 2 == 0) return false;
for(int i = 3; i * i <= n ; i += 2) {
if(n % i == 0)
return false;
}
return true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T18:09:49.183",
"Id": "499620",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/117179/discussion-on-question-by-a-honey-bustard-prime-numbers-that-are-also-a-prime-nu)."
}
] |
[
{
"body": "<ul>\n<li><code>isPrime(9223372036854775783L)</code> incorrectly returns <code>false</code>. Your <code>i * i</code> overflows, better use <code>i <= n / i</code>. Not sure it matters in the context of the problem, though. At least the reverse of <em>this</em> number isn't prime anyway. Division might be slower than multiplication, but might produce <code>n % i</code> as a by-product and a smart compiler might then use that instead of computing it again. So could also be <em>faster</em> overall.</li>\n<li><code>isPrime(1)</code> incorrectly returns <code>true</code>. Doesn't matter in this context, of course, as <code>'1'</code> is a palindrome and thus <code>1</code> doesn't count anyway.</li>\n<li>Beware of reversed numbers overflowing: <code>backwardsPrime(1999999999999999999L, 1999999999999999999L)</code> <em>crashes</em>.</li>\n<li>The line <code>String.valueOf(...</code> should be indented, to make clear it's a continuation of the previous line.</li>\n<li>Testing <code>start > 12</code> seems pointless and counterproductive. It certainly doesn't make the code more concise. I suspect it's intended as a performance optimization, but it only makes very few cases faster, plus they're very fast anyway, so it saves very little very rarely. But it <em>costs</em> extra for all other candidates. Not much, just very little, but for <em>many</em>. So overall it might waste more time than it saves.</li>\n<li>You test <code>isPrime(rev)</code> before <code>isPrime(start)</code> and <code>start != rev</code>. Why? If you test <code>isPrime(start)</code> first and it fails, you don't even have to build <code>rev</code> (let alone test it).</li>\n<li>If you do build <code>rev</code> anyway, it might be beneficial to do the three tests in order of increasing expected time. So <code>start != rev</code> first, as that's very fast. And then test primality of the <em>smaller</em> one of <code>start</code> and <code>rev</code> first. Testing <code>start != rev</code> also quickly rules out most cases ruled out by <code>start > 12</code>, so that's yet another reason to not additionally test <code>start > 12</code>.</li>\n<li>Or test them both <em>in parallel</em>, otherwise you might spend a lot of time to determine that one is a large prime, only to then instantly see that the other one is an even number. Doh! Instead of testing divisors 2, 3, 4, ..., sqrt on one number and then again on the other, testing them in parallel tests the more <em>likely</em> divisors first. Let's say you tested divisors 2 to 96 on the first number already and you didn't test the second number yet. You could test the first number against 97, but that only has a ~1% chance to rule out the current candidate (pair) and go to the next one. Better test the <em>other</em> number against 2, which gives you a 50% chance. And that suboptimality didn't start at 97, it started at 3. So better try both numbers against 2, then both numbers against 3, etc. Until the square root of the smaller one. Then try divisors until the square root of the larger one only against the larger one.</li>\n<li>Instead of building a <code>String</code> and then trimming that, it might be more efficient to remove a final space from the <code>StringBuilder</code>.</li>\n</ul>\n<p>Then again, some of these will make the code longer, so go against your goal of being as concise as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T18:53:31.137",
"Id": "253090",
"ParentId": "253085",
"Score": "20"
}
},
{
"body": "<p><em>One optimisation that could be applied here:</em> keep all the prime pairs that you discovered so far in <code>HashSet</code>.\nLets take a look at example:</p>\n<pre><code>backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] \n</code></pre>\n<p>When we hit number <code>13</code>, we discover that both <code>13</code> and <code>31</code> are prime -> save them in set; <br>\nWhen we hit <code>31</code> we look up this number in our set, and, because it is there, we can just skip this number.</p>\n<p><em>Edit:</em>\nActually, we can go further and store numbers that we discovered as non-prime. In the example above: when we hit 19 (prime) we then check 91, which is not prime. Later on, when we hit 91, we already know that its not prime.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T12:25:54.570",
"Id": "499147",
"Score": "4",
"body": "You could generalize this check simply by testing (with i being the current candidate in the loop) `if (rev >= start && rev <= i) continue` because we have exactly tested these numbers already. And rev <= i includes the test if the number is a palindrome"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T19:48:54.920",
"Id": "253093",
"ParentId": "253085",
"Score": "8"
}
},
{
"body": "<ul>\n<li><p>Iterating over some values in a certain range really asks for a <code>for</code> loop! Although the code is quite simple, it's even easier to understand when the variable referring to the current element is not called <code>start</code>. <code>while (start <= end)</code> is also a bit confusing. So I'd prefer <code>for (long i=start ; i<=end ; i++)</code>.</p>\n</li>\n<li><p>I would also introduce a function <code>rev()</code> to be able to refer to the reverse of <code>i</code> just by <code>rev(i)</code>. This way you can also move the rather clunky expression involving the <code>StringBuilder</code> out of the main method.</p>\n<pre><code> public static Long rev(Long n) {\n StringBuilder b = new StringBuilder(String.valueOf(n));\n return Long.parseLong(b.reverse().toString());\n }\n</code></pre>\n</li>\n<li><p>Finally, the optimizations in <code>isPrime</code> are making the code harder to understand and a bit confusing (shouldn't <code>isPrime(2)</code> return true?). I would only use the square root optimization <code>i * i <= n</code> since it improves efficiency a lot without adding much noise.</p>\n<pre><code> static boolean isPrime(long n) {\n for (int i = 2; i * i <= n ; i++) \n if(n % i == 0)\n return false;\n return true;\n }\n</code></pre>\n</li>\n</ul>\n<p>Given these two helpers you can reduce the main method to this rather minimal version:</p>\n<pre><code>public static String backwardsPrime(long start, long end) {\n StringBuilder sb = new StringBuilder();\n for (long i=start ; i<=end ; i++)\n if (isPrime(i) && isPrime(rev(i)) && i != rev(i)) \n sb.append(i + " "); \n return sb.toString().trim();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T23:26:48.383",
"Id": "253103",
"ParentId": "253085",
"Score": "6"
}
},
{
"body": "<h1>Name Classes properly.</h1>\n<p>What is a "Back Wards Prime"? I have no idea. I can guess what a Backward Prime is; perhaps you need to change the capitalization of the class!</p>\n<p>I'm told that name is dictated by the coding challenge, so you can't change it for your challenge submission; but I'm leaving this comment stand -- the required class name is horrible.</p>\n<h1>Name variables properly.</h1>\n<p>This condition is confusing:</p>\n<pre><code> if ( ... && start != rev)\n</code></pre>\n<p>Is this really testing if the reversed value is different from the starting value? No! You're using the starting value as the loop variable, and continuously incrementing it with <code>start++;</code>. Make a new loop variable, and use a proper loop.</p>\n<pre><code> for(long candidate = start; candidate <= end; candidate++) {\n ...\n } \n</code></pre>\n<h1>Reducing the work</h1>\n<p>You appear to have determined that any single digit prime, when read backwards, will not be different than the original, as well as 10 & 12 not being prime, and 11 not being different when reversed. Therefore, you need only consider values greater than 12. This optimization should be done before the loop starts,\nto avoid the overhead of testing the condition at each iteration.</p>\n<p>You should also notice that 2 is the only even prime number, therefore you need not look at any even value. Instead of moving the start value up by 1, you could skip even values by incrementing by 2.</p>\n<pre><code> if (start < 13)\n start = 13;\n else if (start % 2 == 0)\n start += 1\n\n for(long candidate = start; candidate <= end; candidate += 2) {\n ...\n }\n</code></pre>\n<h1>Avoid creating unnecessary intermediate results</h1>\n<p>Consider:</p>\n<pre><code>new StringBuilder(String.valueOf(start))\n</code></pre>\n<p>You are passing an integer to function which converts it into a string, and then returns that string. How does that function work? You then take that resulting string, and pass it to the constructor of the <code>StringBuilder</code>, to copy into the working area. Do you need that intermediate string?</p>\n<pre><code>new StringBuilder().append(candidate)\n</code></pre>\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/StringBuilder.html#append(long)\" rel=\"nofollow noreferrer\"><code>StringBuilder.append(long)</code></a> function takes a <code>long</code> value, and converts it into string characters directly inside the <code>StringBuilder</code>. This could potentially be faster. It is even 3 characters shorter, while using a longer variable name, so it is certainly more concise!</p>\n<p>Also, consider <code>sb.append(start + " ");</code>. This converts <code>start</code> to a string (again), adds <code>" "</code> to it (internally using another <code>StringBuilder</code>!), and then appends this brand new string to <code>sb</code>. Instead, you could write:</p>\n<pre><code>sb.append(candidate).append(' ');\n</code></pre>\n<p>No intermediate strings needs to be constructed and discarded.</p>\n<h1>Avoid useless work</h1>\n<pre><code> long rev = ...;\n if(start > 12 && isPrime(rev) && isPrime(start) && start != rev) \n ...\n</code></pre>\n<p>If <code>start</code> is not prime, is there any point computing <code>rev</code>?</p>\n<pre><code> for(long candidate = start; candidate <= end; candidate += 2) {\n if (isPrime(candidate)) {\n long rev = ...;\n if (isPrime(rev) && candidate != rev)\n sb.append(candidate).append(' ');\n }\n } \n</code></pre>\n<p>Better. But what about that <code>candidate != rev</code>? That looks like a very fast test, and <code>isPrime(rev)</code> is probably much, much slower.</p>\n<pre><code> for(long candidate = start; candidate <= end; candidate += 2) {\n if (isPrime(candidate)) {\n long rev = ...;\n if (candidate != rev && isPrime(rev))\n sb.append(candidate).append(' ');\n }\n }\n</code></pre>\n<p>But wait! How many times will <code>candidate != rev</code> be false? Very rarely? It may not gain anything, and the change may even slow the program down. Always profile!</p>\n<h1>Performance at the cost of conciseness</h1>\n<p>Constructing a new <code>StringBuilder</code> inside the loop can be a costly operation. You could construct one outside the loop, and use the <code>.setLength(0)</code> method to clear it, for the next iteration:</p>\n<pre><code> StringBuilder temp = new StringBuilder();\n\n for(long candidate = start; candidate <= end; candidate += 2) {\n if (isPrime(candidate)) {\n long rev = Long.parseLong(temp.append(candidate).reverse().toString());\n if (isPrime(rev) && candidate != rev)\n sb.append(candidate).append(' ');\n temp.setLength(0);\n }\n } \n</code></pre>\n<h1>Major optimizations</h1>\n<h2>Reduced search space</h2>\n<p>How many primes in the ranges 200-299, 400-699, and 800-899 will be reversible primes? How about in the ranges 2000-2999, 4000-6999, 8000-8999? How many in the ranges 20000-29999, 40000-69999, 80000-89999? And so on?</p>\n<p>Zero. A reversible prime cannot start with a 2, 4, 5, 6, or 8, because when reversed, the number will be divisible by two or five, and thus won't be prime.</p>\n<p>Implementing this observation in an efficient manner would certainly not make the code concise, but would dramatically speed it up. Left to student.</p>\n<h2>Sieve of Eratosthenes</h2>\n<p>You are potentially doing many, many primality checks using trial division. It may make more sense to use the Sieve of Eratosthenes to generate a <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/BitSet.html\" rel=\"nofollow noreferrer\"><code>BitSet</code></a> of prime flags. Then <code>isPrime(candidate)</code> becomes a simple <span class=\"math-container\">\\$O(1)\\$</span> lookup: <code>prime.get(candidate)</code>.</p>\n<p>Alternately, if maintaining a <code>BitSet</code> of <span class=\"math-container\">\\$10^{\\lceil \\log_{10}{end} \\rceil}\\$</span> bits is too memory intensive, use the sieve to generate the prime numbers up to <span class=\"math-container\">\\$\\sqrt{10^{\\lceil \\log_{10}{end} \\rceil}}\\$</span>, and use trial division with just those prime numbers, to avoid pointless trial division by odd composite numbers (9, 15, 21, 25, 27, 33, ...).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T23:29:57.330",
"Id": "253104",
"ParentId": "253085",
"Score": "27"
}
},
{
"body": "<p>You have skipped checking for divisibility by even numbers. You only need to check for divisibility by prime numbers. Aside from 2 and 3, every prime leaves remainder 1 or 5 on division by 6. (Proof: 0, 2, 3, 4 share a common factor of 2 or 3 with 6.) As a consequence, you can step alternately by 2 and 4. From</p>\n<pre><code>static boolean isPrime(long n) {\n if(n % 2 == 0) return false;\n for(int i = 3; i * i <= n ; i += 2) {\n if(n % i == 0)\n return false;\n }\n return true;\n}\n</code></pre>\n<p>Just check the 6k+1 and 6k+5 cases, eliminating about a third of the comparisons. Also, stop recomputing the termination condition for the loop. This can be replaced with comparison with a constant. See <a href=\"https://stackoverflow.com/questions/15212533/java-square-root-integer-operations-without-casting\">https://stackoverflow.com/questions/15212533/java-square-root-integer-operations-without-casting</a> for a discussion of Java integer square root.</p>\n<pre><code>static boolean isPrime(long n) {\n if( (n % 2 == 0) || (n % 3 == 0) ) return false;\n int i = 5;\n ubound = (int) Math.sqrt(n); \n while( i <= ubound ) {\n if( (n % i == 0) || (n % (i + 2) == 0) )\n return false;\n i += 6;\n }\n return true;\n}\n</code></pre>\n<p>This reduction of cases can be extended. After 2, 3, and 5, every prime leaves remainder 1, 7, 11, 13, 17, 19, 23, or 29 modulo 30. (All other numbers have a common factor with 30.) This reduces the number of modular reductions by 4/5. Although one can keep going, there is seldom any benefit. (For instance, there are 48 remainders to check modulo 2 * 3 * 5 * 7, meaning we have only eliminated 1/7 of iterations of the modulo 30 version.)</p>\n<p>If you have a good <a href=\"https://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"nofollow noreferrer\">integer GCD</a> <a href=\"https://stackoverflow.com/questions/4009198/java-get-greatest-common-divisor\">implementation</a>, you can replace these modular checks with a single GCD. One should profile to find out where the crossover from multiple modular reduction-comparisons is outperformed by a single GCD calculation. Here's a version that is probably not at all faster because the gains don't come until we work with a much larger modulus and its list of candidate primes.</p>\n<pre><code>static boolean isPrime(long n) {\n long modulus = 2*3*5*7*11*13*17*19*23*29; // An excellent place for C++'s static const.\n // modulus^2 > Long.MAX_VALUE\n if( n == 1 ) return false;\n if( (n==2) || (n==3) || (n==5) || (n==7) || (n==11) || (n==13) || (n==17) || (n==19) || (n==23) || (n==29) ) return true;\n if(gcd(modulus, n) > 1) return false;\n for(int i = 31; i <= n/i ; i += 6) {\n if( ( (gcd(modulus, i) == 1) && (n % i == 0) ) \n || ( (gcd(modulus, i+4) == 1) && (n % (i+4) == 0) ) )\n return false;\n }\n return true;\n}\n\nstatic long gcd(long a, long b) {\n if ( b == 0 ) return a;\n return gcd(b, a % b);\n}\n</code></pre>\n<p>I've measured the GCD version to eventually outperform table-based (list, array, association) methods for holding the list of guaranteed-composite remainders. I have never seen the GCD-based version outperform the hand unrolled version. You would like to adjust the <code>modulus</code> based on the intended magnitudes of <code>n</code>s, but that puts you in the slow, table-based modular reductions. So either have a fixed table of reductions or use the GCD method and accept that it is a bit slow for small <code>n</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:32:26.927",
"Id": "499306",
"Score": "0",
"body": "I tried that last code, didn't compile. Had to make `gcd` static and change its `int` to `long`. And then `isPrime(13)` claimed `false`. Also, what's the point of checking `gcd(modulus, i) == 1`? It seems to be an attempt to avoid checking `n % i == 0` when that's pointless due to `i` being composite, but I'd say that that gcd-check costs way more time than it saves. Surely `n % i == 0` is much faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:38:28.070",
"Id": "499307",
"Score": "0",
"body": "@superbrain : `gcd` was copied from cited source withotu change. My code had an omission (stopped typing primes into `modulus` before done). It was fixed before your comment, but I suspect you copied the code in the interim. This would make the code not treat 13 as prime. We check `gcd(modulus, i) = 1` to only test for divisibility by likely primes. As I said in the text, I've only seen the gcd code beat structure-based modular checks, but the problem is not the log-time gcds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:43:36.917",
"Id": "499309",
"Score": "0",
"body": "No, I actually came here because/after you bumped the question with your edit :-). So the *current* version claims 13 isn't prime, and also those other small primes. I just picked 13 because that's the first that's relevant for the OP's use case. Hmm, if the log-time gcds aren't \"the problem\", then what is? Not sure what you mean with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:57:27.887",
"Id": "499310",
"Score": "0",
"body": "@superbrain : Fixed that (missed a line in cut-and-paste). Trying to determine why my code didn't do what you described also detected an error in OP's code: `1` is not prime. \"The problem\" is the runtime, precisely as explained in the text: hand unrolled modular checking always beats GCD eventually beats data structure modular checking. Notice that in the particular case shown, there are > 10^9 remainders to check in the unrolled loop (i.e., there are just over 10^9 numbers up to `modulus` that are relatively prime to `modulus`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T17:32:34.083",
"Id": "499312",
"Score": "0",
"body": "Yeah, the OP's failure at 1 is the second item in my own answer. I didn't mention that it also fails negative numbers because I figured everyone would fix it by checking `n <= 1`, but I guess you proved me wrong :-P. Your updated version still doesn't compile. And after adding the missing `||`, it claims that most numbers under 100 are prime, including 4 and 6. With hand-unrolled, do you mean a big amount of lines like `|| (n % (i+...) == 0)`, one for each hole in the wheel? That looks somewhat reasonable. I still don't think your gcd version shown here makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:15:49.673",
"Id": "499345",
"Score": "0",
"body": "@superbrain : \"the missing ||\"? I see what I suspect you mean right under \"if(\" (else you mean something else). Yes, that is what is meant by hand-unrolled. The gcd version checks for tiny factors, then only trial divides by numbers without tiny factors, slightly less than 15.8% of the numbers less than sqrt(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:18:03.360",
"Id": "499346",
"Score": "0",
"body": "Yes, the missing `||`. In the middle of `(n==19) (n==23)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:23:50.883",
"Id": "499347",
"Score": "0",
"body": "@superbrain : Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:25:53.397",
"Id": "499348",
"Score": "0",
"body": "Still claims that -1, 0, 4 and 6 are prime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:45:43.350",
"Id": "499349",
"Score": "0",
"body": "@superbrain : OP doesn't care about nonnegative numbers and so that must be part of the implicit spec. Likewise that `int i` is sufficient. It reports 4 and 6 false (composite) to me, so I don't know what you're looking at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:54:14.700",
"Id": "499350",
"Score": "0",
"body": "If you get false for 4 and 6 then I'm quite confident you're not testing the code as it is here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T03:03:45.513",
"Id": "499355",
"Score": "0",
"body": "@superbrain :\"1: false\n2: true\n3: true\n4: false\n5: true\n6: false\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T03:44:17.387",
"Id": "499357",
"Score": "0",
"body": "[1: false\n2: true\n3: true\n4: true\n5: true\n6: true](https://preview.tinyurl.com/y2wjhkcz)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T03:57:40.180",
"Id": "499358",
"Score": "0",
"body": "@superbrain : Sorry, can't replicate this deficiency. I'll delete the answer before wasting any more time here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T04:00:04.113",
"Id": "499359",
"Score": "0",
"body": "My guess is your local code doesn't have the factor 19 in the modulus."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T04:00:53.720",
"Id": "499360",
"Score": "0",
"body": "@superbrain : \"long modulus = 2*3*5*7*11*13*17*19*23*29\"..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T04:03:30.127",
"Id": "499361",
"Score": "0",
"body": "Hmm. And you recompiled after including it? That should overflow and thus be a wrong number. What do you get when you print the modulus?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T15:24:31.447",
"Id": "499433",
"Score": "0",
"body": "Btw, after changing the modulus calculation to use `2L` instead of `2` so that it works for me, I benchmarked `isPrime` with the numbers \\$2^{50}\\$ to \\$2^{50}+99\\$. Removing the checks `gcd(modulus, i) == 1` and `gcd(modulus, i+4) == 1` made it about 15 times *faster* (from 5.5 seconds to 0.37 seconds). Sure, you decrease the trial divisions from 100% to 15.8%, but you *increase* the gcd calculations from 0% to 100%. Plus those are slower, so even if it brought trial divisions down to *0%*, it would still make it slower."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T15:43:02.227",
"Id": "253221",
"ParentId": "253085",
"Score": "1"
}
},
{
"body": "<p>Reversing with string operations will be relatively slow. Try something like:</p>\n<pre><code>public static long reverse(long x) {\n long reverseX = 0;\n while (x > 0) {\n reverseX *= 10;\n reverseX += x % 10;\n x /= 10;\n }\n return reverseX;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T13:41:48.007",
"Id": "499424",
"Score": "0",
"body": "How much faster is this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T15:43:45.773",
"Id": "499435",
"Score": "0",
"body": "I haven't measured, but think of all the work that Long.parseLong(new StringBuilder(String.valueOf(start)).reverse().toString()) - creating and destroying objects, writing, reversing, and parsing strings. I'm pretty confident the above will be a lot faster :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-01T16:08:57.857",
"Id": "501279",
"Score": "0",
"body": "How does this code handle numbers that are too long for `long` when reversed? That's obviously a problem with the original code, too, of course..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-01T20:10:35.097",
"Id": "501295",
"Score": "0",
"body": "I think it will do OK, but for bigints I'd use the fact that you're reversing lots of integers contrained in a particular short range to come up with a more efficient algorithm."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:59:55.170",
"Id": "253231",
"ParentId": "253085",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253104",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T16:26:38.803",
"Id": "253085",
"Score": "14",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Prime numbers that are also a prime number when reversed"
}
|
253085
|
<p>I have a complex nested object with an array of objects coming from an API. But the grid tool best works with flattened data. So I came up with this logic that will build the correct object for the grid tool.
To achieve this, it heavily relies on foreach loops and adding object to list object.
Please review the following code snippets. I would be happy for any kind of feedback since this is quite critical a part of my application.</p>
<p><a href="https://dotnetfiddle.net/c28jVw" rel="nofollow noreferrer">Running app</a></p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Processing Data");
List<PanelsMeetingListsViewModel> ListOfPanelsMeeting = new List<PanelsMeetingListsViewModel>();
List<PanelsMeetingViewModel> MeetingVM = new List<PanelsMeetingViewModel>();
MeetingVM.Add(new PanelsMeetingViewModel() { PanelName = "A1", MeetingDate = "Mon" });
MeetingVM.Add(new PanelsMeetingViewModel() { PanelName = "A2", MeetingDate = "Tues" });
MeetingVM.Add(new PanelsMeetingViewModel() { PanelName = "A2", MeetingDate = "Wed" });
ListOfPanelsMeeting.Add(new PanelsMeetingListsViewModel() { Name = "A", TypeId = 1, PanelsMeetingViewModel = MeetingVM});
List<ParentModel> result = new List<ParentModel>();
foreach (var PanelType in ListOfPanelsMeeting)
{
ParentModel PanelsMeetingParent = new ParentModel();
ParentModel ParentGrid = new ParentModel();
PanelsMeetingParent.TitleName = PanelType.Name;
List<GridDetailsModel> GridDetailsListModel = new List<GridDetailsModel>();
GridDetailsModel PanelMeetingGridDetails = new GridDetailsModel();
PanelMeetingGridDetails.GridName = PanelType.TypeId.ToString();
PanelMeetingGridDetails.GridID = PanelType.TypeId;
List<DetailsModel> ListOfGridDetails = new List<DetailsModel>();
foreach (var PanelMeeting in PanelType.PanelsMeetingViewModel)
{
DetailsModel Details = new DetailsModel();
Details.DetailsName = PanelMeeting.PanelName;
Details.DetailsType = PanelMeeting.Type ==null ? "": PanelMeeting.Type;
ListOfGridDetails.Add(Details);
}
PanelMeetingGridDetails.Details = ListOfGridDetails;
GridDetailsListModel.Add(PanelMeetingGridDetails);
PanelsMeetingParent.GridData = GridDetailsListModel;
result.Add(PanelsMeetingParent);
}
foreach (var ParentModel in result)
{
Console.WriteLine(ParentModel.TitleName);
foreach (var GridDetailsModel in ParentModel.GridData)
{
Console.WriteLine(GridDetailsModel.GridName);
foreach (var DetailsModel in GridDetailsModel.Details)
{
Console.WriteLine(DetailsModel.DetailsName);
}
}
}
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>public class PanelsMeetingListsViewModel
{
public string Name { get; set; }
public int TypeId { get; set; }
public List<PanelsMeetingViewModel> PanelsMeetingViewModel { get; set; }
}
public class PanelsMeetingViewModel
{
public string PanelName { get; set; }
public string MeetingDate { get; set; }
public string Type { get; set; }
}
public class ParentModel
{
public string TitleName { get; set; }
public List<GridDetailsModel> GridData { get; set; }
}
public class GridDetailsModel
{
public int GridID { get; set; }
public string GridName { get; set; }
public List<DetailsModel> Details { get; set; }
}
public class DetailsModel
{
public int DetailsID { get; set; }
public string DetailsName { get; set; }
public string DetailsType { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T19:35:10.077",
"Id": "498974",
"Score": "0",
"body": "Your code is broken, it's using 'DetailsModel' in the initialization list for GridDetailsModel. GridDetailsModel doesn't have a property of DetailsModel, and the Details property is of a different type. Additionally, your foreach loop isn't really doing anything since all it's doing is creating locally scoped variables and ending. I'm not sure what you're trying to do here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:13:47.740",
"Id": "498994",
"Score": "0",
"body": "Just to let you know, it would be much easier if you used `AutoMapper` instead! you could use it to map your models or flatten complex objects with ease!."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T00:26:28.577",
"Id": "499002",
"Score": "0",
"body": "Result object is return to the view for the grid control"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T00:27:11.490",
"Id": "499003",
"Score": "0",
"body": "I dont have AutoMapper install is there anything else I can do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T09:33:16.040",
"Id": "499276",
"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": "2020-12-08T09:34:11.233",
"Id": "499277",
"Score": "0",
"body": "\"I dont have AutoMapper install\" https://www.nuget.org/packages/automapper/"
}
] |
[
{
"body": "<p>A few things that have caught my attention:</p>\n<ol>\n<li><p>You write:</p>\n<blockquote>\n<p>But the grid tool best works with flattened data</p>\n</blockquote>\n<p>Since you are turning a two-level hierarchy (<code>PanelsMeetingListsViewModel 1 -- * PanelsMeetingViewModel</code> ) into a three-level hierarchy (<code>ParentModel 1 -- * GridDetailsModel 1 -- * DetailsModel</code>) I fail to see where the flattening is supposedly happening. If anything you nest things even deeper.</p>\n<p>Also the code only ever adds one <code>GridDetailsModel</code> to a <code>ParentModel</code> so it's not clear why there is a list of <code>GridDetailsModel</code></p>\n</li>\n<li><p>Expressions of the form <code>x = A == null ? B : A</code> can be written more concisely using the null-coalescing operator as <code>x = A ?? B</code></p>\n</li>\n<li><p>I would de-compose the big loop into smaller chunks that are each responsible for turning one specific type into another. If we start with the innermost objects we can introduce an extension method that transforms a <code>PanelsMeetingViewModel</code> into a <code>DetailsModel</code>:</p>\n<pre><code>public static DetailsModel ToDetailsModel(this PanelsMeetingViewModel meetingVM)\n{\n return new DetailsModel\n {\n DetailsName = meetingVM.PanelName,\n DetailsType = meetingVM.Type ?? ""\n };\n}\n</code></pre>\n<p>Since the intermediate <code>GridDetailsModel</code> has no correspondent match in the original hierarchy we move one level up to translate a <code>PanelsMeetingListsViewModel</code> into a <code>ParentModel</code>:</p>\n<pre><code>public static ParentModel ToParentModel(this PanelsMeetingListsViewModel listVM)\n{\n var res = new ParentModel() { TitleName = listVM.Name };\n\n var gridData = new GridDetailsModel()\n {\n GridID = listVM.TypeId, \n GridName = listVM.TypeId.ToString(),\n Details = listVM.PanelsMeetingViewModel\n .Select(x => x.ToDetailsModel())\n .ToList()\n };\n res.GridData = new List<GridDetailsModel> { gridData };\n\n return res;\n}\n</code></pre>\n<p>These two extension methods now allow us to write the main loop simply as:</p>\n<pre><code>var result = ListOfPanelsMeeting.Select(x => x.ToParentModel()).ToList();\n</code></pre>\n<p>I've chosen extension methods so that the actual objects themselves don't need to have the knowledge how to transform themselves into other objects yet they allow us to elegantly write the transformation as a nice-to-read LINQ statement.</p>\n<p>Since the methods themselves are smaller only effectively only do one thing they are arguably easier to read and follow. It took me quite some time to dissect the big for-loop which wasn't made any easier by using very verbose type names that all start with the same prefix.</p>\n</li>\n</ol>\n<p>Refactored code can be found here: <a href=\"https://dotnetfiddle.net/Kgyfue\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/Kgyfue</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:23:29.210",
"Id": "499305",
"Score": "0",
"body": "is that the correct Refactored code link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:23:37.413",
"Id": "499319",
"Score": "0",
"body": "@Jefferson - erm well it was meant to be but clearly I don't know how to properly use dotnetfiddle, will correct this shortly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T21:57:25.060",
"Id": "499562",
"Score": "0",
"body": "@Jefferson fiddle code fixed"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:01:22.567",
"Id": "253197",
"ParentId": "253088",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253197",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T17:41:15.353",
"Id": "253088",
"Score": "1",
"Tags": [
"c#",
"array"
],
"Title": "Complex nested object with an array of objects"
}
|
253088
|
<p>I made a calculator in C without #include. Now, I want to make my code shorter and better. But I don't know how.</p>
<p>Here is my code:</p>
<pre><code>int printf(const char *format, ...);
extern int scanf(const char *format, ...);
double pow(double x, double y);
int main()
{
do
{
double num1;
double a, b = 1;
char ch1;
float r;
scanf("%lf", &num1);
printf("\ta - Factorial\n\tb - Continue\n");
scanf(" %c", &ch1);
switch (ch1)
{
case 'a':
for (a = 1; a <= num1; a++)
{
b = b * a;
}
if (b < 500000001 & num1 > 0)
{
printf("%f\n", b);
}
else
{
if (b > 500000000)
{
printf("Number is Big\n");
}
if (num1 < 1)
{
printf("Number is Small\n");
}
}
break;
case 'b':
double num2;
char ch2;
scanf("%lf", &num2);
printf("\ta - Add\n\tb - Substract\n\tc - Multiply\n\td - Divide\n\te - Power\n\tf - Radical\n");
scanf(" %c", &ch2);
switch (ch2)
{
case 'a':
r = num1 + num2;
if (num1 + num2 < 500000001 & num1 + num2 > -500000001 & num1 - num2 < 500000001 & num2 - num1 < 500000001)
{
printf("%lf + %lf = %f\n", num1, num2, r);
}
else if (num1 + num2 > 500000000)
{
printf("Number is Big\n");
}
break;
case 'b':
r = num1 - num2;
if (num1 + num2 < 500000001 & num1 + num2 > -500000001 & num1 - num2 < 500000001 & num2 - num1 < 500000001)
{
printf("%lf - %lf = %f\n", num1, num2, r);
}
else if (num1 + num2 > 500000000)
{
printf("Number is Big\n");
}
break;
case 'c':
r = num1 * num2;
if (num1 * num2 < 500000001 & num1 * num2 > -500000001)
{
printf("%lf * %lf = %f\n", num1, num2, r);
}
else
{
if (num1 * num2 > 500000000)
{
printf("Number is Big\n");
}
if (num1 * num2 < -500000000)
{
printf("Number is Small\n");
}
}
break;
case 'd':
r = num1 / num2;
if (num1 * num2 < 500000001 & num1 * num2 > -500000001 && num2 > 0 | num1 == 0 & num2 != 0)
{
printf("%lf / %lf = %f\n", num1, num2, r);
}
else
{
if (num1 * num2 > 500000000)
{
printf("Number is Big\n");
}
if (num1 * num2 < -500000000)
{
printf("Number is Small\n");
}
if (num1 > 0 & num2 == 0 | num1 == 0 & num2 == 0)
{
printf("Undefined\n");
}
}
break;
case 'e':
r = pow(num1, num2);
if (pow(num1, num2) < 500000001 & pow(num1, num2) > -500000001)
{
printf("%lf ^ %lf = %f\n", num1, num2, r);
}
else
{
if (pow(num1, num2) > 500000000)
{
printf("Number is Big\n");
}
if (pow(num1, num2) > -500000000)
{
printf("Number is Small\n");
}
}
case 'f':
r = pow(num1, 1 / num2);
if (pow(num1, num2) < 500000001 & pow(num1, num2) > -500000001)
{
printf("%lf √ %lf = %f\n", num1, num2, r);
}
else
{
if (pow(num1, num2) > 500000000)
{
printf("Number is Big\n");
}
if (pow(num1, num2) > -500000000)
{
printf("Number is Small\n");
}
}
break;
default:
printf("Invalid\n");
}
break;
}
}
while (1);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T19:11:17.393",
"Id": "498971",
"Score": "7",
"body": "Two questions, if I may: Why avoid `#include` and what is the deal with 500000000 and similar randomly sprinkled throughout the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:58:34.277",
"Id": "499115",
"Score": "1",
"body": "Another question: why is `scanf()` `extern` but `printf()` and `pow()` aren't?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:19:39.417",
"Id": "499595",
"Score": "2",
"body": "Unless this is for some \"code golf\" challenge, then shorter is not necessarily better."
}
] |
[
{
"body": "<blockquote>\n<p>I made a calculator in C without #include. Now, I want to make my code shorter and better.</p>\n</blockquote>\n<p><strong>To make the code <em>better</em></strong></p>\n<p>Focus on clarity and not shortness.</p>\n<p>Use <code>#include<></code>s.</p>\n<p>Check return values from input functions.</p>\n<p>Replace naked magic numbers:</p>\n<pre><code>// if (b > 500000000)\n// if (num1 * num2 < 500000001 \n\n#define LIMIT 500000000\n...\nif (b > LIMIT)\nif (num1 * num2 <= LIMIT /* not quite the same with FP math, but certainly matches intent */\n</code></pre>\n<p>Use <code>&&</code> instead of <code>&</code> for logical tests.</p>\n<p>Remove redundant code</p>\n<pre><code>// r = num1 + num2;\n// if (num1 + num2 < 500000001 & num1 + num2 > -500000001 & num1 - num2 < 500000001 & num2 - num1 < 500000001)\n\nr = num1 + num2;\nif (r <= LIMIT && r >= -LIMIT)\n</code></pre>\n<p>Even better, consider a helper function for the range test.</p>\n<pre><code>r = num1 + num2;\nif (in_range(r))\n</code></pre>\n<p>More informative to print <code>double</code> with <code>"%g"</code> than <code>"%f"</code>.</p>\n<p>Review potential bug in <code>case 'd':</code>. Why <code>if (num1 * num2</code> instead of <code>if (num1 / num2</code>?</p>\n<p>Prevent division by 0.</p>\n<p>Very unclear why code uses <code>float r;</code> with its differing precision and range versus <code>double r;</code> here.</p>\n<hr />\n<p><strong>To make shorter</strong></p>\n<p>Keep in mind shorter is not certainly better.</p>\n<p>Drop <code>extern</code> from <code>extern int scanf(const char *format, ...);</code></p>\n<p>Drop identifiers in prototypes: <code>int scanf(const char *, ...);</code></p>\n<p>Use <code>#include<></code>s, less text in this .c file than adding your own prototypes.</p>\n<p>Replace naked magic numbers.</p>\n<p><code>b = b * a;</code> --> <code>b *= a;</code></p>\n<p>Indent less. Use a tighter format: e.g.:</p>\n<pre><code>// if (num1 < 1)\n// {\n// printf("Number is Small\\n");\n// }\n\nif (num1 < 1) printf("Number is Small\\n");\n</code></pre>\n<p>Replace simply prints</p>\n<pre><code>// printf("Number is Small\\n");\nputs("Number is Small");\n</code></pre>\n<p>Replace <code>do</code></p>\n<pre><code>//do\n// {\n// } while (1);\n\nfor (;;) { }\n</code></pre>\n<p><code>l</code> not needed.</p>\n<pre><code>//printf("%lf - %lf = %f\\n", num1, num2, r);\nprintf("%f - %f = %f\\n", num1, num2, r);\n</code></pre>\n<p>Declare compare types on same line</p>\n<pre><code> // double num1;\n // double a, b = 1;\n double num1, a, b = 1;\n</code></pre>\n<p>I'd re-use code per <code>case</code></p>\n<pre><code>void print_result(double a, double b, double r, char op) {\n if (r >= -LIMIT && r <= LIMIT) {\n printf("%g %c %g = %g\\n", num1, op, num2, r);\n } else {\n printf("Number is Big\\n");\n }\n}\n\n case 'a': print_result(a, b, a+b, '+'); break;\n case 'b': print_result(a, b, a-b, '-'); break;\n case 'c': print_result(a, b, a*b, '*'); break;\n ....\n</code></pre>\n<p>Look to <a href=\"https://codegolf.stackexchange.com\">code golf</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:24:38.237",
"Id": "499614",
"Score": "1",
"body": "Unless I mistake your intent, _Focus on clarity and not shortness_ and _Look to code golf_ seem at odds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:28:43.270",
"Id": "499615",
"Score": "1",
"body": "@Reinderien Yes, parts of OP's 2 goals of \"make the code better\" are at odds with \"To make shorter\". With real world coding, it is striking a balance (mostly in favor of better) than making it shorter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T12:37:24.750",
"Id": "253336",
"ParentId": "253089",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253336",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T18:13:19.577",
"Id": "253089",
"Score": "1",
"Tags": [
"c",
"console",
"io"
],
"Title": "A calculator in C without #include"
}
|
253089
|
<p><strong>Program description:</strong></p>
<blockquote>
<p>You are given a set of two functions: <span class="math-container">$$f=x^3-6x^2+x+5; g=(x-2)^2-6$$</span>
Plot them using Matprolib on a user input segment [a; b].</p>
</blockquote>
<p><strong>My solution:</strong></p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interpolate # for smoothing
def func(x):
return [pow(x, 3) - 6 * pow(x, 2) + x + 5, pow((x-2), 2) - 6]
# plt.plot([1,5, -3, 0.5], [1, 25, 9, 0.5])
# plt.plot(1, 7, "r+")
# plt.plot(-1, 7, "bo")
f = []
f_1 = []
x = []
interval = [int(x) for x in input("Define segment (i.e. a b): ").split(' ')]
for val in range(interval[0], interval[1] + 1):
x.append(val)
f.append(func(val)[0])
f_1.append(func(val)[1])
linear_space = np.linspace(interval[0], interval[1], 300)
a_BSpline = interpolate.make_interp_spline(x, f)
b_BSpline = interpolate.make_interp_spline(x, f_1)
f_new = a_BSpline(linear_space)
f_1_new = b_BSpline(linear_space)
plt.plot(linear_space, f_new, color="#47c984",
linestyle="solid", linewidth=1)
plt.plot(linear_space, f_1_new, color="#fc6703",
linestyle="solid", linewidth=1)
plt.gca().spines["left"].set_position("zero")
plt.gca().spines["bottom"].set_position("zero")
plt.show()
</code></pre>
<p><strong>Input:</strong> <code>-10 10</code></p>
<p><strong>Output:</strong></p>
<p><a href="https://i.stack.imgur.com/jfYMJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jfYMJ.png" alt="1" /></a></p>
<p><strong>Question:</strong>
Is there any way to make this code more concise?</p>
<p>Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T20:50:59.837",
"Id": "498980",
"Score": "1",
"body": "Why do you need `interpolate.make_interp_spline`? If it is required, please update the problem statement and title to include the corresponding logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T21:03:48.113",
"Id": "498983",
"Score": "0",
"body": "@GZ0 when importing interpolate I've intentionally left a comment that it is going to be used for smoothing, thank you for the tip though, I've updated the title accordingly,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:28:32.507",
"Id": "498995",
"Score": "0",
"body": "The logic does not sound right to me. The problem begins with two polynominal functions, which are smooth, rather than piecewise functions which are non-smooth at interval boundaries. Why is it necessary to compute another two sets of smoothing coefficients?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:34:55.863",
"Id": "498997",
"Score": "0",
"body": "@GZ0 interpolation is used for style purposes only, otherwise functions' graphs look rough. Interval boudaries are given on user input, I don't quite get you here. The problem is simple, just plot two functions. I've provided necessary **input** and **output** in my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:37:02.377",
"Id": "498998",
"Score": "0",
"body": "@GZ0 sorry, you are right, I have left the part about custom segment out, I've edited the question"
}
] |
[
{
"body": "<ul>\n<li><p>As I pointed out in the comments, I do not think smoothing is needed when plotting functions that are already smooth, such as polynominals. In those cases, the graphs would look rough only if the points plotted are not dense enough (on the x axis).</p>\n</li>\n<li><p>Since you have already imported and used <code>numpy</code>, it would be better to use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.polyval.html#numpy.polyval\" rel=\"nofollow noreferrer\"><code>numpy.polyval</code></a> for vectorized evaluation of polynominals.</p>\n</li>\n<li><p>Drawing spines at zero would not work well if the input range does not include zero. In that case, the <code>"center"</code> position might be used instead of <code>"zero"</code>. (I will not implement this logic in my code below)</p>\n</li>\n<li><p>The top and right spines should not be shown.</p>\n</li>\n<li><p>Consider using <code>plt.style.use</code> for setting common style information. See <a href=\"https://matplotlib.org/tutorials/introductory/customizing.html#defining-your-own-style\" rel=\"nofollow noreferrer\">here</a> for alternative options for style setting.</p>\n</li>\n<li><p>Avoid constants like <code>"#47c984"</code>. Name them with appropriate constant names for better readability.</p>\n</li>\n<li><p>It is a good practice to comply to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> style when writing Python code. Use an IDE (such as PyCharm) or an online checker (such as <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">this</a>) for automatic PEP 8 violation checking.</p>\n</li>\n<li><p>When running code outside a method / class, it is a good practice to put the code inside a <em>main guard</em>. See <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">here</a> for more explanation.</p>\n</li>\n</ul>\n<p>Here is an improved version:</p>\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\nif __name__ == "__main__":\n # Define constants (color names come from https://colornamer.robertcooper.me/)\n INPUT_MESSAGE = "Lower and upper bounds of x, separated by a space: "\n NUM_POINTS = 300\n PARIS_GREEN = "#47c984"\n BLAZE_ORANGE = "#fc6703"\n\n # Read input\n lb, ub = map(float, input(INPUT_MESSAGE).split())\n\n # Compute coordinates of points to be plotted\n x = np.linspace(lb, ub, NUM_POINTS)\n f_x = np.polyval([1, -6, 1, 5], x)\n g_x = np.square(x - 2) - 6\n\n # Plotting\n plt.style.use({"lines.linestyle": "solid", "lines.linewidth": 1})\n plt.plot(x, f_x, color=PARIS_GREEN)\n plt.plot(x, g_x, color=BLAZE_ORANGE)\n\n # Adjust spines\n spines = plt.gca().spines\n spines["left"].set_position("zero")\n spines["bottom"].set_position("zero")\n spines["right"].set_visible(False)\n spines["top"].set_visible(False)\n\n # Display plot\n plt.show()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:09:41.033",
"Id": "499034",
"Score": "0",
"body": "Thank you for detailed answer. Why don't you consider spines to be const?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:21:36.687",
"Id": "499036",
"Score": "0",
"body": "Using a constant would be the same as using 0. The coordinates have to vary based on the input range. `\"center\"` is just a convenient way to achieve that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:24:20.820",
"Id": "499037",
"Score": "0",
"body": "Makes sense, thank you again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:35:53.127",
"Id": "499038",
"Score": "0",
"body": "By the way, @GZ0, g(x) is not displayed correctly, it's displayed as a plain line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:41:49.650",
"Id": "499039",
"Score": "0",
"body": "Its should be displayed like this: http://yotx.ru/#!1/3_h/ubWwf7Wwf7Rgzhf23/aP9g/2DfT0qt7W/sbe7sru9snu4f7JNo2I2dU8bj6RbjcevyYnd/ax8D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:45:03.797",
"Id": "499049",
"Score": "0",
"body": "`g(x)` is correct. It looks like a line only because of the scale of the y axis. There is a bug in the code and it is fixed in my updated answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T21:50:15.647",
"Id": "499089",
"Score": "0",
"body": "I don't understand your changes, as the plotting didn't change. Values at Y axis were still 10 times larger than those that were on the X axis. I've fixed the problem manually by leaving `plt.ylim(lb, ub)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:54:38.580",
"Id": "499268",
"Score": "0",
"body": "@JoshJohnson The scale of the y axis is determined by `f(x)` in this case since it dominates the y range and shares the axis with `g(x)` in the plot."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T02:45:11.527",
"Id": "253110",
"ParentId": "253094",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253110",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T19:52:06.887",
"Id": "253094",
"Score": "0",
"Tags": [
"python",
"matplotlib"
],
"Title": "Plotting with interpolation using Matplotlib"
}
|
253094
|
<p>I would like to get feedback on my code for Stack implementation written in scala. What can be improved to make it more like scala code. What important helper functions am i missing?</p>
<pre><code>class StackDS[A] {
private var list: List[A] = List[A]()
def push(ele: A) =
list = ele :: list
def pop = {
val pop = list.head
list = list.tail
pop
}
def size: Int = {
list.size
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>layout</strong> - The code is clear and easy to read but I find your use of blank lines a bit excessive.</p>\n<p><strong>braces</strong> - Both the <code>push()</code> and <code>size</code> methods consists of a single line of code so surrounding braces, <code>{..}</code>, are optional. You drop them in one and keep them in the other. Inconsistent.</p>\n<p><strong>types</strong> - The <code>size</code> method declares its return type but <code>push()</code> and <code>pop</code> don't. It's usually a good idea to include them in all but the smallest, simplest method definitions.</p>\n<p><strong>mutation</strong> - The mutating collection, <code>list</code>, is kept local and <code>private</code>, which is good. I might argue that it's better to keep a mutable collection, such as <code>Buffer</code> for example, in a <code>val</code> variable instead of keeping an immutable collection, <code>List</code>, in a <code>var</code> variable.</p>\n<p><strong>mutating methods</strong> - For methods with no arguments that mutate an internal state, such as <code>pop</code> does, the Scala <a href=\"https://docs.scala-lang.org/style/naming-conventions.html#parentheses\" rel=\"nofollow noreferrer\">Style Guide</a> recommends declaring the method with empty parentheses, <code>def pop() ...</code>, as an indicator to the end user.</p>\n<p><strong>safety</strong> - The code will throw an exception if you try to <code>pop</code> an empty stack. That may be as you want it. I prefer methods that return <code>Option[A]</code> instead of throwing.</p>\n<p><strong>convenience</strong> - If I was trying to use <code>StackDS</code> in my code, I'd want to know why stacks have to be created empty. Why can't I create a populated stack? e.g. <code>new StackDS(8,4,11)</code> It would require a small modification to the existing code.</p>\n<p>What I think your code clearly demonstrates is that a simple <code>List</code> does most of what we need from a <code>Stack</code>. So even though the Standard Library includes a full featured <code>Stack</code> implementation, it's not often used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T08:45:03.120",
"Id": "253211",
"ParentId": "253095",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253211",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T19:59:19.223",
"Id": "253095",
"Score": "0",
"Tags": [
"scala"
],
"Title": "Stack Implementation in Scala"
}
|
253095
|
<p>I need to intersect lots of arrays with each other. Those arrays are like:</p>
<pre><code>$a = array(4 => true, 10 => true, 18 => true...);
$b = array(6 => true, 10 => true, 73 => true...);
$c = array(106 => true, 293 => true, 297 => true...);
</code></pre>
<p>In PHP there is a function <code>array_intersect_key</code>, which intersects keys; it works fine but it's not very efficient. There is also another function <code>array_intersect</code>, which intersects values, and is much slower than <code>array_intersect_key</code> because it's <code>O (n^2)</code> instead of <code>O (n)</code> (<code>array_intersect_key</code>).</p>
<p>The problem with <code>array_intersect_key</code> is that it does lots of pre computation before executing the intersection, like ordering the arrays, verifying data types... at <strong>every call</strong> but I don't need that because my arrays are already ordered and contain only numbers. So I came up with this function:</p>
<pre><code>function array_intersect_key_custom($a,$b) {
$intersection = array();
foreach ($a as $chave1 => $valor1) {
if (isset($b[$chave1])) {
$intersection [$chave1] = true;
}
}
return $intersection;
}
</code></pre>
<p>This function runs a little faster than any other alternative I came up, but it's still too slow. Is there any code optimization, mathematical operation, matrix operation... that I can do in order to make this code run faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T04:54:05.137",
"Id": "499025",
"Score": "0",
"body": "Are you able to eliminate whole chunks of elements from your comparison arrays by using array_slice when the max key of your first array is exceeded by the comparison array? Or do the arrays have a good mix of high and low numbers that this will not likely deliver a benefit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T05:01:43.950",
"Id": "499026",
"Score": "0",
"body": "How do we know how to benchmark accurately without knowing how to set the volume and number of arrays?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:54:08.893",
"Id": "499144",
"Score": "0",
"body": "Is this one of those times when you use `yield`?"
}
] |
[
{
"body": "<p>I tried hard but I couldn't find anything faster than the native <code>array_intersect_key</code>. It runs 30-50% faster than your function in my tests. Tried with PHP 7.0 and this array generator for test data:</p>\n<pre><code>function randomArr($size, $max) {\n $res = [];\n for ($i = 0 ; $i<$size; $i++) {\n $r = random_int(1, $max);\n if (!isset($res[$r])) {\n $res[$r] = true;\n }\n else {\n $i = $i-1;\n }\n }\n ksort($res);\n return $res;\n} \n</code></pre>\n<p>Try with 10 Mio entries and <code>$max=100000000</code> and I'd be really surprised if your function was faster. Maybe the densitiy of your arrays plays a role?</p>\n<p>However, I found one little optimization for your function: If you don't require the result to have the form <code>[3 => true, 7 => true, 23 => true, ...]</code>, but you can work with <code>[0 => 3, 1 => 7, 2 => 23, ...]</code> as well, it's a bit faster to just push the intersection keys onto the result array: <code>$intersection[] = $chave1;</code>. But this only saved me at most 10%.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T00:28:01.190",
"Id": "499004",
"Score": "0",
"body": "thank you for your tests (I am running PHP 8 and maybe that's why my custom code runs faster than native `array_intersect_key`). Thank you for your suggestion on the second part of your answer, indeed assigning the results to values instead of keys is faster! Thank you. If no better answer come up in the next days, I will accept yours :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T07:07:39.200",
"Id": "499031",
"Score": "0",
"body": "Thank you for the well considered, if uncommented test data generator."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T22:32:36.243",
"Id": "253100",
"ParentId": "253096",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T20:26:31.927",
"Id": "253096",
"Score": "0",
"Tags": [
"algorithm",
"php"
],
"Title": "Faster way to intersect arrays"
}
|
253096
|
<p>I'm very new to C++ and am trying to code simple programs to test my knowledge on the very basics of this language. Yesterday, I created a very simple calculator script which allows you to add, subtract, multiply, and divide and set of two numbers. While it is still very basic (e.g. only calculating two numbers), I plan on adding more functionality and improving the overall code-base to be not only more efficient, but a more pleasing experience to review. Remember, I am still VERY new to this and need some guidance (for example, I used goto(label) to escape nested loops, there's probably a much better way to do this) on how I can improve this code. Thanks.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#define log(x) std::cout << x;
#define logl(x) std::cout << x << std::endl;
int main() {
int choice, choice2;
float first, second;
logl("-----------------------");
logl("schmobbing's calculator");
logl("-----------------------");
start:
std::cout << "" << std::endl;
logl("Choose one of the following calculation options.");
log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");
std::cin >> choice;
while (true) {
switch (choice) {
case 1:
logl("");
logl("You've chosen addition.");
break;
case 2:
logl("");
logl("You've chosen subtraction.");
break;
case 3:
logl("");
logl("You've chosen multiplication.");
break;
case 4:
logl("");
logl("You've chosen division.");
break;
default:
logl("");
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("You've chosen an invalid operator, please try again.");
log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");
std::cin >> choice;
continue;
} else {
logl("You've chosen an invalid operator, please try again.");
log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");
std::cin >> choice;
continue;
}
}
break;
}
while (true) {
switch (choice) {
case 1:
while (true) {
log("Enter your first number: ");
std::cin >> first;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
while (true) {
log("Enter your second number: ");
std::cin >> second;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
logl("");
std::cout << "The sum of the given numbers is " << first + second << "." << std::endl;
while (true) {
log("Would you like to calculate for a different result? [1] Yes or [2] No: ")
std::cin >> choice2;
switch (choice2) {
case 1:
goto start;
case 2:
goto end;
default:
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid option, please try again.");
break;
} else {
logl("");
logl("You've chosen an invalid option, please try again.");
break;
}
}
}
break;
case 2:
while (true) {
log("Enter your first number: ");
std::cin >> first;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
while (true) {
log("Enter your second number: ");
std::cin >> second;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
logl("");
std::cout << "The difference of the given numbers is " << first - second << "." << std::endl;
while (true) {
log("Would you like to calculate for a different result? [1] Yes or [2] No: ")
std::cin >> choice2;
switch (choice2) {
case 1:
goto start;
case 2:
goto end;
default:
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid option, please try again.");
break;
} else {
logl("");
logl("You've chosen an invalid option, please try again.");
break;
}
}
}
break;
case 3:
while (true) {
log("Enter your first number: ");
std::cin >> first;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
while (true) {
log("Enter your second number: ");
std::cin >> second;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
logl("");
std::cout << "The product of the given numbers is " << first * second << "." << std::endl;
while (true) {
log("Would you like to calculate for a different result? [1] Yes or [2] No: ")
std::cin >> choice2;
switch (choice2) {
case 1:
goto start;
case 2:
goto end;
default:
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid option, please try again.");
break;
} else {
logl("");
logl("You've chosen an invalid option, please try again.");
break;
}
}
}
break;
case 4:
while (true) {
log("Enter your first number: ");
std::cin >> first;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
while (true) {
log("Enter your second number: ");
std::cin >> second;
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid number, please try again.");
continue;
}
break;
}
if (second == 0) {
logl("");
std::cout << "The quotient of the given numbers is undefined." << std::endl;
} else {
logl("");
std::cout << "The quotient of the given numbers is " << first / second << "." << std::endl;
}
while (true) {
log("Would you like to calculate for a different result? [1] Yes or [2] No: ")
std::cin >> choice2;
switch (choice2) {
case 1:
goto start;
case 2:
goto end;
default:
if (!std::cin) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logl("");
logl("You've chosen an invalid option, please try again.");
break;
} else {
logl("");
logl("You've chosen an invalid option, please try again.");
break;
}
}
}
}
end:
break;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T01:12:42.523",
"Id": "499013",
"Score": "1",
"body": "In short words. **DONT** use macros. `goto` should be avoided, but if it is really clear what you are doing, like breaking from multiple nested loops, it is fine. The code is in general hard to read, try to split it into functions. Well, that is the biggest recomendation, learn to use functions. Things like the validation of the user input are copy paste, it is better to abstract it into a function. Just as something tho take into account when you learn abaut them. Give them only one clear purpose, and give then good names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T03:10:09.690",
"Id": "499016",
"Score": "0",
"body": "@Pablochaches \" **DONT** \" use macros? Why? I think I know what you are trying to prove here but **DONT** makes it sound like its extremely bad to have them in your program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T14:39:38.503",
"Id": "499063",
"Score": "0",
"body": "@AryanParekh True, maybe I was a little exagerated. Let me correct. Use macros only when 100% necesary. For things like Logging for debug purposes they are good. Contracts in C++ can only be done, at this time, using macros. But, for things stuff like in this case, if it looks like a function make it a function. If it looks like a constant make it `constexpr`."
}
] |
[
{
"body": "<h1>Macros</h1>\n<p>It is important to be very careful when using macros. A major pitfall of C++ macros is that they ignore namespaces, for example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <map>\n#define map\n\nint main()\n{\n std::map<int, int> my_map;\n}\n</code></pre>\n<p>The macro <code>map</code> will completely ignore the <code>std</code> namespace, this results in <code>std::map_macro_inserted_here<int, int> my_map</code> which will cause a compiler error.</p>\n<p>This is why it is highly recommended to name all macros in UPPER_CASE, this lets you know its a macro and helps avoid naming clashes.</p>\n<p>I don't mind the use of a <code>LOG</code> macro, however it is more often used as a convenience for a more complicated logging system, rather than a single line <code>cout</code>.</p>\n<h1><code>while(true)</code></h1>\n<p>This isn't necessarily bad, and can be useful, however if there is a logical condition that can be used instead of <code>true</code>, you should preference that. It makes the intent clearer, and decreases the chance of getting stuck in the loop due to a logical error. To see this in action, look at the <code>menu_selection</code> function in my example code.</p>\n<h1><code>goto</code> and code reuse</h1>\n<p>In general if you ever feel the need to write a <code>goto</code> statement, you should probably be writing a function instead.</p>\n<p>When reading through your code, if you start to find patterns where you've written the same or even similar code in multiple places, this is also a sign you should be writing a function instead.</p>\n<p>There are a couple of benefits for doing this including:</p>\n<ul>\n<li>clearer/more concise code, making it easier for others to read.</li>\n<li>Better maintainability</li>\n</ul>\n<h1>Example</h1>\n<p>Here is a possible refactor. It is 87 lines long, with whitespace for readability, versus the original 272 with almost no whitespace. It's definitely not perfect, but hopefully demonstrates the idea of code reuse and the benefits it has:</p>\n<p><strong>Update:</strong> Added <code>enum</code>'s to eliminate "magic" numbers as suggested in <a href=\"https://codereview.stackexchange.com/a/253112/128173\">Aryan's</a> answer.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n\nenum Operator { Add = 1, Subtract = 2, Multiply = 3, Divide = 4 };\nenum ExitMenuOption { Continue = 1, Exit = 2 };\n\nint menu_selection(const std::string& menu, int min_option, int max_option);\nfloat get_float_input(const std::string& prompt);\nvoid calculator(Operator operation);\n\nint main()\n{\n const std::string title_bar = "-----------------------\\nschmobbing's calculator\\n-----------------------";\n const std::string operation_menu = "Choose one of the following calculation options.\\n[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ";\n const std::string exit_menu = "Would you like to calculate for a different result? [1] Yes or [2] No: ";\n\n std::cout << title_bar << "\\n";\n\n do\n {\n Operator operation = static_cast<Operator>(menu_selection(operation_menu, 1, 4));\n calculator(operation);\n } while (menu_selection(exit_menu, 1, 2) != ExitMenuOption::Exit);\n}\n\nint menu_selection(const std::string& menu, int min_option, int max_option)\n{\n int choice = -1;\n\n while (choice < min_option || choice > max_option)\n {\n std::cout << menu;\n std::cin >> choice;\n\n if (!std::cin)\n {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n std::cout << "\\nYou've chosen an invalid option, please try again.\\n";\n }\n }\n\n std::cout << "\\n";\n return choice;\n}\n\nfloat get_float_input(const std::string& prompt)\n{\n float input;\n\n do\n {\n std::cout << prompt;\n std::cin >> input;\n\n if (std::cin)\n {\n break;\n }\n else\n {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n std::cout << "\\nYou've chosen an invalid number, please try again.";\n }\n } while (true);\n\n return input;\n}\n\nvoid calculator(Operator operation)\n{\n float first = get_float_input("Enter your first number: ");\n float second = get_float_input("Enter your second number: ");\n\n switch (operation)\n {\n case Operator::Add:\n std::cout << "\\nThe sum of the given numbers is " << first + second << ".\\n";\n break;\n case Operator::Subtract:\n std::cout << "\\nThe difference of the given numbers is " << first - second << ".\\n";\n break;\n case Operator::Multiply:\n std::cout << "\\nThe product of the given numbers is " << first * second << ".\\n";\n break;\n case Operator::Divide:\n if (second == 0)\n std::cout << "\\nThe quotient of the given numbers is undefined.\\n";\n else\n std::cout << "\\nThe quotient of the given numbers is " << first / second << ".\\n";\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:29:55.097",
"Id": "499075",
"Score": "1",
"body": "Your point about macro names is especially important given that the names chosen (`log` and `logl`) are names of standard math functions! There *is* a [`std::log`](https://en.cppreference.com/w/cpp/numeric/math/log) in `<cmath>`, and a full-featured calculator is likely to want it. And in most C++ implementations, `<math.h>` will put those functions in the global namespace. (`logl` is log for long double, `logf` is for float. `log` is overloaded for either or plain double, which is the normal go-to FP type if you don't need to save memory bandwidth / cache footprint with single `float`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T22:16:29.790",
"Id": "499090",
"Score": "0",
"body": "As @Aryan stated, when it comes to enums I don't have to declare the following values as they will increment by one correct? For example, if I create an enumerator for numbers 1-9 like this, \"enum numbers { num1 = 1, num2, num3, num4, etc. }; adding values for num2, num3, num4, and so on is obsolete right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T22:42:56.247",
"Id": "499092",
"Score": "0",
"body": "Also, when it comes to non-void functions, I understand you must return a value. However, why do you return input and choice in two of your functions. I'm really trying to understand the idea behind returning these values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T00:30:46.900",
"Id": "499099",
"Score": "0",
"body": "Correct, it is not required to specifically state each value, however I wanted to make it clear what was happening. Regarding the return values: The functions task is to get the selection from the user, once they've selected a valid option we need to return that value so we can use it in the rest of our program. The variables input and choice are local variables to their respective functions. they only exist within that function. You can research variable scope to find out more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:31:01.897",
"Id": "499109",
"Score": "0",
"body": "@schmobbing yes the values specified are redundant. Some people like to have them, some people don't. It's completely up to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:33:56.490",
"Id": "499110",
"Score": "0",
"body": "@schmobbing kainev has basically created a function that takes a float number from the user while handling the exceptions. This allows him to re-use that function everywhere he would need a floating number as input from the user and he wouldn't have to write the same block of code again."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T02:52:45.773",
"Id": "253111",
"ParentId": "253105",
"Score": "6"
}
},
{
"body": "<p>Welcome to C++!</p>\n<hr />\n<h1>Empty <code>logl("")</code></h1>\n<p>I have seen a few them in your program. But I wasn't 100% sure as to why they keep appearing. My guess is that you are to print a newline. In that case, you should just use something called <a href=\"https://ciphertrick.com/c-beginners-introduction-to-escape-sequences/\" rel=\"noreferrer\">escape sequences</a>. Specifically, <code>'\\n'</code></p>\n<p>Printing <code>'\\n'</code> Will just print a new line onto the terminal</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout << "Hel\\nlo!";\n\n// Output\n\nHel\nlo!\n</code></pre>\n<p>Since you are new, another escape sequence that is often used is the <code>\\t</code>. i.e the TAB. Using this lets you print 8 spaces onto the terminal.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout << "Hel\\tlo!";\n\n// Output\n\nHel lo!\n</code></pre>\n<hr />\n<h2><code>'\\n'</code> vs <code>std::endl</code></h2>\n<p>My previous point must've left you wondering whether you should use <code>'\\n'</code> or <code>std::endl</code>. Since both of them will perform the task, which is to print a new line.</p>\n<p>In this case, you should use <code>'\\n'</code>. <code>'\\n'</code> will be faster to run since <code>std::endl</code> calls <code>std::flush</code>. Basically, <code>std::endl</code> flushes the output stream every time you call it. Which isn't as fast as printing <code>'\\n'</code>.</p>\n<pre><code>std::cout << std::endl;\nstd::cout << '\\n' << std::flush; // equivalent to the top\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><strong>"std::endl" vs "\\n"</strong></a></p>\n<hr />\n<h1>Formatting output</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> logl("-----------------------");\n logl("schmobbing's calculator");\n logl("-----------------------");\n\n start:\n std::cout << "" << std::endl;\n logl("Choose one of the following calculation options.");\n log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");\n</code></pre>\n<p>How about you save this in a variable, and only print that? You can achieve this using the <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"noreferrer\">raw string literal</a>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto Heading = R"(\n -----------------------\n schmobbing's calculator\n -----------------------\n)";\n\nauto Instructions = R"(\nChoose one of the following calculation options.\n[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division\n)";\n\nauto InvaildOperator = R"(\nYou've chosen an invalid operator!\n)"\n\nstd::cout << Heading;\nstd::cout << Instructions;\n</code></pre>\n<p>Here if you want to make tweaks to how the instructions would look, it would be very easy.</p>\n<hr />\n<h1>Repetition</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (!std::cin) {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n logl("You've chosen an invalid operator, please try again.");\n log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");\n std::cin >> choice;\n continue;\n } else {\n logl("You've chosen an invalid operator, please try again.");\n log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");\n std::cin >> choice;\n continue;\n }\n</code></pre>\n<p>You have written something twice here. Both the if statements do the exact same thing, except that the first one does something <strong>extra</strong>. Therefore, keep that extra in the if statement and move everything else out.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (!std::cin) {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n }\n logl("You've chosen an invalid operator, please try again.");\n log("[1] Addition, [2] Subtraction, [3] Multiplication, [4] Division: ");\n std::cin >> choice;\n continue;\n</code></pre>\n<p>+1 if you followed my previous advice.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (!std::cin) {\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n }\n std::cout << InvalidOperator; \n std::cout << Instructions;\n std::cin >> choice;\n continue;\n</code></pre>\n<hr />\n<h1>Use a <code>do-while</code> loop</h1>\n<p>Instead of having <code>goto</code> which many programmers <a href=\"https://stackoverflow.com/questions/46586/goto-still-considered-harmful\">don't like</a>, use a simple do-while loop.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>char PlayAgain;\n\ndo {\n // ...\n // ... \n\n\n // According to user's input, make `PlayAgain` y or n\n} while(std::tolower(PlayAgain) == 'y');\n</code></pre>\n<hr />\n<h1>Functions, please</h1>\n<p>The biggest thing missing in the program are <strong>functions</strong>. You have a huge bunch of code in your <code>main()</code> which is very hard to read. Split your work into different functions. Follow the <a href=\"https://cutt.ly/Jhmae6z\" rel=\"noreferrer\">Single-responsibility principle</a>.</p>\n<p><a href=\"https://codereview.stackexchange.com/a/253111/228914\">Kainev's answer</a> gives a good example of how the program can look with proper structure.</p>\n<hr />\n<h1>No magic numbers</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>case 1:\n\n\ncase 2:\n\n\ncase 3:\n\n\ncase 4:\n\n</code></pre>\n<p>This was the switch statement from your program for the operator selections. Over here 1, 2, 3, and 4 don't necessarily mean anything. They're called <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic numbers</a>. i.e Unnamed numeric constants. A better thing to do would be to use an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\">enum</a></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Operator { Add = 1, Subtract, Multiply, Divide };\n\n\ncase Operator::Add:\n\n\ncase Operator::Subtract:\n\n//...\n</code></pre>\n<p><code>Subtract</code>, <code>Multiply</code>, and <code>Divide</code> are automatically set to 2, 3, and 4 respectively. Now you don't have meaningless numbers pollution your program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T04:21:06.067",
"Id": "253112",
"ParentId": "253105",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T23:36:17.173",
"Id": "253105",
"Score": "2",
"Tags": [
"c++",
"beginner",
"calculator"
],
"Title": "C++ Simple Calculator"
}
|
253105
|
<p>Part of the project I am working on is to maintain the time-of-day, at the sub-millisecond accuracy, while not overwhelming CPU.</p>
<p>The controller has a pretty standard timer, with two registers, <code>COUNTER</code> and <code>PRELOAD</code>. On each system tick <code>COUNTER</code> is decremented; once it reaches 0, the timer posts an interrupt, and reloads <code>COUNTER</code> with the value from <code>PRELOAD</code>.</p>
<p>The value in <code>PRELOAD</code> is calculated off-line, to let the counter expire (and post the interrupt), say, every 100 milliseconds. <code>COUNTER</code> is readable at any time, which allows for a sum-millisecond precision. Yet another timer register, <code>STATUS</code>, has a <code>TIMER_STATUS_IF</code> bit, which determines the state of the timer interrupt.</p>
<p>The timer's registers are memory mapped. Their definitions (along with the definition of <code>timer</code>) come from the manufacturer's <code>#include</code> file. The actual address map is irrelevant.</p>
<p>Here is the code:</p>
<pre><code>static volatile uint32_t ticks;
void ISR timer_isr() {
ticks++;
timer->STATUS &= ~TIMER_STATUS_IF;
}
uint64_t usecs() {
uint32_t counter1 = timer->COUNTER;
uint32_t ticks1 = ticks;
uint32_t counter2 = timer->COUNTER;
uint32_t ticks2 = ticks;
if (timer->STATUS & TIMER_STATUS_IF) {
// The interrupt has been asserted, and the counter has been reloaded,
// but the ISR has not been run (we are called from the higher priority
// ISR). Increment ticks manually.
assert(ticks1 == ticks2);
ticks2 += 1;
} else if (counter1 > counter2) {
// We know that between reading counters the reload did not happen.
// Trust the first reading of ticks.
ticks2 = ticks1;
}
else { // Nothing happens here. It is purely an explanation.
// We know that between reading counters the reload did happen.
// Trust the second reading of ticks.
}
return ticks2 * US_PER_TICK + (timer->PRELOAD - counter2) / CLOCKS_PER_USEC;
}
</code></pre>
<p>This works fine unless some high priority ISR takes more than 100 ms to complete. I am fine with it. If any ISR takes that long, it is much more serious design problem.</p>
<p><strong>What I don't like here.</strong></p>
<p>I am a strong advocate of a comment-less style. To quote myself, "an explanatory comment means that you fail to express the intention in the code". However, I feel I need a large explanatory comment. Any hint on how to remove it is much appreciated.</p>
<p><strong>TL;DR</strong></p>
<p>For a bit of context, the code I inherited (not for a review)</p>
<blockquote>
<pre><code>uint64_t usecs() {
uint32_t counter = timer->COUNTER;
uint32_t ticks = ticks;
return ticks * US_PER_TICK + (timer->PRELOAD - counter) / CLOCKS_PER_USEC;
}
</code></pre>
</blockquote>
<p>once in a while exhibited time travel for about 100 ms into the future.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T09:32:46.757",
"Id": "499043",
"Score": "0",
"body": "Which MCU exactly are you writing this for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T19:59:46.040",
"Id": "499084",
"Score": "0",
"body": "@G.Sliepen Cortex M4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:11:02.887",
"Id": "499085",
"Score": "0",
"body": "That's just the CPU core, it doesn't say much about how the timer/counters work and how they are hooked up to the interrupts. Is it an STM32?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:14:20.167",
"Id": "499086",
"Score": "0",
"body": "@G.Sliepen Oh, got you. It is nxp's s32k."
}
] |
[
{
"body": "<h1>Carefully examine all possible interactions between interrupts</h1>\n<p>There are many possible ways interrupts can happen, you should take some time and carefully try to map them out. I think you missed a few corner cases in case where <code>usecs()</code> is called from a higher priority context than <code>timer_isr()</code>. First, given your description, the function <code>usecs()</code> can be called either from a low or a high priority context:</p>\n<h2>Low priority call to <code>usecs()</code></h2>\n<p>It's either not called from an interrupt context, or from an interrupt with a lower priority than the timer overflow interrupt. In this context, <code>usecs()</code> might be interrupted by <code>timer_isr()</code> at any point during its execution. So look at all the possible places where the <code>timer_isr()</code> could fire:</p>\n<pre><code>// 1\nuint32_t counter1 = timer->COUNTER;\n// 2\nuint32_t ticks1 = ticks;\n// 3\nuint32_t counter2 = timer->COUNTER;\n// 4\nuint32_t ticks2 = ticks;\n// 5\n</code></pre>\n<p>Before I am going to look at all 5 possibilities, I'm also going to make some assumptions:</p>\n<ul>\n<li>Any higher interrupts together will never take more than 100 milliseconds. This should be reasonable, and avoids us having to worry about the timer overflowing twice while <code>usecs()</code> runs.</li>\n<li>The <code>COUNTER</code> effectively gets reset to <code>PRELOAD</code> by the hardware <em>during</em> the interrupt to <code>timer_isr()</code>. You must <em>verify</em> this by reading the documentation of the MCU.</li>\n</ul>\n<p>So now for the five possibilities of where the timer reset happens, and after the four statements have run the results will be:</p>\n<ol>\n<li><code>ticks1 == ticks2</code> and <code>counter1 > counter2</code> (trivial case)</li>\n<li><code>ticks1 == ticks2</code> and <code>counter1 < counter2</code> (only counter2 is valid)</li>\n<li><code>ticks1 != ticks2</code> and <code>counter1 < counter2</code> (either ticks1+counter1 or ticks2+counter2 are valid)</li>\n<li><code>ticks1 != ticks2</code> and <code>counter1 > counter2</code> (only ticks1 is valid)</li>\n<li><code>ticks1 == ticks2</code> and <code>counter1 > counter2</code> (trivial case)</li>\n</ol>\n<p>It looks like your code handles all these cases correctly.</p>\n<h2>High priority calls to <code>usecs()</code></h2>\n<p>Here we can never be that <code>timer_isr()</code> interrupts <code>usecs()</code>, but it could be that <code>usecs()</code> interrupted <code>timer_isr()</code>. Let's look at those cases separately.</p>\n<h3><code>usecs()</code> did not interrupt <code>timer_isr()</code></h3>\n<p>The question is now, what happens when the timer resets? Again, check the documentation of your MCU, but I am assuming that <code>COUNTER</code> will be reset to <code>PRELOAD</code>, just that <code>timer_isr()</code> doesn't fire because we are already in a higher level interrupt. So now <code>ticks1 == ticks2</code> will always be true. We still have the five positions where the reset can happen:</p>\n<ol>\n<li><code>counter1 > counter2</code> (ticks1 and ticks2 are behind)</li>\n<li><code>counter1 < counter2</code> (ticks2 is behind)</li>\n<li><code>counter1 < counter2</code> (ticks2 is behind)</li>\n<li><code>counter1 > counter2</code> (everything is valid)</li>\n<li><code>counter1 > counter2</code> (everything is valid)</li>\n</ol>\n<p>Oops, you cannot distinguish case 1 from cases 4 and 5 just by looking at the counter values. The TIMER_STATUS_IF flag also doesn't help in distinguishing what happened, at least not if you check it <em>after</em> reading the counters. So you have to read the counter again:</p>\n<pre><code>if (timer->STATUS & TIMER_STATUS_IF) {\n // The counters wrapped somewhere prior to exactly this if-statement.\n // We assume it won't wrap again from here, because all interrupts will\n // be handled in less than 100 ms.\n counter2 = timer->COUNTER;\n ticks2 += 1;\n} ...\n</code></pre>\n<h3><code>usecs()</code> did interrupt <code>timer_isr()</code></h3>\n<p>In a way this looks simpler, because we know the counter reset just before <code>usecs()</code> was called, so we don't have to worry about the counters being able to reset during <code>usecs()</code>. However, now we have to worry about where exactly in <code>timer_isr()</code> we had the higher level interrupt. Again there are several possibilities:</p>\n<pre><code>// 1\nticks++;\n// 2\ntimer->STATUS &= ~TIMER_STATUS_IF;\n// 3\n</code></pre>\n<p>Oops, there is no way to distinguish case 1 from case 2 from <code>usecs()</code>! Reordering statements won't help here, there will always be a point right before and one right after the increment. The only way I see is to ensure both <code>ticks++</code> and <code>timer->STATUS &= ~TIMER_STATUS_IF</code> are executed atomically. Perhaps this can be done by having <code>timer_isr()</code> disable higher level interrupts:</p>\n<pre><code>cli(); // disable all interrupts\nticks++;\ntimer->STATUS &= ~TIMER_STATUS_IF;\nsei(); // reenable interrupts\n</code></pre>\n<p>This should make <code>usecs()</code> work correctly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T10:42:33.710",
"Id": "253120",
"ParentId": "253113",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253120",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T05:39:37.017",
"Id": "253113",
"Score": "3",
"Tags": [
"c",
"multithreading",
"embedded"
],
"Title": "Avoiding race in a sub-millisecond TOD timer"
}
|
253113
|
<p><a href="https://codeforces.com/group/Ir5CI6f3FD/contest/276073/problem/Q" rel="nofollow noreferrer">Link to the Problem</a></p>
<p>Here is my code to compute the length of the longest common subsequence of two integer arrays <code>arr[]</code> and <code>brr[]</code>:
<br/></p>
<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
using namespace std;
//Dynamic programm solution
int mem[10004][10004];//mem[i][j] stores length of the longest common subsequence, up to index i of arr and index j of brr
vector<int> arr,brr;
int lcs(int i,int j){
if (i<0||j<0) return 0;
if (mem[i][j]!=-1) return mem[i][j];// if already computed, return mem[i][j]
else {
int tmp = 0;
tmp = max(lcs(i-1,j),lcs(i,j-1));
if (arr[i]==brr[j]) tmp = max(tmp,lcs(i-1,j-1)+1);
mem[i][j] = tmp;
}
return mem[i][j];
}
main(){
int n,m;// n,m are the length of the first and second array
memset(mem,-1,sizeof(mem));
cin >> n >> m;
arr.resize(n+1);brr.resize(m+1);
for (int i = 0;i<n;++i){
cin >> arr[i];
}
for (int i = 0;i<m;++i){
cin >> brr[i];
}
//calculate length of longest common subsequence of two array arr and brr
cout << lcs(n-1,m-1);
}
</code></pre>
<p>The time complexity of the above approach is O(m*n). The running time of the program exceeds 1000ms when m and n are both as large as 10000. How can I improve the above program's speed to solve this problem in the case m = n = 10000 under 1000ms ? (I was trying to solve this problem in Codeforces, and there's a test case where m = n = 10000 and my program failed to solve it under 1000ms)<br/></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T06:08:19.570",
"Id": "499028",
"Score": "3",
"body": "[edit] your question and add a link to the programming challenge"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T08:46:24.653",
"Id": "499040",
"Score": "1",
"body": "A naive comment maybe: `if ((arr[i]==brr[j])`, then is not the solution always `tmp = max(tmp,lcs(i-1,j-1)+1);` ? If it is true, then we can avoid calculating `lcs(i-1,j),lcs(i,j-1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T09:38:02.790",
"Id": "499044",
"Score": "0",
"body": "@Damien I edited the code, but the program still exceeds 1000ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T09:40:46.893",
"Id": "499045",
"Score": "2",
"body": "@WhiteTiger Please don't make changes to your code after you get a suggestion. It isn't allowed."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T05:41:38.900",
"Id": "253114",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"dynamic-programming"
],
"Title": "C++ - Longest Common Subsequence"
}
|
253114
|
<p>I made a calculator in JavaScript. Now, I want to rename my functions, variables, and input names. But I don't know how.</p>
<p>Here is my codes:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Calc() {
var num1 = +txt1.value;
var num2 = +txt2.value;
var ch = +optxt.value;
var result;
if (ch == 1) {
result = num1 + num2;
}
if (ch == 2) {
result = num1 - num2;
}
if (ch == 3) {
result = num1 * num2;
}
if (ch == 4) {
result = num1 / num2;
}
if (ch == 5) {
result = Math.pow(num1, num2);
}
if (ch == 6) {
result = Math.pow(num1, 1 / num2);
}
p.innerHTML = result;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="calculator-1.js"></script>
<input type="text" id="txt1" />
<br>
<input type="text" id="optxt" />
<br>
<input type="text" id="txt2" />
<br>
<button onclick="Calc()">Calculate</button>
<p id="p"></p></code></pre>
</div>
</div>
</p>
<p>Note: I <strong>just</strong> want to change names.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:31:31.237",
"Id": "499048",
"Score": "0",
"body": "how does it work to access the DOM elements directly by there ids. Is this a special feature of Stackoverflow Code Snippets?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T14:12:00.147",
"Id": "499062",
"Score": "0",
"body": "See https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables#:~:text=The%20value%20of%20the%20name,accessible%20as%20a%20global%20variable. (it works, but it's bad practice)"
}
] |
[
{
"body": "<p>You could name your input elements properly: <code>operand1</code> instead of <code>txt1</code> or at least <code>txtOperand1</code> if you like to prefix elements with their type.</p>\n<p>If you really want to use numbers for the operators, at least use named constants: <code>const OP_ADD = 1;</code>, <code>const OP_SUBTRACT = 2;</code> and so on...</p>\n<p>If you want to take advantage of the fact that Javascripts is a function language you could first map your input value for the operator to an <code>operation</code> function and the apply the input values to the function:</p>\n<pre><code>function getOperation(code) {\n switch (code) {\n case OP_ADD: \n return (a, b) => a + b;\n case OP_SUBTRACT:\n return (a, b) => a - b;\n // ...\n }\n}\n</code></pre>\n<p>Finally you can then apply the operation like this:</p>\n<pre><code>let operation = getOperation(optxt.value); \nlet result = operation(txtOperand1.value, txtOperand2.value);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T12:56:28.573",
"Id": "499055",
"Score": "0",
"body": "I don't want to change my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T13:22:00.320",
"Id": "499057",
"Score": "1",
"body": "@Arian What do you mean you don't want to change your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T16:52:09.853",
"Id": "499069",
"Score": "1",
"body": "Oops, pinged wrong person, you both start with A. @Arian The whole point of Code Review is to improve one's code, which can only be done by changing it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:29:23.333",
"Id": "499074",
"Score": "0",
"body": "@CertainPerformance I **just** want to change names."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:47:25.450",
"Id": "253124",
"ParentId": "253115",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T05:55:05.123",
"Id": "253115",
"Score": "-3",
"Tags": [
"javascript",
"html"
],
"Title": "A calculator in JavaScript"
}
|
253115
|
<p>I made a statically allocated memory pool for embedded systems. I think it needs a little work but it works fine so far.</p>
<p>How it works: An array of size <code>MEMORY_POOL_SIZE</code> is first reserved in memory and that's actually the space and the whole program uses to get memory from.<br />
The number of allocations that can happen at the same time are limited and defined from <code>MEMORY_POOLS_NUM</code>. The current implementation below uses <code>16384 bytes</code> of memory space and <code>64</code> concurrent memory allocations. The numbers don't have to be power of 2.</p>
<p>When the program wants to allocate some memory, it access the memory allocator which passes a pointer back to the program.</p>
<p>It is thread safe, which means the program is not interrupted during the allocation or de-allocation of the memory pool.</p>
<p>When the size an allocated space needs to change (realloc) everything in memory has to move. When the pointers of the <code>mem_allocator</code> point to a different address, the program will break and for this reason the pointers that are passed back to the program point to the address of the
<code>start_p</code>.</p>
<p><strong>-- mem_pool.h --</strong></p>
<pre><code>#ifndef MEM_POOL_H
#define MEM_POOL_H
#include <inttypes.h>
/**
* \brief Allocates a chunk from the memory pool
* \param buf Must be a double NULL pointer.
* \param size Must be greater than zero.
*/
void mem_pool_alloc(uint8_t ** buf, uint16_t size);
/**
* \brief Re-allocates a chunk from the memory pool.
* The new chunk is always bigger.
* \param buf Must be a double NULL pointer.
* \param size Must be greater than zero.
*/
void mem_pool_realloc(uint8_t ** buf, uint16_t new_size);
/**
* \brief Release a chunk from the memory pool.
* \param buf Must be a double pointer.
*/
void mem_pool_free(uint8_t ** buf);
#endif
</code></pre>
<p><strong>-- mem_pool.c --</strong></p>
<pre><code>#include "mem_pool.h"
#include <stddef.h>
#include <stdbool.h>
#define MEMORY_POOL_SIZE (16384) /** The size in bytes of the statically allocated memory */
#define MEMORY_POOLS_NUM (64) /** The number of elements of the memory allocator */
typedef struct
{
bool locked; /** Shows whether the element of the memory allocator is reserved or not */
uint8_t* start_p; /** The pointer to the first element in the statically allocated memory */
uint16_t size; /** The total size of the chunk that is allocated from the memory */
}MemPoolAllocator;
/**
* The statically allocated array in memory.
*/
static volatile uint8_t memory_pool[MEMORY_POOL_SIZE];
/**
* Memory allocator struct. It is used to allocate memory in the pool.
*/
static volatile MemPoolAllocator mem_allocator[MEMORY_POOLS_NUM];
void mem_pool_alloc(uint8_t ** buf, uint16_t size)
{
ASSERT(buf != NULL);
ASSERT(*buf == NULL);
ASSERT(size > 0);
__disable_irq();
for (uint8_t i = 0; i < MEMORY_POOLS_NUM; i++) {
if (mem_allocator[i].locked == false) {
mem_allocator[i].locked = true;
// Find the first unlocked element.
if (i > 0) {
mem_allocator[i].start_p = mem_allocator[i - 1].start_p + mem_allocator[i - 1].size;
}
else {
// If the element is the first one the pointer of the chunk points to the first byte of
// the statically allocated memory.
mem_allocator[i].start_p = memory_pool;
}
mem_allocator[i].size = size;
// The double pointer points to the address of the pointer.
// This allows the pointers that the program use to be updated in case
// a re-allocation is needed.
*buf = &mem_allocator[i].start_p;
__enable_irq();
return;
}
}
*buf = NULL;
__enable_irq();
}
void mem_pool_realloc(uint8_t ** buf, uint16_t new_size)
{
ASSERT(buf != NULL);
ASSERT(new_size > 0);
__disable_irq();
if (*buf == NULL) {
mem_pool_alloc(buf, new_size);
}
else {
for (uint8_t id = 0; id < MEMORY_POOLS_NUM; id++) {
if (*buf == &mem_allocator[id].start_p) {
// The current element must be locked.
ASSERT(mem_allocator[id].locked == true);
// Starting from the end, all elements of the memory pool and
// the memory allocator must move as many as the new_size variable.
for (uint8_t x = MEMORY_POOLS_NUM - 1; x > id; x--) {
if (mem_allocator[x].locked == true) {
uint16_t temp_size = mem_allocator[x].size;
uint16_t offset_size = new_size - mem_allocator[x].size;
for (uint16_t a = mem_allocator[x].size; a > 0; a--) {
*(mem_allocator[x].start_p + a + offset_size - 1) = *(mem_allocator[x].start_p + a - 1);
*(mem_allocator[x].start_p + a - 1) = 0; // Initialize the new space to 0.
}
mem_allocator[x].start_p += offset_size;
mem_allocator[x].size = new_size;
}
}
break;
}
}
}
__enable_irq();
}
void mem_pool_free(uint8_t ** buf)
{
if ((*buf == NULL) || (buf == NULL)) {
return;
}
__disable_irq();
uint8_t id = 0;
for (id = 0; id < MEMORY_POOLS_NUM; id++) {
if (*buf == &mem_allocator[id].start_p) {
ASSERT(mem_allocator[id].locked == true);
mem_allocator[id].locked = false;
*buf = NULL;
for (uint16_t i = 0; i < mem_allocator[id].size; i++) {
mem_allocator[id].start_p[i] = 0;
}
mem_allocator[id].start_p = NULL;
mem_allocator[id].size = 0;
break;
}
}
__enable_irq();
}
</code></pre>
|
[] |
[
{
"body": "<h1>Consider using <code>void</code> pointers</h1>\n<p>Prefer using <code>void</code> pointers in your memory pool API, as this allows the caller to pass in any type of pointer without having to explicitly cast them. So for example:</p>\n<pre><code>void mem_pool_alloc(void **buf, uint16_t size);\n</code></pre>\n<h1>Naming things</h1>\n<p>There are several ways the names of constants, variables and functions can be improved. First: avoid repeating <code>mem</code> and <code>memory</code> in private variables and functions inside <code>mem_pool.c</code>. It is already clear from the context that everything has to do with memory pools. So for example:</p>\n<pre><code>#define POOL_SIZE (16384)\n...\nstatic uint8_t pool[POOL_SIZE];\n</code></pre>\n<p>Futhermore, <code>MemPoolAllocator</code> is a misnomer, this <code>struct</code> just represents a single allocation from the memory pool. Also, there is only one pool, so <code>NUM_POOLS</code> is wrong as well. I would instead write:</p>\n<pre><code>#define NUM_ALLOCATIONS (64)\n\ntypedef struct {\n ...\n} Allocation;\n\nstatic Allocation allocations[NUM_ALLOCATIONS];\n</code></pre>\n<h1>Avoid unnecessary use of <code>volatile</code></h1>\n<p>You should not make things <code>volatile</code> unnecessarily. The <code>volatile</code> keyword doesn't make access atomic, and while it prevents the compiler from reordering access to <code>volatile</code> variables with respect to other <code>volatile</code> variables, it doesn't prevent the CPU itself from reordering access.</p>\n<p>I would check if <code>__disable_irq()</code> and <code>__enable_irq()</code> themselves act as memory barriers. If so, that will be enough to guarantee that everything stays consistent. Then the compiler is free to reorder access to the variables between those two statements as it sees fit, resulting in better optimized code.</p>\n<h1>Unnecessary member variable <code>locked</code></h1>\n<p>I see that you do not allow allocations of zero length. This means you can use the member variable <code>size</code> to check whether an allocation is in use or not, and you don't need <code>locked</code> anymore:</p>\n<pre><code>void *mem_pool_alloc(uint16_t size)\n{\n ...\n for (uint8_t i = 0; i < NUM_ALLOCATIONS; i++) {\n if (allocations[i].size == 0) {\n // This allocation is free\n ...\n</code></pre>\n<h1>Check if there is enough space in the pool</h1>\n<p>Your allocator does not properly check if there is enough space for an allocation. First, it allows allocations larger than the size of the whole pool. But second, even if there is enough free space in the pool as a whole, it doesn't check whether there is enough space at the location it has chosen. Consider this order of events:</p>\n<pre><code>void *p1, *p2, *p3;\nmem_pool_alloc(&p1, 10);\nmem_pool_alloc(&p2, 10);\nmem_pool_alloc(&p3, 10);\nmem_pool_free(&p2);\nmem_pool_alloc(&p2, 20); // will overwrite p3\n</code></pre>\n<p>What you should do is find a free spot that is large enough to hold the new allocation. And due to fragmentation there might not be, unless you move allocations here as well.</p>\n<h1>Your reallocation algorithm doesn't move anything before the allocation that is resized</h1>\n<p>When moving existing allocations to make space for the new size of an allocation during <code>mem_pool_realloc()</code>, you only consider moving allocations after the one being resized. But what if it's already the last one? You should handle moving allocations both before and after: move allocations before towards the start of the pool, and allocations after towards the end of the pool, to make enough space in the middle of the pool.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T12:04:55.627",
"Id": "499051",
"Score": "0",
"body": "I'm not sure I can make the interface look like the standard library. I'd still need to return a pointer to a pointer. Because I want to pass the address of `&mem_allocator[i].start_p` and not its value. So, I'd have to dereference the pointer twice in order to access the pool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T13:53:27.577",
"Id": "499060",
"Score": "1",
"body": "Why would you want the caller to have a pointer to a pointer? You can make the code work without needing pointers to pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T15:18:10.093",
"Id": "499064",
"Score": "0",
"body": "The caller needs a pointer that points to `start_p` not to the `pool`. I did that because when you want to reallocate more space for a chunk. Everything else has to move. If you move the data of the memory the pointers of the caller would point to incorrect address. But if the caller has a pointer that points to a pointer, it will get automatically updated after the reallocation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:32:15.827",
"Id": "499088",
"Score": "1",
"body": "Ah ok, now I see. I'll update my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:14:14.343",
"Id": "499178",
"Score": "0",
"body": "I'll have to post a second revision of my code because there are many mistakes on this one as you also have pointed out. But I want to comment also that in fact we need a triple pointer (pointer to pointer to pointer) because we want to pass a pointer to apointer, not just a pointer, so we can dereference the pointer twice and access the data of the pool. Thank you very much for your help and your time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:27:20.610",
"Id": "499185",
"Score": "0",
"body": "You don't need the triple pointer function argument if instead you `return` double pointers. Unless of course you want to be a [three star programmer](https://wiki.c2.com/?ThreeStarProgrammer) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:32:28.800",
"Id": "499187",
"Score": "0",
"body": "That was hilarious, no I don't. I'll try to follow your advice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T11:58:53.657",
"Id": "499292",
"Score": "0",
"body": "\"avoid repeating mem and memory in private variables and functions inside mem_pool.c\" I disagree, to use consistent naming with prefixes even inside private namespaces makes it much easier to debug the program and read map files etc. Imagine if the caller has a variable `pool` which you are watching, then you step into a private function that also happens to have a `pool`. Now you have 2 watches with the same name and only the compiler can keep track of which is which through internal name mangling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T17:47:46.700",
"Id": "499314",
"Score": "0",
"body": "@Lundin I think this is a matter of whether your tools are good enough. At least gdb has no problem setting watchpoints on specific variables, even if they have the same name. I also don't need to use mangled names. Can you give a concrete example of where using the same name might make this a problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:42:21.127",
"Id": "499381",
"Score": "0",
"body": "All debuggers can handle 2 variables with the same name just fine, that's not the problem at all. *The problem is that the programmer trouble-shooting the code is staring at 2 watched variables with the same identical name, doing different things.*"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:29:06.780",
"Id": "253122",
"ParentId": "253119",
"Score": "3"
}
},
{
"body": "<p>Design:</p>\n<ul>\n<li><p>Consider making an API that enforces the caller to allocate aligned chunks. This will make the code much more robust on 32 bit systems. You can still let them state the desired size in bytes, but do the actual allocation on aligned chunks (32 bits etc). It's strange that your code does not address alignment at all(?) as far as I can see.</p>\n</li>\n<li><p>Avoid asserts inside library code. They don't add much but slow everything down. Besides that, the proper way to deal with "dumb" errors such as null pointers or other nonsense parameters is to enforce the error checking on the caller through documentation. It's not the job of your function to chase down application layer bugs in the calling application.</p>\n<p>If you need actual error handling rather than "halt and catch fire like a PC", then return an <code>enum</code> error code from the functions and let the caller deal with the errors.</p>\n</li>\n<li><p>Hitting the global interrupt mask is questionable practice in general. This must be documented too. Besides, your library has no use case that requires the library itself to prevent race conditions with interrupts. So in the normal use-case, all this achieves is to screw up the real-time performance of any program using your library, for no reason what so ever. Not sexy at all. In this case "thread safety" is not a feature, but a burden. The user could as well have shut down the relevant interrupts in the caller code.</p>\n</li>\n<li><p><code>volatile</code> achieves nothing in this case, unless you somehow expect the user to DMA data straight into the memory pool. In which case you should design a special version of the memory pool for that specific purpose.</p>\n</li>\n</ul>\n<p>Style:</p>\n<ul>\n<li>Place all library includes in the header. This documents to the user who reads your header which library dependencies it got.</li>\n<li>I'd use <code>stdint.h</code> over <code>inttypes.h</code> because the former is mandatory for all C systems, including embedded ("freestanding") systems. <code>inttypes.h</code> is not necessarily supported by embedded compilers and apart from including <code>stdint.h</code>, it only contains misc <code>printf</code> formatting goo that you don't need anyway.</li>\n<li>Parenthesis around integer constants in macros <code>(16384)</code> is superfluous and only adds clutter. You only need to use parenthesis when dealing with function-like macros.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T17:37:04.007",
"Id": "499313",
"Score": "0",
"body": "Thanks for your entry. Very helpful! But I'm not sure I'd agree with the `all library includes in the header`. I somehow learned to avoid putting header in header as much as possible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:47:27.157",
"Id": "499383",
"Score": "0",
"body": "@MrBit \"I somehow learned to avoid putting header in header\" By whom? Why? Any rationale or just subjective opinion? The reason for not doing that is: \"missing definition, linker error 1, terminating\". Ever gotten a crap message like that from a linker when you imported a library written by someone else? The cause here is some include path issue in the project or IDE. But how am I supposed to even know what's missing? What if I don't have access to the .c code? I will have access to the .h file. And if it's written there what files it expect, I can fix the problem. If not, then I can't."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T12:28:23.453",
"Id": "253214",
"ParentId": "253119",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T10:24:28.450",
"Id": "253119",
"Score": "2",
"Tags": [
"c",
"embedded"
],
"Title": "Statically allocated memory pool in C for embedded systems"
}
|
253119
|
<p>I'm new to PowerShell (started yesterday) and was wondering if there is a way of exporting Shell bags, Jump lists, and LNK files from the Reg to a local computer's desktop using PowerShell? I have tried a few things and can export them as CSVs... but I'm not sure if that's going to have any forensic merit (dabbling in forensics for some fun but only just started).</p>
<p>Here is my code below for how I am doing it... but I was wondering if there is a more elegant or 'proper' way of doing it? I haven't used variables or anything yet because I'm not that far into tutorials yet.</p>
<p>Any tips or suggestions on making this more dynamic/robust/efficient would be greatly appreciated too!</p>
<pre><code>##Create parent folder for storing retrieved artifacts
$DesktopPath = [Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
New-Item -Path "$DesktopPath\Forensics" -ItemType Directory
$parentFolder = "$DesktopPath\Forensics"
##BEGIN SCRIPT:
Write-Host "Beginning extraction"
##SHELLBAGS
Write-Host "Generating ShellBag CSVs"
Function ShellBags {
New-Item -Path C:\Users\User\Desktop\Forensics\Shellbags -ItemType Directory
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU' |
Export-Csv -Path "$parentFolder\Shellbags\Shellbags_MRU.csv" -UseCulture -NoTypeInformation
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags' |
Export-Csv -Path "$parentFolder\Shellbags\Shellbags.csv" -UseCulture -NoTypeInformation
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache'|
Export-Csv -Path "$parentFolder\Shellbags\Shellbags_MUIcache.csv" -UseCulture -NoTypeInformation
}
ShellBags
##JUMPLISTS:
Write-Host "Generating JumpLists CSV"
Function JumpLists {
New-Item -Path .\USERS\USER\DESKTOP\Forensics\JumpLists -ItemType Directory
Get-ItemProperty -Path 'C:\Users\*\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations' |
Export-Csv -Path "$parentFolder\JumpLists\JumpLists.csv" -UseCulture -NoTypeInformation
}
JumpLists
##LNKLISTS:
Write-Host "Generating LnkLists CSV"
Function LNKList {
New-Item -Path .\Users\User\Desktop\Forensics\LNKList -ItemType Directory
Get-ItemProperty -Path C:\Users\*\AppData\Roaming\Microsoft\Windows\Recent\|
Export-Csv -Path "$parentFolder\LNKList\LNKList_Windows.csv" -UseCulture -NoTypeInformation
Get-ItemProperty -Path C:\Users\*\AppData\Roaming\Microsoft\Office\Recent\ |
Export-Csv -Path "$parentFolder\LNKList\LNKList_Office.csv" -UseCulture -NoTypeInformation
}
LNKList
##LASTLOGON:
Write-Host "Generating LastLogon CSV"
Function LastLogon {
New-Item -Path .\Users\User\Desktop\Forensics\LastLogon -ItemType Directory
Get-LocalUser | Select * | Export-Csv -Path "$parentFolder\LastLogon\LastLogon.csv" -UseCulture -NoTypeInformation
}
LastLogon
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:30:38.073",
"Id": "253123",
"Score": "1",
"Tags": [
"beginner",
"windows",
"powershell"
],
"Title": "Exporting Shellbags, Jump Lists, and LNK files with PowerShell"
}
|
253123
|
<p>I am trying to implement a <em><strong>thread-safe</strong></em> LFU cache algorithm, please review my code and would really appreciate some criticism or suggestion. (on naming, design, data structures used, anything)</p>
<p>Some assumptions:</p>
<ol>
<li>capacity will be larger than 0.</li>
<li>If the cache is full and multiple keys have the same frequency, the least recently used will be evicted.</li>
</ol>
<p>Here is the code:</p>
<pre><code>import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public interface CacheAlgorithm<K, V> {
public V get(K key);
public void put(K key, V value);
}
public class LFU<K, V> implements CacheAlgorithm<K, V> {
private final ReentrantLock lock;
private final int capacity;
private final TreeMap<Integer, Set<K>> frequencyToKeys;
private final Map<K, V> entries;
private final Map<K, Integer> frequencies;
public LFU(int capacity) {
this.capacity = capacity;
lock = new ReentrantLock();
frequencyToKeys = new TreeMap<>();
entries = new HashMap<>();
frequencies = new HashMap<>();
}
@Override
public V get(K key) {
try {
V value = entries.get(key);
if (value != null) {
incrementFrequency(key);
}
return value;
} finally {
lock.unlock();
}
}
@Override
public void put(K key, V value) {
try {
if (entries.containsKey(key)) {
incrementFrequency(key);
entries.put(key, value);
} else {
if (capacity == entries.size()) {
removeLeastFrequentEntry();
}
addNewEntry(key, value);
}
} finally {
lock.unlock();
}
}
private void addNewEntry(K key, V value) {
entries.put(key, value);
setKeyFrequency(key, 1);
}
private void incrementFrequency(K key) {
int frequency = frequencies.get(key);
Set<K> keys = frequencyToKeys.get(frequency);
keys.remove(key);
if (keys.isEmpty()) {
frequencyToKeys.remove(frequency);
}
setKeyFrequency(key, frequency + 1);
}
private void setKeyFrequency(K key, int frequency) {
frequencies.put(key, frequency);
frequencyToKeys.putIfAbsent(frequency, new LinkedHashSet<>());
frequencyToKeys.get(frequency).add(key);
}
private void removeLeastFrequentEntry() {
Map.Entry<Integer, Set<K>> entry = frequencyToKeys.firstEntry();
Integer frequency = entry.getKey();
Set<K> keys = entry.getValue();
K keyToEvict = keys.iterator().next();
keys.remove(keyToEvict);
if (keys.isEmpty()) {
frequencyToKeys.remove(frequency);
}
frequencies.remove(keyToEvict);
entries.remove(keyToEvict);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:51:33.000",
"Id": "499142",
"Score": "0",
"body": "\"*It is recommended practice to* always *immediately follow a call to `lock` with a `try` block…*\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:53:18.227",
"Id": "499143",
"Score": "0",
"body": "As presented, \"Java\" complains about two public in one \"file\"."
}
] |
[
{
"body": "<p>Few comments from my side:</p>\n<p><strong>Looks like a code bug:</strong>\nI think you want to use <code>ReentrantLock</code> to manage concurrent operations in multithreaded environment. But in your code I don't see any place where you have made a call to lock (neither lock() nor tryLock(long timeout, TimeUnit unit)). While unlock() is used couple of time, which is of no use in this case.</p>\n<p><strong>Other suggested updated:</strong></p>\n<ol>\n<li><p>CacheAlgorithm interface should be rather renamed to Cache only. Because it doesn't make sense in any class to make use of word Algorithm.</p>\n</li>\n<li><p>Code should prevent using abbreviations as much as possible. So LFU should be renamed to LeastFrequentlyUsed. Which is not a very big name. Along that it should be ended with Cache to make it more clear to user. So the better name would be LeastFrequentlyUsedCache.</p>\n</li>\n<li><p>It would be better to have a default constructor with default capacity, as Java API has for Collection classes.</p>\n</li>\n<li><p>Avoid auto-boxing and auto-unboxing in code. As these are heavy operations. Rather do custom boxing and unboxing as below:</p>\n</li>\n</ol>\n<hr />\n<pre><code>final int frequency = frequencies.get(key).intValue();\nfinal Set<K> keys = frequencyToKeys.get(Integer.valueOf(frequency));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:38:46.187",
"Id": "499263",
"Score": "0",
"body": "Thanks a lot for your comment, especially for the performance of boxing/unboxing, which I never thought of. For boxing/ unboxing, I googled a bit and it says JVM implicitly calls Integer.valueOf() and intValue() respectively, is there some performance impact for not explicitly boxing/ unboxing interger that I failed to realize?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:44:49.333",
"Id": "499264",
"Score": "0",
"body": "Also, does it make sense to change to `Integer frequency = frequencies.get(key)` to avoid unnecessary boxing later in the code? (can't escape the unboxing/boxing for frequency `setKeyFrequency(key, frequency + 1)` i guess)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:45:27.880",
"Id": "499265",
"Score": "0",
"body": "Also, should i make it `private void setKeyFrequency(K key, Integer frequency)` to avoid boxing in that function ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T15:09:17.520",
"Id": "499300",
"Score": "0",
"body": "@yploo Yes as much as possible avoid boxing and unboxing in code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:23:25.643",
"Id": "253170",
"ParentId": "253125",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T11:56:12.690",
"Id": "253125",
"Score": "2",
"Tags": [
"java",
"multithreading",
"concurrency",
"cache"
],
"Title": "Thread-safe LFU Cache"
}
|
253125
|
<p>I have implemented basic <strong>max heap</strong> insertion and deletion functions without recursion</p>
<pre class="lang-py prettyprint-override"><code># insertion
arr: [6,5,4,3,2,1]
# insert 7
arr: [7,5,6,3,2,1,4]
tree:
7
5 6
3 2 1 4
# delete 7
arr: [6,5,4,3,2,1]
tree:
6
5 4
3 2 1
</code></pre>
<p>My implementation</p>
<pre class="lang-py prettyprint-override"><code>def insert(arr,ele):
# bottom up
n = len(arr)
# insert into the n+1 position
new_arr = arr.append(ele)
i = n # last position
while True:
p_index = int((i-1)/2)
# compare with the parent index
if (arr[i] > arr[p_index]):
# swap the elements
arr[p_index], arr[i] = arr[i], arr[p_index]
i = p_index
else:
# correct
break
return arr
# deletion
def delete(arr):
# top down
if not arr:
return None
# swap the last elment to root
arr[0], arr[len(arr)-1] = arr[len(arr)-1], arr[0]
item = arr.pop()
n = len(arr)
i = 0
# comparing the children
while True:
# left/right child index
lc_index = 2*i + 1
rc_index = 2*i + 2
# no chilren
if lc_index > n-1:
break
# only has left child
if lc_index == (n-1) and rc_index > n-1:
if arr[lc_index] > arr[i]:
arr[i], arr[lc_index] = arr[lc_index], arr[i]
break
else:
if arr[lc_index] > arr[rc_index]:
arr[i], arr[lc_index] = arr[lc_index], arr[i]
i = lc_index
else:
arr[i], arr[rc_index] = arr[rc_index], arr[i]
i = rc_index
return item
</code></pre>
<p>These two functions works fine, but looks pretty cumbersome especially the <code>delete</code> function, any suggestions how to improve the code?</p>
|
[] |
[
{
"body": "<h1>Integer division</h1>\n<p>Are you using Python 3? If so, there is the integer division operator: <code>//</code>. Instead of:</p>\n<pre><code> p_index = int((i-1)/2)\n</code></pre>\n<p>you can write:</p>\n<pre><code> p_index = (i - 1) // 2\n</code></pre>\n<h1>Unnecessary variable</h1>\n<p>In your <code>insert</code> function, where do you use <code>n</code>?</p>\n<pre><code> n = len(arr)\n ...\n i = n # last position\n</code></pre>\n<p>Seems like you can get rid of the <code>n</code> variable, and just initialize <code>i = len(arr)</code></p>\n<h1>Wrong variable</h1>\n<p>In <code>delete</code>, where do you use <code>n</code>?</p>\n<p>You might say it is used in several places. I'd disagree. I'd say it is never used; you only use <code>n-1</code>.</p>\n<p>What is <code>n-1</code>? It is the <code>last</code> index of the array:</p>\n<pre><code> last = len(arr) - 1\n\n ...\n\n if lc_index > last:\n ...\n if lc_index == last and rc_index > last:\n ...\n</code></pre>\n<h1>Unnecessary test:</h1>\n<p>Consider:</p>\n<pre><code> lc_index = 2*i + 1\n rc_index = 2*i + 2\n</code></pre>\n<p>Note that we could rewrite that last statement as</p>\n<pre><code> rc_index = lc_index + 1\n</code></pre>\n<p>Now consider:</p>\n<pre><code> if lc_index == last and rc_index > last:\n ...\n</code></pre>\n<p>Substitute for <code>rc_index</code> ...</p>\n<pre><code> if lc_index == last and lc_index + 1 > last:\n ...\n</code></pre>\n<p>If the first part of that test is <code>True</code>, the second part will always be <code>True</code>; if the first part is false, the second part will never be evaluated. So you just need:</p>\n<pre><code> if lc_index == last:\n ...\n</code></pre>\n<h1>Left or right?</h1>\n<p>The code for the left & right children look identical, save for the index being used.</p>\n<p>Instead of:</p>\n<pre><code> if arr[lc_index] > arr[rc_index]:\n arr[i], arr[lc_index] = arr[lc_index], arr[i]\n i = lc_index\n else:\n arr[i], arr[rc_index] = arr[rc_index], arr[i]\n i = rc_index\n</code></pre>\n<p>You could select the correct left or right index to use:</p>\n<pre><code> child_index = lc_index if arr[lc_index] > arr[rc_index] else rc_index\n</code></pre>\n<p>Then you don't need two copies of the remaining code:</p>\n<pre><code> arr[i], arr[child_index] = arr[child_index], arr[i]\n i = child_index\n</code></pre>\n<h1>Last element</h1>\n<pre><code> arr[0], arr[len(arr)-1] = arr[len(arr)-1], arr[0]\n</code></pre>\n<p>The <code>arr[len(arr)-1]</code> references the last element of <code>arr</code>, by determining the length of the array, and subtracting one to compute the zero-based index.</p>\n<p>Using <code>arr[-1]</code> also references the last element of the array, using Python's negative indexing feature. This allows a much simpler statement:</p>\n<pre><code> arr[0], arr[-1] = arr[-1], arr[0]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:25:05.540",
"Id": "499087",
"Score": "0",
"body": "informative, thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:09:57.373",
"Id": "253134",
"ParentId": "253128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253134",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T12:47:10.420",
"Id": "253128",
"Score": "3",
"Tags": [
"python",
"heap"
],
"Title": "Heap insertion and deletion Implementation using Python"
}
|
253128
|
<p>After a long break I have to return to programming in C. As an exercise I wrote this simple linked list thing. Please just have a look, any comments are appreciated. Just shoot.</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
typedef struct
{
int iNumber;
} TData;
typedef struct TLinkedList
{
struct TLinkedList* iNext;
TData iData;
} TLinkedList;
TLinkedList* Create(TData* aData)
{
TLinkedList* ptr = (TLinkedList*) malloc(sizeof(TLinkedList));
ptr->iData = *aData;
ptr->iNext = NULL;
return ptr;
}
void AddToLinkedList(TLinkedList** aLinkedListStart, TData* aData)
{
printf("%s: aData->iNumber %i\n", __FUNCTION__, aData->iNumber);
TLinkedList* newItem = Create(aData);
if (*aLinkedListStart == NULL)
{
*aLinkedListStart = newItem;
}
else
{
TLinkedList* runner = *aLinkedListStart;
while((*runner).iNext != NULL)
{
runner = runner->iNext;
}
runner->iNext = newItem;
}
}
void FreeLinkedList(TLinkedList** aLinkedListStart)
{
TLinkedList* runner = *aLinkedListStart;
while((*runner).iNext != NULL)
{
TLinkedList* freePtr = runner;
runner = runner->iNext;
free(freePtr);
}
}
void DisplayLinkedList(TLinkedList* aLinkedList)
{
while(aLinkedList != NULL)
{
printf("%s: iNumber %i\n", __FUNCTION__, aLinkedList->iData.iNumber);
aLinkedList = aLinkedList->iNext;
}
}
int main()
{
TLinkedList* firstPtr = NULL;
TData myData_1 = {1};
TData myData_2 = {2};
TData myData_3 = {3};
AddToLinkedList(&firstPtr, &myData_1);
DisplayLinkedList(firstPtr);
AddToLinkedList(&firstPtr, &myData_2);
DisplayLinkedList(firstPtr);
AddToLinkedList(&firstPtr, &myData_3);
DisplayLinkedList(firstPtr);
FreeLinkedList(&firstPtr);
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T02:48:46.590",
"Id": "499107",
"Score": "1",
"body": "Are you following a specific C programming style? Your capitalization is not very C-like..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T15:04:16.603",
"Id": "253129",
"Score": "0",
"Tags": [
"linked-list"
],
"Title": "A simple linked list for C practice"
}
|
253129
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252870/231235">A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++</a> and <a href="https://codereview.stackexchange.com/q/252930/231235">Non-nested std::deque and std::list Generator Function for arithmetic_mean Function Testing in C++</a>. Besides calculating summation and arithmetic mean value of arbitrary nested iterable, I am trying to implement an <code>arithmetic_variance</code> function which can calculate population variance value with the following formula.</p>
<img src="https://render.githubusercontent.com/render/math?math=%5Csigma%5E%7B2%7D%20=%20%5Cfrac%7B%5Csum_%7Bi=1%7D%5E%7BN%7D%20[x_i%20-%20%5Coverline%7Bx%7D]%5E%7B2%7D%7D%7BN%7D%20">
<p><img src="https://render.githubusercontent.com/render/math?math=%5Csigma%5E%7B2%7D"> is population variance value of x, <img src="https://render.githubusercontent.com/render/math?math=x_%7Bi%7D"> is the value of i-th element, <img src="https://render.githubusercontent.com/render/math?math=%5Coverline%7Bx%7D"> is the population mean which is calculated by <code>arithmetic_mean</code> template function and <em>N</em> is the population size which is calculated by <code>recursive_size</code> function (refer to the previous question <a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>).</p>
<p><strong>The usage description</strong></p>
<p>The input of <code>population_variance</code> template function is a arbitrary Nested Iterable. For example, given a test_vector: <code>std::vector<double> test_vector{ 1, 2, 3, 4, 5 };</code>. The <code>population_variance</code> template function can be called like this <code>std::cout << "population_variance: " << population_variance(test_vector) << std::endl;</code> and the output is</p>
<pre><code>population_variance: 2
</code></pre>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>population_variance</code> template function is here.</p>
<pre><code>// population_variance function implementation
template<class T1, class T2>
requires (is_iterable<T1> && is_recursive_reduceable<T1> && is_recursive_sizeable<T1> && is_minusable2<std::iter_value_t<T1>, T2>)
// non-recursive version
auto _population_variance(const T1& input, const T2 arithmetic_mean_result)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [arithmetic_mean_result](auto& element) {
return std::pow(element - arithmetic_mean_result, 2);
});
}
template<class T1, class T2>
requires (is_iterable<T1> && is_elements_iterable<T1> && is_recursive_reduceable<T1> && is_recursive_sizeable<T1>)
auto _population_variance(const T1& input, const T2 arithmetic_mean_result)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [arithmetic_mean_result](auto& element) {
return _population_variance(element, arithmetic_mean_result);
});
}
template<class T>
requires (is_recursive_reduceable<T> && is_recursive_sizeable<T>)
auto population_variance(const T& input)
{
return _population_variance(input, arithmetic_mean(input)) / (recursive_size(input));
}
</code></pre>
<p>The used <code>is_iterable</code>, <code>is_elements_iterable</code>, <code>is_recursive_reduceable</code>, <code>is_recursive_sizeable</code> and <code>is_minusable2</code> concepts are as below.</p>
<pre><code>template<typename T>
concept is_iterable = requires(T x)
{
*std::begin(x);
std::end(x);
};
template<typename T>
concept is_elements_iterable = requires(T x)
{
std::begin(x)->begin();
std::end(x)->end();
};
template<typename T>
concept is_recursive_reduceable = requires(T x)
{
recursive_reduce(x, 0.0);
};
template<typename T>
concept is_recursive_sizeable = requires(T x)
{
recursive_size(x);
};
template<typename T>
concept is_minusable = requires(T x) { x - x; };
template<typename T1, typename T2>
concept is_minusable2 = requires(T1 x1, T2 x2) { x1 - x2; };
</code></pre>
<p>The implementation of the used <code>arithmetic_mean</code> function:</p>
<pre><code>template<class T> requires (is_recursive_reduceable<T> && is_recursive_sizeable<T>)
auto arithmetic_mean(const T& input)
{
return (recursive_reduce(input, 0.0)) / (recursive_size(input));
}
</code></pre>
<p>The implementation of the used <code>recursive_size</code> function:</p>
<pre><code>// recursive_size implementation
template<class T> requires (!is_iterable<T>)
auto recursive_size(const T& input)
{
return 1;
}
template<class T> requires (!is_elements_iterable<T> && is_iterable<T>)
auto recursive_size(const T& input)
{
return input.size();
}
template<class T> requires (is_elements_iterable<T>)
auto recursive_size(const T& input)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>A more complex example is like:</p>
<pre><code>// std::vector<std::vector<int>> case
std::vector<double> test_vector{ 1, 2, 3, 4, 5 };
std::cout << "recursive_size of test_vector: " << recursive_size(test_vector) << std::endl;
std::cout << "population_variance of test_vector: " << population_variance(test_vector) << std::endl;
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
std::cout << "recursive_size of test_vector2: " << recursive_size(test_vector2) << std::endl;
std::cout << "population_variance of test_vector2: " << population_variance(test_vector2) << std::endl;
auto test_vector3 = n_dim_container_generator<10, std::vector, decltype(test_vector)>(test_vector, 3);
std::cout << "recursive_size of test_vector3: " << recursive_size(test_vector3) << std::endl;
std::cout << "population_variance of test_vector3: " << population_variance(test_vector3) << std::endl;
</code></pre>
<p>The used <code>n_dim_container_generator</code> template function is as follows. Thanks to <a href="https://codereview.stackexchange.com/a/253039/231235">G. Sliepen's answer</a>.</p>
<pre><code>template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
</code></pre>
<p><a href="https://godbolt.org/z/r3P9n6" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252870/231235">A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/252930/231235">Non-nested std::deque and std::list Generator Function for arithmetic_mean Function Testing in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Besides the functions for calculating summation and arithmetic mean value of arbitrary nested iterable, a new function <code>population_variance</code> implementation is the main part of this question.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>There are more concepts used here, including <code>is_iterable</code>, <code>is_elements_iterable</code>, <code>is_recursive_reduceable</code>, <code>is_recursive_sizeable</code> and <code>is_minusable2</code>. Please check if the design is appropriate or not.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Consider using <code>namespace detail</code> to make functions private</h1>\n<p>Names starting with an underscore in the global namespace are <a href=\"https://en.cppreference.com/w/cpp/language/identifiers\" rel=\"nofollow noreferrer\">reserved by the C++ language</a>. In general, avoid starting any name with an underscore unless you really want to memorize all the rules surrounding them. The typical solution C++ libraries use to make things "private" in header-only libraries is to introduce a <code>namespace detail</code> in which they put private variables, functions and classes. So:</p>\n<pre><code>namespace detail {\n\ntemplate<class T1, class T2> requires ...\n// non-recursive version\nauto population_variance(const T1& input, const T2 arithmetic_mean_result) {...}\n\ntemplate<class T1, class T2> requires ...\nauto population_variance(const T1& input, const T2 arithmetic_mean_result) {...}\n\n}\n\ntemplate<class T> requires (is_recursive_reduceable<T> && is_recursive_sizeable<T>)\nauto population_variance(const T& input)\n{\n return detail::population_variance(...) / ...;\n}\n</code></pre>\n<h1>Use the correct types</h1>\n<p>The whole point of writing templates is so that they work with different types. This means you have to be careful to hardcode types, or to use literal constants of the wrong type. For example, in your code, you have:</p>\n<pre><code>return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [arithmetic_mean_result](auto& element) {...});\n</code></pre>\n<p>Here you force the accumulator to be of <code>std::size_t</code>. But what if I want to calculate the mean and variance of floating point values between <code>0.0</code> and <code>1.0</code>? Everything would be cast to <code>std::size_t</code> in your code, making the final result <code>0</code> no matter what. You should ensure the type matches that of the values stored in the nested container.</p>\n<p>For the <code>detail::population_variance()</code> functions which take a parameter with the mean, I would just use the type of the mean:</p>\n<pre><code>template<class T1, class T2> requires ...\nauto population_variance(const T1& input, const T2 mean)\n{\n return std::transform_reduce(std::begin(input), std::end(input), T2{}, std::plus<T2>(), [mean](auto& element) {\n return std::pow(element - mean, 2);\n });\n}\n</code></pre>\n<p>So now the problem is in <code>arithmetic_mean()</code>. There you have:</p>\n<pre><code>return (recursive_reduce(input, 0.0)) / (recursive_size(input));\n</code></pre>\n<p>The literal <code>0.0</code> forces the result to be <code>double</code>. This might be OK, it probably is what you want even if the input is a nested container of integers, but it might also be wrong. Consider that the values in the container might be a <code>std::complex</code>, or some other custom type? Maybe the concept of variance doesn't make sense anymore for these types, but that means you have to make a decision:</p>\n<ol>\n<li>Only accept containers of value types that have a mean and variance that can be accurately described by a <code>double</code>.</li>\n<li>Deduce the value type of the nested container and use that type for the initial value.</li>\n<li>Allow the user to specify the type used to represent the mean and variance.</li>\n</ol>\n<p>The STL typically lets the caller specify the type of the result in some way, usually by taking a parameter for the initial value. That of course doesn't make sense for <code>arithmetic_mean</code> and <code>population_variance</code>, but then I would use a template parameter for that. Unfortunately, you cannot have a default value for a template parameter that depends on a subsequent parameter, so I think this is the best compromise:</p>\n<pre><code>template<class T = double, class Container> requires ...\nauto arithmetic_mean(const Container& input)\n{\n return recursive_reduce(input, T{}) / recursive_size(input);\n}\n\ntemplate<class T = double, class Container> requires ...\nauto population_variance(const Container& input)\n{\n return detail::population_variance(input, arithmetic_mean<T>(input)) / recursive_size(input);\n}\n</code></pre>\n<h1>Use of concepts</h1>\n<p>Try to reduce the number of concepts used in the <code>requires</code> statements. Also, if the concepts are very specific and use derived types, as in:</p>\n<pre><code>requires (... && is_minusable2<std::iter_value_t<T1>, T2>)\n</code></pre>\n<p>Then if this fails the error message will probably be as crytped as if you did not require this concept and the error would occur in the body of the instantiated template.</p>\n<p>You should first use concepts to ensure the right template variant is chosen, and for that you just need <code>is_elements_iterable</code> to distinguish between the recursive and non-recursive variants. Everything else is just to give a better error message. In this case, I would just write one concept that checks whether the given value type can have the variance calculated of:</p>\n<pre><code>template<typename T>\nconcept can_calculate_variance_of(const T& value)\n{\n (std::pow(value, 2) - value) / std::size_t{1};\n}\n</code></pre>\n<p>Also, you shouldn't check for those requirements in <code>detail::population_variance()</code>, but rather in the public <code>population_variance()</code> function. Otherwise, the error will still happen inside the body of <code>population_variance()</code>, and will be more cryptic than necessary. So ideally you want something like:</p>\n<pre><code>template<class T>\nrequires (... && can_calculate_variance_of<recursive_iter_value_t<T>>)\nauto population_variance(const T& input)\n{\n return detail::population_variance(input, arithmetic_mean(input)) / recursive_size(input);\n}\n</code></pre>\n<h1>Cleaner way to handle recursion</h1>\n<p>In this case it is not necessary to have both <code>detail::population_variance()</code> functions call <code>std::transform_reduce()</code>. That looks like unnecessary repetition. You can instead write:</p>\n<pre><code>namespace detail\n{\n\ntemplate<class T1, class T2>\nrequires (!is_iterable<T1>)\nauto population_variance(const T1& input, const T2 mean)\n{\n return std::pow(input - mean, 2);\n}\n\ntemplate<class T1, class T2>\nauto population_variance(const T1& input, const T2 mean)\n{\n return std::transform_reduce(std::begin(input), std::end(input), T2{}, std::plus<T2>(), [mean](auto& element) {\n return population_variance(element, mean);\n });\n}\n\n}\n</code></pre>\n<p>But perhaps even better would be to have a <code>recursive_transform_reduce()</code>, so you can get rid of the detail functions and replace the public function with:</p>\n<pre><code>template<class T, class Container>\nrequires (...)\nauto population_variance(const Container& input)\n{\n auto mean = arithmetic_mean<T>(input);\n return recursive_transform_reduce(input, T{}, std::plus<T>(), [mean](auto &element) {\n return std::pow(element - mean, 2);\n }) / recursive_size(input);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:21:07.920",
"Id": "253182",
"ParentId": "253131",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T15:25:10.940",
"Id": "253131",
"Score": "1",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
253131
|
<p>I have a weather station with a <a href="https://www.thiesclima.com/en/Products/Miscellaneous-Devices-Data-logger/?art=991" rel="nofollow noreferrer">data logger</a> which accepts commands (specified in user manual) and sends back the respective data over a serial interface. In my case, I want to read the current data from the different sensors of the weather station in a specified interval and then publish them on a MQTT topic.</p>
<p>For this purpose I wrote a Python script with an object-oriented approach for better maintainability and to be able to extend some functionalities more easily, e.g. adding more functions for reading out some other data from the data logger.</p>
<p>This works fine for me now, but I wonder if my approach/structure is generally good so far or "if that's how you would do it" in a correct and tidy way.</p>
<p><strong>INFO</strong> This script is running inside a docker container. As a daemon, unattended 24/7 operation is absolutely necessary. Maybe you have also tips on exception handling.</p>
<p>Overall I have one main file and files containing the different classes:</p>
<p><strong>main.py</strong></p>
<pre><code> import mqttClient
import logger
import watchdogResetter
import dlxMetDatalogger
from apscheduler.schedulers.blocking import BlockingScheduler
import serial
import os
class WetterStationToMQTT:
"""Used to create all necessary functions and instances to get and publish weatherstation data
"""
def __init__(self):
os.environ['TZ']= 'Europe/Berlin' #set timezone for logger/watchdog
self.logger = logger.Logger(os.environ['LOG_FILE_PATH'],os.environ['LOG_LEVEL_FILE'],os.environ['LOG_LEVEL_CONSOLE'])
self.serialParameters = {
'device' : os.environ['SERIAL_DEVICE'], #specify in docker-compose.yaml
'bytesize' : serial.EIGHTBITS,
'baud' : 115200,
'parity' : serial.PARITY_NONE,
'stopbit' : serial.STOPBITS_ONE,
'timeout' : 1
}
self.device = dlxMetDatalogger.DataloggerDLxMET_9_1756_x0_100(self.serialParameters)
self.mqttServer = os.environ['MQTT_SERVER'] #specify in docker-compose.yaml
self.mqttTopic = os.environ['MQTT_TOPIC'] #specify in docker-compose.yaml
self.mqttClient = mqttClient.MQTTClient(self.mqttServer)
self.watchdogResetter = watchdogResetter.WatchdogResetter(os.environ['WATCHDOG_FILE_PATH'])
self.schedulerInterval_sec = int(os.environ['QUERY_INTERVAL_SEC']) #specify in docker-compose.yaml
self.start()
def schedulerjob_readDataAndPublish(self):
"""Scheduler worker function
"""
try:
currentDataMeasurement = self.device.measure_CurrentData()
if(currentDataMeasurement.dataValid):
self.mqttClient.publishJson(self.mqttTopic, currentDataMeasurement.jsonData)
self.logger.logInfo("[o] Raw data: " + str(currentDataMeasurement.rawData))
self.logger.logInfo("[o] ParsedData: " + str(currentDataMeasurement.parsedData))
else:
self.logger.logError("[x] Raw data: " + str(currentDataMeasurement.rawData))
self.logger.logError("[x] ParsedData: " + str(currentDataMeasurement.parsedData))
self.watchdogResetter.resetWatchdog()
except Exception as e:
self.logger.logError(f"Exception {e} in scheduler worker function")
def start(self):
"""Creates all necessary instances and starts scheduler.
"""
try:
self.scheduler = BlockingScheduler()
self.scheduler.add_job(self.schedulerjob_readDataAndPublish, 'interval', seconds = self.schedulerInterval_sec)
self.scheduler.start()
except Exception as e:
self.logger.logError(str(e))
if __name__ == '__main__':
wetterStationToMqtt = WetterStationToMQTT()
</code></pre>
<p><strong>mqttClient.py</strong></p>
<pre><code>import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import json
class MQTTClient:
"""A wrapper around the paho MQTT libary
"""
def __init__(self, mqttServer):
"""Establishes MQTT connection with given MQTT server.
Args:
mqttServer (String): Address of MQTT server (e.g. "172.23.62.255", "localhost", etc. )
"""
self.mqttClient = mqtt.Client()
self.mqttClient.connect(mqttServer, 1883)
self.mqttClient.loop_start() # for keeping alive
def publishJson(self, topic, jsonData):
"""Publishes data in the JSON format to the given topic
Args:
topic (String): The MQTT topic
jsonData (String): JSON data
"""
self.mqttClient.publish(topic, payload = jsonData)
</code></pre>
<p><strong>logger.py</strong></p>
<pre><code>import logging
import os
class Logger:
"""Class providing logging functionalities
"""
def __init__(self,logFilePath,loggerLevelFile,loggerLevelConsole):
"""Sets up a logger instance and handler to write the logs to a file and console
"""
#set logs
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
#formatting logs
self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# send logs to file
self.filehandler = logging.FileHandler(logFilePath)
self.filehandler.setLevel(eval(f"logging.{loggerLevelFile}"))
self.filehandler.setFormatter(self.formatter)
self.logger.addHandler(self.filehandler)
# send logs to console
self.streamhandler = logging.StreamHandler()
self.streamhandler.setLevel(eval(f"logging.{loggerLevelConsole}"))
self.streamhandler.setFormatter(self.formatter)
self.logger.addHandler(self.streamhandler)
def logError(self,message):
"""Logs message with logger-level ERROR
Args:
message (string): Message to print with log
"""
self.logger.error(message)
def logWarning(self,message):
"""Logs message with logger-level WARNING
Args:
message (string): Message to print with log
"""
self.logger.warning(message)
def logInfo(self,message):
"""Logs message with logger-level INFO
Args:
message (string): Message to print with log
"""
self.logger.info(message)
def logDebug(self,message):
"""Logs message with logger-level DEBUG
Args:
message (string): Message to print with log
"""
self.logger.debug(message)
</code></pre>
<p><strong>watchdogResetter.py</strong></p>
<pre><code>from time import gmtime, strftime
class WatchdogResetter:
"""Used to reset the BCM2711 watchdog (on a raspberry pi 4)
"""
def __init__(self,watchdogfilePath):
"""
Args:
watchdogfilePath (String): Path to the textfile checked by the watchdog module
"""
self.watchdogfilePath=watchdogfilePath
def resetWatchdog(self):
"""resets the watchdog by writing to the designated textfile monitored by the watchdog module
"""
with open(self.watchdogfilePath, "w") as watchdogFile:
watchdogFile.write(strftime("%Y-%m-%d %H:%M:%S", gmtime())+"\n")
</code></pre>
<p><strong>dlxMetDatalogger.py</strong></p>
<pre><code>
import serial
import string
import measurement
BEGIN_OF_COMMAND = "\x02" #begin of command (ascii STX, see docu)
END_OF_COMMAND = "\x03" #end of command (ascii ETX)
class DataloggerDLxMET_9_1756_x0_100:
"""Encapsulates one DLxMet 9.1756.x0.100 data logger (weather station)
"""
def __init__(self,serialParameters):
"""Establishes serial connection with weather station
"""
self.serialParameters = serialParameters
#establish serial connection
self.ser = serial.Serial(
self.serialParameters['device'],
self.serialParameters['baud'],
self.serialParameters['bytesize'],
self.serialParameters['parity'],
self.serialParameters['stopbit'],
self.serialParameters['timeout'])
self.ser.flush()
def ask(self, command_str):
"""Sends command to weather station and returns its answer
Args:
command_str (String): Command to send to the weather station (e.g. "mm" - for reading current sensordata)
Returns:
list: list of answer lines
"""
#format command
command_unicode = BEGIN_OF_COMMAND + command_str + END_OF_COMMAND
command_bytes = bytearray(command_unicode, 'ascii')
#send command
self.ser.flush()
self.ser.write(command_bytes)
#read out data from datalogger
rawData = []
for line in self.ser.readlines():
rawData.append(line)
return rawData
def measure_CurrentData(self):
"""Gets current sensor data
Returns:
DataloggerDLxMET_9_1756_x0_100_CurrentSensorData_Measurement: Measurement object
"""
return measurement.DataloggerDLxMET_9_1756_x0_100_CurrentSensorData_Measurement(self,self.ask("mm"))
</code></pre>
<p><strong>measurement.py</strong></p>
<pre><code>import re
import json
class DataloggerDLxMET_9_1756_x0_100_Measurement:
"""Encapsulates one (generic) measurement of the DLxMet 9.1756.x0.100 data logger (weather station)
"""
def __init__(self,device,rawData):
self.device=device
self.rawData=rawData
self.parsedData=None
self.dataValid=False
self.parseData()
def parseData(self):
raise NotImplementedError #Force subclass to implement method
class DataloggerDLxMET_9_1756_x0_100_CurrentSensorData_Measurement(DataloggerDLxMET_9_1756_x0_100_Measurement):
"""Encapsulates one current sensor values measurement of the DLxMet 9.1756.x0.100 data logger (weather station)
(special case of DataloggerDLxMET_9_1756_x0_100_Measurement)
"""
def __init__(self, device, rawData):
super(DataloggerDLxMET_9_1756_x0_100_CurrentSensorData_Measurement,self).__init__(device,rawData)
if(self.dataValid):
self.convertDataToJSON()
def parseData(self):
"""Parses self.rawData to self.parsedData (a dict). Sets self.dataValid if raw data could be parsed correctly
"""
#regEx for strictly matching on correctly received data
reString = ("(\d+\.\d+)\s+" #hours and decimal minutes
"(\d+\.\d+)\s+" #Windspeed
"(\d+)\s+" #Winddirection
"([-]?\d+\.\d+)\s+" #Temperature
"(\d+\.\d+)\s+" #Humidity
"(\d+\.\d+)\s+" #Precipitation
"(\d+\.\d+)\s+" #Pressure
"(\d+\.\d+)\s+" #Radiation
"(\?+\.\?+)\s+" #not connected sensor => "???.?" in bytestring
"(\d+\.\d+)\s+" #0.0
"(\d+\.\d+)\s+" #1.0
"(\d+\.\d+\.\d+)\s+" #Date
"(\d+\:\d+\:\d+)") #Time
matchedDataList = [item for sublist in re.findall(reString,str(self.rawData)) for item in sublist]
#check data and convert sensordata to float
self.dataValid = True
if (len(matchedDataList) == 13 and matchedDataList[9] == '0.0' and matchedDataList[10] == '1.0'):
for i in range(1,8):
try:
matchedDataList[i] = float(matchedDataList[i])
except ValueError:
self.dataValid = False
else:
self.dataValid = False
return
# write data into dict
self.parsedData = {
'windspeed' : matchedDataList[1],
'winddirection' : matchedDataList[2],
'temperature' : matchedDataList[3],
'humidity' : matchedDataList[4],
'precipitation' : matchedDataList[5],
'pressure': matchedDataList[6],
'radiation' : matchedDataList[7]
}
def convertDataToJSON(self):
"""Converts self.parsedData to JSON string (self.jsonData)
"""
self.jsonData = json.dumps(self.parsedData)
</code></pre>
<p><strong>For information:</strong></p>
<p>docker-compose.yaml</p>
<pre><code>version: '2'
services:
wetterlog:
build : .
container_name: dataToMQTT
restart: always
volumes:
- .:/code
- ~/watchdog:/watchdog
- ~/log:/log
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"
ports:
- 21883:1883
environment:
- SERIAL_DEVICE=/dev/ttyUSB0
- MQTT_SERVER=172.23.62.107
- MQTT_PORT=1883
- MQTT_TOPIC=sensors
- QUERY_INTERVAL_SEC=5
- LOG_FILE_PATH=./log/log.txt
- LOG_LEVEL_FILE=ERROR
- LOG_LEVEL_CONSOLE=INFO
- WATCHDOG_FILE_PATH=./watchdog/watchdog.txt
</code></pre>
<p>Dockerfile</p>
<pre><code>FROM python:alpine3.7
WORKDIR /
COPY requirements.txt /
RUN pip install -r requirements.txt
COPY . /
CMD python __main__.py
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T15:31:01.453",
"Id": "253132",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"logging"
],
"Title": "Reading sensor data from serial device and publishing on MQTT"
}
|
253132
|
<p>I've written a piece of code to play a video using OpenCV on tkinter. Its part of a game I've made and compiled into an application. But I've noticed that when I play the game in a different computers, since the screen sizes are different, the video doesn't fit exactly to screen size like I want it to. The same goes for the background images I used in different pages but I wrote a piece of code to resize the background images to screen size. Here it is:</p>
<pre class="lang-py prettyprint-override"><code> def resizeimage(self,event) :
width, height = self.winfo_width(), self.winfo_height()
image = self.bg_image.resize((width,height))
self.image1 = ImageTk.PhotoImage(image)
self.bg_label.config(image = self.image1)
</code></pre>
<p>I've bound this function to the label that displays the background image like this:</p>
<pre class="lang-py prettyprint-override"><code> self.bg_image = Image.open("project_pics\\start_pg.png")
bg_image = ImageTk.PhotoImage(self.bg_image)
self.bg_label = Label(self,image=bg_image)
self.bg_label.image = bg_image
self.bg_label.bind('<Configure>',self.resizeimage)
self.bg_label.grid(sticky="nwse")
</code></pre>
<p>here, <code>self.bg_image</code> is the image to be displayed as background and <code>self.bg_label</code> is the label that displays the image.
I know that I can implement something similar by resizing the frames, in my code to play the video, but I cant seem to figure out a quick, efficient a way to do so. Here is the code for the video player:</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import *
from tkinter.ttk import Button
from PIL import Image, ImageTk
import time
import cv2 as cv2
from threading import Thread
from Scripts.music_player import m_player
from Scripts.styles import Styles
# The Video Player
class VideoPlayer :
def __init__(self,parent) :
self.parent = parent
self.play = False
def player(self,vid_file,m_file,nxt_func):
def get_frame():
ret,frame = vid.read()
if ret and self.play :
return(ret,cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
else :
return(ret,None)
def update() :
ret,frame = get_frame()
if ret and self.play :
img = Image.fromarray(frame)
photo = ImageTk.PhotoImage(image=img)
photo.image=img
self.canvas.itemconfig(self.vid_frame,image=photo)
self.canvas.image=photo
self.parent.after(delay,lambda : update())
else :
time.sleep(0.01)
# stopping vid_music and starting game music
m_player.music_control(m_file,True,-1,0)
m_player.music_control("project_media\\signal.ogg",False,-1,0)
nxt_func()
def skip() :
self.play = False
self.parent.clear()
self.play = True
# starting music
m_player.music_control("project_media\\signal.ogg",True,-1,0)
m_player.music_control(m_file,False,-1,0)
vid = cv2.VideoCapture(vid_file)
width = vid.get(cv2.CAP_PROP_FRAME_WIDTH)
height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.canvas = Canvas(self.parent, width = width, height = height)
self.canvas.place(relx=0.5,rely=0.5,anchor=CENTER)
self.vid_frame = self.canvas.create_image(0, 0, anchor = NW)
# Skip button
if vid_file != "project_media\\glitch.mp4" :
skip_thread = Thread(target=skip)
skip = Button(self.parent,text="Skip",command=skip_thread.start,style="skip.TButton")
skip.place(relx=0.88,rely=0.04)
delay = 5
update()
</code></pre>
<p>My question is this. <strong>How could I efficiently resize my frames to fit screen size without slowing down execution?</strong>. Also, the function I'm using right now to resize my background images also seems to be slowing down execution. So I can see something like a glitch on the screen every time I change pages. So is there any other way I can resize my background images. Sorry if the code is a bit messy. I'm a beginner and this is the first game I've made . Any tips on improving the code would also be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:03:24.227",
"Id": "499071",
"Score": "0",
"body": "If your code isn't working up to your expectations, it is off-topic. The exception being performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T17:20:25.413",
"Id": "499072",
"Score": "0",
"body": "Yeah the problem here is with the performance of the code I wrote to resize. Its not fast enough(according to my assessment), hence I cant use that code to somehow try to resize all the frames individually as it will just end up making the video much slower."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T16:49:09.897",
"Id": "253133",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"tkinter",
"opencv"
],
"Title": "Resize video frame to fit tkinter window size when the window is resized"
}
|
253133
|
<p>I have the following array, and I want to convert it to an array without duplicates.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = [
{
items: [
{ outerKey: { innerKey: 1 } },
{ outerKey: { innerKey: 2 } },
{ outerKey: { innerKey: 3 } },
],
},
{
items: [
{ outerKey: { innerKey: 3 } },
{ outerKey: { innerKey: 5 } },
{ outerKey: { innerKey: 5 } },
],
},
{
items: [
{ outerKey: { innerKey: 1 } },
{ outerKey: { innerKey: 8 } },
{ outerKey: { innerKey: 2 } },
],
},
];
const finalArray = [...new Set(a.reduce((acc, curr) => { acc.push(curr.items.map(item => item.outerKey.innerKey)); return acc;} , []).flat())];
console.log(finalArray);</code></pre>
</div>
</div>
</p>
<p>Is there a better approach than this? considering there could be > 1000 items.</p>
|
[] |
[
{
"body": "<p>Adding all the elements to a <code>Set</code> should be generally the most efficient way. However, before you add them to the <code>Set</code> you are creating lots of intermediate arrays. It will likely be more efficient to just iterate over the elements and add them to the set one by one:</p>\n<pre><code>let set = new Set();\na.forEach(o => {\n o.items.forEach(i => {\n set.add(i.outerKey.innerKey);\n });\n});\nconst finalArray = [...set];\nconsole.log(finalArray);\n</code></pre>\n<p>Not sure if <code>forEach()</code> is the fastest way to iterate over the array elements in whatever runtime you are using. See <a href=\"https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript\">here</a> for a discussion of how to iterate arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T12:31:21.413",
"Id": "499148",
"Score": "0",
"body": "I think this is the fastest and most readable solution. If I show this code without comments to someone and ask what it does, he can clearly see it at firs glance."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T21:13:30.423",
"Id": "253145",
"ParentId": "253139",
"Score": "5"
}
},
{
"body": "<p>From a code review standpoint, to start with, a better approach than this line:</p>\n<pre><code>const finalArray = [...new Set(a.reduce((acc, curr) => { acc.push(curr.items.map(item => item.outerKey.innerKey)); return acc;} , []).flat())];\n</code></pre>\n<p>would be to separate it out onto separate lines to make it more easily readable:</p>\n<pre><code>const finalArray = [...new Set(\n a.reduce(\n (acc, curr) => {\n acc.push(curr.items.map(item => item.outerKey.innerKey));\n return acc;\n },\n [])\n .flat()\n)];\n</code></pre>\n<p>or something of the sort - better to have long, easy-to-read code than to conserve lines at the expense of readability - leave that to the automatic minifiers at the end of a build process. More than 4 or 5 operators and function calls on a single line is usually a red flag.</p>\n<p>The algorithm you're using is slightly inefficient in that it's iterating over every subarray twice (once to map the <code>items</code> to each <code>.innerKey</code>, and again to flatten each subarray), but that's not so bad. A similar approach but using a slightly more appropriate method would be to use <code>.flatMap</code> instead of using <code>.reduce</code> and <code>.flat</code> at the end:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a=[{items:[{outerKey:{innerKey:1}},{outerKey:{innerKey:2}},{outerKey:{innerKey:3}}]},{items:[{outerKey:{innerKey:3}},{outerKey:{innerKey:5}},{outerKey:{innerKey:5}}]},{items:[{outerKey:{innerKey:1}},{outerKey:{innerKey:8}},{outerKey:{innerKey:2}}]}];\n\nconst finalArray = [...new Set(\n a.flatMap(\n ({ items }) => items.map(\n item => item.outerKey.innerKey\n )\n )\n)];\n\nconsole.log(finalArray);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>(Using <code>.reduce</code> when the accumulator stays the same object is arguably inappropriate anyway - see <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">this video</a> by V8 developers on the subject)</p>\n<p>Using a Set to begin with <a href=\"https://codereview.stackexchange.com/a/253145\">in the other answer</a> instead of making intermediate arrays is even better.</p>\n<h3>But:</h3>\n<blockquote>\n<p>considering there could be > 1000 items.</p>\n</blockquote>\n<p>On modern computers, 1000 items in a data structure is <em>nothing</em>. (If they were elements in the DOM, that'd be another matter, but if they're just array items, it's almost certainly not something to worry about.) Better to write clean, readable code, and then <em>if</em> you find something doesn't seem to be running as fast as you'd like, run a performance test to identify the bottleneck(s) and fix them. (The bottleneck will almost certainly not be a section like this.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T01:35:50.707",
"Id": "253154",
"ParentId": "253139",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253145",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T18:21:08.010",
"Id": "253139",
"Score": "5",
"Tags": [
"javascript",
"performance"
],
"Title": "Convert array of arrays to array without duplicates"
}
|
253139
|
<p>This is a simple bash script that I use to compile and run single C++ files for coding competitions.</p>
<p>Features:</p>
<ul>
<li>Detects if there is a corresponding <code>.in</code> file next to it, and if so uses that as stdin
<ul>
<li>e.g. if the file <code>problem1.cpp</code> and <code>problem1.in</code> are in the same directory, the script will redirect stdin from <code>problem1.in</code></li>
</ul>
</li>
<li>Compile each file to a temp directory so it doesn't clutter the working directory</li>
<li>Configurable g++ warning flags as needed</li>
</ul>
<p>Note: <code>\033[32m</code> and <code>\033[0m</code> are terminal color codes that make the text green</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# Compiles and runs .cpp code
# if there exists an .in file next to the .cpp file
# it will use that as input
if [ -z $1 ]; then
echo -e "Please choose an input file"
exit 1
fi
FILE="$1"
FILE_IN="${FILE%.*}.in"
clear
echo -e "\033[32mCompiling...\033[0m"
TMPFILE=$(mktemp /tmp/run-cpp.XXXXXXXXXX)
WARNING_FLAGS="-Wuninitialized -Wmaybe-uninitialized"
g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE
if [ $? -eq 0 ]; then
echo -e "\033[32mRunning...\033[0m"
if [ -f $FILE_IN ]; then
$TMPFILE < $FILE_IN
else
$TMPFILE
fi
ERROR=$?
fi
rm $TMPFILE 2> /dev/null
exit $ERROR
</code></pre>
<p>Usage:
<code>./runcpp.sh /path/to/my-cpp-file.cpp</code></p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>#!/bin/bash\n</code></pre>\n</blockquote>\n<p>I don't see why you're using Bash for this - there should be no problem using standard POSIX shell.</p>\n<blockquote>\n<pre><code>if [ -z $1 ]; then\n</code></pre>\n</blockquote>\n<p>I would recommend <code>"$1"</code> there, even though extra arguments will cause <code>[</code> to return false for other reasons. Passing as a single argument won't emit any error messages.</p>\n<blockquote>\n<pre><code> echo -e "Please choose an input file"\n</code></pre>\n</blockquote>\n<p><code>echo -e</code> isn't portable, and isn't necessary here anyway.</p>\n<blockquote>\n<pre><code>FILE="$1"\nFILE_IN="${FILE%.*}.in"\n</code></pre>\n</blockquote>\n<p>Avoid all-caps names for variables in your own program - these are generally reserved for environment variables which change programs' behaviour.</p>\n<blockquote>\n<pre><code>clear\n</code></pre>\n</blockquote>\n<p>I think that's a bit rude - some of us like to be able to compare results against the previous run. If I want to clear before I run, I can type that easily.</p>\n<blockquote>\n<pre><code>echo -e "\\033[32mCompiling...\\033[0m"\n</code></pre>\n</blockquote>\n<p>Don't embed terminal-specific escape codes like that! Even though most recent terminals support the ANSI escapes, there are others - and if you redirect to file, you don't want it littered with control characters. Use <code>tput</code> to generate the correct escapes for your <code>$TERM</code> (and slightly more readable code).</p>\n<blockquote>\n<pre><code>TMPFILE=$(mktemp /tmp/run-cpp.XXXXXXXXXX)\n</code></pre>\n</blockquote>\n<p>That's not a very descriptive variable name. It's more informative to say what it's <em>for</em> (the executable to create). And why hard-code <code>/tmp</code> as the directory? Prefer <code>$TMPDIR</code> if set (perhaps systems with per-user temp directories, or with a choice of fast or large temporary storage).</p>\n<blockquote>\n<pre><code>WARNING_FLAGS="-Wuninitialized -Wmaybe-uninitialized"\n</code></pre>\n</blockquote>\n<p>That's quite a lax set of warnings. If you care about the quality of your source, add a few more. I suggest <code>-Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++</code>. If you only care about performance, then perhaps <code>-Wall -Wextra -Wno-parentheses -Warray-bounds</code> might be sufficient.</p>\n<p>Since we use this variable only once, perhaps we should inline its use, thereby not triggering a Shellcheck warning where we (correctly) expand it without quotes.</p>\n<blockquote>\n<pre><code>g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE\n</code></pre>\n</blockquote>\n<p><code>"$FILE"</code> here, too. I'd write <code>"$TMPFILE"</code> even though we constructed it to be a safe name.</p>\n<blockquote>\n<pre><code>if [ $? -eq 0 ]; then\n</code></pre>\n</blockquote>\n<p>Anti-pattern - just use the preceding command directly after <code>if</code>. Or, enable the <code>-e</code> flag of the shell, to just exit if the compilation fails.</p>\n<blockquote>\n<pre><code> echo -e "\\033[32mRunning...\\033[0m"\n</code></pre>\n</blockquote>\n<p><code>tput</code> again.</p>\n<blockquote>\n<pre><code> if [ -f $FILE_IN ]; then\n</code></pre>\n</blockquote>\n<p>Quotes again.</p>\n<blockquote>\n<pre><code> $TMPFILE < $FILE_IN\n else\n $TMPFILE\n fi\n</code></pre>\n</blockquote>\n<p>As we don't use stdin, we could just redirect <code>stdin</code> using <code>exec</code>, and not need two different commands.</p>\n<blockquote>\n<pre><code> ERROR=$?\nfi\nrm $TMPFILE 2> /dev/null\n</code></pre>\n</blockquote>\n<p>Why didn't we remove the temporary file if we exited early?</p>\n<blockquote>\n<pre><code>exit $ERROR\n</code></pre>\n</blockquote>\n<p>We wouldn't need to store the error if we made removing the temp-file an exit trap.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#!/bin/sh\n# Compiles and runs C++ source code. A corresponding file\n# ending with .in will be used as input, if present\n\nset -eu\n\nif [ $# -ne 1 ] || [ -z "$1" ]\nthen\n echo "Usage: $0 SOURCE"\n exit 1\nfi\n\nexecutable=$(mktemp -t run-cpp.XXXXXXXXXX)\ntrap 'rm $executable' EXIT\n\ngreen=$(tput setaf 2)\nnormal=$(tput sgr0)\n\necho "${green}Compiling...${normal}"\ng++ -o "$executable" -std=c++17 -O3 \\\n -Wall -Wextra -Wwrite-strings -Wno-parentheses \\\n -Wpedantic -Warray-bounds -Weffc++ \\\n "$1"\n\necho "${green}Running...${normal}"\ninput=${1%.*}.in\nif [ -f "$input" ]\nthen exec <"$input"\nfi\n\n"$executable"\n</code></pre>\n<p>You might also be interested in <a href=\"https://codereview.stackexchange.com/q/165861/75307\">my approach to a similar situation</a>, which uses Make rather than shell.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:37:37.707",
"Id": "253316",
"ParentId": "253140",
"Score": "4"
}
},
{
"body": "<p>The other review makes most of the points I would have, so I'll just add three more points.</p>\n<h2>Don't ignore the return value of <code>mktemp</code></h2>\n<p>For security reasons, <code>mktemp</code> will refuse to create a file if the name it has chosen already exists. This is to avoid <a href=\"https://owasp.org/www-community/vulnerabilities/Insecure_Temporary_File\" rel=\"nofollow noreferrer\">security flaws</a>. You will probably be saved because <code>/tmp/</code> should always have the sticky bit set, preventing users other than the owner of the file from deleting it. Still, I'd recommend a construction like this instead:</p>\n<pre><code>TMPFILE=$(mktemp /tmp/example.XXXXXXXXXX) || exit 1\n</code></pre>\n<p>Another option would be to omit the output file name and just allow the compiler to create <code>a.out</code> in the local directory, bypassing the issue entirely as well as shortening your script.</p>\n<h2>Use the result directly instead of testing <code>$?</code></h2>\n<p>The code includes this:</p>\n<pre><code>g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE\nif [ $? -eq 0 ]; then\n</code></pre>\n<p>But this could be made a little more direct:</p>\n<pre><code>if g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE ; then\n</code></pre>\n<p>Or perhaps better, see the next suggestion.</p>\n<h2>Consider using functions</h2>\n<p>I'd suggest it may be useful to create functions, such as <code>run</code> and <code>compile</code> to make the script a little easier to understand. For example:</p>\n<pre><code>compile() {\n WARNING_FLAGS="-Wuninitialized -Wmaybe-uninitialized"\n g++ "$1" -std=c++17 $WARNING_FLAGS -O3 -o "$2"\n}\n\nif compile "$FILE" "$TMPFILE"; then\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T15:03:18.660",
"Id": "499606",
"Score": "1",
"body": "Also, this [alternative approach](https://codereview.stackexchange.com/questions/124479/from-q-to-compiler-in-less-than-30-seconds) uses Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T16:34:20.970",
"Id": "499609",
"Score": "0",
"body": "I did mention that testing `$?` is an antipattern. But your explanation is more helpful, since it shows the fix, whereas mine is hidden in the rewritten script. (In fact, it's not even there, due to `set -e`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T15:00:59.037",
"Id": "253343",
"ParentId": "253140",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253316",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T18:22:46.010",
"Id": "253140",
"Score": "6",
"Tags": [
"c++",
"bash",
"gcc"
],
"Title": "Bash script - compile and run c++ code for coding competitions"
}
|
253140
|
<p>I have been learning firebase with react js lately and I have stumbled upon a situation where I think my code is somewhat not okay.</p>
<pre><code> const handleFormSubmit = (e) => {
e.preventDefault();
if(props.addOrEdit(values).path.pieces_[0] === "Contacts"){
setValues(initialFieldValues);
} else {
}
};
</code></pre>
<p>The aim here is to validate if I am inserting the data into the right database, and then insert but there are a couple of anomalies here. Please note that I am not calling <code>addOrEdit</code> method anywhere else except for this part.</p>
<ol>
<li>In the if/else block the code is getting inserted while it should be comparing.</li>
<li>I think what I have written is a patchwork.</li>
</ol>
<p>The code works as it should but the quality of it merely good enough.</p>
<p>Kindly add your comments on it, how can it be improved in the aspect of validating and inserting the data.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T19:01:50.350",
"Id": "253141",
"Score": "0",
"Tags": [
"react.js",
"firebase"
],
"Title": "Validating firebase insert"
}
|
253141
|
<pre><code>/* Generates permutations over an array of integers by backtracking.
*
* chain[] Status stack with box index per level
* box[] Marks pieces available for next permutation
*
* The candidate_next() is a filter or wrapper to box_next(). It is needed
* to prune the huge tree (26! = 10^25 final permutations). It also simulates
* the way to place a constraint satisfaction test (does the current chain
* plus the new piece fit?).
*
* If show_chain() is added higher up in the main while loop,
* then the growing and shrinking chains can be observed.
*
* With only 5 levels ("ABCDE") the candidate testing can be set to always return.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LEVELS 26
char pieces[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int chain[LEVELS];
int box[LEVELS];
const int TOPLEVEL = LEVELS - 1;
/* Prints the chain up to level "lvl", translating index to letter. */
void show_chain(int lvl) {
for (int i = 0; i <= lvl; i++ )
printf("%c", pieces[chain[i]]);
printf(" ");
}
/* Returns lowest *present* index *above* "lim", -1 if fail. */
int box_next(int lim) {
while (++lim < LEVELS)
if (box[lim]) {
box[lim] = 0;
return lim;
}
return -1;
}
/* Returns first index in box[] above "start" that passes some tests */
/* "lvl" is only here for tweaking probability */
int candidate_next(int start, int lvl) {
int new;
while (start < LEVELS) {
new = box_next(start);
if (new == -1)
return -1;
/* Test the new candidate -- somehow, or not at all */
//return new;
if (lvl == 0)
return new;
if (rand() > RAND_MAX*0.86 + RAND_MAX*0.11 * lvl*lvl/(LEVELS*LEVELS))
return new;
/* Failed, put back and continue above */
box[new] = 1;
start = new;
}
/* Should only happen with a careless call */
return -1;
}
int main() {
srand(time(NULL));
/* Fill the box */
for (int i = 0; i < LEVELS; i++)
box[i] = 1;
int new;
int loops = 1;
int lvl = -1;
int btrack = 0;
/* The loop starts at "lvl" underground (-1), non-backtracking ("btrack" is 0).
* It breaks when it reaches same level *backways*
*/
while (loops++) {
if (!btrack) {
//show_chain(lvl); printf("\n");
if (lvl < TOPLEVEL) {
new = candidate_next(-1, lvl+1); /* Search all (-1) */
if (new >= 0) {
chain[++lvl] = new; /* Next Level UP/forward and done */
continue;
}
} else {
show_chain(lvl); printf("*\n"); /* On TOPLEVEL. Print before tracking back */
}
btrack = 1;
box[chain[lvl--]] = 1; /* Back Down one level */
continue;
}
/* Backtracking */
if (lvl == -1)
break;
box[chain[lvl]] = 1;
new = candidate_next(chain[lvl], lvl); /* Search only above current */
if (new >= 0) {
chain[lvl] = new; /* Stay, Replace this node, Turn around Forwards */
btrack = 0;
} else {
lvl--; /* Go back, still pointing backwards */
}
}
printf("%9d\n", loops);
}
</code></pre>
<p>A typical output is:</p>
<pre><code> IRMPGALUBWJKZSYHXTCQFDVOEN *
OZBPDAMKULGVIFWRCETHSYQXNJ *
ZERKJTCSGBUHFWNMXDPIOQAVYL *
10915520
</code></pre>
<p>I adjusted the probability <code>if (rand() > RAND_MAX*0.86 + RAND_MAX*0.11 * lvl*lvl/(LEVELS*LEVELS))</code> to give a large number of branch visits (10 million), but only a few that reach maximum level of 26. It takes one second.</p>
<p>I think this is quite a generic and flexible algorithm, but I can not find any other
examples - if, then they use recursion.</p>
<p>The while loop in <code>main()</code> does have some "if"s on <code>lvl</code> and <code>btrack</code>, and these variables are also modified in different ways in different branches.</p>
<p>But this is all needed to cover the combinations <code>up/down x success/fail</code> plus the check for min. and max. level, isn't it?</p>
<p>Would a recursive solution "look better"?</p>
<p>Is there another way to <em><strong>backtrack</strong></em>? Or can the same incremental permutations be generated without?</p>
<hr />
<p>With <code>#define LEVELS 5</code> and printing every forward chain</p>
<pre><code>A
AB
ABC
ABCD
ABCDE *
ABCE
ABCED *
ABD
ABDC
ABDCE *
ABDE
ABDEC *
ABE
ABEC
ABECD *
ABED
ABEDC *
AC
...
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:04:05.280",
"Id": "253142",
"Score": "1",
"Tags": [
"c",
"combinatorics",
"backtracking"
],
"Title": "Permutations of the alphabet with backtracking"
}
|
253142
|
<p>I've made a major update to my Noughts & Crosses program, this ISN'T a duplicate! I know it's not good to use system("pause") and system("cls"), however, I just wanted to make the console screen more readable so resorted to these methods to achieve this. I would like feedback on how well I've used std::shared_ptr, the std::algorithm library, and any suggestions on how I can improve. I have also returned a std::shared_ptr null-ptr. A lot of what I've done has been intuitive and I'm unsure if what I've done is the best way to go about doing certain things. If you run this program, please, just press enter where needed, it's two robots playing against each other. If you'd like to manually play it, please change the arguments passed into the game.play function to a human.</p>
<pre><code>#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
#include <random>
#include <ctime>
#include <cstdlib>
#include <ranges>
class Player
{
private:
std::string m_type;
unsigned char m_name;
int m_winTally;
int m_drawed;
public:
std::string GetType()const { return m_type; };
Player(unsigned char name, std::string&& type = "Player") :m_name(name), m_type(type), m_winTally(0), m_drawed(0) {}
virtual unsigned char GetName()const { return m_name; }
virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move) = 0;
virtual int NextMove(std::map<int, unsigned char>& board) = 0;
virtual ~Player() = default;
void AddWinToTally() { m_winTally++; }
void Drawed() { m_drawed++; }
int GetGameWins() const { return m_winTally; }
int GetDraws() const { return m_drawed; }
};
class Human : public Player
{
public:
Human(unsigned char name) :Player(name, "Human") {}
virtual int NextMove(std::map<int, unsigned char>& board) override {
int move;
std::cout << "Enter a number on the board (e.g. 1): ";
std::cin >> move;
return move;
}
virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move)
{
auto validSquare = std::find_if(board.begin(), board.end(), [&](auto pair) {
return pair.first == move;
});
if (validSquare != board.end())
{
if (validSquare->second == '-')
{
validSquare->second = Player::GetName();
return true;
}
else
{
std::cout << "This square has already been claimed. Choose a different square!" << std::endl;
return false;
}
}
return false;
}
virtual ~Human() = default;
};
class Robot : public Player
{
public:
Robot(unsigned char name) :Player(name, "Robot") {}
bool CheckAvailability(std::map<int, unsigned char>& board, int number, std::vector<int>& keys) {
for (auto& cell : board) {
if (cell.first == number) {
if (cell.second == '-') {
return true;
}
}
}
std::remove_if(keys.begin(), keys.end(), [&](auto& key) {
return key == number;
});
return false;
}
virtual int NextMove(std::map<int, unsigned char>& board) override
{
std::vector<int>number = { 1,2,3,4,5,6,7,8,9 };
int randNum = 0;
std::srand(std::time(0));
do
{
randNum = rand() % 9 + 1;
}
while (CheckAvailability(board, randNum, number) == false);
return randNum;
}
virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move)
{
auto validSquare = std::find_if(board.begin(), board.end(), [&](auto pair) {
return pair.first == move;
});
if (validSquare != board.end())
{
if (validSquare->second == '-')
{
validSquare->second = Player::GetName();
return true;
}
else
{
std::cout << "This square has already been claimed. Choose a different square!" << std::endl;
return false;
}
}
return false;
}
virtual ~Robot() = default;
};
class NoughtsAndCrosses
{
private:
//std::vector<Player*> m_p;
std::map<int, unsigned char>board;
void DisplayBoard()
{
for (auto const& cell : board)
{
if (cell.first % 3 == 1) {
std::cout << "\n\n";
}
if (cell.second != '-') {
std::cout << cell.second << " ";
}
else
{
std::cout << cell.first << " ";
}
}
std::cout << "\n\n";
}
auto CheckForAWinner(std::map<int, unsigned char>& board, std::shared_ptr<Player>& player)
{
if (board.at(1) == player->GetName() && board.at(2) == player->GetName() && board.at(3) == player->GetName()) {
return true;
}
else if (board.at(4) == player->GetName() && board.at(5) == player->GetName() && board.at(6) == player->GetName()) {
return true;
}
else if (board.at(7) == player->GetName() && board.at(8) == player->GetName() && board.at(9) == player->GetName()) {
return true;
}
else if (board.at(1) == player->GetName() && board.at(4) == player->GetName() && board.at(7) == player->GetName()) {
return true;
}
else if (board.at(2) == player->GetName() && board.at(5) == player->GetName() && board.at(8) == player->GetName()) {
return true;
}
else if (board.at(3) == player->GetName() && board.at(6) == player->GetName() && board.at(9) == player->GetName()) {
return true;
}
else if (board.at(1) == player->GetName() && board.at(5) == player->GetName() && board.at(9) == player->GetName()) {
return true;
}
else if (board.at(7) == player->GetName() && board.at(5) == player->GetName() && board.at(3) == player->GetName()) {
return true;
}
else
{
return false;
}
}
bool CheckForDraw(std::map<int, unsigned char>& board) {
return std::all_of(board.begin(), board.end(), [&](auto& pair) {return pair.second != '-'; });
}
public:
NoughtsAndCrosses()
{
board = { std::make_pair(1,'-'),std::make_pair(2,'-'),std::make_pair(3,'-'),
std::make_pair(4,'-'),std::make_pair(5,'-'),std::make_pair(6,'-'),
std::make_pair(7,'-'),std::make_pair(8,'-'),std::make_pair(9,'-') };
}
void ResetBoard() {
std::for_each(board.begin(), board.end(), [&](auto& pair) {
pair.second = '-';
});
}
auto play(std::shared_ptr<Player>& p1, std::shared_ptr<Player>& p2)
{
int currentPlayer = 1;
bool isWinner = false;
bool isDraw = false;
std::vector<std::shared_ptr<Player>>m_player = { p1, p2 };
do
{
currentPlayer = (currentPlayer + 1) % 2;
do
{
system("cls");
std::cout << m_player.at(currentPlayer)->GetType() << ": " << m_player.at(currentPlayer)->GetName() << " turn: " << std::endl;
DisplayBoard();
system("pause");
}
while (m_player.at(currentPlayer)->ClaimSquare(board, m_player.at(currentPlayer)->NextMove(board)) == false);
//std::cout << "\nPress enter to make the robot move. . .";
//std::cin.get();
//system("cls");
} while (CheckForDraw(board) == false && (isWinner = CheckForAWinner(board, m_player.at(currentPlayer))) == false);
if (isWinner == true)
{
return m_player.at(currentPlayer);
}
m_player.at(0)->Drawed();
m_player.at(1)->Drawed();
DisplayBoard();
ResetBoard();
return std::shared_ptr<Player>(nullptr);
}
};
int main() {
std::shared_ptr<Player> human1 = std::make_shared<Human>('O');
std::shared_ptr<Player> human2 = std::make_shared<Human>('X');
std::shared_ptr<Player> robot1 = std::make_shared<Robot>('O');
std::shared_ptr<Player> robot2 = std::make_shared<Robot>('X');
std::vector<std::shared_ptr<Player>>player = { robot1, robot2 };
NoughtsAndCrosses game;
int round = 3;
int roundCount = 0;
std::shared_ptr<Player>winner;
do
{
int gameCount = 1;
int totalGamesinRound = 3;
std::cout << "START GAME!\n";
system("pause");
system("cls");
std::cout << "\nROUND " << ++roundCount << ". . .\n";
do
{
std::cout << "Game " << gameCount << " of round " << roundCount << "\n";
winner = game.play(robot1, robot2);
if (winner != std::shared_ptr<Player>(nullptr))
{
std::cout << "Winner of game " << gameCount << " is type: " << winner->GetType() << ": " << winner->GetName() << "\n";
winner->AddWinToTally();
}
else
{
system("cls");
std::cout << "Game " << gameCount << " is a draw!\n";
}
gameCount++;
totalGamesinRound--;
}
while (totalGamesinRound != 0);
/* std::cout << "Game 2: Human vs Robot\n";
game.play(robot1, robot1);*/
std::cout << "Wins for " << robot1->GetType() << ": Player : " << robot1->GetName() << " - " << robot1->GetGameWins() << "\n";
std::cout << "Wins for " << robot2->GetType() << ": Player : " << robot2->GetName() << " - " << robot2->GetGameWins() << "\n";
std::cout << "Drawed: " << robot1->GetDraws() << "\n";
auto playerWithMostWins = std::max_element(player.begin(), player.end(),
[](const auto& lhs, const auto& rhs)
{
return lhs->GetGameWins() < rhs->GetGameWins();
});
std::cout << "Winner of round " << roundCount << " is " << playerWithMostWins->get()->GetName() << "\n";
round--;
}
while (round != 0);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T23:00:28.493",
"Id": "499095",
"Score": "0",
"body": "Well, I’ve used the std::algorithm library so I would say C++ 17."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T23:12:22.360",
"Id": "499096",
"Score": "0",
"body": "I’ve changed it to C++ 17."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T08:51:06.640",
"Id": "499129",
"Score": "0",
"body": "Just so you know, the algorithms library existed even before C++11 :)"
}
] |
[
{
"body": "<h2>Make <code>system()</code> more portable</h2>\n<p>The reason <code>system("cls")</code> isn't portable is because the command on windows is <code>cls</code> but on most other platforms it is <code>clear</code>. You can <a href=\"https://stackoverflow.com/questions/142508/how-do-i-check-os-with-a-preprocessor-directive\">check for the OS</a> using certain macros.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void clear_screen() {\n#ifdef _WIN32 // windows\n system("cls");\n#else // macOS and linux\n system("clear");\n#endif //_WIN32\n}\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/1449324/how-to-simulate-press-any-key-to-continue\">A similar situation for <code>pause</code></a></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void pause() {\n#ifdef _WIN32 // windows\n system("pause");\n#else // macOS and linux\n system("read")\n#endif //_WIN32\n}\n</code></pre>\n<blockquote>\n<p>I know it's not good to use system("pause") and system("cls") however, I just wanted to > make the console screen more readable</p>\n</blockquote>\n<p>It isn't <em>not good</em>, but <a href=\"http://www.cplusplus.com/articles/j3wTURfi/\" rel=\"nofollow noreferrer\">pure evil</a></p>\n<hr />\n<h1>Code structure</h1>\n<p>There is a lot of room for improvement here. Let me start with the simplest one</p>\n<ul>\n<li><strong>Unecessary getters and setters!</strong></li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Player\n{\nprivate:\n std::string m_type;\n unsigned char m_name;\n int m_winTally;\n int m_drawed;\n\npublic:\n std::string GetType()const { return m_type; };\n Player(unsigned char name, std::string&& type = "Player") :m_name(name), m_type(type), m_winTally(0), m_drawed(0) {}\n virtual unsigned char GetName() const { return m_name; }\n virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move) = 0;\n virtual int NextMove(std::map<int, unsigned char>& board) = 0;\n\n void AddWinToTally() { m_winTally++; }\n void Drawed() { m_drawed++; }\n int GetGameWins() const { return m_winTally; }\n int GetDraws() const { return m_drawed; }\n};\n</code></pre>\n<p>How about</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Player\n{\npublic:\n std::string m_type;\n unsigned char m_name;\n int m_winTally;\n int m_drawed;\n\n Player(unsigned char name, std::string&& type = "Player")\n : m_name(name), m_type(type), m_winTally(0), m_drawed(0)\n {}\n\n virtual unsigned char GetName() const { return m_name; }\n virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move) = 0;\n virtual int NextMove(std::map<int, unsigned char>& board) = 0;\n};\n\n</code></pre>\n<hr />\n<ul>\n<li><code>ClaimSquare()</code></li>\n</ul>\n<p>Your function <code>ClaimSquare()</code> is virtual and has been overridden in both of the derived classes, let's look at them</p>\n<h2><code>Human</code></h2>\n<pre class=\"lang-cpp prettyprint-override\"><code> virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move)\n {\n auto validSquare = std::find_if(board.begin(), board.end(), [&](auto pair) {\n return pair.first == move;\n });\n if (validSquare != board.end())\n {\n if (validSquare->second == '-')\n {\n validSquare->second = Player::GetName();\n return true;\n }\n else\n {\n std::cout << "This square has already been claimed. Choose a different square!" << std::endl;\n return false;\n }\n }\n return false;\n }\n</code></pre>\n<h2><code>Robot</code></h2>\n<pre class=\"lang-cpp prettyprint-override\"><code> virtual bool ClaimSquare(std::map<int, unsigned char>& board, int move)\n {\n auto validSquare = std::find_if(board.begin(), board.end(), [&](auto pair) {\n return pair.first == move;\n });\n if (validSquare != board.end())\n {\n if (validSquare->second == '-')\n {\n validSquare->second = Player::GetName();\n return true;\n }\n else\n {\n std::cout << "This square has already been claimed. Choose a different square!" << std::endl;\n return false;\n }\n }\n return false;\n }\n</code></pre>\n<ul>\n<li>They both are the EXACT same. The point of polymorphism is to reuse the same code i.e reduce repetition. Here you have done the EAXCT opposite, introduced more repetition.</li>\n<li>Why is it <code>virtual</code>?</li>\n<li>On the contrary, it shouldn't be a part of the player class. It should be a part of your <code>NoughtsAndCrosses</code> since that contains the game board. The same applies to <code>CheckAvailibility()</code>. What does that have to do with a player? Nothing at all. All of that belongs to <code>NoughtsAndCrosses</code></li>\n</ul>\n<p>With all of that being said, here is what I think it should be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Player {\n \n char symbol;\n const std::string type;\n int wins;\n int draws;\n\n virtual int nextMove() const = 0;\n \n Player (const char symbol, std::string&& type)\n : symbol(symbol), type(std::move(type)), wins(0), draws(0)\n {}\n};\n// Edit: As pointed out by G.Sliepen, Player::type remains unchanged, therefore `const`\n\nstruct Human : public Player {\n Human(const char symbol)\n : Player(symbol, "Human")\n {}\n\n int nextMove() const override {\n // get move from STDIN and return \n }\n};\n\nstruct Robot : public Player {\n Robot(const char symbol)\n : Player(symbol, "Robot")\n {}\n\n int nextMove() const override {\n // generate random number and return \n }\n};\n</code></pre>\n<p>Using this, your game class can have two objects, one player and one human, and you can switch between them when you need to.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Game{\n Player* one;\n Player* two;\n\n Player* turn; // either points to player one or player two, switch accordingly\n\n\n \npublic:\n Game(Player& one, Player& two)\n : one(&one), two(&two), turn(&one)\n {}\n\n // board, checkWin(), checkDraw()....\n // if player one wins -> one.wins++\n // if player two wins -> two.wins++\n}\n</code></pre>\n<p>With that, you can easily create games, human vs human, robot vs human, robot vs robot</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main() {\n Human h('x');\n Human h2('o');\n \n Game game1(h, h2) // human vs human, can be anything else\n}\n</code></pre>\n<p>No need for <code>shared_ptr</code> here.</p>\n<p>With all that being said, I suggest you create a <code>gameloop()</code> function for the <code>Game</code> class that automatically plays the game. That is calling <code>nextMove()</code> until someone wins.</p>\n<hr />\n<h2>Represent the board with <code>std::array</code></h2>\n<p>I'm not sure why you chose <code>std::map</code> to represent the board. Using <code>std::array</code> here is enough and will simplify everything further.</p>\n<hr />\n<p>Pseudo code</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Game\n{\n Player* one;\n Player* two;\n\n Player* turn; // either points to player one or player two\npublic:\n \n\n Game(Player& one, Player& two)\n : one(&one), two(&two), turn(&one)\n {}\n\n\n void gameloop(){\n for(;;){\n clear_screen();\n playerMove();\n if (win())\n ;// bla bla\n else if (draw())\n ; // bla bla bla\n\n }\n }\n\nprivate:\n bool moveIsValid(const int move){\n // check if square is occupied, or out of range and return accordingly \n }\n\n void performMove(const int move){\n // perform move on the board \n }\n\n void playerMove(){\n int move = -1;\n\n for(;;){\n move = turn->nextMove();\n if (moveIsValid(move))\n break;\n }\n performMove(move);\n switchPlayers();\n }\n\n void switchPlayers(){\n turn = turn == one ? two : one;\n }\n\n char win(){\n // self explanatory\n }\n bool draw(){\n // self explanatory\n }\n\n\n std::array < char, 9 > board;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T08:54:31.973",
"Id": "499130",
"Score": "1",
"body": "If you are using public member variables instead of getters and setters, you should make the ones that should not change after construction `const`. Of course they could've been made `const` even if you use getters and setters, but then it's slightly less important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T09:04:22.853",
"Id": "499131",
"Score": "0",
"body": "@G.Sliepen are you referring to `type` in `Player`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T09:42:52.450",
"Id": "499132",
"Score": "0",
"body": "Both `m_type` and `m_name`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:00:14.830",
"Id": "499136",
"Score": "1",
"body": "Thanks so much for reviewing my program! I'm now analysing all you have mentioned! I shall mark as answer after I have considered whether I need to ask any questions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:19:45.197",
"Id": "499138",
"Score": "0",
"body": "@G.Sliepen yes I changed type, but shouldn't you be able to change name? So you could reuse the same object with a different symbol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:22:59.933",
"Id": "499181",
"Score": "1",
"body": "@AryanParekh If it's desired to be able to change `m_name`, then of course it shouldn't be `const`. But in OP's code there was no way to change it after construction, that's why I assumed it was meant to be constant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:54:35.610",
"Id": "499247",
"Score": "0",
"body": "How am I supposed to switch between the two players if they’re no longer in a vector? Also. Why can’t the player be passed through the play function? It will save me having to create a new instance of game when I can just reuse the same instance and pass in different types of the parent class “Player” achieved my polymorphism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:59:53.417",
"Id": "499248",
"Score": "0",
"body": "Also, why do I want to use an std::array? I need the std::map to represent firstly the number they want to choose and in the second part, the ‘-‘. A map allows me to achieve this whereas with a array I’ll need to create probably another array just to store the numbers then another array to to store the X or the O. A map allows me to do both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:54:17.313",
"Id": "499252",
"Score": "0",
"body": "@GeorgeAustinBradley read my implementation again, switching between players is already shown"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:56:47.650",
"Id": "499253",
"Score": "0",
"body": "@GeorgeAustinBradley creating a play function is the same here too, you just have to change player one and two.The problem with your original code is that there is no good structure. also, have you heard to of array indexing? That should be enough for your goal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:59:37.180",
"Id": "499254",
"Score": "0",
"body": "@GeorgeAustinBradley moreover, that's not the purpose of std:: vector"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T08:01:45.927",
"Id": "499270",
"Score": "1",
"body": "Oh crumbs, I missed the switch player part. Thanks very much for reviewing my program. I have learned so much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T11:03:59.347",
"Id": "499289",
"Score": "0",
"body": "You didn't answer my question passing the players through the play function. Can you address this please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T11:04:56.097",
"Id": "499290",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117057/discussion-between-aryan-parekh-and-george-austin-bradley)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T13:34:42.000",
"Id": "499747",
"Score": "0",
"body": "Hi Aryan Parekh, I followed along with the psudocode you provided and did my best to implement it. Can you have a look at it for me? I'd greatly appreciate feedback and anything else you suggest! Click the following link to see it: https://codereview.stackexchange.com/a/253421/214082"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T16:02:20.967",
"Id": "499758",
"Score": "0",
"body": "@GeorgeAustinBradley you can post a new question, everyone can contribute"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T16:53:45.697",
"Id": "499767",
"Score": "0",
"body": "But I just want feedback from yourself as you’re the one who suggested the design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T16:54:21.657",
"Id": "499768",
"Score": "0",
"body": "Don’t want to ask a new question as just want feedback from the person who suggested me the design..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T18:20:15.393",
"Id": "499773",
"Score": "0",
"body": "@GeorgeAustinBradley I get it, not that I have a problem with that, but if you ask a new question then everyone can contribute! Some things which I can't spot other's can. There's nothing wrong with posting an extra follow up so feel free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T18:27:11.687",
"Id": "499774",
"Score": "0",
"body": "So was forced to by a moderator, here’s the link to the new question. https://codereview.stackexchange.com/q/253428/214082"
}
],
"meta_data": {
"CommentCount": "20",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T08:02:47.540",
"Id": "253166",
"ParentId": "253144",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253166",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T20:50:14.947",
"Id": "253144",
"Score": "2",
"Tags": [
"object-oriented",
"tic-tac-toe",
"c++17",
"classes",
"inheritance"
],
"Title": "Noughts & Crosses (Final Version)"
}
|
253144
|
<p>I've been messing around with merge sort. Instead of doing a recursive division of the array I chose to keep keep track of the middle index of every three numbers. Using the index of the middle number, it sorts the numbers directly around it and then merges the consecutive portions of the array.I'm having trouble figuring out the time complexity of the sorting portion. I know it's worse than actual Merge sort, I think it's either O(2^n) or O(n^2). How do I analyze the time complexity of this sorting algorithm?</p>
<pre><code>
import java.util.Random;
public class modifiedMergeSort {
/**
* Merges two sorted portions of the array (Same algorithm as conventional MergeSort)
* @param arr the array to be sorted
* @param p beginning index of first array
* @param q last index of first array
* @param r last index of second array
*/
void merge(int arr[], int p, int q, int r) {
// Create L ← A[p..q] and M ← A[q+1..r]
int n1 = q - p + 1;
int n2 = r - q;
int[]L = new int[n1];
int[]M = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = p;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
/**
* Uses a set of three numbers and keeps track of the index of the middle number
* Sorts each set of 3 numbers using the index of the middle number to make comparisons with the number at index i+1 and i-1
* @param array the array to be sorted
*/
public void triSort(int[] array){
/**
* Figure out how many indexes you need to keep track of
*/
int pointersNeeded;
if(array.length % 3 == 0){
pointersNeeded = array.length / 3;
}else {
pointersNeeded = (array.length / 3) + 1;
}
/**
* Find the pointers for every set of three and place in an array
*/
int[] pointerArray = new int[pointersNeeded];
for (int i = 0; i < pointersNeeded; i++){
if ((1 + (i * 3)) < array.length - 1){
pointerArray[i] = 1 + (i * 3);
}else {
pointerArray[i] = array.length - 1;
}
}
/**
* Sorts each set of 3 numbers
*/
for (int pointer: pointerArray) {
if(pointer < array.length-1){
if (array[pointer] < array[pointer-1])
{
swap(array, pointer, pointer-1);
}
if (array[pointer+1] < array[pointer])
{
swap(array, pointer, pointer + 1);
if (array[pointer] < array[pointer-1])
{
swap(array, pointer, pointer - 1);
}
}
}else {
if (((array.length - 1) - pointer) == 0){
System.out.println();
swap(array, pointer-1, pointer);
}
}
}
int beg = 0;
int mid;
int right;
/**
* Merges two subset of the array to make 1 set and then moves the middle and right indexes to the next subset for merging
*/
for(int i = 0; i < pointerArray.length - 1; i++){
mid = pointerArray[i] + 1;
right = mid + 3;
if (pointerArray[i] >= (array.length - 1) || right > (array.length - 1)) {
right = array.length - 1;
}
merge(array, beg, mid, right);
}
}
/**
* Swaps two numbers in the array
* @param array the array
* @param index1 the index of the first number to swap
* @param index2 the index of the second number to swap
*/
public void swap(int[] array, int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
/**
* Prints array
* @param arr the array
*/
static void printArray(int arr[]) {
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
/**
* Make an array with size 100,000
*/
int[] arr = new int[100000];
/**
* Fill array with nums 0-999,999
*/
for (int i = 0; i < 100000; i++){
arr[i] = i;
}
/**
* Randomly shuffle numbers in array
*/
Random rand = new Random();
for (int i = 0; i < arr.length; ++i) {
int index = rand.nextInt(arr.length - i);
int temp = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = arr[index];
arr[index] = temp;
}
modifiedMergeSort ob = new modifiedMergeSort();
/**
* Sort
*/
long start = System.currentTimeMillis();
ob.triSort(arr);
long end = System.currentTimeMillis();
System.out.println("Sorted in: " + (end-start) + "ms");
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T10:50:14.150",
"Id": "499287",
"Score": "0",
"body": "@superbrain No I'm leaning more towards O(n^2)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T22:24:17.457",
"Id": "253148",
"Score": "1",
"Tags": [
"java",
"complexity",
"mergesort"
],
"Title": "Sorting Algorithm using Modified Merge sort"
}
|
253148
|
<p>I have attempted to do Model View Controller in Python for learning. First, I am not sure if dictionaries are faster than lists for about N = 30 (20 to 40) items. Second, how maintainable is this design since I got abstraction but not very much encapsulation. The abstraction comes from abstracting towards to the domain classes.</p>
<p>The classes and their purposes:</p>
<p>Table Model is a data class in the domain model.<br />
Total Price Model is an algorithm to compute the total price of Table Models.
Table File handles File I/O of and sets the fields of Table Model.
Table View handles user I/O which is currently command line.
main is a driver program to run the code.</p>
<pre><code>
class TableModel:
"""
Data Model of a table
"""
def __init__(self, key :int, name: str, price_cents: int) -> None:
"""
:param key: computer generated number
:param name: name of this what
:param price_cents: price in USD, in cents, of this what
"""
self.key = key
self.name = name
self.price_cents = price_cents
def __str__(self) -> str:
"""
Input: None \n
Output: string to allow for debuging (print object out) \n
"""
string = "key: " + str(self.key) + "\n"
string = string + "name: " + self.name + "\n"
string = string + "price_cents: " + str(self.price_cents) + "\n"
return string
class TotalPriceModel:
"""
Algorithm for total price
"""
def total_price_cents(self, table_models:dict) -> int:
"""
:param table_models: the table models
Output: total price
"""
cents = 0
for key in table_models:
cents = cents + table_models[key].price_cents
return cents
class TableFile:
"""
Models the file of table
Note: this is a text file (for now anyways)
"""
def __init__(self, table_models:[TableModel]) -> None:
"""
:param table_models: dict, keys are str(table_model.key) and val are the talbe_model
"""
self.table_models = table_models
def to_file(self) -> None:
"""
Input: None \n
Output: None \n
Note: puts info into file \n
"""
file = open("save_file.txt", "r+")
name = ""
price_cents = ""
key = ""
for key in range(self.table_models):
name = self.table_models[key].name
price_cents = str(self.table_models[key].price_cents)
key = str(self.table_models[key].key)
file.write(name + "#" + price_cents + "#" + key)
file.close()
def from_file(self) -> None:
"""
Input: None \n
Output: None \n
Note: puts file info into this \n
"""
file = open("save_file.txt", "r+")
name = ""
price_cents = 0
key = 0
table_model = None
#use gen so that the extra space is less
for line in file.readlines():
name = line.split("#")[0]
price_cents = int(line.split("#")[1])
key = int(line.split("#")[2])
table_model = TableModel(key, name, price_cents)
self.table_models.append(table_model)
file.close()
def add(self, what:TableModel) -> None:
"""
:param what: what to add
Output: None
"""
self.table_models[str(what.key)] = what
def remove(self, key:int) -> None:
"""
:param key: key of the object to remove
Output: None \n
Note: if this not in the class, this results in nothing done
"""
if key in self.table_models:
del self.table_models[str(key)]
def change(self, table:TableModel) -> None:
"""
:param table: table that was changed using the computer \n
Output: None \n
"""
self.table_models[str(table.key)] = table
class TableView:
"""
User Input and User Output
"""
def __init__(self, tables_model:dict) -> None:
self.tables = tables_model
def render(self) -> None:
"""
Input: None \n
Output: None \n
Note: outputs to user
"""
print("Table View")
name = ""
price_cents = ""
for key in self.tables:
name = self.tables[key].name
price_cents = str(self.tables[key].price_cents)
print(name + " " + price_cents)
def change_event(self, table: TableModel) -> None:
"""
:param table: table that was changed using the computer
Output: None
"""
self.tables[str(table.key)] = table
def append_event(self, table: TableModel) -> None:
"""
:param table: table that was added within the computer
Output: None
"""
self.tables[str(table.key)] = table
def remove_event(self, table: TableModel) -> None:
"""
:param table: table that was removed from the computer
Output: None
"""
if str(table.key) in self.tables:
del self.tables[str(table.key)]
def main() -> None:
"""
Input: None \n
Output: None \n
Note: Runs the code, can test using std output \n
"""
table_model = TableModel(0, "Bob's Table", 0)
table_view = TableView({})
table_view.append_event(table_model)
table_view.render()
print(table_model)
print("hello world")
if __name__ == "__main__":
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-06T22:54:15.423",
"Id": "253150",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Model View Controller in Python"
}
|
253150
|
<p>This is a Clojurescript solution to parts 1 and 2 of <a href="https://adventofcode.com/2020/day/1" rel="nofollow noreferrer">Day 1</a> of Advent of Code 2020.</p>
<p>This code is written in Clojurescript to run on Node.js. It can be run simply using <a href="https://github.com/anmonteiro/lumo" rel="nofollow noreferrer">lumo</a> and this command: <code>lumo filename.cljs</code>.</p>
<p>Here's a short version of the problem statement:</p>
<p>Part 1. Given a list of numbers, find the two entries that sum to 2020 and then multiply those two numbers together.</p>
<pre><code>(ns day-01.core
(:require [clojure.string]))
(def fs (js/require "fs"))
(def entries
(set
(map js/parseInt
(clojure.string/split-lines
(.readFileSync fs "puzzle.input" "utf8")))))
(println (reduce *
(filter (fn [entry]
(contains? entries (- 2020 entry))) entries)))
</code></pre>
<p>Part 2: what is the product of the <strong>three</strong> entries that sum to 2020?</p>
<pre><code>;; Same boilerplate
(def match
(first
(filter #(= 2020 (reduce + %))
(for [x entries y entries z entries] [x y z]))))
(println (reduce * match))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T01:15:03.800",
"Id": "253153",
"Score": "1",
"Tags": [
"clojurescript"
],
"Title": "Advent of Code 2020 Day 1 in Clojurescript"
}
|
253153
|
<h1>My goal</h1>
<p>I am parsing from a string which contains <code>token:value</code> pairs into a type.</p>
<p>Example:</p>
<pre><code>mutable struct Foo
bar
baz
qux
end
function parse(str::AbstractString)::Foo
f = Foo()
bar_pattern = r"bar:(\w*)"
baz_pattern = r"baz:(\d*)"
qux_pattern = r"qux:(\w*)"
f.bar = match(bar_pattern, s)[1]
f.baz = match(baz_pattern, s)[1]
f.qux = match(qux_pattern, s)[1]
return d
end
</code></pre>
<h1>Problem</h1>
<p><strong>This works</strong> but only if the patterns are actually present. When <code>match</code> can't find the pattern, it returns <code>nothing</code>, which of course can't be indexed <code>[1]</code> or accessed with <code>captures</code>. The result is an error.</p>
<p><em>I want the fields of the returned struct to either get the matched result (the "capture") directly, or remain empty or set to <code>nothing</code>, should the match be unable to find the pattern.</em></p>
<p><strong>I could do</strong> something like this:</p>
<pre><code>function safeparse(str::AbstractString)::Foo
f = Foo()
bar_pattern = r"bar:(\w*)"
baz_pattern = r"baz:(\d*)"
qux_pattern = r"qux:(\w*)"
if !isnothing(match(bar_pattern, s))
f.bar = match(bar_pattern, s)[1]
end
if !isnothing(match(baz_pattern, s))
f.baz = match(baz_pattern, s)[1]
end
if !isnothing(match(qux_pattern, s))
f.qux = match(qux_pattern, s)[1]
end
return f
end
</code></pre>
<p>But that approach seems ugly and becomes verbose very quick if more/new patterns are introduced.</p>
<h1>Question</h1>
<p>Is there a nicer but readable way to achieve this?</p>
<p><em>Preferably</em> without combining/changing the regex patterns or <em>too</em> much regex magic, however I am
open to that route too if it is the only nice (less verbose) way. I am of course also open to general tips.</p>
<p>To keep things simple, just assume that the patterns my example is looking for only appear 0 or 1 times. <em>However</em> if the only way to make this nicer involves writing another function like <code>safematch</code> which does the check for nothing and returns the captured value or nothing, I would want <em>that</em> to also work with multiple matches somehow and stay a bit more general.</p>
|
[] |
[
{
"body": "<p>The easiest thing I can think of is to use <code>eachmatch</code> -- when there is no match at all, it returns an empty iterator:</p>\n<pre><code>julia> collect(eachmatch(r"(bar:(\\w*))", "bla bar:werfsd 1223 bar:skdf"))\n2-element Array{RegexMatch,1}:\n RegexMatch("bar:werfsd", 1="bar:werfsd", 2="werfsd")\n RegexMatch("bar:skdf", 1="bar:skdf", 2="skdf")\n\njulia> collect(eachmatch(r"(bar:(\\w*))", "bla "))\nRegexMatch[]\n</code></pre>\n<p>Then you can simply combine those into a dictionary, for example:</p>\n<pre><code>julia> Dict(re => [m[1] for m in eachmatch(re, s)] for re in patterns)\nDict{Regex,Array{T,1} where T} with 3 entries:\n r"qux:(\\w*)" => Union{Nothing, SubString{String}}[]\n r"baz:(\\d*)" => SubString{String}["33"]\n r"bar:(\\w*)" => SubString{String}["werfsd", "skdf"]\n</code></pre>\n<p>Without further information about how you want to organize your data structure when more then one value occurs, I can't really say more. Perhaps you can make use of <a href=\"https://docs.julialang.org/en/v1/base/collections/#Base.merge\" rel=\"nofollow noreferrer\"><code>merge</code></a>.</p>\n<p>Give types to struct fields, and don't use mutable structs unless necessary. Without knowing more, I suggest</p>\n<pre><code>struct Foo\n bar::Union{String, Nothing}\n baz::Union{String, Nothing}\n qux::Union{String, Nothing}\nend\nfunction Foo(;bar=nothing, baz=nothing, qux=nothing) \n return Foo(convert(Union{String, Nothing}, bar),\n convert(Union{String, Nothing}, baz),\n convert(Union{String, Nothing}, qux))\nend\n</code></pre>\n<p>which also takes care of converting the <code>SubString</code> from the regex match, in case this is relevant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T15:00:18.913",
"Id": "253663",
"ParentId": "253158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253663",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T02:57:09.013",
"Id": "253158",
"Score": "3",
"Tags": [
"parsing",
"regex",
"julia"
],
"Title": "Parsing values from string into struct using match in Julia"
}
|
253158
|
<p>When I first got the idea for creating a tiny mandelbrot renderer I knew It would be possible
since people having creating tiny demos for a while and that I would probably use a shader. However at that point I had no idea for how to even begin so for a while it was just something that in the back of my head untill recently when I had finaly gotten to learning opengl and realized that I finaly knew how I how do it and as a result I was able create a tiny Mandelbrot renderer. My main questions are in what ways can i improve the code in general and how can make the executable smaller since it is currently 1538 bytes and I don’t know how I can make smaller?</p>
<p><code>main.c</code></p>
<pre><code>// standard headers
#include <stdint.h>
#include <stdbool.h>
// windows headers
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#include <Windows.h>
// opengl headers
#define WGL_WGLEXT_PROTOTYPES
#include <gl/GL.h>
#include "glext.h"
#include "wglext.h"
#include "opengl.h"
// needed when we use floats
extern int _fltused;
int _fltused;
typedef struct Window
{
HDC device_context;
float aspect_ratio;
float scale, pos[2];
float smooth_scale, smooth_pos[2];
int32_t max_iterations;
} Window;
typedef enum Keys
{
KEY_W,
KEY_S,
KEY_A,
KEY_D,
KEY_PLUS1,
KEY_PLUS2,
KEY_MINUS1,
KEY_MINUS2,
KEY_UP,
KEY_DOWN,
KEY_R,
KEY_CTRL,
KEY_LENGTH // needed to keep track of number of keys
} Keys;
// NOTE: we could use GetWindowLongPtr and SetWindowLongPtr
// however this is much more easier
static Window global_window;
static bool keys[KEY_LENGTH];
static LRESULT CALLBACK WinProc(HWND window_handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_SYSKEYDOWN:
case WM_SYSCHAR:
case WM_SYSKEYUP:
{
} break;
case WM_SIZE:
{
// the width and height are stored in the low and high word of lParam respectively
LPARAM const width = lParam & 0xFFFF;
LPARAM const height = (lParam >> 16) & 0xFFFF;
// store the aspect ratio
global_window.aspect_ratio = (float)width / (float)height;
glViewport(0, 0, width, height);
} break;
case WM_QUIT:
case WM_CLOSE:
case WM_DESTROY:
{
ExitProcess(0);
}
case WM_KEYUP:
case WM_KEYDOWN:
{
bool const should_flip = ((lParam >> 30) & 0x1) == ((lParam >> 31) & 0x1);
if (should_flip)
{
switch (wParam)
{
case 'W':
{
keys[KEY_W] = !keys[KEY_W];
} break;
case 'S':
{
keys[KEY_S] = !keys[KEY_S];
} break;
case 'A':
{
keys[KEY_A] = !keys[KEY_A];
} break;
case 'D':
{
keys[KEY_D] = !keys[KEY_D];
} break;
case 'R':
{
keys[KEY_R] = !keys[KEY_R];
} break;
case VK_CONTROL:
{
keys[KEY_CTRL] = !keys[KEY_CTRL];
} break;
case VK_OEM_PLUS:
{
keys[KEY_PLUS1] = !keys[KEY_PLUS1];
} break;
case VK_ADD:
{
keys[KEY_PLUS2] = !keys[KEY_PLUS2];
} break;
case VK_OEM_MINUS:
{
keys[KEY_MINUS1] = !keys[KEY_MINUS1];
} break;
case VK_SUBTRACT:
{
keys[KEY_MINUS2] = !keys[KEY_MINUS2];
} break;
case VK_UP:
{
keys[KEY_UP] = !keys[KEY_UP];
} break;
case VK_DOWN:
{
keys[KEY_DOWN] = !keys[KEY_DOWN];
} break;
}
if (wParam == VK_ESCAPE) ExitProcess(0);
}
} break;
default:
{
return DefWindowProc(window_handle, message, wParam, lParam);
}
}
return 0;
}
static void create_opengl_context(HDC const device_context)
{
// same as:
// static PIXELFORMATDESCRIPTOR const pfd = {
// .nSize = sizeof(pfd),
// .dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW,
// .iPixelType = PFD_TYPE_RGBA,
// .cColorBits = 32,
// .cDepthBits = 32,
// .iLayerType = PFD_MAIN_PLANE
// };
SetPixelFormat(device_context, 9, NULL);
// create an opengl 3.3 context
HGLRC const opengl_context = wglCreateContext(device_context);
// make the new opengl context current and active
wglMakeCurrent(device_context, opengl_context);
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)
wglGetProcAddress("wglSwapIntervalEXT");
wglSwapIntervalEXT(0);
}
static void create_window(int32_t width, int32_t height)
{
// create a window class
static WNDCLASSA const wndclass = {
.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
.lpfnWndProc = &WinProc,
.lpszClassName = "0",
};
RegisterClassA(&wndclass);
// create a window
HWND const window_handle = CreateWindowA(wndclass.lpszClassName,
"",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
width, height, NULL, NULL,
NULL, NULL);
// create a device context
HDC const device_context = GetDC(window_handle);
// create an opengl context
create_opengl_context(device_context);
// load opengl extensions after creating an opengl context
load_extensions();
// setup global window
{
global_window.device_context = device_context;
global_window.aspect_ratio = (float)width / (float)height;
global_window.scale = 1.0f;
global_window.smooth_scale = 0.5f;
global_window.max_iterations = 200;
}
// show the window
ShowWindow(window_handle, SW_SHOWDEFAULT);
}
static unsigned int compile_shaders(char const *vertex_shader_source,
char const *fragment_shader_source)
{
// compile vertex shader
unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
// compile fragment shader
unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
// only needed for debugging
#ifdef DEBUG_MODE
{
int success;
char info_log[512];
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
if(success == GL_FALSE)
{
glGetShaderInfoLog(fragment_shader, sizeof(info_log),
NULL, info_log);
WriteFile((HANDLE)(STD_OUTPUT_HANDLE),
info_log, (DWORD)lstrlenA(info_log),
NULL, NULL);
}
}
#endif
// link the shaders
unsigned int shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
return shader_program;
}
static float lerp(float v0, float v1, float t)
{
return (1.0f - t) * v0 + t * v1;
}
__declspec(noreturn) void __stdcall entry(void)
{
create_window(800, 600);
// by making this smaller we can save space at the cost of readabilty
#define VERTEX_SHADER \
"#version 330\n" \
"out vec2 u;void main(){u=vec2[](vec2(0),vec2(1,0),vec2(0,1),vec2(1))[gl_VertexID];" \
"gl_Position=vec4(vec2[](vec2(-1,-1),vec2(1,-1),vec2(-1,1),vec2(1))[gl_VertexID],0,1);}" \
#define FRAGMENT_SHADER \
"#version 330\n" \
"#define B 200000.0\n" \
"out vec4 F;in vec2 u;uniform int I;uniform float A;uniform vec4 D;" \
"void main(){vec2 c=((u*2-1)*vec2(A,1)*D.y-D.zw);vec2 z=vec2(0);int i;" \
"for(i=0;i<I&&dot(z,z)<B;++i)z=vec2(z.x*z.x-z.y*z.y,z.x*z.y*2)+c;" \
"float s=sqrt((i-log2(log(dot(z,z))/log(B)))/float(I));" \
"F=(sin(D.x+20*s*vec4(1.5,1.8,2.1,0))*0.5+0.5)*float(i!=I);}" \
unsigned int const shader_program = compile_shaders(VERTEX_SHADER,
FRAGMENT_SHADER);
glUseProgram(shader_program);
float color_offset = 0.0f;
MSG msg;
for(;;)
{
// process events and messages
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
else
{
// pass uniforms
glUniform1f(glGetUniformLocation(shader_program, "A"),
global_window.aspect_ratio);
glUniform4f(glGetUniformLocation(shader_program, "D"), color_offset, global_window.smooth_scale,
global_window.smooth_pos[0], global_window.smooth_pos[1]);
glUniform1i(glGetUniformLocation(shader_program, "I"),
global_window.max_iterations);
// draw a quad
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// finally draw to the screen
SwapBuffers(global_window.device_context);
// the smooth values will smoothly converge to the real values
{
global_window.smooth_pos[0] = lerp(global_window.smooth_pos[0],
global_window.pos[0], 0.005f);
global_window.smooth_pos[1] = lerp(global_window.smooth_pos[1],
global_window.pos[1], 0.005f);
global_window.smooth_scale = lerp(global_window.smooth_scale,
global_window.scale, 0.005f);
}
color_offset += 0.001f;
}
// handle input
{
// some keyboards have two plus keys(number row and numpad)
if (keys[KEY_PLUS1] || keys[KEY_PLUS2])
{
global_window.scale *= 1.0f - 0.003f;
}
// see the above comment
if(keys[KEY_MINUS1] || keys[KEY_MINUS2])
{
global_window.scale *= 1.0f + 0.003f;
}
if (keys[KEY_W])
{
global_window.pos[1] -= global_window.scale * 0.003f;
}
if (keys[KEY_S])
{
global_window.pos[1] += global_window.scale * 0.003f;
}
if (keys[KEY_A])
{
global_window.pos[0] += global_window.scale * 0.003f;
}
if (keys[KEY_D])
{
global_window.pos[0] -= global_window.scale * 0.003f;
}
// if ctrl-r is pressed reset the scale and pos
if (keys[KEY_CTRL] && keys[KEY_R])
{
global_window.pos[0] = 0.0f;
global_window.pos[1] = 0.0f;
global_window.scale = 1.0f;
}
if (keys[KEY_UP])
{
global_window.max_iterations += 1;
}
if (keys[KEY_DOWN] &&
global_window.max_iterations > 2)
{
global_window.max_iterations -= 1;
}
}
}
}
</code></pre>
<p><code>opengl.h</code></p>
<pre><code>#ifndef OPENGL_H
#define OPENGL_H
/* from http://dantefalcone.name/tutorials/1a-windows-win32-window-and-3d-context-creation/ */
// Program
static PFNGLCREATEPROGRAMPROC glCreateProgram;
static PFNGLUSEPROGRAMPROC glUseProgram;
static PFNGLATTACHSHADERPROC glAttachShader;
static PFNGLLINKPROGRAMPROC glLinkProgram;
static PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
static PFNGLUNIFORM1IPROC glUniform1i;
static PFNGLUNIFORM1FPROC glUniform1f;
static PFNGLUNIFORM4FPROC glUniform4f;
// Shader
static PFNGLCREATESHADERPROC glCreateShader;
static PFNGLSHADERSOURCEPROC glShaderSource;
static PFNGLCOMPILESHADERPROC glCompileShader;
// for debuging
static PFNGLGETSHADERIVPROC glGetShaderiv;
static PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
// we need to load opengl extensions from opengl32.dll
static void load_extensions(void)
{
// Program
glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram");
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wglGetProcAddress("glGetUniformLocation");
glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i");
glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f");
glUniform4f = (PFNGLUNIFORM4FPROC)wglGetProcAddress("glUniform4f");
// Shader
glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader");
#ifdef DEBUG_MODE
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog");
glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv");
#endif
}
#endif // OPENGL_H
</code></pre>
<p><code>wglext.h</code>
<a href="https://www.khronos.org/registry/OpenGL/api/GL/wglext.h" rel="noreferrer">https://www.khronos.org/registry/OpenGL/api/GL/wglext.h</a></p>
<p><code>glext.h</code>
<a href="https://www.khronos.org/registry/OpenGL/api/GL/glext.h" rel="noreferrer">https://www.khronos.org/registry/OpenGL/api/GL/glext.h</a></p>
<p>to build use:</p>
<p><code>Makefile</code>:</p>
<pre><code>NAME = prog
CC = clang-cl # if you don't have clang-cl use cl instead and change FLAGS
FLAGS = -m32 -W4 -c -nologo -GS- -Gr -Ofast -Oi -Gs9999999
LINK_FLAGS = /UNSAFEIMPORT /TRUNCATEFLOATS:18 /HASHSIZE:10 main.obj \
kernel32.lib user32.lib shell32.lib gdi32.lib opengl32.lib \
/SUBSYSTEM:windows /NODEFAULTLIB /ENTRY:entry /OUT:"$(NAME).exe" /STACK:0x100000,0x100000
all: main.c
$(CC) $(FLAGS) main.c && Crinkler $(LINK_FLAGS)
clean:
del $(NAME).exe
</code></pre>
<p>to build you will need to also download Crinkler <a href="https://github.com/runestubbe/Crinkler" rel="noreferrer">https://github.com/runestubbe/Crinkler</a></p>
<p>here is what it looks like:
<a href="https://i.stack.imgur.com/S72Y0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S72Y0.png" alt="enter image description here" /></a></p>
|
[] |
[
{
"body": "<p>First, note that significant effort toward hyper-optimizing a program for smallest executable size is effectively the domain of <a href=\"https://codegolf.stackexchange.com/\">Code Golf</a>; Code Review concerns itself with well-structured, reliable code that follows best practices. If the former gets in the way of the latter, you will tend to find that recommendations on this site bend toward "good code" rather than "small code".</p>\n<p>To that end:</p>\n<h2>Redeclaration</h2>\n<pre><code>extern int _fltused;\nint _fltused;\n</code></pre>\n<p>Why? You haven't marked it <code>static</code> so it should be exported already. Declaring it <code>extern</code> would be more useful in a header file that a different translation unit includes, which is not what's happening here; so just <code>int _fltused = 0;</code>.</p>\n<h2>Lookup tables</h2>\n<p><a href=\"https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes\" rel=\"nofollow noreferrer\">Virtual key codes fit in one byte</a>. Consider replacing your <code>switch (wParam)</code> with a lookup into a 256-byte-long correspondence table where the index is the virtual key code and the value is your <code>enum Keys</code> code.</p>\n<p>Better yet, make <code>keys</code> itself 256 bytes long, do away with your <code>enum</code> altogether, and assume that indexes map to virtual key codes. Be sure to range-check any incoming VKs just to be sure that an out-of-range dereference is not possible.</p>\n<h2>Strange modifier declaration order</h2>\n<p>Whereas <code>bool const</code> <a href=\"https://stackoverflow.com/questions/24325108/order-of-const-and-volatile-for-a-variable\">is equivalent</a> to <code>const bool</code>, the latter is much more common.</p>\n<h2>Header files</h2>\n<p>The conventional thing to do for <code>load_extensions</code> is put it in a C file. That will be better-structured and should not affect the compilation size given a correctly-configured compiler and linker.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:13:58.493",
"Id": "253635",
"ParentId": "253160",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T03:57:20.877",
"Id": "253160",
"Score": "8",
"Tags": [
"c",
"opengl",
"glsl"
],
"Title": "tiny mandelbrot"
}
|
253160
|
<p>I'm the maintainer of <a href="https://github.com/servian/aws-auto-cleanup" rel="nofollow noreferrer">https://github.com/servian/aws-auto-cleanup</a>. I'm by no means a Python expert and hence I'd say I'm way off creating code that would be considered Pythonic. I do however love to tweak and improve code quality where I can.</p>
<p>I'd love for someone to check over a single class of mine and provide some tips where I could improve.</p>
<p>A simple class to look at is:</p>
<pre><code>import sys
import boto3
from src.helper import Helper
class AmplifyCleanup:
def __init__(self, logging, whitelist, settings, execution_log, region):
self.logging = logging
self.whitelist = whitelist
self.settings = settings
self.execution_log = execution_log
self.region = region
self._client_amplify = None
self._dry_run = self.settings.get("general", {}).get("dry_run", True)
@property
def client_amplify(self):
if not self._client_amplify:
self._client_amplify = boto3.client("amplify", region_name=self.region)
return self._client_amplify
def run(self):
self.apps()
def apps(self):
"""
Deletes Amplify Apps.
"""
self.logging.debug("Started cleanup of Amplify Apps.")
clean = (
self.settings.get("services", {})
.get("amplify", {})
.get("app", {})
.get("clean", False)
)
if clean:
try:
resources = self.client_amplify.list_apps().get("apps")
except:
self.logging.error("Could not list all Amplify Apps.")
self.logging.error(sys.exc_info()[1])
return False
ttl_days = (
self.settings.get("services", {})
.get("amplify", {})
.get("app", {})
.get("ttl", 7)
)
for resource in resources:
resource_id = resource.get("name")
resource_app_id = resource.get("appId")
resource_date = resource.get("updateTime")
resource_action = None
if resource_id not in self.whitelist.get("amplify", {}).get("app", []):
delta = Helper.get_day_delta(resource_date)
if delta.days > ttl_days:
try:
if not self._dry_run:
self.client_amplify.delete_app(appId=resource_app_id)
except:
self.logging.error(
f"Could not delete Amplify App '{resource_id}'."
)
self.logging.error(sys.exc_info()[1])
resource_action = "ERROR"
else:
self.logging.info(
f"Amplify App '{resource_id}' was last modified {delta.days} days ago "
"and has been deleted."
)
resource_action = "DELETE"
else:
self.logging.debug(
f"Amplify App '{resource_id}' was last modified {delta.days} days ago "
"(less than TTL setting) and has not been deleted."
)
resource_action = "SKIP - TTL"
else:
self.logging.debug(
f"Amplify App '{resource_id}' has been whitelisted and has not been deleted."
)
resource_action = "SKIP - WHITELIST"
Helper.record_execution_log_action(
self.execution_log,
self.region,
"Amplify",
"App",
resource_id,
resource_action,
)
self.logging.debug("Finished cleanup of Amplify Apps.")
return True
else:
self.logging.info("Skipping cleanup of Amplify Apps.")
return True
</code></pre>
<p>All my classes are basically the same general template calling different AWS Boto3 APIs. Hence if I can improve one, I can improve all of them.</p>
<p>My main dislikes are my dictionary retrievals:</p>
<pre><code>clean = (
self.settings.get("services", {})
.get("amplify", {})
.get("app", {})
.get("clean", False)
)
</code></pre>
<p>and</p>
<pre><code>ttl_days = (
self.settings.get("services", {})
.get("amplify", {})
.get("app", {})
.get("ttl", 7)
)
</code></pre>
<p>Should I be moving these to functions that I would call or should I do something else?</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review!</p>\n<p>As this is an open source project, some guidelines/maintenance rules might take precedence over the suggestions here. However, a few points I'd like to mention:</p>\n<ol>\n<li><p>Subclassing your cleanups. Looking through <a href=\"https://github.com/servian/aws-auto-cleanup/tree/master/app/src\" rel=\"nofollow noreferrer\">the project source</a>, I notice that all AWS/boto3 supported classes have their own duplicates of <code>__init__</code>, with very minimal changes (like referencing a resource instead of low-level client). Using a base class which does a majority of this work for you would probably be more maintainable.</p>\n</li>\n<li><p>Naming of certain methods appears counter-intuitive. For example, the function <code>apps()</code> should actually read <code>cleanup_apps()</code>?</p>\n</li>\n<li><p>As you pointed out in the question itself, your primary concern is with the nested dictionary retrievals. Looking at the source, I notice that again, all looks are always from the <code>self.settings</code> dictionary. Perhaps a helper method in parent class (or extracted into the <code>Helper</code> class) could keep it smaller:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def setting_lookup(self, path, default=None):\n result = self.settings\n for key in path.split("."):\n result = result.get(key)\n if result is None:\n return default\n return result\n</code></pre>\n<p>and the call would be (aws doesn't allow <code>/</code> and <code>.</code> in their resource names):</p>\n<pre class=\"lang-py prettyprint-override\"><code>clean = self.settings_lookup("services.amplify.app.clean", default=False)\n</code></pre>\n<p>If you think that the <code>jq</code> like lookup is not for you, it can be just sent across as list of consecutive keys.</p>\n</li>\n<li><p>The current system does not account for paginated results from <a href=\"https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/amplify.html#Amplify.Client.list_apps\" rel=\"nofollow noreferrer\">the <code>list_apps</code></a> method. From the official docs, a default maximum is 100 resources in an API call, however for cleaning up of more resources, there is no pagination support in the <code>apps()</code> method for the cleanup class.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T12:36:25.420",
"Id": "253174",
"ParentId": "253161",
"Score": "1"
}
},
{
"body": "<p>To be honest, I don't see much needed change except those dict look-ups you complained about.</p>\n<p>Observe that whenever any key in the <code>get</code> chain is missing, the last default will be returned. So you can safely convert that chain to a <code>try/except</code> structure and use the last default value in case of a missing key.</p>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>clean = (\n self.settings.get("services", {})\n .get("amplify", {})\n .get("app", {})\n .get("clean", False)\n)\n</code></pre>\n<p>Will be equivalent to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n clean = self.settings["services"]["amplify"]["app"]["clean"]\nexcept KeyError:\n clean = False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:31:35.937",
"Id": "253185",
"ParentId": "253161",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:10:57.647",
"Id": "253161",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Pythonic improvements to object retrieval and more"
}
|
253161
|
<p>Trying to improve my HTML and CSS.</p>
<p>Creating a Basic Table using CSS grid, to match as closely to this image:
<a href="https://i.stack.imgur.com/J9iMW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J9iMW.png" alt="enter image description here" /></a></p>
<p>Please ignore the color red and green in the rows and Some rows are missing since it was used with data inside a react application and since I only care about the HTML and CSS I copied only what was relevant.</p>
<p>Having trouble with expanding the last row.</p>
<p>I know it's a mess and a lot to improve.</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>.App {
display: flex;
justify-content: center;
align-items: center;
}
.wrapper {
background-color: rgb(243, 241, 241);
border: 1px solid rgb(170, 167, 167);
padding: 5px;
}
.table-border {
background-color: rgb(170, 167, 167);
border: 1px solid rgb(170, 167, 167);
border-radius: 6px;
}
.table {
display: grid;
/* background-color:rgb(243, 241, 241); */
border: 1px solid rgb(170, 167, 167);
border-radius: 6px;
font-size: 12px;
grid-template-columns: auto auto auto auto;
gap: 1px 0px;
color: #444;
}
.table-footer {
padding: 5px;
background-color: rgb(243, 241, 241);
}
.th {
margin-bottom: 3px;
}
.last {
border-right: none;
}
.cell {
padding: 5px;
background-color: white;
}
.cell.th {
background-color: rgb(243, 241, 241);
}
.top-left-corner {
border-radius: 6px 0px 0px 0px;
}
.top-right-corner {
border-radius: 0px 6px 0px 0px;
}
.bottom-right-corner {
border-radius: 0px 0px 6px 0px;
}
.bottom-left-corner {
border-radius: 0px 0px 0px 6px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="table-border">
<div class="table">
<div class="cell th top-left-corner">Agent ID</div>
<div class="cell th">Country</div>
<div class="cell th">Address</div>
<div class="cell th last top-right-corner">Date</div>
<div class="cell">007</div>
<div class="cell">Brazil</div>
<div class="cell">
Avenida Vieira Souto 168 Ipanema, Rio de Janeiro
</div>
<div class="cell">Dec 17, 1995, 9:45:17 PM</div>
<div class="cell">005</div>
<div class="cell">Poland</div>
<div class="cell">Rynek Glowny 12, Krakow</div>
<div class="cell">Apr 5, 2011, 5:05:12 PM</div>
<div class="cell">007</div>
<div class="cell">Morocco</div>
<div class="cell">27 Derb Lferrane, Marrakech</div>
<div class="cell">Jan 1, 2001, 12:00:00 AM</div>
<div class="cell">005</div>
<div class="cell">Brazil</div>
<div class="cell">Rua Roberto Simonsen 122, Sao Paulo</div>
<div class="cell">May 5, 1986, 8:40:23 AM</div>
<div class="table-footer bottom-left-corner">10</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:42:03.987",
"Id": "499157",
"Score": "3",
"body": "The biggest problem I see here, is that you are not using a table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:58:04.547",
"Id": "499222",
"Score": "0",
"body": "@RoToRa tried using a table but can't set rounded border.\nyou need to do border-collapse but than you lose the gaps between table cells."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T09:42:11.663",
"Id": "499282",
"Score": "0",
"body": "I'm quite sure you can have rounded borders on a table no matter the border-collapse state. Also I don't see any gaps between tables cells in the image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T19:19:45.670",
"Id": "500177",
"Score": "0",
"body": "I'm fully agree with @RoToRa, you don't need to try to emulate a table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:03:41.753",
"Id": "520123",
"Score": "0",
"body": "Can you include a screenshot of how your proposed source renders?"
}
] |
[
{
"body": "<p>Semantically, it is preferable that you use <code>table</code> instead of <code>div</code>.\nIn fact, it is possible to apply rounded edges to tables and still maintain the gap you need.</p>\n<p>I did a part of what you need here in the snippet below, but I'll leave the rest of the work to you.</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>:root {\n --border: 1px solid rgb(170, 167, 167);\n --main-color: rgb(243, 241, 241);\n}\n\n.wrapper {\n border: var(--border);\n border-radius: 6px;\n}\n\n.table-border {\n color: #444;\n font-size: 9pt;\n font-family: Arial, Helvetica, sans-serif;\n width: 100%;\n text-align: left;\n overflow: hidden;\n border-width: 0 1px;\n border-spacing: 0 8px;\n border-collapse: separate;\n -webkit-border-radius: 6px;\n -moz-border-radius: 6px;\n border-radius: 6px;\n}\n\nthead tr th {\n padding: 7px 10px;\n border-right: var(--border);\n background-color: var(--main-color);\n box-shadow: 0px -20px var(--main-color);\n}\n\nthead tr th:last-of-type {\n border: none;\n}\n\ntbody tr:first-of-type td {\n box-shadow: 0 -10px rgb(243 241 241);\n}\n\ntbody tr td {\n padding: 12px 10px 3px;\n background-color: white;\n border-top: var(--border);\n}\n\ntfoot tr td {\n padding: 5px 10px;\n text-align: right;\n border-top: var(--border);\n background-color: var(--main-color);\n box-shadow: 0px 20px var(--main-color);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"wrapper\">\n <table class=\"table-border\">\n <thead>\n <tr>\n <th>Agent ID</th>\n <th>Country</th>\n <th>Address</th>\n <th>Date</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>007</td>\n <td>Brazil</td>\n <td>Avenida Vieira Souto 168 Ipanema, Rio de Janeiro</td>\n <td>Dec 17, 1995, 9:45:17 PM</td>\n </tr>\n <tr>\n <td>005</td>\n <td>Poland</td>\n <td>Rynek Glowny 12, Krakow</td>\n <td>Apr 5, 2011, 5:05:12 PM</td>\n </tr>\n <tr>\n <td>007</td>\n <td>Morocco</td>\n <td>27 Derb Lferrane, Marrakech</td>\n <td>Jan 1, 2001, 12:00:00 AM</td>\n </tr>\n <tr>\n <td>005</td>\n <td>Brazil</td>\n <td>Rua Roberto Simonsen 122, Sao Paulo</td>\n <td>May 5, 1986, 8:40:23 AM</td>\n </tr>\n </tbody>\n <tfoot>\n <tr>\n <td colspan=\"4\">10 missions</td>\n </tr>\n </tfoot>\n </table>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Take a look at <code>border-spacing</code>.</p>\n<p><strong>Sources</strong>:</p>\n<ul>\n<li><a href=\"https://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_cellspacing\" rel=\"nofollow noreferrer\">W3 Schools: A table with cell spacing</a></li>\n<li><a href=\"https://pt.stackoverflow.com/questions/59602/border-radius-na-tabela-n%C3%A3o-funciona-css\">Border-radius na tabela não funciona CSS</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:03:27.963",
"Id": "520122",
"Score": "0",
"body": "Can you include a screenshot of how your proposed source renders?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T17:51:56.603",
"Id": "520134",
"Score": "0",
"body": "I wrote the code in VSCode and just realized that I pasted the wrong code here. It's already edited, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T20:54:18.487",
"Id": "520150",
"Score": "1",
"body": "Neat trick emulating separated borders using box shadow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T00:30:47.503",
"Id": "520157",
"Score": "1",
"body": "Yeah, sometimes we have to think of an alternative solution. haha"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T14:37:28.370",
"Id": "263455",
"ParentId": "253162",
"Score": "1"
}
},
{
"body": "<p>Points:</p>\n<ul>\n<li>Improve the semantic meaning of your markup. Basically tell the browser more machine-readable information about the data in your page:\n<ul>\n<li>it's definitely a table, not a collection of divs</li>\n<li>there are some real datetimes, addresses, and countries that have machine-legible ISO3166-2 codes</li>\n<li>generally, rely on sane CSS selection rather than explicit classes to apply your styles</li>\n</ul>\n</li>\n<li>The separators in the header look vaguely like non-collapsed borders, but it is not possible to have separated borders and collapsed borders co-existing in the same table - so just add borders to inner spans in the header.</li>\n<li>Since the body of the table does have collapsed borders, you cannot apply border radii. Add a container and apply it to that instead.</li>\n</ul>\n<p>An approximate match is the following:</p>\n<pre class=\"lang-html prettyprint-override\"><code><!DOCTYPE html>\n<head>\n <style type="text/css">\n address {\n font-style: normal;\n }\n\n body {\n font-family: "Century Gothic", sans-serif;\n text-align: left;\n color: #565656;\n margin: 0;\n padding: 2em;\n }\n\n body, thead, tfoot {\n background-color: #FAFAFA;\n }\n\n .table-container, th, th span, td {\n border-color: #CCCCCC;\n }\n\n .table-container {\n margin: 0;\n padding: 0;\n overflow: hidden;\n border-width: 0.2em;\n border-style: solid;\n border-radius: 0.4em;\n }\n\n table {\n margin: 0;\n width: 100%;\n border-collapse: collapse;\n }\n\n thead {\n font-size: 1.4em;\n }\n\n th, tfoot td {\n border-width: 0.2em;\n }\n\n th {\n padding: 0.5em 0 0.5em 1em;\n }\n\n td {\n padding: 1em;\n }\n\n tbody td {\n border-width: 0.1em;\n border-style: solid none;\n }\n\n th {\n border-width: 0.2em;\n border-style: none none solid none;\n }\n\n th:not(:last-child) span {\n width: 100%;\n padding: 0.5em 0;\n display: block;\n border-width: 0.1em;\n border-style: none solid none none;\n }\n\n tbody {\n background-color: white;\n font-size: 1.5em;\n }\n\n tfoot {\n font-size: 1.4em;\n text-align: right;\n }\n\n tfoot td {\n border-style: solid none none none;\n }\n </style>\n</head>\n\n<body>\n <div class="table-container">\n <table>\n <thead>\n <tr>\n <th><span>Agent ID</span></th>\n <th><span>Country</span></th>\n <th><span>Address</span></th>\n <th><span>Date</span></th>\n </tr>\n </thead>\n\n <tbody>\n <tr>\n <td>005</td>\n <td><data value="BR">Brazil</data></td>\n <td>\n <address>Rua Roberto Simonsen 122, Sao Paulo</address>\n </td>\n <td>\n <time datetime="1986-05-05T08:40:23">May 5, 1986, 8:40:23 AM</time>\n </td>\n </tr>\n\n <tr>\n <td>007</td>\n <td><data value="BR">Brazil</data></td>\n <td>\n <address>Avenida Vieira Souto 168 Ipanema, Rio de Janeiro</address>\n </td>\n <td>\n <time datetime="1995-12-17T21:45:17">Dec 17, 1995, 9:45:17 PM</time>\n </td>\n </tr>\n\n <tr>\n <td>011</td>\n <td><data value="PL">Poland</data></td>\n <td>\n <address>swietego Tomasza 35, Krakow</address>\n </td>\n <td>\n <time datetime="1997-09-07T19:12:53">Sep 7, 1997, 7:12:53 PM</time>\n </td>\n </tr>\n\n <tr>\n <td>007</td>\n <td><data value="MA">Morocco</data></td>\n <td>\n <address>27 Derb Lferrane, Marrakech</address>\n </td>\n <td>\n <time datetime="2001-01-01T00:00:00">Jan 1, 2001, 12:00:00 AM</time>\n </td>\n </tr>\n\n <tr>\n <td>013</td>\n <td><data value="PL">Poland</data></td>\n <td>\n <address>Zlota 9, Lublin</address>\n </td>\n <td>\n <time datetime="2002-10-17T10:52:19">Oct 17, 2002, 10:52:19 AM</time>\n </td>\n </tr>\n\n <tr>\n <td>008</td>\n <td><data value="BR">Brazil</data></td>\n <td>\n <address>Rua tamoana 418, tefe</address>\n </td>\n <td>\n <time datetime="2005-11-10T13:25:13">Nov 10, 2005, 1:25:13 PM</time>\n </td>\n </tr>\n\n <tr>\n <td>005</td>\n <td><data value="PL">Poland</data></td>\n <td>\n <address>Rynek Glowny 12, Krakow</address>\n </td>\n <td>\n <time datetime="2011-04-05T17:05:12">Apr 5, 2011, 5:05:12 PM</time>\n </td>\n </tr>\n\n <tr>\n <td>003</td>\n <td><data value="MA">Morocco</data></td>\n <td>\n <address>Rue Al-Aidi Ali Al-Maaroufi, Casablanca</address>\n </td>\n <td>\n <time datetime="2012-08-29T10:17:05">Aug 29, 2012, 10:17:05 AM</time>\n </td>\n </tr>\n\n <tr>\n <td>009</td>\n <td><data value="MA">Morocco</data></td>\n <td>\n <address>atlas marina beach, agadir</address>\n </td>\n <td>\n <time datetime="2016-12-01T21:21:21">Dec 1, 2016, 9:21:21 PM</time>\n </td>\n </tr>\n\n <tr>\n <td>002</td>\n <td><data value="MA">Morocco</data></td>\n <td>\n <address>Riad Sultan 19, Tangier</address>\n </td>\n <td>\n <time datetime="2017-01-01T17:00:00">Jan 1, 2017, 5:00:00 PM</time>\n </td>\n </tr>\n </tbody>\n\n <tfoot>\n <tr>\n <td colspan="4">10 missions</td>\n </tr>\n </tfoot>\n </table>\n </div>\n</body>\n</html>\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/NUGVh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NUGVh.png\" alt=\"test render\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T20:34:37.603",
"Id": "263468",
"ParentId": "253162",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T04:22:46.360",
"Id": "253162",
"Score": "4",
"Tags": [
"html",
"css"
],
"Title": "Creating a basic table with CSS grid"
}
|
253162
|
<p>I have been working on this question in particular. I'm a bit of a python beginner myself, having re-learnt functions just a few days back.</p>
<blockquote>
<p>Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. Be sure to test the case where an empty list [] is passed to your function.</p>
</blockquote>
<p>My idea for this was to have my function run a for loop on the range of the number of elements of the list, add the elements of the list to a comma. If the element of the list happens to be the last element, 'and' and that specific element are added together.</p>
<p>Here is the code:</p>
<pre class="lang-py prettyprint-override"><code>def listsmash(listu):
y = ''
for x in range(len(listu)):
if x == len(listu) -1 :
y+= 'and '+ str(listu[x])
else:
y+= str(listu[x]) + ','
return y
print(listsmash([1,345,34656,456456,456454564]))
</code></pre>
<p>Is this an efficient piece of code? Any way for me to make it more efficient than it already is?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T06:23:41.133",
"Id": "499120",
"Score": "1",
"body": "Your code isn't indented properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:58:43.853",
"Id": "499146",
"Score": "2",
"body": "@MiguelAvila ... but for the `'and'`."
}
] |
[
{
"body": "<p>Nice solution, these are my suggestions:</p>\n<ul>\n<li><strong>Indentation</strong>: the first line is not indented correctly, there is an extra tab or spaces before <code>def listsmash(listu):</code>.</li>\n<li><strong>Code formatting</strong>: follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> to format the code. You can use <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">pep8online</a> or just use the auto-formatting feature of many IDEs.</li>\n<li><strong>Bug</strong>: the output should be <code>apples, bananas, tofu, and cats</code> but the code outputs <code>apples,bananas,tofu,and cats</code>. There should be a space after the comma.</li>\n<li><strong>Edge case</strong>: if the input list contains only <code>apples</code> the code outputs <code>and apples</code>. This is an edge case to handle, probably at the beginning of the method.</li>\n<li><strong>Performance</strong>: there is no much to worry about performances, as it runs linearly to the input size. However, the first if condition is executed everytime:\n<pre class=\"lang-py prettyprint-override\"><code>for x in range(len(listu)):\n if x == len(listu) -1 :\n y+= 'and '+ str(listu[x])\n else:\n y+= str(listu[x]) + ','\n</code></pre>\nLimit the number of iterations to <code>len(listy) - 1</code> and add the last element outside the for-loop:\n<pre class=\"lang-py prettyprint-override\"><code>def listsmash(listu):\n y = ''\n for x in range(len(listu) - 1):\n y += str(listu[x]) + ', '\n y += 'and ' + str(listu[-1])\n return y\n</code></pre>\n</li>\n<li><strong>Use str.join</strong>: <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\">str.join</a> is a handy function in this case:\n<pre><code>def listsmash(listu):\n y = ', '.join(str(value) for value in listu[:-1])\n return y + ', and ' + str(listu[-1])\n</code></pre>\nIt joins all elements of <code>listu</code> (except the last one) with <code>, </code> and then we can append the last element at the end. Additionally, the function <code>.join()</code> <a href=\"https://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python\">is faster</a> than <code>+=</code>.</li>\n<li><strong>Naming</strong>: I am not sure what <code>listu</code> means, maybe you can consider a better name like <code>items</code> following from the problem description.</li>\n</ul>\n<p><strong>Runtime for 1 million items</strong>:</p>\n<pre><code>Original: 4.321 s\nImproved: 0.418 s\n</code></pre>\n<p><strong>Full code</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from random import randint\nfrom time import perf_counter\n\n\ndef original(listu):\n y = ''\n for x in range(len(listu)):\n if x == len(listu) - 1:\n y += 'and ' + str(listu[x])\n else:\n y += str(listu[x]) + ', '\n return y\n\n\ndef improved(items):\n result = ', '.join(str(item) for item in items[:-1])\n return result + ', and ' + str(items[-1])\n\n\n# Correctness\nitems = ['apples', 'bananas', 'tofu']\nassert original(items) == improved(items)\n\n# Benchmark\nn = 1_000_000\nitems = [randint(0, n) for _ in range(n)]\n\nt0 = perf_counter()\noriginal(items)\ntotal_time = perf_counter() - t0\nprint(f'Original: {round(total_time, 3)} s')\n\nt0 = perf_counter()\nimproved(items)\ntotal_time = perf_counter() - t0\nprint(f'Improved: {round(total_time, 3)} s')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T07:19:33.493",
"Id": "499124",
"Score": "0",
"body": "Where exactly should I fix the indentation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T07:29:40.660",
"Id": "499125",
"Score": "0",
"body": "@HankRyan there is an extra tab before `def listsmash(listu):`. I think it's due to copying and pasting the code in the question, not a big deal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:45:32.463",
"Id": "499140",
"Score": "0",
"body": "In python, [`str`](https://docs.python.org/3/library/stdtypes.html#textseq) and [`string`](https://docs.python.org/3/library/string.html) are two different things. Shouldn't it be `str.join`? Apart from that review is excellent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:50:32.873",
"Id": "499141",
"Score": "1",
"body": "And one more thing [`str.join with list comprehension faster than str.join with generator`](https://stackoverflow.com/a/9061024/12416453)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:16:38.470",
"Id": "499153",
"Score": "0",
"body": "*\"it runs linearly to the input size\"* - Not true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:48:54.387",
"Id": "499158",
"Score": "0",
"body": "@Ch3steR thanks, updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:51:57.247",
"Id": "499159",
"Score": "0",
"body": "@superbrain do you mind elaborating?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:57:51.283",
"Id": "499161",
"Score": "0",
"body": "If you're lucky, it might be linear for a while, but ultimately in general it degrades to the quadratic behavior you'd expect. See [this](https://stackoverflow.com/q/44487537/13008439). Or is there some newer development that really does make it linear, that I'm not aware of?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:33:07.050",
"Id": "499166",
"Score": "0",
"body": "Both versions fail with list size `0` and return (probably) bad output for list size `1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:18:02.880",
"Id": "499179",
"Score": "0",
"body": "@Tomerikoo I mentioned about the list of size 1 (see edge case), but then I focused on performance as OP requested and ignored such cases. Feel free to post your review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:25:12.633",
"Id": "499249",
"Score": "0",
"body": "@Ch3steR what about the overhead of creating the whole list, when you would eventually throw them away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T03:34:29.710",
"Id": "499260",
"Score": "2",
"body": "From the SO answer linked `The reason is that .join() needs to make two passes over the data, so it actually needs a real list. If you give it one, it can start its work immediately. If you give it a genexp instead, it cannot start work until it builds-up a new list in memory by running the genexp to exhaustion` @theProgrammer"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T06:43:15.147",
"Id": "253165",
"ParentId": "253164",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253165",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T06:05:37.020",
"Id": "253164",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Code to take a list, convert to string and insert comma between the 'elements' - From Automate The Boring Stuff"
}
|
253164
|
<p>I have created a Python & Node JS encryption/decryption AES 256-CFB. The point of this little project is that I will encrypt a special URL with Python covered with base64 & URL encoding and then the Node JS will decrypt it.</p>
<p>For now the Node JS is working perfectly fine that can starts by decoding the URL, decoding the Base64 and then decrypt the AES with special password key. Meaning that I will have the same key for Node JS and Python to be able to decrypt. Something to add, this will not be added to any other clients/users meaning that covering the password is not needed since no one will reach the code ever but me :)</p>
<pre><code>import base64
import hashlib
import urllib.parse
from Crypto import Random
from Crypto.Cipher import AES
key = "testing" # Will of course be another password
def encrypt(url):
"""
Encrypting the given url
:param url:
:return:
"""
private_key = hashlib.sha256(key.encode()).digest()
rem = len(url) % 16
padded = str.encode(url) + (b'\0' * (16 - rem)) if rem > 0 else str.encode(url)
iv = Random.new().read(AES.block_size)
cipher = AES.new(private_key, AES.MODE_CFB, iv, segment_size=128)
enc = cipher.encrypt(padded)[:len(url)]
return base64.b64encode(iv + enc).decode()
def main():
encrypted = urllib.parse.quote(encrypt("https://stackoverflow.com/"))
url_decode = urllib.parse.unquote(encrypted)
print(f'Encrypted and URL encoded: {encrypted}\n')
print(f'URL decoded: {urllib.parse.unquote(url_decode)}\n')
if __name__ == '__main__':
main()
</code></pre>
<p>Now I wonder if there is anyhow where I can improve the code in any how? In my eyes I don't see any ways to improve anyhow but I always end up be wrong :D</p>
|
[] |
[
{
"body": "<p>The padding step is unnecessary - CFB works out of the box on any plaintext length since it XORS the plaintext with the AES output.</p>\n<p>Lack of authentication means that the scheme is vulnerable to a bit flipping attack, where you can flip bits in the ciphertext and cause a corresponding bit flip in the plaintext.</p>\n<p>Other nitpicks:</p>\n<ul>\n<li><code>str.encode(url)</code> should be <code>url.encode()</code></li>\n<li>your docstring has a <code>:return:</code> but it doesn't declare anything</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T00:30:47.937",
"Id": "253239",
"ParentId": "253167",
"Score": "2"
}
},
{
"body": "<p>Just a quick note on how you generate the key:</p>\n<pre><code>key = "testing" # Will of course be another password\n</code></pre>\n<ul>\n<li>IMO, <code>password</code> would be a more descriptive variable name</li>\n<li>there is no need to write a password in your source code. You can either read it from a file or from the console via the <code>getpass</code> module</li>\n</ul>\n<hr />\n<pre><code> private_key = hashlib.sha256(key.encode()).digest()\n</code></pre>\n<ul>\n<li>when you derive a key from a password you shouldn't use sha256, since there are more specialized functions for this purpose. I would suggest you to use <code>hashlib.scrypt</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T21:52:17.653",
"Id": "253798",
"ParentId": "253167",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T08:14:55.773",
"Id": "253167",
"Score": "3",
"Tags": [
"python",
"cryptography",
"aes"
],
"Title": "Encryption/Decryption between Python and Node JS"
}
|
253167
|
<p><strong>Dear Python VIS community.</strong></p>
<p>Imagine the following situation:</p>
<p>You ran an experiment in an earth system model (ESM) where you altered some input parameters relative to a control run of the same ESM. Now you look at the surface air temperature and since you have this information for both your experiment and your control run, you can compare the two data sets. Say you want to look at the seasonal difference in air temperature between the experiment and the control (i.e. experiment - contorl = difference). This would result in four maps, one for each season (Winter, Spring, Summer, Autumn, defined as "DJF", "MAM", "JJA", "SON").</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.colors as mcol
import matplotlib.cbook as cbook
import matplotlib.colors as colors
import numpy as np
import sys
winter = np.random.random((96,144))
winter[0:48,:] = winter[0:48,:] * 3
winter[48:,:] = winter[48:,:] * -6
spring = np.random.random((96,144))
spring[0:48,:] = spring[0:48,:] * 4
spring[48:,:] = spring[48:,:] * -6
summer = np.random.random((96,144))
summer[0:48,:] = summer[0:48,:] * 10
summer[48:,:] = summer[48:,:] * -2
autumn = np.random.random((96,144))
autumn[0:48,:] = autumn[0:48,:] * 4
autumn[48:,:] = autumn[48:,:] * -7
</code></pre>
<p>Cool data! But how do you visualize this using matplotlib? Okay you decide for filled contours from matplotlib. This will yield a map including a colorbar for each season. Now that is cool and all, but you would like to have the four maps in subplots (easy!, see Figure 1).</p>
<pre><code>fig, axes = plt.subplots(2, 2)
axes = axes.flatten()
seasons = zip(axes, [winter, spring, summer, autumn])
for pair in seasons:
im = pair[0].contourf(pair[1])
plt.colorbar(im, ax=pair[0])
</code></pre>
<p><a href="https://i.stack.imgur.com/TKX4G.png" rel="nofollow noreferrer">Figure 1. Suplots with individual colorbar.</a></p>
<p>Since you want to look at the difference, you can tell that 0 will be important, because your temperature can either be the same (x=0), or it can be regionally cooler (x < 0) or warmer (0 < x).<br />
In order to have the value zero (0) exactly split the colormap you decide for a diverging colormap (based on this example: <a href="https://matplotlib.org/3.2.0/gallery/userdemo/colormap_normalizations_diverging.html#sphx-glr-gallery-userdemo-colormap-normalizations-diverging-py" rel="nofollow noreferrer">https://matplotlib.org/3.2.0/gallery/userdemo/colormap_normalizations_diverging.html#sphx-glr-gallery-userdemo-colormap-normalizations-diverging-py</a>). Perfect you think?</p>
<pre><code>colors_low = plt.cm.RdBu_r(np.linspace(0, 0.3, 256))
colors_high = plt.cm.RdBu_r(np.linspace(0.5, 1, 256))
all_colors = np.vstack((colors_low, colors_high))
segmented_map = colors.LinearSegmentedColormap.from_list('RdBu_r', all_colors)
divnorm = colors.TwoSlopeNorm(vmin=-7, vcenter=0, vmax=10)
fig, axes = plt.subplots(2, 2)
axes = axes.flatten()
seasons = zip(axes, [winter, spring, summer, autumn])
for pair in seasons:
im = pair[0].contourf(pair[1], cmap=segmented_map, norm=divnorm, vmin=-7, vmax=10)
plt.colorbar(im, ax=pair[0])
</code></pre>
<p><a href="https://i.stack.imgur.com/w1rux.png" rel="nofollow noreferrer">Figure 2. Diverging colormap with 0 in as the center.</a></p>
<p>Not quite, because although you supply contourf() with the overall vmin and vmax and your derived colormap, the levels (i.e. ticks) in the colorbar are not the same for the four plots ("WHY?!?", you scream)!</p>
<p>Aha you find that you need to supply the same levels to contourf() in all four subplots (based on this: <a href="https://stackoverflow.com/questions/53641644/set-colorbar-range-with-contourf">https://stackoverflow.com/questions/53641644/set-colorbar-range-with-contourf</a>). But how do you exploit the functionality of contourf, that automatically choses appropriate contour levels?</p>
<p>You think that you could invisibly plot the four individual images, and then extract the color levels from each (im = contourf(), im.levels, <a href="https://matplotlib.org/3.3.1/api/contour_api.html#matplotlib.contour.QuadContourSet" rel="nofollow noreferrer">https://matplotlib.org/3.3.1/api/contour_api.html#matplotlib.contour.QuadContourSet</a>) and from this create a unique set of levels that combines the maximum and minimum from the extracted color levels.</p>
<pre><code># -1- Create the pseudo-figures for extraction of color levels:
fig, axes = plt.subplots(2, 2)
axes = axes.flatten()
seasons = zip(axes, [winter, spring, summer, autumn])
c_levels = []
for pair in seasons:
im = pair[0].contourf(pair[1], cmap=segmented_map, norm=divnorm, vmin=-7, vmax=10)
c_levels.append(im.levels)
# -1.1- Clear the figure
plt.clf()
# -2- Find the colorbars with the most levels below and above 0:
lower = sys.maxsize
lower_i = 0
higher = -1 * sys.maxsize
higher_i = 0
for i, c_level in enumerate(c_levels):
if np.min(c_level) < lower: # extract the index for the array with the minimum value
lower = np.min(c_level)
lower_i = i
if np.max(c_level) > higher: # extract the index for the array with the maximum value
higher = np.max(c_level)
higher_i = i
# -3- Create the custom color levels as a combination of the minimum and maximum found above
custom_c_levels = []
for level in c_levels[lower_i]:
if level <= 0: # define the levels for the negative section, including 0
custom_c_levels.append(level)
for level in c_levels[higher_i]:
if level > 0: # define the levels for the positive section, excluding 0
custom_c_levels.append(level)
custom_c_levels = np.array(custom_c_levels)
# -4- create the new normalization to go along with the new color levels
v_min = custom_c_levels[0]
v_max = custom_c_levels[-1]
divnorm = divnorm = colors.TwoSlopeNorm(vmin=v_min, vcenter=0, vmax=v_max)
# -5- plot the figures
fig, axes = plt.subplots(2, 2)
axes = axes.flatten()
seasons = zip(axes, [winter, spring, summer, autumn])
for pair in seasons:
im = pair[0].contourf(pair[1], levels=custom_c_levels, cmap=segmented_map, norm=divnorm, vmin=v_min, vmax=v_max)
# -6- Get the positions of the lower right and lower left plot
left, bottom, width, height = axes[3].get_position().bounds
first_plot_left = axes[2].get_position().bounds[0]
# -7- the width of the colorbar
width = left - first_plot_left + width
# -8- Add axes to the figure, to place the color bar in
colorbar_axes = plt.axes([first_plot_left, bottom - 0.15, width, 0.03])
# -9- Add the colour bar
cbar = plt.colorbar(im, colorbar_axes, orientation='horizontal')
# -10- Label the colour bar and add ticks
cbar.set_label("Custom Colorbar")
</code></pre>
<p><a href="https://i.stack.imgur.com/kXDYd.png" rel="nofollow noreferrer">Figure 3. Final figure, including correct contours and single colorbar.</a></p>
<p><strong>And it works!</strong></p>
<p>But I'm sure the community is able to do that in a <em>much more straight forward kind of way</em>.</p>
<p><strong>Challenge accepted? Then I would really appreciate if you could show me how to do that in a more simple approach.</strong></p>
<p>ps: I give random data because I think it is more reasonable for the exercise (not using additional libraries such as iris and cartopy). However you can imagine that we are actually looking at a world map with land surface temperature ;).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:56:42.643",
"Id": "499174",
"Score": "0",
"body": "Interesting question. The colorbars end up uniformly distributed out from 0, so why not just find the global min and max values, take their absolute values, and generate a fixed number of ticks from those, using something like ``np.linspace``? I'm not super familiar with making contour plots and not sure what its auto-coloring does that's more complicated than just that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:25:51.847",
"Id": "499261",
"Score": "0",
"body": "The goal is basically that the contours (i.e. the colors) are the same for the positive as well as the negative case. In this case a contour matches a change in 1.5 no matter if positive or negative. Your idea has potential. I started out initially with something like that but couldn't figure out a nice approach that would generally work. I will give it another thought. Thank you @scnerd"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T07:33:41.850",
"Id": "499262",
"Score": "0",
"body": "The problem is basically that it's not straight forward to use ```np.linspace``` if you desire an optimal range below and above 0. E.g. imagine the min is -15 and the max 10, and you would like to have \"nice\" contours. What could then be an approach to define a nice amount of ticks automatically? E.g. ```np.linspace(-15,10,?)```."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:32:48.380",
"Id": "499323",
"Score": "0",
"body": "That's what I meant by \"out from 0\", I was suggesting ``pos_ticks = np.linspace(0, 10, x)`` and ``neg_ticks = np.linspace(0, -15, x)``, then just concatenate those two lists. Whether or not those two x's are the same thing may or may not matter depending on how you build the colormap"
}
] |
[
{
"body": "<p>I conducted some research into the way the color levels are chosen in contourf in the matplotlib python code (<a href=\"https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/contour.py#L1050\" rel=\"nofollow noreferrer\">https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/contour.py#L1050</a>). They use a matplotlib ticker MaxNLocator() instance to define the color levels, here is its documentation <a href=\"https://matplotlib.org/3.3.3/api/ticker_api.html#matplotlib.ticker.MaxNLocator\" rel=\"nofollow noreferrer\">https://matplotlib.org/3.3.3/api/ticker_api.html#matplotlib.ticker.MaxNLocator</a>.</p>\n<p>Then I found this documentation <a href=\"https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-locators.html\" rel=\"nofollow noreferrer\">https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-locators.html</a>.</p>\n<p>This yields the following working solution that is more straight forward than the presented approach (based on the data and colormap initialized above):</p>\n<pre><code>import matplotlib.ticker as ticker \n\n# -1- Find the global min and max values:\ngl_min = np.min(np.stack((winter, spring, summer, autumn))) \ngl_max = np.max(np.stack((winter, spring, summer, autumn)))\n\n# -2- Create a simple plot, where the xaxis is using the found global min and max\nfig, ax = plt.subplots() \nax.set_xlim(gl_min, gl_max)\n\n# -3- Use the MaxNLocator() to get the contours levels\nax.xaxis.set_major_locator(ticker.MaxNLocator())\ncustom_c_levels = ax.get_xticks()\n\n# -4- Clear the figure\nplt.clf()\n\n# -5- Create the diverging norm\ndivnorm = colors.TwoSlopeNorm(vmin=gl_min, vcenter=0, vmax=gl_max)\n\n# -6- plot the figures\nfig, axes = plt.subplots(2, 2)\naxes = axes.flatten()\nseasons = zip(axes, [winter, spring, summer, autumn])\nfor pair in seasons:\n im = pair[0].contourf(pair[1], levels=custom_c_levels, cmap=segmented_map, norm=divnorm, vmin=gl_min, vmax=gl_max)\n\n# -7- Get the positions of the lower right and lower left plot\nleft, bottom, width, height = axes[3].get_position().bounds\nfirst_plot_left = axes[2].get_position().bounds[0]\n\n# -8- the width of the colorbar \nwidth = left - first_plot_left + width\n\n# -9- Add axes to the figure, to place the color bar in\ncolorbar_axes = plt.axes([first_plot_left, bottom - 0.15, width, 0.03])\n\n# -10- Add the color bar\ncbar = plt.colorbar(im, colorbar_axes, orientation='horizontal')\n\n# -12- Label the color bar and add ticks\ncbar.set_label("Custom Colorbar")\n\n# -13- Show the figure\nplt.show()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/0gkxD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0gkxD.png\" alt=\"Figure 1 | Final working example.\" /></a></p>\n<p>The process is simple:\nFirst we have to find the global min and max value (i.e. across all data sets). Then we create a figure and set its limits to the found min/max values. Then we tell the axis that we want to use the MaxNLocator(). Then we can easily extract the found labels and use them as our custom contour levels.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T16:52:29.910",
"Id": "253223",
"ParentId": "253169",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253223",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T10:37:15.387",
"Id": "253169",
"Score": "0",
"Tags": [
"python",
"matplotlib"
],
"Title": "What do you think about my version of matplotlib subplots of filled contours with a \"synchronized\" color scheme?"
}
|
253169
|
<p>I made this project to practice object-oriented programming. I have implemented <code>operator+</code> and <code>operator+=</code>. The rationale behind <code>struct cache</code> are</p>
<ol>
<li>I don't necessarily need to traverse the entire container to display the value.</li>
<li>Using a <code>struct cache</code> makes it possible to modify its value even in a const method</li>
</ol>
<p>I also considered eliminating the container entirely and representing <code>BigInt</code> as a string, that might have been a better approach.</p>
<p>Here is my code</p>
<h2>BigInt.h</h2>
<pre><code>#ifndef BIGINTEGER_H_
#define BIGINTEGER_H_
#include <iostream>
#include <deque>
#include <string>
namespace MyBigInteger
{
struct cache
{
bool has_changed{true};
std::string cache_value{""};
};
class BigInt
{
friend std::ostream& operator<<(std::ostream& os, const BigInt& bigint);
friend std::istream& operator>>(std::istream& is, BigInt& bigint);
public:
BigInt();
explicit BigInt(const std::string &str_number);
BigInt& operator+=(const BigInt& rhs);
BigInt operator+(const BigInt& lhs) const;
size_t size() const;
private:
cache* string_rep;
size_t bigint_size;
std::deque<int8_t> elems;
std::string get_new_cache_value() const;
};
int8_t to_digit(const char chr);
char to_char(const int value);
}
#endif
</code></pre>
<h2>BigInt.cpp</h2>
<pre><code>#include "BigInt.h"
#include <algorithm>
namespace MyBigInteger
{
BigInt::BigInt()
: string_rep{new cache{false, ""}} {}
BigInt::BigInt(const std::string& str_number)
: string_rep{new cache{false, str_number}}, bigint_size{str_number.size()}
{
for(const auto chr : str_number)
elems.push_back(to_digit(chr));
}
int8_t to_digit(const char chr)
{
return chr - '0';
}
char to_char(const int value)
{
return value + '0';
}
std::ostream& operator<<(std::ostream& os, const BigInt& bigint)
{
if(bigint.string_rep->has_changed)
{
bigint.string_rep->cache_value = bigint.get_new_cache_value();
bigint.string_rep->has_changed = false;
}
os << bigint.string_rep->cache_value;
return os;
}
std::istream& operator>>(std::istream& is, BigInt& bigint)
{
is >> bigint.string_rep->cache_value;
return is;
}
std::string BigInt::get_new_cache_value() const
{
std::string temp_str;
std::for_each(elems.cbegin(), elems.cend(), [&](const int x)
{ temp_str += to_char(x); });
return temp_str;
}
BigInt& BigInt::operator+=(const BigInt& rhs)
{
*this = std::move(*this + rhs);
return *this;
}
BigInt BigInt::operator+(const BigInt& rhs) const
{
BigInt res;
res.string_rep = new cache{true, ""};
unsigned total = 0;
unsigned carry = 0;
auto beg = elems.crbegin(), rhs_beg = rhs.elems.crbegin();
for(; beg != elems.crend() && rhs_beg != rhs.elems.crend();
++beg, ++rhs_beg)
{
total = *beg + *rhs_beg + carry;
carry = total / 10;
res.elems.push_front(total % 10);
}
if(beg == elems.crend() && rhs_beg == rhs.elems.crend())
return res;
else if(beg == elems.crend())
{
for(; rhs_beg != rhs.elems.crend(); ++rhs_beg)
{
total = *rhs_beg + carry;
carry = total / 10;
res.elems.push_front(total % 10);
}
}
else
{
for(; beg != elems.crend(); ++beg)
{
total = *beg + carry;
carry = total / 10;
res.elems.push_front(total % 10);
}
}
if(carry)
res.elems.push_front(carry);
return res;
}
size_t BigInt::size() const
{
return bigint_size;
}
}
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "BigInt.h"
#include <iostream>
using namespace MyBigInteger;
int main()
{
BigInt my_bigint{"123456789123456789123456789"};
BigInt my_bigint2{"24682468246824682468"};
std::cout << "my_bigint + my_bigint2: " << my_bigint + my_bigint2 << '\n';
my_bigint += my_bigint2;
std::cout << "my_bigint after my_bigint += my_bigint2: " << my_bigint << '\n';
BigInt my_bigint3{};
std::cout << "default my_bigint3: " << my_bigint3 << '\n';
std::cin >> my_bigint3;
std::cout << "my_bigint3 after input: " << my_bigint3 << '\n';
BigInt my_bigint4{my_bigint3};
std::cout << "After copy constructor: " << my_bigint4 << '\n';
my_bigint4 = my_bigint;
std::cout << "After copy assignment: " << my_bigint4 << '\n';
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Use <code>constexpr</code></h2>\n<p>These functions</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> int8_t to_digit(const char chr)\n {\n return chr - '0';\n }\n\n char to_char(const int value)\n {\n return value + '0';\n }\n</code></pre>\n<p>can be marked <code>constexpr</code>. You are telling that it is possible to calculate the value at compile-time. <code>constexpr</code> also implies <code>inline</code>, resulting in faster execution time. Note that after marking it <code>constexpr</code> you must define it with the declaration.</p>\n<hr />\n<h2>Use <code>string_view</code></h2>\n<p>As your class name suggests, you are going to be working with <strong>big</strong> numbers, i.e <strong>big</strong> strings will come. In that case, copying can be very bad and slow.</p>\n<p>In your class constructor</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> BigInt::BigInt(const std::string& str_number)\n : string_rep{new cache{false, str_number}}, bigint_size{str_number.size()}\n {\n for(const auto chr : str_number)\n elems.push_back(to_digit(chr));\n }\n</code></pre>\n<p>I refactored it for this example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct cache\n{\n std::string str;\n};\n\nstruct BigInt\n{\n cache c;\n\n BigInt(const std::string& str)\n : c{ str.data() }\n}\n</code></pre>\n<p>Assuming there is no small string optimization, you will be calling <code>new</code> 2 times, once for constructing <code>str</code>, and the other time for copying into <code>c.str</code>.</p>\n<p>However, if you use <code>string_view</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct cache\n{\n std::string str;\n};\n\nstruct BigInt\n{\n cache c;\n\n BigInt(std::string_view str)\n : c{str.data()}\n {}\n\n};\n</code></pre>\n<p>You will be calling <code>new</code> only once, to construct the string and that same string into the member.</p>\n<hr />\n<h2>TODO</h2>\n<p>Here are some things that you left out as far as I can remember</p>\n<ul>\n<li>Operators - <code>-,*,/,%,^,&,~,|, ==, ++, --</code></li>\n<li>Casting - Decide whether your data type should be able to cast to the primitive ones, or the opposite</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:10:06.147",
"Id": "499196",
"Score": "0",
"body": "I would implement those `operators`, I just wanted review of what I have done so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:12:08.460",
"Id": "499199",
"Score": "0",
"body": "Adding `inline` is reductant, the compiler should be smart enough to select what to inline, but great review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:15:43.627",
"Id": "499201",
"Score": "0",
"body": "@theProgrammer Yes surely, but the compiler can't inline your original function since the declaration and definition are split"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:29:25.687",
"Id": "253184",
"ParentId": "253172",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:43:06.257",
"Id": "253172",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"bigint"
],
"Title": "A BigInteger class"
}
|
253172
|
<p>I am on the way implementing my own STL-like library in C language. The main reasons are learning DS&A better, as well as the C language itself. Here I am trying to implement Vector (a.k.a. array-list) data structure. Would really appreciate to hear constructive criticism. Please, kindly give your thoughts on how the code can be further improved performance, readability, and maintenance wise.</p>
<p>File: ue_vector.h</p>
<pre><code>#ifndef UE_VECTOR_H
#define UE_VECTOR_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
typedef struct ue_vector {
size_t length;
size_t capacity;
size_t data_size;
void** data;
} ue_vector;
ue_vector* ue_vector_start (size_t init_capacity, size_t data_size);
void ue_vector_finish (ue_vector* vect);
size_t ue_vector_length (const ue_vector* const vect);
size_t ue_vector_capacity (const ue_vector* const vect);
size_t ue_vector_data_size (const ue_vector* const vect);
bool ue_vector_is_empty (const ue_vector* const vect);
void ue_vector_resize (ue_vector* vect);
void ue_vector_shrink_to_fit (ue_vector* vect);
void ue_vector_add_back (ue_vector* vect, const void* const to_be_added);
void ue_vector_add_front (ue_vector* vect, const void* const to_be_added);
void ue_vector_add_in (ue_vector* vect, const void* const to_be_added, size_t pos);
void* ue_vector_get_back (const ue_vector* const vect);
void* ue_vector_get_front (const ue_vector* const vect);
void* ue_vector_get_in (const ue_vector* const vect, size_t pos);
void ue_vector_delete_back (ue_vector* vect);
void ue_vector_delete_front (ue_vector* vect);
void ue_vector_delete_in (ue_vector* vect, size_t pos);
#endif // UE_VECTOR_H
</code></pre>
<p>File: ue_vector.c</p>
<pre><code>#include "ue_vector.h"
ue_vector* ue_vector_start(size_t init_capacity, size_t data_size) {
if (init_capacity == 0)
init_capacity = 4;
ue_vector* new_vect = (ue_vector*)malloc(sizeof(ue_vector));
assert(new_vect != NULL);
new_vect->data = (void**)malloc(sizeof(void*) * init_capacity);
assert(new_vect->data != NULL);
new_vect->data_size = data_size;
new_vect->capacity = init_capacity;
new_vect->length = 0;
return new_vect;
}
void ue_vector_finish(ue_vector* vect) {
for (size_t i = 0; i < ue_vector_length(vect); ++i)
free(vect->data[i]);
free(vect->data);
free(vect);
}
size_t ue_vector_length(const ue_vector* const vect) {
assert(vect != NULL);
return vect->length;
}
size_t ue_vector_capacity(const ue_vector* const vect) {
assert(vect != NULL);
return vect->capacity;
}
size_t ue_vector_data_size(const ue_vector* const vect) {
assert(vect != NULL);
return vect->data_size;
}
bool ue_vector_is_empty(const ue_vector* const vect) {
assert(vect != NULL);
return ue_vector_length(vect) == 0;
}
void ue_vector_resize(ue_vector* vect) {
assert(vect != NULL);
if (ue_vector_length(vect) == ue_vector_capacity(vect)) {
vect->capacity += ue_vector_capacity(vect) / 2;
vect->data = (void**)realloc(vect->data, sizeof(void*) * ue_vector_capacity(vect));
}
}
void ue_vector_shrink_to_fit(ue_vector* vect) {
assert(vect != NULL);
assert(!ue_vector_is_empty(vect));
vect->capacity = ue_vector_length(vect) + 1;
vect->data = (void**)realloc(vect->data, sizeof(void*) * ue_vector_capacity(vect));
}
void ue_vector_add_back(ue_vector* vect, const void* const to_be_added) {
assert(vect != NULL);
assert(to_be_added != NULL);
if (!ue_vector_is_empty(vect))
ue_vector_add_in(vect, to_be_added, ue_vector_length(vect));
else
ue_vector_add_in(vect, to_be_added, 0);
}
void ue_vector_add_front(ue_vector* vect, const void* const to_be_added) {
assert(vect != NULL);
assert(to_be_added != NULL);
ue_vector_add_in(vect, to_be_added, 0);
}
void ue_vector_add_in(ue_vector* vect, const void* const to_be_added, size_t pos) {
assert(vect != NULL);
assert(to_be_added != NULL);
assert(pos <= ue_vector_length(vect));
ue_vector_resize(vect);
vect->data[ue_vector_length(vect)] = (void*)malloc(ue_vector_data_size(vect));
// moving elements
for (size_t i = ue_vector_length(vect); i > pos; --i) {
memcpy(vect->data[i], vect->data[i - 1], ue_vector_data_size(vect));
}
memcpy(vect->data[pos], to_be_added, ue_vector_data_size(vect));
++(vect->length);
}
void* ue_vector_get_back(const ue_vector* const vect) {
assert(vect != NULL);
assert(ue_vector_length(vect) != 0);
return ue_vector_get_in(vect, ue_vector_length(vect) - 1);
}
void* ue_vector_get_front(const ue_vector* const vect) {
assert(vect != NULL);
assert(ue_vector_length(vect) != 0);
return ue_vector_get_in(vect, 0);
}
void* ue_vector_get_in(const ue_vector* const vect, size_t pos) {
assert(vect != NULL);
assert(ue_vector_length(vect) != 0);
assert(pos < ue_vector_length(vect));
return vect->data[pos];
}
void ue_vector_delete_back(ue_vector* vect) {
assert(vect != NULL);
assert(!ue_vector_is_empty(vect));
ue_vector_delete_in(vect, ue_vector_length(vect) - 1);
}
void ue_vector_delete_front(ue_vector* vect) {
assert(vect != NULL);
assert(!ue_vector_is_empty(vect));
ue_vector_delete_in(vect, 0);
}
void ue_vector_delete_in(ue_vector* vect, size_t pos) {
assert(vect != NULL);
assert(!ue_vector_is_empty(vect));
assert(pos < ue_vector_length(vect));
// moving elements
for (size_t i = pos; i < ue_vector_length(vect) - 1; ++i) {
memcpy(vect->data[i], vect->data[i + 1], ue_vector_data_size(vect));
}
free(vect->data[ue_vector_length(vect) - 1]);
--(vect->length);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-14T06:19:59.250",
"Id": "499803",
"Score": "0",
"body": "using `assert()` for validation is dangerous. In production `assert()` is a no-op and thus has no protective value. If any operations fails that was protected by an assert it now results in broken code that at best results in a crash at worst keeps on running have just corrupted some other piece of memory."
}
] |
[
{
"body": "<h1>Assert is a Debug Tool</h1>\n<p>The code makes heave use of the assert macro() for logic. The problem with this is that when the code is optimized and not being debugged the code generated for <code>assert()</code> statement simply disappears. If you want the error checking to be there in production code than don't use the <a href=\"http://www.cplusplus.com/reference/cassert/assert/\" rel=\"nofollow noreferrer\">assert()</a> function, use if statements and standard print methods.</p>\n<blockquote>\n<p>This macro is disabled if, at the moment of including <assert.h>, a macro with the name NDEBUG has already been defined. This allows for a coder to include as many assert calls as needed in a source code while debugging the program and then disable all of them for the production version by simply including a line like:\n#define NDEBUG\nat the beginning of the code, before the inclusion of <assert.h>.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:18:35.023",
"Id": "499154",
"Score": "0",
"body": "I only need error checking during Debug mode. The Release code is supposed to be error free. That's is why I chose assertions over ugly & noisy if statements... Correct me if I am wrong, though,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:23:23.903",
"Id": "499155",
"Score": "1",
"body": "@khasanovasad Do not assume that malloc() won't fail in production. Do not assume that the user of the library will provide correct inputs to begin with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:53:32.503",
"Id": "499160",
"Score": "0",
"body": "Would it be OK if I used If-Else style of error handling after malloc() and use assertions elsewhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:00:48.383",
"Id": "499162",
"Score": "0",
"body": "All values that malloc() is based on should be checked before use. One of the main problems with any code is user input and there should be checking on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:04:58.043",
"Id": "499163",
"Score": "0",
"body": "Will keep that in mind. Thanks a ton )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:59:40.457",
"Id": "499393",
"Score": "0",
"body": "I believe there was a way for debug mode, I think that could be used with `#if`. But that of course would only be used for *extra* checks."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T13:15:11.580",
"Id": "253176",
"ParentId": "253173",
"Score": "2"
}
},
{
"body": "<p>Design:</p>\n<ul>\n<li><p>Overall, function naming and const correctness etc looks good. The header is nicely formatted and easy to read. Most function names are self-explanatory, though I wouldn't use <code>start</code> and <code>finish</code>.</p>\n<p>Commonly used names for the constructor are <code>init</code>, <code>create</code>, <code>construct</code>, <code>alloc</code> etc.<br />\nCommonly used names for the destructor is <code>delete</code>, <code>destruct</code>, <code>free</code>, <code>cleanup</code> etc.</p>\n</li>\n<li><p>I'm getting some déjà vu from this whole vector implementation - check out <a href=\"https://codereview.stackexchange.com/questions/249508/type-independent-vector-in-c/249612#249612\">this review</a> regarding how you could implement the concept of opaque type.</p>\n</li>\n<li><p>It's strange and needlessly complicated to use <code>void**</code> for the data. Why can't you use <code>void*</code>, since all data stored can be assumed to be of the same type?</p>\n</li>\n<li><p><code>void*</code> is overall not very meaningful when dealing with raw data, so you should consider swapping it for <code>uint8_t*</code>.</p>\n</li>\n<li><p>You should implement some manner of error handling through a return type <code>enum</code> or similar, rather than using <code>assert</code>.</p>\n</li>\n<li><p>Generally, when developing actual library quality data containers, you should avoid excessive calls to malloc & realloc. These are very slow functions and calling them often also causes heap fragmentation and poor cache use etc. It is therefore custom to allocate a "x times alignment" capacity per vector instance, regardless of how much memory the user actually needs. There's plenty of heap memory, execution speed is much more important than a few bytes of RAM here and there.</p>\n<p>Example: Lets say you have a 32 bit CPU = 4 byte word alignment. The user wants to store 10 bytes of data. Regardless of that, you allocate a minimum of 4 * 8 = 32 bytes and keep track of how much of that memory that's used. 4 = alignment and 8 = some conventient multiple of 8. Then when the user requests a resize to 20 bytes, you simply mark 20 out of your 32 allocated bytes as used. Only when they go beyond the allocated size do you call malloc. But this time you allocate a total of 4 * 8*2 = 64 bytes. Next time 128 bytes, and so on. This is to reduce the amount of calls to malloc functions. And there is usually no need to shrink the allocated space, ever.</p>\n<p>The above is especially important for "<code>vector::push_back</code>"-like APIs, where you add one item at a time! You can't call malloc each time that happens, or you would have been better off using a linked list.</p>\n</li>\n<li><p>With the above in mind, capacity should be handled internally by your code, not by the user! <code>capacity</code> should be a private variable and the caller shouldn't meddle with it.</p>\n</li>\n</ul>\n<p>Bugs:</p>\n<ul>\n<li>You don't check if <code>realloc</code> succeeded.</li>\n</ul>\n<p>Style:</p>\n<ul>\n<li>It's a bit subjective, but in my opinion <code>const * const</code> function parameters are just clutter and should be changed to <code>const*</code>. The parameter is a <em>local copy</em> of the original pointer and the caller really couldn't care less if the function modifies that pointer internally. What meaningful change could a function do to a copy of a <code>void*</code> anyway?</li>\n<li><code>--(vect->length);</code> looks strange, just write <code>vect->length--;</code>.</li>\n<li>Casting the result of malloc/realloc is pretty pointless and just adds clutter. In particularly, casting from <code>void*</code> to <code>void*</code> is very pointless.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:16:25.590",
"Id": "499394",
"Score": "0",
"body": "Thank you very much. I am actually on the way of implementing my own enum error type."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:36:35.283",
"Id": "253253",
"ParentId": "253173",
"Score": "3"
}
},
{
"body": "<p><strong>Unneeded exposure</strong></p>\n<p>The details of <code>ue_vector</code> are not needed in the *.h file. <code>typedef struct ue_vector ue_vector;</code> is sufficient and promotes good information hiding.</p>\n<p>Save the complete definition for the *.c file.</p>\n<p><strong>Excess #include</strong></p>\n<p>In the .h file only, <code><stdlib.h></code> and <code><stdbool.h></code> needed.</p>\n<p>For .h files, good to keep <em>includes</em> to a minimum to reduce public name collisions and improve compile time.</p>\n<p>Those other includes should be added to the *.c file.</p>\n<p><strong>Consider <code>apply()</code></strong></p>\n<p>A candidate function to add would be</p>\n<pre><code>int ue_vector_apply(ue_vector *vect, int (*f)(void *state, void *data), void *state);\n</code></pre>\n<p>I have found this useful - especially for printing the data.</p>\n<p>This applies <code>f()</code> to each element of the vector.</p>\n<pre><code>// Pseudo code\nint ue_vector_apply(ue_vector *vect, int (*f)(void *state, void *data), void *state) {\n for each data in the vector {\n int result = f(state, vect->data);\n if (result) return result;\n }\n return 0;\n}\n</code></pre>\n<p><strong>Capacity</strong></p>\n<p>I see little value exposing <code>.capacity</code> to the user.</p>\n<p>Could drop that:</p>\n<pre><code>// ue_vector* ue_vector_start (size_t init_capacity, size_t data_size);\nue_vector* ue_vector_start (size_t data_size);\n\n// size_t ue_vector_capacity (const ue_vector* const vect);\n</code></pre>\n<p><strong>Documentation</strong></p>\n<p>The .h deserve comments explaining the overall functionality and some function details/limits.</p>\n<p>Assume the user does <strong>not</strong> have or may not want access to the *.c file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T20:06:38.763",
"Id": "499630",
"Score": "0",
"body": "Thank you for your suggestions! You really mean that including only necessary files in .h and others in .c files reduce compilation time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T00:24:00.177",
"Id": "499649",
"Score": "0",
"body": "@khasanovasad Assume your `ue_vector.h` file is included in _many_ other .c files - it is a generic vector code after all. Wise to spend the effort to 1) reduce compile time in those `N` other files and 2) those other files may not like your including unnecessary .h files. As for this `ue_vector.c` file, there are few concerns with a reduced .h file set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T07:49:09.737",
"Id": "499663",
"Score": "0",
"body": "Makes sense. Thanks a ton"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T19:33:00.770",
"Id": "253319",
"ParentId": "253173",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253253",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T11:50:52.207",
"Id": "253173",
"Score": "1",
"Tags": [
"algorithm",
"c",
"stl"
],
"Title": "Generic Vector implemented in C language"
}
|
253173
|
<p>A codepoint in UTF-8 can be represented by one to four bytes. Given a codepoint, I need to determine the length (in bytes) of the codepoint if it were represented in UTF-8. For this, I've written the following function:</p>
<pre class="lang-cpp prettyprint-override"><code>char utf8_char_size(uint32_t ch) {
if (ch < 0x80) return 1;
if (ch < 0x800) return 2;
if (ch < 0x10000) return 3;
return 4;
}
</code></pre>
<p>It works, and it's pretty simple to understand. However, I'm afraid that branching three times per codepoint could lead to a large amount of branch mispredictions which would slow my code down tremendously. Is this code fine?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:48:37.583",
"Id": "499171",
"Score": "1",
"body": "\"slow my code down tremendously\" - why? sure, branch mispredictions can be bad, but there are *many* other things that can blow you out of the water. Why do you think you need to optimize this tiny function first?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:50:56.453",
"Id": "499173",
"Score": "1",
"body": "If you truly need a branchless approach, you could do this with only bitwise operators, which shouldn't cause branching. Otherwise you can use ternary and/or boolean operators, which may or may not cause branching depending on architecture"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:08:28.217",
"Id": "499176",
"Score": "0",
"body": "@Dannnno Could you show it with only bitwise operators?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:24:59.957",
"Id": "499182",
"Score": "0",
"body": "@superbrain I have no interest in writing it out, because it'll be painful. General idea will look like this: (1) identify if there is a bit set above 0x10000 (2) identify if there is a bit set between 0x800 and 0x10000 (3) identify if there is a bit set between 0x80 and 0x800. (4) Sum those 3 numbers and add 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:26:04.143",
"Id": "499183",
"Score": "0",
"body": "off the top, I figure you'd do a bitshift down into your range, then |= each bit in the range until you have either a 1 or a 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:27:36.320",
"Id": "499186",
"Score": "2",
"body": "@Dannnno So you'd explicitly look at each bit separately? Then I suspect `return 1 + (ch >= 0x80) + (ch >= 0x800) + (ch >= 0x10000)` would be faster..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:36:13.033",
"Id": "499189",
"Score": "0",
"body": "Almost certainly; but the request was for bitwise only"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:02:20.077",
"Id": "499193",
"Score": "1",
"body": "Another possibility: `return ffs(ch)[\"\\1\\1\\1\\1\\1\\1\\1\\2\\2\\2\\2\\2\\2\\2\\2\\3\\3\\3\\3\\3\\3\\3\\3\\3\\4\\4\\4\\4\\4\\4\\4\\4\"];` or perhaps: `return 1 + ((0xffffaaaa95554000 >> 2 * ffs(ch)) & 2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:09:45.337",
"Id": "499195",
"Score": "2",
"body": "[`ffs()`](https://man7.org/linux/man-pages/man3/ffs.3.html) is POSIX, and indeed not in the standard library. With C++20 you could use [`std::countl_zero()`](https://en.cppreference.com/w/cpp/numeric/countl_zero) to similar effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:10:21.253",
"Id": "499197",
"Score": "1",
"body": "@G.Sliepen im benchmarking all of our solutions, so far yours is the fastest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:11:21.410",
"Id": "499198",
"Score": "0",
"body": "@AryanParekh Please do create an answer containing the various alternative solutions and the benchmark results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:13:00.973",
"Id": "499200",
"Score": "0",
"body": "@G.Sliepen Yes Il do that, Let more solutions come in :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:20:11.357",
"Id": "499203",
"Score": "0",
"body": "@G.Sliepen Would you happen to know how to call `ffs` in MSVC? I see `_BitScanForward` but it takes a 64-bit number,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:23:27.173",
"Id": "499205",
"Score": "0",
"body": "You can replace `ffs()` with `31 - std::countl_zero()`. GCC recognizes this pattern, and on x86_64 it will use the `bsr` instruction. However, Clang uses `lzcnt` and has to subtract the result from 31 somehow. So changing the functions to have the string and constant reversed might be faster with Clang. Different CPU architectures also have different ways to report the first set bit. As for `ffs()` on MSVC: use [_BitScanReverse](https://docs.microsoft.com/en-us/cpp/intrinsics/bitscanreverse-bitscanreverse64?view=msvc-160)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T16:24:04.057",
"Id": "499206",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117031/discussion-between-aryan-parekh-and-g-sliepen)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:19:37.150",
"Id": "253177",
"Score": "2",
"Tags": [
"c++",
"performance",
"utf-8"
],
"Title": "Find the UTF-8 Length of a given codepoint"
}
|
253177
|
<p>A box contains a number of chocolates that can only be removed 1 at a time or 3 at a a time. How many ways can the box be emptied?
The answer can be very large so return it modulo of 10^9+7</p>
<pre><code>def f(n):
if n==1 or n==2:return 1
if n==3: return 2
else: return f(n-3)+f(n-1)
ip=int(input())
if 1<=ip<(10**9):
print(f(ip)%1000000007)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:42:55.313",
"Id": "499169",
"Score": "1",
"body": "One way to improve your approach is by adding [memoization](https://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:01:13.020",
"Id": "499175",
"Score": "0",
"body": "sry but it simple mistake from my side,I actually retyped the code to match code in my compiler"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T23:19:52.930",
"Id": "499240",
"Score": "0",
"body": "What exactly is your question? Surely you don't want to print out 10**9 values?"
}
] |
[
{
"body": "<h1>Code Style</h1>\n<p>Various <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8</a> style guidelines:</p>\n<ul>\n<li>Avoid one-line if statements</li>\n<li>Add a blank line after each function declaration.</li>\n<li>Use one space around binary operators</li>\n<li>Avoid unnecessary parenthesis.</li>\n</ul>\n<p>Applying the above guidelines, your code might look more like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def f(n):\n if n == 1 or n == 2:\n return 1\n if n == 3:\n return 2 \n else:\n return f(n-3) + f(n-1)\n\nip = int(input())\nif 1 <= ip < 10**9: \n print(f(ip) % 1000000007)\n</code></pre>\n<p>This revised code is much more readable.</p>\n<h1>Unnecessary elses</h1>\n<p>Why do you have <code>else:</code> before <code>return f(n-3)+f(n-1)</code>? All prior code paths ended in a return statement. Use:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if n == 1 or n == 2:\n return 1\n if n == 3:\n return 2\n return f(n-3) + f(n-1)\n</code></pre>\n<p>Or</p>\n<pre class=\"lang-py prettyprint-override\"><code> if n == 1 or n == 2:\n return 1\n elif n == 3:\n return 2\n else:\n return f(n-3) + f(n-1)\n</code></pre>\n<h1>Names</h1>\n<p>Apart from exceptions like a few single letter variable names (<code>i</code>, <code>j</code>, <code>k</code>, <code>n</code>, <code>x</code>, <code>y</code>, and <code>z</code>), variable names should be long enough to be descriptive. While <code>n</code> is barely acceptable; <code>num_chocolates</code> would be much better. But <code>ip</code> is definitely not a good, descriptive name.</p>\n<p>Function names should also be descriptive. If you have a math problem, which uses the a function named “f”, it is acceptable to call your function <code>f</code>. When you are computing the number of ways to remove chocolates from a box, you should use a more descriptive name, like <code>ways_to_remove_chocolates</code>.</p>\n<h1>Comments and documentation</h1>\n<p>Functions should be documented. Python’s <code>"""docstrings"""</code> make this easy. Type hints can be added to indicate what the arguments are expected to be, and what the function will return:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def ways_to_remove_chocolates_from_box(num_chocolates_in_box: int) -> int:\n """\n Computes the number of ways to remove chocolates from a box,\n when chocolates are only allowed to be removed one or three at a time.\n """\n\n if num_chocolates_in_box == 1 or num_chocolates_in_box == 2:\n return 1\n ...\n</code></pre>\n<h1>Input validation</h1>\n<p>If you run your program, there is no “prompt” describing that the program expects an input. That may be forgivable in a programming challenge where the unexpected output would confuse the automated grader.</p>\n<p>But <code>1.5</code>, <code>hello</code> or various other invalid integer inputs will cause the program to crash. Maybe you consider that acceptable output, but most people would not.</p>\n<p>Worse is valid integer inputs like <code>0</code>, or <code>-10</code> which silently produce no output at all. An <code>else:</code> clause that prints a message like “That input is out of range” should be added.</p>\n<h1>Memoization</h1>\n<p>You compute the same values over and over again. You could avoid this, and dramatically improve your code execution times, by added:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from functools import lru_cache\n@lru_cache\n</code></pre>\n<p>at the start of your program. What that does, how it works, and why it works I’ll leave as an <em>exercise to the student</em>.</p>\n<p><strong>Note</strong>: there are better ways to solve this problem, which do not involve, memoization, <code>@lru_cache</code> helpers, or even dynamic programming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T21:52:36.313",
"Id": "499236",
"Score": "1",
"body": "I think it's quite interesting that such a limited cache works well here. You can even limit it much further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:51:34.327",
"Id": "499246",
"Score": "1",
"body": "`lru_cache(3)` suffices. The default is 128. If we change the order in the recursive call to `return f(n-1) + f(n-3)`, then we need `lru_cache(5)`. I don't think it's as trivial as the \"exercise to the student\" makes it sound :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T03:15:52.657",
"Id": "499257",
"Score": "1",
"body": "@KellyBundy Oh, \"_exercise to the student_\" was not meant to imply trivial. Decorators are far from trivial, and it may not even be obvious that the `@lru_cache` is not a complete statement. The mystery of what those two line do, how it works, and when it won't work is part of the learning experience. I just opened the door; they need to walk through it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T03:31:13.307",
"Id": "499258",
"Score": "0",
"body": "I'm curious: Did you think it through yourself? I think I understand why it works, but I'm having difficulty explaining the `f(n-1) + f(n-3)` version..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T19:23:57.217",
"Id": "253192",
"ParentId": "253178",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T14:20:26.540",
"Id": "253178",
"Score": "-4",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Removing chocolates 1 & 3 at a time"
}
|
253178
|
<p>I am learning JavaScript. Please review my code. Just created this Celsius & Fahrenheit Converter. Any suggestions to improve my code will be really helpful.</p>
<pre><code>const celsiusToFahrenheit = document.getElementById('celsiusToFarhenhite');
const fahrenheitToCelsius = document.getElementById('farhenhiteToCelsius');
const converterButton = document.querySelector('.calculate');
converterButton.addEventListener('click', function(event){
event.preventDefault();
const celsiusToFahrenheitValue = (celsiusToFahrenheit.value * 9/5 + 32);
const fahrenheitToCelsiusValue = (fahrenheitToCelsius.value - 32) * 5/9;
if(celsiusToFahrenheit.value){
document.write(`<h1>Celcius To Fahrenheit Result: </h1> ${celsiusToFahrenheitValue} &#8457;`);
}else if (fahrenheitToCelsius.value){
document.write(`<h1>Fahrenheit To Celcius Result: </h1> ${fahrenheitToCelsiusValue} &#8451;`);
}else{
document.write(`<h1>You must enter a number!</h1>`);
}
})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:13:13.613",
"Id": "499177",
"Score": "0",
"body": "@Dannnno Thank you, Sir."
}
] |
[
{
"body": "<p><strong>Use proper spelling</strong> - it'll looks more professional and can prevent bugs stemming from the typo. <code>Farhenhite</code> should be <code>Fahrenheit</code>, and <code>Celcius</code> should be <code>Celsius</code>.</p>\n<p><strong>Use proper indentation</strong> - every new block should open a new indentation level. You're doing this well with the <code>if</code>/<code>else</code>s, but you should also do it for the whole click listener as well:</p>\n<pre><code>converterButton.addEventListener('click', function(event){\n event.preventDefault();\n\n const celsiusToFahrenheitValue = (celsiusToFahrenheit.value * 9/5 + 32);\n const fahrenheitToCelsiusValue = (fahrenheitToCelsius.value - 32) * 5/9;\n // etc\n</code></pre>\n<p><strong><code>preventDefault</code>?</strong> Is the button inside a <code><form></code>? If so, the <code>preventDefault</code> is fine. Otherwise, it won't do anything and can be removed.</p>\n<p><strong>Avoid <code>document.write</code></strong> - it can be insecure and somewhat confusing. Here, since it's called after the page loads, it will replace the whole document with the new HTML, which is probably not what you want - you'd probably rather preserve the converter and let people continue to convert after pressing the button once. Instead, populate, say, a results element with the results.</p>\n<p><strong>Confusing variable names</strong> Without reading the variable definition, it isn't entirely clear what the difference between <code>celsiusToFahrenheitValue</code> and <code>celsiusToFahrenheit.value</code> is. Consider only calculating the new value <em>when it's needed</em>, inside the <code>if</code> statements, and calling it something like <code>convertedToFah</code>. Also consider renaming <code>celsiusToFahrenheit</code> to just plain <code>celsius</code>, since the value it will hold is the plain celcius value.</p>\n<pre><code><h1 class='conversion-type'></h1>\n<div class='result'></div>\n</code></pre>\n<pre><code>if (celsius.value) {\n const convertedToFah = (celsius.value * 9/5 + 32);\n document.querySelector('.conversion-type').textContent = 'Celsius To Fahrenheit Result:';\n document.querySelector('.result').textContent = `${convertedToFah} ℉`;\n}\n</code></pre>\n<p><strong>When one input is changed, consider clearing the other input</strong> to make it clear what will be converted when the button is pressed - use an <code>input</code> listener.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:14:16.493",
"Id": "499220",
"Score": "0",
"body": "Thank you so much, Sir, I really learned a lot from this answer :) Thank you so much again for taking the time to write this answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:22:57.663",
"Id": "253183",
"ParentId": "253180",
"Score": "3"
}
},
{
"body": "<p>I think you should write your code to more clearly treat nouns as nouns and verbs as verbs. <code>celsiusToFahrenheit</code> is a noun, but its name makes it sound like a verb. Getting rid of the to part makes your variable names simpler, and more clearly nouns.</p>\n<p>The line <code>celsiusToFahrenheitValue = (celsiusToFahrenheit.value * 9/5 + 32);</code> is a verb, but you're doing it in a <code>const</code> declaration, making it seem like a noun. In addition, you only need to calculate one. Moving the declaration into if-branches both saves calculation, makes it clearer that you're doing a calculation, and allows you to not introduce another const.</p>\n<p>Your if-then logic catches the case where neither are set, but doesn't anticipate the possibility that both are set. You should either disable one entry when the other is entered, or have logic dealing with this case. You could also separate out the two converter: have an input box for Celcius, a "convert from Celcius to Farenheit" button, and an output box for the calculation, and then another input box for Farenheit, "convert from Farenheit to Celcius" button, and another output box for that output.</p>\n<p>Some of your lines are almost 100 characters long. If a language uses semicolons to demarcate commands, that implies that it ignores carriage returns. So if a line is getting long, you can just put a line break in.</p>\n<p>Javascript isn't my primary language, so hopefully I have the syntax correct on this:</p>\n<pre><code>const Celcius = document.getElementById('celciusToFarhenheit');\nconst Fahrenheit = document.getElementById('farhenheitToCelcius');\nconst converterButton = document.querySelector('.calculate');\n\nconverterButton.addEventListener('click', \n function(event){\n event.preventDefault(); \n if(Celcius.value && !Farenheit.value){\n document.write(`<h1>Celcius To Fahrenheit Result: </h1> \n ${Celcius.value * 9/5 + 32 } &#8457;`);\n } \n if(Farenheit.value && !Celcius.value){\n document.write(`<h1>Celcius To Fahrenheit Result: </h1> \n ${(Fahrenheit.value - 32) * 5/9} &#8451;`); \n } \n if (Celcius.value && Farenheit.value){\n document.write(`<h1>Enter only one number.</h1>`); \n } \n if !(Celcius.value || Farenheit.value){\n document.write(`<h1>You must enter a number!</h1>`);\n } \n }\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T01:56:51.953",
"Id": "253200",
"ParentId": "253180",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253183",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T15:00:13.520",
"Id": "253180",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Celsius and Fahrenheit Converter in JavaScript"
}
|
253180
|
<p>I've started learning Angular (With Angular 10) roughly 2 months ago and I recently began wanting to avoid hard-coding my URLs under any circumstances, but was unable to find anything that satisfied me in Angular's Routing module. I always liked <a href="https://docs.djangoproject.com/en/3.1/ref/urlresolvers/" rel="nofollow noreferrer">Django's "reverse()" utility function</a>. This utility function requires you only to give the name of a path and its namespace. Further parameters are only required if the path itself contains variables that need to be filled. Thusly inspired I sought to implement a simple version of it myself.</p>
<p>The implementation is two-fold:</p>
<ol>
<li>Ensure in app-routing.module.ts that every route has a <code>data</code> attribute that contains a <code>name</code> attribute.</li>
<li>Implement a function that returns the route-path for a given route-name. Fill in variables if necessary</li>
</ol>
<p>What I'd especially like feedback for:</p>
<p>Implement as an Object?: The current implementation of 2) is just a bunch of functions. I'm tempted to make an entire object out of it so that I can grab the Router object through injection in the constructor. That way I'd avoid needing it as a parameter, but I'm still somewhat uncertain in Angular on whether that might make the intended use of this function unnecessarily tedious (wouldn't I need to instantiate the object I create?). Was my choice here a sensible one?</p>
<p>Error Messages?: I have absolutely 0 established best practices yet on error messages. The one thing I know is that ideally they give someone with developer knowledge that never saw the project a roughly accurate idea of what went wrong. If there are any standards beyond that, I don't know of them, but would appreciate some hints of what I should look at.</p>
<p>Variable Names?: I'm currently distinguishing between <strong>Routes</strong> (the object) and <strong>paths</strong> (the string). I'd also have loved to distinguish paths that don't have variables ( e.g. <code>/this/has/no/variables)</code> and those that do (e.g. e.g. /this/has/variable/:variable) but couldn't think of any better words than mashing the word <code>variable</code> in combination with <code>path</code> together in various constellations whenever a path had the potential to have a variable.</p>
<p>Of course any feedback is appreciated though!</p>
<p><strong>Step 1: Ensure that every route has a <code>data</code> attribute</strong></p>
<pre><code>//app-routing.module.ts
//Enforced data attribute with name attribute through typing
const routes: {path: string, component: any, data: {name: string}}[] = [
{path: `SomePath/`, component: SomeComponent, data:{name: "NameForThisPath"}},
...
]
</code></pre>
<p><strong>Step 2: Implement a function that returns the route-path for a given route-name</strong></p>
<pre><code>// src/app/utils/functions/routeBuilder.ts
export function getRoutePath(router: Router, routeName: string, parameters = {}): string{
let variableRoutePath = getVariableRoutePathByName(router, routeName);
if (hasPathVariables(variableRoutePath)){
const variableNames: string[] = getPathVariableNames(variableRoutePath);
for (let variableName of variableNames){
if(!parameters.hasOwnProperty(variableName)) throw `Tried to create path for route ${routeName} but lacked parameter ${variableName}`;
variableRoutePath = variableRoutePath.replace(`:${variableName}`, params[variableName]);
}
}
return `/${variableRoutePath}`;
}
function getVariableRoutePathByName(router: Router, routeName: string): string{
const targetRouteObject: Route = getVariableRouteByName(router, routeName);
return targetRouteObject.path;
}
function hasPathVariables(routePath: string): boolean{
return routePath.includes('/:');
}
function getPathVariableNames(routePath: string): string[]{
const routeSegments: string[] = routePath.split("/");
const pathVariables: string[] = routeSegments.filter((segment: string) => segment.startsWith(":"));
const variableNameStartIndex = 1;
return pathVariables.map(segment => segment.slice(variableNameStartIndex));
}
function getVariableRouteByName(router: Router, routeName: string): Route{
const routes: Route[] = router.config;
const routesWithRouteName: Route[] = routes.filter(pathObject => pathObject.data.name === routeName);
if (routesWithRouteName.length > 1) throw `There is more than 1 route with the name ${routeName}. Please contact the Developer to ensure all routes have unique names.`;
if (routesWithRouteName.length === 0) throw `There is no route with the name ${routeName}. Please contact the Developer to use either a different route name or create a route for this name.`;
const targetRouteObject = routesWithRouteName[0];
return targetRouteObject;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T17:32:17.540",
"Id": "253189",
"Score": "0",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Implementing Django's \"reverse\" functionality in Angular-Routing"
}
|
253189
|
<p>I had to create this method <code>GetModelFormat</code> and wanted to see if there is a better way to format the view model that is being return. I would be happy for any kind of feedback since this is quite critical a part of my application.</p>
<pre><code> static void Main(string[] args)
{
try
{
List<carmake> listofcarmakes = new List<carmake>();
List<carmnodeltype> cartype = new List<carmnodeltype>();
cartype.Add(new carmnodeltype() { TypeId = 1, Type="Red" });
List<carmnodeltype> cartype1 = new List<carmnodeltype>();
cartype1.Add(new carmnodeltype() { TypeId = 2, Type = "Green" });
List<carmodel> carmodel = new List<carmodel>();
carmodel.Add(new carmodel() { Modelid = 4, Model = "535d" , ListOfCarType = cartype });
carmodel.Add(new carmodel() { Modelid = 5, Model = "535", ListOfCarType = cartype1 });
carmake carmakes = new carmake();
carmakes.MakeName = "BMW";
carmakes.Makeid =1;
carmakes.ListOfCarModel = carmodel;
listofcarmakes.Add(carmakes);
var listOfcarmodel = listofcarmakes
.Select(x => new CarViewModel
{
MakeName = x.MakeName,
CarModelViewModel = x.ListOfCarModel?.Select(z => new CarModelViewModel
{
Type = GetModelFormat(z.ListOfCarType)
}).ToList()
}).ToList();
foreach (var obj in listOfcarmodel)
{
foreach (var vm in obj.CarModelViewModel)
{
Console.WriteLine(vm.Type);
}
}
}
catch (Exception ex)
{
ex.ToString();
}
}
private static string GetModelFormat(IEnumerable<carmnodeltype> ListOfModel)
{
StringBuilder builder = new StringBuilder();
foreach (var item in ListOfModel)
{
if (item.Type == "Red")
{
if (item.TypeId == 1)
{
builder.Append("Super Car");
builder.Append("<br>");
}
else if (item.TypeId == 2)
{
builder.Append("<b>diesel engine</b>");
builder.Append("<br>");
}
else
{
builder.Append(item.Type);
builder.Append("<br>");
}
}
}
return builder.ToString();
}
</code></pre>
<p>Model</p>
<pre><code>class carmake
{
public int Makeid { get; set; }
public string MakeName { get; set; }
public List<carmodel> ListOfCarModel { get; set; }
}
class carmodel
{
public int Modelid { get; set; }
public string Model { get; set; }
public List<carmnodeltype> ListOfCarType { get; set; }
}
class carmnodeltype
{
public int TypeId { get; set; }
public string Type { get; set; }
}
class CarViewModel
{
public string MakeName { get; set; }
public string Type { get; set; }
public List<CarModelViewModel> CarModelViewModel { get; set; }
}
class CarModelViewModel
{
public string Model { get; set; }
public string Type { get; set; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T09:37:21.803",
"Id": "499279",
"Score": "2",
"body": "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": "2020-12-08T09:37:55.140",
"Id": "499280",
"Score": "0",
"body": "WRT your code: https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions ."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:18:16.383",
"Id": "253190",
"Score": "1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "ViewModel Format Function"
}
|
253190
|
<p>I created a typing test app. I would love some feedback from you guys about my code so I can improve.
<br>Here is github <strong><a href="https://github.com/Isaayy/JavaScript-projects/tree/master/typing-test" rel="nofollow noreferrer">repo</a></strong> and hosted <strong><a href="https://isaayy.github.io/JavaScript-projects/typing-test/index.html" rel="nofollow noreferrer">preview</a></strong>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
const block = document.querySelector('.words');
const inputBox = document.querySelector('.input');
let wordIds;
let wordsBlock = [];
let currentWord;
let wpm = 0;
let accuracy = 0;
const wordsInBlock = 25;
const keywords = [
'ability',
'able',
'about',
'above',
'accept',
'according',
'account',
'across',
'act',
'action',
'activity',
'actually',
'behavior',
'behind',
'believe',
'benefit',
'best',
'better',
'between',
'beyond',
'big',
'bill',
'billion',
'bit',
'black',
'blood',
'blue',
'board',
'body',
'book',
'born',
'both',
'box',
'boy',
'break',
'case',
'catch',
'cause',
'cell',
'center',
'central',
'century',
'certain',
'certainly',
'chair',
'challenge',
'chance',
'change',
'character',
'charge',
'check',
'child',
'choice',
'choose',
'church',
'citizen',
'city',
'civil',
'claim',
'class',
'clear',
'clearly',
'close',
'coach',
'cold',
'collection',
'college',
'color',
'come',
'commercial',
'common',
'community',
'eight',
'either',
'election',
'else',
'employee',
'end',
'energy',
'enjoy',
'enough',
'enter',
'entire',
'environment',
'environmental',
'especially',
'establish',
'even',
'evening',
'event',
'ever',
'every',
'everybody',
'everyone',
'everything',
'evidence',
'exactly',
'example',
'executive',
'exist',
'expect',
'experience',
'expert',
'explain',
'eye',
'face',
'fact',
'factor',
'fail',
'fall',
'family',
'far',
'fast',
'father',
'fear',
'federal',
'feel',
'feeling',
'few',
'field',
'fight',
'figure',
'fill',
'film',
'final',
'finally',
'financial',
'find',
'fine',
'finger',
'finish',
'fire',
'firm',
'first',
'fish',
'five',
'floor',
'fly',
'focus',
'follow',
'food',
'foot',
'for',
'force',
'foreign',
'forget',
'form',
'former',
'forward',
'four',
'free',
'friend',
'from',
'front',
'full',
'fund',
'future',
'game',
'garden',
'gas',
'general',
'generation',
'get',
'girl',
'give',
'glass',
'go',
'goal',
'good',
'government',
'great',
'green',
'ground',
'group',
'grow',
'growth',
'guess',
'gun',
'guy',
'hair',
];
// ######################################################################
// Generate keywords
const generateOutput = () => {
let randomNumber;
for (let i = 0; i < wordsInBlock; i++) {
randomNumber = Math.floor(Math.random() * keywords.length);
wordsBlock.push(keywords[randomNumber]);
block.innerHTML += `<p class='word-ids' id='word-id${i}'>${keywords[randomNumber]}</p>`;
}
wordIds = document.querySelectorAll('.word-ids');
currentWord = 0;
wordIds[currentWord].classList.toggle('highlight');
};
generateOutput();
// ######################################################################
// Reset
const reset = (type) => {
if (type === 'complete') {
wpm = 1;
accuracy = 1;
secondsLeft = 59;
inputBox.disabled = false;
clearInterval(timer);
results.classList.add('hidden');
}
block.textContent = '';
wordsBlock = [];
inputBox.value = '';
generateOutput();
};
// ######################################################################
// Game
inputBox.addEventListener('keyup', (event) => {
if (event.code === 'Space') {
if (secondsLeft === 59) setInterval(timer, 1000);
if (currentWord === wordsInBlock - 1) {
reset();
} else {
if (inputBox.value.trim() === wordsBlock[currentWord]) {
wordIds[currentWord].classList.toggle('mark-green');
accuracy++;
} else wordIds[currentWord].classList.toggle('mark-red');
wordIds[currentWord].classList.toggle('highlight');
currentWord++;
wordIds[currentWord].classList.toggle('highlight');
inputBox.value = '';
wpm++;
}
}
});
// ######################################################################
// Restart
const restartBtn = document.querySelector('.restart');
restartBtn.addEventListener('click', () => {
reset('complete');
});
// ######################################################################
// Timer
const timerBox = document.querySelector('.timer');
const results = document.querySelector('.results');
const wpmBox = document.querySelector('.wpm');
const accuracyBox = document.querySelector('.accuracy');
let interval;
let secondsLeft = 59;
const timer = () => {
if (secondsLeft > 0) {
if (secondsLeft >= 10) timerBox.textContent = `0:${secondsLeft}`;
else timerBox.textContent = `0:0${secondsLeft}`;
secondsLeft--;
} else {
clearInterval((secondsLeft = 0));
wpmBox.textContent = wpm;
accuracyBox.textContent = `${parseInt((accuracy / wpm) * 100)}%`;
inputBox.disabled = true;
results.classList.remove('hidden');
}
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;600&display=swap");
*,
*::after,
*::before {
padding: 0;
margin: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body {
background-color: #f2bac9;
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.main {
background-color: #e887a1;
border-radius: 10px;
padding: 5rem 10rem;
text-align: center;
}
.main h2 {
font-weight: 600;
font-size: 2rem;
color: white;
}
.main .words {
border-radius: 3px;
padding: 1rem 2rem;
margin-top: 3rem;
margin-bottom: 3.5rem;
width: 50rem;
overflow: hidden;
background-color: white;
color: black;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.main .words p:not(:first-child) {
margin-left: 0.2rem;
}
.main .menu {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.main .input {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
padding: 1rem 1.5rem;
border-radius: 3px;
border: none;
outline: none;
}
.main .timer,
.main .restart {
padding: 1rem 1.5rem;
border-radius: 3px;
margin-left: 0.5rem;
}
.main .timer {
background-color: #d90368;
color: white;
}
.main .restart {
background-color: #4ecdc4;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
cursor: pointer;
}
.main .restart img {
width: 1.5rem;
}
.results {
background-color: white;
border-radius: 10px;
padding: 3rem 10rem;
text-align: center;
font-size: 1.6rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
font-weight: 300;
-webkit-transition: all 0.5s;
transition: all 0.5s;
}
.results span {
font-weight: bold;
}
.highlight {
background-color: #4ecdc4;
padding: 0.1rem 0.2rem;
}
.mark-green {
color: #02cc02;
}
.mark-red {
color: red;
}
.hidden {
visibility: hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typing test</title>
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<main>
<div class="main">
<h2>Typing test</h2>
<div class="words"></div>
<div class="menu">
<input type="text" class="input">
<div class="timer">1:00</div>
<div class="restart">
<img src="refresh.svg" alt="refresh">
</div>
</div>
</div>
<div class="results hidden">
<p>wpm: <span class="wpm">88</span></p>
<p>accuracy: <span class="accuracy">75%</span></p>
</div>
</main>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Here's a few thoughts</p>\n<ul>\n<li>Put your list of words in its own file - a large chunk of data doesn't belong intermixed in the code, it gets in the way.</li>\n<li>Avoid innerHTML whenever possible - it opens your app up for a lot of potential security exploits (e.g. XXS attacks). Just use the DOM manipulation functions like document.createElement(). If you find them hard to work with, consider making helper functions (<a href=\"https://codereview.stackexchange.com/questions/253287/task-list-app-which-allows-to-add-and-remove-tasks-from-list/253317#253317\">this</a> code-review answer has some nice suggestions)</li>\n<li>I like extracting out little utility functions, like <code>chooseRandomEntry(someList) -> randomElementFromList</code>. This can help improve the readability of functions. i.e. if you used this helper in generateOutput(), then generateOutput can focus more on saying what needs to be done to actually generate the output (the purpose of the function), and doesn't have to spell the step by step mundane details of finding a random element in an array. It makes it much easier to understand what the function does at a glance.</li>\n<li>Be very careful with your variable naming. Make sure the names accurately describe their purpose. Good naming really helps make a program readable. Bad naming causes readers to have to look at how a variable is being used before they know what it really means, which takes a lot more time. For example, in your code, wpm doesn't really mean words-per-minute, it actually means "how many words the user has typed in thus far" which you eventually use to calculate the wpm. Maybe a better name would be wordCount. Same goes for accuracy - it does not hold an accuracy ratio, rather, it holds the number of correct words the user has typed in. So maybe numberOfCorrectWords or correctWordCount (don't be afraid of longer names if it helps make the intent more clear).</li>\n<li>This is more UX than code-review, but I noticed in the live preview, there's a lot of content shifting around. Give the timer box a fixed-width so it doesn't keep changing size as it counts down. Give each word enough padding so that when you put the highlighted box on one of them, you don't have to add more padding and shift the words around.</li>\n</ul>\n<p>A bigger change that would really help improve this code would be to separate your "view" logic from your "model", or state. What this would look like is your user does some action, triggering an event that update the model (state), then informs the view of this update.</p>\n<p>A rough example of one possible implementation of this:</p>\n<pre><code>// model (or application state)\nconst createInitialState = () => ({\n wpm: 1,\n accuracy: 1,\n secondsLeft: 59,\n timerRunning: false,\n wordsBlock: generateRandomWordList({size: wordsInBlock})\n});\n\nlet state = createInitialState();\n\n// Your event listener\nconst completeReset = () => {\n state = createInitialState();\n updateView();\n};\n\n// view\nconst updateView = () => {\n inputBox.disabled = !state.timerRunning;\n if (!state.timerRunning && currentInterval == null) {\n clearInterval(currentInterval);\n currentInterval = null;\n } else if (state.timerRunning && currentInterval != null) {\n currentInterval = setInterval(countDown, 1000);\n }\n // etc\n}\n</code></pre>\n<p>That's just a quick and dirty example, don't take that specific example too seriously, you can figure out how to best make the general idea work in your program as you go along. But it should show how you might be able to segregate the view from the model. And notice how updateView() is able to figure itself out based on the model alone - this isn't always possible, but its good to do when it makes sense as it often simplifies logic. i.e. if everything is coded right, as soon as your timer reaches zero, just set timerRunning to false in the state and notify the view, and the view will update itself to render stats to the user.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T23:59:13.587",
"Id": "500252",
"Score": "0",
"body": "thanks for the feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T08:24:02.997",
"Id": "253651",
"ParentId": "253191",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253651",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T18:30:25.907",
"Id": "253191",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Typing Test in JS"
}
|
253191
|
<p>Is there a better way of creating a nested dictionary than what I'm doing below? The result for the <code>setdefault</code> is because I don't know whether that particular key exists yet or not.</p>
<pre><code>def record_execution_log_action(
execution_log, region, service, resource, resource_id, resource_action
):
execution_log["AWS"].setdefault(region, {}).setdefault(service, {}).setdefault(
resource, []
).append(
{
"id": resource_id,
"action": resource_action,
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:25:50.393",
"Id": "499242",
"Score": "0",
"body": "You can used a `defaultdict` from `collections` module instead, it automatically creates the default( this can be a `list`) if the `key` is not found."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:45:19.873",
"Id": "499245",
"Score": "1",
"body": "I've created about `defaultdict` but I don't get how to use it for my nested use case properly. Could you give an example?"
}
] |
[
{
"body": "<p>Use a <code>defaultdict</code> like so:</p>\n<pre><code>from collections import defaultdict\n\nresource_dict = lambda: defaultdict(list)\nservice_dict = lambda: defaultdict(resource_dict)\nregion_dict = lambda: defaultdict(service_dict)\nexecution_log = defaultdict(region_dict)\n\nexecution_log['AWS']['region']['service']['resource'].append({\n "id": 'resource_id',\n "action": 'resource_action',\n "timestamp": "%Y-%m-%d %H:%M:%S",\n })\n\nexecution_log\n</code></pre>\n<p>output:</p>\n<pre><code>defaultdict(<function __main__.<lambda>()>,\n {'AWS': defaultdict(<function __main__.<lambda>()>,\n {'region': defaultdict(<function __main__.<lambda>()>,\n {'service': defaultdict(list,\n {'resource': [{'id': 'resource_id',\n 'action': 'resource_action',\n 'timestamp': '%Y-%m-%d %H:%M:%S'}]})})})})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T04:06:41.477",
"Id": "253205",
"ParentId": "253195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253205",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T23:51:25.490",
"Id": "253195",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Nested dictionary creation with setdefault"
}
|
253195
|
<p>I've written some code which features Eric Elliot's javascript factory function mixin composition (<a href="https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1" rel="nofollow noreferrer">https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1</a>), but since there's no object field name associated with the class it doesn't seem like most other forms of composition I see. What would the draw backs be compared the style of composition where each class you compose with is given a field name (I'm calling this named composition)?</p>
<pre><code>let pipe = (...fns) =>x => fns.reduce((acc,fn)=> {
return fn(acc)
},x)
let createCanvas= ()=>o=> ({
...o,
makeCanvas(width,height) {
this.can = document.createElement("canvas")
this.can.width = width
this.can.height = height
this.ctx = this.can.getContext("2d")
},
clearCanvas() {
this.ctx.clearRect(0,0,this.can.width,this.can.height)
},
returnCanvas() {
return this.can
}
})
let drawingLines = () => o => ({
...o,
line(x, y, xx, yy) {
this.ctx.beginPath();
this.ctx.moveTo(x, y);
this.ctx.lineTo(xx, yy);
this.ctx.stroke();
}
});
let mouseTracker = () => o => ({
...o,
trackCanvas() {
this.track(this.can);
},
track(ele) {
ele.addEventListener("mousemove", e => {
this.bb = ele.getBoundingClientRect();
this.mx = e.clientX - this.bb.left;
this.my = e.clientY - this.bb.top;
});
}
});
let rectMethods = () => ({
makeRect(x, y, w, h) {
this.ctx.strokeRect(x, y, w, h);
},
});
let rectMixin = () => o => ({
...o,
...rectMethods()
});
// apparently width gets set automatically, which is pretty nice
let height = 150;
let width= 150;
let firstCanvas = pipe(
createCanvas(),
drawingLines(),
mouseTracker(),
rectMixin()
)({});
firstCanvas.makeCanvas(width, height);
firstCanvas.trackCanvas();
</code></pre>
<p>I'm very interested in avoiding the verbosity of named composition, especially in cases where an existing class has many methods that I would have to rewrite the methods for.</p>
<pre><code>let usefulEventFunctions=()=>({
//...imagine functions named one-five for countings sake...
evOne() {
},
evTwo() {
},
})
let usefulMathFunctions =()=>({
//...imagine another set of named functions one-five also...
mthOne(){
},
mthTwo(){
}
})
// here's the class composed of the others
let myObject = ()=>({
math:usefulMathFunctions(),
events:usefulEventFunctions(),
// below would be the 10 signatures
evOne() {
this.events.evOne()
},...
mthTen() {
this.math.mthTen()
}
})
</code></pre>
<p>Using the mixin composition I can see how we would avoid this in a language like javascript, but looking over <a href="https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance">https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance</a>, and <a href="https://codereview.stackexchange.com/questions/32213/object-composition">Object Composition</a>, it appears other languages only feature named composition, so how is one supposed to avoid all the duplicated methods in choosing composition over inheritance?</p>
|
[] |
[
{
"body": "<h2>Question</h2>\n<blockquote>\n<p>*"...so how is one supposed to avoid all the duplicated methods in choosing composition over inheritance?"</p>\n</blockquote>\n<p>I assume you are talking about JavaScript.</p>\n<p>It might be a minor point but In JS we use functions, methods are reserved for the engine where the name comes from the language it is written in V8 for example is written in C++</p>\n<h2>Duplicating functions</h2>\n<p>There is no need to duplicate functions no matter how you create your object in JavaScript.</p>\n<p>I just can not workout why you would want to do</p>\n<p>From your bottom snippet</p>\n<blockquote>\n<pre><code>mthTen() { // WHY??????\n this.math.mthTen()\n}\n</code></pre>\n</blockquote>\n<h2>Examining your example via rewrites</h2>\n<p>Defining the objects</p>\n<pre><code>const Events = () => ({evOne() {}, evTwo() {}});\nconst Maths = () => ({mthOne() {}, mthTwo() {}});\n</code></pre>\n<h3>BTW Use literal if you don't need closure</h3>\n<p>BTW you would only define objects (using this pattern) via functions if you were closing over some encapsulated data. They are better defined as literals in this case, avoiding the creation of unused closure for each object</p>\n<pre><code>const events = {evOne() {}, evTwo() {}};\nconst maths = {mthOne() {}, mthTwo() {}};\n</code></pre>\n<h3>At the object level</h3>\n<p>If you want the functions to be accessible at the object level you may build it as follow</p>\n<pre><code>const createFoo = (math, events) => ({...math, ...events});\nconst obj = createFoo(math, events);\n\n// Calling\nobj.evOne();\nobj.mthOne();\n</code></pre>\n<h3>At the object property level</h3>\n<p>To create them as named properties</p>\n<pre><code>const createFoo = (math, events) => ({math:{...math}, events:{...events}});\nconst obj = createFoo(math, events);\n\n// Calling\nobj.events.evOne();\nobj.math.mthOne();\n</code></pre>\n<h3>As static functions</h3>\n<p>In many cases you would use them as static functions.</p>\n<pre><code>// static instance reference. There is only one math and events for many Foos\nconst Foo = (math, events) => ({math, events});\nconst obj = Foo(math, events);\n\n// Calling\nobj.events.evOne();\nobj.math.mthOne();\n</code></pre>\n<p>Or\n// Static instance. There is only one instance of math and events referenced by the constructor Foo\nconst Foo = Object.assign(() => ({}), {math, events});\nconst obj = Foo();</p>\n<pre><code>// Note access via the instantiation function Foo\nFoo.events.evOne();\nFoo.math.mthOne();\nobj.event.evOne(); // will throw as it does not exist.\n</code></pre>\n<p>Or</p>\n<pre><code>// Static instance functions. There is only one instance of math and events \n// referenced via functions of the constructor Foo\nconst Foo = Object.assign(() => ({}), {...math, ...events});\nconst obj = Foo();\n\n// Note access via the instantiation function Foo\nFoo.evOne();\nFoo.mthOne();\nobj.evOne(); // will throw as it does not exist.\n</code></pre>\n<p><strong>Note</strong> there is no formal way to define static functions its only static by how it is used and instanced (Via the <code>class</code> syntax <code>static</code> is just syntactical sugar for (assign to <code>constructor</code>, rather than <code>prototype</code>))</p>\n<h2>If you must duplicate</h2>\n<p><strong>Warning</strong> Don't do this at home, it is only as an example. Doing this in any code can result in severe confusion and eventual application death.</p>\n<p>If you really wanted to have a second copy of each function. <code>eg obj.evOne</code> and <code>obj.event.evOne</code> You can automate the function creation, binding the copied function references to the object you want as <code>this</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const events = {evOne() {}, evTwo() {}};\nconst logger = {\n logA() { console.log(\"A\" + this.count++)},\n logB() { console.log(\"B\" + this.count++)}, \n count: 0\n};\n\nconst addFunctions = (obj, ...instances) => {\n for (const instance of instances) {\n for (const [name, func] of Object.entries(instance)) {\n func instanceof Function && (obj[name] = func.bind(instance));\n }\n }\n return obj;\n}\n\nconst createFoo = (a, b) => addFunctions({logger: a, events: b}, a, b);\nconst foo = createFoo({...logger}, {...events});\n\nfoo.logger.logA(); // should be A0\nfoo.logA(); // should be A1\nfoo.logger.logB(); // should be B2\nfoo.logB(); // should be B3</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Question</h2>\n<blockquote>\n<p><em>"What would the draw backs be compared the style of composition where each class you compose with is given a field name (I'm calling this named composition)?"</em></p>\n</blockquote>\n<p>This question is way too subjective to answer in any death.</p>\n<p>There are drawbacks to every pattern, how the drawbacks effect the code quality is very dependent on the coders skill and level of experience.</p>\n<p>If you are comfortable with a pattern and have the experience your proficiency outweighs any pattern's drawbacks.</p>\n<p>The biggest drawback to any pattern is how experience a coder is in using it.</p>\n<p>To be a well rounded coder you must gain proficiency in all the patterns.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:56:18.017",
"Id": "253229",
"ParentId": "253196",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T23:59:39.880",
"Id": "253196",
"Score": "0",
"Tags": [
"javascript",
"object-oriented",
"design-patterns"
],
"Title": "Avoiding verbose compositional class design"
}
|
253196
|
<p><strong>Problem</strong>: IPython's <code>autoreload</code> and <code>superreload</code> may reload modules such that <code>obj=Obj()</code> -> edit file & save -> <code>isinstance(obj, Obj) == False</code>. Sometimes even <code>imp.reload</code> of all involved modules doesn't absolve it.</p>
<p><strong>Goal</strong>: a method with a 'fallback' on looser criterion that are as close to <code>isinstance</code> as possible.</p>
<p><strong>Attempt</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def isinstance_ipython(obj, ref_class):
def _class_name(obj):
name = getattr(obj, '__qualname__', getattr(obj, '__name__', ''))
return (getattr(obj, '__module__', '') + '.' + name).lstrip('.')
return (isinstance(obj, ref_class) or
_class_name(type(obj)) == _class_name(ref_class))
</code></pre>
<p><code>obj</code> is always instance of a class, and <code>ref_class</code> is always a Python 3.x, non-builtin class. <code>__qualname__</code> and <code>__module__</code> are included to prefer longest possible name, but fallback upon shorter names via empty strings.</p>
<hr>
<p>Any improvements to reliability of this method (i.e. reduced false positives/negatives)? Not interested in speed or readability, but they're welcome as bonus.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T00:06:04.217",
"Id": "253198",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Improved isinstance for IPython"
}
|
253198
|
<p>I wrote this code for a home task, and received some negative feedback. Though I really appreciated the reviewer, but I disagree when he said I use <code>auto</code> disorderly, and the algorithm is not optimal (I know it's not optimal, but comparing to the code that they expected which runs about 5 times slower than mine, it's really hard to accept).</p>
<p>There are two big problems I see (when reviewing again my code):</p>
<ul>
<li>I did not handle the case when there are more than 1024 chunks, which usually is the number of max open files in Linux. I'm aware of that and I mentioned it when I sent the code instead of handling it in my code, as we can increase the limit of the system.</li>
<li>There is a bug when storing strings with vectors. When we use GCC, the vector will resize by allocating new <code>2x current memory</code> and copy new elements to the new location, so we can use more memory than we expected. Interestingly, no one points out this.</li>
</ul>
<p>I would appreciate any comments to know where should I improve and get better next time. Below is from the reviewer:</p>
<blockquote>
<ul>
<li>His application could not run with 1.6GB, this error might come from the limitation for reading file simultaneously. I think he did
not check with huge file and he could not avoid the I/O problem. {{{
./main
~/PycharmProjects/serp_improvement/data_restore/ch_result_20.csv
out_ch_result_20.csv 100000 Sort chunks in async mode Intermediate
files 1021 are missing! Considering remove all temp files with "rm -r
*.tmp" }}}</li>
<li>His algorithm is not good enough:</li>
<li>To get the data by line, he used the seek function to back the latest line for avoiding limitation exceeding. This method is quite
complex.</li>
<li>He merges all chunks files to the output file at the same time. This method faces I/O blocking, on my machine, OS allows reading 1024
files simultaneously.</li>
<li>His coding is quite complex, hard to read: for example, sometimes, he used auto, sometimes no.</li>
</ul>
</blockquote>
<p>My code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <future>
#include <memory>
#include <algorithm>
#include <locale>
#include <codecvt>
#include <deque>
#include <cstdio>
#include <queue>
// we will use async read & write, so make the stream shareable
typedef std::shared_ptr<std::ifstream> istream_pointer;
typedef std::shared_ptr<std::ofstream> ostream_pointer;
// string comparison, sort by < by default
// uncomment bellow line to sort with std::locale
// #define ENABLE_LOCALE
#ifdef ENABLE_LOCALE
bool strComp(const std::string& a, const std::string& b) {
// en rules works quite well for latin characters
static std::locale comp("en_US.UTF-8");
return comp(a, b);
}
#else
bool strComp(const std::string& a, const std::string& b) { return a < b; }
#endif
// read from a stream no more than `limit` bytes
std::vector<std::string> readFromStream(const istream_pointer& fin,
size_t limit) {
std::vector<std::string> ret;
std::string line;
size_t sz = 0; // total bytes of contents
size_t len = fin->tellg(); // for back track
while (std::getline(*fin, line)) {
if (sz + line.size() > limit) {
// put line back to stream
fin->seekg(len, std::ios_base::beg);
break;
}
sz += line.size();
len += line.size() + 1; // +1 for newline
ret.push_back(std::move(line));
}
// assume copy elision
return ret;
}
// write a vector of string to a stream line by line
int writeToStream(const ostream_pointer& fout,
const std::vector<std::string>& chunks) {
for (auto& v : chunks) {
*fout << v << '\n';
}
return 1;
}
// split file to chunks and sort each chunks
size_t sortChunks(const istream_pointer& fin, size_t nbytes) {
// pre-read some lines
std::vector<std::string> cur;
const size_t sz = nbytes;
readFromStream(fin, sz).swap(cur);
size_t n_chunks = 0;
while (cur.size() > 0) {
// sort current chunk
std::sort(cur.begin(), cur.end(), strComp);
// write the chunk to fout
ostream_pointer fout =
std::make_shared<std::ofstream>(std::to_string(n_chunks++) + ".tmp");
writeToStream(fout, cur);
// read new chunks
cur.clear();
readFromStream(fin, sz).swap(cur);
}
return n_chunks;
}
// split file to chunks and sort each chunks - async read
size_t sortChunksAsync(const istream_pointer& fin, size_t nbytes) {
// pre-read some lines
std::vector<std::string> cur;
const size_t sz = nbytes / 2;
readFromStream(fin, sz).swap(cur);
int n_chunks = 0;
while (cur.size() > 0) {
// async point: read next chunk from stream async while process current
// chunk
std::future<std::vector<std::string>> nxt = std::async(
std::launch::async, readFromStream, fin, sz); // non-blocking
// sort current chunk
std::sort(cur.begin(), cur.end(), strComp);
// write the chunk to fout
ostream_pointer fout =
std::make_shared<std::ofstream>(std::to_string(n_chunks++) + ".tmp");
writeToStream(fout, cur);
// wait for reading nxt done
nxt.wait();
// async point: swap cur with next
nxt.get().swap(cur);
}
return n_chunks;
}
// we will use priority queue to merge k buffers, but the actual strings should
// not be pushed to the queue. In stead, we use vector iterator (which is just
// pointer). We also need the identity of the buffer to handle when we reach
// end()
typedef std::pair<std::vector<std::string>::iterator, size_t> vstring_iterator;
// Merge K streams and write to fout
void kWayMerge(const std::vector<istream_pointer>& streams,
const ostream_pointer& fout, size_t nbytes) {
const size_t n_chunks = streams.size();
std::cout << "Merging " << n_chunks << " streams\n";
// max size of chunks
const size_t sz = nbytes / (n_chunks + 1);
// buffer to store sorted chunks
std::vector<std::vector<std::string>> bufs(n_chunks);
// fill the buffer some lines
for (size_t i = 0; i < n_chunks; ++i) {
readFromStream(streams[i], sz).swap(bufs[i]);
}
// output buffers
std::vector<std::string> ret;
// comparator for priority queue
auto comp = [](const vstring_iterator& it0, const vstring_iterator& it1) {
return strComp(*it1.first, *it0.first); // min heap
};
std::priority_queue<vstring_iterator, std::vector<vstring_iterator>,
decltype(comp)> pq(comp);
// push the begining of each buffer to pq
for (size_t i = 0; i < n_chunks; ++i) {
if (bufs[i].size() > 0) {
pq.push({bufs[i].begin(), i});
}
else {
streams[i]->close(); // empty stream
}
}
size_t sz2 = 0; // keep track the size of output buffer
// now run untill we have nothing to push to pq
while (!pq.empty()) {
auto vit = pq.top();
auto it = vit.first; //current iterator
auto id = vit.second; // id of the buffer
pq.pop();
// std::cout << *it << std::endl;
if (sz2 + it->size() > sz) {
writeToStream(fout, ret);
sz2 = 0;
ret.clear();
}
sz2 += it->size();
auto nxt = it + 1; // next string in bufs[id]
ret.push_back(move(*it));
if (nxt == bufs[id].end()) { // reach end of buffer id
bufs[id].clear();
readFromStream(streams[id], sz).swap(bufs[id]);
if (bufs[id].size() > 0) {
nxt = bufs[id].begin();
pq.push({nxt, id});
} else {
// if buf is empty, streams is ended
streams[id]->close();
}
} else { // if not, just push to queue
pq.push({nxt, id});
}
}
// last write
writeToStream(fout, ret);
return;
}
// Merge K streams and write to fout - async read
void kWayMergeAsync(const std::vector<istream_pointer>& streams,
const ostream_pointer& fout, size_t nbytes) {
const size_t n_chunks = streams.size();
std::cout << "Merging " << n_chunks << " streams\n";
// max size of chunks
const size_t sz = nbytes / n_chunks;
// we only use half limit size of buffer for async read
const size_t bz = sz / 2;
// buffer to store strings in sorted chunks
std::vector<std::vector<std::string>> bufs(n_chunks);
// next buffers
std::vector<std::future<std::vector<std::string>>> nxt_bufs(n_chunks);
// fill the buffer some line
for (size_t i = 0; i < n_chunks; ++i) {
readFromStream(streams[i], bz).swap(bufs[i]);
}
// prefetch some next buffer
for (size_t i = 0; i < n_chunks; ++i) {
nxt_bufs[i] = std::async(readFromStream, streams[i], bz);
}
// mereged buffers
std::vector<std::string> ret;
std::future<int> pret = std::async(std::launch::async,writeToStream,fout,std::move(ret));
// comparator for priority queue
auto comp = [](vstring_iterator& it0, vstring_iterator& it1) {
return strComp(*it1.first, *it0.first); // min heap
};
std::priority_queue<vstring_iterator, std::vector<vstring_iterator>,
decltype(comp)> pq(comp);
// push the begining of each buffer to pq
for (size_t i = 0; i < n_chunks; ++i) {
if (bufs[i].size() > 0) {
pq.push({bufs[i].begin(), i});
}
else {
streams[i]->close(); // empty stream
}
}
size_t sz2 = 0; // keep track the size of merged buffer
// now run until we have nothing to push to pq
while (!pq.empty()) {
auto vit = pq.top();
auto it = vit.first; //current iterator
auto id = vit.second; // id of the buffer
pq.pop();
// std::cout << *it << std::endl;
if (sz2 + it->size() > bz) {
pret.wait();
pret = std::async(std::launch::async,writeToStream,fout,std::move(ret));
sz2 = 0;
}
sz2 += it->size();
auto nxt = it + 1; // next string in bufs[id]
ret.push_back(move(*it));
if (nxt == bufs[id].end()) { // reach end of buffer id
// wait for next buffer - expected no wait
nxt_bufs[id].wait();
// swap contents of current buffer with next buffer
nxt_bufs[id].get().swap(bufs[id]);
if (bufs[id].size() > 0) {
nxt = bufs[id].begin();
pq.push({nxt, id});
// prefetch next bufs[id]
nxt_bufs[id] = std::async(std::launch::async, readFromStream, streams[id], bz);
} else {
// if buf is empty, streams is ended
streams[id]->close();
}
} else { // if not, just push to queue
pq.push({nxt, id});
}
}
// last write
pret.wait();
writeToStream(fout, ret);
return;
// what if using k thread to push to a priority queue and one thread to from
// the queue?
}
void cleanTmpFiles(size_t chunks) {
for (size_t i = 0; i < chunks; ++i) {
std::remove((std::to_string(i) + ".tmp").c_str());
}
}
// Our extenal sort funtion
void externalSort(const char* input_file, const char* output_file,
size_t limits, int async) {
// read input file
istream_pointer fin = std::make_shared<std::ifstream>(input_file);
if (!fin->is_open()) {
throw std::logic_error("Input file is missing");
}
// sort the stream
size_t n_chunks = 0;
if (async & 1) {
std::cout << "Sort chunks in async mode\n";
n_chunks = sortChunksAsync(fin, limits);
} else {
n_chunks = sortChunks(fin, limits);
}
fin->close();
// read temporary file
std::vector<istream_pointer> streams(n_chunks);
for (size_t i = 0; i < n_chunks; ++i) {
istream_pointer isptr =
std::make_shared<std::ifstream>(std::to_string(i) + ".tmp");
if (!isptr->is_open()) {
cleanTmpFiles(n_chunks);
throw std::logic_error("Itermediate files " + std::to_string(i) +
" are missing!");
}
streams[i] = std::move(isptr);
}
// stream to output file
ostream_pointer fout = std::make_shared<std::ofstream>(output_file);
// merge the streams
if (async & 2) {
std::cout << "Merge chunks in async mode\n";
kWayMergeAsync(streams, fout, limits);
} else {
kWayMerge(streams, fout, limits);
}
fout->close();
// clean tmp file
cleanTmpFiles(n_chunks);
std::cout << "Done!\n";
}
// out main application
int main(int argc, char* argv[]) {
const char* input_file = (argc > 1) ? argv[1] : "input.txt";
const char* output_file = (argc > 2) ? argv[2] : "output.txt";
size_t limits = (argc > 3) ? std::stoull(argv[3]) : 6000;
int async = (argc > 4) ? std::stoi(argv[4]) : 3;
try {
externalSort(input_file, output_file, limits, async);
}
// should clean tmp files, but don't know how many files, so let remind users
// doing it
catch (const std::exception& e) {
std::cerr << e.what() << "\n";
std::cerr << "Considering remove all temp files with \"rm -r *.tmp\"\n";
return -1;
} catch (...) {
std::cerr << "Exception caught during sorting!\nConsidering remove all temp "
"files with \"rm -r *.tmp\"";
return -1;
}
return 0;
}
</code></pre>
<p><strong>UPDATE</strong> I will summarise the bugs here, and make the better version in my spare time.</p>
<p>Bugs found from <code>user673679</code>:</p>
<ul>
<li>Formatting is hard to read. <code>2 spaces</code> indent is good for me, but I think it may be hard for others to read. I used <code>clang-format</code>, so it may make thing worst.</li>
<li>Bugs related to the minimum size of memory; we should handle the case when we have more than allowed opened files. I think it can be done with incremental merging (merge 512 files at a time for example).</li>
<li>The code is over-complicated, especially when handling async IO. He suggests an <code>async_read</code> and <code>async_write</code> class that hold both <code>current</code> and <code>next</code> buffer and hide all internal async detail. I think this is a very nice idea.</li>
<li>I should use <code>runtime_error</code> instead of <code>logic_error</code>.</li>
</ul>
|
[] |
[
{
"body": "<p><strong>Formatting:</strong></p>\n<ul>\n<li><p>Please don't use two spaces for indent - it's really hard to visually match indentation levels. Either use 4 spaces, or an actual tab character (so that someone with bad eyes like me can set the spacing to whatever they need without having to reformat the code).</p>\n</li>\n<li><p>Some vertical spacing would also help readability.</p>\n</li>\n</ul>\n<hr />\n<p><strong>Bugs:</strong></p>\n<p>I used a ~4MB random word list for input, and rapidly found the following:</p>\n<ul>\n<li><p>Windows (or more specifically the C runtime library on Windows) <a href=\"https://stackoverflow.com/questions/870173/is-there-a-limit-on-number-of-open-files-in-windows\">limits the number of open files to 512</a> by default. We can increase this to 8192 with <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-160\" rel=\"nofollow noreferrer\">_setmaxstdio</a>, but this may not be sufficient either. We probably need an algorithm that explicitly works with a specified file limit.</p>\n</li>\n<li><p>If we fail to open a temporary file (e.g. because we hit the file limit), <code>cleanTmpFiles</code> is called. However, this will not clean up any temporary files that we already have open (i.e. all the files up to the file limit).</p>\n</li>\n<li><p>If the line length is greater than the byte limit, we silently produce nonsense output. With the random word list and the default 6000 byte limit, we get limits that are too small to be practically used (<code>sz = 3</code>, <code>bz = 1</code> in <code>kWayMergeAsync</code>). We should either emit an error if this happens, or accept lines longer than the limit when necessary.</p>\n</li>\n<li><p><code>writeToStream</code> writes an empty line at the end of each temporary file. We should either avoid this, or change <code>readFromStream</code> to ignore empty lines.</p>\n</li>\n<li><p>The sorted output contains some duplicate words where the input has no duplicates (I think it's a problem with the read function backtracking, though I haven't tracked it down exactly).</p>\n</li>\n</ul>\n<hr />\n<p><strong>Buffering:</strong></p>\n<p>The OS does its own buffering for file I/O. I'm not convinced there's a benefit to doing manual buffering on top of that in the merge stage of the algorithm. (If we have strict memory limits, we can call <a href=\"https://en.cppreference.com/w/cpp/io/basic_filebuf/setbuf\" rel=\"nofollow noreferrer\">setbuf / pubsetbuf</a> to supply our own buffers).</p>\n<p>I'd suggest starting with an unbuffered version, and examining how that performs before adding any extra complexity.</p>\n<hr />\n<p><strong>Complexity:</strong></p>\n<p>I agree with the reviewers that the code is over-complicated. I think mostly this is due to logic and state that should be hidden (in another function or object) being "inlined" into the higher-level algorithm. e.g. <code>kWayMergeAsync</code> could look something like:</p>\n<pre><code>void kWayMergeAsync(const std::vector<istream_pointer> &streams,\n const ostream_pointer &fout, size_t nbytes)\n{\n // ... declare limits as before ...\n \n // class async_buffered_reader:\n // holds a pair of buffers (current and future)\n // hides the complexity of buffering and async reading\n std::vector<async_buffered_reader> bufs;\n for (size_t i = 0; i != n_chunks; ++i)\n bufs.emplace_back(streams[i], bz);\n\n // ... declare pq as before ...\n\n for (size_t i = 0; i != n_chunks; ++i)\n pq.push({ bufs.next(), i }); // next() does everything we need in terms of waiting, swapping buffers, launching async reads, etc.\n\n // class async_buffered_writer:\n // holds the output buffer\n // hides the complexity of buffering and async writing\n async_buffered_writer abw_out(fout, sz);\n\n while (!pq.empty())\n {\n auto [nxt, i] = pq.top();\n pq.pop();\n\n abw_out.push(std::move(nxt)); // push() does buffering / writing as necessary.\n\n if (!bufs[i].is_complete())\n pq.push({ bufs.next(), i }); // again, next() does everything we need :)\n }\n\n // abw_out destructor will ensure we finish writing... so we don't need to do anything here!\n}\n</code></pre>\n<p>Quite a rough sketch, but all the complexity that doesn't matter to the algorithm is hidden away in the <code>async_buffered_reader</code> and <code>async_buffered_writer</code> classes.</p>\n<p>We could even implement other <code>reader</code> and <code>writer</code> classes (e.g. without buffering or with different async implementations) with the same interface. And, if we make <code>kWayMerge</code> a template function, we could then switch to those types without changing the merge algorithm at all!</p>\n<hr />\n<p><strong>Algorithm</strong>:</p>\n<p>Beyond the bugs mentioned, I don't think there's too much wrong with the algorithm.</p>\n<p>I/O from disk is really slow compared to sorting, so minimizing the amount of reading and writing to disk (which your algorithm does) is a good thing.</p>\n<p>However, it also means that there's not much point in the async I/O (at least with the current implementation). With a fixed memory limit, we always have to wait for a chunk to be fully read or written. An HDD / SSD can only read or write one thing at a time (at least over SATA).</p>\n<p>So improvements we could make would probably focus on:</p>\n<ul>\n<li><p>Working with specific hardware (do we have an M.2 SSD allowing multiple operations at once? do we have 8 drives to work with, or just one?).</p>\n</li>\n<li><p>Allowing the user to specify multiple drives / locations for the temporary files.</p>\n</li>\n<li><p>Creating one thread per location for I/O, instead of using <code>std::async</code>.</p>\n</li>\n<li><p>Profiling the code (e.g. using <a href=\"https://github.com/hrydgard/minitrace\" rel=\"nofollow noreferrer\">minitrace</a> and chrome://tracing), to optimize it for a specific scenario.</p>\n</li>\n</ul>\n<hr />\n<p><strong>Misc.:</strong></p>\n<ul>\n<li><p><code>std::logic_error</code> is the wrong exception type to use here (<code>std::runtime_error</code> is probably what we want).</p>\n</li>\n<li><p>We don't need to wrap the file streams in <code>std::shared_ptr</code>.</p>\n</li>\n<li><p><code>writeToStream</code> returns <code>int</code> for some reason? It could also use a <code>const&</code> when iterating.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T13:18:10.583",
"Id": "253216",
"ParentId": "253206",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T06:19:37.397",
"Id": "253206",
"Score": "5",
"Tags": [
"c++",
"c++11",
"mergesort"
],
"Title": "External sorting with async read and write"
}
|
253206
|
<p>Solved one of the <a href="https://acm.timus.ru/problem.aspx?space=1&num=1001" rel="nofollow noreferrer">easiest problems</a> from acm.timus.ru.</p>
<blockquote>
<p><a href="https://acm.timus.ru/problem.aspx?space=1&num=1001" rel="nofollow noreferrer">1001. Reverse Root</a></p>
<p>The input stream contains a set of integer numbers Aᵢ (0 ≤ Aᵢ ≤ 10¹⁸).
The numbers are separated by any number of spaces and line breaks.
A size of the input stream does not exceed 256 KB.</p>
<p>For each number Aᵢ from the last one till the first one you should
output its square root. Each square root should be printed in a
separate line with at least four digits after decimal point.</p>
</blockquote>
<p>I would like to know why my solution is relatively slow (execution time is 1s) and uses so much memory (7 072 KB)? Compared to C++: 0.093s and 408 KB of memory.</p>
<pre class="lang-golang prettyprint-override"><code>
package main
import "fmt"
import "math"
var a []int64
func main() {
for {
var x int64
k, _ := fmt.Scan(&x)
if k != 1 {
break
}
a = append(a,x)
}
n := len(a)
for n > 0 {
n--
fmt.Printf("%.4f\n", math.Sqrt(float64(a[n])))
}
}
</code></pre>
<p>Is the significantly larger resource consumption due to garbage collection and imported libraries or just my code is inefficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T09:29:55.033",
"Id": "499273",
"Score": "3",
"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": "2020-12-08T09:30:34.510",
"Id": "499274",
"Score": "2",
"body": "Links can rot. Please include the necessary info in your question. 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>A benchmark is a scientific experiment.</p>\n<p>An essential feature of a scientific experiment is that it be reproducible.</p>\n<p>You do not provide any C++ code. You do provide some Go code. You do not define your methods for measuring CPU and memory. You provide some undefined CPU and memory measurements.</p>\n<p>Your Go code looks inefficient.</p>\n<hr />\n<blockquote>\n<p><a href=\"https://acm.timus.ru/problem.aspx?space=1&num=1001\" rel=\"nofollow noreferrer\">1001. Reverse\nRoot</a></p>\n<p>The input stream contains a set of integer numbers Aᵢ (0 ≤ Aᵢ ≤ 10¹⁸).\nThe numbers are separated by any number of spaces and line breaks. A\nsize of the input stream does not exceed 256 KB.</p>\n<p>For each number Aᵢ from the last one till the first one you should\noutput its square root. Each square root should be printed in a\nseparate line with at least four digits after decimal point.</p>\n</blockquote>\n<hr />\n<p>Compare my Go code (revroot.go) to your slower Go code (revroot.ivan.go):</p>\n<pre><code>$ ls -s -h revroot.in.data\n256K revroot.in.data\n$\n\n$ go build revroot.go && time ./revroot < revroot.in.data > revroot.out.data\nreal 0m0.007s\nuser 0m0.007s\nsys 0m0.000s\n$ go build revroot.go && time ./revroot < revroot.in.data > revroot.out.data\nreal 0m0.008s\nuser 0m0.008s\nsys 0m0.000s\n$ ls -s -h revroot.out.data\n208K revroot.out.data\n$\n\n$ go build revroot.ivan.go && time ./revroot.ivan < revroot.in.data > revroot.out.data\nreal 0m0.251s\nuser 0m0.141s\nsys 0m0.113s\n$ go build revroot.ivan.go && time ./revroot.ivan < revroot.in.data > revroot.out.data\nreal 0m0.245s\nuser 0m0.147s\nsys 0m0.100s\n$ ls -s -h revroot.out.data\n208K revroot.out.data\n$\n</code></pre>\n<hr />\n<p><code>revroot.go</code>:</p>\n<pre><code>package main\n\nimport (\n "bufio"\n "fmt"\n "io"\n "math"\n "os"\n "strconv"\n)\n\nfunc RevRoot(in io.Reader, out io.Writer) error {\n var a []float64\n\n s := bufio.NewScanner(in)\n s.Split(bufio.ScanWords)\n for s.Scan() {\n i, err := strconv.ParseUint(s.Text(), 10, 64)\n if err != nil {\n return err\n }\n a = append(a, math.Sqrt(float64(i)))\n }\n if err := s.Err(); err != nil {\n return err\n }\n\n w, ok := out.(*bufio.Writer)\n if !ok {\n w = bufio.NewWriter(out)\n }\n defer w.Flush()\n buf := make([]byte, 0, 32)\n for n := len(a) - 1; n >= 0; n-- {\n buf = strconv.AppendFloat(buf[:0], a[n], 'f', 4, 64)\n buf = append(buf, '\\n')\n _, err := w.Write(buf)\n if err != nil {\n return err\n }\n }\n err := w.Flush()\n if err != nil {\n return err\n }\n\n return nil\n}\n\nfunc main() {\n err := RevRoot(os.Stdin, os.Stdout)\n if err != nil {\n fmt.Fprintln(os.Stderr, err)\n }\n return\n}\n</code></pre>\n<p><code>revroot.ivan.go</code>:</p>\n<pre><code>package main\n\nimport "fmt"\nimport "math"\n\nvar a []int64\n\nfunc main() {\n for {\n var x int64\n k, _ := fmt.Scan(&x)\n if k != 1 {\n break\n }\n a = append(a, x)\n }\n n := len(a)\n\n for n > 0 {\n n--\n fmt.Printf("%.4f\\n", math.Sqrt(float64(a[n])))\n }\n}\n</code></pre>\n<hr />\n<p>In Go, to measure performance we run benchmarks. We exclude I/O and other OS functions.</p>\n<pre><code>$ go test revroot_test.go revroot.go -run=! -bench=. -benchmem\nBenchmarkRevRoot-4 249 4775861 ns/op 833577 B/op 13202 allocs/op\n$ \n</code></pre>\n<p>My <code>RevRoot</code> function takes 4,775,861 nanoseconds (0.004,775,861 seconds) for 13,177 square roots.</p>\n<p><code>revroot_test.go</code>:</p>\n<pre><code>package main\n\nimport (\n "bytes"\n "io/ioutil"\n "math/rand"\n "strconv"\n "strings"\n "testing"\n)\n\nfunc BenchmarkRevRoot(b *testing.B) {\n buf := bytes.NewBuffer(make([]byte, 0, 256*1024))\n r := rand.New(rand.NewSource(42))\n for {\n buf.WriteString(strconv.Itoa(r.Int()))\n buf.WriteString("\\n")\n if buf.Len() > 256*1024-256 {\n break\n }\n }\n data := buf.String()\n\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n err := RevRoot(strings.NewReader(data), ioutil.Discard)\n if err != nil {\n b.Fatal(err)\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T01:34:07.013",
"Id": "253240",
"ParentId": "253207",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T06:28:20.113",
"Id": "253207",
"Score": "1",
"Tags": [
"performance",
"memory-management",
"go"
],
"Title": "Reverse Root Solution"
}
|
253207
|
<p>I'm using a NodeJS script to do some geo calculations using the h3.js library by Uber. the concept of getting a nodejs script result back into php is new to me. I found the following example online, which I'm not following.</p>
<pre><code>$output = [];
$arg = escapeshellcmd('some variable to pass on');
$command = 'node /var/www/hex/src/h3.js ' . $arg;
exec($command, $output);
var_dump($output);
</code></pre>
<p>This is returning the correct result, which I'm using <code>console.log()</code> for on the NodeJS side.</p>
<ul>
<li>I'm wondering if my method has any implications I might not be aware of</li>
<li>Is this the way to go for a case like this?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T14:17:57.027",
"Id": "499295",
"Score": "0",
"body": "What other PHP code exists in this project? Is it just this, which gets passed onto the client, or is there other stuff as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T14:19:30.520",
"Id": "499296",
"Score": "0",
"body": "This would be the code of one method (h3Service.php for example) that gets the output and passes it on to my database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T05:41:25.527",
"Id": "499368",
"Score": "1",
"body": "They probably meant escapeshellarg, not escapeshellcmd... From manual: \"Warning\nescapeshellcmd() should be used on the whole command string, and it still allows the attacker to pass arbitrary number of arguments. For escaping a single argument escapeshellarg() should be used instead.\" https://www.php.net/manual/en/function.escapeshellcmd.php"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T05:47:06.813",
"Id": "499369",
"Score": "1",
"body": "BTW can you explain what you mean by \"the following example which I'm not following\". Either that's the code of the example and then it is off-topic because of authorship of the code. Or that's your code and than the reference to an example you found is completely irrelevant and in worse case, confusing... Or maybe the word \"not\" should not be there?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T06:38:50.683",
"Id": "253208",
"Score": "1",
"Tags": [
"php",
"node.js"
],
"Title": "Getting output of a NodeJS script in PHP"
}
|
253208
|
<p>I have a set of template functions that have itrator types as template parameters, so can be used with any kind of iterators. <code>std::find</code> can be a good example.
Also I have a class that uses this function in its implementation and I don't want to expose my algorithms' header. Regarding the template function, inside my class I expect the iterators to be of random access type. So I wrote a wrapper class which can be constructed from any iterator Type that has the same pointer type and <code>std::random_access_iterator_tag</code></p>
<pre><code>template <typename IterR, typename IterL>
using iter_same_value_type = std::is_same<
typename std::iterator_traits<IterR>::value_type,
typename std::iterator_traits<IterL>::value_type>;
template <typename IterR, typename IterL>
using iter_same_category = std::is_same<
typename std::iterator_traits<IterR>::iterator_category,
typename std::iterator_traits<IterL>::iterator_category>;
template <typename T>
class WrapperRandomAccessIterator
{
using this_type = WrapperRandomAccessIterator<T>;
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;
template <typename RandomAccessIter, typename = typename
std::enable_if<iter_same_category<this_type, RandomAccessIter>() &&
iter_same_value_type<this_type, RandomAccessIter>()>::type>
constexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)
: ptr_(&*iter)
{}
reference operator*()
{
return *ptr_;
}
// Warning says "const has no effect on type reference"
const T& /*reference*/ operator*() const
{
return *ptr_;
}
const this_type& operator++()
{
ptr_ = std::next(ptr_);
return *this;
}
this_type operator++(int)&
{
auto res = *this;
++(*this);
return res;
}
private:
T *ptr_;
};
</code></pre>
<p>Here I have clang-tidy complaining about <code>operator++(int)&</code> that it returns non-const object.
It also says that for <code>const reference operator*()</code> that `const qualifier have no effect.</p>
<ol>
<li>How can it be improved?</li>
<li>Do I have to use the rule of 3 or 5 in such case?</li>
<li>Does it make sense to create a generic iterator wrapper class and a specialization for each iterator type? (I know, this question probably belongs with engineering stack exchange).</li>
</ol>
|
[] |
[
{
"body": "<p>I’m going to answer your questions first, then get into the actual code review.</p>\n<h1>Questions</h1>\n<h2>How can “it” [the code/the design] be improved?</h2>\n<p>I’ll get into details in the review, but the broad answer to this question is: I don’t know.</p>\n<p>The reason I don’t know is two-fold:</p>\n<ol>\n<li>you don’t provide even a single comment to explain the logic of what this code is doing; and</li>\n<li>you don’t provide even a single example to show what the intended usage is.</li>\n</ol>\n<p>Without any clue about what the code is supposed to be doing or how it’s supposed to be used, how can anyone answer the question of whether it can be improved? Maybe it’s absolute perfection; maybe there is no possible way to make this code any better for what it was written for. Or maybe it’s the absolute worst possible solution for what it’s for. All that depends on what it’s for.</p>\n<p>Obviously I’m going to try to review the code anyway, but to do so I’ll have to make a lot of assumptions about what you mean in your very brief, wildly unclear description of what the purpose of this wrapper is. I may guess wrong—that’s very likely, in fact—which means a lot of what I say may be incorrect, or even gibberish. For that I apologize, but it can’t be helped; I have to work with what I have.</p>\n<p>So I guess one way to answer the question is: documentation… lots of documentation, and some example usage code. For something this small, there’s really no reason one couldn’t provide a complete, compile-able test program (even if you want to keep that algorithm secret; you could just include a stub or dummy implementation just for the purposes of illustration and testing).</p>\n<h2>Do I have to use the rule of 3 or 5 in such case?</h2>\n<p>Yes. You always✻ have to. That’s why they call it a “rule”.</p>\n<p>✻ (Okay, technically the rule says “<em>almost</em> always”. But that just means that unless you’re 100% sure you <em>don’t</em> need to follow the rule, then the answer is yes.)</p>\n<p>The only question is <em>which</em> rule: 3, 5, or 0?</p>\n<p>Unfortunately, I can’t really give a coherent answer to that without making some guesses. So… just looking at what you’ve got there, and going by your description, I don’t… <em>think</em>… you need the rule of 3 or 5 (that is, you can use the rule of 0).</p>\n<p><em>BUT…</em></p>\n<p>I <em>suspect</em> that if the intended usage is more than what you explicitly <em>say</em> it is—that is, if I have to guess at practical usage of this wrapper, at least in my imagination—then the answer is that you <em>do</em> need to use the rule of 3 or 5. In fact, I think this wrapper is dangerously broken, and I’ll explain why in the review.</p>\n<h2>Does it make sense to create a generic iterator wrapper class and a specialization for each iterator type?</h2>\n<p>Absolutely. It’s not a bad idea at all. In fact, I wouldn’t be surprised if there were already “type-erased iterator” types out there. You could even make an argument for including one in the standard library. It would be <em>hella</em> useful.</p>\n<p>Now, does it make sense to do it <em>this</em> way? Mm, maybe? Impossible to say for sure. For the <em>general</em> use case I’d say no, but for the specific use case of random-access iterators <em>only</em>—with some additional caveats on both the iterator and algorithm characteristics—then maybe.</p>\n<p>So, onto the code review.</p>\n<h1>Code review</h1>\n<p>I’m going to skip the type traits, because I’ll talk about them when we get to the constructor that uses them.</p>\n<pre><code>template <typename T>\nclass WrapperRandomAccessIterator\n</code></pre>\n<p>Okay, so, here’s the first point of confusion. The type is called <code>WrapperRandomAccessIterator</code>… but it doesn’t look like you’re actually wrapping a random-access iterator. It looks like you’re trying to <em>create</em> a random-access iterator (actually, technically a <em>contiguous</em> iterator, but if you’re still stuck with C++11, then you don’t have that concept yet—seriously, though, who’s still using C++11 in 2020… almost 2021!) to a value sequence, and you’re trying to do so by stealing the value out from under a random-access iterator, and creating a pointer directly to it.</p>\n<p>The point is… the name is misleading. This is not an iterator wrapper. It does not wrap an iterator. It just transforms an iterator to a pointer.</p>\n<pre><code>using this_type = WrapperRandomAccessIterator<T>;\n</code></pre>\n<p>As type aliases go, this is really… kinda useless. So long as you’re inside the class body, you can omit the template arguments. Sure <code>WrapperRandomAccessIterator</code> is a little longer than <code>this_type</code>… but you really shouldn’t need to repeat it so often that it becomes a problem.</p>\n<pre><code>using difference_type = std::ptrdiff_t;\nusing value_type = T;\nusing pointer = T*;\nusing reference = T&;\nusing iterator_category = std::random_access_iterator_tag;\n</code></pre>\n<p>These are all okay, but I would suggest defining <code>value_type</code> as:</p>\n<pre><code>using value_type = typename std::remove_cv<T>::type;\n</code></pre>\n<p>This is to bring it in line with the way people expect to use <code>value_type</code>. If you have a case like this…:</p>\n<pre><code>template <typename Iterator>\nvoid max_value(Iterator first, Iterator last)\n{\n using type = typename iterator_traits<Iterator>::value_type;\n\n type val = *first;\n\n while (++first != last)\n if (*first > val)\n val = *first;\n\n return val;\n}\n\n// used with:\nconst vector<string> vec{"string1", "string2", ... };\n\nstring v = max_value(vec.begin(), vec.end());\n</code></pre>\n<p>… you would normally expect this to work because <code>val</code> <em>should</em> be a copy of whatever <code>*first</code> references, and that copy is not <code>const</code>. (And that would be true if you’d just used <code>auto</code> instead of <code>type</code>.) But with your <code>WrapperRandomAccessIterator</code>, it won’t work, because <code>value_type</code> will be <code>const string</code>, not <code>string</code>.</p>\n<p>(It’s correct to use plain <code>T</code> for <code>pointer</code> and <code>reference</code>, because that makes them <code>const string*</code> and <code>const string&</code>… which is what you want.)</p>\n<pre><code>template <typename RandomAccessIter, typename = typename\n std::enable_if<iter_same_category<this_type, RandomAccessIter>() &&\n iter_same_value_type<this_type, RandomAccessIter>()>::type>\nconstexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)\n : ptr_(&*iter)\n{}\n</code></pre>\n<p>Now, here’s where the problems start. What exactly is the purpose of <code>iter_same_category</code> and <code>iter_same_value_type</code>? Let’s look at the first one to show you what I mean:</p>\n<pre><code>iter_same_category<this_type, RandomAccessIter>\n</code></pre>\n<p>Now, this expands to:</p>\n<pre><code>std::is_same<\n typename std::iterator_traits<this_type>::iterator_category,\n typename std::iterator_traits<RandomAccessIter>::iterator_category>\n</code></pre>\n<p>And <code>this_type</code> is just <code>WrapperRandomAcessIterator<T></code>. But why all the shenanigans going through <code>iterator_traits</code> to get the <code>iterator_category</code> of <code>this_type</code>? There’s no mystery; it’s <code>iterator_category</code>. <code>typename std::iterator_traits<this_type>::iterator_category</code> is <em>always</em> <code>iterator_category</code>.</p>\n<p>So you could just do:</p>\n<pre><code>std::is_same<\n iterator_category,\n typename std::iterator_traits<RandomAccessIter>::iterator_category>\n</code></pre>\n<p>… and there’s no need for <code>iter_same_category</code> at all.</p>\n<p>Same goes for <code>iter_same_value_type</code>.</p>\n<p>That gives:</p>\n<pre><code>template <\n typename RandomAccessIter,\n typename = typename std::enable_if<\n std::is_same<\n iterator_category,\n typename std::iterator_traits<RandomAccessIter>::iterator_category>()\n && std::is_same<\n value_type,\n typename std::iterator_traits<RandomAccessIter>::value_type>()>::type\n>\nconstexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)\n : ptr_(&*iter)\n{}\n</code></pre>\n<p>Also, <code>iterator_category</code> is always going to be <code>std::random_access_iterator_tag</code>. That’s kinda the point of the class.</p>\n<p>To be safe, it might be wise to use <code>remove_cv</code> on the <code>RandomAccessIterator</code>’s <code>value_type</code>. You shouldn’t <em>need</em> to, because most well-behaved containers and iterators will already have removed the <code>const</code>/<code>volatile</code>… but it pays to be safe, just in case. (I think, for example, there was a bug in the standard in C++11 that raw pointers didn’t behave properly.)</p>\n<p>There is another nasty little bug lurking here with types that overload the address-of operator (unary <code>operator&</code>). To avoid that, you should use <code>std::address_of()</code>. Note that means you can’t be <code>constexpr</code> anymore in C++11, because <code>address_of()</code> wasn’t <code>constexpr</code> until C++17, but… . Can’t be helped. <code>constexpr</code> wasn’t really well-supported in C++11.</p>\n<p>But even in C++11, this <em>can</em> be <code>noexcept</code>, and there’s no reason it shouldn’t be.</p>\n<p><code>operator*</code> is okay, though it too should be <code>noexcept</code>. And it should probably be <code>const</code>. You’re not changing the iterator (wrapper) with this function, or with returned value (which is a pointer to something else entirely, not the iterator). That is why the next function is superfluous.</p>\n<pre><code>// Warning says "const has no effect on type reference"\nconst T& /*reference*/ operator*() const\n{\n return *ptr_;\n}\n</code></pre>\n<p>Okay, to understand what this warning is telling you, I first have to break your misconception of <code>const</code>. <code>const</code> (and <code>volatile</code>, for that matter), does <em>NOT</em> apply to what’s on its <em>RIGHT</em>; it applies to what’s on its <em>LEFT</em>.</p>\n<p>In other words, <code>const T</code> is <em>WRONG</em>. <code>T const</code> is correct. This is the subject of religious fights in the C++ community, but there is an objectively correct answer, and it really matters… as you’ve discovered.</p>\n<p>Now, C++ has a silly little loophole that allows you to write <code>const T&</code>, and the compiler will understand that you <em>REALLY</em> mean <code>T const&</code>. Same for <code>const T*</code>; it gets quietly translated to <code>T const*</code>. So most of the time, you don’t notice that you’re using <code>const</code> wrong. But in <em>this</em> case, you’ve hit one of the cases where the mistake actually causes a problem.</p>\n<p><code>reference</code> is <code>T&</code>. When you <code>const reference</code>… or, better, when you write it <em>CORRECTLY</em> as <code>reference const</code>, that expands to <code>T& const</code>… <em>NOT</em> <code>T const&</code> (or <code>const T&</code>).</p>\n<p>Now do you understand the warning?</p>\n<p>You can’t have a “<code>const</code> reference”, or <code>thing& const</code>. You can have a “reference to a <code>const</code> (thing)”, or <code>thing const&</code>. The thing-being-referenced can be <code>const</code>, but the reference <em>itself</em> cannot. References are <em>always</em> <code>const</code>, because unlike pointers, you can’t change what they are referenced to.</p>\n<p>Note that pointers <em>CAN</em> be <code>const</code>. You can have a <code>T const * const</code>, which is a <code>const</code> pointer to a <code>const</code> <code>T</code> (which is basically <code>T const&</code>, except it can be <code>nullptr</code> and you have to use <code>*</code> everywhere). You can have a <code>T const*</code> which is a non-<code>const</code> pointer to a <code>const</code> <code>T</code>. You can have a <code>T* const</code>, which is a <code>const</code> pointer to a non-<code>const</code> <code>T</code> (basically <code>T&</code>). And of course you can have <code>T*</code>, a non-<code>const</code> pointer to a non-<code>const</code> <code>T</code>.</p>\n<p>I suggest to people I teach C++ to that they read the type <em>backwards</em>. So <code>T&</code> is a “reference to <code>T</code>”, and <code>T const&</code> is a “reference to <code>const</code> <code>T</code>”. (And <code>T const * const</code> is a <code>const</code> pointer to a <code>const</code> <code>T</code>, and so on.)</p>\n<p>So to silence the warning, you have tried to replace <code>reference const</code> with <code>T const&</code>. But that’s wrong. Those are two completely different things. That’s similar to trying to replace a <code>T* const</code> with a <code>T const*</code>. It “works” (without a warning for pointers) only because dropping the <code>const</code> on the pointer doesn’t matter when you’re doing with a copy, and <em>adding</em> the <code>const</code> on the <code>T</code> is always allowed—you’re always allowed to <em>add</em> <code>const</code>. Assigning the former to the latter “works”… but <code>T const*</code> and <code>const T*</code> still are very different things. Assigning <code>T& const</code> to <code>T const&</code> “works” for references too; the only reason you get the warning is because <code>T& const</code> is gibberish.</p>\n<p>All this, by the way, is why <em>CONTAINERS</em> have <code>reference</code> (which is usually <code>T&</code>) and <code>const_reference</code> (which is usually <code>T const&</code>). (And <code>pointer</code> and <code>const_pointer</code>.) If <code>reference</code> was just <code>reference const</code>, there wouldn’t be any need for <code>const_reference</code>.</p>\n<ul>\n<li><code>reference</code> is <code>T&</code></li>\n<li><code>reference const</code> would be <code>T& const</code> (which is gibberish); and</li>\n<li><code>const_reference</code> is <code>T const&</code>.</li>\n</ul>\n<p>Similarly, for <em>CONTAINERS</em>:</p>\n<ul>\n<li><code>pointer</code> is <code>T*</code></li>\n<li><code>pointer const</code> is <code>T* const</code>; and</li>\n<li><code>const_pointer</code> is <code>T const*</code>.</li>\n</ul>\n<p><em>ITERATORS</em> don’t have <code>const_reference</code> or <code>const_pointer</code> because they don’t make any sense for iterators. Instead, there are <code>iterator</code>s and <code>const_iterators</code>:</p>\n<ul>\n<li><code>iterator::reference</code> is <code>T&</code></li>\n<li><code>iterator::pointer</code> is <code>T*</code></li>\n<li><code>const_iterator::reference</code> is <code>T const&</code>; and</li>\n<li><code>const_iterator::pointer</code> is <code>T const*</code>.</li>\n</ul>\n<p>So let’s circle back to the operator functions here:</p>\n<pre><code>reference operator*() const // <- I recommend both const (and noexcept)\n{\n return *ptr_;\n}\n\n// Warning says "const has no effect on type reference"\nconst T& /*reference*/ operator*() const\n{\n return *ptr_;\n}\n</code></pre>\n<p>Notice now that the two functions are literally identical? That’s because you don’t need a non-<code>const</code> version, and because the correct return type for the <code>const</code> version is just <code>reference</code> (not <code>reference const</code> or <code>T const&</code>).</p>\n<p>So all you need is:</p>\n<pre><code>reference operator*() const noexcept\n{\n return *ptr_;\n}\n</code></pre>\n<p>And maybe <code>constexpr</code>, though I don’t know if C++11’s <code>constexpr</code> rules will allow it. (C++17+ will, though.)</p>\n<pre><code>const this_type& operator++()\n{\n ptr_ = std::next(ptr_);\n return *this;\n}\n</code></pre>\n<p>You mentioned that clang-tidy gave a warning about <code>const</code> for the <em>postfix</em> increment operator… are you sure it wasn’t for <em>this</em> function, the <em>prefix</em> increment operator? Because returning a <code>const</code> reference is wrong here. Try doing <code>++ ++i</code> for this type; it won’t compile. The correct form for this operator is to return a non-<code>const</code> reference.</p>\n<p>As for the <em>postfix</em> increment operator, I don’t really see anything wrong with it.</p>\n<p>Now, I’m honestly not sure what you think <code>std::next()</code> is doing here. <code>ptr_</code> is a <code>T*</code>. <code>std::next()</code> for any pointer <code>p</code> is just <code>++p</code>. All this function needs to be is:</p>\n<pre><code>WrappedRandomAccessIterator operator++() noexcept\n{\n ++ptr_;\n return *this;\n}\n</code></pre>\n<p>Alright, that’s it for the code as written. Now I’m going to go on to do a design review.</p>\n<h1>Design review</h1>\n<h2>Ceci n’est pas un iterator</h2>\n<p>Okay, this first problem here is that you claim this to be a random-access iterator… but it’s not. It’s not even a bidirectional iterator. It can’t possibly be any better than a forward iterator… except it’s not even that! It’s not even a legal iterator at all!</p>\n<p>Why? Because an iterator needs more than just <code>operator++</code> (prefix and postfix) and unary <code>operator*</code>. At the bare <em>minimum</em>, the most basic kinds of iterators—input, output, and forward iterators—also require equality operators… that is, both <code>operator==</code> and <code>operator!=</code>. How can you possibly even implement the simplest algorithms, like <code>std::for_each()</code>, without them?</p>\n<pre><code>template <typename Iterator, typename Func>\nvoid example_for_each(Iterator first, Iterator last, Func&& func)\n{\n while (first != last) // won't work without operator !=\n func(*first++);\n}\n</code></pre>\n<p>I’d have to check, but I’m pretty sure that the most basic iterators also need <code>operator-></code>, too.</p>\n<p>A random-access operator also needs <code>operator--</code> (prefix and postfix). And it needs <code>operator+=</code> and <code>operator-=</code> with <code>difference_type</code>. <em>AND</em> it needs binary <code>operator+</code> and binary <code>operator-</code> with <code>difference_type</code> (both ways around). <em>AND</em> it <em>ALSO</em> needs <code>operator-</code> between two iterators, returning a <code>difference_type</code>. And I’m probably forgetting a bunch of other stuff, too. There’s actually quite a lot of operations a random-access iterator can do.</p>\n<p>You need to add a <em>whole</em> lot of extra operators to this class to make it a random-access iterator.</p>\n<h2>Random-access ≠ contiguous</h2>\n<p>Okay, so, here is where I really have to guess at what the real purpose of this class is. I imagine you have some function, call it <code>foo()</code>, that takes a pair of iterators to a sequence—let’s assume it’s a sequence of <code>int</code>s. To actually think this problem concretely through without resorting to vague and nebulous hand-waving, I’m going to assume that <code>foo()</code> actually does something real: I’m going to assume <code>foo()</code> does what <a href=\"https://en.cppreference.com/w/cpp/algorithm/minmax_element\" rel=\"nofollow noreferrer\"><code>std::minmax_element()</code></a> does.</p>\n<p>Now the tricky thing here is that you want <code>foo()</code> to <em>NOT</em> be a function template. You want only the declaration in the header, and the definition in a source file:</p>\n<pre><code>// foo.hpp\nauto foo(??? first, ??? last) -> std::pair<???, ???>;\n\n// foo.cpp\nauto foo(??? first, ??? last) -> std::pair<???, ???>\n{\n auto result = std::pair<???, ???>{first, first};\n\n for (; first != last; ++first)\n {\n if (*first < *(result.first))\n result.first = first;\n\n if (*(result.second) == *first or *(result.second) < *first)\n result.second = first;\n }\n\n return result;\n}\n</code></pre>\n<p>Now we need to figure out what the type <code>???</code> is. This is what I presume you intend <code>WrapperRandomAccessIterator</code> for. You want to do:</p>\n<pre><code>// foo.hpp\nauto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)\n -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>;\n\n// foo.cpp\nauto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)\n -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>\n{\n auto result =\n std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>{\n first, first};\n\n for (; first != last; ++first)\n {\n if (*first < *(result.first))\n result.first = first;\n\n if (*(result.second) == *first or *(result.second) < *first)\n result.second = first;\n }\n\n return result;\n}\n</code></pre>\n<p>And you want to be able to call it with a <code>vector</code> of <code>int</code>s like this:</p>\n<pre><code>auto int_vec = std::vector<int>{};\n// ... fill it with ints somehow...\n\nauto result = foo(\n WrapperRandomAccessIterator<int>{int_vec.begin()},\n WrapperRandomAccessIterator<int>{int_vec.end()});\n</code></pre>\n<p>Something like that, right?</p>\n<p>So the question is… will this work? Yes. Once you add <code>operator!=</code> to the class, then yes, this will work.</p>\n<p>So all good, right?</p>\n<p>No. In fact, you have some nasty bugs lurking, which could easily lead to a segfault, but just as easily not while doing catastrophic damage to your machine… almost certainly not for a machine running a modern desktop OS, of course, but who knows? That’s the problem with UB. Anything could happen.</p>\n<p>Here’s the problem. You assume that given a pair of random-access iterators to a sequence, you can degrade them to pointers, and then treat them the same as the original iterators. For example:</p>\n<pre><code>auto sequence = std::vector<int>{};\n// ... fill sequence with a million ints...\n\n// You assume that this...:\nauto iter_beg = sequence.begin();\nauto iter_end = sequence.end();\nstd::for_each(iter_beg, iter_end, [](int i) { std::cout << i << ' '; });\n\n// ... is basically the same as this...:\nauto ptr_beg = &(*(sequence.begin()));\nauto ptr_end = &(*(sequence.end()));\nstd::for_each(ptr_beg, ptr_end, [](int i) { std::cout << i << ' '; });\n</code></pre>\n<p>For a <code>vector</code>, you’d be right. The two cases above are functionally identical, and your <code>WrapperRandomAccessIterator</code> would work just fine, no problems. It would also work for <code>std::array</code>, <code>std::string</code>, and C arrays (and <code>std::valarray</code>, but who even uses that anymore?).</p>\n<p>But you know what? It won’t work for <code>std::deque</code>.</p>\n<p>Why not? Because you have confused the concept of “random-access iterator” with the concept of “contiguous iterator”. Not all random-access iterators are contiguous iterators:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Container</th>\n<th>Random access?</th>\n<th>Contiguous?</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>std::vector</code></td>\n<td>✓</td>\n<td>✓</td>\n</tr>\n<tr>\n<td><code>std::array</code></td>\n<td>✓</td>\n<td>✓</td>\n</tr>\n<tr>\n<td><code>std::string</code></td>\n<td>✓</td>\n<td>✓</td>\n</tr>\n<tr>\n<td>C array</td>\n<td>✓</td>\n<td>✓</td>\n</tr>\n<tr>\n<td><code>std::deque</code></td>\n<td>✓</td>\n<td>✗</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Internally, a <code>deque</code> is an vector of pointers to arrays. This structure makes appending to the front and back fast—if there’s no space, just add another array chunk, at either the beginning or the end. It also allows for random access—element <code>N</code> is at position “<code>num_elements_in_first_chunk + ((chunk_number * chunk_size) + n)</code>”, and you just solve for <code>chunk_number</code> and <code>n</code> (which is just subtracting <code>num_elements_in_first_chunk</code> from <code>N</code>, then doing <code>N / chunk_size</code> to get <code>chunk_number</code> and <code>N % chunk_size</code> to get <code>n</code>).</p>\n<p>But while random-access is possible in a <code>deque</code>, that doesn’t mean that the elements are contiguous. They <em>are</em> if they all happen to be in the same array chunk. But if the elements are in two different chunks, all bets are off.</p>\n<p>So if you did the example above with a <code>deque</code>…:</p>\n<pre><code>auto sequence = std::deque<int>{};\n// ... fill sequence with a million ints...\n\n// No problems:\nauto iter_beg = sequence.begin();\nauto iter_end = sequence.end();\nstd::for_each(iter_beg, iter_end, [](int i) { std::cout << i << ' '; });\n\n// Boom, UB, possible segfault:\nauto ptr_beg = &(*(sequence.begin()));\nauto ptr_end = &(*(sequence.end()));\nstd::for_each(ptr_beg, ptr_end, [](int i) { std::cout << i << ' '; });\n</code></pre>\n<p>So you might think that, okay, if random-iterators won’t work, you could just use contiguous iterators instead. Well, sorry. There are no contiguous iterators in C++11. (Well, there <em>are</em>, but the concept wasn’t standardized.) Contiguous iterators didn’t come around until C++17… but you couldn’t actually <em>use</em> them until C++20.</p>\n<p>So… what does that mean?</p>\n<p>Well, it means your <code>WrapperRandomAccessIterator</code> won’t actually work for all random-access iterators. Sure, it will work for <em>most</em> random-access iterators (if you actually implement all the required functions)… but not all. And there’s no safe way to detect which iterators will cause a crash (not until C++20).</p>\n<p>So you have two options:</p>\n<ol>\n<li>throw the whole design out; <em>or</em></li>\n<li>accept the limitations, accept that it will only work for <em>some</em> types and maybe add checks to make sure only those types are used, and just live with that.</li>\n</ol>\n<p><em>HOWEVER</em>… if you chose option 2, there is one more thing to consider…</p>\n<h2>Going contiguous? Don’t over-engineer; just use pointers</h2>\n<p>Contiguous iterators are really just pointers. Your misnamed <code>WrapperRandomAccessIterator</code> is actually <code>WrapperContiguousIterator</code>, because it only works for contiguous iterators, because it uses pointers internally.</p>\n<p>But… here’s the thing… if you’re just going to use pointers internally… why not just use them <em>externally</em>, too?</p>\n<p>Let's go back to the <code>foo()</code> function:</p>\n<pre><code>// foo.hpp\nauto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)\n -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>;\n\n// foo.cpp\nauto foo(WrapperRandomAccessIterator<int> first, WrapperRandomAccessIterator<int> last)\n -> std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>\n{\n auto result =\n std::pair<WrapperRandomAccessIterator<int>, WrapperRandomAccessIterator<int>>{\n first, first};\n\n for (; first != last; ++first)\n {\n if (*first < *(result.first))\n result.first = first;\n\n if (*(result.second) == *first or *(result.second) < *first)\n result.second = first;\n }\n\n return result;\n}\n\n// Usage in other.cpp\nauto int_vec = std::vector<int>{};\n// ... fill it with ints somehow...\n\nauto result = foo(\n WrapperRandomAccessIterator<int>{int_vec.begin()},\n WrapperRandomAccessIterator<int>{int_vec.end()});\n</code></pre>\n<p>Since <code>WrapperRandomAccessIterator<int></code> is ultimately just an <code>int*</code>… why not do:</p>\n<pre><code>// foo.hpp\nauto foo(int* first, int* last) -> std::pair<int*, int*>;\n\n// foo.cpp\nauto foo(int* first, int* last) -> std::pair<int*, int*>\n{\n auto result = std::pair<int*, int*>{first, first};\n\n for (; first != last; ++first)\n {\n if (*first < *(result.first))\n result.first = first;\n\n if (*(result.second) == *first or *(result.second) < *first)\n result.second = first;\n }\n\n return result;\n}\n\n// Usage in other.cpp\nauto int_vec = std::vector<int>{};\n// ... fill it with ints somehow...\n\nauto result = foo(&(*(int_vec.begin())), &(*(int_vec.end())));\n// or:\nauto result = foo(int_vec.data(), int_vec.data() + int_vec.size());\n</code></pre>\n<p>Note that if you were going this route, rather than taking a pair of pointers, a safer option might be to take a pointer and a size. It’s easy to mix up pointers, or to one pointer from one sequence and another pointer from another sequence. It’s a lot harder to screw up using a pointer and a size.</p>\n<h2>Actual type-erased iterators…?</h2>\n<p>Okay, so pointers work fine for contiguous iterators, but let’s say you really, <em>really</em> want to use random-access iterators. Or maybe even bidirectional or forward iterators. Can it be done? How?</p>\n<p>Well, I’m not going to put any real thought into solving this problem right now… but if I had to just barf something up, I might do something like this:</p>\n<p>Rather than trying to degrade iterators to pointers, I would ask what are the fundamental operations an iterator needs. A basic iterator—input, output, and forward—needs to be able to do 3 things:</p>\n<ul>\n<li>dereferencing (so <code>*i</code> returns a possibly-<code>const</code> reference)</li>\n<li>movement (so <code>++i</code> advances the <code>i</code>); and</li>\n<li>equality (so <code>i == j</code> returns <code>true</code> if they reference the same thing).</li>\n</ul>\n<p>A bidirectional iterator only adds the ability to do “negative movement”; movement backwards via decrement.</p>\n<p>A random-access iterator adds a <em>TON</em> of stuff… but it really boils down to:</p>\n<ul>\n<li>really big movement (<code>i += n</code> or <code>i -= n</code>)</li>\n<li>distance measuring (<code>i - j</code>); and</li>\n<li>comparison (<code>i < j</code>).</li>\n</ul>\n<p>“Really big movement” is just movement, as is “negative movement”. And we can join equality and comparison if we keep track of what kind of comparison we’re actually doing.</p>\n<p>So we can boil this down to 4 operations. Assuming <code>p</code> and <code>q</code> are type-erased (<code>std::any</code>—I know this requires C++17, but you can always use <code>boost::any</code>) iterators:</p>\n<ul>\n<li><code>deref(std::any p)</code> handles dereferencing (returns a possibly-<code>const</code> reference to whatever the iterator references);</li>\n<li><code>advance(std::any p, std::ptrdiff_t n)</code> handles movement (normally <code>n</code> must be 1, but can be <code>-1</code> for bidirectional iterators, and any number for random-access iterators);</li>\n<li><code>compare(std::any p, std::any q, bool eq)</code> returns <code>int(i == j)</code> if <code>eq</code> is true using the iterators under <code>p</code> and <code>q</code>, or 1, 0, or −1 if <code>eq</code> is <code>false</code> doing a standard 3-way compare between <code>i</code> and <code>j</code>, handling both equality and comparison; and</li>\n<li><code>distance(std::any p, std::any q)</code> handles distance measurement.</li>\n</ul>\n<p>Then we define a class that holds <em>functions</em>:</p>\n<pre><code>template <typename T, typename IterCat>\nclass type_erased_iterator\n{\nprivate:\n std::any _iter;\n std::function<T& (std::any&)> _deref;\n std::function<void (std::any&, std::ptrdiff_t)> _advance;\n std::function<int (std::any const&, std::any const&, bool)> _compare;\n std::function<std::ptrdiff_t (std::any const&, std::any const&)> _distance;\n\npublic:\n using difference_type = std::ptrdiff_t;\n using value_type = typename std::decay_cv<T>::type;\n using pointer = T*;\n using reference = T&;\n using iterator_category = IterCat;\n\n template <typename Iterator>\n explicit type_erased_iterator(Iterator it) :\n _iter{it},\n _deref{[](std::any& p) -> T& { return *std::any_cast<Iterator>(p); }},\n _advance{[](std::any& p, std::ptrdiff_t n) { std::advance(std::any_cast<Iterator>(p), n); }},\n // you get the idea...\n {}\n\n template <typename Iterator>\n type_erased_iterator(\n Iterator it,\n std::function<T& (std::any&)> deref,\n std::function<void (std::any&, std::ptrdiff_t)> advance,\n std::function<int (std::any const&, std::any const&, bool)> compare,\n std::function<std::ptrdiff_t (std::any const&, std::any const&)> distance\n ) :\n _iter{it},\n _deref{std::move(deref)},\n _advance{std::move(advance)},\n _compare{std::move(compare)},\n _distance{std::move(distance)}\n {}\n\n // Now just implement the iterator ops in terms of the core functions.\n\n auto operator++() -> type_erased_iterator&\n {\n _advance(_iter, 1);\n return *this;\n }\n\n auto operator*() -> T&\n {\n return _deref(_iter);\n }\n\n // and so on...\n};\n\n// usage:\nauto int_vec = std::vector<int>{};\n// ... fill it with ints somehow...\n\nauto result = foo(\n type_erased_iterator<int, std::random_access_iterator_tag>{int_vec.begin()},\n type_erased_iterator<int, std::random_access_iterator_tag>{int_vec.end()});\n</code></pre>\n<p>As you can see, it’s used pretty much exactly like the way I assumed <code>WrapperRandomAccessIterator</code> would be used. You could even make a helper function to make it simpler:</p>\n<pre><code>auto result = foo(\n make_type_erased_iterator(int_vec.begin()),\n make_type_erased_iterator(int_vec.end()));\n</code></pre>\n<p>Given that most iterators are small (often just pointers), and that the functions will probably never be closures, there shouldn’t be any dynamic allocation required. This class won’t be fast, but it will allow you to type-erase <em>ANY</em> iterator. Not just random-access; you can even type erase input or output iterators.</p>\n<p>If you really <em>just</em> want to support random-access iterators, that eliminates much of the complexity of SFINAE-ing away illegal iterator operations (like preventing <code>operator--</code> for forward iterators).</p>\n<h1>Summary</h1>\n<p><code>WrapperRandomAccessIterator</code> is unfortunately named, because it is not a wrapper, and it does not work with random-access iterators.</p>\n<p>It <em>does</em> work with contiguous iterators, and <em>ONLY</em> contiguous iterators… or at least it would if you added all the required iterator operations. However, contiguous iterators aren’t really a thing until C++17, and not a <em>practical</em> thing until C++20.</p>\n<p>But if you really only want it to work with contiguous iterators, you might as well just use pointers.</p>\n<p>If you really need other iterator categories (including actual random-access iterators), you will need a much more advanced type-erasure system.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T13:33:50.767",
"Id": "253660",
"ParentId": "253210",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T08:27:31.737",
"Id": "253210",
"Score": "4",
"Tags": [
"c++",
"c++11",
"template",
"iterator"
],
"Title": "wrapper class for random access iterator to hide template method implementation from header file"
}
|
253210
|
<p>It's me again, talented programming beginner fast-learner, so I have overcomed yet another self-imposed programming challenge, I have developped two algorithms to calculate occurrences of Friday the 13th between two given years(including the two inputed years) as said in title using PowerShell, one with built-in, the other without built-in. I have tested them numerous times on Windows 10 Power 7.1 x64, redirected their outputs to txt and compared the txts using fc and compared the results with outputs of other softwares and confirmed they are both working.</p>
<p>My idea is to loop through all 13th's (loop1 through years loop2 in loop1 through months) and check their Fridayness, the one with builtin, I used [DateTime] and [DateTime].DayOfWeek to do this mainly in one line, the one without builtin I used brute force to convert date to number of days, using this:
days=365(y-1)+m+d+leap, where y is the year, m is sum of days before the month, d is day, and leap is: q(y/4)-q(y/100)+q(y/400), where q() means quotient of the division, Now I know of [math]::floor()
and I know I can determine number of leap years using this:</p>
<pre><code>$leap=[math]::floor($year/4)-[math]::floor($year/100)+[math]::floor($year/400)
</code></pre>
<p>But I decided against using this, then I checked Fridayness by date mod 7, I have found out if the remainder is 5 then it's Friday, now here are the scripts:</p>
<p>With Built-in:</p>
<pre><code>$start=Read-Host "Input start year"
$end=Read-Host "Input end year"
$years=$start..$end
$blackfriday=@()
foreach ($year in $years) {
$blackfriday+=1..12 | foreach { [datetime]"$year-$_-13" } | where { $_.DayOfWeek -eq 'Friday'} | foreach {$_.tostring("yyyy, MMMM dd, dddd")}
}
$blackfriday
</code></pre>
<p>Without Built-in:</p>
<pre><code>$months=@(
[PSCustomObject]@{Month='January';Days=31}
[PSCustomObject]@{Month='February';Days=28}
[PSCustomObject]@{Month='March';Days=31}
[PSCustomObject]@{Month='April';Days=30}
[PSCustomObject]@{Month='May';Days=31}
[PSCustomObject]@{Month='June';Days=30}
[PSCustomObject]@{Month='July';Days=31}
[PSCustomObject]@{Month='August';Days=31}
[PSCustomObject]@{Month='September';Days=30}
[PSCustomObject]@{Month='October';Days=31}
[PSCustomObject]@{Month='November';Days=30}
[PSCustomObject]@{Month='December';Days=31}
)
function BlackFriday {
param(
[Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] [int64] $start,
[Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] [int64] $end
)
$years=$start..$end
$blackfriday=@()
foreach ($year in $years) {
$array=1..12
foreach ($arra in $array) {
$month=0
for ($i=0;$i -lt $arra-1;$i++) {
$month+=$months[$i].Days
}
[int]$ye=$year
if ($arra -le 2) { $ye-=1}
if ($ye % 4 -eq 0) {$leap=$ye/4}
else {while ($ye % 4 -ne 0) {$ye-=1}
$leap=$ye/4}
if ($ye % 100 -eq 0) {$century=$ye/100}
else {while ($ye % 100 -ne 0) {$ye-=4}
$century=$ye/100}
if ($ye % 400 -eq 0) {$cycle=$ye/400}
else {while ($ye % 400 -ne 0) {$ye-=100}
$cycle=$ye/400}
$leap=$leap-$century+$cycle
$date=[int64](($year-1)*365+$month+13+$leap)
if ($date % 7 -eq 5) {
$name=$months[$arra-1].Month
$blackfriday+=[string]"$year, $name 13, Friday"
}
}
}
$blackfriday
}
$start=Read-Host "Input start year"
$end=Read-Host "Input end year"
BlackFriday $start $end
</code></pre>
<p>But wait, I have also written a script based on Zeller's algorithm from here:
<a href="https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week</a>
Which is not working, I don't know where I did wrong, I don't know whose fault this is, please help me make all three scripts better, I will post it below:</p>
<pre><code>$months=@(
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December'
)
function BlackFriday {
param(
[Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] [int64] $start,
[Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] [int64] $end
)
$years=$start..$end
$blackfriday=@()
foreach ($year in $years) {
$array=1..12
foreach ($arra in $array) {
$m=$arra
$ye=$year
if ($arra -le 2) {
$m=$m+12
$ye-=1
}
[int64]$y=([string]$ye).substring(([string]$ye).length-2)
[int64]$c=([char[]]"$ye"|Select-Object -First 2) -Join ''
$week=[int](((13*($m+1))/5 + $y/4 + $c/4 + 13 + $y - 2*$c) % 7)
if ($week -eq 6) {
$name=$months[$arra-1]
$blackfriday+=[string]"$year, $name 13, Friday"
}
}
}
$blackfriday
}
$start=Read-Host "Input start year"
$end=Read-Host "Input end year"
BlackFriday $start $end
</code></pre>
|
[] |
[
{
"body": "<p>Why reinvent the wheel? Why not use <strong><code>Get-Date</code></strong> cmdlet, and simplify the code?</p>\n<pre><code>$StartDate = Get-Date -Day 13 -Month 1 -Year 2019\n$EndDate = Get-Date -Day 13 -Month 12 -Year 2020\n$IntStartDate = $StartDate.TofileTime()\n$IntEndDate = $EndDate.TofileTime()\n\ndo {\n if ($StartDate.DayOfWeek -eq 'Friday') {\n Write-Host ($StartDate.tostring("dd-MMMM-yyyy"))\n }\n $StartDate = $StartDate.AddMonths(1)\n $IntStartDate = $StartDate.TofileTime()\n}\nwhile ($IntStartDate -le $IntEndDate)\n</code></pre>\n<p>Implement this in your function with parametrization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-31T11:56:40.450",
"Id": "254129",
"ParentId": "253213",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T10:26:40.473",
"Id": "253213",
"Score": "1",
"Tags": [
"beginner",
"programming-challenge",
"datetime",
"powershell"
],
"Title": "PowerShell - calculate occurences of Friday the 13th between (including) two given years with builtin and without builtin"
}
|
253213
|
<p>Required to splice specific element value in an array based on the condition.</p>
<p>Both the below code does the same job and yields the correct results. But couldn't figure out how to reduce coding structure with ECMAScript and which is performance oriented considering an array would have atleast 1.5k or even larger</p>
<p>This is with ECMAScript</p>
<pre><code>this.candidateColumns.filter(item => item === 'Certificate').map(m => {
if (!this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {
this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')
}
});
</code></pre>
<p>This is simple forEach Loop code</p>
<pre><code>this.candidateColumns.forEach((currentValue, index) => {
if (currentValue === 'Certificate' && !this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {
this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')
}
});
</code></pre>
<p>Any other Built In function Approach could be done for better performance or readability</p>
|
[] |
[
{
"body": "<p><strong><code>.map</code> is only for the construction of new arrays</strong> - for example, <code>arr.map(num => num / 2)</code>, to transform every element of one array into another array. If you aren't returning anything from the <code>.map</code> callback, or if you aren't using the resulting array, then <code>.map</code> isn't appropriate. If all you're interested in is something that can be accomplished with side-effects, use a generic iteration method like <code>for..of</code> or <code>forEach</code> (like with your second snippet).</p>\n<p>But:</p>\n<p><strong>Select the proper iteration method</strong> - <code>forEach</code> can be used to accomplish pretty much any task while iterating over an array, but that's somewhat of a <em>weakness</em>, because it makes the intent of the code somewhat less clear. In this case, your logic is:</p>\n<blockquote>\n<p>If <code>CERTIFICATEPRINT</code> showing is off, remove any Certificate items from the <code>candidateColumns</code> array.</p>\n</blockquote>\n<p>There's no need for a nested loop, which will increase the computational complexity to <code>O(n ^ 2)</code> (a <em>big</em> jump). This can easily be accomplished by putting a <code>.filter</code> inside an <code>if</code>, <code>O(n)</code>:</p>\n<pre><code>if (!this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {\n this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')\n}\n</code></pre>\n<blockquote>\n<p>performance oriented considering an array would have atleast 1.5k or even larger</p>\n</blockquote>\n<p>With thousands of elements, <code>O(n ^ 2)</code> would indeed be a problem, but the <code>O(n)</code> operation should be quite reasonable; a few thousand operations is next to nothing on modern hardware.</p>\n<p><strong>Is reassignment necessary?</strong> You assign the result of the filter to <code>this.candidateColumns</code>. Is that required? Could you, for example, allow the filtered array to be used by <em>returning</em> it instead, or by passing it along to whatever needs the data? If possible, consider doing so, if it doesn't make the code convoluted - code is generally easier to make sense of when mutations are only done when necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T15:05:21.417",
"Id": "253219",
"ParentId": "253217",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T14:05:24.870",
"Id": "253217",
"Score": "1",
"Tags": [
"javascript",
"array",
"ecmascript-6",
"typescript"
],
"Title": "Filtering Array Based on Element Values"
}
|
253217
|
<h1>Spoiler: <a href="https://adventofcode.com/2020/day/8" rel="nofollow noreferrer">Advent of Code 2020 Day 8</a></h1>
<blockquote>
<p>Your flight to the major airline hub reaches cruising altitude without incident. While you consider checking the in-flight menu for one of those drinks that come with a little umbrella, you are interrupted by the kid sitting next to you.</p>
<p>Their handheld game console won't turn on! They ask if you can take a look.</p>
<p>You narrow the problem down to a strange infinite loop in the boot code (your puzzle input) of the device. You should be able to fix it, but first you need to be able to run the code in isolation.</p>
<p>The boot code is represented as a text file with one instruction per line of text. Each instruction consists of an operation (acc, jmp, or nop) and an argument (a signed number like +4 or -20).</p>
<ul>
<li>acc increases or decreases a single global value called the accumulator by the value given in the argument. For example, acc +7 would increase the accumulator by 7. The accumulator starts at 0. After an acc instruction, the instruction immediately below it is executed next.</li>
<li>jmp jumps to a new instruction relative to itself. The next instruction to execute is found using the argument as an offset from the jmp instruction; for example, jmp +2 would skip the next instruction, jmp +1 would continue to the instruction immediately below it, and jmp -20 would cause the instruction 20 lines above to be executed next.</li>
<li>nop stands for No OPeration - it does nothing. The instruction immediately below it is executed next.</li>
</ul>
<p>For example, consider the following program:</p>
<p>nop +0<br />
acc +1<br />
jmp +4<br />
acc +3<br />
jmp -3<br />
acc -99<br />
acc +1<br />
jmp -4<br />
acc +6</p>
<p>These instructions are visited in this order:</p>
<p>nop +0 | 1<br />
acc +1 | 2, 8(!)<br />
jmp +4 | 3<br />
acc +3 | 6<br />
jmp -3 | 7<br />
acc -99 |<br />
acc +1 | 4<br />
jmp -4 | 5<br />
acc +6 |</p>
<p>First, the nop +0 does nothing. Then, the accumulator is increased from 0 to 1 (acc +1) and jmp +4 sets the next instruction to the other acc +1 near the bottom. After it increases the accumulator from 1 to 2, jmp -4 executes, setting the next instruction to the only acc +3. It sets the accumulator to 5, and jmp -3 causes the program to continue back at the first acc +1.</p>
<p>This is an infinite loop: with this sequence of jumps, the program will run forever. The moment the program tries to run any instruction a second time, you know it will never terminate.</p>
<p>Immediately before the program would run an instruction a second time, the value in the accumulator is 5.</p>
<p>Run your copy of the boot code. Immediately before any instruction is executed a second time, what value is in the accumulator?</p>
</blockquote>
<p>I'm solving AoC problems with Rust this year and ran across something where I <em>feel</em> there has to be a better, more Rust-like solution. In my loop, I'm derefing mutable references quite a bit and someone suggested smart pointers, but I don't know how that would look in my existing implementation.</p>
<p>How would you address the mutability on <code>Instruction</code>'s members?</p>
<pre class="lang-rust prettyprint-override"><code>pub enum Instruction {
Jump { address: i32, is_noop: bool, has_run: bool },
Acc(i32, bool),
}
impl Instruction {
pub fn new(s: &str) -> Self {
let instruction = &s[..3];
let address: i32 = (&s[4..]).parse().unwrap();
match instruction {
"jmp" => Self::Jump { address, is_noop: false, has_run: false },
"nop" => Self::Jump { address, is_noop: true, has_run: false },
"acc" => Self::Acc(address, false),
_ => unreachable!(),
}
}
}
pub fn parse(s: &str) -> Vec<Instruction> {
s.split('\n')
.map(Instruction::new)
.collect()
}
pub fn solve(input: &mut Vec<Instruction>) -> i32 {
let mut acc = 0;
let mut idx = 0;
loop {
match &mut input[idx] {
Instruction::Jump { address, is_noop, has_run } => {
if *has_run {
break;
}
*has_run = true;
if !*is_noop {
idx = (idx as i32 + *address) as usize;
continue;
}
}
Instruction::Acc(data, has_run) => {
if *has_run {
break;
}
*has_run = true;
acc += *data;
}
}
idx += 1;
}
acc
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn p1_example() {
let input = "nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6";
let mut input = parse(input);
let acc = solve(&mut input);
assert_eq!(acc, 5);
}
}
</code></pre>
<p>--- Part Two ---</p>
<blockquote class="spoiler">
<p><br />
After some careful analysis, you believe that exactly one instruction is corrupted.<br />
<br />
Somewhere in the program, either a jmp is supposed to be a nop, or a nop is supposed to be a jmp. (No acc instructions were harmed in the corruption of this boot code.)<br />
<br />
The program is supposed to terminate by attempting to execute an instruction immediately after the last instruction in the file. By changing exactly one jmp or nop, you can repair the boot code and make it terminate correctly.<br />
<br />
For example, consider the same program from above:<br />
<br />
nop +0<br />
acc +1<br />
jmp +4<br />
acc +3<br />
jmp -3<br />
acc -99<br />
acc +1<br />
jmp -4<br />
acc +6<br />
<br />
If you change the first instruction from nop +0 to jmp +0, it would create a single-instruction infinite loop, never leaving that instruction. If you change almost any of the jmp instructions, the program will still eventually find another jmp instruction and loop forever.<br />
<br />
However, if you change the second-to-last instruction (from jmp -4 to nop -4), the program terminates! The instructions are visited in this order:<br />
<br />
nop +0 | 1<br />
acc +1 | 2<br />
jmp +4 | 3<br />
acc +3 |<br />
jmp -3 |<br />
acc -99 |<br />
acc +1 | 4<br />
nop -4 | 5<br />
acc +6 | 6<br />
<br />
After the last instruction (acc +6), the program terminates by attempting to run the instruction below the last instruction in the file. With this change, after the program terminates, the accumulator contains the value 8 (acc +1, acc +1, acc +6).<br />
<br />
Fix the program so that it terminates normally by changing exactly one jmp (to nop) or nop (to jmp). What is the value of the accumulator after the program terminates?</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:47:02.673",
"Id": "499320",
"Score": "1",
"body": "I'm not sure I understand what part of *dereferencing mutable references* is supposed to be a problem, or how smart pointers could \"solve\" it. I mean, \"dereference\" is pretty much the main useful thing you do with a reference. Is this just about reducing the number of `*`s in your source code? Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:13:53.707",
"Id": "499321",
"Score": "0",
"body": "@trentcl It's about ergonomics mostly and learning what patterns are available for mutability; having to deref everything feels sloppy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:34:47.260",
"Id": "499324",
"Score": "1",
"body": "*and someone suggested smart pointers* — did you ask that person for specifics of **how** it would help? If you just want to reduce the `*`, you can try something like `match *&mut input[idx] { Instruction::Jump { address, is_noop, ref mut has_run }` to dereference `address` / `is_noop` in the pattern match"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:56:34.993",
"Id": "499325",
"Score": "0",
"body": "@Shepmaster negative; it was a one-off comment when I was asking for feedback on a different platform. Is `*&mut` different from `mut`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T20:11:04.547",
"Id": "499326",
"Score": "1",
"body": "`mut` by itself isn't syntactically valid in this context. You should actually use `match input[idx]` as it's less tangled :-) See also [What's the difference between placing “mut” before a variable name and after the “:”?](https://stackoverflow.com/q/28587698/155423)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T20:52:51.053",
"Id": "499332",
"Score": "0",
"body": "@Shepmaster gotcha, in my head `*` is inverse to `&`. that answer was illuminating. So it sounds like for my case here, the \"best\" approach is to deref in the match argument so I don't have to deref literally everything else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T21:03:14.300",
"Id": "499333",
"Score": "0",
"body": "That's what I would do without looking at the bigger picture of your code (thus why the comments and not an answer) See also [What does &* combined together do in Rust?](https://stackoverflow.com/q/41273041/155423)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T11:05:38.400",
"Id": "499736",
"Score": "1",
"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 [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>Having derefs is OK, as others mentioned in comments. I just wanted to address the existence of <em>explicit</em> derefs. We can use <em>implicit</em> derefs. This requires splitting off our <code>Instruction</code> type into <code>JumpInstruction</code> and <code>AccInstruction</code>, which is common practice, done for example in Rust's AST. We have:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub enum Instruction {\n Jump(JumpInstruction),\n Acc(AccInstruction),\n}\n\npub struct JumpInstruction {\n address: i32,\n is_noop: bool,\n has_run: bool,\n}\n\npub struct AccInstruction {\n data: i32,\n has_run: bool,\n}\n</code></pre>\n<p>Then it's a matter of changing each <code>*field</code> to <code>jump.field</code> or <code>acc.field</code>. Also, some code must be accomodated:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>impl Instruction {\n pub fn new(s: &str) -> Self {\n let instruction = &s[..3];\n let address: i32 = (&s[4..]).parse().unwrap();\n\n match instruction {\n "jmp" => Self::Jump(JumpInstruction {\n address,\n is_noop: false,\n has_run: false,\n }),\n "nop" => Self::Jump(JumpInstruction {\n address,\n is_noop: true,\n has_run: false,\n }),\n "acc" => Self::Acc(AccInstruction {\n data: address,\n has_run: false,\n }),\n _ => unreachable!(),\n }\n }\n}\n\npub fn parse(s: &str) -> Vec<Instruction> {\n s.split('\\n').map(Instruction::new).collect()\n}\n\npub fn solve(input: &mut Vec<Instruction>) -> i32 {\n let mut result = 0;\n let mut idx = 0;\n\n loop {\n match &mut input[idx] {\n Instruction::Jump(jump) => {\n if jump.has_run {\n break;\n }\n jump.has_run = true;\n if !jump.is_noop {\n idx = (idx as i32 + jump.address) as usize;\n continue;\n }\n }\n Instruction::Acc(acc) => {\n if acc.has_run {\n break;\n }\n acc.has_run = true;\n result += acc.data;\n }\n }\n\n idx += 1;\n }\n\n result\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn p1_example() {\n let input = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6";\n let mut input = parse(input);\n let acc = solve(&mut input);\n\n assert_eq!(acc, 5);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:32:19.623",
"Id": "499532",
"Score": "0",
"body": "So `Enum(struct)` is different from `Enum { .. }`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:50:05.653",
"Id": "499535",
"Score": "0",
"body": "@MaximilianBurszley Yes. They look different and need different looking code, but fundamentally work the same way. The former has one tuple-like field with multiple fields whereas in the latter, access does not go through that one tuple-like field. The code semantics should be the same in both cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:59:36.580",
"Id": "499536",
"Score": "0",
"body": "This is much cleaner than my approach and I like it. Thanks for the advice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:19:29.263",
"Id": "253312",
"ParentId": "253224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253312",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T17:20:01.450",
"Id": "253224",
"Score": "-1",
"Tags": [
"rust",
"pointers"
],
"Title": "How to eliminate derefs?"
}
|
253224
|
<p>I'm working on a school project where I need to implement the pathfinding algorithm. The requirements are that it needs to find the path in at most a few seconds and ideally in less than 1 second. I've been trying to optimize my code to make the algorithm faster but it keeps taking a few minutes to find the path and I can't find what the cause it is..</p>
<p>I'll provide my code below and I hope someone will be able to help and/or point to things that can be done more efficiently which would be greatly appreciated.</p>
<p>Header of Pathfinder:</p>
<pre><code>#ifndef PATHFINDER_H
#define PATHFINDER_H
//#include "world.h"
#include "lib/world.h"
#include "node.h"
#include <iostream>
#include <QSet>
#include <QStack>
#include <QHash>
#include <cmath>
#include <queue>
class Pathfinder
{
public:
Pathfinder(std::vector<std::shared_ptr<Tile>> tiles, int columns, int rows);
struct compareDistance {
bool operator()(const std::shared_ptr<Node> a , const std::shared_ptr<Node> b){
return (b->getF() < a->getF());
}
};
std::vector<std::shared_ptr<Node>> nodeList;
std::priority_queue<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>,
compareDistance> openList;
std::vector<std::shared_ptr<Node>> closedList;
QStack<std::shared_ptr<Tile>> path;
QStack<std::shared_ptr<Tile>> findPath(int xDestination, int yDestination);
std::vector<std::shared_ptr<Enemy>> enemyList;
std::vector<std::shared_ptr<PEnemy>> pEnemyList;
//std::vector<std::shared_ptr<HealthPack>> healthpacks;
float getWeight() const;
void setWeight(float value);
float getHeuristicCost(int current_x, int current_y, int destination_x, int destination_y);
int getHeight() const;
void setHeight(int value);
int getWidth() const;
void setWidth(int value);
float getMoveCost() const;
void setMoveCost(float value);
bool solveAlgorithm(int xDestination, int yDestination);
void startingPoint(int xStart, int yStart);
private:
std::vector<std::shared_ptr<Tile>> tiles;
float weight = 1;
int width = 0;
int height = 0;
bool isValid(int x, int y);
void addNeighbors(int index, std::shared_ptr<Node> pre, std::shared_ptr<Node> finalNode);
std::shared_ptr<Tile> getTile(int x,int y);
std::vector<int> specialTiles;
};
#endif // PATHFINDER_H
</code></pre>
<p>Function to iterate over all the nodes and update their distance:</p>
<pre><code>bool Pathfinder::solveAlgorithm(int xDestination, int yDestination)
{
std::cout<<"Solve Algorithm starting"<<std::endl;
auto destinationIndex = xDestination + yDestination*width;
auto destinationTile = std::make_shared<Tile>(xDestination,yDestination,tiles[(uint)destinationIndex]->getValue());
std::shared_ptr<Node> destinationNode = std::make_shared<Node>(destinationTile,nullptr);
nodeList[destinationIndex] = destinationNode; //nodeList is std::vector<std::shared_ptr<Node>>
std::cout<<"Width: "<<width<<std::endl;
std::cout<<"Height: "<<height<<std::endl;
//openList is priorityQueue
while(!openList.empty()){
std::shared_ptr<Node> currentNode = openList.top();
openList.pop(); //remove currentNode from openList
closedList.push_back(currentNode); //closedList is std::vector<shared_ptr<Node>>
//int index = currentNode->getTile()->getXPos()+currentNode->getTile()->getYPos()*width;
//closed.insert(index,currentNode);
auto currentTile = currentNode->getTile();//Tile the current node points to
int currentX = currentTile->getXPos();
int currentY = currentTile->getYPos();
std::cout<<"Start position: "<<currentTile->getXPos()<<", "<<currentTile->getYPos()<<std::endl;
if(currentNode == destinationNode){
return true;
}
for (int newX = -1; newX <= 1; newX++) {
for (int newY = -1; newY <= 1; newY++) {
if(isValid(currentX+newX,currentY+newY) && !(newX == 0 && newY == 0)){
int newIndex = (currentX+newX) + (currentY+newY)*width;
addNeighbors(newIndex,currentNode,destinationNode);
}
}
}
}
return false;
}
</code></pre>
<p>Function to check or add neighbours:</p>
<pre><code>void Pathfinder::addNeighbors(int index, std::shared_ptr<Node> parent, std::shared_ptr<Node> final)
{
//tiles is std::vector<std::shared_ptr<Tile>>
auto tilePointer = tiles[(uint)index];//convert tile this node is associated with from unique ptr to shared ptr
std::shared_ptr<Node> neighbor;
//Neighbor not yet discovered
if(nodeList[index] == nullptr){
neighbor = std::make_shared<Node>(tilePointer, nullptr);
nodeList[index] = neighbor;
}
else{
neighbor = nodeList[index];
}
if(neighbor->getTile()->getValue() <= 1){
//if neighbor is not in closed list
if(std::find(closedList.begin(), closedList.end(), neighbor) == closedList.end()){
auto tempG = parent->getG() + sqrt(pow(neighbor->getTile()->getXPos()-parent->getTile()->getXPos(),2)+pow(neighbor->getTile()->getYPos()-parent->getTile()->getYPos(),2));
tempG = (tempG + (1-neighbor->getTile()->getValue()));//*weight;
auto tempH = getHeuristicCost(neighbor->getTile()->getXPos(),neighbor->getTile()->getYPos(),final->getTile()->getXPos(),final->getTile()->getYPos());
tempH *= weight;
double tempF = tempG + tempH;
//The neighbor was newly made node - also possible to check the G cost of neighbor
//If G = 0 ==> not yet updated and hence new node
if(neighbor->getParent() == nullptr){
neighbor->setParent(parent);
neighbor->setG(tempG);
neighbor->setH(tempH);
openList.push(neighbor);
}
else {
//We found better path ==> update cost and parent
if(neighbor->getF() > tempF){
neighbor->setParent(parent);
neighbor->setG(tempG);
neighbor->setH(tempH);
}
}
}
}
}
</code></pre>
<p>The header of the Node Class:</p>
<pre><code>#ifndef NODE_H
#define NODE_H
#include "world.h"
#include "lib/world.h"
#include <memory>
#include <limits>
class Node
{
public:
Node(std::shared_ptr<Tile> tile,std::shared_ptr<Node> previousNode);
Node();
std::shared_ptr<Tile> getTile() const;
void setTile(const std::shared_ptr<Tile> &value);
std::shared_ptr<Node> getParent() const;
void setParent(std::shared_ptr<Node> value);
double getG() const;
void setG(double value);
double getF() const;
double getH() const;
void setH(double value);
private:
std::shared_ptr<Node> parent;
std::shared_ptr<Tile> tile;
double g;
double h;
};
</code></pre>
<p>My heuristic function is the Manhattan distance: <code>return abs(destination_x - current_x)+abs(destination_y - current_y);</code></p>
<p>For the backtracing I use a Stack so I can simply <code>pop()</code> as long as it is not empty to draw the tiles being part of the path found:</p>
<pre><code>QStack<std::shared_ptr<Tile>> Pathfinder::findPath(int xDestination, int yDestination)
{
if(solveAlgorithm(xDestination,yDestination) == true){
std::shared_ptr<Node> endNode = closedList.back(); //endNode or destination is the last added node to the closedList
while(endNode->getParent() != nullptr){
path.push(endNode->getTile());//push the tile of parent to top of stack
endNode = endNode->getParent();
}
return path;
}
else{
return path;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T05:52:43.960",
"Id": "499484",
"Score": "0",
"body": "Please show the header of the `Pathfinder` class also"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T13:03:16.377",
"Id": "499512",
"Score": "0",
"body": "@harold I just added the Pathfinder header"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T19:22:03.803",
"Id": "499557",
"Score": "0",
"body": "I could not compile it, various types do not match. For example there is `void addNeighbors(int index, Node* pre, Node* finalNode);` in the header, but the implementation uses `shared_ptr<Node>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T20:07:01.437",
"Id": "499559",
"Score": "0",
"body": "@harold My apologies, I copy pasted my actual version of the Pathfinder header where I changed everything to ```Node*``` instead of ```std::shared_ptr<Node>```. I edited the header, it should be fine now"
}
] |
[
{
"body": "<h1>An easy performance win</h1>\n<p>I had to make up some code to "fill the gaps", and my own map, but with that I managed to compile and profile the code. The result is not a big surprise though. On a 200x200 map with some annoying obstacles (to prevent the search being too trivial), there was one line in the whole program that took 95% of the time:</p>\n<blockquote>\n<pre><code>if (std::find(closedList.begin(), closedList.end(), neighbor.get()) == closedList.end())\n</code></pre>\n</blockquote>\n<p>That does not surprise me: the closed list can easily get quite large (depending on the obstacles, about as large as the whole map), and here is a linear search over the whole thing.</p>\n<p>There are other ways it could work, for examble a boolean <code>isClosed</code> on the <code>Node</code> object (this is the simplest way to fix the problem), or a hashmap of coordinates, or even a 2D array of booleans. <code>std::vector</code> is not a good choice to represent the Closed set with.</p>\n<p>Keep in mind that this line will stop working:</p>\n<blockquote>\n<pre><code> Node* endNode = closedList.back();\n</code></pre>\n</blockquote>\n<p>But there are other ways to get that node.</p>\n<h1>A sneaky bug</h1>\n<p>Consider this piece of the code:</p>\n<blockquote>\n<pre><code>//We found better path ==> update cost and parent\nif (neighbor->getF() > tempF) {\n neighbor->setParent(parent);\n neighbor->setG(tempG);\n neighbor->setH(tempH);\n}\n</code></pre>\n</blockquote>\n<p>Often I see this code omitted, which in a sense is even more incorrect, but this implementation of the "change parent if a shortcut to an open node is found" has a problem: the priority queue is not informed of the new F score. As a result, the node may not come out of the queue at the right moment, and more insidiously this violates the internal structure of the priority queue.</p>\n<p><code>std::priority_queue</code> does not have the capability of responding to a changed key. You could make your own data structure that <em>can</em> do that, by implementing your own binary heap on top of an <code>std::vector</code> and a hashmap from coordinate to index-in-the-heap. The hashmap is to be able to efficiently find where in the heap a given node currently is, which is necessary to be able to restore the heap property for that node. Any time something in the heap moves, that hashmap would need to be updated with the new indexes.</p>\n<p>Since that slightly odd mechanism is needed, the <code>std::push_heap</code> and <code>std::pop_heap</code> functions from the <code>algorithm</code> header are not much use. It can be done without the hashmap mechanism, but then there will sometimes be a linear search over the entire Open List, which would create a similar situation as there was with the slow search through the Closed List.</p>\n<h1>Overuse of <code>std::shared_ptr</code></h1>\n<p>For large maps, destroying the <code>Pathfinder</code> object can cause a stack overflow due to too many chained <code>shared_ptr<Node></code> destructions. In my opinion, the pointer to <code>parent</code> should not be a <code>shared_ptr</code>: nodes don't partially own their parent, the <code>Pathfinder</code> owns all nodes. It should be possible to arrange that with <code>unique_ptr</code>, or by keeping the nodes in the <code>nodeList</code> by value. The node itself can refer to its parent by raw pointer or node-index or coordinate or even by an integer 0..7 that tells the direction to go in. A node does not need <em>access</em> to its parent, it merely needs to record which way to go when constructing the path.</p>\n<p>The <code>openList</code> does not need to redundantly double-own the nodes which the pathfinder already owns through the <code>nodeList</code>. That applies to <code>closeList</code> as well, but I recommended its removal to begin with.</p>\n<p>Similarly, in my view nodes don't really have shared ownership of tiles, the map owns tiles and nodes merely refer to existing tiles: <code>shared_ptr</code> is not really appropriate.</p>\n<p>The resulting path does not need to own the tiles either and I would suggest a vector of coordinates (by value) to ensure that it only contains the data that really matters and doesn't entangle itself with ownership.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T20:10:55.187",
"Id": "499631",
"Score": "0",
"body": "Thanks for this detailed answer! Indeed I changed this line you pointed out and it is much faster now! Also I had already changed all these ```std::shared_ptr``` and I'm using raw pointer now for parent etc.\nI don't quite understand this _The ```openList``` does not need to redundantly double-own the nodes which the pathfinder already owns through the ```nodeList```_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T00:28:45.690",
"Id": "499650",
"Score": "1",
"body": "@Zyo2606 I mean since the nodes are present in the `nodeList` and kept alive that way, the `openList` does not need to keep alive those nodes also: it could refer to them to by raw pointer or index or coordinate etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T11:49:55.153",
"Id": "499666",
"Score": "0",
"body": "Yes ok I understand, that is indeed changed to raw pointer in the meantime :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T22:04:50.603",
"Id": "253321",
"ParentId": "253225",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T17:38:05.393",
"Id": "253225",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"c++17",
"a-star"
],
"Title": "A-star pathfinding algorithm"
}
|
253225
|
<p>Simple code for getting documents that have a <code>creationDate</code> between two values in mongodb.</p>
<p>If the user provides only one of the values the code should still work and get the documents that have either a <code>creationDate</code> less than or bigger than the given value.</p>
<p>I'm mainly looking for more readability and simplicity.</p>
<pre><code>interface mongoDateFilter {
$gte?: Date;
$lte?: Date;
}
export const getReportsForContent = async (
contentId: ObjectId,
beginDate: Date | undefined,
endDate: Date | undefined,
): Promise<Report[]> => {
const reportsCollection = await getCollection('reports');
const creationDateMongoFilter: mongoDateFilter = {};
if (beginDate) {
creationDateMongoFilter['$gte'] = beginDate;
}
if (endDate) {
creationDateMongoFilter['$lte'] = endDate;
}
let reportsForContent: Report[] = [];
if (beginDate || endDate) {
reportsForContent = await reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
} else {
reportsForContent = await reportsCollection.find({ contentId }).toArray();
}
return reportsForContent;
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Prefer dot notation over bracket notation</strong> when syntax permits it - it's a bit easier to read and write. ESLint rule: <a href=\"https://eslint.org/docs/rules/dot-notation\" rel=\"nofollow noreferrer\"><code>dot-notation</code></a>.</p>\n<p><strong>Construct objects all in one go</strong> rather than mutating them afterwards, if you can - it's easier to write (especially in TypeScript, since you don't have to denote the type ahead of time) and can be easier to understand at a glance when unnecessary mutation is avoided.</p>\n<p><strong>Don't assign expressions that won't be used</strong> - with</p>\n<pre><code>let reportsForContent: Report[] = [];\n</code></pre>\n<p>regardless of the situation, <code>reportsForContent</code> will be reassigned to something else afterwards, so you can leave off the <code>= []</code> part.</p>\n<p>Or, even better:</p>\n<p><strong>Return the value retrieved instead of reassigning a variable and then returning the variable</strong>. This:</p>\n<pre><code> if (beginDate || endDate) {\n reportsForContent = await reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();\n } else {\n reportsForContent = await reportsCollection.find({ contentId }).toArray();\n }\n</code></pre>\n<p>can be</p>\n<pre><code> if (beginDate || endDate) {\n return reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();\n } else {\n return reportsCollection.find({ contentId }).toArray();\n }\n</code></pre>\n<p>Or, even better, handle the case where no date is set at the very beginning, and only construct the <code>creationDateMongoFilter</code> later, if it's needed.</p>\n<p><strong>In all:</strong></p>\n<pre><code>export const getReportsForContent = async (\n contentId: ObjectId,\n beginDate: Date | undefined,\n endDate: Date | undefined,\n): Promise<Report[]> => {\n const reportsCollection = await getCollection('reports');\n if (!beginDate && !endDate) {\n return reportsCollection.find({ contentId }).toArray();\n }\n const creationDateMongoFilter = {\n (...beginDate && { $gte: beginDate }),\n (...endDate && { $lte: endDate }),\n };\n return reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();\n};\n</code></pre>\n<p>No need for the <code>mongoDateFilter</code> interface anymore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:53:31.063",
"Id": "499466",
"Score": "0",
"body": "Sending `undefined` to one of `$gte` or `$lte` while the other one is a defined and a date, will not result in the same behavior as supplying only one of `$gte` or `$lte` that's why I had those if statements and conditionally filled the `creationDateMongoFilter` object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T00:27:45.110",
"Id": "499471",
"Score": "1",
"body": "Oh, that's unfortunate, that's a surprisingly strict interpretation Mongo has. Tweak is simple enough, you can conditionally add properties to the object during its definition, see https://stackoverflow.com/q/11704267"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:45:25.970",
"Id": "253228",
"ParentId": "253226",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:14:01.283",
"Id": "253226",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"typescript",
"mongodb"
],
"Title": "MongoDB Filter between two dates"
}
|
253226
|
<p>The code determines if a number is prime or not, and there are some initial checks to rule out some values.</p>
<p>I would like feedback on how to speed up this program. I am really new to threads - might that be useful? I really don't know where to begin multithreading this code.</p>
<pre><code>import java.io.*;
import java.math.BigInteger;
/*
A known proof exists for prime numbers not withstanding the values 2 and 3, such that
all prime numbers are of the form (6k)+-1.
For example:
{(5 = 6(1)-1),(13 = 6(2)+1),(1 = 6(0)+1),(5081 = 6(847)-1)...(anyPrimeNumberNot2or3 = (6k)+-1)}
*/
class primeFinder {
// takes your number to check
static boolean isPrime(BigInteger n) {
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
BigInteger five = new BigInteger("5");
BigInteger six = new BigInteger("6");
// we omit one because isnt prime because it has less
// than 2 divisors, and we also omit negatives
if (n.compareTo(BigInteger.ONE) != 1) return false;
// 2 and 3 are both prime so we return true for each
if (n.compareTo(three) != 1) return true;
/*
check here to see if divisible by two or three to speed things up
*/
try {
if (n.mod(two) == BigInteger.ZERO || n.mod(three) == BigInteger.ZERO) return false;
} catch (ArithmeticException a) {
return false;
}
/*
starting at 5, check for divisibility based on our proof.
incrementing i by 6 each time gives us a chance to check when
the index is a value of 6k.
it begins by squaring 5 to compare with 25. If n is less than 25
and it is divisible by 2 or three, it will have been caught by this
point in the last check. We use this squaring iteratively because it
concludes primality at a much faster rate by checking realatively large
ranges of numbers instead of one integer at a time.
e.g. n = 18 or 15
N will have been thrown already because numbers
that small can only be divisible by a few integers that are all divisible
by two or three. ,
however, if n = 19, than it will be found to be prime and the program
will return true after failing the second argument of the for loop...
e.g. (25 !<= 19)
*/
for (BigInteger i = five; i.pow(2).compareTo(n) != 1; i = i.add(six))
/*
otherwise, if the number is larger than 25 (needs to be for this assignment),
we check to see if we can mod it by i or if we can mod it by i + 2. The first
reflects checking the first number not divisible by 2 or 3 in the counting
sequence. The second check is to see if we add 2 to i, will n divide evenly
into it.
for example, in the first iteration we have i = 5. we know that n is not divisible
by 2 or 3, so we see if it is divisible by five (four is divisible by 2!). We also
check if n is divisible by i + 2 = 7 (i +1 = 6 % 3 = 0, it would have been caught).
Assuming that our proof holds, the following iterations will abide by this structure.
e.g.=> n=223 (known prime), i = i+6 = 11 (second iteration)
223 % 11 = 3
i can be prime; at this point we have determined that i is not divisible by 2 || 3,
so integers {6,8,9,10} have been checked. As for 7, it was checked in the second half
of the first iteration; recall (n % i + 2) => (223 % 5 + 2) => (223 % 7).
or
223 % 13 = 2. At this point we have checked n % {5,6,7,8,9,10,11,12,13}.
this will continue until i squared >= n, however this will probably be overkill,
since we really only need to check up until sqrt(n). This method was difficult enough
to implement and i dont think it would work well with such a limit; It also retains a
more robust proofing method in the code.
*/
if (n.mod(i) == BigInteger.ZERO || n.mod(i.add(two)) == BigInteger.ZERO) return false;
return true;
}
// Main
public static void main(String args[]) {
long start = System.nanoTime();
// sigh of simplicity
if (args.length != 1) {
System.out.println(
"usage: java primeFinder <insert integer here (up quintillions"
+ "- 19 digits) - false primes will return faster>");
return;
} else {
long l = Long.parseLong(args[0]);
BigInteger n = BigInteger.valueOf(l);
if (isPrime(n)) System.out.println("true");
else System.out.println("false");
}
long end = System.nanoTime();
System.out.println(((end - start) / 1000000) + " ms");
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T21:18:58.740",
"Id": "499334",
"Score": "2",
"body": "Hello, this question is off-topic, since we cannot make the code for you; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:24:30.810",
"Id": "499390",
"Score": "0",
"body": "I’m voting to close this question because introducing explicit multithreading is a source-level change of mechanisms used. Such if [off-topic](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T14:53:37.243",
"Id": "499430",
"Score": "0",
"body": "@JeremyHunt While you edit is an improvement it is not enough of an improvement to reopen the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T08:13:19.610",
"Id": "499725",
"Score": "0",
"body": "(via \"\\[[tag:primes]\\] thread\": [A fast parallel Sieve of Eratosthenes](https://codereview.stackexchange.com/q/104736) [Parallel sieve of Eratosthenes](https://codereview.stackexchange.com/q/47067))"
}
] |
[
{
"body": "<blockquote>\n<p>I am really new to threads and I can't see where it would be most useful, but it is required.</p>\n</blockquote>\n<p>Why is multithreading required? You may not get the performance boost you're looking for just by implementing multiple threads. Or do you just mean that you require better performance than you're getting? (Why?) I'll address both.</p>\n<h2>BigInteger</h2>\n<p>Your <code>main</code> function limits the input to the range of <code>long</code> but your implementation then uses <code>BigInteger</code> anyway. Either preserve the input <code>BigInteger</code> made from the <code>string</code> input, or otherwise you should be able to work only with <code>long</code>.</p>\n<p>When I tried changing <code>isPrime</code> to take a <code>long</code>, it was much, much <em>slower</em> actually...! But then after I swapped <code>i^2 <= n</code> for <code>i <= Math.sqrt(n)</code> to prevent <code>i^2</code> from overflowing the size of a <code>long</code>, then it was about 8 times <em>faster</em> than the <code>BigInteger</code> version.</p>\n<h2>Single thread performance</h2>\n<p>The only part of the program that takes any time at all is the <code>for</code> loop. Since <code>i</code> is always increasing, there's no opportunity to cache prior calculations within the loop.</p>\n<p>The intermediate values aren't useful to other calculations on different inputs because the entire loop has to be run for a different <code>n</code>.</p>\n<p>If it is likely that the function will be called with the same input repeatedly, you might benefit from caching the output of the function in a lookup table such as a <code>HashMap</code>.</p>\n<h2>Multithreaded performance</h2>\n<p>Multithreading on a single core will only increase performance if the core is not fully utilized. For instance, it might be waiting on network, and multithreading means it can swap to a new job while waiting. But this program is fully utilizing a single core as there is no need to wait for anything.</p>\n<p>Adding threads will allow you to take advantage of multiple cores, which doesn't happen with a single thread, but you'll need to be very careful with your implementation.</p>\n<p>If we knew how many times the <code>for</code> loop has to run, we could just divide up the work between as many threads as we have cores, and start each thread with a different starting value and upper bound of <code>i</code>.</p>\n<p>But we can't know that, and in fact most of the time the function will return early, so how about a system where a thread reserves a fixed amount of work, comes back with an answer, then requests more work until all the work is done or a <code>false</code> was found. The problem is that starting up a <code>Thread</code> can take a long time, so you'd want to make sure that each thread is started with enough work to keep it busy for a while. You'd also want to keep the threads alive between batches instead of destroying them, so using something like <code>Executors.newFixedThreadPool</code>.</p>\n<p>So then ask are you going to set up a thread pool every single time you call the function? If you're going to call it more than a few times, you might want to start the thread pool and be ready for calls to the function.</p>\n<h2>Formatting</h2>\n<p>Class names should begin with a capital letter.</p>\n<p>Sometimes comments do belong just to specific lines, but huge blocks of comments can make it harder to see what's going on. Sometimes it's best just to explain how the algorithm works in one go, and then let the code speak for itself.</p>\n<pre><code>class PrimeFinder {\n\n /*\n * A known proof exists for prime numbers not withstanding the values 2 and 3,\n * such that all prime numbers are of the form (6k)+-1.\n * \n * For example: {(5 = 6(1)-1),(13 = 6(2)+1),(1 = 6(0)+1),(5081 =\n * 6(847)-1)...(anyPrimeNumberNot2or3 = (6k)+-1)}\n * \n * \n * we omit one because isnt prime because it has less than 2 divisors, and we\n * also omit negatives\n * \n * 2 and 3 are both prime so we return true for each\n * \n * starting at 5, check for divisibility based on our proof. incrementing i by 6\n * each time gives us a chance to check when the index is a value of 6k.\n * \n * it begins by squaring 5 to compare with 25. If n is less than 25 and it is\n * divisible by 2 or three, it will have been caught by this point in the last\n * check. We use this squaring iteratively because it concludes primality at a\n * much faster rate by checking realatively large ranges of numbers instead of\n * one integer at a time.\n * \n * e.g. n = 18 or 15\n * \n * N will have been thrown already because numbers that small can only be\n * divisible by a few integers that are all divisible by two or three. ,\n * \n * however, if n = 19, than it will be found to be prime and the program will\n * return true after failing the second argument of the for loop...\n * \n * e.g. (25 !<= 19)\n * \n * otherwise, if the number is larger than 25 (needs to be for this assignment),\n * we check to see if we can mod it by i or if we can mod it by i + 2. The first\n * reflects checking the first number not divisible by 2 or 3 in the counting\n * sequence. The second check is to see if we add 2 to i, will n divide evenly\n * into it.\n * \n * for example, in the first iteration we have i = 5. we know that n is not\n * divisible by 2 or 3, so we see if it is divisible by five (four is divisible\n * by 2!). We also check if n is divisible by i + 2 = 7 (i +1 = 6 % 3 = 0, it\n * would have been caught).\n * \n * Assuming that our proof holds, the following iterations will abide by this\n * structure.\n * \n * e.g.=> n=223 (known prime), i = i+6 = 11 (second iteration)\n * \n * 223 % 11 = 3 i can be prime; at this point we have determined that i is not\n * divisible by 2 || 3, so integers {6,8,9,10} have been checked. As for 7, it\n * was checked in the second half of the first iteration; recall (n % i + 2) =>\n * (223 % 5 + 2) => (223 % 7).\n *\n * or\n * \n * 223 % 13 = 2. At this point we have checked n % {5,6,7,8,9,10,11,12,13}. this\n * will continue until i squared >= n, however this will probably be overkill,\n * since we really only need to check up until sqrt(n). This method was\n * difficult enough to implement and i dont think it would work well with such a\n * limit; It also retains a more robust proofing method in the code.\n */\n static boolean isPrime(final long n) {\n if (n <= 1) {\n return false;\n }\n if (n <= 3) {\n return true;\n }\n if (n % 2 == 0 || n % 3 == 0) {\n return false;\n }\n for (long i = 5; i <= Math.sqrt(n); i += 6) {\n if (n % i == 0 || n % (i + 2) == 0) {\n return false;\n }\n }\n return true;\n }\n\n public static void main(String args[]) {\n if (args.length != 1) {\n System.out.println("usage: java primeFinder"\n + "<insert integer here (up quintillions - 19 digits)"\n + " - false primes will return faster>");\n return;\n }\n long start = System.nanoTime();\n System.out.println(isPrime(Long.valueOf(args[0])));\n long end = System.nanoTime();\n System.out.printf("%d ms", ((end - start) / 1000000));\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:38:13.067",
"Id": "253254",
"ParentId": "253227",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T18:19:55.173",
"Id": "253227",
"Score": "-1",
"Tags": [
"java",
"multithreading"
],
"Title": "Determine whether number is prime"
}
|
253227
|
<p>I implemented a Stack in C++ using a dynamic C-style array. I tried sticking to the most important functions a Stack has to have to be usable. This is meant to only be for integers. I appreciate any suggestions on how to improve this. Here is my code:</p>
<p><em>Stack.h</em></p>
<pre><code>#ifndef STACK_H
#define STACK_H
#include <cstdint>
#include <algorithm>
class Stack
{
public:
Stack(int32_t u_size = 10) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ u_size }{ // constructor
m_stack_arr = new int32_t[u_size];
};
~Stack() { // destructor
delete[] m_stack_arr;
};
Stack(const Stack& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ 0 }{ // copy constructor
for (int32_t i = 0; i < other.size(); i++)
{
push(other.m_stack_arr[i]);
}
}
Stack(Stack&& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ 0 }{ // move constructor
m_stack_arr = std::exchange(other.m_stack_arr, nullptr);
}
Stack& operator=(const Stack& other) { // copy assignment operator
if (this != &other)
{
clear();
for (int32_t i = 0; i < other.size(); i++)
{
push(other.m_stack_arr[i]);
}
}
return *this;
}
Stack& operator=(Stack&& other) { // move assignment operator
if (this != &other)
{
m_stack_arr = std::exchange(other.m_stack_arr, nullptr);
m_size = other.m_size;
m_capacity = other.m_capacity;
m_current_ind = other.m_current_ind;
}
return *this;
}
void clear(int32_t new_capacity = 10); // clear stack and initialise new empty array
bool is_empty() const; // check if stack is empty
int32_t pop(); // delete value on top and return it
int32_t peek() const; // return value on top of the stack
void push(int32_t u_value); // add value to stack
int32_t size() const; // return size
private:
void extend(); // double capacity
int32_t m_current_ind;
int32_t m_size;
int32_t m_capacity;
int32_t* m_stack_arr;
};
#endif
</code></pre>
<p><em>Stack.cpp</em></p>
<pre><code>#include "Stack.h"
#include <stdexcept>
void Stack::clear(int32_t new_capacity)
{
delete[] m_stack_arr;
m_stack_arr = new int32_t[new_capacity];
m_capacity = new_capacity;
m_current_ind = -1;
m_size = 0;
}
bool Stack::is_empty() const
{
return !m_size;
}
int32_t Stack::pop()
{
if (!is_empty())
{
m_size--;
return m_stack_arr[m_current_ind--];
}
throw std::out_of_range("Stack is already empty.");
}
int32_t Stack::peek() const
{
if (!is_empty())
{
return m_stack_arr[m_current_ind];
}
throw std::out_of_range("Stack is empty.");
}
void Stack::push(int32_t u_value)
{
m_size++;
m_current_ind++;
if (m_size > m_capacity)
{
extend();
}
m_stack_arr[m_current_ind] = u_value;
}
int32_t Stack::size() const
{
return m_size;
}
void Stack::extend()
{
int32_t* temp = new int32_t[m_capacity * 2];
m_capacity *= 2;
std::copy(m_stack_arr, m_stack_arr + m_size, temp);
delete[] m_stack_arr;
m_stack_arr = temp;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T01:49:22.507",
"Id": "499352",
"Score": "0",
"body": "The copy constructor is broken, because the first push will call extend, doubling the capacity. But since the capacity was set to 0 you don't get any usable storage space."
}
] |
[
{
"body": "<h2>Prefer std::vector to dynamic allocation</h2>\n<p>I understand this project was meant for practice, I have done a similar project, who wouldn't want to mess around with memory allocation, but doing so leads to errors when the programmer is not careful or chooses to ignore certain things. Using <code>std::vector</code> gives you the following for free</p>\n<ol>\n<li>Copy constructor</li>\n<li>Copy assignment</li>\n<li>Move constructor</li>\n<li>Move assignment</li>\n</ol>\n<p>This enables you to focus more on the business logic of the problem.</p>\n<h2><code>Stack</code> class does not cater for default constructed objects</h2>\n<p>Right now, your class assumes that users do not have default constructible objects. This is okay because you are holding <code>Integral</code> values, but you might change it in the future. The following</p>\n<pre><code>int *p = new int{}\n</code></pre>\n<p>allocates and construct an <code>int</code> in memory, this is okay for <code>int</code> because it has a default constructor. Your class might hold objects that are very expensive to construct and as such, users might need to just have a stack that can hold their default constructible objects and construct them when they are needed. This give rise to <code>placement new</code>, see more about <code>placement new</code> <a href=\"https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new\">here</a></p>\n<h1>CODE REVIEW</h1>\n<ol>\n<li>In Stack constructor, you declared the following</li>\n</ol>\n<pre><code>Stack(int32_t u_size = 10)\n</code></pre>\n<p>This is okay, you want a default <code>stack</code> to have 10 elements, A better approach is to declare a <code>default stack</code> to hold 0 elements, this is the behavior of <code>std::vector</code>. The <code>stack</code> can grow when necessary. If the user wants to explicitly request for space, declare a <code>reserve</code> method that allocates space. You might also consider a <code>shrink_to_fit</code> method, well am going overboard for a simple <code>stack</code> class.</p>\n<ol start=\"2\">\n<li>You forgot to allocate memory in your copy constructor. This is dangerous, you are reading into memory that was never allocated. The result is undefined, it might work today and crash tomorrow. A correct approach is this</li>\n</ol>\n<pre><code> Stack(const Stack& other) : m_current_ind{ -1 }, m_size{ 0 }, m_capacity{ other.m_capacity } { // copy constructor\n m_stack_arr = new int32_t[other.m_size];\n for (int32_t i = 0; i < other.size(); i++)\n {\n push(other.m_stack_arr[i]);\n }\n}\n</code></pre>\n<p>Now this is better, we explicitly created <code>m_stack_arr</code>.</p>\n<ol start=\"3\">\n<li>Move constructor does not work. On testing your move constructor, I resulted to a <code>segmentation fault.</code> <code>m_size</code> was not given the appropriate size, the same case with <code>m_capacity</code>. using a <code>swap</code> method, your move constructor can be defined as follow</li>\n</ol>\n<pre><code>void swap(Stack& lhs, Stack& rhs)\n{\n using std::swap;\n swap(lhs.m_current_ind, rhs.m_current_ind);\n swap(lhs.m_size, rhs.m_size);\n swap(lhs.m_capacity, rhs.m_capacity);\n swap(lhs.m_stack_arr, rhs.m_stack_arr);\n}\n\n</code></pre>\n<p>This method just swap the internal representation of objects. Using this method, move constructor and move assignment becomes easy</p>\n<pre><code>Stack(Stack&& other) noexcept { // move constructor\n swap(*this, other);\n other.m_stack_arr = nullptr;\n}\n</code></pre>\n<p>We set the value of <code>other.m_stack_arr</code> to a <code>nullptr</code> to make it a cheap resource for the compiler to destroy.</p>\n<p>Move assigment is also similar, a self move is not bad and no need for a check here.</p>\n<pre><code>Stack& operator=(Stack&& other) noexcept { \n swap(*this, other);\n other.m_current_ind = -1;\n other.m_size = 0;\n other.m_stack_arr = nullptr;\n return *this;\n}\n</code></pre>\n<p>Both methods are marked <code>noexcept</code> because we are guaranteed that <code>move assignment</code> and <code>move constructor</code> would not throw an exception, this gives room for compiler to optimize some certain things.</p>\n<ol start=\"4\">\n<li>In <code>clear</code> method, you delete <code>m_stack_arr</code> before allocating a new one, what if <code>new</code> throws an exception, you have lost <code>m_stack_arr. </code></li>\n</ol>\n<pre><code>void Stack::clear(int32_t new_capacity)\n{\n int32_t* temp_arr; = new int32_t[new_capacity];\n delete[] m_stack_arr;\n std::copy(m_stack_arr, m_stack_arr + m_size, temp_arr);\n \n //.. Your code goes in here\n}\n</code></pre>\n<p>Here we created our memory and store it <code>temp_arr</code>, if that doesn't throw, we delete our old array and copy the new one.\nA more optimized version would be to use <code>memcpy</code> to copy the bytes from memory, but that is a different topic entirely.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T13:48:47.720",
"Id": "253265",
"ParentId": "253230",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253265",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T19:10:11.107",
"Id": "253230",
"Score": "2",
"Tags": [
"c++",
"reinventing-the-wheel",
"stack"
],
"Title": "C++ implementation of a Stack with dynamic C-style array"
}
|
253230
|
<p><strong>About</strong></p>
<p>This is a follow-up of a previous question <a href="https://codereview.stackexchange.com/questions/250578/private-vba-class-initializer-called-from-factory">Private VBA Class Initializer called from Factory</a>. I've decided to create a new question instead of answering my old question because I would like the community to review and possibly suggest improvements on the new improved code.</p>
<p>VBA Class methods are always called with an instance pointer but the implementation is hidden and managed by VBA. If we can manipulate that specific instance pointer then we can access methods from instance B of a class directly from instance A (of the same class type) even if those methods are declared as Private. The previous question does exactly that but in a crude, slow and unsafe way. This question will cover a better approach (in my humble view).</p>
<p>For example, a method of a class might look like this in VBA:</p>
<pre><code>Public Sub Test(ByVal arg1)
</code></pre>
<p>but the method is actually implemented more like this:</p>
<pre><code>Public Sub Test(this As LongPtr, ByVal arg1)
</code></pre>
<p>The code presented in this question replaces the <code>this</code> pointer with another instance pointer (directly in memory) and thus allows inter-instance calls.</p>
<p><strong>The <code>Me</code> keyword</strong></p>
<p>Before we continue, let's clarify what the <code>Me</code> keyword is. <code>Me</code> behaves as a locally-scoped variable to any class method but in reality it is implemented as a hidden <code>Property Get</code> that is reading the above mentioned <code>this</code> pointer (which is locally scoped because it was passed as an argument to the class method). This is easy to check:</p>
<p>Code inside a <code>SomeClass</code> class:</p>
<pre><code>Option Explicit
Public Sub Test()
Dim ptr1 As LongPtr
Dim ptr2 As LongPtr
Dim ptr3 As LongPtr
Dim tempPtr As LongPtr
ptr1 = LibMemory.MemLongPtr(VarPtr(Me)) 'Me is still within scope while memory is read
ptr2 = LibMemory.MemLongPtr(VarPtr(Me)) 'Me is still within scope while memory is read
Debug.Assert ptr1 = ptr2 'Same address so code does not stop
tempPtr = VarPtr(Me) 'Me gets out of scope after assignment
ptr3 = LibMemory.MemLongPtr(tempPtr) 'Me is not is scope anymore
Debug.Assert ptr1 = ptr3 'ptr3 is 0
End Sub
</code></pre>
<p>Code in a standard module:</p>
<pre><code>Sub TestME()
Dim c As New SomeClass
c.Test
End Sub
</code></pre>
<p>By running the <code>TestME</code> method, the second <code>Assert</code> within the class instance will fail because <code>Me</code> got out of scope. This suggests that <code>Me</code> is actually a <code>Property Get</code> or a <code>Function</code> rather than a locally-scoped variable. Hence, we cannot use <code>Me</code> to get to <code>this</code>.</p>
<p>Notice that I am not using the well-known <code>CopyMemory</code> API. Instead I am using a <code>LibMemory</code> library that I have created specifically for this question. <code>LibMemory</code> can be found at <a href="https://codereview.stackexchange.com/questions/252659/fast-native-memory-manipulation-in-vba">CodeReview</a> and <a href="https://github.com/cristianbuse/VBA-MemoryTools" rel="nofollow noreferrer">GitHub</a>. The CR question explains the reasoning behind the library.</p>
<p><strong>The Code</strong></p>
<p>First of all, we need the above-mentioned <code>LibMemory</code></p>
<p>We also need a class that encapsulates all the logic for redirecting class instances.<br />
Code inside <code>InstanceRedirector</code> class:</p>
<pre><code>Option Explicit
Private Type INSTANCE_REDIRECT
#If VBA7 Then
swapAddress As LongPtr
originalPtr As LongPtr
#Else
swapAddress As Long
originalPtr As Long
#End If
targetInstance As Object 'Keep a reference until restore is called
End Type
Private this As INSTANCE_REDIRECT
'*******************************************************************************
'Redirects the instance of a class to another instance of the same class
'This method must be called from a class instance's Function (not Sub)
'
'Warning! RestoreInstance must be called before the calling function goes out
' of scope OR this instance must be terminated so that RestoreInstance is
' called at Class_Terminate
'
'Warning! vbArray + vbString Function return type is not supported. It would be
' possible to find the correct address by reading memory in a loop but there
' would be no checking available
'*******************************************************************************
#If VBA7 Then
Public Sub Redirect(ByVal funcReturnPtr As LongPtr, ByVal currentInstance As Object, ByVal targetInstance As Object)
#Else
Public Sub Redirect(ByVal funcReturnPtr As Long, ByVal currentInstance As Object, ByVal targetInstance As Object)
#End If
Const methodName As String = "Redirect"
'
'Validate Input
If currentInstance Is Nothing Or targetInstance Is Nothing Then
Err.Raise 91, TypeName(Me) & "." & methodName, "Object not set"
ElseIf TypeName(currentInstance) <> TypeName(targetInstance) Then
Err.Raise 5, TypeName(Me) & "." & methodName, "Expected same interface"
ElseIf funcReturnPtr = 0 Then
Err.Raise 5, TypeName(Me) & "." & methodName, "Missing Func Return Ptr"
End If
'
'Store original pointer
this.originalPtr = ObjPtr(GetDefaultInterface(currentInstance))
'
'On x64 the shadow stack space is allocated next to the Function Return
'On x32 the stack space has a fixed offset (found through testing)
#If Win64 Then
Const memOffsetNonVariant As LongLong = LibMemory.PTR_SIZE
Const memOffsetVariant As LongLong = LibMemory.PTR_SIZE * 3
#Else
Const memOffsetNonVariant As Long = LibMemory.PTR_SIZE * 28
Const memOffsetVariant As Long = LibMemory.PTR_SIZE * 31
#End If
'
'Try Non-Variant func return first and then Variant if the former fails
If Not SetSwapAddress(funcReturnPtr, memOffsetNonVariant) Then
SetSwapAddress funcReturnPtr, memOffsetVariant
End If
'
If this.swapAddress = 0 Then
Err.Raise 5, TypeName(Me) & "." & methodName, "Invalid input or " _
& "not called from class function or vbArray + vbString func return type"
End If
'
'Keep a reference until restore is called, for extra safety
Set this.targetInstance = GetDefaultInterface(targetInstance)
'
'Redirect Instance
LibMemory.MemLongPtr(this.swapAddress) = ObjPtr(this.targetInstance)
End Sub
'*******************************************************************************
'Finds and sets the swap address (address of the instance pointer on the stack)
'*******************************************************************************
#If VBA7 Then
Private Function SetSwapAddress(ByRef funcReturnPtr As LongPtr, ByRef memOffset As LongPtr) As Boolean
#Else
Private Function SetSwapAddress(ByRef funcReturnPtr As Long, ByRef memOffset As Long) As Boolean
#End If
#If VBA7 Then
Dim tempPtr As LongPtr
#Else
Dim tempPtr As Long
#End If
'
tempPtr = LibMemory.UnsignedAddition(funcReturnPtr, memOffset)
#If Win64 Then
#Else
tempPtr = UnsignedAddition(MemLongPtr(tempPtr), PTR_SIZE * 2)
#End If
If LibMemory.MemLongPtr(tempPtr) = this.originalPtr Then
this.swapAddress = tempPtr
SetSwapAddress = True
End If
End Function
'*******************************************************************************
'Returns the default interface for an object
'Casting from IUnknown to IDispatch (Object) forces a call to QueryInterface for
' the IDispatch interface (which knows about the default interface)
'*******************************************************************************
Private Function GetDefaultInterface(obj As IUnknown) As Object
Set GetDefaultInterface = obj
End Function
'*******************************************************************************
'Restores the original instance pointer at the previously used swap address
'*******************************************************************************
Public Sub Restore()
If this.swapAddress = 0 Or this.originalPtr = 0 Then Exit Sub
LibMemory.MemLongPtr(this.swapAddress) = this.originalPtr
this.swapAddress = 0
this.originalPtr = 0
Set this.targetInstance = Nothing
End Sub
'*******************************************************************************
'Extra safety in case .Restore is not called
'*******************************************************************************
Private Sub Class_Terminate()
Restore
End Sub
</code></pre>
<p>Notice that this code has a lot of checks in place compared to the previous CR question which was only reading memory in a loop until a specific value was found. Moreover, the exact location is found using predefined memory offsets.</p>
<p><strong>Demo</strong></p>
<p>Consider a <code>Class1</code> which has <code>VB_PredeclaredId</code> set to True:</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'@PredeclaredId
Option Explicit
Private m_id As Long
Public Function Factory(ByVal newID As Long) As Class1
Dim c As New Class1
'
With New InstanceRedirector
.Redirect VarPtr(Factory), Me, c
Init newID
.Restore 'This can be ommited within a With New block (Class_Terminate calls it anyway)
End With
Set Factory = c
End Function
Private Sub Init(newID As Long)
m_id = newID
End Sub
Public Function Factory2(ByVal newID As Long) As Class1
Dim c As New Class1
'
c.Init2 newID
Set Factory2 = c
End Function
Public Sub Init2(newID As Long)
m_id = newID
End Sub
Public Property Get ID() As Long
ID = m_id
End Property
</code></pre>
<p>The <code>Factory</code> method uses a private <code>Init</code> method while the <code>Factory2</code> uses a public <code>Init2</code> method.</p>
<p>Quick speed test in a standard module:</p>
<pre><code>Option Explicit
Sub TestFactorySpeeds()
Const loopsCount As Long = 100000
Dim i As Long
Dim t As Double
'
t = Timer
For i = 1 To loopsCount
Debug.Assert Class1.Factory2(i).ID = i
Next i
Debug.Print "Public Init (seconds): " & VBA.Round(Timer - t, 3)
'
t = Timer
For i = 1 To loopsCount
Debug.Assert Class1.Factory(i).ID = i
Next i
Debug.Print "Private Init (seconds): " & VBA.Round(Timer - t, 3)
End Sub
</code></pre>
<p>In general the Private method seems to be only 3x slower but the benefit of accessing private methods seems to be worth the speed loss.</p>
<p><strong>Notes</strong></p>
<p>Obviously, the demo above shows how to create a Factory that is using a Private Init but the approach presented here allows any class instance (Predeclared or not) to access private methods within other instances of the same class type. A good idea provided by @TinMan in the previous question is to create a class <code>Clone</code> method.</p>
<p>The return value of the class function where the redirection is used does not necessarily need to be an Object. It can be any data type (except an Array of String i.e. vbArray + vbString VarType). For return types of Array type, the <code>VarPtrArray</code> function from the <code>LibMemory</code> library can be used for the first argument when calling InstanceRedirector.Redirect.</p>
<p>The class method where the redirection is used/called needs to be a <code>Function</code> and not a <code>Sub</code> because the function return will be allocated on the call stack and we can use it's address to find the actual memory location of the class instance pointer.</p>
<p>On x64 the instance pointer is allocated on the call stack immediately after the function return while on x32 there is a fixed offset and a redirection. If the function return type is of type Variant then the offsets are increased by two ptr positions on x64 (i.e. + 16 bytes) and three ptr positions on x32 (i.e. + 12 bytes).</p>
<p><strong>Question(s)</strong></p>
<p>I would be very grateful for suggestions that could improve the code in any way (speed, readability, structure, naming etc.).</p>
<hr />
<p><strong>EDIT #1</strong></p>
<p>If an unexpected error occurs while the <code>Init</code> method is running then the whole application will crash because <code>.Restore</code> gets called too late.</p>
<p>Obviously, this code (see demo <code>Class1</code> in the original question):</p>
<pre><code>With New InstanceRedirector
.Redirect VarPtr(Factory), Me, c
Init newID
.Restore
End With
</code></pre>
<p>can be replaced with something like:</p>
<pre><code>With New InstanceRedirector
.Redirect VarPtr(Factory), Me, c
On Error Resume Next
Init newID
.Restore
If Err.Number <> 0 Then
'Do whatever
End If
On Error GoTo 0
End With
</code></pre>
<p>but we now have boilerplate code that we would need to remember to copy everytime we want to use the redirection capability within a class.</p>
<p>However, the instance pointer does not need to be restored if we don't use the redirection inside the first method called on a class (e.g. the public <code>Factory</code> method in the example).</p>
<p>If we use the redirection inside any class method that is called from another method of the same class then it's safe to skip restoring the instance pointer. No error handling is required to prevent any crashes. Moreover, there is no need to have a separate class for the redirection. A simple method inside a .bas module will suffice.</p>
<p>The best place to make the redirection is in the private method that will need the redirection. Makes perfect sense - it will always be called from another method of the same class. The code in the original example could leave the reader wondering what is happenin in the private <code>Init</code> method but doing the redirection within the <code>Init</code> is much more readable anyway.</p>
<p>The code in the original question had some alignment issues on x32 when the return value of the function was less/more than 4 bytes in size. If we fix that then consider this minimal code for redirection (in a standard .bas module):</p>
<pre><code>Option Explicit
Option Private Module
'*******************************************************************************
'Redirects the instance of a class to another instance of the same class within
' the scope of a class Function (not Sub) where the call happens.
'
'Warning! ONLY call this method from a Private Function of a class!
'
'vbArray + vbString Function return type is not supported. It would be
' possible to find the correct address by reading memory in a loop but there
' would be no checking available
'*******************************************************************************
#If Win64 Then
Public Sub RedirectInstance(ByVal funcReturnPtr As LongLong _
, ByVal currentInstance As Object _
, ByVal targetInstance As Object)
#Else
Public Sub RedirectInstance(ByVal funcReturnPtr As Long _
, ByVal currentInstance As Object _
, ByVal targetInstance As Object)
#End If
Const methodName As String = "RedirectInstance"
#If Win64 Then
Dim originalPtr As LongLong
Dim newPtr As LongLong
Dim swapAddress As LongLong
#Else
Dim originalPtr As Long
Dim newPtr As Long
Dim swapAddress As Long
#End If
'
originalPtr = ObjPtr(GetDefaultInterface(currentInstance))
newPtr = ObjPtr(GetDefaultInterface(targetInstance))
'
'Validate Input
If currentInstance Is Nothing Or targetInstance Is Nothing Then
Err.Raise 91, methodName, "Object not set"
ElseIf MemLongPtr(originalPtr) <> MemLongPtr(newPtr) Then 'Faster to compare vTables than to compare TypeName(s)
Err.Raise 5, methodName, "Expected same VB class"
ElseIf funcReturnPtr = 0 Then
Err.Raise 5, methodName, "Missing Function Return Pointer"
End If
'
'On x64 the shadow stack space is allocated next to the Function Return
'On x32 the stack space has a fixed offset (found through testing)
#If Win64 Then
Const memOffsetNonVariant As LongLong = PTR_SIZE
Const memOffsetVariant As LongLong = PTR_SIZE * 3
#Else
Const memOffsetNonVariant As Long = PTR_SIZE * 28
Const memOffsetVariant As Long = PTR_SIZE * 31
#End If
'
swapAddress = FindSwapAddress(funcReturnPtr, memOffsetNonVariant, originalPtr)
If swapAddress = 0 Then
swapAddress = FindSwapAddress(funcReturnPtr, memOffsetVariant, originalPtr)
If swapAddress = 0 Then
Err.Raise 5, methodName, "Invalid input or not called " _
& "from class Function or vbArray + vbString function return type"
End If
End If
'
'Redirect Instance
MemLongPtr(swapAddress) = newPtr
End Sub
'*******************************************************************************
'Finds the swap address (address of the instance pointer on the stack)
'*******************************************************************************
#If Win64 Then
Private Function FindSwapAddress(ByVal funcReturnPtr As LongLong _
, ByVal memOffset As LongLong _
, ByVal originalPtr As LongLong) As LongLong
Dim swapAddr As LongLong: swapAddr = funcReturnPtr + memOffset
If MemLongLong(swapAddr) = originalPtr Then
FindSwapAddress = swapAddr
End If
End Function
#Else
Private Function FindSwapAddress(ByVal funcReturnPtr As Long _
, ByVal memOffset As Long _
, ByVal originalPtr As Long) As Long
Dim startAddr As Long: startAddr = funcReturnPtr + memOffset
Dim swapAddr As Long
'
'Adjust memory alignment for Boolean/Byte/Integer function return type
startAddr = startAddr - (startAddr Mod PTR_SIZE)
'
swapAddr = GetSwapIndirectAddress(startAddr)
If swapAddr = 0 Then
'Adjust mem alignment for Currency/Date/Double function return type
swapAddr = GetSwapIndirectAddress(startAddr + PTR_SIZE)
If swapAddr = 0 Then Exit Function
End If
If MemLongPtr(swapAddr) = originalPtr Then
FindSwapAddress = swapAddr
End If
End Function
Private Function GetSwapIndirectAddress(ByVal startAddr As Long) As Long
Const maxOffset As Long = PTR_SIZE * 100
Dim swapAddr As Long: swapAddr = MemLong(startAddr) + PTR_SIZE * 2
'
'Check if the address is within acceptable limits. The address
' of the instance pointer (within the stack frame) cannot be too far
' from the function return address (first offsetted to startAddr)
If startAddr < swapAddr And swapAddr - startAddr < maxOffset * PTR_SIZE Then
GetSwapIndirectAddress = swapAddr
End If
End Function
#End If
'*******************************************************************************
'Returns the default interface for an object
'Casting from IUnknown to IDispatch (Object) forces a call to QueryInterface for
' the IDispatch interface (which knows about the default interface)
'*******************************************************************************
Private Function GetDefaultInterface(ByVal obj As IUnknown) As Object
Set GetDefaultInterface = obj
End Function
</code></pre>
<p>The code will work even if an error is raised within the <code>Init</code> method. Will work means that only runtime error will be raised but no crash will occur.</p>
<p>The <code>DemoClass</code> would look like this:</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'@PredeclaredId
Option Explicit
Private m_id As Long
Public Function Factory(ByVal newID As Long) As DemoClass
Dim c As New DemoClass
Init c, newID
Set Factory = c
End Function
Private Function Init(ByVal c As DemoClass, ByVal newID As Long) As Boolean
RedirectInstance VarPtr(Init), Me, c
m_id = newID
End Function
Public Function Factory2(ByVal newID As Long) As Class1
Dim c As New Class1
'
c.Init2 newID
Set Factory2 = c
End Function
Public Sub Init2(newID As Long)
m_id = newID
End Sub
Public Property Get ID() As Long
ID = m_id
End Property
</code></pre>
<p>Since the <code>RedirectInstance</code> method is using <a href="https://github.com/cristianbuse/VBA-MemoryTools" rel="nofollow noreferrer">LibMemory</a> then it makes sense to have it within the same memory module. Repository will be updated soon.</p>
<p>Finally, removing the need for restoring the instance pointer and the instantiation of a new class makes this faster. A private init is now only 1.75x slower than the public counterpart as opposed to 3x slower with the class/restore approach.</p>
<p>I guess the only risk here is that the redirection can be called from a method that is not private. I don't think it's possible to force the user to use a private method. I also don't think there is an easy way to check if the calling method is private. So, the only warning is the comment above the method definition.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T20:35:28.507",
"Id": "253233",
"Score": "8",
"Tags": [
"vba",
"classes",
"factory-method"
],
"Title": "Private VBA Class Initializer called from Factory #2"
}
|
253233
|
<p>As a beginner this is my first code. Any comments?</p>
<pre><code>import numpy as np
import math
import matplotlib.pylab as plt
x=np.linspace(-360,360,45)*np.pi/180
plt.subplot(111)
_sin=plt.plot(x, np.sin(x),label="Sine Curve")
_cos=plt.plot(x,np.cos(x),label="Cos Curve")
#_tan=plt.plot(x,np.tan(x),label="Tan Curve")
plt.legend(['sin','cos','tan'])
plt.show()#This line might be required on some python implementations.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:50:36.980",
"Id": "499384",
"Score": "4",
"body": "(To split an excessively fine hair, not specifying in any way what the code is to accomplish (beyond naming a theme) makes it correspondingly hard to tell whether the code works as intended.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T21:12:31.373",
"Id": "499457",
"Score": "0",
"body": "@greybeard Considering the title, I think it's supposed to plot (co)sine waves."
}
] |
[
{
"body": "<p>First, <a href=\"https://stackoverflow.com/questions/11469336/what-is-the-difference-between-pylab-and-pyplot\">use pyplot instead of pylab.</a></p>\n<p>Secondly, check out <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, the Python style guide. stdlib imports should be at the very top, then 3rd-party imports. However, <code>math</code> isn't even used anywhere, so you can just remove the import entirely.</p>\n<p>In addition, your spacing is a bit inconsistent. Assignments should have 1 space on each side and there should be a space after the commas within a func call. I recommend using an auto-formatter to fix these stylistic issues, such as black or yapf.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T23:42:02.783",
"Id": "253238",
"ParentId": "253234",
"Score": "2"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/253238/100620\">SuperStormer's points</a> ...</p>\n<h1>Unused variables</h1>\n<p><code>_sin</code> and <code>_cos</code> are never used. You don't need to assignments to these variable.</p>\n<h1>Naming conventions</h1>\n<p>In the event you will eventually use them...</p>\n<p>Leading underscore are used to indicate private members of a class. To avoid collisions with keywords, by convention, a trailing underscore is used (i.e. <code>sin_</code> & <code>cos_</code>).</p>\n<h1>Unused arguments</h1>\n<p><code>'tan'</code> is being passed to <code>plt.legend()</code>, but there is no tangent plot.</p>\n<p>It works, but it is a bad habit to get into. Pass the desired curve titles directly to the <code>plt.plot()</code> function (i.e.<code>, label="sin"</code>), and simply call <code>plt.legend()</code> with no arguments.</p>\n<h1>Magic numbers</h1>\n<p>What is <code>111</code> and why are you passing it to <code>subplot()</code>?</p>\n<h1>Updated code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pylab as plt\n\nx = np.linspace(-360, 360, 45) * np.pi / 180\n\nplt.subplot()\nsin_ = plt.plot(x, np.sin(x), label="sin")\ncos_ = plt.plot(x, np.cos(x), label="cos")\n#tan_ = plt.plot(x, np.tan(x), label="tan")\n\nplt.legend()\n\n# plt.show() # For CPython\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T05:58:46.410",
"Id": "253246",
"ParentId": "253234",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T20:48:57.843",
"Id": "253234",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"numpy"
],
"Title": "SineCosine Wave"
}
|
253234
|
<p>So I am using the latest version of <code>Dapper</code> and it works great for mapping my POCO classes but there are some scenarios where I need to return a DataSet instead of strongly typed classes back to my service.</p>
<p>Is this correct approach for repository pattern with Unit of work using ADO.NET in C# to authenticate user from database?</p>
<p>I am following the <code>UoW</code> pattern but I am using ADO.Net, so I am not sure if that is the correct approach. I will give the relevant classes that I am using to setup my infrastructure and Unit of Work objects:</p>
<p>Infrastructure class (where I am setting up my DB connection):</p>
<pre><code>public class ConnectionFactory: IConnectionFactory
{
private readonly string epaperconnectionString = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
private MySqlConnection _myDBString;
public IDbConnection GetMyDBConnection
{
get
{
_myDBString = new MySqlConnection(epaperconnectionString);
return _myDBString;
}
}
}
</code></pre>
<p>Unit of Work class:</p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
public UnitOfWork(IMyDBRepository mydbRepository)
{
MyDBRepository = mydbRepository;
}
void IUnitOfWork.Complete()
{
throw new NotImplementedException();
}
public IMyDBRepository MyDBRepository { get; }
}
</code></pre>
<p>MyDBRepository class:</p>
<pre><code>public sealed class MyDBRepository : IMyDBRepository
{
IConnectionFactory _connectionFactory;
Helper helper = new Helper();
public MyDBRepository (IConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
public async Task<DataSet> checkForUser(string useremail, StringBuilder EncPassword)
{
string query = string.Format("SELECT id FROM USER WHERE PASSWORD=@pwd AND Email=@emailid");
DynamicParameters param = new DynamicParameters();
param.Add("@emailid", useremail.Trim());
param.Add("@pwd", EncPassword.ToString().Trim());
IDataReader list = await SqlMapper.ExecuteReaderAsync(_connectionFactory.GetMyDBConnection, query, param, commandType: CommandType.Text);
DataSet dataset = helper.ConvertDataReaderToDataSet(list);
return dataset;
}
}
</code></pre>
<p>I am assuming here that <code>SqlMapper</code> automatically takes care of the opening and disposing the SQL connection so I am not explicitly using the technique to take care of disposing of SQL connections.</p>
<p>My helper ConvertDataReaderToDataSet is:</p>
<pre><code>public DataSet ConvertDataReaderToDataSet(IDataReader data)
{
DataSet ds = new DataSet();
int i = 0;
while (!data.IsClosed)
{
ds.Tables.Add("Table" + (i + 1));
ds.EnforceConstraints = false;
ds.Tables[i].Load(data);
i++;
}
return ds;
}
</code></pre>
<p>My Service class looks like:</p>
<pre><code>public class MyService : IMyService
{
IUnitOfWork _unitOfWork;
#region CTOR
public MyService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<result> checkForUserService(string useremail, StringBuilder EncPassword)
{
var obj = await _unitOfWork.MyDBRepository.checkForUser(useremail, EncPassword);
if (obj.Tables[0].Rows.Count == 0)
{
//Incorrect username/password
result.flag=false;
}
else
{
//Do stuff
result.flag=true;
}
}
}
</code></pre>
<p>I call the above service from a MVC project (4.6.1):</p>
<pre><code>public class TestController : Controller
{
IMyService _myService;
ISubscriptionService _subscriptionService;
public TestController()
{
}
public TestController(IMyService myService)
{
_myService = myService;
}
// GET: check user test
public ActionResult checkUserTest()
{
string EmailId = "myemail@blah.com";
StringBuilder EncPassword = new StringBuilder();
//Using a standard hashing algorithm
EncPassword.Append("encodedpassword");
var resultData = _myService.checkForUserService(EmailId, EncPassword).Result;
if(resultData.flag)
{
//Set session variable here
System.Web.HttpContext.Current.Session["loggedinemail"] = resultData.EmailId;
}
string jsonDataSet = JsonConvert.SerializeObject(resultData);
return Json(jsonDataSet, JsonRequestBehavior.AllowGet);
}
}
</code></pre>
<p>I wanted any suggestions/design changes that I can do in order to use the repository pattern with Unit of Work with Dapper correctly. It is working for me at the moment but I am not sure if the implementation of the repository pattern is done correctly with Unit of work since I am using ADO.NET.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:15:36.757",
"Id": "499388",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and title your question for what the code presented is to accomplish."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:59:40.833",
"Id": "499413",
"Score": "0",
"body": "@greybeard I have updated the title to be more descriptive as required"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T11:21:35.880",
"Id": "499416",
"Score": "0",
"body": "_\"there are some scenarios where I need to return a DataSet instead of strongly typed classes\"_ Why your data set's columns not be expressed as a concrete class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T14:36:00.140",
"Id": "499428",
"Score": "0",
"body": "@RahulSharma Why do you use custom encoding algorithm against password? Why don't you use one of standard hashing algorithm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:58:53.893",
"Id": "499693",
"Score": "0",
"body": "@Flater I can do that part also but that would require a lot of rework at my end because of the original implementation done like this. We are getting the `DataSet` back from the database to perform manipulations on it in `C#` before mapping them to a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:59:35.973",
"Id": "499694",
"Score": "1",
"body": "@PeterCsala Thank you for your concern but I might have mislead the readers on that part. I am using a standard hashing algorithm for this purpose. Sorry my bad there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T11:59:45.353",
"Id": "499740",
"Score": "1",
"body": "@RahulSharma: \"it exists\" shouldn't be the main reason why you choose to take a provably inefficient approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T18:48:42.127",
"Id": "500465",
"Score": "0",
"body": "@Flater I did not get your point. Can you please elaborate here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T14:49:57.703",
"Id": "501348",
"Score": "0",
"body": "Please do not edit your question with new code now that there's an answer. Submit a new question instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T19:36:03.813",
"Id": "504998",
"Score": "0",
"body": "@Reinderien I have submitted a new question for the same: https://codereview.stackexchange.com/questions/255835/is-this-correct-way-to-setup-db-infrastructure-with-repository-pattern-and-dappe"
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>epaperconnectionString</code> doesn't follow the proper naming conventions for compound words. Also: why wouldn't you store all your configuration settings in a dedicated class? (I'm not a fan of seeing <code>ConfigurationManager</code> all over the place: if you ever need to change a setting's name you need to look in multiple places, whereas it would be a single location if you'd centralized all those settings.)</p>\n</li>\n<li><p><code>Helper</code> is too generic a class name. So is <code>MyDBRepository</code>. So is <code>resultData</code>. Don't get me started on <code>obj</code>.</p>\n</li>\n<li><p><code>list</code> isn't the correct name for an <code>IDataReader</code>.</p>\n</li>\n<li><p><code>checkForUser</code> doesn't follow the naming guidelines. Ditto <code>checkForUserService</code> (that method name is simply baffling, BTW).</p>\n</li>\n<li><p>What is <code>result</code>? Why doesn't it follow the naming conventions? Why does it have a property <code>flag</code> that also doesn't follow naming conventions?</p>\n</li>\n</ul>\n<hr />\n<p>But mostly this looks to me like a solution in search of a problem. Why work with <code>DynamicParameters</code> and <code>SqlMapper</code> and <code>IDataReader</code> etc. when you could just as easily use "proper" Dapper code, return a class or an <code>int</code> (whatever type "id" is) and then convert that to a <code>DataSet</code>?</p>\n<p>And for what? You end up with <code>var obj = await _unitOfWork.MyDBRepository.checkForUser(useremail, EncPassword);</code> and then based on <code>obj.Tables[0].Rows.Count == 0</code> you set <code>result.flag</code> to <code>true</code> or <code>false</code>. And so on. I see a massive amount of code that pointlessly uses a <code>DataSet</code> etc. for what (as far as I can deduct) a ridiculously simple piece of logic: you need the ID belonging to a provided email address.</p>\n<p>I can throw away 90% of your code (including the overkill of a unit of work and a repository) and replace it with a simple service class that contains a single method with a simple Dapper query that returns an <code>int?</code> (or whatever type that ID is). Why did you overengineer it in the way you did?</p>\n<hr />\n<p>You say:</p>\n<blockquote>\n<p>there are some scenarios where I need to return a DataSet instead of strongly typed classes</p>\n</blockquote>\n<p>Nothing in the code you provide here proves this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:53:28.347",
"Id": "499690",
"Score": "0",
"body": "Thank you for review on this. I have understood the naming convention and I will do the changes proposed by you. Can you give me an example of getting the configuration in the correct way. I encounter the `object not set to an instance of an object` error on this line in: `ConfigurationManager.ConnectionStrings[\"MyDB\"].ConnectionString;`. I am working with `DynamicParameters`, `SqlMapper` because they are integral part of `Dapper` so I need them in my code. You are right about the overengineer part but this is sample piece from a huge library of methods. I wanted a service based model."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:55:38.763",
"Id": "499691",
"Score": "0",
"body": "Basically, all the business logic goes into the Service class. The database class (repository) is only for performing CRUD operations. I could have made it into all a simple service class as you proposed but then it would have been cumbersome to put business logic there. This is a small sample from a huge codebase. All I wanted to know is if the repository pattern with unit of work is properly being followed with all resource management being done (in the repository class). Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T20:16:31.777",
"Id": "499698",
"Score": "0",
"body": "Also for `there are some scenarios where I need to return a DataSet instead of strongly typed classes`: I have some scenarios where I need to perform manipulations from the data returned back from the database before finally sending it out to the client. This can be done using a `DTO` if I were using a service based web api but since this a .NET Standard libary project, I am left with the option to get the dataset and then perform manipulation on it before mapping to the c# class. If there is a better and efficient way to do it, then I would like to know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T15:46:43.590",
"Id": "499755",
"Score": "0",
"body": "I have used Dapper countless times and the only time I have used `DynamicParameters` was in one exceptional case, and I have never used its `SqlMapper`. Those things are there for exceptional cases, and your code isn't that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T15:51:59.043",
"Id": "499756",
"Score": "0",
"body": "Nothing is stopping you from having a \"DAO\" class that still uses DTOs. So what if you need to do data manipulation post-db retrieval? Just return a \"raw\"/\"simplified\" DTO and transform that to a more complex DTO in the class with your business logic. A `DataSet` is IMHO absolutely the wrong thing to use here, not in the least because you lose so much and gain nothing. \"since this a .NET Standard library project\": why would this be relevant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T15:55:26.053",
"Id": "499757",
"Score": "0",
"body": "I have used the Unit Of Work / Repository structure one time at my current place of employment, and each time I have to make adjustments in that code I cringe and curse myself for doing it. It adds pointless overhead and it requires you to write tons of duplicate code that only gets in the way of what you need to do."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T11:32:31.817",
"Id": "253260",
"ParentId": "253235",
"Score": "4"
}
},
{
"body": "<h2>Side-effects</h2>\n<p>On its own, this:</p>\n<pre><code>private MySqlConnection _myDBString;\npublic IDbConnection GetMyDBConnection\n{\n get\n {\n _myDBString = new MySqlConnection(epaperconnectionString);\n return _myDBString;\n }\n}\n</code></pre>\n<p>is a deeply bad idea. Getters should usually be trusted to have no side-effects that mutate the class.</p>\n<p>The only exception to this I would make is if you're using <code>_myDBString</code> as a cache, which you're not. To do this you would check to see if that member has already been set, and if so, return the member without a new call to <code>MySqlConnection</code>.</p>\n<p>Even so, such caching is not the right way to go about reducing connection load; instead use an actual connection pool. For more information on this approach a reasonable starting point is the <a href=\"https://dev.mysql.com/doc/connector-net/en/connector-net-connections-pooling.html\" rel=\"nofollow noreferrer\">MySQL Connector Documentation</a>.</p>\n<p>Also <code>_myDBString</code> is the wrong name. It's <em>not</em> a connection string; it's a <em>connection</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-16T07:53:31.750",
"Id": "499944",
"Score": "0",
"body": "The ID is used: `[\"loggedinemail\"] = resultData.EmailId;`. But the code is needlessly overcomplicated, which is why it is almost impossible to figure out what it exactly does; yet in its core it is really simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-16T20:01:41.530",
"Id": "499998",
"Score": "0",
"body": "@BCdotWEB I didn't catch that; thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-17T17:37:18.250",
"Id": "500079",
"Score": "0",
"body": "@Reinderien Thank you very much for the review. Could you give me an example of how the correctly implement the above connection initialization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T15:42:44.273",
"Id": "500156",
"Score": "0",
"body": "@Reinderien Is there any example that you can direct me to handle this properly? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T16:58:55.713",
"Id": "500166",
"Score": "0",
"body": "@RahulSharma Sure; I linked to the MySQL documentation on connection pooling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-20T18:41:38.750",
"Id": "500287",
"Score": "0",
"body": "@Reinderien Thank you very much. I shall take a look into it. Other than that, is there any suggestions that you can give on the above code structure Or does the implementation look right to you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-01T17:47:26.990",
"Id": "501286",
"Score": "0",
"body": "@Reinderien I was investigation into this and apparently, connection pooling is set by default in ADO.NET: `To enable this connection pooling in asp.net we don’t need to do anything by default connection pooling is enabled in ADO.NET. Unless we manually disable the connection pooling, the pooler will optimize the connections when they are opened and closed in our application.` https://www.aspdotnet-suresh.com/2016/07/connection-pooling-in-aspnet-using-csharp-with-example.html. So my question would be here is how to handle to properly handle the connection string in this class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-01T18:29:08.673",
"Id": "501287",
"Score": "0",
"body": "In a method like your check-for-user, do not call `_connectionFactory.GetMyDBConnection` as you are. Instead, tell ADO to open a new connection, and put it in a `using` clause that restricts the scope of the connection lease to your query."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T17:36:42.627",
"Id": "253510",
"ParentId": "253235",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T21:06:24.833",
"Id": "253235",
"Score": "4",
"Tags": [
"c#",
"asp.net-mvc",
"repository",
"dapper"
],
"Title": "Repository pattern with Unit of work using ADO.NET in C# to authenticate user from database"
}
|
253235
|
<p>I'm creating an RSVP-type application which will later be implemented in a mobile application I'm making. In this mobile application the user can select different events around their area and can choose whether they want to come to the event or not.</p>
<p>Of course in the real application the user will need to get a 5 character code and input it in order to confirm whether they are going or not. They will most likely get that code in the physical invitation or as an email. From there - the organiser can have a clean view as to who is coming and who is not.</p>
<p>The user can get the details of the event - such as the date, and what time it will happen, the user can also get the detail of the event organiser - such as the contact details, email, etc.</p>
<p>This is my first go at implementing the classes. I am looking for feedback as to how I can improve the structure and clarity of the code - I also want to obey SOLID principles to ensure the code is as good as possible.</p>
<p>Here is the current code:</p>
<pre><code>namespace FunTest
{
public class Location
{
public Location(string city, string region, string streetName, int streetNumber) => (City, Region, StreetName, StreetNumber) =
(city, region, streetName, streetNumber);
public string City { get; set; }
public string Region { get; set; }
public string StreetName { get; set; }
public int StreetNumber { get; set; }
}
public static class EmailValidator
{
public static bool ValidateEmail(string email)
{
try
{
MailAddress address = new MailAddress(email);
return address.Address == email;
}
catch
{
return false;
}
}
}
public class EmailAddress
{
private string _email;
public string Email
{
get => _email;
set
{
if (EmailValidator.ValidateEmail(_email))
_email = value;
}
}
}
public class EventOrganizer
{
public EventOrganizer(string firstName, string lastName, int phoneNumber) => (FirstName, LastName, PhoneNumber) =
(firstName, lastName, phoneNumber);
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => FirstName + LastName;
public int PhoneNumber { get; set; }
public EmailAddress EmailAddress { get; set; }
}
public class RSVPEvent
{
public string EventName { get; set; }
public string EventDescription { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public DateTime Date { get; set; }
public Location EventLocation { get; set; }
public EventOrganizer EventOrganizer { get; set; }
public IList<string> Attendees { get; set; }
public IList<string> Absentees { get; set; }
}
class Program
{
static void Main(string[] args)
{
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:51:36.273",
"Id": "499406",
"Score": "0",
"body": "StreetName and StreetNumber are way to limiting. https://www.mjt.me.uk/posts/falsehoods-programmers-believe-about-addresses/ or https://github.com/kdeldycke/awesome-falsehood#postal-addresses or https://github.com/kdeldycke/awesome-falsehood#geography etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:54:13.333",
"Id": "499410",
"Score": "0",
"body": "Why is StartTime a TimeSpan? How does `MailAddress address = new MailAddress(email);` validate anything? (Also, the only way to validate an email address is to send an email to it containing an action the user has to do (e.g. click a link)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:55:15.750",
"Id": "499411",
"Score": "1",
"body": "`FullName => FirstName + LastName;` is just wrong. It is not true for all cultures, but more importantly usually there is a space between the two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T19:35:45.543",
"Id": "499448",
"Score": "0",
"body": "@BCdotWEB by validation I was meaning to validate that the email is in the correct format but thanks for the comments"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T23:19:25.317",
"Id": "253236",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "Implementing an RSVP Event App in C#"
}
|
253236
|
<p>I have a button component on react native, depending on the "theme" prop I need to render a different style for the button</p>
<pre><code>const OvalButton = ({ title, onPress, theme, style }) => {
switch(theme){
case GRAY_BUTTON:
return (
<TouchableOpacity style={[styles.graybutton, style]} onPress={onPress}>
<Text style={styles.buttonText}>{title}</Text>
</TouchableOpacity>
)
case BORDERED_BLUE_BUTTON:
return (
<TouchableOpacity style={[styles.bordered_button, style]} onPress={onPress}>
<Text style={styles.buttonText}>{title}</Text>
</TouchableOpacity>
)
default:
return (
<TouchableOpacity style={[styles.button, style]} onPress={onPress}>
<Text style={styles.buttonText}>{title}</Text>
</TouchableOpacity>
)
}
}
export default OvalButton;
const styles = StyleSheet.create({
button: {
height: 44,
backgroundColor: PRIMARY,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 22
},
graybutton: {
height: 44,
backgroundColor: BACKGROUND_LIGHT,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 22
},
bordered_button: {
height: 44,
backgroundColor: PRIMARY,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 22,
borderWidth: 5,
borderColor: 'white'
},
buttonText: {
fontSize: 14,
color: 'white',
fontWeight: 'bold'
}
})
</code></pre>
<p>so when I instantiate the button:</p>
<pre><code><OvalButton
title="CONTINUE"
style={[styles.continueButton]}
onPress= { () => navigation.dispatch(navigateToOnboarding()) }
theme={BORDERED_BLUE_BUTTON}
/>
</code></pre>
<p>it renders different, but I have lots of duplicated code, how to polish this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:47:43.700",
"Id": "499403",
"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": "2020-12-09T23:17:14.180",
"Id": "499469",
"Score": "0",
"body": "Why don't you just set `buttonStyle` with a switch or dict and then return `<TouchableOpacity style={[buttonStyle, style]}>` once?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T03:37:22.643",
"Id": "253241",
"Score": "0",
"Tags": [
"react-native"
],
"Title": "react, react native refactor component for style"
}
|
253241
|
<p>I am fairly new to Python. I wrote a program to take the user inputs which are service, the top-up time, the top-up amount, and exit or stay on the program.</p>
<p>Please review my code. And, can my code be organized? I think it looks a bit messy, maybe it can be shorter?</p>
<ul>
<li>First, I wrote everything under function, so I can restart the program later on.</li>
<li>Second, I want to take user input about the service that they want to top up by limiting the choice of service to only 3 which are Green, Blue, or Red. If none of it, display "Try Again!, Wrong Service" otherwise, "Welcome to Top-up Service".</li>
<li>Third, after passed service versification, the user can top up but limit to only 50,100,300,500,1000. Also, the user can only choose "How many times they want to top-up".</li>
<li>Forth, after top-up, the list of top-up and sum of top-up is presented.</li>
<li>Last, the user can choose to stay or exit the program. If stay, the program is restarted, if exit, the program is terminated.</li>
</ul>
<p><strong>Here is the code that I wrote</strong></p>
<pre><code> def main():
# Letting user choose a service
service = None
while service not in {"Green", "Blue", "Red"}:
service = input("Please enter Green, Blue or Red: ")
# Now service is either Green, Blue or Red
if service in {"Green", "Blue", "Red"}:
print("Welcome to Top-up Service")
else:
print("Try Again!, Wrong Service")
# Doing Top up(s)
top_list = []
n=int(input("How many times do you want to top up? "))
for i in range(1,n+1):
top_up = None
while top_up not in {50,100,300,500,1000}:
top_up = int(input("Please enter 50,100,300,500 or 1000: "))
# Now top_up is either 50,100,300,500 or 1000"
if top_up in {50,100,300,500,1000}:
top_list.append(top_up)
else:
print("Try Again!, Wrong Top-up")
# Show all top up(s) information & Sum all top up(s)
print("Top up(s) information : ", top_list)
print("Total top up(s): ", sum(top_list))
# Letting user choose to stay or exit
restart = input("Do you want to start again?,Y or else ").upper()
if restart == "Y":
main()
else:
print("Thank you for using our service")
exit()
main()
</code></pre>
<p><strong>This is the example of output</strong></p>
<pre><code>Please enter Green, Blue or Red: o
Try Again!, Wrong Service
Please enter Green, Blue or Red: Blue
Welcome to Top-up Service
How many times do you want to top up? 2
Please enter 50,100,300,500 or 1000: 20
Try Again!, Wrong Top-up
Please enter 50,100,300,500 or 1000: 50
Please enter 50,100,300,500 or 1000: 500
Top up(s) information : [50, 500]
Total top up(s): 550
Do you want to start again?,Y or else n
Thank you for using our service
</code></pre>
|
[] |
[
{
"body": "<h2>Make use of docstring</h2>\n<p>A docstring explains what the function does, the input it expects and what output it gives. It's pythonic to include docstrings in functions and classes just below the function or class definition. For example</p>\n<pre><code>def f():\n """This is a function"""\n</code></pre>\n<h2>Irrelevant checks</h2>\n<p>In your while loop, you check if <code>service</code> is in your <code>set</code> and also do a similar check in the while loop's body, the latter is irrelevant, you should take advantage of the first check and refactor the code like this</p>\n<pre><code>service = input("Please enter Green, Blue or Red: ")\nwhile service not in {"Green", "Blue", "Red"}:\n print("Try Again!, Wrong Service")\n service = input("Please enter Green, Blue or Red: ")\n# service is valid because the while loop breaks\n# continue the code here....\n\n</code></pre>\n<p>A similar approach can be done for <code>top_up</code></p>\n<h2>Side note</h2>\n<p>This program does nor necessarily need a recursive\napproach, recursion tends to slower and takes more memory due to keeping temporaries in the stack frame, consider using a while loop instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T06:36:17.007",
"Id": "253247",
"ParentId": "253244",
"Score": "2"
}
},
{
"body": "<p>You can divide your whole program into parts, this way it becomes easy while debugging and increases modularity in the code.</p>\n<p>You can divide into multiple functions like</p>\n<ul>\n<li>Selecting service.</li>\n<li>Add top-up</li>\n<li>Restart logic</li>\n</ul>\n<h3>Refractored code</h3>\n<pre><code>AVAILABLE_SERVICES = {"Green", "Blue", "Red"} \nAVAILABLE_TOPUPS = {50, 100, 300, 500, 1000}\n\n\ndef select_service():\n while True:\n service = input("Please enter Green, Blue or Red: ").title()\n if service in AVAILABLE_SERVICES:\n print("Welcome to Top-up Service")\n break\n return service\n\n\ndef top_up(service):\n times_topup = int(input("How many times do you want to top up? "))\n topups_selected = []\n for _ in range(times_topup):\n while True:\n topup = int(input("Please enter 50,100,300,500 or 1000: "))\n if topup in AVAILABLE_TOPUPS:\n topups_selected.append(topup)\n break\n else:\n print("Try Again!, Wrong Top-up")\n\n print("Top up(s) information : ", topups_selected)\n print("Total top up(s): ", sum(topups_selected))\n\n\ndef process():\n restart = "Y"\n while restart == "Y":\n service = select_service()\n top_up(service)\n restart = input("Do you want to start again?,Y or else: ").upper()\n print("Thank you for using our service")\n\n\nif __name__ == "__main__":\n process()\n</code></pre>\n<h3>Output:</h3>\n<pre><code>Please enter Green, Blue or Red: Blue\nWelcome to Top-up Service\nHow many times do you want to top up? 2\nPlease enter 50,100,300,500 or 1000: 7\nTry Again!, Wrong Top-up\nPlease enter 50,100,300,500 or 1000: 50\nPlease enter 50,100,300,500 or 1000: 10\nTry Again!, Wrong Top-up\nPlease enter 50,100,300,500 or 1000: 100\nTop up(s) information : [50, 100]\nTotal top up(s): 150\nDo you want to start again?,Y or else: Y\nPlease enter Green, Blue or Red: Red\n...\n...\n...\nDo you want to start again?,Y or else: n\nThank you for using our service\n</code></pre>\n<h2>Code Review</h2>\n<ul>\n<li><h3><code>PEP-8</code> violations:</h3>\n<ul>\n<li><code>E231</code> - missing whitespace after <code>,</code>\n<ul>\n<li><code>range(1,n+1)</code> ⟶ <code>range(1, n+1)</code></li>\n<li><code>{50,100,300,500,1000}</code> ⟶ <code>{50, 100, 300, 500, 1000}</code></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Declare constants for services and top-ups instead of writing <code>{"Blue", ...}</code> and <code>{50, ...}</code> everywhere.\n<ul>\n<li><code>{"Blue", ...}</code> ⟶ <code>AVAILABLE_SERVICES = {"Green", "Blue", "Red"}</code> Now you can use <code>AVAILABLE_SERVICES</code> instead of writing <code>{"Blue", ...}</code></li>\n<li><code>{50, ...}</code> ⟶ <code>AVAILABLE_TOPUPS = {50, 100, 300, 500, 1000}</code></li>\n</ul>\n</li>\n<li>Use <code>str.title</code> when taking input for <code>service</code>, so <code>"BLUE"</code> would become <code>"Blue"</code>.</li>\n<li>Use <code>_</code> here <code>for i in range(1, n+1)</code> when you are not using <code>i</code> in the loop.\n<ul>\n<li><code>for i in range(1, n+1)</code> ⟶ <code>for _ in range(n)</code></li>\n<li><a href=\"https://stackoverflow.com/q/5893163/12416453\">What's the purpose of <code>_</code> in python</a></li>\n</ul>\n</li>\n<li>You can make <code>AVAILABLE_SERVICES</code> as <code>frozenset</code> to make immutable.\n<ul>\n<li><code>AVAILABLE_SERVICES = frozenset({"Green", "Blue", "Red"})</code></li>\n<li><code>AVAILABLE_TOPUPS = frozenset({50, 100, 300, 500, 1000})</code></li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>You can use <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">pep8online</a><sup>*</sup> to check if your code is in accordance with PEP-8 standard.</p>\n<p>You can use <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><strong><code>black</code></strong></a><sup>*</sup> (code formatting tool)</p>\n<pre><code>black --line-length 79 your_file.py\n</code></pre>\n<hr />\n<p><sub><sub>* I'm not affiliated to <code>pep8online</code> and <code>black</code>.</sub></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T15:50:09.470",
"Id": "499436",
"Score": "1",
"body": "`service` isn't global"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T16:08:00.037",
"Id": "499437",
"Score": "0",
"body": "@user253751 We can add return statement to `select_service` and pass it as arg to `top_up`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T06:43:30.307",
"Id": "253248",
"ParentId": "253244",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T05:44:14.160",
"Id": "253244",
"Score": "5",
"Tags": [
"python",
"beginner"
],
"Title": "Program to top-up phone with conditions in Python"
}
|
253244
|
<p>I am a self-learned programmer and this is my first program. I would really appreciate any critique on my approach.</p>
<p>The program should automatically download the who data file to the folder these files are in.</p>
<h3>file: who_report.py</h3>
<pre><code># https://covid19.who.int/
# https://covid19.who.int/WHO-COVID-19-global-data.csv
# https://www.kaggle.com/tanuprabhu/population-by-country-2020
import numpy as np
import matplotlib.pyplot as plt
import math
import os
# local imports
from who_report_helper import get_who_statistics, get_range_date
"""
This script will download the latest Covid statistics directly from WHO and write it to a local csv.
Then parse 9 countries statistics to compare.
Then it will generate a mat plot chart saving to a png after.
"""
def create_report(cdf, ytd, end):
# from pprint import pprint # Uncomment for list of country codes to compare other country stats
# countries = dict(zip(cdf.Country.unique(), cdf.Country_code.unique()))
# pprint(countries)
US = cdf[(cdf['Country_code'] == "US") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # US
MX = cdf[(cdf['Country_code'] == "MX") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Mexico
BR = cdf[(cdf['Country_code'] == "BR") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Brazil
GB = cdf[(cdf['Country_code'] == "GB") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # UK
DE = cdf[(cdf['Country_code'] == "DE") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Germany
IT = cdf[(cdf['Country_code'] == "IT") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Italy
FR = cdf[(cdf['Country_code'] == "FR") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # France
ES = cdf[(cdf['Country_code'] == "ES") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Spain
IN = cdf[(cdf['Country_code'] == "IN") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # India
RU = cdf[(cdf['Country_code'] == "RU") & (cdf['Date_reported'] <= end) & (cdf['Date_reported'] >= ytd)] # Russia
# Setting up the figure and its grids to plot
grid_size = (13, 3)
plt.style.use('seaborn-darkgrid')
fig = plt.figure(figsize=(13, 13))
ax1 = plt.subplot2grid(grid_size, (0, 0), colspan=1, rowspan=4)
ax2 = plt.subplot2grid(grid_size, (0, 1), colspan=1, rowspan=2)
ax3 = plt.subplot2grid(grid_size, (2, 1), colspan=1, rowspan=2)
ax4 = plt.subplot2grid(grid_size, (0, 2), colspan=1, rowspan=4)
ax5 = plt.subplot2grid(grid_size, (4, 0), colspan=3, rowspan=3)
ax6 = plt.subplot2grid(grid_size, (7, 0), colspan=3, rowspan=3)
ax7 = plt.subplot2grid(grid_size, (10, 0), colspan=3, rowspan=3)
fig.tight_layout(pad=3)
fig.suptitle(f"United States and World Covid Statistics: {ytd[5:]} to {end[5:]}-2020\n", size=12, weight='bold')
# This is all of the information needed for the graphs/charts
world_dfs = (US, MX, BR, DE, GB, IT, FR, ES, RU, IN)
populations = [country.Population.iloc[0] for country in world_dfs]
cases_per50k = [country['New_cases'].sum() / populations[i] * 50000 for i, country in enumerate(world_dfs)]
cases_per100k = [country['New_cases'].sum() / populations[i] * 100000 for i, country in enumerate(world_dfs)]
deaths_per100k = [country['New_deaths'].sum() / populations[i] * 100000 for i, country in enumerate(world_dfs)]
deaths_per1m = [country['New_deaths'].sum() / populations[i] * 1000000 for i, country in enumerate(world_dfs)]
us_total_cases = US['New_cases'].sum()
us_total_deaths = US['New_deaths'].sum()
world_td = cdf[cdf['Date_reported'] >= ytd]
world_total_cases = world_td['New_cases'].sum()
world_total_deaths = world_td['New_deaths'].sum()
us_world_cases = (us_total_cases, world_total_cases)
us_world_deaths = (us_total_deaths, world_total_deaths)
us_world_labels = ('$US$', '$World$')
country_labels = ['$US$', '$Mexico$', '$Brazil$', '$Germany$', '$UK$', '$Italy$',
'$France$', '$Spain$', '$Russia$', '$India$'] # toggle this if you change countries
# country_labels = [f"${country.Country.iloc[0]}$" for country in world_dfs] # toggle this if you change countries
label_cols = math.ceil(len(country_labels) / 2)
explode = (0.025, 0, 0, 0, 0, 0, 0, 0, 0, 0)
pos = np.arange(len(country_labels))
width = 0.25
# \\...Pie chart for Cases per capita of 100,000 for selected countries...\\
ax1.pie(cases_per100k, explode=explode, labels=country_labels, shadow=False, startangle=90, pctdistance=0.8,
autopct=lambda temp: '${:.0f}$'.format(temp * sum(cases_per100k) / 100))
ax1.set_title('Cases per capita (100,000)')
# \\...Pie chart for Deaths per capita of 100,000 for selected countries...\\
ax4.pie(deaths_per100k, explode=explode, labels=country_labels, shadow=False, startangle=90, pctdistance=0.8,
autopct=lambda temp: '${:.0f}$'.format(temp * sum(deaths_per100k) / 100))
ax4.set_title('Deaths per capita (100,000)')
# \\...Pie Donut chart for total cases US vs World...\\
ax2.pie(us_world_cases, labels=us_world_labels, textprops={'fontsize': 8}, colors=['#ff0000', '#7ab6ff'],
wedgeprops=dict(width=.1), startangle=115, pctdistance=0.45,
autopct=lambda temp: '${:.1f}$%\n$({:.0f})$'.format(temp, (temp / 100) * sum(us_world_cases)))
ax2.set_title('USA vs World: Total Cases\n_______________________', y=-0.3)
# \\...Pie Donut chart for total deaths US vs World...\\
ax3.pie(us_world_deaths, labels=us_world_labels, textprops={'fontsize': 8}, colors=['#ff0000', '#7ab6ff'],
wedgeprops=dict(width=.1), startangle=115, pctdistance=0.45,
autopct=lambda temp: '${:.1f}$%\n$({:.0f})$'.format(temp, (temp / 100) * sum(us_world_deaths)))
ax3.set_title('USA vs World: Total Deaths')
# \\...Line chart for Cases for selected countries...\\
for country in world_dfs:
ax5.plot(country['Date_reported'], country['New_cases'] / country['Population'] * 10000000)
ax5.set_title('Daily Covid Cases per capita (1,000,000)')
ax5.set_ylabel('Cases')
ax5.set_xticks(ax5.get_xticks()[::31])
leg = ax5.legend(country_labels, loc='upper center', ncol=label_cols, fontsize=8, bbox_to_anchor=(0.5, 1.3))
for line in leg.get_lines():
line.set_linewidth(3.0)
# \\...Line chart for Deaths per Capita 1,000,000 for selected countries...\\
for country in world_dfs:
ax6.plot(country['Date_reported'], country['New_deaths'] / country['Population'] * 10000000)
ax6.set_title('Daily Covid Deaths per capita (1,000,000)')
ax6.set_ylabel('Deaths')
ax6.set_xticks(ax6.get_xticks()[::31])
# \\...Bar chart for Deaths per Capita 50k cases/1m deaths, for selected countries...\\
ax7.bar(pos, cases_per50k, width, alpha=0.5, color='#EE3224')
ax7.bar([p + width for p in pos], deaths_per1m, width, alpha=0.5, color='#FFC222')
ax7.set_ylabel('Cases/Deaths')
ax7.set_title('Countries: Cases and Deaths per capita')
ax7.set_xticks([p + .5 * width for p in pos])
ax7.set_xticklabels(country_labels)
ax7.set_xlim(min(pos) - width, max(pos) + width * 2)
ax7.set_ylim([0, max((cases_per50k + deaths_per1m))])
ax7.legend(['Cases per Capita (50,000)', 'Deaths per capita (1,000,000)'], loc='upper right')
return plt
def save_plot(figure, ytd, end):
if not os.path.exists('covid_charts'):
os.makedirs('covid_charts')
if ytd <= '2020-01-03':
figure.savefig(f'covid_charts/COVID-19-chart-{end}', dpi=300)
else:
figure.savefig(f'covid_charts/COVID-19-chart-{ytd[5:]}-{end[5:]}', dpi=300)
figure.show()
def main():
stats = get_who_statistics()
dates = get_range_date()
figure = create_report(stats, *dates)
save_plot(figure, *dates)
if __name__ == "__main__":
main()
</code></pre>
<h3>file: who_report_helper.py</h3>
<pre><code># Programmer: Jeffrey Carvalho
# https://covid19.who.int/
# https://covid19.who.int/WHO-COVID-19-global-data.csv
# https://www.kaggle.com/tanuprabhu/population-by-country-2020
import requests
import pandas as pd
import datetime as dt
import os
import calendar
replacements = {
'Bolivia': 'Bolivia (Plurinational State of)',
'Brunei': 'Brunei Darussalam',
'Caribbean Netherlands': 'Bonaire, Sint Eustatius and Saba',
'Channel Islands': 'Jersey',
'Czech Republic (Czechia)': 'Czechia',
'Côte d\'Ivoire': 'Côte d’Ivoire',
'DR Congo': 'Democratic Republic of the Congo',
'Faeroe Islands': 'Faroe Islands',
'Falkland Islands': 'Falkland Islands (Malvinas)', #
'Iran': 'Iran (Islamic Republic of)',
'Laos': "Lao People's Democratic Republic", #
'Micronesia': 'Micronesia (Federated States of)',
'Moldova': 'Republic of Moldova',
'North Korea': "Democratic People's Republic of Korea",
'Northern Mariana Islands': 'Northern Mariana Islands (Commonwealth of the)',
'Russia': 'Russian Federation',
'Saint Barthelemy': 'Saint Barthélemy',
'Saint Kitts & Nevis': 'Saint Kitts and Nevis',
'Saint Pierre & Miquelon': 'Saint Pierre and Miquelon',
'Sao Tome & Principe': 'Sao Tome and Principe',
'South Korea': 'Republic of Korea',
'St. Vincent & Grenadines': 'Saint Vincent and the Grenadines',
'State of Palestine': 'occupied Palestinian territory, including east Jerusalem',
'Syria': 'Syrian Arab Republic', #
'Tanzania': 'United Republic of Tanzania',
'Turks and Caicos': 'Turks and Caicos Islands',
'U.S. Virgin Islands': 'United States Virgin Islands',
'United Kingdom': 'The United Kingdom',
'United States': 'United States of America',
'Venezuela': 'Venezuela (Bolivarian Republic of)',
'Vietnam': 'Viet Nam',
'Wallis & Futuna': 'Wallis and Futuna',
}
def get_who_statistics():
# Returns the latest version WHO report or passes on a Panda Data Frame from an already downloaded CSV file
PATH = 'https://covid19.who.int/WHO-COVID-19-global-data.csv'
FILE = 'WHO-COVID-19-global-data.csv'
def dl_data():
data_source = requests.get(PATH)
data = data_source.content
if not os.path.exists('data'):
os.makedirs('data')
covid_data = open(f'data/{FILE}', 'wb')
covid_data.write(data)
covid_data.close()
who = input('Would you like to get today\'s COVID stats from WHO?\n\nType Yes to download\nPress ENTER to skip\n')
if who.lower() == 'yes':
dl_data()
try:
cdf = pd.read_csv(f'data/{FILE}')
except FileNotFoundError:
print('ERROR: File not found!\nDownloading new file now.\n')
dl_data()
cdf = pd.read_csv(f'data/{FILE}')
finally:
cdf = cdf[['Date_reported', 'Country_code', 'Country', 'New_cases', 'New_deaths', 'Cumulative_deaths']]
world_pop = pd.read_csv('data/population_by_country_2020.csv')
world_pop = world_pop[['Country (or dependency)', 'Population (2020)']]
world_pop['Country (or dependency)'].replace(replacements, inplace=True)
cdf = cdf.join(world_pop.set_index('Country (or dependency)'), on='Country')
cdf.rename(columns={'Population (2020)': 'Population'}, inplace=True)
return cdf
def get_range_date():
# Returns the range of dates to use on the charts
msg1 = '''When would you like to start the graphs at?\n\n0: for Complete data\
\n1: for the past week\n2: for past 30 days\n3: for past 90 days\
\n4: Select number of days to look back\n5: Select a month in 2020\n'''
msg2 = "How many days would you like to set the chart back to?\n"
msg3 = "What month of 2020 would you like to look at?\nEnter numeric month value (1-12)"
today = end = dt.date.today()
ytd = dt.date(2020, 1, 3)
try:
date_range = int(input(msg1))
while date_range < 0 or date_range > 5:
date_range = int(input(msg1))
if date_range == 1: ytd = today - dt.timedelta(days=7)
if date_range == 2: ytd = today - dt.timedelta(days=30)
if date_range == 3: ytd = today - dt.timedelta(days=90)
if date_range == 4:
days = int(input(msg2))
while days < 0:
days = int(input(msg2))
ytd = today - dt.timedelta(days=days)
if date_range == 5:
month = int(input(msg3))
while month < 1 or date_range > 12:
month = int(input(msg3))
month_range = calendar.monthrange(2020, month)
ytd = dt.date(2020, month, 1)
end = dt.date(2020, month, month_range[1])
except ValueError:
print('PLEASE ENTER NUMBERS ONLY!\n')
return get_range_date()
else:
return str(ytd), str(end)
def main():
print('This file is used for collecting the covid data from WHO for the report')
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:55:03.917",
"Id": "510469",
"Score": "0",
"body": "It would help to know what the code is supposed to do -- in English, not just in code."
}
] |
[
{
"body": "<pre><code> US = cdf[(cdf['Country_code'] == "US") &\n (cdf['Date_reported'] <= end) & \n (cdf['Date_reported'] >= ytd)] # US\n</code></pre>\n<p>You have a lot of lines like that.</p>\n<ul>\n<li>Build an array of 'US', 'MX', ...</li>\n<li>Have an associative array for the left part</li>\n<li>Use a loop to perform those 'identical' statements</li>\n</ul>\n<p>(Sorry, I don't know python, so I can't write it for you.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T01:00:06.507",
"Id": "258904",
"ParentId": "253245",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T05:57:49.973",
"Id": "253245",
"Score": "1",
"Tags": [
"python",
"sorting",
"database",
"pandas",
"matplotlib"
],
"Title": "Covid-19 World Case Report Beta 0.1"
}
|
253245
|
<p>I am sick of File Explorer's super slow deletion speed, so I tried to write a PowerShell script to make deletion faster, and while it does its job, its speed isn't as high as what I intended it to be.</p>
<p>I have written this:</p>
<pre><code>Function Fast-Delete {
Param(
[Parameter(Valuefrompipeline=$True, Mandatory=$True)] [String]$Directory0
)
Write-Warning "This Process Will Delete Everything In The Target Directory: $Directory0, Do You Want To Confirm Deletion?" -Warningaction Inquire
$Directory=$Directory0
While ((Get-Childitem -Path $Directory0 -Depth 0 -Force).Count -Ne 0) {
If ((Get-Childitem -Path $Directory -Directory -Force -Depth 0).Count -Ne 0) {
$Directory=(Get-Childitem -Path $Directory -Directory -Force -Depth 0).Fullname | Select-Object -Index 0
}
If ((Get-Childitem -Path $Directory -File -Force).Count -Ne 0) {
(Get-Childitem -Path $Directory -File -Recurse -Force).Fullname | Foreach {Remove-Item -Path $_}
}
$Directory1=$Directory
$Directory=$Directory | Split-Path -Parent
Remove-Item -Path $Directory1
}
Remove-Item -Path $Directory0
}
</code></pre>
<p>It is significantly faster than explorer, but still isn't ideal, I have tested it, I used it to delete 208,000 files in 1,000 folders , and the folders disappear at speed of 1 per second, so it's about 208 files/s, now the next challenge should be parallelization, But this is currently really way above me, but it shouldn't be too hard, I am just not experienced enough.</p>
<p>Update2</p>
<p>I have managed to make it run in parallel with this script:</p>
<pre><code>function Parallel-Delete {
param(
[Parameter(Valuefrompipeline=$true, Mandatory=$true, Position=0)] [array]$filelist,
[Parameter(Valuefrompipeline=$true, Mandatory=$true, Position=1)] [int]$number
)
0..($filelist.count-1) | Where-Object {$_ % 16 -eq $number} | foreach {Remove-Item -Path $filelist[$_]}
}
Function Fast-Delete {
Param(
[Parameter(Valuefrompipeline=$True, Mandatory=$True)] [String]$Directory0
)
Write-Warning "This Process Will Delete Everything In The Target Directory: $Directory0, Do You Want To Confirm Deletion?" -Warningaction Inquire
$Directory=$Directory0
While ((Get-Childitem -Path $Directory0 -Depth 0 -Force).Count -Ne 0) {
If ((Get-Childitem -Path $Directory -Directory -Force -Depth 0).Count -Ne 0) {
$Directory=(Get-Childitem -Path $Directory -Directory -Force -Depth 0).Fullname | Select-Object -Index 0
}
If ((Get-Childitem -Path $Directory -File -Force).Count -Ne 0) {
If ((Get-Childitem -Path $Directory -File -Force).Count -Ge 128) {
[array]$filelist=(Get-Childitem -Path $Directory -File -Force).Fullname
0..15 | foreach-object {Invoke-Command -ScriptBlock { Parallel-Delete $filelist $_}}
} else {
(Get-Childitem -Path $Directory -File -Force).Fullname | Foreach {Remove-Item -Path $_}
}
}
$Directory1=$Directory
$Directory=$Directory | Split-Path -Parent
Remove-Item -Path $Directory1
}
Remove-Item -Path $Directory0 -erroraction silentlycontinue
}
$Directory0=Read-Host "Please input target directory to be deleted"
Fast-Delete $Directory0
</code></pre>
<p>But it still isn't ideal, it isn't 15 times faster as expected, what did I miss?</p>
<p>Edit: simplified the creation of parallel processes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:33:53.243",
"Id": "499376",
"Score": "2",
"body": "the fastest way to delete an entire dir tree is to use robocopy. you mirror a blank \"source\" dir to the one you want removed ... and the \"destination\" gets emptied _quickly_. [*grin*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:51:15.010",
"Id": "499385",
"Score": "0",
"body": "@Lee_Dailey, in fact I wanted to write a new script, not to use existing things, and the method you mentioned sounds like a bug..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T08:08:40.430",
"Id": "499386",
"Score": "3",
"body": "i understand your desire. [*grin*] as for a bug ... it is exactly what the options mean - mirror empty source to full destination gives empty source and empty destination. so ... have fun playing with a script ...but PoSh will always be slower than any well written utility."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T10:37:24.827",
"Id": "499871",
"Score": "0",
"body": "And I have tried Start-Job, but they just hang in place, they are not working so I used stop-job to terminate them... And still I can't pass to variables to new powershell process started by start-process..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T23:37:01.303",
"Id": "499924",
"Score": "0",
"body": "i would narrow your problems to specifics ... and open a Question for each of them. the `pass variable to start-process` question has been answered here OR in stackoverflow many times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T00:14:55.380",
"Id": "504318",
"Score": "0",
"body": "@XeнεiΞэnвϵς Replace all `where-object` with `foreach-object` and use `If()` conditions instead. Put `process { }` wrap in all your `foreach-object` and also in all `invoke-command` within your script. E.g. `0..($filelist.count-1) | % { Process { If ($_ % 16 -eq $number) { Remove-Item -Path $filelist[$_] } } }` and `0..15 | % { Process { Invoke-Command -ScriptBlock { Process { Parallel-Delete $filelist $_ }}}}` for starters... Just start incorporating that way and then measure to test the speed differences. I always start with those simple techniques for PS processing speed 101."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T00:17:19.700",
"Id": "504319",
"Score": "0",
"body": "@XeнεiΞэnвϵς Yes, it's me from the other sister site with an old handle name or whatever it is called. Look at my profile and click on the SU community from there and you'll see. I don't use the same avatar or moniker on each of the communities always so I mix and match like a bucket of chicken from KFC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T05:48:33.100",
"Id": "513004",
"Score": "0",
"body": "why you dont remove the dire complete and recreate him after ?"
}
] |
[
{
"body": "<p>May be try this:</p>\n<pre><code>#solution 1 - Remove content of dir \nremove-item "C:\\temp\\tmp2\\*" -Recurse -Force\n\n#Solution 2 - Remove dir and recreate dir\nremove-item "C:\\temp\\tmp2\\" -Recurse -Force\nNew-Item "C:\\temp\\tmp2\\" -ItemType Directory\n\n#Solution 3 - Loop into dir and remove all with intercept error\nGet-ChildItem "C:\\temp\\tmp2\\" -Recurse | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T07:51:26.630",
"Id": "513007",
"Score": "0",
"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]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T06:16:59.290",
"Id": "259969",
"ParentId": "253249",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:06:02.477",
"Id": "253249",
"Score": "4",
"Tags": [
"performance",
"beginner",
"file-system",
"powershell"
],
"Title": "PowerShell - fast remove a directory with 10,000+ files"
}
|
253249
|
<p>The following is a trimmed-down example of my actual code, but it suffices to show the algorithmic problem I'm trying to solve.</p>
<p>Given is a DataFrame with events, each with a user ID and a timestamp.</p>
<pre class="lang-scala prettyprint-override"><code>val events = Seq(
("1001", 1),
("1001", 2),
("1001", 3),
("1001", 5),
("1001", 6),
("1002", 1),
("1002", 3),
).toDF("user_id", "timestamp")
events.orderBy($"user_id", $"timestamp").show
</code></pre>
<pre><code>+-------+---------+
|user_id|timestamp|
+-------+---------+
| 1001| 1|
| 1001| 2|
| 1001| 3|
| 1001| 5|
| 1001| 6|
| 1002| 1|
| 1002| 3|
+-------+---------+
</code></pre>
<p>My goal is to group events from the same user together into one session if the timestamp gap is not above some threshold (<code>1</code> in this example).</p>
<p>In my solution, I determine the given sessions by looking for timestamp gaps and then applying <code>monotonically_increasing_id</code>.</p>
<pre class="lang-scala prettyprint-override"><code>val sessions = {
events
.withColumn(
"timestamp_gap_before",
$"timestamp" - lag($"timestamp", 1).over(Window.partitionBy($"user_id").orderBy($"timestamp"))
)
.withColumn(
"timestamp_gap_after",
lead($"timestamp", 1).over(Window.partitionBy($"user_id").orderBy($"timestamp")) - $"timestamp"
)
.withColumn(
"is_session_start",
$"timestamp_gap_before".isNull || $"timestamp_gap_before" > lit(1)
)
.withColumn(
"is_session_end",
$"timestamp_gap_after".isNull || $"timestamp_gap_after" > lit(1)
)
.filter($"is_session_start" || $"is_session_end")
.withColumn(
"min_timestamp",
least($"timestamp", lead($"timestamp", 1).over(Window.partitionBy($"user_id").orderBy($"timestamp")))
)
.withColumn(
"max_timestamp",
greatest($"timestamp", lead($"timestamp", 1).over(Window.partitionBy($"user_id").orderBy($"timestamp")))
)
.filter($"is_session_start")
.select(
$"user_id" as "session_user_id",
$"min_timestamp" as "session_start_timestamp",
// Special handling for sessions with only one event.
when($"is_session_end", $"min_timestamp").otherwise($"max_timestamp") as "session_end_timestamp",
)
.orderBy($"user_id", $"session_start_timestamp")
.withColumn("session_id", monotonically_increasing_id)
}
sessions.orderBy($"session_user_id", $"timestamp").show
</code></pre>
<pre><code>+---------------+-----------------------+---------------------+-----------+
|session_user_id|session_start_timestamp|session_end_timestamp| session_id|
+---------------+-----------------------+---------------------+-----------+
| 1001| 1| 3| 0|
| 1001| 5| 6| 8589934592|
| 1002| 1| 1|17179869184|
| 1002| 3| 3|25769803776|
+---------------+-----------------------+---------------------+-----------+
</code></pre>
<p>Then, I just need to join these session IDs onto the events:</p>
<pre class="lang-scala prettyprint-override"><code>val assignedEvents = {
events
.join(sessions,
$"session_user_id" === $"user_id" &&
$"timestamp" >= $"session_start_timestamp" &&
$"timestamp" <= $"session_end_timestamp")
.drop("session_user_id", "session_start_timestamp", "session_end_timestamp")
}
assignedEvents.orderBy($"user_id", $"timestamp").show
</code></pre>
<pre><code>+-------+---------+-----------+
|user_id|timestamp| session_id|
+-------+---------+-----------+
| 1001| 1| 0|
| 1001| 2| 0|
| 1001| 3| 0|
| 1001| 5| 8589934592|
| 1001| 6| 8589934592|
| 1002| 1|17179869184|
| 1002| 3|25769803776|
+-------+---------+-----------+
</code></pre>
<p>It works, but it feels somewhat clumsy. Especially the definition of <code>sessions</code> seems superfluous complex to me.</p>
<p>Does anybody know a simpler solution? :-)</p>
|
[] |
[
{
"body": "<p>Couldn't you reduce the complexity a lot by transforming the timestamp data per user to a <code>KeyValueGroupedDataSet[String, Int]</code> and then group the sessions based on the <code>Int</code> groups without having to care about data frames and columns in the process?</p>\n<p>I'm not a Spark expert (this is actually the first thing I'm trying out in Spark) so I'm formulating this as a question. I am not sure if this is reasonable from a performance point of view or if sorting is lost during any transformation step. Anyway, this seemed to work for me to obtain the sessions:</p>\n<pre><code>val maxDistance = 1\ndef closeEnough(a: Int, b: Int) = Math.abs(b - a) <= maxDistance\n\ndef groupSessions(timestamps: List[Int]) =\n timestamps.drop(1).foldLeft(List(List(timestamps.head))) {\n (acc, e) =>\n if (closeEnough(e, acc.head.head)) (e :: acc.head) :: acc.tail\n else List(e) :: acc\n }\n\nval sessions =\n events\n .groupBy("user_id")\n .as[String, (String, Int)]\n .mapValues(_._2)\n .flatMapGroups((s, ii) =>\n groupSessions(ii.toList.reverse)\n .map(sessionTs => (s, sessionTs.head, sessionTs.last))\n )\n .toDF("session_user_id", "session_start_timestamp", "session_end_timestamp")\n .orderBy($"session_user_id", $"session_start_timestamp")\n .withColumn("session_id", monotonically_increasing_id)\n</code></pre>\n<p>I borrowed the <code>groupSessions()</code> function from <a href=\"https://stackoverflow.com/a/37817742/302793\">this SO answer</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T09:03:29.167",
"Id": "253413",
"ParentId": "253251",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:48:14.637",
"Id": "253251",
"Score": "1",
"Tags": [
"scala",
"apache-spark"
],
"Title": "Group events close in time into sessions and assign unique session IDs"
}
|
253251
|
<p>This is a solution for part 1 & 2 of <a href="https://adventofcode.com/2020/day/9" rel="nofollow noreferrer">Advent of Code 2020 Day 9</a>.</p>
<p>Given the example input <code>sample.txt</code>:</p>
<pre><code>35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
</code></pre>
<p><strong>Part 1</strong>: find the first number in the list (after the preamble) which is not the sum of two of the n numbers before it. n is the preamble.</p>
<p>For example, after the 5-number preamble, almost every number is the sum of two of the previous 5 numbers; the only number that does not follow this rule is <strong>127</strong>.</p>
<p><strong>Part 2</strong>: find a contiguous set of at least two numbers in your list which sum to the invalid number from part 1.</p>
<p>For example, in this list, adding up all of the numbers from 15 through 40 produces the invalid number from part 1, 127. Add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing <strong>62</strong>.</p>
<p><strong>Code</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def not_in_preamble(nums, preamble):
diff = set()
for i in range(preamble, len(nums)):
current = nums[i]
found = False
for j in range(i - preamble, i):
if nums[j] in diff:
found = True
break
diff.add(current - nums[j])
if not found:
return current
diff.clear()
def sub_array_with_sum(nums, n):
i, j = 0, 1
partial_sum = nums[i] + nums[j]
while j < len(nums):
if partial_sum == n:
return nums[i: j + 1]
if partial_sum < n or i == j - 1:
j += 1
partial_sum += nums[j]
else:
partial_sum -= nums[i]
i += 1
# Part 1
preamble = 5
with open('sample.txt') as f:
nums = [int(l) for l in f.read().splitlines()]
pt1_result = not_in_preamble(nums, preamble)
print(f'PT 1 result: {pt1_result}')
# Part 2
n = pt1_result
sub_array = sub_array_with_sum(nums, n)
print(f'PT 2 result {min(sub_array) + max(sub_array)}')
</code></pre>
<p>The code outputs:</p>
<pre><code>PT 1 result: 127
PT 2 result 62
</code></pre>
<p>Which is the correct result for the sample input.</p>
<p>Changing the <code>sample.txt</code> to the <a href="https://adventofcode.com/2020/day/9/input" rel="nofollow noreferrer">puzzle input</a> and setting <code>preamble=25</code>, will give the correct result for the challenge.</p>
<p>Can the code be made more compact and efficient? Any other feedback or alternative solutions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:35:02.060",
"Id": "499397",
"Score": "0",
"body": "where is the part 2? I can only see the \"_What is the first number that does not have this property?_\" on advent webpage"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T10:48:23.657",
"Id": "499405",
"Score": "0",
"body": "@hjpotter92 I think that part 2 is only for logged in users."
}
] |
[
{
"body": "<h1>Part 1</h1>\n<p>For <code>not_in_preamble</code>, I'd use a <code>for-else</code> instead of your <code>found</code> variable, and not re-use the same set (I don't think it's worth it):</p>\n<pre><code>def not_in_preamble(nums, preamble):\n for i in range(preamble, len(nums)):\n current = nums[i]\n diff = set()\n for j in range(i - preamble, i):\n if nums[j] in diff:\n break\n diff.add(current - nums[j])\n else:\n return current\n</code></pre>\n<p>Since your <em>"Any other feedback or alternative solutions are welcome"</em> also allows less efficient solutions, here's how I <em>actually</em> solved it myself :-)</p>\n<pre><code>from itertools import combinations\n\ndef not_in_preamble(nums, preamble):\n for i in range(preamble, len(nums)):\n if nums[i] not in map(sum, combinations(nums[i-preamble : i], 2)):\n return nums[i]\n</code></pre>\n<p>Preamble size 25 and <code>nums</code> size 1000 are easily small enough for that to run quickly.</p>\n<h1>Part 2</h1>\n<p>Your <code>sub_array_with_sum</code> is great, although it does rely on the input being non-negative numbers, which isn't guaranteed in the problem statement (but is the case for the fixed input file).</p>\n<p>I'd just go with <a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow noreferrer\">PEP 8</a> and change <code>nums[i: j + 1]</code> to <code>nums[i : j + 1]</code> or <code>nums[i : j+1]</code>. And perhaps I'd go with <code>while True:</code>, relying on the existence of an answer.</p>\n<p>Your algorithm almost only takes O(1) space. The only reason it takes more is copying out the sub-array (or rather sub-<em>list</em>, as this is Python and the problem never says "array", so there's really no need to call it array). Could be done in O(1) space to make the algorithm not just time-optimal (O(n)) but also space-optimal. Though that would require more code, not worth it (unless you have an interviewer who insists).</p>\n<h1>Input</h1>\n<p>I'd change <code>[int(l) for l in f.read().splitlines()]</code> to <code>list(map(int, f))</code>, or at least <code>[int(line) for line in f]</code>.</p>\n<h1>Output</h1>\n<p>I'd change<br />\n<code>print(f'PT 1 result: {pt1_result}')</code> to<br />\n<code>print('PT 1 result:', pt1_result)</code>. Bit shorter, and it works in older versions of Python. And at least in IDLE, the f-string is styled only as string, the whole thing green, including the variable. I don't like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T00:42:17.277",
"Id": "499472",
"Score": "0",
"body": "Thanks a lot for the review! Impressive how well the `for-else` fits for the part 1, the example in the [doc](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) looks almost the same."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T13:21:47.030",
"Id": "253263",
"ParentId": "253252",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253263",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T07:52:01.413",
"Id": "253252",
"Score": "1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Advent of Code 2020 Day 9 in Python"
}
|
253252
|
<p>My aim was to provide functionality for a <a href="https://flutter.dev/" rel="noreferrer">Flutter</a> app on Windows to accept drag-and-dropped files.
Flutter apps are written in Dart and compiled to native code, but since this is a cross-platform framework there needs to be a native part - the runner app - which kickstarts the Dart part of the app.</p>
<p>So I changed the C++ code of the Windows runner app to support drag and drop. The code works but I have very little C++ experience, so I likely</p>
<ol>
<li>made mistakes</li>
<li>implemented anti-patterns</li>
<li>created memory leaks</li>
<li>introduced performance issues</li>
<li>all of the above</li>
</ol>
<p>Here's the code, please be gentle with me:</p>
<p><strong>flutter_window.h</strong></p>
<pre><code>#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#include "run_loop.h"
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window, public IDropTarget {
public:
// Creates a new FlutterWindow driven by the |run_loop|, hosting a
// Flutter view running |project|.
explicit FlutterWindow(RunLoop* run_loop,
const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
// IUnknown implementation
HRESULT __stdcall QueryInterface (REFIID iid, void ** ppvObject);
ULONG __stdcall AddRef (void);
ULONG __stdcall Release (void);
// IDropTarget implementation
HRESULT __stdcall DragEnter(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect);
HRESULT __stdcall DragOver(DWORD grfKeyState, POINTL pt, DWORD * pdwEffect);
HRESULT __stdcall DragLeave(void);
HRESULT __stdcall Drop(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect);
private:
// The run loop driving events for this window.
RunLoop* run_loop_;
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
// the D&D registered object
HWND _hwndRegistered;
// helper function to convert 16-bit wstring to utf-8 encoded string
std::string utf8_encode(const std::wstring &wstr);
};
#endif // RUNNER_FLUTTER_WINDOW_H_
</code></pre>
<p><strong>flutter_window.cpp</strong></p>
<pre><code>#include "flutter_window.h"
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <optional>
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(RunLoop *run_loop,
const flutter::DartProject &project)
: run_loop_(run_loop), project_(project) {}
const char kChannelName[] = "desktop_drop";
std::unique_ptr<flutter::MethodChannel<>> channel;
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate()
{
if (!Win32Window::OnCreate())
{
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view())
{
return false;
}
RegisterPlugins(flutter_controller_->engine());
run_loop_->RegisterFlutterInstance(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
//DnD: Initialize OLE
OleInitialize(nullptr);
//DnD: Register Drag & Drop
if (SUCCEEDED(RegisterDragDrop(flutter_controller_->view()->GetNativeWindow(), this)))
{
_hwndRegistered = flutter_controller_->view()->GetNativeWindow();
}
channel = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
flutter_controller_->engine()->messenger(), kChannelName,
&flutter::StandardMethodCodec::GetInstance());
return true;
}
void FlutterWindow::OnDestroy()
{
if (flutter_controller_)
{
run_loop_->UnregisterFlutterInstance(flutter_controller_->engine());
flutter_controller_ = nullptr;
}
//DnD: Unregister Drag & Drop
if (_hwndRegistered)
{
RevokeDragDrop(_hwndRegistered);
_hwndRegistered = NULL;
}
//DnD: Uninitialize OLE
OleUninitialize();
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept
{
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_)
{
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result)
{
return *result;
}
}
switch (message)
{
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
//DnD: Implement IUnknown
HRESULT STDMETHODCALLTYPE
FlutterWindow::QueryInterface(REFIID riid, _COM_Outptr_ void **ppvObject)
{
return S_OK;
}
//DnD: Implement IUnknown
ULONG STDMETHODCALLTYPE FlutterWindow::AddRef()
{
return 0;
}
//DnD: Implement IUnknown
ULONG STDMETHODCALLTYPE FlutterWindow::Release()
{
return 0;
}
//DnD: Implement IDropTarget
HRESULT __stdcall FlutterWindow::DragEnter(IDataObject *pDataObject, DWORD grfKeyState,
POINTL pt, DWORD *pdwEffect)
{
channel.get()->InvokeMethod("entered", nullptr);
// TODO: Implement
return S_OK;
}
//DnD: Implement IDropTarget
HRESULT __stdcall FlutterWindow::DragOver(DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
channel.get()->InvokeMethod("updated", nullptr);
// TODO: Implement
return S_OK;
}
//DnD: Implement IDropTarget
HRESULT __stdcall FlutterWindow::DragLeave(void)
{
// TODO: Implement
channel.get()->InvokeMethod("exited", nullptr);
return S_OK;
}
//DnD: Implement IDropTarget
HRESULT __stdcall FlutterWindow::Drop(IDataObject *pDataObject, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
//wchar_t caFileName[MAX_PATH];
FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT,
-1, TYMED_HGLOBAL};
STGMEDIUM stgm;
if (SUCCEEDED(pDataObject->GetData(&fmte, &stgm)))
{
HDROP hDropInfo = reinterpret_cast<HDROP>(stgm.hGlobal);
// Get the number of files
UINT nNumOfFiles = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
flutter::EncodableList list = {};
wchar_t sItem[MAX_PATH];
for (UINT nIndex = 0; nIndex < nNumOfFiles; ++nIndex)
{
//fetch the length of the path
UINT cch = DragQueryFileW(hDropInfo, nIndex, NULL, 0);
//fetch the path and store it in 16bit wide char
DragQueryFileW(hDropInfo, nIndex, (LPWSTR)sItem, cch + 1);
std::wstring pathInfoUtf16(sItem, cch);
std::string pathInfoUtf8 = FlutterWindow::utf8_encode(pathInfoUtf16);
list.push_back(flutter::EncodableValue(pathInfoUtf8));
}
DragFinish(hDropInfo);
ReleaseStgMedium(&stgm);
channel.get()->InvokeMethod("dropped", std::make_unique<flutter::EncodableValue>(list));
}
return S_OK;
}
// helper function to convert 16-bit wstring to utf-8 encoded string
std::string FlutterWindow::utf8_encode(const std::wstring &wstr)
{
if (wstr.empty())
return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
</code></pre>
<p>Most of this code is auto-generated when creating a new Flutter project on Windows.
Everything that is annotated with <code>//DnD:</code> is my code.</p>
<p>I specifically would like to know whether I implemented the <code>IUnknown</code> and <code>IDropTarget</code> interfaces correctly.
The base line for my app is Windows 10 64 bit, so I don't need to be compatible with older versions of Windows.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T14:21:26.500",
"Id": "499425",
"Score": "0",
"body": "We may not be able to spot memory leaks unless the code that calls the functions is included (main?). Excellent first question other than that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T17:25:20.830",
"Id": "499442",
"Score": "1",
"body": "Unfortunately it's impossible to provide all files to run this example. To be able to run it, one has to set up the flutter framework on Windows (https://flutter.dev/docs/get-started/install/windows) and then create an empty project. The above files (flutter_window.h and flutter_window.cpp) are part of each flutter app and their contents can be replaced with the above code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T13:44:47.510",
"Id": "253264",
"Score": "5",
"Tags": [
"c++",
"windows",
"flutter"
],
"Title": "Make Flutter app on Windows a drop target to accept files"
}
|
253264
|
<p>I am currently working through the C# Yellow Book, as a first step in self directed learning. I'm supplementing that with C#8 In a Nutshell, and general searches of the Microsoft C# language references, StackOverflow etc. Working from multiple sources, however, results in sometimes conflicting coding best practices.</p>
<p>I do have a background in industrial programming (ladder logic, function-block programming etc), so I'm thankfully not starting from scratch regarding logical thinking. Unfortunately, this doesn't translate into knowledge of best practices and conventions in an object-orriented language.</p>
<p>Below is my first attempt at a program that implements objects and multiple method levels. It is based on the exercise from the Yellow Book course to implement a program that allows a user to select a movie, and then check if they are old enough to attend, though I have increased the scope somewhat to match where I am in the textbook and my own coding comfort level.</p>
<p>It is 428 lines, including comments, method summaries and white space (and one commented out code block I kept as refference to compare to a Visual IDE recomended change that I don't fully understand); 1 class object with 2 member variables and 5 methods; and 8 static methods.</p>
<p>The code does work as intended, with limitations mentioned in header comment.</p>
<p>To anyone willing to slog through and have a look:
-I'm looking for general feedback on conventions rather than specific code implementations, though any input is greatly appreciated!
-This is my first time using the "///" comment blocks. I would love feedback on whether I should be more or less descriptive in these.
-I realize in this implementation, use of a class object may be a bit over the top, however that was the key item I wanted to practice.
-If anyone is wanting to try and compile and test the code: the age limits are based on UK film ratings. U, 12A, 15 and 18 are implemented.</p>
<p>Cheers,</p>
<p>~NomadicAquatic</p>
<p>The code:</p>
<pre><code>/* Future improvements:
* 1) Define maximum film title length as a global constant
* a) Would impact: Class Film, DisplayNowShowing() column width, GenerateNowShowingArray();
* 2) Define as external global constant the acceptabe age limits, and their assosciated numeric age limit to allow for implementation in regions with different classification systems.
* a) Would impact: Film.InputAge(), GenerateNowShowingArray(),
* 3) Define maximum films showing as external global constant
* a) Would impact GenerateNowShowingFile()
* 4) Create adjustable filepath.
* 5) Backup NowShowing.txt before deletion
* 6) Implement password check for admin ChooseMovie() break.
* 7) Refactor movieList array to be indexed from 1, to remove need to subtract 1 from all uses of the array.
* 8) Rebuild administrative function to allow editing of currently showing movies, rather than strictly rebuilding every time from scratch.
* 9) GUI
*/
using System;
using System.IO;
using System.Collections.Generic;
/// <summary>
/// A program to manage checking if a guest is old enough to attend a movie.
/// Stores current movies showing in a file NowShowing.txt, located in the same dirrectory as the program.
/// Allows system administrator to generate a new list of movies.
/// </summary>
class MovieAgeCheck
{
/// <summary>
/// Class of type 'Film'
/// Used during the generation of the NowShowing.txt file, and generating a working array of the current films.
/// </summary>
class Film
{
//constants local to class
private readonly int maxFilmLength = 30; //Maximum characters in the film title. If changed, also change in DisplayFilmList() WriteLine column width.
private readonly char[] forbidinText = new char[] { '*' }; //'*' banned due to use in file system.
//key members
private string filmName;
private string ageLimit;
//Functions relating to the initialization of the class members.
/// <summary>
/// Method to assign a film title to Film.filmName.
/// </summary>
public void InputName()
{
string inputString;
do
{
Console.Write("Please enter film name: ");
inputString = Console.ReadLine().Trim();
string inputStringTest = inputString;
foreach (char f in forbidinText)
{
foreach (char c in inputStringTest)
{
if (c == f)
{
Console.WriteLine($"You have entered a forbidin character: {f}");
inputString = "";
break;
};
};
}
if (inputString.Length > maxFilmLength)
{
Console.WriteLine($"The maximum film title lenght is {maxFilmLength} characters.");
inputString = "";
}
} while (inputString == "");
filmName = inputString;
}
/// <summary>
/// Method to assign a film age rating to Film.ageLimit.
/// </summary>
public void InputFilmAge()
{
string inputString;
bool inputValid = false;
do
{
Console.Write($"Please enter the age restriction for {filmName}: ");
inputString = Console.ReadLine().Trim().ToUpper();
switch (inputString)
{
case "U":
case "12A":
case "15":
case "18":
inputValid = true;
break;
default:
Console.WriteLine($"{inputString} is an invalid age restriction. Valid age restrictions are:");
Console.WriteLine("\"U\" (Unrestricted), 12A (12 unless accompanied by parent), 15, or 18.");
break;
}
} while (!inputValid);
ageLimit = inputString;
}
//funcions relating to the accessing of class members.
/// <summary>
/// Returns Film.filmName. Will throw exception if filmName is not innitialized.
/// </summary>
/// <returns>string Film.filmName</returns>
public string FilmName()
{
if (filmName == null)
{
throw new Exception("Attempted to access an uninitialized film name.");
}
return filmName;
}
/// <summary>
/// Returns Film.ageLimit. Will throw exception if ageLimit not innitialized.
/// </summary>
/// <returns>string Film.ageLimit</returns>
public string AgeLimit()
{
if (ageLimit == null)
{
throw new Exception("Attempted to access an uninitialized age restriction.");
}
return ageLimit;
}
/// <summary>
/// Function to obtain derived string containing both FilmName and AgeLimit, separated by '*' character.
/// </summary>
/// <returns>string in form "filmName*ageLimit"</returns>
public string FilmStorageString()
{
string film;
film = FilmName() + "*" + AgeLimit();
return film;
}
}
/// <summary>
/// Method to run the program initialization sequence.
/// Checks for existing film list file, if none immediatelly begin generation method.
/// Prints current film list to screen, asks user to confirm, regenerate, or terminate program.
/// If file does not contain appropriate strings, catches exception from method GenerateNowShowingArray, and terminates program.
/// </summary>
/// <param name="shutdown">If true, terminates program</param>
/// <returns>string["Film Title","Age limit"]</returns>
static string[,] InitializeAgeCheck(out bool shutdown)
{
string[,] nowShowingArray;
do
{
if (!File.Exists(@"NowShowing.txt")) CreateNowShowingFile();
try
{
nowShowingArray = GenerateNowShowingArray();
}
catch (Exception)
{
Console.WriteLine("Invalid NowShowing.txt\nPlease contact system administrator.");
shutdown = true;
return null;
}
Console.WriteLine("Currently showing:");
DisplayNowShowing(nowShowingArray);
}while(!RegenerateList(out shutdown));
Console.Clear();
return nowShowingArray;
}
/// <summary>
/// Prompt for admin to begin user program sequence, regenerate now showing NowShowing.txt file, or shutdown system.
/// </summary>
/// <param name="shutdown">If true, terminates program</param>
/// <returns>TRUE to begin main program, otherwise returns FALSE</returns>
static bool RegenerateList(out bool shutdown)
{
char choose;
do
{
Console.Write("Would you like to use this list of movies ('U'), create a new list('N'), or Shutdown('S')? ");
choose = Console.ReadLine().ToUpper()[0];
if (choose == 'N')
{
string confirm;
Console.Write("Are you sure you want to delete the current file and generate a new list?\nType 'delete' to continue:");
confirm = Console.ReadLine().ToLower();
if (confirm == "delete") //string to confirm deletion. Change prompt above if string chaged.
{
File.Delete(@"NowShowing.txt");
}
else choose = ' '; //assignes char other than 'U','N', or 'S' to ensure reloop of outer do..while loop.
}
shutdown = choose == 'S';
} while (choose != 'U' && choose != 'N' && choose != 'S');
return choose == 'U';
}
/// <summary>
/// Itterates through entire link of working string to display currently active film list.
/// </summary>
/// <param name="list">string["Film Title","Age limit"]</param>
static void DisplayNowShowing(string[,] list)
{
for (int i = 0; i < list.GetLength(0); i++)
{
Console.WriteLine($"{i + 1,1}:{list[i, 0],-30}{list[i, 1]}");
}
}
/// <summary>
/// Reads NowShowing.txt and converts to a two dimensional string array
/// </summary>
/// <returns>string[,] in form [FilmName,AgeLimit]</returns>
static string[,] GenerateNowShowingArray()
{
var filmsList = new List<string>();
StreamReader read = new StreamReader($"NowShowing.txt");
int currentLine = 0;
while (!read.EndOfStream)
{
string line = read.ReadLine();
filmsList.Add(line);
currentLine++;
}
var filmsArray = new string[filmsList.Count,2];
//Splits raw string from file at character '*'
for (int i = 0; i < filmsList.Count; i++)
{
filmsArray[i,0] = filmsList[i].Split('*')[0];
filmsArray[i,1] = filmsList[i].Split('*')[1];
if (filmsArray[i,0].Length > 30)
{
throw new Exception("Invalid NowShowing.txt");
}
switch (filmsArray[i,1])
{
case "U":
case "12A":
case "15":
case "18":
break;
default:
throw new Exception("Invalid NowShowing.txt");
}
}
read.Close();
return filmsArray;
}
/// <summary>
/// Walk administrator through creation of a new NowShowing.txt
/// Contains const to limit number of films showing.
/// </summary>
static void CreateNowShowingFile()
{
var films = new List<Film>();
const int maxFilmsShowing = 15;
const char breakChar = '#';
Console.Clear();
Console.WriteLine("Please enter the films currently showing.");
Console.WriteLine($"The maximum number of films is {maxFilmsShowing}.");
Console.WriteLine($"Enter {breakChar} to finish.");
for (int i = 0; i < maxFilmsShowing; i++)
{
Film f = new Film();
Console.WriteLine($"Film {i+1}: ({breakChar} to end)");
f.InputName();
if (f.FilmName()[0] == breakChar) break;
f.InputFilmAge();
films.Add(f);
}
StreamWriter write = new StreamWriter(@"NowShowing.txt");
for (int i = 0; i < films.Count; i++)
{
write.WriteLine(films[i].FilmStorageString());
}
write.Close();
}
/// <summary>
/// User selects film from displayed list of currently showing films.
/// Entering "*admin" will leave method and reenter initialization method.
/// </summary>
/// <param name="list">string[,] in format [FilmName,AgeLimit]</param>
/// <param name="kill">when true will exit user interface method</param>
/// <returns>int user film selection index</returns>
static int ChooseMovie(in string[,] list, out bool kill)
{
int movieSelection = 0;
do
{
kill = false;
Console.Write("Please enter the number of the film you wish to see: ");
try
{
string input = Console.ReadLine().Trim().ToLower();
if (input == "*admin")
{
kill = true;
return movieSelection = 0;
}
movieSelection = int.Parse(input);
}
catch (Exception)
{
Console.WriteLine("Please enter numbers only.");
}
if (movieSelection > list.GetLength(0) || movieSelection <= 0)
{
Console.WriteLine($"Please enter a movie selection betwee 1 and {list.GetLength(0)}");
}
} while (movieSelection <=0 || movieSelection > list.GetLength(0));
return movieSelection;
}
/// <summary>
/// Checks user entered age against classification of film selected
/// </summary>
/// <param name="list">string[,] in format [FilmName,AgeLimit]</param>
/// <param name="selection"></param>
static void ConfirmAge(string[,] list, int selection)
{
const int maxAge = 125; //This is the maximum user enterable age.
var ageLimit = (list[selection - 1, 1]) switch
{
"U" => 0,
"12A" => 12,
"15" => 15,
"18" => 18,
_ => throw new Exception("Something has gone wrong with the list of movies. Please contact staff"),
};
//No need for explicit check for Unrestricted rated movie. Immediatelly return from method.
if(ageLimit == 0)
{
Console.WriteLine($"The film {list[selection - 1, 0]} is suitable for all ages!\nPlease enjoy the show!");
return;
}
int userAge;
do
{
Console.Write("Please enter your age: ");
try
{
userAge = int.Parse(Console.ReadLine().Trim());
}
catch (Exception)
{
Console.WriteLine("Please enter numbers only.");
userAge = -1;
}
} while (userAge <= 0 || userAge > maxAge);
if(userAge < ageLimit)
{
Console.WriteLine($"I'm sorry, you are to yougn to see {list[selection - 1, 0]}.\nPlease select a different movie to watch today.");
}
else
{
Console.WriteLine($"Please enjoy today's showing of {list[selection - 1, 0]}!");
}
}
/// <summary>
/// Primary user facing method. Displayes currently showing films using DisplayNowShowing(). Calls ChooseMovie() and ConfirmAge() for user prompts.
/// Pauses after each user awaiting any key, then clears console and repeats.
/// </summary>
/// <param name="moviesList">string[,] in format [FilmName,AgeLimit]</param>
static void CheckAges(in string[,] moviesList)
{
bool quitChecking;
do
{
Console.WriteLine("Welcome to out Multiplex.");
Console.WriteLine("We are currently showing:");
DisplayNowShowing(moviesList);
int selectedMovie = ChooseMovie(moviesList, out quitChecking);
if (quitChecking) break;
ConfirmAge(moviesList, selectedMovie);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
Console.Clear();
} while (!quitChecking);
Console.Clear();
}
static void Main()
{
string[,] list; //Working array of current films list.
bool shutdown; //Flag to terminate program.
do
{
list = InitializeAgeCheck(out shutdown);
if (shutdown) break;
CheckAges(list);
} while (!shutdown);
Console.WriteLine("Shutting down system.");
Console.ReadKey();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T17:59:14.723",
"Id": "499444",
"Score": "0",
"body": "Please remove any commented out code, it indicates that the code is not ready to be reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T18:06:51.183",
"Id": "499446",
"Score": "0",
"body": "@pacmaninbw Commented out code removed, as it was simply for my own reference while learning so I could compare my implementation to the implementation recommended by Visual Studio IDE. Still learning StackExchange etiquette, thanks for the tip!"
}
] |
[
{
"body": "<p>Uh, the bottom line to the proceeding is at the bottom. Or, read through if you like suspense.</p>\n<p><strong>C#8 In a Nutshell</strong></p>\n<p>Excellent. Get an awareness of the scope of the language. Then as opportunity presents, use the book for a good overview and quick start for specific topics</p>\n<hr />\n<p><strong>It is 428 lines, including comments</strong></p>\n<p>Beware writing too cute or too clever code for brevity's sake.</p>\n<p>Work very hard at making comments complement the code. Focus on the <em>why</em> of the code. Assume the reader understands C#, in this case.</p>\n<hr />\n<p><strong>the "///" comment blocks</strong></p>\n<p>The rich collection of tags, like <code><summary></code>, are intended for generating documentation, complete with links. Somewhere in MSDN there is complete explanation of this.</p>\n<hr />\n<p><strong>one commented out code block</strong></p>\n<p>The road to hell is paved with commented out code. This is the very big clue that it is time to use version control. IMHO everyone uses GIT because everyone uses GIT. I've found Mercurial is easer to use. There are others. But pick one and start using it. Version control allows one to be bold with experimentation, changes, and fixes.</p>\n<hr />\n<hr />\n<pre><code> private readonly int maxFilmLength = 30; //Maximum characters in the film title. If changed, also change in DisplayFilmList() WriteLine column width.\n</code></pre>\n<p>The variable name is obvious - half of the comment is not needed.</p>\n<p><code>If changed, also change</code> - This is a code smell (i.e. something might be wrong). Make a public getter property of/for <code>maxFilmLength</code>.</p>\n<hr />\n<hr />\n<pre><code>public class Film {\n public string FilmName() {\n</code></pre>\n<p><code>Name()</code>, not <code>FilmName()</code>. It's containing class gives the context needed.</p>\n<hr />\n<hr />\n<pre><code>public string FilmName()\n {\n if (filmName == null)\n {\n throw new Exception("Attempted to access an uninitialized film name.");\n }\n return filmName;\n }\n</code></pre>\n<p>Set properties in a constructor. Then you'll never have to check for null. For strings prefer <code>String.Empty</code> over <code>null</code>. Because:</p>\n<pre><code>string NameNull; // initializes to null\nstring NameEmpty = String.Empty; \n\nNameNull.Value(); // throws an exception\nNameEmpty.Value(); // does not throw and exception\n</code></pre>\n<p>Saves exceptions for things you can do nothing about. Instead do this in a constructor:</p>\n<pre><code> this.Name = passedInArgumentName ?? String.Empty; // null coalesce. C# in a nutshell is your friend.\n</code></pre>\n<p>or at the very least:</p>\n<pre><code> if(this.Name == null) this.Name = String.Empty;\n</code></pre>\n<p>Why test for null on every <code>Name</code> call when you can set it once and forget it?</p>\n<hr />\n<hr />\n<p><strong>Console.WriteLine($"You have entered a forbidin character: {f}");</strong></p>\n<p>Read about the <code>String</code> class in MS documentation. You'll find methods and properties that will significantly simplify string validation.</p>\n<p>Displaying this error message without telling what is forbidden or valid is just cruel.</p>\n<hr />\n<hr />\n<p><strong>What's in a name?</strong></p>\n<pre><code>public class MovieAgeCheck () { \n public void InputFilmAge()\n {\n string inputString;\n bool inputValid = false;\n</code></pre>\n<p><code>MovieAgeCheck</code> - 'MovieAgeRestriction<code> or MovieViewerRestrictions</code> (if it is about more than just age). It is about viewer age restrictions, not how old the movie is.</p>\n<p>The method name says we're getting the age of the film. <code>InputAgeRestriction</code> is better. Again, the containing class should be enough to understand we're talking about a film. If not, the method might be in the wrong class.</p>\n<p><code>inputString</code> - <code>viewerRestrictionCode</code> or <code>RestrictionCode</code>. It is a code being entered, not an actual age as in "happy birthday!, age.</p>\n<p>Everything the user types is "input". "Input.." is not helpful as a variable name. As an <em>action</em> verb in the method name, that's OK.</p>\n<p>Do not use the data type in variable names. The reader knows it's a string. <strong>It is far more important to name things for what they are in the "film viewer age restriction" domain.</strong></p>\n<p><code>inputValid</code> - <code>isValid</code> or <code>isValidName</code>. Starting boolean names with "is" <code>isConvential</code>.</p>\n<p><strong>Context, all the way down</strong></p>\n<p>Given the suggested name changes:</p>\n<p>The CLASS name tells me it is about viewing restrictions of a movie\nThe METHOD name tells me it is about ( movie viewing restriction, implied) age.\nThe VARIABLE name tells me it is about (for movie viewing restriction age, implied) code representing said restriction.</p>\n<hr />\n<hr />\n<p><strong>class nesting</strong></p>\n<p>Does your IDE generate a shell for <code>public static void Main()</code>? Main should be where the movie program object(s) get instantiated and then probably a "main loop" for user prompting and results displaying.</p>\n<p>Do not nest your classes in <code>MovieAgeCheck</code>, especially <code>Main</code>. I see no compelling reason and nesting technical detail becomes like self flagellation for the beginner.</p>\n<hr />\n<hr />\n<p><strong>Group Think</strong></p>\n<p>Think about code grouped into major functionality. This is the beginnings of classes and good code organization generally.</p>\n<p>Generally, write code on a function by function basis and then call this code. Do not write pieces of like-functionality spread within long in-line code dumps.</p>\n<p><strong>Possible function groups</strong></p>\n<p><code>Film.ToString()</code> - output a formatted string/lines of string, of it's own data.</p>\n<p>The text file - create a collection of <code>Film</code> objects. The text file becomes a <code>string[,]</code>. It should be an array of <code>Film</code> objects.</p>\n<p>Data validation - <code>Film</code> constructor calls validation for each parameter. Each film property has a corresponding validate method in the film class. User entered data will be passed to <code>Film</code> constructor. I'm imagining a public method or property for the message.</p>\n<p>The text/data file - probably a separate class because it is a clearly different thing from <code>Film</code>s and <code>AgeRestrictions</code>. With methods to fetch from file and another to pass the plain text as Film objects. Your plans for future changes will be helped if this is an independent class.</p>\n<p><code>Film</code> - a basic film object: name, restriction code, validation for same.</p>\n<ul>\n<li>ToString(), returns formatted line(s) of this object's data.</li>\n<li>should not have to call the textFile object for anything.</li>\n<li>should not have to call MovieAgeCheck object for anything.</li>\n</ul>\n<p><code>MovieAgeCheck</code> - Has methods that are called in the various "main loop" places.</p>\n<ul>\n<li><code>ToString()</code> - calls <code>Film.ToString()</code> of all Film objects, in a loop</li>\n<li>Does not create film objects. Film constructor does that</li>\n<li>Does not fetch the text file. Calls textFile object to do it.</li>\n</ul>\n<p><strong>EDIT</strong></p>\n<p><strike> - Does not create Film objects from textFile. TextFile object passes its data to Film constructor.</strike></p>\n<ul>\n<li>Coordinates Film object creation from textFile raw data. Asks (calls) textFile object for the <code>string[,]</code> raw data and (in a loop probably) then calls Film constructor, passing each "raw film data" element in turn.</li>\n</ul>\n<p><strong>end Edit</strong></p>\n<ul>\n<li>Does not validate Film objects. Film constructor does it.</li>\n<li>Calls data file object method(s) to: fetch text file, return an array of Film objects.</li>\n<li>Calls <code>Film</code> constructor passing in user entered data</li>\n</ul>\n<p><code>Main</code> - Has the prompt-fetch-display loop.</p>\n<ul>\n<li>Instantiates a <code>MovieAgeCheck</code> object.</li>\n<li>Displays error messages but does not generate them.</li>\n<li>passes user entered data to <code>MovieAgeCheck</code></li>\n<li>has loop control structure to continue entry, stop and display error message, et cetera.</li>\n</ul>\n<hr />\n<hr />\n<p>Here is a rough cut</p>\n<p><strong>NOTE</strong>: pseudocode. Do not assume this is compile-able and logically perfect.</p>\n<pre><code>public static Main() {\n MovieAgeCheck Checker = new MovieAgeCheck();\n\n Checker.GetMovies(); // textFile object called in here\n console.WriteLine(Checker.ToString(); // display all movies\n\n bool keepGoing = true;\n bool isAgeAppropriate;\n\n while(keepGoing) do {\n // prompt for data\n isAgeAppropriate = Checker.Validate(name, code, ...); \n \n if(! isAgeAppropriate) {\n // whatever\n console.WriteLine(Checker.ErrorMessage());\n }\n \n //prompt to keepGoing\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T02:46:49.157",
"Id": "499474",
"Score": "0",
"body": "I'm working through your amazing answer one at a time. Some makes sense, some I'm having to parse through bit by bit.\n\nTwo specific questions, possibly out of the scope of this forum:\n1) If I choose a version control system now, how interchangeable are they; how easy to pivot to a different system if needed later?\n2) When working through tutorial's like this as a beginner, do you feel there is more value to revisit the program and refactor it, or to move on to the next concept and exercise, and put the learning/feedback into practice on the next program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:21:37.397",
"Id": "499522",
"Score": "3",
"body": "Revisit and Refactor is always fun, because you can see how much you have learned. revisiting and refactoring code you've written previously may give you the idea for an application that could help many people. I have a running project that I visit once in a while that I started in school. it's a game, but same concept. if you use source control, you can see all the changes that you made from the beginning which is fun too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T06:13:21.003",
"Id": "499657",
"Score": "0",
"body": "*If I choose a version control system now, how interchangeable are they*. When researching, some years ago, not. But use a \"distributed\" model tool - Git or Mecurial. TL;DR. Workaround Anecdote: Our Team used Subversion. I wanted my own repository for independent experimentation, subversion can't do that - it is not a \"distributed\" system. So happens Subversion and Mercurial metadata (buried in your source code folders) can be mutually ignored. Was not difficult to keep straight because our team versioning plan kept branching sane."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T06:37:22.440",
"Id": "499659",
"Score": "0",
"body": "Refactoring is the active process of tweaking as you write a program. The impulse is maintaining design and structure, changing methodically as needed to facilitate new code and editing generally, while keeping and improving overall quality. The book [*Refactoring* by Martin Fowler](https://martinfowler.com/books/refactoring.html) is the seminal word on the subject. He defines many step by step \"refactorings\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T06:55:24.420",
"Id": "499660",
"Score": "0",
"body": "Pick a VC tool and learn to use it well. Forget about \"what if\". Available helper tools may help you choose. For example \n TortoiseSVN for subversion and TortoiseHg for Mercurial come to mind. The Visual Studio IDE has integrate-aible tools."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:57:22.253",
"Id": "253284",
"ParentId": "253269",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "253284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T17:02:06.053",
"Id": "253269",
"Score": "2",
"Tags": [
"c#",
"beginner",
"object-oriented"
],
"Title": "A program to check the age of a movie attendee (C# Yellow Book excersize)"
}
|
253269
|
<p>Django implements a <a href="https://docs.djangoproject.com/en/3.1/topics/checks/" rel="nofollow noreferrer">System Check</a> framework that enables apps to perform checks on settings, runtime, etc. When creating an app, one can plug checks with the framework by following some requirements, one of them being how errors are reported.</p>
<p>The integrations are actually ok, but the error management system is a bit too manual. The recommendation is that errors are created from base classes of <a href="https://github.com/django/django/blob/2c5d6dc44779448de1497f32c925c96975fae461/django/core/checks/messages.py#L9" rel="nofollow noreferrer">CheckMessage</a>, such as <a href="https://github.com/django/django/blob/2c5d6dc44779448de1497f32c925c96975fae461/django/core/checks/messages.py#L68" rel="nofollow noreferrer">Error</a>. It's also available for warnings, info, etc. Here's an example:</p>
<pre><code>Error(
'an error',
hint='A hint.',
obj=checked_object,
id='myapp.E001',
)
</code></pre>
<p>What bothers me with this is that error codes are tracked manually and spread out through the code. If two developers are working in the same rep, it'll be easy to conflict error codes, something that could easily pass code reviews, merge conflicts, etc. Initially I thought that this could only be for tutorial purposes, but turns out <a href="https://github.com/django/django/blob/2c5d6dc44779448de1497f32c925c96975fae461/django/contrib/auth/checks.py#L34" rel="nofollow noreferrer">that's actually how they do it</a>.</p>
<p>The problem with this approach is the numbering system. The <code>id</code> is prefixed with the app name, which is OK, followed by a level indication (e.g. <code>E</code> for error), both of which are easily trackable. But the numbering system can easily generate a conflict (e.g. two developers create the same code in different modules of the same app).</p>
<p>I wanted to have an approach that would enable the error codes to be generated serially and in a centralized way, so that the conflicts are avoided, but one is stuck with this system behind the curtains. Here's what I tried:</p>
<pre><code>from collections import defaultdict
from django.core.checks import messages
from django.core.checks import CheckMessage
class MessageRegistry(object):
""" Keeps a registry of Django CheckMessages identifiers.
Django implements a System Check framework used for validating projects. The
framework can be used by third-parties to improve on Django's functionality,
while at the same time implementing checks of the same kind.
However, the error reporting system relies on hardcoded message identifiers
that must be tracked throughout the code. This is an anti-paradigm, since it
implies that, sooner or later, codes will collide, possibly without anyone
noticing (e.g. easily missed in code reviews).
A MessageRegistry keeps track of registered messages, in order, so that
their identifiers are generated in sequence. This is useful to prevent error
codes from colliding within the same app domain.
This class is mostly used internally, and the methods register, make, and
get_code are the preferred way to consume the API. That's because this is a
helper class, since the registry is actually handled by a default instance
of this class.
Although this class implements the methods with the same names as the API,
the difference is that the methods act on the instance they are bound to
and the API entry points act on a default instance.
"""
levels = {
messages.DEBUG: 'D',
messages.INFO: 'I',
messages.WARNING: 'W',
messages.ERROR: 'E',
messages.CRITICAL: 'C'
}
def __init__(self):
self.counters = defaultdict(lambda: defaultdict(int))
self.codes = defaultdict(lambda: defaultdict(str))
def _level_identifier(self, level):
# Make sure the given level is OK
if level not in self.levels:
raise KeyError(f'Unrecognized message level "{level}" registered as a message')
return self.levels[level]
def register(self, code, app, level):
""" Registers a message code.
Given a code and an (app, level) pair, this method register the message
and increments the corresponding counter, assigning it an identifier
corresponding to the current counter position. If the given code already
exists, KeyError is raised. Otherwise the counter is incremented and the
identifier is generated for when the code is referenced, either through
get_code or make. The method doesn't return anything.
"""
# Codes can only be registered once
if code in self.codes:
raise KeyError(f'The message code "{code}" is already registered')
# Count the registrations, segregated by app and level
self.counters[app][level] += 1
# Register an accessor
self.codes[code] = level, f'{app}.{self._level_identifier(level)}{self.counters[app][level]:03}'
def get_code(self, code):
""" Returns the generated code for a given message code.
The message code must have previously been registered. If it's not,
KeyError is raised.
"""
if code not in self.codes:
raise KeyError(f'Unrecognized code "{code}" could not be mapped to a message')
return self.codes[code]
def make(self, code, message, hint, object=None):
""" Creates a CheckMessage using the code as a reference.
The code argument is a code that has previously been registered. If the
code is not found, KeyError is raised.
The rest of the arguments are passed verbatin to the CheckMessage
initializer, with the difference that the code is used to query the
level (e.g. warning, error, etc) and the generated code reference is
used as the identifier for the message.
"""
level, reference = self.get_code(code)
return CheckMessage(level, message, hint, object, reference)
# Global registry
_message_registry = MessageRegistry()
def register(code, app, level):
""" Registers a message with a given code.
The (app, level) pair becomes associated with that code and is used to
generate the message ID when the code is referenced. When a message is
registered, a counter is incremented progressively, so message codes are
sequential.
If the same code is registered more than once, KeyError is raised,
effectively preventing duplications.
"""
global _message_registry
_message_registry.register(code, app, level)
def make(code, message, hint, object=None):
""" Creates a messages from a code and some extra parameters.
The code must be registered or KeyError is raised. Otherwise, if the code
was previously registered, the message identifier is generated from the
(app, level) pair given earlier.
"""
global _message_registry
return _message_registry.make(code, message, hint, object)
</code></pre>
<p>This can be used by creating a, say, <code>errors.py</code> file where every contributor can register errors in an append-only fashion. Because the file is append-only, conflicts are easy to track. Here's an example:</p>
<pre><code>from djutils import messages
messages.register('D5A88CC0B3EC', 'djutils', checks.ERROR)
messages.register('0A25CEA3F2C3', 'djutils', checks.WARNING)
messages.register('A84DEF26F5A0', 'djutils', checks.INFO)
messages.register('5DE1BAF3E498', 'djutils', checks.ERROR)
messages.register('FA9544893762', 'djutils', checks.DEBUG)
</code></pre>
<p>Referencing the messages is also easy:</p>
<pre><code>messages.make('D5A88CC0B3EC', 'Something failed', 'Try last minute pressure', self)
</code></pre>
<p>The registration seems a bit redundant because the pairs (app, level) don't appear significant, but keep in mind that a counter is being tracked. The identifiers can be any convention, but in this case I use the last few digits of <code>uuidgen</code> because those are highly unique and easy to generate.</p>
<p>Upsides of this approach:</p>
<ul>
<li>Message codes are sequential, avoiding conflicts, as initially intended</li>
<li>It's easy to make the numbering immutable from code reviews; e.g. it's easy to notice that a message was deleted. If a message is not being used anymore, it should stick around, so that the numbering is kept. Because the IDs are unreadable, it also disincentivizes changes, as it should, to keep the list deterministic</li>
<li>It's easy to maintain; e.g. developers generate a code, use it, and move on. If a new code is needed, they register another one.</li>
<li>It abstracts away Django's details for message creation</li>
<li>It works even if the the module is <a href="https://python-reference.readthedocs.io/en/latest/docs/functions/reload.html" rel="nofollow noreferrer">reloaded</a>, since the registry is cleaned and the registrations occur again and in the same order</li>
</ul>
<p>Downsides:</p>
<ul>
<li>When the message code is being referenced (with <code>messages.make</code>) you can't tell the level (error, info, debug, etc) directly from the reference. If you need to know that, you need to check the code in the registry file</li>
<li>It feels a bit anti-paradigmatic. Managing error codes is not imperative in terms of functionality, only documentation, which is what message codes are most useful for</li>
<li>In order to know a given code order, you need to open a shell and query it with <code>get_code</code> (helper method not implemented yet), since the value is generated at runtime and you can't just read it from the source</li>
</ul>
<p>What are your thoughts?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T17:13:23.550",
"Id": "253271",
"Score": "3",
"Tags": [
"python",
"django"
],
"Title": "Handling System Check message identifiers with Django"
}
|
253271
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253131/231235">A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/q/253131/231235">G. Sliepen's answer</a>, I am trying to implement the mentioned <code>recursive_transform_reduce</code> function here.</p>
<p><strong>The usage description</strong></p>
<p>Similar to <a href="https://en.cppreference.com/w/cpp/algorithm/transform_reduce" rel="nofollow noreferrer"><code>std::transform_reduce</code></a>, the purpose of <code>recursive_transform_reduce</code> function is to apply a function (unary operation) to each element in the given range then reduce the results with a binary operation. There are four parameters in <code>recursive_transform_reduce</code> function (the version without execution policy). The first one is a input range, the second one is the initial value of reduction result, the third one is a function (unary operation) which is to apply to each element and the final one is a binary operation for reduction operation.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>recursive_transform_reduce</code> template function is as below.</p>
<pre><code>// recursive_transform_reduce implementation
template<class Container, class ValueType, class UnaryOp, class BinaryOp = std::plus<ValueType>>
requires (std::ranges::range<Container>) && (!is_elements_iterable<Container>)
constexpr auto recursive_transform_reduce(const Container& input, ValueType init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<ValueType>())
{
for (const auto& element : input) {
auto result = unary_op(element);
init = binop(init, result);
}
return init;
}
template<class Container, class ValueType, class UnaryOp, class BinaryOp = std::plus<ValueType>>
requires (std::ranges::range<Container>) && (is_elements_iterable<Container>)
constexpr auto recursive_transform_reduce(const Container& input, ValueType init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<ValueType>())
{
return std::transform_reduce(std::begin(input), std::end(input), init, binop, [&](auto& element) {
return recursive_transform_reduce(element, init, unary_op, binop);
});
}
// With execution policy
template<class ExPo, class Container, class ValueType, class UnaryOp, class BinaryOp = std::plus<ValueType>>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::range<Container>) && (!is_elements_iterable<Container>))
constexpr auto recursive_transform_reduce(ExPo execution_policy, const Container& input, ValueType init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<ValueType>())
{
for (const auto& element : input) {
auto result = unary_op(element);
init = binop(init, result);
}
return init;
}
template<class ExPo, class Container, class ValueType, class UnaryOp, class BinaryOp = std::plus<ValueType>>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::range<Container>) && (is_elements_iterable<Container>))
constexpr auto recursive_transform_reduce(ExPo execution_policy, const Container& input, ValueType init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<ValueType>())
{
return std::transform_reduce(execution_policy, std::begin(input), std::end(input), init, binop, [&](auto& element) {
return recursive_transform_reduce(execution_policy, element, init, unary_op, binop);
});
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>With <code>recursive_transform_reduce</code> function here, <code>population_variance</code> function in <a href="https://codereview.stackexchange.com/q/253131/231235">the previous question</a> can be improved as below.</p>
<pre><code>template<typename T>
concept can_calculate_variance_of = requires(const T & value)
{
(std::pow(value, 2) - value) / std::size_t{ 1 };
};
template<typename T>
struct recursive_iter_value_t_detail
{
using type = T;
};
template <std::ranges::range T>
struct recursive_iter_value_t_detail<T>
: recursive_iter_value_t_detail<std::iter_value_t<T>>
{ };
template<typename T>
using recursive_iter_value_t = typename recursive_iter_value_t_detail<T>::type;
// population_variance function implementation (with recursive_transform_reduce template function)
template<class T = double, class Container>
requires (is_recursive_sizeable<Container>&& can_calculate_variance_of<recursive_iter_value_t<Container>>)
auto population_variance(const Container& input)
{
auto mean = arithmetic_mean<T>(input);
return recursive_transform_reduce(std::execution::par,
input, T{}, [mean](auto& element) {
return std::pow(element - mean, 2);
}, std::plus<T>()) / recursive_size(input);
}
</code></pre>
<p>Note: <code>recursive_iter_value_t</code> is referred from <a href="https://stackoverflow.com/a/65210724/6667035">How to solve requires clause is incompatible</a>.</p>
<p>The improved version of <code>arithmetic_mean</code> function implementation:</p>
<pre><code>template<typename T>
concept is_recursive_reduceable = requires(T x)
{
recursive_reduce(x, T{});
};
template<typename T>
concept is_recursive_sizeable = requires(T x)
{
recursive_size(x);
};
template<class T = double, class Container> requires (is_recursive_sizeable<Container>)
auto arithmetic_mean(const Container& input)
{
return (recursive_reduce(input, T{})) / (recursive_size(input));
}
</code></pre>
<p>The implementation of <code>recursive_reduce</code> function:</p>
<pre><code>template<class T, class ValueType, class Function = std::plus<ValueType>>
auto recursive_reduce(const T& input, ValueType init, const Function& f)
{
return f(init, input);
}
template<class Container, class ValueType, class Function = std::plus<ValueType>>
requires is_iterable<Container>
auto recursive_reduce(const Container& input, ValueType init, const Function& f = std::plus<ValueType>())
{
for (const auto& element : input) {
auto result = recursive_reduce(element, ValueType{}, f);
init = f(init, result);
}
return init;
}
</code></pre>
<p>The <code>recursive_size</code> function implementation:</p>
<pre><code>// recursive_size implementation
template<class T> requires (!std::ranges::range<T>)
auto recursive_size(const T& input)
{
return 1;
}
template<class T> requires (!is_elements_iterable<T> && std::ranges::range<T>)
auto recursive_size(const T& input)
{
return input.size();
}
template<class T> requires (is_elements_iterable<T>)
auto recursive_size(const T& input)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
</code></pre>
<p>The test of <code>population_variance</code> function is like:</p>
<pre><code>std::vector<double> test_vector{ 1, 2, 3, 4, 5 };
std::cout << "recursive_size of test_vector: " << recursive_size(test_vector) << std::endl;
std::cout << "population_variance of test_vector: " << population_variance(test_vector) << std::endl;
// std::vector<std::vector<double>> case
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
std::cout << "recursive_size of test_vector2: " << recursive_size(test_vector2) << std::endl;
std::cout << "population_variance of test_vector2: " << population_variance(test_vector2) << std::endl;
auto test_vector3 = n_dim_container_generator<10, std::vector, decltype(test_vector)>(test_vector, 3);
std::cout << "recursive_size of test_vector3: " << recursive_size(test_vector3) << std::endl;
std::cout << "population_variance of test_vector3: " << population_variance(test_vector3) << std::endl;
</code></pre>
<p>Then, the execution output:</p>
<pre><code>recursive_size of test_vector: 5
population_variance of test_vector: 2
recursive_size of test_vector2: 15
population_variance of test_vector2: 2
recursive_size of test_vector3: 295245
population_variance of test_vector3: 2
</code></pre>
<p>Another test of <code>population_variance</code> function:</p>
<pre><code>std::vector<double> test_vector{ 1, 2, 3 };
std::cout << "recursive_size of test_vector: " << recursive_size(test_vector) << std::endl;
std::cout << "population_variance of test_vector: " << population_variance(test_vector) << std::endl;
// std::vector<std::vector<double>> case
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
std::cout << "recursive_size of test_vector2: " << recursive_size(test_vector2) << std::endl;
std::cout << "population_variance of test_vector2: " << population_variance(test_vector2) << std::endl;
auto test_vector3 = n_dim_container_generator<10, std::vector, decltype(test_vector)>(test_vector, 3);
std::cout << "recursive_size of test_vector3: " << recursive_size(test_vector3) << std::endl;
std::cout << "population_variance of test_vector3: " << population_variance(test_vector3) << std::endl;
</code></pre>
<p>The execution output of the above test code:</p>
<pre><code>recursive_size of test_vector: 3
population_variance of test_vector: 0.666667
recursive_size of test_vector2: 9
population_variance of test_vector2: 0.666667
recursive_size of test_vector3: 177147
population_variance of test_vector3: 0.666667
</code></pre>
<p><a href="https://godbolt.org/z/86ohjd" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/253131/231235">A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am trying to implement a recursive_transform_reduce function here and use it in <code>population_variance</code> function.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>Please check the implementation of <code>recursive_transform_reduce</code> function and if there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Ensure <code>init</code> is only used once</h1>\n<p>Since you pass the value of <code>init</code> to recursive calls to <code>recursive_transform_reduce()</code>, the value of <code>init</code> ends up being added potentially more than once to the output. For example:</p>\n<pre><code>recursive_transform_reduce(std::vector<std::vector<int>>{{},{}}, 1, std::identity())\n</code></pre>\n<p>This will return <code>3</code> instead of <code>1</code>. To fix it, instead of passing <code>init</code>, pass <code>ValueType{}</code> to the recursive call. Although of course that assumes there is a default constructible null element.</p>\n<h1>Consider using advice given in earlier answers</h1>\n<p>I think you should follow the advise given to you in <a href=\"https://stackoverflow.com/a/65210724/5481471\">this answer</a> to your question you reference about a recursive <code>iter_value_t</code>:</p>\n<ul>\n<li>Have one unconstrained template</li>\n<li>Avoid the <code>requires</code> clause if possible by using the concept name instead of <code>class</code> in the template parameter list</li>\n</ul>\n<p>Also again, both your templates implement do a <code>std::transform_reduce()</code>, you just wrote out one of them manually. But it should just be one of the variants that has to do the heavy lifting, the other can just deal with a single value. Then it becomes:</p>\n<pre><code>template<class Input, class T, class UnaryOp, class BinaryOp = std::plus<T>>\nconstexpr auto recursive_transform_reduce(const Input& input, T init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<T>())\n{\n return binop(init, unary_op(input));\n}\n\ntemplate<std::ranges::range Input, class T, class UnaryOp, class BinaryOp = std::plus<T>>\nconstexpr auto recursive_transform_reduce(const Input& input, T init, const UnaryOp& unary_op, const BinaryOp& binop = std::plus<T>())\n{\n return std::transform_reduce(std::begin(input), std::end(input), init, binop, [&](auto& element) {\n return recursive_transform_reduce(element, T{}, unary_op, binop);\n });\n}\n</code></pre>\n<p>I also changed the names of the types to match <code>std::transform_reduce</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:28:30.200",
"Id": "253280",
"ParentId": "253272",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253280",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T19:16:18.040",
"Id": "253272",
"Score": "2",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
253272
|
<p>I am new to Python, the script below provides the desired output and completes the task as required. I would like to know if there is any better ways of completing what I have written and any ways of speeding up the process?</p>
<p>Thank you for looking.</p>
<pre><code>from netmiko import ConnectHandler
import sys
# **************************************************************** Functions ***
def add_traffic( traffic, detail_interface ):
global disable
global traffic_count
interface = detail_interface.split()
if traffic.strip() == no_traffic:
disable.append( [ interface[ 0 ], traffic.strip() ] )
return interface[ 0 ]
else:
traffic_split = traffic.split( ', ' )
if check_traffic_date( traffic_split[ 0 ] ) == bool( True ):
disable.append( [ interface[ 0 ], traffic.strip() ] )
return interface[ 0 ]
def check_traffic_date( traffic ):
traffic = traffic.strip().split( ' ' )
data_period = traffic[ 2 ]
if data_period.find( 'y' ) > 0:
years = data_period.split( 'y' )
years = int( years[ 0 ] )
if years >= 1:
return bool( True )
elif data_period.find( 'w' ) > 0:
weeks = data_period.split( 'w' )
weeks = int( weeks[ 0 ] )
if weeks >= 4:
return bool( True )
else:
return bool( False )
def check_switch( output, user_disable ):
for i in range( 0, len( output ) ):
# Ignore any interfaces that are currently connected
if output[ i ].find( '(connected)' ) != -1:
pass
# Ignore any interfaces that are disabled/shutdown
elif output[ i ].find( '(disabled)' ) != -1:
pass
# Ignore any interfaces that are disabled/shutdown
elif output[ i ].find( 'GigabitEthernet0/0' ) != -1:
pass
elif output[ i ].find( 'GigabitEthernet' ) != -1:
unused_interface = add_traffic( output[ i + 1 ], output[ i ] )
if user_disable.upper() == 'Y':
auto_disable( unused_interface )
elif output[ i ].find( 'FastEthernet' ) != -1:
unused_interface = add_traffic( output[ i + 1 ], output[ i ] )
if user_disable.upper() == 'Y':
auto_disable( unused_interface )
def auto_disable( interface ):
if str( interface ) != 'None':
config_commands = [ "int " + str( interface ), "shutdown" ]
net_connect.send_config_set( config_commands )
# **************************************************************** Main Content ***
platform = 'cisco_ios'
username = 'username'
password = 'password'
ip_hosts = open( r"ip_list.txt","r" )
# Pre-defined variables
no_traffic = "Last input never, output never, output hang never"
traffic_count = []
disable = []
# Ask whether auto disable is to be used
user_disable = input( 'Would you like to auto disable unused interfaces? (Y/N): ' )
for host in ip_hosts:
net_connect = ConnectHandler( device_type=platform, ip=host, username=username, password=password )
output = net_connect.send_command( 'show interface | include FastEthernet|GigabitEthernet|Last in' )
output = output.splitlines()
check_switch( output, user_disable )
print( '###########################################################################################' )
print( '# Cisco Command Output #' )
print( '###########################################################################################' )
for i in disable:
print( i )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T21:18:47.493",
"Id": "499460",
"Score": "0",
"body": "You have a syntax error on line 37, that I assume is a copy-paste error (`if weeks >=4:` is over-indented)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T21:19:41.497",
"Id": "499461",
"Score": "0",
"body": "Also, throughout `check_switch` you have an extra space (from the first `elif` on) in the indent, which is also a syntax error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T01:17:44.980",
"Id": "499473",
"Score": "1",
"body": "Please checkout [PEP8](https://www.python.org/dev/peps/pep-0008/), the Python style guide. Following it will make it easier for others to read your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T08:46:51.740",
"Id": "499493",
"Score": "0",
"body": "Thanks for the replies, I believe the indentation has been messed up with the copy paste.\n\nIs anyone able to provide information on the code itself, better techniques to use and anything that may make the code more efficient?"
}
] |
[
{
"body": "<h2>Avoid globals</h2>\n<p>Try deleting these:</p>\n<pre><code> global disable\n global traffic_count\n</code></pre>\n<p>and passing them in either as parameters to <code>add_traffic</code> or as members on a class.</p>\n<h2>Booleans</h2>\n<pre><code>bool( True )\n</code></pre>\n<p>is redundant and equivalent to <code>True, but you can further shorten that </code>if` to</p>\n<pre><code>if check_traffic_date(traffic_split[0]):\n</code></pre>\n<h2>Named unpacking</h2>\n<p>Consider converting</p>\n<pre><code> traffic = traffic.strip().split( ' ' )\n data_period = traffic[ 2 ]\n</code></pre>\n<p>to something like</p>\n<pre><code>foo, bar, data_period = traffic.strip().split(' ')\n</code></pre>\n<p>This works well if you understand what is expected at each position. You can splat-unpack <code>, *_</code> as the last entry if you don't care about trailing entries.</p>\n<h2>String membership</h2>\n<pre><code> if data_period.find( 'y' ) > 0:\n</code></pre>\n<p>might be a bug. If you're intent on checking whether <code>'y'</code> is in <code>data_period</code>, this should actually be <code>>= 0</code>, since <code>0</code> is a valid index.</p>\n<p>If you only care about membership,</p>\n<pre><code>if 'y' in data_period:\n</code></pre>\n<p>If you care about membership past the first position (which is what you're currently doing),</p>\n<pre><code>if 'y' in data_period[1:]:\n</code></pre>\n<h2>Return paths</h2>\n<p>Omitting a few intermediate statements,</p>\n<pre><code> if data_period.find( 'y' ) > 0:\n if years >= 1:\n return bool( True )\n\n elif data_period.find( 'w' ) > 0:\n if weeks >= 4:\n return bool( True )\n else:\n return bool( False )\n</code></pre>\n<p>doesn't do what you think it does. This actually has a tri-valued return, potentially <code>True</code>, <code>False</code> or <code>None</code>. <code>None</code> will be returned if (for example) you successfully parse <code>years</code> but <code>years == 0</code>.</p>\n<p>An easy way to fix this is</p>\n<pre><code> if data_period.find( 'y' ) > 0:\n return years >= 1\n\n elif data_period.find( 'w' ) > 0:\n return weeks >= 4\n\n return False\n</code></pre>\n<h2>Loop like a native</h2>\n<pre><code> for i in range( 0, len( output ) ):\n if output[ i ] # ...\n add_traffic( output[ i + 1 ], output[ i ] )\n</code></pre>\n<p>can be</p>\n<pre><code> for i, this_output in enumerate(output):\n if this_output # ...\n next_output = output[i + 1]\n add_traffic(next_output, this_output)\n</code></pre>\n<h2>Direct None checks</h2>\n<pre><code> if str( interface ) != 'None':\n</code></pre>\n<p>should probably be</p>\n<pre><code>if interface is not None:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T12:25:45.050",
"Id": "499879",
"Score": "1",
"body": "Thank you very much for your time and advice, really helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T18:59:58.153",
"Id": "253393",
"ParentId": "253276",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253393",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T20:44:27.063",
"Id": "253276",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Script to find and auto-disable interfaces on Cisco switches with either no traffic no traffic older than 4 weeks"
}
|
253276
|
<p><strong>Problem description:</strong> You are given a segment [568023; 569230]. Find integer within given range that has the most natural dividers. If 2 or more integers are found, return the lowest integer among them.</p>
<p><strong>Solution:</strong></p>
<pre><code>def allnums(k):
cnt = 0
for i in range(2, k // 2):
if k % i == 0:
cnt += 1
return cnt
MAX_NUM = 0
MAX = 0
for i in range(568023, 569231):
cnt = allnums(i)
if MAX < cnt:
MAX = cnt
MAX_NUM = i
print(MAX, ' ', MAX_NUM)
</code></pre>
<blockquote>
<p><strong>Output:</strong> 141 568260</p>
<p><strong>Runtime:</strong> 17s</p>
</blockquote>
<p><strong>Question:</strong> Is there any way to make this code more concise, maybe also improving its runtime? Thank you in advance.</p>
|
[] |
[
{
"body": "<p>As far as conciseness, the naive approach is probably about as good as you can get. A slightly simpler solution would use a generator expression + <code>sum</code></p>\n<pre><code>def allnums_comprehension(k):\n return sum(1 for i in range(2, k // 2) if k % i == 0)\n</code></pre>\n<p>In order to improve performance, we'll need to examine some traits of the numbers that do (or don't) meet our criteria.</p>\n<p>A few observations:</p>\n<ol>\n<li>If a number <span class=\"math-container\">\\$k\\$</span> is not divisible by <span class=\"math-container\">\\$x\\$</span>, then no multiple of <span class=\"math-container\">\\$x\\$</span> will be a natural divisor of <span class=\"math-container\">\\$k\\$</span></li>\n<li>Every natural divisor <span class=\"math-container\">\\$x\\$</span> of <span class=\"math-container\">\\$k\\$</span> has another number <span class=\"math-container\">\\$y\\$</span> that is also a natural divisor of <span class=\"math-container\">\\$k\\$</span> (e.g. <span class=\"math-container\">\\$x * y = k\\$</span>). (If <span class=\"math-container\">\\$x = \\sqrt k\\$</span> then <span class=\"math-container\">\\$x=y\\$</span>)</li>\n</ol>\n<p>If we want to pursue the first observation, we might try to use a sieving approach, similar to one you might use for the <a href=\"https://www.cs.hmc.edu/%7Eoneill/papers/Sieve-JFP.pdf\" rel=\"noreferrer\">Sieve of Eratosthenes</a>. I'll save you the time of trying this one out - its way worse (~10x slower on my computer). The <span class=\"math-container\">\\$O\\$</span> notation for this approach is left as an exercise for the reader.</p>\n<p>The second observation is much nicer; if we look at the original algorithm, the cost is <span class=\"math-container\">\\$O(n)\\$</span>. Under the new algorithm we only need to try up to <span class=\"math-container\">\\$\\sqrt k\\$</span>, giving us a complexity of <span class=\"math-container\">\\$O(\\sqrt n)\\$</span>.</p>\n<p>The new function is somewhat less readable, but still fairly simple overall:</p>\n<pre><code>def allnums_sqrt(k):\n count = 1 if k % 2 == 0 else 0\n return count + sum(2 if i * i != k else 1\n for i in range(3, math.floor(math.sqrt(k)))\n if k % i == 0)\n</code></pre>\n<p>Please note I've made some... questionable decisions here, because (as pointed out by <a href=\"https://codereview.stackexchange.com/a/253283/47529\">superb rain</a>, your definition of natural divisor is somewhat odd. The magic numbers here are a result of my attempt to replicate your results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:41:10.607",
"Id": "253282",
"ParentId": "253277",
"Score": "6"
}
},
{
"body": "<p>It's not clear what you mean with "natural dividers". Better specify that, show examples, and document <code>allnums</code> to say what it does. A better name would also help. For example <code>allnums(6)</code> returns only <code>1</code>, despite having divisors 1, 2, 3 and 6. At the very least I'd expect answer <code>2</code> (for the divisors 2 and 3). So probably it's incorrect, but we can't even tell because you didn't say what exactly it's <em>supposed</em> to do.</p>\n<p>Anyway, as usual it suffices to try divisors until the square root, not until half. If you find a divisor <code>i</code> of <code>k</code>, then don't just count that divisor but also count its partner divisor <code>k/i</code>. Unless that's the same.</p>\n<p>And <code>max</code> can take an iterable and key.</p>\n<p>So:</p>\n<pre><code>from math import isqrt\n\ndef divisors(k):\n """Compute the number of k's divisors 1 < divisor < k."""\n cnt = 0\n for i in range(2, isqrt(k) + 1):\n if k % i == 0:\n cnt += 2 - (k // i == i)\n return cnt\n\nprint(max(range(568023, 569231), key=divisors))\n</code></pre>\n<p>Takes about 0.1 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T12:48:21.907",
"Id": "499507",
"Score": "0",
"body": "you need `(k // i == i)` in `cnt += 2 - (k // i == i)` to make it not count the square root of the integer twice, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:09:34.253",
"Id": "499525",
"Score": "1",
"body": "@JoshJohnson Yes, that's the *\"Unless that's the same\"* from the explanation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:43:05.440",
"Id": "253283",
"ParentId": "253277",
"Score": "7"
}
},
{
"body": "<p>You're doing trial division. As for primality checking, something like the sieve of Eratosthenes is faster. Have a list representing the counts of the desired range, then go through candidate divisors and increase the counts of their multiples. Only use candidates up to the largest square root, and also count their partner divisors (as described in the other answers) unless they're among the candidates themselves and thus increase the counts themselves.</p>\n<p>Execution time: 1.9 ms on my laptop (AJNeufeld's takes 4.0 ms there, didn't measure the others).</p>\n<pre><code>from math import isqrt\n\nstart, stop = 568023, 569231\n\nsize = stop - start\ncnt = [0] * size\ncandidates = range(2, isqrt(stop-1) + 1)\nfor i in candidates:\n for multiple in range(-start % i, size, i):\n cnt[multiple] += 1\n if (start + multiple) // i not in candidates:\n cnt[multiple] += 1\n\nprint(start + cnt.index(max(cnt)))\n</code></pre>\n<p>(Note that <code>multiple</code> is the <em>index</em> of the multiple, the actual value of the multiple is <code>start + multiple</code>.)</p>\n<h1>Mixing mine with AJNeufeld's</h1>\n<p>Taking my Eratosthenes-like list approach, combined with AJNeufeld's calculation of numbers of divisors from prime powers. Instead of finding the prime divisor powers with trial division, I directly visit only multiples of the prime powers. So AJNeufeld's structure is like</p>\n<pre><code>for n in TheRange:\n for p in PRIMES:\n if p divides n:\n for powers of p:\n ...\n</code></pre>\n<p>while I now do this:</p>\n<pre><code>for p in PRIMES:\n for P in powers of p:\n for multiple of P in TheRange:\n ...\n</code></pre>\n<p>Where AJNeufeld has the <em>single</em> current <code>n</code> and its number of divisors <code>divisors</code>, I have <em>lists</em> <code>n</code> and <code>divisors</code> representing the same, but for <em>all</em> numbers in the desired range. So I treat all numbers in the range in parallel, one prime at a time.</p>\n<p>AJNeufeld determines the number <code>k</code> of exactly how often a number is divisible by a prime factor <code>p</code>. That then multiplies the number of divisors by <code>k + 1</code>. Here I simulate that by first going over all multiples of <code>p</code> and multiplying the number of divisors by <code>2</code>. Then I go over all multiples of <code>p**2</code> and instead multiply the number of divisors by <code>3</code> (by dividing by 2 and then multiplying by 3). And so on for larger powers of <code>p</code>. In the end, each number divisible by <code>p</code> exactly <code>k</code> times will have its number of divisors multiplied by <code>k + 1</code>.</p>\n<p>Execution time: 0.76 ms on my laptop:</p>\n<pre><code>PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,\n 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,\n 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,\n 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283,\n 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461,\n 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563,\n 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,\n 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739,\n 743, 751, ]\n\nstart, stop = 568023, 569231\n\nsize = stop - start\nn = list(range(start, stop))\ndivisors = [1] * size\n\nfor p in PRIMES:\n P = p\n k = 1\n while P < stop:\n K = k + 1\n for multiple in range(-start % P, size, P):\n divisors[multiple] = divisors[multiple] // k * K\n n[multiple] //= p\n P *= p\n k += 1\nfor i in range(size):\n if n[i] != 1:\n divisors[i] *= 2\n\nprint(start + divisors.index(max(divisors)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T05:22:45.473",
"Id": "499479",
"Score": "0",
"body": "Nice solution. I ran both on `range(2, 10_000_000)`. Your solution is about 3 times faster. Eratosthenes 1, Math 0. (I'm disappointed that the math solution doesn't win.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T06:45:17.607",
"Id": "499486",
"Score": "0",
"body": "Wow! Nice mashup of solutions! Try `for i, n_i in enumerate(n): if n_i != 1:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T06:58:25.667",
"Id": "499487",
"Score": "0",
"body": "@AJNeufeld Didn't make it faster. That part doesn't take much time anyway. And I like it better the way it is, as it is a bit shorter and I want to keep treating `n` and `divisors` equally and keep it close to your style (I even changed my usual exponent name `e` to your `k` now :-)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T23:42:40.197",
"Id": "253286",
"ParentId": "253277",
"Score": "4"
}
},
{
"body": "<h1>Naming</h1>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8 - the Style Guide for Python Code</a> list several conventions for Python coding.</p>\n<p>First, function and variable names formed by multiple words should be <code>snake_case</code>. The <code>allnum()</code> function violates this; it should be named <code>all_num()</code>, but a better name would be <code>num_divisors()</code>.</p>\n<p>Second, only constants should be in <code>UPPER_CASE</code>. <code>MAX_NUM</code> and <code>MAX</code> are not constants. They should be lowercase. Perhaps <code>max_divisors</code> and <code>number_with_max_divisors</code>.</p>\n<hr />\n<h1>Efficiency</h1>\n<p>Concise and efficiency do not necessarily go hand-in-hand.</p>\n<p>The number of natural divisors of an integer is a well studied area of mathematics.</p>\n<p>If N is expressed in its prime factorization form:</p>\n<p><span class=\"math-container\">$$N = \\prod_{i} p_i^{k_i}$$</span></p>\n<p>then the <a href=\"https://www.cut-the-knot.org/blue/NumberOfFactors.shtml\" rel=\"nofollow noreferrer\">number of natural divisors</a> of N can be directly computed as:</p>\n<p><span class=\"math-container\">$$ NumDivisors = \\prod_{i} (k_i + 1)$$</span></p>\n<p>For example: <span class=\"math-container\">\\$200 = 2^3 \\cdot 5^2\\$</span>, so 200 has <span class=\"math-container\">\\$(3 + 1)\\cdot(2+1) = 12\\$</span> natural divisors (1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200).</p>\n<p>Since the largest number we're looking for the number of natural divisors of is 569230, the largest possible prime factor is <span class=\"math-container\">\\$\\lfloor\\sqrt{569230}\\rfloor = 754\\$</span>. We only need prime numbers up to 754!</p>\n<pre class=\"lang-py prettyprint-override\"><code>PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,\n 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,\n 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,\n 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283,\n 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461,\n 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563,\n 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,\n 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739,\n 743, 751, ]\n\ndef num_divisors(n):\n\n divisors = 1\n limit = isqrt(n)\n\n for p in PRIMES:\n\n if p > limit:\n break\n\n if n % p == 0:\n k = 1\n n //= p\n while n % p == 0:\n k += 1\n n //= p\n \n divisors *= k + 1\n limit = isqrt(n)\n\n if n != 1:\n divisors *= 2\n\n return divisors\n</code></pre>\n<p>As prime factors are found, the value <code>n</code> is reduced, which reduces the search space. Consider the last value in the range: 569230. Very quickly, both 2 and 5 are factored out, leaving <code>n = 56923</code>, which is a prime number, but we don't know that yet. As successive prime candidate factors are examined, we come to <code>239</code>, which squared is larger than <code>56923</code>. At this point, we can stop, ignoring all larger primes; none can be a factor.</p>\n<p>Using this function, we can quickly (and concisely) determine the number of factors in each value of our range, and determine the number which produces the maximum:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(max(range(568023, 569230 + 1), key=num_divisors))\n</code></pre>\n<p>Execution time: 7ms.</p>\n<hr />\n<h1>Conciseness</h1>\n<p>For a concise solution, look for a library which does all of the heavy lifting for you:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from sympy import divisor_count\n\nprint(max(range(568023, 569230 + 1), key=divisor_count))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T05:38:51.933",
"Id": "499480",
"Score": "1",
"body": "Tried a few more variations of this. [Here](https://preview.tinyurl.com/y5c8falh) are two, the first is my fastest and the second is my shortest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T05:40:35.813",
"Id": "499481",
"Score": "0",
"body": "@KellyBundy I've added a few optimizations to mine, and it is down to 3.9ms -vs- 3.6ms for yours. I'm not going to post the `not n % p` improvement -- it does not improve readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T05:50:14.427",
"Id": "499483",
"Score": "0",
"body": "Ah yes, that's a bigger improvement. Though on my laptop, it's now 4.0 ms vs my 1.9 ms. I do find `not n % p` quite readable, I read it like the common expression \"[(leaves) no remainder](https://www.google.com/search?q=\"leaves+no+remainder\")\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:45:14.767",
"Id": "499524",
"Score": "0",
"body": "@KellyBundy Yes, it should be `divisor_count`. And I didn't brag about the time because it wasn't worth bragging about at 36ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:42:17.937",
"Id": "499534",
"Score": "0",
"body": "Woah, that seems surprisingly slow. Indeed not worth \"bragging\" about, rather worth *warning* about :-D Ok, your hardcoded just-long-enough list of primes is cheating a bit, but I wouldn't expect that sympy solution to be *that* much slower. Would've guessed anything from much faster to a bit slower."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T04:05:51.337",
"Id": "253291",
"ParentId": "253277",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253283",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T21:12:29.117",
"Id": "253277",
"Score": "5",
"Tags": [
"python",
"algorithm"
],
"Title": "Finding integer with the most natural dividers"
}
|
253277
|
<p>I implemented the solution to the classic <em>Matching Brackets</em> problem:</p>
<p><em>Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any pairs are matched and nested correctly.</em></p>
<p>The code should be correct since it passes several test cases.</p>
<p>I would like to know if:</p>
<ul>
<li>the usage of the <code>enum Bracket</code> is an idiomatic construct or a useless complexity</li>
<li>the function <code>brackets_are_balanced</code> can be simplified while keeping the <code>enum Bracket</code></li>
<li>further improvement/suggestions</li>
</ul>
<pre class="lang-rust prettyprint-override"><code>#![warn(missing_crate_level_docs)]
#![warn(missing_docs)]
//! # Matching Brackets
//!
//! `matching_brackets` is a collection of utilities to solve [this exercise](https://exercism.io/my/solutions/8ecfdc024536471a8c36ac2a3ff4b119).
enum Bracket {
OPEN(char),
CLOSE(char),
}
impl Bracket {
pub fn new(c: char) -> Option<Bracket> {
match c {
'{' | '[' | '(' => Some(Bracket::OPEN(c)),
'}' => Some(Bracket::CLOSE('{')),
']' => Some(Bracket::CLOSE('[')),
')' => Some(Bracket::CLOSE('(')),
_ => None,
}
}
}
/// Check if the input `string` has balanced brackets.
///
/// # Examples
///
/// ```rust
/// use matching_brackets::brackets_are_balanced;
/// assert!(brackets_are_balanced("(((185 + 223.85) * 15) - 543)/2"));
/// assert!(brackets_are_balanced("([{}({}[])])"));
/// assert!(!brackets_are_balanced("{[)][]}"))
/// ```
pub fn brackets_are_balanced(string: &str) -> bool {
let mut brackets: Vec<Bracket> = vec![];
for c in string.chars() {
match Bracket::new(c) {
Some(Bracket::OPEN(char_bracket)) => {
brackets.push(Bracket::OPEN(char_bracket));
}
Some(Bracket::CLOSE(char_close_bracket)) => match brackets.pop() {
Some(Bracket::OPEN(char_open_bracket)) => {
if char_close_bracket != char_open_bracket {
return false;
}
}
_ => return false,
},
_ => (),
};
}
brackets.is_empty()
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>the introduction of <code>enum Bracket</code> is good and idiomatic. However, this is not the only useful form, there are at least 2 other forms that would work just fine.</li>\n<li><code>brackets_are_balanced</code> can be simplified when we notice that all <code>Bracket</code>s in <code>Vec<Bracket></code> are of the <code>Open</code> variant, so we do not need to store <code>Bracket</code>s, just their <code>char</code>s.</li>\n<li>the introduction of <code>fn new</code> is against standard practice. A conversion constructor should not be called <code>fn new</code> and every constructor should return only Self (= <code>Bracket</code>). That's why the function should be renamed to <code>from_char</code>.</li>\n<li>it's common practice to name enum variants with <code>PascalCase</code>, in your program, <code>Bracket::Open</code> and <code>Bracket::Close</code>. Not sure why you did all uppercase.</li>\n<li>the result of <code>brackets.pop()</code> does not need matching, it can be simply compared.</li>\n</ul>\n<p>The refactored code is</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#![warn(missing_crate_level_docs)]\n#![warn(missing_docs)]\n//! # Matching Brackets\n//!\n//! `matching_brackets` is a collection of utilities to solve [this exercise](https://exercism.io/my/solutions/8ecfdc024536471a8c36ac2a3ff4b119).\n\nenum Bracket {\n Open(char),\n Close(char),\n}\n\nimpl Bracket {\n pub fn from_char(c: char) -> Option<Bracket> {\n match c {\n '{' | '[' | '(' => Some(Bracket::Open(c)),\n '}' => Some(Bracket::Close('{')),\n ']' => Some(Bracket::Close('[')),\n ')' => Some(Bracket::Close('(')),\n _ => None,\n }\n }\n}\n\n/// Check if the input `string` has balanced brackets.\n///\n/// # Examples\n///\n/// ```rust\n/// use matching_brackets::brackets_are_balanced;\n/// assert!(brackets_are_balanced("(((185 + 223.85) * 15) - 543)/2"));\n/// assert!(brackets_are_balanced("([{}({}[])])"));\n/// assert!(!brackets_are_balanced("{[)][]}"))\n/// ```\npub fn brackets_are_balanced(string: &str) -> bool {\n let mut brackets: Vec<char> = vec![];\n for c in string.chars() {\n match Bracket::from_char(c) {\n Some(Bracket::Open(char_bracket)) => {\n brackets.push(char_bracket);\n }\n Some(Bracket::Close(char_close_bracket)) => {\n if brackets.pop() != Some(char_close_bracket) {\n return false;\n }\n }\n _ => {}\n }\n }\n brackets.is_empty()\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:12:35.290",
"Id": "499539",
"Score": "0",
"body": "great thanks! could you elaborate more about: \"there are at least 2 other forms that would work just fine\". \nSpecifically, what are the \"2 other forms\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:37:50.187",
"Id": "499543",
"Score": "1",
"body": "@Angelo we can rearrange this definition: `enum Bracket1 {\n Paren(Direction),\n CurlyBrace(Direction),\n SquareBracket(Direction),\n}\n\nstruct Bracket2 {\n direction: Direction,\n kind: BracketKind,\n}\n\nenum BracketKind { Paren, CurlyBrace, SquareBracket }\nenum Direction { Open, Close }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T18:10:14.917",
"Id": "499551",
"Score": "0",
"body": "thanks, clear, one last question: I saw several code snippets where `new` was used with multiple input parameters. could you give me some references/reasons why `new` should not contain any parameter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T18:26:46.787",
"Id": "499553",
"Score": "2",
"body": "@Angelo that's wrong, my bad. I looked into what the standard library does, and found that `new` can take arguments, but these arguments tend to be very simple like in your case. Still, I should have just said that calling the function `from_char` is more descriptive, since you're doing a conversion."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:00:37.873",
"Id": "253309",
"ParentId": "253279",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:21:09.600",
"Id": "253279",
"Score": "3",
"Tags": [
"algorithm",
"rust"
],
"Title": "Matching brackets in Rust"
}
|
253279
|
<p>I made this project in my free time to try to crack a 4x hashed md5 with a couple of hints but I'm looking for ways I can optimize this algo because it's pretty slow and I know you could probs use threading or some other ways to increase speed.</p>
<p>If you can even point out some minor ways to increase performance I would be eternally grateful.</p>
<p>I was told I could try re-using the memory for the strings but I'm not sure how to do that. I was also told to not generate the wordlist in advance and try as I go but I dont think the algorithm I used supports that?</p>
<p>Here's the branch to review (more info in the readme): <a href="https://github.com/TransmissionsDev/crack_yearn_md5/tree/v1" rel="noreferrer">https://github.com/TransmissionsDev/crack_yearn_md5/tree/v1</a></p>
<p>Here's the main.rs file:</p>
<pre class="lang-rust prettyprint-override"><code>#[cfg(debug_assertions)]
use num_format::{Locale, ToFormattedString};
fn hash_md5(input: String) -> String {
format!("{:x}", md5::compute(input.into_bytes()))
}
fn main() {
let goal_hash = "dbba1bfe930d953cabcc03d7b6ab05e";
let length = 17;
let alphabet = "bdeilmostu-"
.split("")
.map(String::from)
.filter(|letter| !letter.is_empty())
.collect::<Vec<String>>();
let mut words = alphabet.clone();
for phase in 1..length {
let mut temp: Vec<String> = Vec::new();
#[cfg(not(debug_assertions))]
let loopable_words = words.iter();
#[cfg(debug_assertions)]
let loopable_words = words.iter().enumerate();
for data in loopable_words {
#[cfg(not(debug_assertions))]
let word = data;
#[cfg(debug_assertions)]
let word = data.1;
#[cfg(debug_assertions)]
let index = data.0;
for letter in alphabet.iter() {
let new_word = format!("{}{}", word, letter);
temp.push(new_word);
}
#[cfg(debug_assertions)]
if index != 0 && ((index % 1000000) == 0) {
println!(
"Completed phase {}/{}'s sub-phase {}/{}",
phase,
length,
index.to_formatted_string(&Locale::en),
words.len().to_formatted_string(&Locale::en),
);
}
}
words = temp;
}
#[cfg(debug_assertions)]
let word_list_length = words.len();
#[cfg(debug_assertions)]
println!("\n\nLength of word list: {}\n\n", word_list_length);
#[cfg(not(debug_assertions))]
let loopable_words = words.iter();
#[cfg(debug_assertions)]
let loopable_words = words.iter().enumerate();
for data in loopable_words {
#[cfg(not(debug_assertions))]
let word = data;
#[cfg(debug_assertions)]
let word = data.1;
#[cfg(debug_assertions)]
let attempts = data.0;
let merged = format!(
"{}{}",
word, "........................................................!1"
);
let hash = hash_md5(hash_md5(hash_md5(hash_md5(merged.clone()))));
#[cfg(debug_assertions)]
println!(
"Attempts: {}/{}, Hash: {}, Text: {}",
attempts, word_list_length, hash, merged
);
if hash == goal_hash {
println!("We found the password: {}", merged);
return;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:37:17.467",
"Id": "499463",
"Score": "1",
"body": "This looks useful: https://github.com/deeprobin/bruteforce-rs"
}
] |
[
{
"body": "<p>First, I would change the approach fundamentally: I'd consider the plaintext as a 17-digit number in "base 11" (because there are 11 "letters" in the alphabeth). Then the loop becomes a simple iteration through a range from 0 to 11<sup>17</sup>-1. On top of that, threading will be easy to add using <code>rayon</code>.</p>\n<p>As you were told, we should re-use memory for strings and not generate the wordlist in advance.</p>\n<p>To re-use memory for strings, we treat them as long-living containers and call <code>.clear()</code> whenever we need to reuse them for another purpose.</p>\n<p>This part in your code</p>\n<pre class=\"lang-rust prettyprint-override\"><code>for letter in alphabet.iter() {\n let new_word = format!("{}{}", word, letter);\n\n temp.push(new_word);\n}\n</code></pre>\n<p>is very inefficient as it's calling <code>format!</code>, which is complex machinery, just to append a letter. It would be better to have at least <code>String::push</code> there, but we will take another approach below.</p>\n<hr />\n<p>On 4 cores, the all-in-one is roughly as fast as just your non-parallelized first pass. For parallelism, I did parallel <code>fold</code> after <code>Range<u64></code>. So each thread has a little bit of its own state there.</p>\n<p>Make sure you add <code>rayon = "0.6"</code> in the Cargo manifest.</p>\n<p>Here is the code:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[cfg(debug_assertions)]\nuse num_format::{Locale, ToFormattedString};\nuse std::str;\nuse std::io::Write;\nuse rayon::prelude::*;\n\nstatic PASS_LENGTH: u32 = 17;\n\n#[derive(Default)]\nstruct State {\n plaintext: Vec<u8>,\n intermediate: Vec<u8>,\n}\n\nimpl State {\n fn new() -> Self {\n let mut result = State::default();\n for _ in 0 .. PASS_LENGTH {\n result.plaintext.push(b"x"[0]);\n }\n result.plaintext.extend(b"........................................................!1".iter().copied());\n result\n }\n}\n\nfn main() {\n let goal_hash = "dbba1bfe930d953cabcc03d7b6ab05e";\n\n let num_of_md5 = 4;\n let alphabet = "bdeilmostu-";\n let alphabet_len = alphabet.len() as u64;\n\n let total = alphabet_len.pow(PASS_LENGTH);\n\n (0 .. total).into_par_iter().fold(\n || State::new(),\n |mut state, num| {\n for i in 0 .. PASS_LENGTH {\n let letter = ((num / alphabet_len.pow(i)) % alphabet_len) as usize;\n state.plaintext[i as usize] = alphabet.as_bytes()[letter];\n }\n\n state.intermediate.clear();\n write!(&mut state.intermediate, "{:x}", md5::compute(&state.plaintext[..]));\n for _ in 1 .. num_of_md5 {\n let digest = md5::compute(&state.intermediate[..]);\n state.intermediate.clear();\n write!(&mut state.intermediate, "{:x}", digest);\n }\n let result = &state.intermediate[..];\n\n if result == goal_hash.as_bytes() {\n println!("We found the password: {}", str::from_utf8(&state.plaintext[..]).unwrap());\n }\n\n if num % 1_000_000 == 0 && num != 0 {\n #[cfg(debug_assertions)]\n println!(\n "Attempts: {}/{}, Text: {}",\n num, total, str::from_utf8(&state.plaintext[..]).unwrap()\n );\n }\n\n state\n }\n ).for_each(|_| {});\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:57:24.250",
"Id": "499692",
"Score": "0",
"body": "thank you so much for this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T20:00:50.323",
"Id": "499696",
"Score": "1",
"body": "@TransmissionsDev sure thing. It would be interesting to improve the conversion from number to plaintext probably through smarter division or add-1 with carry.Further, I'm not sure how you'd like to use this program, but it's possible to adapt it for distributed computation or even the cloud."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T15:05:43.617",
"Id": "253344",
"ParentId": "253281",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253344",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T22:33:00.743",
"Id": "253281",
"Score": "5",
"Tags": [
"algorithm",
"rust",
"hash"
],
"Title": "RUST: How can I optimize this password cracking algorithm?"
}
|
253281
|
<p>I recently learned about <code>classes</code> in python. I only have a brief understanding of them, but I think it's good enough for me to write a tic tac toe program (been working on this for the last week or so). My title may be a little misleading (again, because I only have a brief understanding...) but I think you'll get the point when you see my code. I don't have any concerns with my code, but if you have any suggestions/criticism please don't hesitate to let me know.</p>
<p>my code:</p>
<pre><code>from tkinter import *
import numpy as np
size_of_board = 600
size_of_symbol = (size_of_board / 3 - size_of_board / 8) / 2
thickness_of_symbol = 50
colour_of_X = '#FFB6C1'
colour_of_O = '#2ADCCB'
score_board_colour = '#8A2BE2'
class Tic_Tac_Toe():
# ------------------------------------------------------------------
# initialize functions:
# ------------------------------------------------------------------
def __init__(self):
self.window = Tk()
self.window.title('Tic-Tac-Toe')
self.canvas = Canvas(self.window, width = size_of_board, height = size_of_board)
self.canvas.pack()
# input from user in the form of clicks
self.window.bind('<Button-1>', self.click)
self.initialize_board()
self.player_X_turns = True
self.board_status = np.zeros(shape = (3, 3))
self.player_X_starts = True
self.reset_board = False
self.gameover = False
self.tie = False
self.X_wins = False
self.O_wins = False
self.X_score = 0
self.O_score = 0
self.tie_score = 0
def mainloop(self):
self.window.mainloop()
def initialize_board(self):
for i in range(2):
self.canvas.create_line((i + 1) * size_of_board / 3, 0, (i + 1) * size_of_board / 3, size_of_board)
for i in range(2):
self.canvas.create_line(0, (i + 1) * size_of_board / 3, size_of_board, (i + 1) * size_of_board / 3)
def play_again(self):
self.initialize_board()
self.player_X_starts = not self.player_X_starts
self.player_X_turns = self.player_X_starts
self.board_status = np.zeros(shape = (3, 3))
# ------------------------------------------------------------------
# the modules required to draw required game based object on canvas
# ------------------------------------------------------------------
def draw_O(self, logical_position):
logical_position = np.array(logical_position)
# logical_position = grid value on the board
# grid_position = actual pixel values of the center of the grid
grid_position = self.convert_logical_to_grid_position(logical_position)
self.canvas.create_oval(grid_position[0] - size_of_symbol, grid_position[1] - size_of_symbol,
grid_position[0] + size_of_symbol, grid_position[1] + size_of_symbol,
width = thickness_of_symbol, outline = colour_of_O)
def draw_X(self, logical_position):
grid_position = self.convert_logical_to_grid_position(logical_position)
self.canvas.create_line(grid_position[0] - size_of_symbol, grid_position[1] - size_of_symbol,
grid_position[0] + size_of_symbol, grid_position[1] + size_of_symbol,
width = thickness_of_symbol, fill = colour_of_X)
self.canvas.create_line(grid_position[0] - size_of_symbol, grid_position[1] + size_of_symbol,
grid_position[0] + size_of_symbol, grid_position[1] - size_of_symbol,
width = thickness_of_symbol, fill = colour_of_X)
def display_gameover(self):
if self.X_wins:
self.X_score += 1
text = 'Player 1 (X) has won'
colour = colour_of_X
elif self.O_wins:
self.O_score += 1
text = 'Player 2 (O) has won'
colour = colour_of_O
else:
self.tie_score += 1
text = 'Draw!!'
colour = 'coral'
self.canvas.delete('all')
self.canvas.create_text(size_of_board / 2, size_of_board / 3, font = 'cmr 40 bold', fill = colour, text = text)
score_text = 'Scores \n'
self.canvas.create_text(size_of_board / 2, 5 * size_of_board / 8, font = 'cmr 30 bold', fill =
score_board_colour, text = score_text)
score_text = 'Player 1 (X) : ' + str(self.X_score) + '\n'
score_text += 'Player 2 (O) : ' + str(self.O_score) + '\n'
score_text += 'Tie : ' + str(self.tie_score)
self.canvas.create_text(size_of_board / 2, 3 * size_of_board / 4, font = 'cmr 20 bold', fill =
score_board_colour, text = score_text)
self.reset_board = True
score_text = 'Click to play again \n'
self.canvas.create_text(size_of_board / 2, 15 * size_of_board / 16, font = 'cmr 10 bold', fill = 'orange',
text = score_text)
# ------------------------------------------------------------------
# the modules required to carry out game logic
# ------------------------------------------------------------------
def convert_logical_to_grid_position(self, logical_position):
logical_position = np.array(logical_position, dtype = int)
return (size_of_board / 3) * logical_position + size_of_board / 6
def convert_grid_to_logical_position(self, grid_position):
grid_position = np.array(grid_position)
return np.array(grid_position // (size_of_board / 3), dtype = int)
def is_grid_occupied(self, logical_position):
if self.board_status[logical_position[0]][logical_position[1]] == 0:
return False
else:
return True
def is_winner(self, player):
player = -1 if player == 'X' else 1
# three in a row
for i in range(3):
if self.board_status[i][0] == self.board_status[i][1] == self.board_status[i][2] == player:
return True
if self.board_status[0][i] == self.board_status[1][i] == self.board_status[2][i] == player:
return True
# diagonals
if self.board_status[0][0] == self.board_status[1][1] == self.board_status[2][2] == player:
return True
if self.board_status[0][2] == self.board_status[1][1] == self.board_status[2][0] == player:
return True
return False
def is_tie(self):
r, c = np.where(self.board_status == 0)
tie = False
if len(r) == 0:
tie = True
return tie
def is_gameover(self):
# either someone is declared the winner or the entire grid is occupied
self.X_wins = self.is_winner('X')
if not self.X_wins:
self.O_wins = self.is_winner('O')
if not self.O_wins:
self.tie = self.is_tie()
gameover = self.X_wins or self.O_wins or self.tie
if self.X_wins:
print('X wins')
if self.O_wins:
print('O wins')
if self.tie:
print('It\'s a tie')
return gameover
def click(self, event):
grid_position = [event.x, event.y]
logical_position = self.convert_grid_to_logical_position(grid_position)
if not self.reset_board:
if self.player_X_turns:
if not self.is_grid_occupied(logical_position):
self.draw_X(logical_position)
self.board_status[logical_position[0]][logical_position[1]] = -1
self.player_X_turns = not self.player_X_turns
else:
if not self.is_grid_occupied(logical_position):
self.draw_O(logical_position)
self.board_status[logical_position[0]][logical_position[1]] = 1
self.player_X_turns = not self.player_X_turns
# check if the game has concluded
if self.is_gameover():
self.display_gameover()
# print('Done')
else: # Play Again
self.canvas.delete('all')
self.play_again()
self.reset_board = False
play_game = Tic_Tac_Toe()
play_game.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>The main problem I see is how closely tied to the UI the game logic is. You have one class that's responsible for both handling the UI (<code>initialize_board</code>, <code>display_gameover</code>, <code>draw_X</code>) and handing game logic (<code>is_winner</code>, <code>is_tie</code>, <code>is_grid_occupied</code>). This means that in order to test the logic of the game, you need to construct a <code>Tic_Tac_Toe</code>, which will launch the UI.</p>\n<p>I'd break the game logic off into its own class that wraps the <code>numpy</code> array, and exposes game-related methods (<code>place_x</code>, <code>place_o</code>, <code>is_winner</code>). That way you can manipulate the game object easily using automated testing, completely separately from UI. You would then give the main "application class" an instance of the game for it to manipulate and query as needed.</p>\n<hr />\n<p>For the same, but lesser reasons, you may also want to directly wrap the <code>numpy</code> array in a <code>Board</code> class to clean up reads/writes to the board in your game class. Adding helper methods that allow for setting using tuples could clean up lines like this:</p>\n<pre><code>self.board[logical_position[0]][logical_position[1]] = 1\n</code></pre>\n<p>A <code>set_at</code> method that accepts a tuple/sequence could replace that:</p>\n<pre><code>self.board.set_at(logical_position, 1)\n</code></pre>\n<p>Which reads much nicer. A similar <code>get_at</code> method could be created for lookups that use sequences as well.</p>\n<hr />\n<p><code>is_grid_occupied</code> is more verbose than it needs to be. Using a conditional statement to dispatch to <code>True</code>/<code>False</code> is redundant since the condition already evaluates to the same values. You can just have:</p>\n<pre><code>def is_grid_occupied(self, logical_position):\n return self.board[logical_position[0]][logical_position[1]] == 0\n</code></pre>\n<p>Or, if you implement a <code>get_at</code> method:</p>\n<pre><code>def is_grid_occupied(self, logical_position):\n return self.board.get_at(logical_position) == 0\n</code></pre>\n<p>You could also negate the condition instead of comparing against <code>0</code>, but I'd keep it like this for explicitness.</p>\n<hr />\n<pre><code>def is_winner(self, player):\n player = -1 if player == 'X' else 1\n</code></pre>\n<p>There's a couple things to note here:</p>\n<ul>\n<li><p>You're using <code>-1</code> and <code>1</code> as placeholder values to indicate the players. These are examples of <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">Magic Numbers</a>, and should ideally be replaced by a more descriptive name. I'm not sure what the limitation on <code>numpy</code> arrays are, but an <code>Enum</code> of something like:</p>\n<pre><code>from enum import Enum\n\nclass Cell(Enum):\n X = -1\n O = 1\n EMPTY = 0\n</code></pre>\n<p>would allow you to make more sensical code:</p>\n<pre><code>self.board_status[logical_position[0]][logical_position[1]] = Cell.X\n. . .\nself.board_status[logical_position[0]][logical_position[1]] = Cell.O\n. . .\nplayer = Cell.X if player == 'X' else Cell.O\n</code></pre>\n<p>And you could do away with that first line of <code>is_winner</code> altogether by just using the enum when calling it:</p>\n<pre><code>self.X_wins = self.is_winner(Cell.X)\n</code></pre>\n<p>If <code>numpy</code> arrays can't hold enums, try using an <code>IntEnum</code> instead of <code>Enum</code>, or just have global constants:</p>\n<pre><code>PLAYER_X = -1\nPLAYER_O = 1\nEMPTY = 0\n</code></pre>\n<p>And use those instead. You could also just switch to using normal Python <code>list</code>s. I don't think <code>numpy</code> is necessary here.</p>\n</li>\n<li><p>I usually try to avoid needlessly reassigning variables, especially parameters. It's often handy to see what data was previously when print-debugging/sitting at a breakpoint in a debugger. I prefer to give it a name that describes the new state, or distinguishes it from the previous state. Since the string being passed in is a formatted string representation, I might rename it:</p>\n<pre><code> def is_winner(self, formatted_player):\n player = Cell.X if formatted_player == 'X' else Cell.O\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>I realized after that it is actually possible to instantiate the class without actually launching the UI. I would still recommend splitting the separate functionality off though, for the sake of readability and maintenance. The less code you have to sift through when trying to pin down a bug or understand a section of code, the better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:10:41.957",
"Id": "499537",
"Score": "0",
"body": "thank you so much!! really appreciate your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:49:03.870",
"Id": "499548",
"Score": "0",
"body": "that is true, I'll remove the accept for now..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T01:28:57.553",
"Id": "253289",
"ParentId": "253285",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T23:33:57.720",
"Id": "253285",
"Score": "3",
"Tags": [
"python",
"beginner",
"game",
"tic-tac-toe",
"classes"
],
"Title": "Tic Tac Toe using the __init__ constructor"
}
|
253285
|
<p>I wrote my first web app. Please let me know what I should improve. I want to write as clean code as possible.</p>
<p>App is about adding and removing tasks from list. Backend is written in Django, frontend in Sass and JavaScript.</p>
<p>Below my code for items view. Whole project can be seen in link:</p>
<p><a href="https://github.com/Damiant94/TodoList" rel="nofollow noreferrer">Link to my code on GitHub</a></p>
<p>Demo:</p>
<p><a href="http://awesome-todo-list.herokuapp.com/" rel="nofollow noreferrer">Link to app on heroku</a></p>
<p>Code for items view:</p>
<ol>
<li>JavaScript</li>
<li>Sass</li>
<li>HTML</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>// Start with first item
let counter = 0;
// Load 6 items at a time
const QUANTITY_START = 6;
const QUANTITY_TO_ADD_ON_SCROLL = 3;
let isListEmpty = true;
let removed = [];
let areMoreItems = true;
const HIDE_ANIMATION_DURATION_OPACITY = 1500
document.addEventListener('DOMContentLoaded', () => {
// SETTING LISTENERS:
window.onscroll = () => {
if (areMoreItems && isScrolledToBottom()){
const scroll = window.onscroll;
window.onscroll = "none";
load(QUANTITY_TO_ADD_ON_SCROLL);
setTimeout(() => {
window.onscroll = scroll;
}, 1000);
}
}
deleteItemListener();
confirmDeleteButtonListener();
// END OF SETTING LISTENERS
load(QUANTITY_START);
})
function confirmDeleteButtonListener() {
const confirm_button = document.querySelector(".confirm-delete-button");
confirm_button.addEventListener("click", () => {
confirm_button.value = removed.join();
})
}
function deleteItemListener() {
document.querySelector(".main").addEventListener("click", function(event) {
if(event.target.nodeName === "I") {
const itemElement = event.target.parentElement.parentElement;
const item_id = itemElement.querySelector('.id').innerHTML;
removed.push(item_id);
itemElement.style.animationPlayState = 'running';
// itemElement.addEventList;
document.querySelector(".confirm-delete-button").disabled = false;
}
});
}
function isScrolledToBottom() {
return window.innerHeight + window.scrollY >= document.body.offsetHeight
}
function load(quantity) {
const start = counter;
const end = start + quantity - 1;
counter = end + 1;
fetch(`itemslist?start=${start}&end=${end}`)
.then(response => response.json())
.then(data => {
if (data.itemslist.length > 0) {
isListEmpty = false;
data.itemslist.forEach(addItem);
} else {
areMoreItems = false;
if (isListEmpty) {
addEmptyListInfo();
}
}
});
}
function addEmptyListInfo() {
const item = document.createElement('section');
item.className = "empty-list";
item.innerText = "Your list is empty";
document.querySelector('.main-items').append(item)
}
function addItem(item) {
const itemNode = document.createElement('section');
itemNode.className = "todo-item";
itemNode.innerHTML =
`<p hidden class="id">${item.id}</p>
<div name="delete-button" value="${item.id}" class="x-wrapper">
<i class="far fa-times-circle"></i>
</div>
<h2 name="name" class="todo-item-name">${item.name}</h2>
<label for="details">Details:</label>
<p class="details" name="details">${item.details}</p>
<p class="date">Deadline: ${item.date}</p>`;
document.querySelector('.main-items').append(itemNode);
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav {
.li {
background-color: transparent;
border: none;
cursor: pointer;
font-family: 'Caveat', cursive;
color: #fff;
outline: none;
}
form {
display: flex;
display: -webkit-box;
display: -ms-flexbox;
flex-direction: row;
}
}
.main-items {
opacity: 0.9;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
flex-direction: row !important;
justify-content: space-evenly;
flex-wrap: wrap;
.todo-item {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
color: #000;
height: 300px;
width: 400px;
padding: 20px;
margin: 0 15px;
position: relative;
-webkit-animation-name: hide;
animation-name: hide;
-webkit-animation-duration: 1.5s;
animation-duration: 1.5s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-play-state: paused;
animation-play-state: paused;
background-image: url(../img/sticky1.png);
background-size: 400px 300px;
line-height: 100%;
.todo-item-name {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: flex-start;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin-bottom: 10px;
margin-left: 40px;
margin-right: 25px;
height: 40px;
font-size: 25px;
font-weight: bold;
margin-top: 20px;
padding: 5px;
outline: none;
color: #000;
overflow-y: auto;
scrollbar-width: thin;
scroll-padding: 0;
scroll-margin: 0;
white-space: nowrap;
cursor: default;
}
.details {
border-radius: 5px;
overflow-wrap: break-word;
overflow-y: auto;
height: 100px;
padding: 10px;
margin-left: 40px;
margin-right: 25px;
text-align: justify;
resize: none;
margin-bottom: 10px;
outline: none;
font-size: 22px;
scrollbar-width: thin;
scroll-padding: 0;
scroll-margin: 0;
cursor: default;
}
.x-wrapper {
position: absolute;
right: 0;
top: 0;
margin: 10px;
font-size: 20px;
-webkit-transition: all 0.2s;
transition: all 0.2s;
cursor: pointer;
border: none;
color: #e9c1c1;
background-color: transparent;
}
.x-wrapper:hover {
color: #fff;
}
}
.empty-list {
font-size: 44px;
margin-bottom: 40px;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
padding-right: 15px;
border-radius: 10px;
text-align: center;
pointer-events: none;
}
.todo-item label {
font-size: 20px;
margin-bottom: 2px;
margin-left: 40px;
margin-right: 25px;
}
.date {
text-align: right;
margin-right: 25px;
pointer-events: none;
}
}
@-webkit-keyframes hide {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes hide {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends "TodoListApp/base.html" %}
{% load static %}
{% block style %}
<link rel="stylesheet" href="{% static 'TodoListApp/css/items.css' %}">
<link rel="stylesheet" href="{% static 'TodoListApp/css/loader.css' %}">
<title>Items</title>
{% endblock %}
{% block body %}
<div id="loader-wrapper">
<div id="loader"></div>
<div class="section-left"></div>
<div class="section-right"></div>
</div>
<nav class="nav">
<a href="{% url 'newitem' %}">
<div class="li">Add new item</div>
</a>
<form action="{% url 'items' %}" method="post">
{% csrf_token %}
<button class="add-10-items li" value="add-10-items" name="add-10-items">add 10 items</button>
<button disabled class="confirm-delete-button li" value="" name="confirm-delete-button">confirm deleting</button>
</form>
<a href="{% url 'logout' %}">
<div class="li">Logout</div>
</a>
</nav>
<div class="container container-items">
<header class="header">
<h1>Hello :{{ name }}:</h1>
<h1>Here is a list of your activities:</h1>
</header>
<main class="main main-items">
</main>
</div>
<script src="{% static 'TodoListApp/js/items.js' %}"></script>
<script src="{% static 'TodoListApp/js/loader.js' %}"></script>
{% endblock %}</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Pretty good code, I'd remove variable <code>isListEmpty</code> as it does nothing at all, your if else branch already checks for empty list and you get rid of one ugly global variable.</p>\n<p>Consider getting rid of all the global variables by wrapping functions, that need them into either into class or another function. that way variables are not global, and you can even pass some of these as parameters (ex: <code>QUANTITY_START</code>).</p>\n<p><code>addEmptyListInfo</code> and <code>addItem</code> have identical first and last line. You can extract middle of them into separate functions and create 3rd common function to avoid redundancy and make sure adding new "section" is only in one place.</p>\n<p>I don't like that <code>fetch</code> url is hardcoded into .js file. Consider extracting it somewhere into html as data-attribute, that way you can control how is url generated and if you change django routing, you don't have to modify url in multiple places.</p>\n<p>Consider extracting debounce listener of scroll into separate function, example:\n<a href=\"https://stackoverflow.com/a/12009497/4070660\">https://stackoverflow.com/a/12009497/4070660</a></p>\n<p>As for scss, you can use autoprefixer to handle vendor prefixes for you and clean up your code a bit.</p>\n<p>Most of time it's better to use other units than pixels. Consider using em/rem or vw/vh/</p>\n<p>Nothing comes to mind when checking your html :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T00:23:32.597",
"Id": "253288",
"ParentId": "253287",
"Score": "1"
}
},
{
"body": "<p><strong>Use <code>const</code> when possible</strong> - using <code>let</code> is a warning to readers of the code that a variable may get reassigned in the future. If that's not actually the case, <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">better to use <code>const</code></a> for the <code>removed</code> variable; consider <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\">a linter</a>.</p>\n<p><strong><code>removed</code> array?</strong> Its purpose isn't entirely clear at first glance, I had to read over a few sections of the code to understand what it's doing. Consider naming it <code>itemIdsToBeRemoved</code>. Also, <code>counter</code> might be better named <code>lastItemIdLoaded</code> or something of the sort.</p>\n<p><strong>Use <code>camelCase</code> for plain variables</strong>, as is the overwhelming convention in JS: eg, consider using <code>itemId</code> and <code>confirmButton</code>. (The all-caps numeric constants at the top are just fine.)</p>\n<p><strong>DOMContentLoaded section</strong> You do 4 things there:</p>\n<ul>\n<li>Add a scroll listener</li>\n<li>Call <code> deleteItemListener</code>, <code>confirmDeleteButtonListener</code>, and <code>load</code></li>\n</ul>\n<p>To be stylistically consistent, consider abstracting the scroll listener into a separate function, like you're doing with the other listeners. (But the functions aren't <em>event listeners themselves</em> - they <em>add</em> event listeners, so maybe call them, eg, <code>addDeleteConfirmListener</code>)</p>\n<p><strong>Load quantity complication</strong> Juggling a dynamic number of items requested from the server seems a bit overcomplicated for my tastes. Unless you're expecting to have huge payloads, I think it'd make a bit more sense to fetch <em>all</em> items immediately, and then sort through what should be displayed at what time <em>on the client</em>. Sending all items at once will also reduce the visible delay for the user.</p>\n<p>If you were to send all items immediately, consider interpolating the data into the HTML, rather than using a request after the page loads. Eg, you could have</p>\n<pre><code><script type="application/json" class="items-data">\n{"itemslist": [{"id": 191, "user_id": 26, "name": "name", "details": "details", "date": "2020-12-09"}]}\n</script>\n</code></pre>\n<pre><code>const items = JSON.parse(document.querySelector('.items-data').textContent);\n</code></pre>\n<p>This will make the page load more quickly for the user; assuming the app's been loaded before and you have a sensible cache policy, they won't have to wait for <em>two</em> round-trips to your server for the todos to be displayed, but only one.</p>\n<p><strong>Return early to avoid indentation hell</strong> This:</p>\n<pre><code>function deleteItemListener() {\n document.querySelector(".main").addEventListener("click", function(event) {\n if(event.target.nodeName === "I") {\n // big block of code\n</code></pre>\n<p>can be</p>\n<pre><code>function deleteItemListener() {\n document.querySelector(".main").addEventListener("click", function(event) {\n if (event.target.nodeName !== "I") {\n return;\n }\n // big block of code\n</code></pre>\n<p>or even</p>\n<pre><code>function deleteItemListener() {\n document.querySelector(".main").addEventListener("click", function(event) {\n if (event.target.nodeName === "I") {\n deleteItem(event.target);\n }\n</code></pre>\n<p><strong>nodeName?</strong> It's not clear at a glance that a <code>nodeName</code> of <code>i</code> corresponds to the X icon. Consider giving the <code>i</code> a class that indicates what it is, eg <code>delete-icon</code>, allowing you to do <code>e.target.matches('.delete-icon')</code>.</p>\n<p><strong>Use <code>.closest</code></strong> when navigating to parents - the selector passed to <code>.closest</code> can be more informative as to which parent you're navigating to, <em>and</em> it's shorter than using <code>.parentElement.parentElement</code>:</p>\n<pre><code>const itemElement = event.target.closest('section');\n</code></pre>\n<p><strong><code>innerHTML</code>, <code>textContent</code>, and <code>innerText</code></strong></p>\n<ul>\n<li><p>Avoid <code>innerText</code>. It's <a href=\"http://perfectionkills.com/the-poor-misunderstood-innerText/\" rel=\"nofollow noreferrer\">almost never what you want</a> - it has some confusing behaviors. Except in the very few cases where you need to retrieve text using <code>innerText</code>'s peculiar formatting quirks, better to use <code>.textContent</code> or <code>.innerHTML</code>.</p>\n</li>\n<li><p>Only use <code>.innerHTML</code> when setting or retrieving HTML markup. If all you want to set or retrieve is <em>plain text</em>, use <code>.textContent</code> instead; <code>.textContent</code> is faster, safer, and more semantically appropriate.</p>\n</li>\n</ul>\n<p>Related to the above:</p>\n<p><strong><code>innerHTML</code> is a security risk with user input</strong> I can get your site to execute arbitrary code by entering the following description into a todo:</p>\n<pre><code><img src onerror="alert('evil')">\n</code></pre>\n<p>I could disguise the markup in other text, then tell another user "Hey, try making a new todo with this description, you won't believe what happens next!" - and then steal their login credentials if they fall for it.</p>\n<p>The problem is that you're using:</p>\n<pre><code> itemNode.innerHTML = \n `<p hidden class="id">${item.id}</p>\n ...\n <p class="details" name="details">${item.details}</p>\n</code></pre>\n<p>Direct concatentation of an HTML string like that should always be looked at suspiciously. If the interpolated value isn't 100% trustworthy, you probably have problems. To fix it, populate the untrustworthy values into the DOM by setting <code>.textContent</code> after creating the element, like this:</p>\n<pre><code>itemNode.innerHTML = `\n <p hidden class="id">${item.id}</p>\n <div name="delete-button" value="${item.id}" class="x-wrapper">\n <i class="far fa-times-circle"></i>\n </div>\n <h2 name="name" class="todo-item-name"></h2>\n <label for="details">Details:</label>\n <p class="details" name="details"></p>\n <p class="date">Deadline: ${item.date}</p>\n`;\nitemNode.querySelector('h2').textContent = item.name;\nitemNode.querySelector('.details').textContent = item.details;\n</code></pre>\n<p>That's if the <code>id</code> and <code>date</code> are saved in a safe form in your database by your backend, which I'd expect they are, though the code isn't in the question - eg the <code>id</code> should be saved as a number, and the date should be saved as a unix timestamp or a Date. If they aren't and you can't for whatever reason, then you'll need to sanitize whatever comes from the user manually before saving it. If you can't do that either for some reason, then you'll have to insert the <code>id</code> and <code>date</code> properties into the DOM above by using DOM methods instead of by HTML concatenation - but it'd be better to be sure that they're in an expected, safe format ahead of time.</p>\n<p>You could also enable direct concatenation of the <code>name</code> and <code>details</code> by sending them through a sanitizer before saving them to the database.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:25:26.300",
"Id": "499516",
"Score": "0",
"body": "?? Your security fix `itemNode.innerHTML = ` (last snippet) is incomplete as un-vetted content `item.id` and `item.date` are still being added to the page as markup"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:09:33.410",
"Id": "499520",
"Score": "0",
"body": "I was assuming that those were saved by the backend in a sensible (and therefore trustworthy) format, but the code that does that isn't in the question, so I guess it's not an entirely safe assumption"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T03:05:03.547",
"Id": "253290",
"ParentId": "253287",
"Score": "1"
}
},
{
"body": "<h2>Adding elements</h2>\n<p>As pointed out in "CertainPerformance's" answer adding content via HTML in this case can present a security risk.</p>\n<p>However adding elements via innerHTML should always be avoided as it is very inefficient, noisy, and hard to read and maintain (due to there being no code formatting in a string)</p>\n<p>With a few simple functions you can avoid the very slow setter <code>.innerHTML</code> and add content in an efficient way, without the verbosity of the DOM API.</p>\n<p>The following set of functions can take care of most of your HTML creation needs</p>\n<ul>\n<li><code>tag</code> creates an element and adds properties, returning the new tag.</li>\n<li><code>append</code> appends siblings to an element, returning the parent.</li>\n<li><code>query</code> queries an element returning the found element (if found)</li>\n</ul>\n<p>Code</p>\n<pre><code>const tag = (tag, props = {}) => Object.assign(document.createElement(tag), props);\nconst append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par);\nconst query = (qStr, el = document) => el.querySelector(qStr);\n</code></pre>\n<p>And would replace your code with</p>\n<pre><code>function load(quantity) {\n const url = `itemslist?start=${counter}&end=${counter + quantity - 1}`;\n const mainItems = query(".main-items");\n counter = end + 1;\n\n fetch(url)\n .then(response => response.json())\n .then(data => {\n if (data.itemslist.length > 0) {\n isListEmpty = false;\n append(mainItems, ...data.itemslist.map(addItem));\n } else {\n areMoreItems = false;\n isListEmpty && append(mainItems, addEmptyListInfo());\n }\n });\n}\n\nfunction addEmptyListInfo() {\n return tag("section", {className: "empty-list", textContent: "Your list is empty"});\n}\nfunction addItem(item) {\n return append(tag("section", {className: "todo-item"}),\n tag("p", {hidden: true, className: "id", textContent: item.id}),\n append(tag("div", {name: "delete-button", value: item.id, className:"x-wrapper"}), \n tag("i", {className: "far fa-times-circle"})\n ),\n tag("h2", {name: "name", className: "todo-item-name", textContent: item.name}),\n tag("label", {for: "details", textContent: "Details:"}),\n tag("p", {className: "details", name:"details", textContent: item.details}),\n tag("p", {className: "date", textContent: `Deadline: ${item.date}`}),\n );\n}\n</code></pre>\n<h2>Make the code work for YOU!</h2>\n<p>Personally I use a modification combing <code>tag</code> and <code>query</code> and naming it <code>$</code> (as I never use jQuery) and name <code>append</code> <code>$$</code> with helper functions to simplify common properties. Example <code>$.text</code>, <code>$.classText</code>, <code>$.class</code>, create properties, <code>textContent</code>, <code>className</code> and <code>textContent</code>, and <code>className</code> plus any additional properties.</p>\n<p>There are dozens of ways you can simplify adding content to the page. And the best thing it is lightning fast, you can really notice the speed increase when building a page using the DOM API calls</p>\n<pre><code>function addItem(item) {\n return <span class=\"math-container\">$$( $(\"<section>\", $.class(\"todo-item\")),\n $(\"<p>\", $.classText(\"id\", item.id, {hidden: true})),\n $$</span>( $("<div>", $.class("x-wrapper", {name: "delete-button", value: item.id}), \n $("<i>", $.class("far fa-times-circle"))\n ),\n $("<h2>", $.classText("todo-item-name", item.name, {name: "name"})),\n $("<label>", $.text("Details:", {for: "details"})),\n $("<p>", $.classText("details", item.details, {name:"details"})),\n $("<p>", $.classText("date", `Deadline: ${item.date}`))\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:37:58.797",
"Id": "253317",
"ParentId": "253287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T23:54:13.667",
"Id": "253287",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"django",
"sass"
],
"Title": "Task-list app, which allows to add and remove tasks from list"
}
|
253287
|
<p>Problem Statement:</p>
<blockquote>
<p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p>
<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p>
</blockquote>
<p>Implementation</p>
<pre class="lang-golang prettyprint-override"><code>func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
return helper(l1, l2, 0)
}
func helper(left *ListNode, right *ListNode, carry int) *ListNode {
if left == nil && right == nil {
if carry > 0 {
return &ListNode{
Val: carry,
}
}
return nil
}
if left == nil {
r := right.Val + carry
return &ListNode{
Val: r % 10,
Next: helper(nil, right.Next, r / 10),
}
} else if right == nil {
r := left.Val + carry
return &ListNode{
Val: r % 10,
Next: helper(left.Next, nil, r / 10),
}
}
r := left.Val + right.Val + carry
return &ListNode{
Val: r % 10,
Next: helper(left.Next, right.Next, r / 10),
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Go does not have tail recursion: <a href=\"https://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">Wikipedia: Tail call</a>. Use iteration rather than recursion.</p>\n<p>Simplify your sprawling, hard-to-read code.</p>\n<hr />\n<pre><code>type ListNode struct {\n Val int\n Next *ListNode\n}\n\n// Add Two Numbers\n// https://leetcode.com/problems/add-two-numbers/\nfunc addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {\n root := &ListNode{} // at end, start = root.Next\n end := root\n\n c := 0\n for {\n if l1 == nil && l2 == nil && c == 0 {\n break\n }\n\n v := c\n if l1 != nil {\n v += l1.Val\n l1 = l1.Next\n }\n if l2 != nil {\n v += l2.Val\n l2 = l2.Next\n }\n c = v / 10\n v = v % 10\n\n end.Next = &ListNode{\n Val: v,\n Next: nil,\n }\n end = end.Next\n }\n\n return root.Next // start\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T07:12:56.023",
"Id": "253331",
"ParentId": "253292",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T04:20:35.480",
"Id": "253292",
"Score": "0",
"Tags": [
"algorithm",
"go"
],
"Title": "Is there a better \"Go\" way to implement LC Add Two Numbers solution"
}
|
253292
|
<p>Follow up question from <a href="https://codereview.stackexchange.com/questions/252737/post-json-using-http-and-verify-whether-all-actions-completed-successfully-or-no">here</a>.</p>
<p>I am working on a project where I need to do below things in Python:</p>
<ul>
<li><p>Take few input parameters like - <code>environmentName</code>, <code>instanceName</code>, <code>configName</code> from command line.</p>
</li>
<li><p>Get JSON string as the response by calling service url. For example - Below is the JSON I will get:</p>
<p><code>{"flag":false, "configName":"abc-123.tar"}</code></p>
</li>
<li><p>Modify the above JSON by passing <code>configName</code> passed from the command line. So if <code>configName</code> is passed as <code>abc-124.tar</code> then my modified JSON will be:</p>
<p><code>{"flag":false, "configName":"abc-124.tar"}</code></p>
</li>
<li><p>Now there are two actions - <code>download</code> and <code>verify</code>. For <code>download</code> action - I will modify above JSON like below and then post this new modified JSON to same service.</p>
<p><code>{"flag":false, "configName":"abc-124.tar", "action":"download"}</code></p>
</li>
<li><p>Once all machines have downloaded successfully then I will modify my JSON again for <code>verify</code> action like below and then post this new modified JSON again to same service.</p>
<p><code>{"flag":false, "configName":"abc-124.tar", "action":"verify"}</code></p>
</li>
<li><p>Now I will verify whether all files looks good or not. But if <code>download</code> action failed then I will not do <code>verify</code> action.</p>
</li>
</ul>
<p>I am calling another endpoint to validate whether each action (download or verify) completed successfully or not. This logic is done in <code>validate</code> method.</p>
<p>Below is my code which does that and it works fine:</p>
<pre><code>import json
import sys
import requests
ACTIONS = ['download', 'verify']
ENDPOINT = "http://consul.{}.demo.com/"
CONFIG_PATH = "v1/kv/app-name/{}/config"
STATUS_PATH = "v1/kv/app-name/{}/status/{}"
CATALOG_PATH = "v1/catalog/service/app-name?ns=default&tag={}"
RAW = "?raw"
def update(url, json_):
try:
r = requests.put(url, data=json_, headers={'Content-type': 'application/json'})
r.raise_for_status()
return True
except requests.exceptions.HTTPError as http_error:
print(f"Http Error: {http_error}")
except requests.exceptions.ConnectionError as connection_error:
print(f"Error Connecting: {connection_error}")
except requests.exceptions.Timeout as timeout_error:
print(f"Timeout Error: {timeout_error}")
except requests.exceptions.RequestException as request_error:
print(f"Ops: Something Else: {request_error}")
return False
def validate(environment, instance, config, action):
flag = True
catalog_url = ENDPOINT.format(environment) + CATALOG_PATH.format(instance)
response = requests.get(catalog_url)
url = ENDPOINT.format(environment) + STATUS_PATH.format(instance) + RAW
json_array = response.json()
count = 0
for x in json_array:
ip = x['Address']
count += 1
r = requests.get(url.format(ip))
data = r.json()
# validate download action here
if (
action == 'download'
and "isDownloaded" in data
and data['isDownloaded']
and "currentCfg" in data
and data['currentCfg'] == config
):
continue
# validate verify action here
elif (
action == 'verify' and "activeCfg" in data
and data['activeCfg'] == config
):
continue
else:
flag = False
print(f"Failed to {action} on {ip}")
if flag and action == 'download':
print(f"Downloaded successfully on all {count} machines")
elif flag and action == 'verify':
print(f"Verified successfully on all {count} machines")
return flag
def main():
environment = sys.argv[1]
instance = sys.argv[2]
new_config = sys.argv[3]
# make url for get api to get JSON config
url = ENDPOINT.format(environment) + CONFIG_PATH.format(instance)
response = requests.get(url + RAW)
# get JSON string from my service
data = json.loads(response.content)
# modify json with config being passed from command line
data['remoteConfig'] = new_config
# now for each action, update json and then validate whether that
# action completed successfully or not.
for action in ACTIONS:
data['action'] = action
if update(url, json.dumps(data)):
if validate(environment, instance, new_config, action):
continue
else:
print(f"{action} action failed")
return
else:
print("failed to update")
return
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\nCaught ctrl+c, exiting")
</code></pre>
<p><strong>Problem Statement</strong></p>
<p>I have my above code which works fine so opting for code review to see if there is any better way to do the above things efficiently and cleanly. I am new to <code>Python</code> so I might have made lot of mistakes in designing it. Given this code will be running in production wanted to see what can be done to improve it?</p>
<p>The idea is something like this when I run it from the command line.</p>
<p>If everything is successful then it should look like this:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
downloaded successfully on all 10 machines
verified successfully on all 10 machines
config pushed successfully!!
</code></pre>
<p>In case of <code>download</code> action failure:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
failed to download on 1.2.3.4
failed to download on 4.2.3.4
download action failed
</code></pre>
<p>In the case of <code>verify</code> action failure:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
downloaded successfully on all 10 machines
failed to verify on 1.2.3.4
failed to verify on 4.2.3.4
verify action failed
</code></pre>
<p>or if there is any better way to make the output cleaner - I am open to the suggestion as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T09:10:05.860",
"Id": "499495",
"Score": "0",
"body": "This is a [follow-up question](https://codereview.stackexchange.com/q/252737/61966)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:23:50.913",
"Id": "499514",
"Score": "0",
"body": "Just edited it in my question as well."
}
] |
[
{
"body": "<h2>Manual serialization and content type</h2>\n<p>Try to avoid this:</p>\n<pre><code>requests.put(url, data=json_, headers={'Content-type': 'application/json'})\n \n</code></pre>\n<p>Read <a href=\"https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests\" rel=\"nofollow noreferrer\">https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests</a> . It serializes the JSON for you and sets the content type for you if you use the <code>json=</code> kwarg instead, passing a dictionary or list.</p>\n<h2>Variable naming</h2>\n<p>Rename <code>flag</code> to something like <code>is_valid</code>.</p>\n<h2>Format binding</h2>\n<p>There's a neat trick that is sometimes used in Python for constructs like this:</p>\n<pre><code>ENDPOINT = "http://consul.{}.demo.com/"\nCONFIG_PATH = "v1/kv/app-name/{}/config"\nSTATUS_PATH = "v1/kv/app-name/{}/status/{}"\nCATALOG_PATH = "v1/catalog/service/app-name?ns=default&tag={}"\n# ...\nurl = ENDPOINT.format(environment) + CONFIG_PATH.format(instance)\n</code></pre>\n<p>Instead consider</p>\n<pre><code>endpoint = "http://consul.{}.demo.com/".format\nconfig_path = "v1/kv/app-name/{}/config".format\nstatus_path = "v1/kv/app-name/{}/status/{}".format\ncatalog_path = "v1/catalog/service/app-name?ns=default&tag={}".format\n# ...\nurl = endpoint(environment) + config_path(instance)\n</code></pre>\n<p>These variables become function references, so that you can only call <code>format</code> on the referenced string and nothing else.</p>\n<h2><code>if</code>/<code>else</code></h2>\n<p>This thing in a loop:</p>\n<pre><code> if update(url, json.dumps(data)):\n if validate(environment, instance, new_config, action):\n continue\n else:\n print(f"{action} action failed")\n return\n else:\n print("failed to update")\n return\n</code></pre>\n<p>seems like it would be more easily expressed as</p>\n<pre><code>if not (\n update(url, json.dumps(data)) and\n validate(environment, instance, new_config, action)\n):\n print(f"{action} action failed")\n return\n</code></pre>\n<p>However, a better way to make use of exceptions is:</p>\n<ul>\n<li>Stop returning booleans from your inner functions</li>\n<li>Move your <code>try</code> to outside of the <code>for</code> loop in <code>main</code></li>\n<li>Also move your <code>except</code> and print statements outside of the <code>for</code> loop in <code>main</code></li>\n</ul>\n<p>Then you will not need a <code>continue</code> - simply loop, and outside of the loop if anything is caught, the loop will have been broken for you.</p>\n<h2>Return codes</h2>\n<p>You do</p>\n<pre><code>sys.exit(main())\n</code></pre>\n<p>but you never return an integer from <code>main</code>. Either drop the <code>exit</code>, or return meaningful integer codes from <code>main</code>.</p>\n<ul>\n<li>Remove your <code>if</code> applied to <code>update</code> and <code>validate</code></li>\n</ul>\n<h2>Proposed</h2>\n<p>Since your API is hosted internally I wasn't able to test this very far.</p>\n<pre><code>from argparse import ArgumentParser\nfrom typing import Tuple, List, Dict\n\nfrom requests import Session\n\n\nclass NetworkError(Exception):\n pass\n\n\nclass ValidationError(Exception):\n pass\n\n\nENDPOINT_PATH = 'http://consul.{env:}.demo.com/v1/'\n\nmake_config_url = (\n ENDPOINT_PATH + 'kv/app-name/{instance:}/config?raw'\n).format\n\nmake_status_url = (\n ENDPOINT_PATH + 'kv/app-name/{instance:}/status/{ip:}?raw'\n).format\n\nmake_catalog_url = (\n ENDPOINT_PATH + 'catalog/service/app-name'\n).format\n\n\ndef validate(\n session: Session, env: str, instance: str, new_config: str, action: str,\n machine: Dict[str, object],\n):\n ip = machine['Address']\n with session.get(\n make_status_url(env=env, instance=instance, ip=ip)\n ) as response:\n response.raise_for_status()\n status = response.json()\n\n prefix = f'{action} failed for {ip}: '\n\n if action == 'download':\n if not status.get('isDownloaded'):\n raise ValidationError(prefix + 'not downloaded')\n if status.get('currentCfg') != new_config:\n raise ValidationError(prefix + 'configuration mismatch')\n elif action == 'verify' and status.get('activeCfg') != new_config:\n raise ValidationError(prefix + 'configuration mismatch')\n\n\ndef validate_all(\n session: Session, env: str, instance: str, new_config: str, action: str\n) -> Tuple[\n int, # Succeeded machines\n int, # Total machines\n List[str], # Error messages\n]:\n """\n This will get list of all ipAddresses for that 'instance' in that 'environment'.\n And then check whether each machine/ipAddress from that list have downloaded and\n verified successfully. Basically for each 'action' type I need to validate to make\n sure each of those 'actions' completed successfully. If successful at the end then print out the message.\n\n Returns the number of machines.\n """\n\n with session.get(\n make_catalog_url(env=env),\n params={'ns': 'default', 'tag': instance}\n ) as response:\n response.raise_for_status()\n machines = response.json()\n\n n_succeeded = 0\n n_total = len(machines)\n messages = []\n\n for machine in machines:\n try:\n validate(session, env, instance, new_config, action, machine)\n except Exception as e:\n messages.append(str(e))\n n_succeeded += 1\n\n return n_succeeded, n_total, messages\n\n\ndef reconfigure(env: str, instance: str, new_config: str):\n config_url = make_config_url(env=env, instance=instance)\n\n with Session() as session:\n try:\n with session.get(config_url) as response:\n response.raise_for_status()\n data = response.json()\n except Exception as e:\n raise NetworkError('Failed to get original config') from e\n\n # modify json with config being passed from command line\n data['remoteConfig'] = new_config\n\n # now for each action, update json and then validate whether that\n # action completed successfully or not.\n for action in ('download', 'verify'):\n data['action'] = action\n try:\n with session.put(config_url, json=data) as response:\n response.raise_for_status()\n except Exception as e:\n raise NetworkError(f'Failed to update for action {action}') from e\n\n n_succeeded, n_total, errors = validate_all(session, env, instance, new_config, action)\n \n print(f'Action {action} validated for {n_succeeded}/{n_total} machines')\n print('\\n'.join(errors))\n\n\ndef main():\n parser = ArgumentParser(\n description='Reconfigure a Consul service to do some magic.',\n )\n parser.add_argument('-e', '--env')\n parser.add_argument('-i', '--instance')\n parser.add_argument('-c', '--config')\n args = parser.parse_args()\n\n try:\n reconfigure(args.env, args.instance, args.config)\n except KeyboardInterrupt:\n pass\n except Exception as e:\n print(e, end='')\n if e.__cause__ is None:\n print()\n else:\n print(':', e.__cause__)\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T18:46:52.277",
"Id": "499678",
"Score": "0",
"body": "Thanks for great suggestion. Learned something new. I will read about the link you shared about the post requests. But I am kinda confuse on this suggestion `However, a better way to make use of exceptions is:`. Do you think you can provide can example basis on my code so that I can understand properly on how to do it cleanly? Also do you see any design issues in my above code? Like it can be rewritten in better ways if possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:10:25.210",
"Id": "499680",
"Score": "0",
"body": "@AndyP Can you provide meaningful `argv` parameters for me to test this, to be able to provide an example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:18:36.500",
"Id": "499681",
"Score": "0",
"body": "In my case, `argv` parameters are gonna be exactly like what I have in my question `python test.py dev master-instace test-config-124.tgz`. Testing for you might be hard as it involves working with `Consul` service. As of now I call consul service to get JSON string and then change `configName` in the original JSON string and update it on Consul for each `action` type. If `download` action works fine successfully on each machine then I do same thing for `verify` action. Let me know if anything is unclear and then I can try to help you out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:20:30.867",
"Id": "499682",
"Score": "0",
"body": "@AndyP Is it actually `master-instace`, or is it master-_instance_ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:29:00.807",
"Id": "499683",
"Score": "0",
"body": "In this line `python test.py dev master-instace test-config-124.tgz` - `environmentName` is `dev`. `instanceName` is this `master-instace` and `configName` is this `test-config-124.tgz`. so yeah it is actually as `master-instace` value for `instanceName` command line parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T19:30:27.380",
"Id": "499684",
"Score": "1",
"body": "You should think about fixing the spelling. Anyway, I'm writing up an example."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T15:15:54.393",
"Id": "253345",
"ParentId": "253294",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253345",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T06:21:17.680",
"Id": "253294",
"Score": "2",
"Tags": [
"python",
"beginner",
"json",
"error-handling",
"http"
],
"Title": "Modify original JSON few times and post http request"
}
|
253294
|
<p>Here I have a list which is months = ["Jan", "May", "Jul", "Aug", "Oct", "Dec"]</p>
<p>I want to do the following with this list</p>
<ul>
<li>append months that are missing --->
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']</li>
<li>Delete months at index [2,5,9] from the list --->
months = ['Jan', 'Feb', 'Apr', 'May', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']</li>
</ul>
<p>Can you please help me improve the code with list appending and deleting?.</p>
<p><strong>I did the following</strong></p>
<pre><code>months = ["Jan", "May", "Jul", "Aug", "Oct", "Dec"]
# Appending "Feb", "Mar","Apr", "Jun" and "Sep" into months
months[1:1]= ["Feb", "Mar","Apr"]
months[5:5]= ["Jun"]
months[8:8]= ["Sep"]
months[10:10]= ["Nov"]
print("All months: ", months)
# Deleting index 2, 5, 9
del_index = [2, 5, 9]
months = [i for i in months if months.index(i) not in del_index]
print("Del Months:" , months)
</code></pre>
<p><strong>Outputs</strong></p>
<pre><code>All months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Del Months: ['Jan', 'Feb', 'Apr', 'May', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T09:08:50.043",
"Id": "499494",
"Score": "0",
"body": "Is `months` list going to always contain the same months / missing months? that's how it looks from you code but I just want to make sure"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T09:10:53.977",
"Id": "499496",
"Score": "0",
"body": "no, first --> months = [\"Jan\", \"May\", \"Jul\", \"Aug\", \"Oct\", \"Dec\"], after appending --> months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] then after deleting --> months = ['Jan', 'Feb', 'Apr', 'May', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T09:19:44.247",
"Id": "499497",
"Score": "0",
"body": "You didn't gen my question: is the first list (the one with the missing months) always going to be the same and ordered (by months)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T09:28:12.917",
"Id": "499498",
"Score": "0",
"body": "Yes, I want it to be in that order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:40:49.657",
"Id": "499544",
"Score": "3",
"body": "Why not just do `months = <the complete list of all 12 months>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T23:12:27.243",
"Id": "499563",
"Score": "1",
"body": "You are not appending `\"Feb\", \"Mar\",\"Apr\", \"Jun\" and \"Sep\"`, you are inserting them at the correct positions, which you had to calculate by hand. There isn't much of a program here -- are you certain you've followed the problems instructions correctly?"
}
] |
[
{
"body": "<p>So, if the resulting <code>months</code> list always needs to have all 12 months, regardless of what it had before your operation, then there is no need to insert or append:</p>\n<pre class=\"lang-py prettyprint-override\"><code>months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]\nprint("All months: ", months)\n</code></pre>\n<p>For "deleting" you can build a subset of your list with:</p>\n<pre class=\"lang-py prettyprint-override\"><code>months = [month for i, month in enumerate(months) if i not in del_index]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T07:30:07.847",
"Id": "499581",
"Score": "0",
"body": "For an easier way of defining a list of all months one can do: `import calendar; all_months=list(calendar.month_abbr)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T01:51:59.803",
"Id": "253325",
"ParentId": "253295",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T08:23:16.020",
"Id": "253295",
"Score": "-1",
"Tags": [
"python",
"beginner"
],
"Title": "List appending and deleting"
}
|
253295
|
<p><strong>Check for Expiry</strong></p>
<ul>
<li>Expiry can go from 1 to 299</li>
<li>Expiry can be 1 digit, 2 digits or 3 digits</li>
</ul>
<p>This will be the Input I check my regExp against.</p>
<pre><code>Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp276
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp82
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp2
</code></pre>
<p>exp will <strong>decrease</strong> every second by <strong>one</strong></p>
<p>My <strong>RegExp</strong></p>
<pre><code>let regExp = \exp[0-2]{0,1}[0-9]{1,2}\
</code></pre>
<p>The regeExp matches everything up from 0 up to 299.</p>
<p>Try it <a href="https://regex101.com/r/udp9BX/6" rel="nofollow noreferrer">here</a></p>
<p>What do you think about this regExp.</p>
<p>I'm looking forward to any advice about Regular Expressions</p>
|
[] |
[
{
"body": "<p>What is the volume of usage? ie 86400 time per day per user? How many users? 1, 100, 1000? Regular Expressions are slow, but slow is ok if the volume is low.</p>\n<p>Your regex is fine, though you meant / I believe. Depending on your needs this maybe a slight improvement.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const regExp = /exp(?<seconds>[0-2]?\\d{1,2})/\n\nconst tests = [\n `Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp276`,\n `Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp82`,\n `Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp2`,\n]\n\nconst results = tests.map(test=>parseInt(regExp.exec(test)?.groups?.seconds))\n\nconsole.log(results)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Secondly, a good IDE is important. While this suggestion likely has little to no performance benefit, I do feel it better expresses that fact that the first digit is optional. I considered doing the same for the second digit.</p>\n<pre><code>let regExp = /exp[0-2]{0,1}[0-9]{1,2}/\n// ^-- IDE flagged this as 'Repetition range replaceable by ?'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:15:52.333",
"Id": "253306",
"ParentId": "253301",
"Score": "0"
}
},
{
"body": "<p><strong>Shortcuts</strong> You can use 2 special regex syntax rules to make the pattern more concise:</p>\n<ul>\n<li><p>When a token may or may not be matched, instead of <code>{0,1}</code>, it can be done with <code>?</code> instead - they're exactly equivalent.</p>\n</li>\n<li><p>When you want to match a digit from 0 to 9, rather than writing out <code>[0-9]</code>, you can use <code>\\d</code> instead (they're exactly equivalent):</p>\n</li>\n</ul>\n<p><strong>Typo?</strong> Regular expressions in JS are delimited by forward slashes, not backslashes.</p>\n<p><strong>Prefer <code>const</code></strong> - Unless you plan on reassigning the <code>regExp</code> variable name, better to use <code>const</code> - only use <code>let</code> when you need to warn readers that the variable may be reassigned.</p>\n<p><strong>Missing semicolon</strong> Unless you're an expert and can avoid the pitfalls of Automatic Semicolon Insertion, I'd highly recommend using semicolons whenever appropriate, else you will occasionally run into hard-to-understand bugs.</p>\n<p><strong>Bug?</strong> You probably only want to match digits if they fulfill all the rules - I doubt you want to match the <code>30</code> part of <code>300</code>, for example. I'd expect that you want a line that ends with 300 to not match at all, right? Fix it by adding a word boundary at the end:</p>\n<pre><code>const regExp = /exp[0-2]?\\d{1,2}\\b/;\n</code></pre>\n<p>Or, if the digits will always come at the end of the line, use <code>$</code> and the <code>m</code> flag instead:</p>\n<pre><code>const regExp = /exp[0-2]?\\d{1,2}$/m;\n</code></pre>\n<p><a href=\"https://regex101.com/r/udp9BX/7\" rel=\"nofollow noreferrer\">https://regex101.com/r/udp9BX/7</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:24:50.980",
"Id": "499515",
"Score": "0",
"body": "Thank you a lot. I updated my RegEx.\nI understand the bug with my RegEx I also recognized it while testing around but I thought it is fine because this will not happen.\nBut I'm interested in the word boundary, what does this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:27:31.183",
"Id": "499518",
"Score": "0",
"body": "A word boundary will be matched if the position is between a word character and not a word character. For example, `300` doesn't match `30\\b0` because the `\\b` there is between *two* word characters. (Numbers, letters, and underscores are all word characters.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:18:09.170",
"Id": "253307",
"ParentId": "253301",
"Score": "1"
}
},
{
"body": "<p>Based on your explanation of requirements and your sample data, I get the impression that the only number that may start with a zero is <code>0</code>.</p>\n<p>For this reason, the pattern can be tightened to prevent unwanted leading zeros.</p>\n<pre><code>/exp(?:[12]\\d|[1-9])?\\d$/m\n</code></pre>\n<ul>\n<li>the hundreds digit is optional, but must be a one or a two, then followed by two digits, then the end of the line.</li>\n<li>the tens digit is optional, but must be between one and nine, then followed by a digit, then the end of the line.</li>\n<li>the ones digit is required, it can be from zero to nine, then the end of the line.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-14T07:11:42.293",
"Id": "253447",
"ParentId": "253301",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "253307",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T11:21:36.277",
"Id": "253301",
"Score": "2",
"Tags": [
"javascript",
"regex"
],
"Title": "regex check variable amount of digits"
}
|
253301
|
<p>I'm a beginner and I wonder if Is what I have created a good practice as a structure and way of working for input data processing?
Is the way I wrote the index.php file a correct and secure way of manipulation?
The majority of my programming experience (and I do mainly do it for fun) comes from following tutorials on google, so I apologize in advance if this seems an exceptionally daft question - but I do want to start improving my code.</p>
<p>Whenever I have needed to make a multidimensional array, my naming has always placed the counter in the first element.</p>
<pre><code> <?php
$file = dirname(__FILE__) . '/Validator.php';
if (file_exists($file)) {
require $file;
}
function get_intersect(...$arrays){
$instersect_arrays = array();
foreach($arrays as $array){
if(!empty($array)){
array_push($instersect_arrays,$array);
}
}
return call_user_func_array('array_intersect', $instersect_arrays);
}
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
$langs_all = [
'bg' => [ 'id' => '1', 'code' => 'bg', ],
'us' => [ 'id' => '2', 'code' => 'us', ],
'gr' => [ 'id' => '3', 'code' => 'gr', ],
];
$langs_enabled = [
'bg' => [ 'id' => '1', 'code' => 'bg', ],
'us' => [ 'id' => '2', 'code' => 'us', ],
];
$langs_default = [
'bg' => [ 'id' => '1', 'code' => 'bg', ],
];
$langs_real = array();
$langs_real = get_intersect($langs_enabled, $langs_all);
$stop = [];
if(isset($_POST['submit'])) {
$array = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING, true);
$return = array();
foreach ( array_keys($array) as $fieldKey ) {
foreach ( $array[$fieldKey] as $lang_code => $value ) {
if( in_array_r( $lang_code, $langs_real) ) {
$return[$fieldKey][$lang_code] = $value;
}
}
}
foreach ( $langs_default as $lang_code => $value ) {
// Set data and validation rules
$rules = array(
'title['.$lang_code.']' => 'required:Title|min:8|max:200',
'description['.$lang_code.']' => 'norequired:Description|min:20'
);
$data = array(
'title['.$lang_code.']' => $return['title'][$lang_code],
'description['.$lang_code.']' => $return['description'][$lang_code],
);
}
// Run validation
$validator = new Validator();
if ($validator->validate($data, $rules) == true) {
// Validation passed. Set user values.
echo "<h1>SUCCESS</h1>";
print_r ( $return );
} else {
// Validation failed. Dump validation errors.
var_dump($validator->getErrors());
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<label for="title[bg]">title bg</label> <input type="text" name="title[bg]" id="title[bg]" /><br />
<label for="title[us]">title us</label> <input type="text" name="title[us]" id="title[us]" /><br />
<label for="title[gr]">title gr</label> <input type="text" name="title[gr]" id="title[gr]" /><br /><br />
<label for="description[bg]">description bg</label> <input type="text" name="description[bg]" id="description[bg]" /><br />
<label for="description[us]">description us</label> <input type="text" name="description[us]" id="description[us]" /><br />
<label for="description[gr]">description gr</label> <input type="text" name="description[gr]" id="description[gr]" /><br />
<input type="submit" name="submit" />
</form>
</code></pre>
<p>Validator.php</p>
<pre><code>
<?php
class Validator
{
/**
* Validation errors
* @var array
*/
private $errors = array();
private $Msg = array();
/**
* Validate data against a set of rules and set errors in the $this->errors
* array
* @param array $data
* @param array $rules
* @return boolean
*/
public function validate (Array $data, Array $rules)
{
$valid = true;
foreach ($rules as $item => $ruleset) {
// required|email|min:8|msg:title
$ruleset = explode('|', $ruleset);
foreach ($ruleset as $rule) {
$pos = strpos($rule, ':');
if ($pos !== false) {
$parameter = substr($rule, $pos + 1);
$rule = substr($rule, 0, $pos);
}
else {
$parameter = '';
}
// validateEmail($item, $value, $param)
$methodName = 'validate' . ucfirst($rule);
$value = isset($data[$item]) ? $data[$item] : NULL;
if (method_exists($this, $methodName)) {
$this->$methodName($item, $value, $parameter) OR $valid = false;
}
}
}
return $valid;
}
/**
* Get validation errors
* @return array:
*/
public function getErrors ()
{
return $this->errors;
}
/**
* Validate the $value of $item to see if it is present and not empty
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateRequired ($item, $value, $parameter)
{
if ($value === '' || $value === NULL || $parameter == false) {
$this->Msg[$item] = $parameter;
$Msg = isset($parameter) ? $parameter : $item;
$this->errors[$item][] = 'The '.$Msg.' field is required';
return false;
}
return true;
}
/**
* Validate the $value of $item to see if it is present and not empty
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateNorequired ($item, $value, $parameter)
{
$this->Msg[$item] = $parameter;
return true;
}
/**
* Validate the $value of $item to see if it is a valid email address
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateEmail ($item, $value, $parameter)
{
if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
$Msg[$item] = isset($this->Msg[$item]) ? $this->Msg[$item] : $item;
$this->errors[$item][] = 'The ' . $Msg[$item] . ' field should be a valid email addres';
return false;
}
return true;
}
/**
* Validate the $value of $item to see if it is fo at least $param
* characters long
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateMin ($item, $value, $parameter)
{
if (strlen($value) >= $parameter == false) {
$Msg[$item] = isset($this->Msg[$item]) ? $this->Msg[$item] : $item;
$this->errors[$item][] = 'The ' . $Msg[$item] . ' field should have a minimum length of ' . $parameter;
return false;
}
return true;
}
/**
* Validate the $value of $item to see if it is fo at least $param
* characters long
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateMax ($item, $value, $parameter)
{
if (strlen($value) < $parameter == false) {
$Msg[$item] = isset($this->Msg[$item]) ? $this->Msg[$item] : $item;
$this->errors[$item][] = 'The ' . $Msg[$item] . ' field should have a maximum length of ' . $parameter;
return false;
}
return true;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:21:01.697",
"Id": "499529",
"Score": "2",
"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": "2020-12-10T16:21:32.750",
"Id": "499530",
"Score": "2",
"body": "Please note: generic best practices are outside the scope of this site. 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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T04:54:50.550",
"Id": "499656",
"Score": "0",
"body": "Initially on Stack Overflow: https://stackoverflow.com/q/65233025/2943403"
}
] |
[
{
"body": "<p>The thing that strikes me first is that there are 3 declared lookup arrays with redundant data in them. I see that the script needs to combine and filter these arrays. I would begin the refactor by eliminating redundant data -- declare a single lookup and add any additional metadata within the subarrays.</p>\n<p>Until your app has <code>code</code> values that differ from the keys in <code>$lang</code>, remove this unnecessary/redundant column.</p>\n<p>Declare the key of the default item for instant referencing/maintenance.</p>\n<pre><code>$defaultLang = 'bg';\n\n$langs = [\n 'bg' => ['id' => 1, 'active' => true],\n 'us' => ['id' => 2, 'active' => true],\n 'gr' => ['id' => 3, 'active' => false],\n];\n</code></pre>\n<p>This way you have a time complexity of O(1) to find the default entry. You probably free yourself from needing those helper functions too.</p>\n<p>Even your html form markup generation can be DRYed out by leveraging the single lookup array.</p>\n<p>The explicit truthy check of <code> == true</code> can be omitted. By removing those 8 characters the exact same condition is evaluated for an identical result.</p>\n<p>Inside of the inner loop of the validate method, I recommend unconditionally exploding on the optional colon. An early return is appropriate.</p>\n<pre><code>public function validate (array $data, array $rules): bool\n{\n foreach ($rules as $item => $ruleset) {\n // required|email|min:8|msg:title\n $ruleset = explode('|', $ruleset);\n foreach ($ruleset as $rule) {\n [$rule, $param] = array_pad(explode(':', $rule, 2), 2, ''); \n $methodName = 'validate' . ucfirst($rule);\n if (!method_exists($this, $methodName)\n || !$this->$methodName($item, $data[$item] ?? null, $parameter)\n ) {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n<p>...you might prefer to throw an exception if a dynamically called method does not exist.</p>\n<p>Some other DRYing techniques can be realized in <code>validateRequired()</code>. I always try to eliminate single-use variables.</p>\n<pre><code> private function validateRequired ($item, $value, $parameter)\n {\n if ((string)$value === '' || !$parameter) {\n $this->Msg[$item] = $parameter;\n $this->errors[$item][] = 'The ' . ($parameter ?? $item) . ' field is required';\n return false;\n }\n \n return true;\n }\n</code></pre>\n<p>In fact, all <code>isset()</code> calls that exist in your posted code can be swapped out for null coalescing operators.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T05:42:22.587",
"Id": "253411",
"ParentId": "253303",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T11:52:16.370",
"Id": "253303",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "What good practice to use for input data with arrays?"
}
|
253303
|
<p>I am trying to get my head around how MVVM pattern works. Would like to hear some reviews if I am implementing it correctly.</p>
<p><strong>View</strong></p>
<pre><code><Window x:Class="Login_App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Login_App"
xmlns:vm ="clr-namespace:Login_App.ViewModel"
mc:Ignorable="d"
Title="Login" Height="380" Width="650" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<vm:LoginVM x:Key="vm"/>
</ResourceDictionary>
</Window.Resources>
<StackPanel DataContext="{StaticResource vm}">
<TextBlock Text="Username"/>
<TextBox Text="{Binding Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="Password"/>
<TextBox Text="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Login"
Command="{Binding LoginCommand}"
CommandParameter="{Binding User}"/>
</StackPanel>
</Window>
</code></pre>
<p><strong>LoginView.xaml.cs</strong></p>
<pre><code>namespace Login_App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
LoginVM viewModel;
public MainWindow()
{
InitializeComponent();
viewModel = Resources["vm"] as LoginVM;
viewModel.Authenticated += ViewModel_Authenticated;
}
private void ViewModel_Authenticated(object sender, EventArgs e)
{
Close();
}
}
}
</code></pre>
<p><strong>Model</strong></p>
<pre><code>namespace Login_App.Model
{
public class UserModel
{
public int UserID { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int DepartmentID { get; set; }
public int GroupID { get; set; }
public bool Inactive { get; set; }
}
}
</code></pre>
<p><strong>ViewModel</strong></p>
<p>This is the structure:</p>
<p><a href="https://i.stack.imgur.com/lg4tM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lg4tM.png" alt="enter image description here" /></a></p>
<p><strong>LoginVM.cs</strong></p>
<pre><code>namespace Login_App.ViewModel
{
public class LoginVM : INotifyPropertyChanged
{
private UserModel user;
public UserModel User
{
get { return user; }
set
{
user = value;
OnPropertyChanged("User");
}
}
private string username;
public string Username
{
get { return username; }
set
{
username = value;
User = new UserModel
{
Username = username,
Password = this.Password
};
OnPropertyChanged("Username");
}
}
private string password;
public string Password
{
get { return password; }
set
{
password = value;
User = new UserModel
{
Username = this.Username,
Password = password
};
OnPropertyChanged("Password");
}
}
public Commands.LoginCommand LoginCommand { get; set; }
public LoginVM()
{
LoginCommand = new Commands.LoginCommand(this);
user = new UserModel();
}
public async void Login()
{
bool result = await Helpers.MySQLHelper.Login(User);
if (result)
{
Authenticated?.Invoke(this, new EventArgs());
}
}
public EventHandler Authenticated;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
</code></pre>
<p><strong>Commands > LoginCommand.cs</strong></p>
<pre><code>namespace Login_App.ViewModel.Commands
{
public class LoginCommand : ICommand
{
public LoginVM ViewModel { get; set; }
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public LoginCommand(LoginVM vm)
{
ViewModel = vm;
}
public bool CanExecute(object parameter)
{
UserModel user = parameter as UserModel;
if (user == null)
return false;
if (string.IsNullOrEmpty(user.Username))
return false;
if (string.IsNullOrEmpty(user.Password))
return false;
return true;
}
public void Execute(object parameter)
{
ViewModel.Login();
}
}
}
</code></pre>
<p><strong>Helpers > MySQLHelper.cs</strong></p>
<pre><code>namespace Login_App.ViewModel.Helpers
{
public class MySQLHelper
{
// Connection string
private static string connectionString = "server=localhost;user id=root;password=password;persistsecurityinfo=True;database=Logindatabase";
// Login Functionality
public static async Task<bool> Login(UserModel user)
{
try
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*), u.id FROM users u WHERE Username = @Username AND Password = @Password", conn))
{
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password", user.Password);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
App.UserId = dt.Rows[0][1].ToString();
return true;
}
else
{
MessageBox.Show("Incorrect Username or Password", "Login App Error", MessageBoxButton.OK, MessageBoxImage.Warning);
return false;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Login App Error", MessageBoxButton.OK, MessageBoxImage.Warning);
return false;
}
}
}
}
</code></pre>
<p><strong>Edit 1 - Using dapper</strong></p>
<p>I have been recommended to use Dapper, and I see it is far less coding rather than doing the standard <code>MySQLCommand cmd = new...</code> etc..</p>
<p>So here it is.</p>
<p>I have used message box just to see what value will be returned.</p>
<pre><code>public class MySQLHelper
{
// Login Functionality
public static async Task<bool> Login(UserModel user)
{
try
{
/// Query to get count of users from the parameters provided by the user.
/// On successful Login, the details from the database,
/// will be saved in the <App.xaml.cs> file.
string mysqlUserDetails = "SELECT COUNT(*), u.id AS UserID, Username, Email, DepartmentID, Inactive" +
" FROM users u WHERE Username = @Username AND Password = MD5(@Password)";
using(var connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString))
{
var userDetails = connection.Query<UserModel>(mysqlUserDetails, new { Username = user.Username, Password = user.Password }).ToList();
// Determine whether to autherize or not
if(userDetails.Count == 1)
{
var details = userDetails.First();
App.UserId = details.UserID;
App.Username = details.Username;
App.Email = details.Email;
App.DepartmentID = details.DepartmentID;
App.Inative = details.Inactive;
}
}
return false;
}
catch (Exception ex)
{
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:03:45.060",
"Id": "499519",
"Score": "0",
"body": "Your code formatting appears to be off in MySQLHelper.cs around the if/else statement. you should double check to make sure you don't have any errors there. it could just be a copy paste error, it happens sometimes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:27:13.607",
"Id": "499523",
"Score": "1",
"body": "@Malachi Thank you for that. Have updated the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:16:29.067",
"Id": "499527",
"Score": "0",
"body": "Use https://github.com/StackExchange/Dapperinstead of ADO.NET. Don't call a class \"helper\". Don't hardcode a connection string (get it from a config file). Don't mix UI and backend-code (`MessageBox.Show` in your MySqlHelper class)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:34:56.833",
"Id": "499533",
"Score": "0",
"body": "@BCdotWEB Hi, the link does not work. How would you show an error message?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T08:13:10.990",
"Id": "499583",
"Score": "0",
"body": "https://github.com/StackExchange/Dapper . Method returns result -> UI level inspects results and shows message if necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T09:21:02.650",
"Id": "499586",
"Score": "0",
"body": "@BCdotWEB Thank you for the tip using the `app.config` file, for the connection string. Much appreciated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T10:59:26.157",
"Id": "499588",
"Score": "0",
"body": "@BCdotWEB See `Edit 1` where amended code to use `Dapper`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-25T20:11:59.083",
"Id": "500724",
"Score": "1",
"body": "[Relaying Command Logic](https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern#relaying-command-logic) and [Overriding `OnStartup` to instantiate ViewModels](https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern#mainwindowviewmodel-class) can be useful here. I'm not sure that `ResourceDictionary` is the best place to store ViewModel. Learn something about \"Composition Root\" in MVVM apps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T09:09:35.457",
"Id": "500751",
"Score": "1",
"body": "@aepot Spasibo :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T14:34:36.953",
"Id": "253308",
"Score": "2",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "C# Learning MVVM by creating a Login functionality"
}
|
253308
|
<p>This is wrapper for <a href="https://docs.python.org/3/library/poplib.html#poplib.POP3" rel="nofollow noreferrer"><code>POP3</code></a>, <a href="https://docs.python.org/3/library/poplib.html#poplib.POP3_SSL" rel="nofollow noreferrer"><code>POP3_SSL</code></a>, <a href="https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4" rel="nofollow noreferrer"><code>IMAP4</code></a>, <a href="https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4_SSL" rel="nofollow noreferrer"><code>IMAP4_SSL</code></a>, <a href="https://docs.python.org/3/library/smtplib.html#smtplib.SMTP" rel="nofollow noreferrer"><code>SMTP</code></a> and <a href="https://docs.python.org/3/library/smtplib.html#smtplib.SMTP_SSL" rel="nofollow noreferrer"><code>SMTP_SSL</code></a> classes which let them work through proxies. For creating socket with proxy I've used <a href="https://pypi.org/project/PySocks/" rel="nofollow noreferrer"><em>PySocks</em></a>.</p>
<p><strong>Code:</strong></p>
<pre class="lang-py prettyprint-override"><code>from imaplib import IMAP4, IMAP4_SSL, IMAP4_PORT, IMAP4_SSL_PORT
from poplib import POP3, POP3_SSL, POP3_PORT, POP3_SSL_PORT
from smtplib import SMTP, SMTP_SSL, SMTP_PORT, SMTP_SSL_PORT
from socks import create_connection, PROXY_TYPE_HTTP, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5
import socket
import sys
from urllib.parse import urlparse
from collections import namedtuple
def imap_before_connection(self, *args):
sys.audit("imaplib.open", self, self.host, self.port)
def smtp_before_connection(self, host, port):
if self.debuglevel > 0:
self._print_debug('connect: to', (host, port), self.source_address)
def pop_before_connection(*args):
pass
DEFAULT_SETTINGS = {
POP3_SSL: (POP3_SSL_PORT, pop_before_connection),
IMAP4_SSL: (IMAP4_SSL_PORT, imap_before_connection),
SMTP_SSL: (SMTP_SSL_PORT, smtp_before_connection),
POP3: (POP3_PORT, pop_before_connection),
IMAP4: (IMAP4_PORT, imap_before_connection),
SMTP: (SMTP_PORT, smtp_before_connection)
}
def proxify(base_type):
for type_, (default_port, before_connection) in DEFAULT_SETTINGS.items():
if issubclass(base_type, type_):
break
else:
raise TypeError(f"Can't proxify {base_type}")
class Proxified(base_type):
Proxy = namedtuple("Proxy", ("host", "port", "username", "password", "proxy_type", "rdns"))
on_before_connection = before_connection
@staticmethod
def parse_proxy_string(proxy_string):
if not proxy_string:
return None
parsed = urlparse(proxy_string)
_scheme = parsed.scheme.lower()
if _scheme in {"http", "https"}:
proxy_type, remote_dns = PROXY_TYPE_HTTP, True
elif _scheme in {"socks4", "socks4a"}:
proxy_type, remote_dns = PROXY_TYPE_SOCKS4, _scheme.endswith("a")
elif _scheme in {"socks5", "socks5h"}:
proxy_type, remote_dns = PROXY_TYPE_SOCKS5, _scheme.endswith("h")
else:
raise ValueError(f'"{_scheme}" is not supported proxy type')
return Proxified.Proxy(parsed.hostname, parsed.port, parsed.username, parsed.password,
proxy_type, remote_dns)
def __init__(self, host="", port=default_port, *args, **kwargs):
self.proxy = self.parse_proxy_string(kwargs.pop("proxy", ""))
super().__init__(host, port, *args, **kwargs)
def _create_socket(self, timeout): # used in POP3 and IMAP
return self._get_socket(self.host, self.port, timeout)
def _get_socket(self, host, port, timeout): # used in SMTP
if timeout is not None and not timeout:
raise ValueError('Non-blocking socket (timeout=0) is not supported')
self.on_before_connection(self, host, port)
if not self.proxy:
sock = socket.create_connection(
(host, port),
timeout,
getattr(self, "source_address", None)
)
else:
sock = create_connection( # socks.create_connection
(host, port),
timeout,
getattr(self, "source_address", None),
self.proxy.proxy_type,
self.proxy.host,
self.proxy.port,
self.proxy.rdns,
self.proxy.username,
self.proxy.password
)
ssl_context = getattr(self, "context", None) or getattr(self, "ssl_context", None)
if ssl_context:
return ssl_context.wrap_socket(sock, server_hostname=host)
else:
return sock
return Proxified
</code></pre>
<p><strong>Usage:</strong></p>
<pre class="lang-py prettyprint-override"><code>from imaplib import IMAP4, IMAP4_SSL
from poplib import POP3, POP3_SSL
from smtplib import SMTP, SMTP_SSL
mail, mail_pass = "email@example.com", "password"
http_proxy = "http://username:password@127.0.0.1:8080"
pop_server = "pop.example.com"
imap_server = "imap.example.com"
smtp_server = "smtp.example.com"
pop_handler = proxify(POP3)(pop_server, proxy=http_proxy)
pop_secure_handler = proxify(POP3_SSL)(pop_server, proxy=http_proxy)
imap_handler = proxify(IMAP4)(imap_server, proxy=http_proxy)
imap_secure_handler = proxify(IMAP4_SSL)(imap_server, proxy=http_proxy)
smtp_handler = proxify(SMTP)(smtp_server, proxy=http_proxy)
smtp_secure_handler = proxify(SMTP_SSL)(smtp_server, proxy=http_proxy)
</code></pre>
<p>It works and works good but I look on this code and .. I feel that solution is a bit cumbersome.</p>
<p>Could you please take a look on it and point me what I've done in "wrong" way and suggest the correct way. Thanks.</p>
<p><strong>UPD.</strong></p>
<p>There's also another option which looks much better <em>(imho)</em>, but it uses <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch" rel="nofollow noreferrer"><code>mock.patch()</code></a> and I'm not quite sure that it's okay to use it in production.</p>
<p><strong>Code:</strong></p>
<pre class="lang-py prettyprint-override"><code>from poplib import POP3
from imaplib import IMAP4
from smtplib import SMTP
from functools import wraps, partial
from collections import namedtuple
from unittest.mock import patch
from urllib.parse import urlparse
from socks import create_connection, PROXY_TYPE_HTTP, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5
def mock_if_proxy(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
if self.proxy:
with patch("socket.create_connection",
partial(create_connection, proxy_type=self.proxy.proxy_type, proxy_addr=self.proxy.host,
proxy_port=self.proxy.port, proxy_rdns=self.proxy.rdns,
proxy_username=self.proxy.username, proxy_password=self.proxy.password)):
return method(self, *args, **kwargs)
else:
return method(self, *args, **kwargs)
return wrapper
def proxify(base_type):
if not issubclass(base_type, (POP3, IMAP4, SMTP)):
raise TypeError(f"Can't proxify {base_type}")
class Proxified(base_type):
# skipped Proxy and parse_proxy_string() declaration, it's the same
if hasattr(base_type, "_create_socket"):
_create_socket = mock_if_proxy(base_type._create_socket)
if hasattr(base_type, "_get_socket"):
_get_socket = mock_if_proxy(base_type._get_socket)
def __init__(self, *args, **kwargs):
self.proxy = self.parse_proxy_string(kwargs.pop("proxy", ""))
super().__init__(*args, **kwargs)
return Proxified
</code></pre>
<p>Maybe you could advice me a better way without <code>mock</code>?</p>
|
[] |
[
{
"body": "<h2>Iteration</h2>\n<pre><code>for type_, (default_port, before_connection) in DEFAULT_SETTINGS.items():\n</code></pre>\n<p>doesn't necessarily need a <code>for / break</code>: an alternative is</p>\n<pre><code>try:\n default_port, before_connection = next(\n vals for type_, vals in DEFAULT_SETTINGS.items()\n if issubclass(base_type, type_)\n )\nexcept StopIteration:\n raise TypeError(f"Can't proxify {base_type}")\n</code></pre>\n<h2>namedtuple</h2>\n<p>This:</p>\n<pre><code> Proxy = namedtuple("Proxy", ("host", "port", "username", "password", "proxy_type", "rdns"))\n</code></pre>\n<p>isn't bad, but consider replacing it with a <code>@dataclass</code> having typed members. This will improve your static analysis (as much as that's meaningful in Python).</p>\n<h2>Explicit <code>None</code> checks</h2>\n<pre><code> if timeout is not None and not timeout:\n</code></pre>\n<p>is a little muddy. You have an explicit <code>None</code> check, but then use truthy syntax to imply a zero-check. You're better off just spelling out</p>\n<pre><code>if timeout == 0:\n</code></pre>\n<p>which, given this context, has the same effect.</p>\n<h2>Type hints</h2>\n<p>Particularly for signatures like</p>\n<pre><code> def _get_socket(self, host: str, port: int, timeout: int) -> socket: # used in SMTP\n</code></pre>\n<p>type hints are often even more useful than documentation in understanding what a method is supposed to do.</p>\n<h2>General</h2>\n<p>I'd recommend your first approach over using <code>mock</code>, which I usually only expect to see in tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T06:50:59.127",
"Id": "499580",
"Score": "0",
"body": "1. I need `items()` in that case, because after I `break` loop values of `default_port` and `before_connection` is remaining from last iteration and I use this values in class declaration. 2. I can't replace this loop with `all()`, I possibly can replace it with `any()` but it will require to iterate over loop again to search for settings. 3. I copied this *explicit `None` check* from code of `imaplib` and left like it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T07:54:15.777",
"Id": "499582",
"Score": "0",
"body": "Doublechecked about `None` and found it in sources of all modules I'm working with: [*poplib*](https://github.com/python/cpython/blob/67b769f5157c9dad1c7dd6b24e067b9fdab5b35d/Lib/poplib.py#L111), [*imaplib*](https://github.com/python/cpython/blob/67b769f5157c9dad1c7dd6b24e067b9fdab5b35d/Lib/imaplib.py#L295), [*smtplib*](https://github.com/python/cpython/blob/67b769f5157c9dad1c7dd6b24e067b9fdab5b35d/Lib/smtplib.py#L306). About static typing - I haven't added it because I won't use this methods at all, I'm overriding it and somewhere deep it uses by module itself, so I see no reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:49:24.027",
"Id": "499602",
"Score": "0",
"body": "About `items()`, I misinterpreted what's going on - edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:50:05.820",
"Id": "499604",
"Score": "0",
"body": "About `None` - just because someone else does something bad, that doesn't mean that you have to follow suit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:51:04.837",
"Id": "499605",
"Score": "0",
"body": "And about typing - types still have value even if they're not directly, externally visible. Your unit tests that you should be writing will benefit from them, and any sort of `mypy` verification will benefit from them too."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T04:36:58.333",
"Id": "253328",
"ParentId": "253311",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T15:50:29.390",
"Id": "253311",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"mocks",
"proxy"
],
"Title": "Universal class for proxifying poplib, imaplib and smtplib. Lame inheritance or mock or something else?"
}
|
253311
|
<p>I am a beginner in Python, and I made a Morse translator that converts letters to Morse, and Morse to letters (where a decimal point is 'dot' and underscore is 'dash'). Is there any way I could make my code shorter and more efficient? For reference, <a href="https://en.wikipedia.org/wiki/Morse_code" rel="noreferrer">here's the translation</a> of Morse to letter characters.</p>
<pre><code>dot = '.'
dash = '_'
letter_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
morse_list = [dot + dash, dash + dot * 3, dash + dot + dash + dot, dash + dot * 2, dot, dot * 2 + dash + dot,
dash * 2 + dot, dot * 4, dot * 2, dot + dash * 3, dash + dot + dash, dot + dash + dot * 2,
dash * 2, dash + dot, dash * 3, dot + dash * 2 + dot, dash * 2 + dot + dash, dot + dash + dot,
dot * 3, dash, dot * 2 + dash, dash * 3 + dot, dot + dash * 2, dash + dot * 2 + dash,
dash + dot + dash * 2, dash * 2 + dot * 2]
# The for loop below prints the entire translation (Eg. 'A: ._ B: _...') so the user could reference it
for n in range(len(letter_list)):
print(letter_list[n] + ': ' + morse_list[n], sep=' ', end=' ', flush=True)
while True:
print("\nTYPE 'EXIT' if you want to EXIT.")
user_input = input("INPUT LETTERS OR MORSE CHARACTERS (DECIMAL AND UNDERSCORE) TO CONVERT."
"\nSEPERATE LETTERS WITH SPACES: ")
# Converts user input into an iterable list
user_list = user_input.split()
if user_input == 'EXIT':
print("THANK YOU FOR USING THE MORSE TRANSLATOR")
break
for i in range(len(user_list)):
if user_list[i] in letter_list:
for n in range(len(morse_list)):
if user_list[i] == letter_list[n]:
print(morse_list[n], sep=' ', end=' ', flush=True)
elif user_list[i] in morse_list:
for n in range(len(letter_list)):
if user_list[i] == morse_list[n]:
print(letter_list[n], sep=' ', end=' ', flush=True)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T18:02:11.810",
"Id": "499550",
"Score": "0",
"body": "Yes. Mixed translations are allowed. So if the user inputs 'A ._' it will output, '._ A'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T18:24:35.950",
"Id": "499552",
"Score": "0",
"body": "I would suggest a `dictionary`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T18:30:36.583",
"Id": "499554",
"Score": "1",
"body": "Since the morse code are known at compile time, why calculate them? You should simply map `A: '.-'` instead, this saves the multiplication and addition cost"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T23:28:02.727",
"Id": "499564",
"Score": "0",
"body": "@theProgrammer Thank you for the tips. The reason I did not map it was because I might want to change the value of dot and dash. So dot could be either ```• and —``` rather than ```. and _```. If it's in a variable, i would only have to change 2 lines, rather than an entire dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T12:53:12.537",
"Id": "499594",
"Score": "0",
"body": "`Concatenation` of strings are relatively expensive but its okay for this scenario, but do keep that in mind."
}
] |
[
{
"body": "<p>There is no need to store characters in a list when you can do it in a string.</p>\n<p>Instead of the confusion index checks all over your code, use can usea 2 python <code>dict</code>:</p>\n<pre><code>dot = '.'\ndash = '_'\nletter_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\nmorse_list = [dot + dash,\n dash + dot * 3,\n dash + dot + dash + dot,\n dash + dot * 2, dot,\n dot * 2 + dash + dot,\n dash * 2 + dot,\n dot * 4, dot * 2,\n dot + dash * 3,\n dash + dot + dash,\n dot + dash + dot * 2,\n dash * 2,\n dash + dot, dash * 3,\n dot + dash * 2 + dot,\n dash * 2 + dot + dash,\n dot + dash + dot,\n dot * 3, dash,\n dot * 2 + dash,\n dash * 3 + dot,\n dot + dash * 2,\n dash + dot * 2 + dash,\n dash + dot + dash * 2,\n dash * 2 + dot * 2]\n\ndct = dict(list(zip(letter_list, morse_list)) + list(zip(morse_list, letter_list)))\n\nprint(" ".join(f"{k}: {dct[k]}" for k in dct))\n\nwhile True:\n print("\\nTYPE 'EXIT' if you want to EXIT.")\n user_input = input("INPUT LETTERS OR MORSE CHARACTERS (DECIMAL AND UNDERSCORE) TO CONVERT."\n "\\nSEPERATE LETTERS WITH SPACES: ")\n if user_input == 'EXIT':\n print("THANK YOU FOR USING THE MORSE TRANSLATOR")\n break\n user_list = user_input.split()\n print(" ".join(dct.get(i) for i in user_list))\n</code></pre>\n<hr />\n<p>For more understanding of what <code>dict(list(zip(letter_list, morse_list)) + list(zip(morse_list, letter_list)))</code> does:</p>\n<ul>\n<li><code>list(zip([1, 2, 3], "abc"))</code> would return <code>[(1, 'a'), (2, 'b'), (3, 'c')]</code></li>\n<li><code>list(zip("abc", [1, 2, 3]))</code> would return <code>[('a', 1), ('b', 2), ('c', 3)]</code></li>\n<li><code>list(zip([1, 2, 3], "abc")) + list(zip("abc", [1, 2, 3]))</code> would return <code>[(1, 'a'), (2, 'b'), (3, 'c'), ('a', 1), ('b', 2), ('c', 3)]</code></li>\n<li><code>dict(list(zip([1, 2, 3], "abc")) + list(zip("abc", [1, 2, 3])))</code> would return <code>{1: 'a', 2: 'b', 3: 'c', 'a': 1, 'b': 2, 'c': 3}</code></li>\n</ul>\n<hr />\n<p>UPDATE:</p>\n<pre><code>d = dict(zip(letter_list, morse_list))\nd.update(zip(morse_list, letter_list))\n</code></pre>\n<p>is more efficient than</p>\n<pre><code>d = dict(list(zip(letter_list, morse_list)) + list(zip(morse_list, letter_list)))\n</code></pre>\n<p>Credits to GZ0 and superb rain in the comments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T17:12:38.263",
"Id": "253315",
"ParentId": "253313",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Since it is really difficult to tell what letter maps to what, it will be much easier to validate your code (for yourself & future maintainers) if you write out the dictionary directly:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>CHAR_TO_MORSE = {\n 'A': '._',\n 'B': '_...',\n 'C': '_._.',\n 'D': '_..',\n 'E': '.',\n 'F': '.._.',\n 'G': '__.',\n 'H': '....',\n 'I': '..',\n 'J': '.___',\n 'K': '_._',\n 'L': '._..',\n 'M': '__',\n 'N': '_.',\n 'O': '___',\n 'P': '.__.',\n 'Q': '__._',\n 'R': '._.',\n 'S': '...',\n 'T': '_',\n 'U': '.._',\n 'V': '___.',\n 'W': '.__',\n 'X': '_.._',\n 'Y': '_.__',\n 'Z': '__..',\n}\nMORSE_TO_CHAR = {v: k for k, v in CHAR_TO_MORSE.items()}\nCHAR_OR_MORSE_TO_INVERSE = {**CHAR_TO_MORSE, **MORSE_TO_CHAR}\n</code></pre>\n<ol start=\"2\">\n<li>Avoid string concatenation (<code>+</code>) when possible (mostly for performance):</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>print(' '.join("{}: {}".format(k, v) for k, v in CHAR_TO_MORSE.items()))\n</code></pre>\n<ol start=\"3\">\n<li>Very minor but check exit condition before parsing:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>if user_input == 'EXIT':\n break\nuser_list = user_input.split()\n</code></pre>\n<ol start=\"4\">\n<li>What happens if the input contains neither a single char nor valid morse? Your program will eat it, potentially at the confusion of the user. Maybe you can default to printing a question mark; something like:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>print(' '.join(CHAR_OR_MORSE_TO_INVERSE.get(c, '?') for c in user_list))\n</code></pre>\n<p>Note that this uses a single dictionary lookup per item <code>user_list</code>, which is about as efficient as you could ask for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T02:17:15.343",
"Id": "499574",
"Score": "1",
"body": "+1 for the nice review. There is an extra `{` after `CHAR_TO_MORSE` and a missing `)` in the first print. The first print can also be shorten using f-strings: `print(' '.join(f'{k}: {v}' for k, v in CHAR_TO_MORSE.items()))`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T22:58:08.237",
"Id": "253323",
"ParentId": "253313",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T16:27:24.003",
"Id": "253313",
"Score": "10",
"Tags": [
"python",
"beginner",
"python-3.x",
"morse-code"
],
"Title": "Morse Translator in Python"
}
|
253313
|
<p><strong>My Code</strong></p>
<pre><code>import shutil
import os
from pathlib import Path
from datetime import datetime
DOWNLOAD_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3/")
ZIPPED_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3.zip")
ZIPPED_DIR.mkdir(exist_ok=True)
def make_archive(source, destination):
delivery_file_name = destination.split("/")[-1]
delivery_name = delivery_file_name.split(".")[0]
format = delivery_file_name.split(".")[1]
archive_from = os.path.dirname(source)
archive_to = os.path.basename(source.strip(os.sep))
shutil.make_archive(delivery_name, format, archive_from, archive_to)
shutil.move(
"%s.%s" % (delivery_name, format),
"/Users/my_name/Desktop/Zip Test/zipped_content",
)
make_archive(str(DOWNLOAD_DIR), str(ZIPPED_DIR))
</code></pre>
<p><strong>Description</strong></p>
<p>I am very new to python so i had a very hard time getting shutil.make_archive to do what i want. This code is finally working and i feel it is a little hard to read so i was wondering if someone can help me refactor this to simplify it. I don't want to loose the functionality of what i am doing. In my code i basically go to my <code>/Users/my_name/Desktop/Zip Test</code> and inside it is a folder called <code>g_2020-12-10_3</code> which contains the contents i want to zip up so i do that.</p>
<p>When i unzip the contents it unzips folder named <code>g_2020-12-10_3</code> and inside it are the contents.</p>
<p>I want to keep this functionality but at the same time simplify the code below and any help would be appreciated here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T21:05:22.810",
"Id": "499560",
"Score": "1",
"body": "Why did you try to use pathlib, just to turn everything into a string and make it yourself? Pathlib provides all the APIs you need to do the kinds of operations you did"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T21:12:03.743",
"Id": "499561",
"Score": "0",
"body": "right, i am not as familiar with pathlib i know i can do somethings like rglob etc to look up files"
}
] |
[
{
"body": "<p>You're using <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a>, which is great! Unfortunately, you immediately discard the functionality it gives you, and use old-style <code>os</code> APIs.</p>\n<p>A good place to start is <a href=\"https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module\" rel=\"nofollow noreferrer\">here</a> - a mapping between the <code>os[.path]</code> APIs and their <code>Path</code> equivalents. Doing that gets us here:</p>\n<pre><code>def make_archive2(source, destination):\n shutil.make_archive(destination.stem, destination.suffix, source.parent, source.name)\n shutil.move(destination, "/Users/my_name/Desktop/Zip Test/zipped_content")\n</code></pre>\n<p>We now don't need to do any manual manipulations using <code>os</code> or <code>os.path</code>. Once we're here, we can actually realize that the first parameter to <a href=\"https://docs.python.org/3/library/shutil.html#shutil.make_archive\" rel=\"nofollow noreferrer\"><code>make_archive</code></a> is a <em>full path</em> to the file, completely removing the requirement to call <code>shutil.move</code></p>\n<p>From there, we can improve some of the other things you do. For example:</p>\n<ul>\n<li>Your source and destination are the same thing... but you don't actually use the destination in a meaningful way</li>\n<li>You extract the format from the destination, which feels a bit odd</li>\n<li>You hardcode the actual final destination</li>\n<li>You use both the <code>root_dir</code> and <code>base_dir</code> parameters, when that really isn't necessary</li>\n<li>You don't return where the file ended up, which feels nicer than the caller having to set up their <code>Path</code> themselves</li>\n</ul>\n<p>Altogether, I ended up with something like this:</p>\n<pre><code>def make_archive3(to_archive, move_to, archive_format="zip"):\n move_to.mkdir(exist_ok=True)\n return shutil.make_archive(move_to / to_archive.name, archive_format, to_archive)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T22:54:38.887",
"Id": "253322",
"ParentId": "253320",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T19:37:12.867",
"Id": "253320",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Simple Python Code that zips file"
}
|
253320
|
<p>Created a validation form in vanilla JS. Due to my little experience, I have a bunch of "if" here, I can not transfer the coordinates of Yandex.Maps to another function for validation, and it is still unknown what. With the coordinates, I "crutch" by saving them to an invisible div :-) I deleted my Api key, so I won't be able to get the coordinates in the example, I don't know if it's worth giving the key to public access :-) The code is working.</p>
<p>Tell me how I can reduce the code or how to perform form validation without my crutch using a div :-) (pass the variable to another function so that when the button is clicked, it checks that the coordinates are entered)</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 errorName = document.querySelector(".name-error");
let errorNumber = document.querySelector(".number-error");
let errorEmail = document.querySelector(".email-error");
let errorMap = document.querySelector(".map-error");
let completed = document.querySelector(".mailForm__completed");
function viodChecker() {
let name = document.querySelector(".mailForm__name").value;
let number = document.querySelector(".mailForm__number").value;
let Email = document.querySelector(".mailForm__email").value;
let Coords = document.querySelector(".coords");
if (name === "") {
errorName.style.display = "block";
}
if (name !== "") {
errorName.style.display = "none";
}
if (number === "") {
errorNumber.style.display = "block";
}
if (number !== "") {
errorNumber.style.display = "none";
}
if (Email.indexOf("@") === -1) {
errorEmail.style.display = "block";
}
if (Email.indexOf("@") !== -1) {
errorEmail.style.display = "none";
}
if (Email.indexOf("@") !== -1) {
errorEmail.style.display = "none";
}
if (Coords.textContent === "") {
errorMap.style.display = "block";
}
if (Coords.textContent !== "") {
errorMap.style.display = "none";
}
if (name !== "" && number !== "" && Email.indexOf("@") !== -1 && Coords.textContent !== "") {
completed.style.display = "block";
}
}
ymaps.ready(init);
function init() {
var myPlacemark,
myMap = new ymaps.Map('map', {
center: [40.391917, -73.524590],
zoom: 17,
controls: ['geolocationControl', 'searchControl']
});
// We listen to the click on the map.
myMap.events.add('click', function (e) {
var coords = e.get('coords');
// If the label has already been created, just move it.
if (myPlacemark) {
myPlacemark.geometry.setCoordinates(coords);
}
// If not, we create.
else {
myPlacemark = createPlacemark(coords);
myMap.geoObjects.add(myPlacemark);
// Listen to the drag-and-drop event on the label.
myPlacemark.events.add('dragend', function () {
getAddress(myPlacemark.geometry.getCoordinates());
});
}
getAddress(coords);
});
// Create a label.
function createPlacemark(coords) {
return new ymaps.Placemark(coords, {
iconCaption: 'search...'
}, {
preset: 'islands#violetDotIconWithCaption',
draggable: true
});
}
// Coords
function getAddress(coords) {
myPlacemark.properties.set('iconCaption', 'поиск...');
ymaps.geocode(coords).then(function (res) {
var firstGeoObject = res.geoObjects.get(0);
myPlacemark.properties
.set({
// We form a line with data about the object.
iconCaption: [
firstGeoObject.geometry.getCoordinates(),
].filter(Boolean).join(', '),
// We set the line with the object address as the balloon content.
balloonContent: firstGeoObject
});
document.querySelector(".coords").textContent = firstGeoObject.geometry.getCoordinates();
});
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, .mailForm {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
input, textarea {
font-size: 14px;
margin: 10px 0 0 0;
width: 350px;
resize: none;
}
.mailForm__map {
margin-top: 10px;
}
button {
margin: 10px 0 0 0;
font-size: 14px;
cursor: pointer;
}
.mailForm__comment {
display: inline-block;
height: 200px;
}
.mailForm__error, .mailForm__completed, .coords {
display: none;
color: red;
font-size: 16px;
font-weight: bold;
margin-top: 10px;
}
.mailForm__completed {
color: green;
font-size: 20px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="style.css" rel="stylesheet">
<title>Mail Form</title>
<script src="https://api-maps.yandex.ru/2.1/?apikey=5200498b-0123-4796-1-bee4ea5473212&lang=ru_RU" type="text/javascript">
</script>
</head>
<body>
<div class="mailForm">
<input class="mailForm__name" placeholder="Name" type="text" value="">
<input class="mailForm__number" placeholder="Tel" type="tel" value="">
<input class="mailForm__email" placeholder="Email" type="email" value="">
<div id="map" class="mailForm__map" style="width: 100%; height: 200px">
</div>
<textarea class="mailForm__comment" maxlength="500" placeholder="Comment" type="text" value=""></textarea>
<button onclick="viodChecker()">SEND</button>
<div class="mailForm__error name-error">NAME ERROR</div>
<div class="mailForm__error number-error">TEL ERROR</div>
<div class="mailForm__error email-error">@ ERROR</div>
<div class="mailForm__error map-error">COORDS ERROR</div>
<div class="mailForm__completed">NICE!</div>
<div class="coords"></div>
</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong>DRYing the ifs</strong> One option would be to use <code>else</code>, or even better, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">conditional (ternary) operator</a> instead of having two separate blocks for each validator:</p>\n<pre><code>errorName.style.display = name ? 'none' : 'block';\nerrorNumber.style.display = number ? 'none' : 'block';\nerrorEmail.style.display = email.includes('@') ? 'none' : 'block';\nerrorMap.style.display = Coords.textContent ? 'block' : 'none';\n</code></pre>\n<p>(You could also use a CSS class for this instead, and use <code>classList.toggle</code> and a second argument)</p>\n<p>But for the inputs, rather than having these manual error divs, consider using the HTML to force validation instead. Put the inputs into a <code><form></code>, and then:</p>\n<ul>\n<li>For the name and number, use the <code>required</code> attribute - the user's browser will tell them to fill out the fields</li>\n<li>For the email, use the <code>type="email"</code> attribute, and the user's browser will validate the email address (more reliably than just checking for <code>@</code>s).</li>\n</ul>\n<p><strong>Div crutch</strong> Rather than using a <code><div></code> to populate the <code>getCoordinates</code> results, you can save in an outer variable, eg:</p>\n<pre><code>// top level\nlet coords;\n// ...lots of code\n coords = firstGeoObject.geometry.getCoordinates();\n</code></pre>\n<p>Then rather than checking <code>Coords.textContent</code>, check the contents of the variable <code>coords</code>.</p>\n<p>Other suggestions:</p>\n<p><strong>Always use <code>const</code></strong> when you can - only use <code>let</code> when you <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">must warn readers of the code</a> that you may be reassigning the variable later in the code. 95% of variable declarations can be with <code>const</code>, usually.</p>\n<p>On a similar note:</p>\n<p><strong>If you're writing in modern syntax</strong> (which you are, and you should!), never use <code>var</code> - <code>var</code> has the same problems as <code>let</code>, but also has issues with having unintuitive function scope instead of block scope, and of being automatically assigned to a property of the global object when on the top level.</p>\n<p><strong>Catch asynchronous errors</strong>, don't ignore them - currently, if <code>.geocode</code> throws, no indication will be given to the user, and they may well be confused. When dealing with a Promise, usually you'll want to follow a pattern like:</p>\n<pre><code>someProm\n .then((result) => {\n // do stuff with result\n })\n .catch((err) => {\n // there was an error, inform the user and maybe log it for debugging\n });\n</code></pre>\n<p><strong>Avoid inline event handlers</strong>, they have <a href=\"https://stackoverflow.com/a/59539045\">too many problems</a> to be worth using nowadays, including a demented scope chain and requiring global pollution. Instead, add the event listener using JavaScript instead, eg:</p>\n<pre><code>document.querySelector('.mailform > button').addEventListener('click', viodChecker);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T06:50:13.363",
"Id": "499579",
"Score": "0",
"body": "Thanks you for help :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T06:12:52.823",
"Id": "253330",
"ParentId": "253329",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253330",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T05:52:00.097",
"Id": "253329",
"Score": "2",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Validation Form"
}
|
253329
|
<p>Hey I have the following code written in VBA. It simulates trajectory of asset price (<code>BS_trajektoria_2</code> function) and calculate payoff from option, This procedure is repeated <code>num_of_sim</code> times to get better ressult (because asset price is random so payoff is random).I use it like this: <code>barrier_MC(100;100;1;0,05;0,02;0,2;120;365;10000;"call";"UO")</code>.
How can I speed up this code? I would like to use bigger number of <code>N</code> and <code>num_of_sim</code> but it takes a long time to compile.</p>
<pre><code>Function RandNorm(Optional mean As Double = 0, Optional sd As Double = 1) As Double
Dim r1, r2, s As Double
r1 = Rnd()
If r1 = 0 Then r1 = Rnd()
r2 = Rnd()
s = Sqr(-2 * Log(r1)) * Cos(6.283185307 * r2)
RandNorm = mean + sd * s
End Function
Function payoff(S_T As Double, K As Double, CallPut As String)
If CallPut = "call" Then
omega = 1
Else: omega = -1
End If
payoff = WorksheetFunction.Max(omega * (S_T - K), 0)
End Function
Function BS_trajektoria2(S_0 As Double, T As Double, r As Double, q As Double, sigma As Double, N As Long) As Double()
Randomize
Dim s() As Double
Dim delta_t As Double
Dim i As Long
ReDim s(N)
Dim rand As Double
s(0) = S_0
delta_t = T / N
For i = 1 To N
s(i) = s(i - 1) * Exp((r - q - 0.5 * sigma ^ 2) * delta_t + sigma * delta_t ^ 0.5 * RandNorm())
Next i
BS_trajektoria2 = s
End Function
Function barrier_MC(S_0 As Double, K As Double, T As Double, r As Double, q As Double, sigma As Double, _
B As Double, N As Long, num_of_sim As Long, CallPut As String, BarType As String) As Double
Dim max_value As Double
Dim suma_wyplat As Double
Dim wyplata As Double
Dim i As Long
Dim s() As Double
suma_wyplat = 0
If (BarType = "DO" Or BarType = "DI") And B > S_0 Then
MsgBox "Too high barrier!"
Exit Function
ElseIf (BarType = "UO" Or BarType = "UI") And B < S_0 Then
MsgBox "Too low barrier"
Exit Function
End If
With WorksheetFunction
For i = 1 To num_of_sim
Randomize
s = BS_trajektoria2(S_0, T, r, q, sigma, N)
max_value = .Max(s)
If max_value >= B Then
wyplata = 0
Else
wyplata = payoff(s(N), K, CallPut)
End If
suma_wyplat = suma_wyplat + wyplata
Next i
End With
barrier_MC = Exp(-r * T) * suma_wyplat / num_of_sim
End Function
Sub test3()
MsgBox barrier_MC(100, 100, 1, 0.05, 0.02, 0.2, 120, 1000, 10000, "call", "UO")
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T12:36:30.730",
"Id": "499590",
"Score": "2",
"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": "2020-12-11T12:48:45.197",
"Id": "499593",
"Score": "0",
"body": "Please use Option Explit at the start of each module. Also take a look at the fantastic and free Rubberduck addin for VBA. The indenter and code inspections will help your code a lot. Given the above my inclination would be to move from pure VBA to a library in C#. http://pragmateek.com/extend-your-vba-code-with-c-vb-net-or-ccli/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:45:46.573",
"Id": "499597",
"Score": "1",
"body": "What does the code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:13:31.173",
"Id": "499599",
"Score": "0",
"body": "@pacmaninbw it simulates trajectory of asset price and calculate payoff from option, This procedure is repeated num_of_sim times to get better ressult"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:37:03.550",
"Id": "499600",
"Score": "1",
"body": "Please state that in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:49:39.273",
"Id": "499603",
"Score": "0",
"body": "Ok I add some information."
}
] |
[
{
"body": "<p>The question is how much speed improvement you expect. What I would do:</p>\n<p>I'd analyze <code>RandNorm</code> for this is a user function that you call 10M times that really influences runtime. Considering that <code>rnd</code> provides pseudo-random numbers it might even be unappropriate but it's your choice.</p>\n<p>Minor improvements can be achieved by replacing</p>\n<pre><code> For i = 1 To N\n s(i) = s(i - 1) * Exp((r - q - 0.5 * sigma ^ 2) * delta_t + sigma * delta_t ^ 0.5 * RandNorm())\n Next i\n</code></pre>\n<p>with</p>\n<pre><code> fact1 = Exp((r - q - 0.5 * sigma ^ 2) * delta_t\n fact2 = sigma * delta_t ^ 0.5\n For i = 1 To N\n s(i) = s(i - 1) * fact1 + fact2 * RandNorm())\n Next i\n</code></pre>\n<p>for most factors are constant within the loop so you don't need to calculate them so many times.</p>\n<p>Also you can check max value in this loop like</p>\n<pre><code>If s(i) > sMax Then sMax = s(i)\n</code></pre>\n<p>and return sMax somehow to <code>barrier_MC</code> so you don't need to call <code>WorksheetFunction.Max</code> on an array of 1K doubles 10K times.</p>\n<p>I'd also rework <code>payoff</code> to eliminate the need of <code>WorksheetFunction.Max</code> (10K times) like</p>\n<pre><code>payoff = omega * (S_T - K)\nIf CallPut = "call" Then\n If payoff > 0 Then payoff = 0\nElse\n If payoff < 0 Then payoff = 0\nEnd If\n</code></pre>\n<p>I'd also consider replacing "Call" <code>string</code> parameter with a <code>Long</code> constant so you can replace 10K string comparisons with <code>Long</code> comparisons.</p>\n<p>You <code>Randomize</code> before calling <code>BS_trajektoria2</code> and within <code>BS_trajektoria2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-29T13:59:17.777",
"Id": "254039",
"ParentId": "253334",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254039",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T11:26:04.757",
"Id": "253334",
"Score": "-1",
"Tags": [
"vba"
],
"Title": "VBA how to speed up the code"
}
|
253334
|
<p>I am trying to improve my code that involves a thread (<code>threadA</code>) handling some UDP communication and another thread (<code>threadB</code>) that works with the output of that communication.</p>
<p>My basic idea is to <code>.push()</code> new data into a <code>std::queue</code> within <code>threadA</code>.
<code>threadB</code> is looking for new data periodically - if it gets new data it processes it. Then <code>.pop</code> is called and the data is deleted.</p>
<p>Implementation:</p>
<ol>
<li><p><code>threadA</code> will call <code>addNewElement()</code> any time new UDP data arrives.</p>
</li>
<li><p><code>threadB</code> will call <code>getNewestPtr()</code> to access the data.</p>
</li>
<li><p>when done with the data, <code>threadB</code> will call <code>doneWithNewest()</code>.</p>
</li>
</ol>
<p>I am managing the access to the data (which comes in the form of <code>std::array</code>) through the use of <code>std::shared_ptr</code>. I know that the <code>shared_ptr</code> will manage the access to the pointer in a thread safe manner, but the underlying object is not going to be managed. <em>Here lies my problem</em> - in my implementation of the class, I am not sure where to put in memory locks, to ensure thread safety. My implementation already works, I have been testing it for a few days without problems, but I have the feeling I am doing something wrong, as I have not used any <code>std::mutex</code>. Anyway, here is my code:</p>
<p><strong>commbufferfifo.h</strong></p>
<pre><code>#ifndef COMMBUFFERFIFO_H
#define COMMBUFFERFIFO_H
#include <queue>
#include <array>
#include <memory>
const size_t COMMLENGTH = 56;
/**
* @brief The commbufferfifo class
* @details used to safely share data between the comm thread and the visu thread
*/
class commbufferfifo
{
public:
commbufferfifo();
/**
* @brief getNewestPtr only accessed in visu thread
* @return returns nullptr if fifo is empty!
*/
std::shared_ptr<std::array<int16_t, COMMLENGTH>> getNewestPtr();///< @brief
void doneWithNewest();///< @brief call when newest object can be deleted
void addNewElement(const std::array<int16_t, COMMLENGTH> &commBuffer); ///< @brief only accessed in comm thread
private:
std::queue<std::shared_ptr<std::array<int16_t, COMMLENGTH>>> m_fifo;
};
#endif // COMMBUFFERFIFO_H
</code></pre>
<p><strong>commbufferfifo.cpp</strong></p>
<pre><code>#include "commbufferfifo.h"
commbufferfifo::commbufferfifo()
{
}
std::shared_ptr<std::array<int16_t, COMMLENGTH> > commbufferfifo::getNewestPtr()
{
if (m_fifo.empty())
return nullptr;
else
return m_fifo.front();
}
void commbufferfifo::doneWithNewest()
{
if (m_fifo.empty())
return;
else
m_fifo.pop();
}
void commbufferfifo::addNewElement(const std::array<int16_t, COMMLENGTH> &commBuffer)
{
m_fifo.push(std::make_shared<std::array<int16_t, COMMLENGTH>>(commBuffer));
}
</code></pre>
<p>some pseudo usage:
<strong>main.cpp</strong></p>
<pre><code>#include "includes/commbufferfifo.h"
#include <unistd.h>
void threadA(std::shared_ptr<commbufferfifo> myPointer){
std::array<int16_t, COMMLENGTH> arr;
for (int iteration = 0; iteration < 1000; iteration++){
arr.at(0) = iteration;
myPointer->addNewElement(arr);
usleep(100);
}
}
int main()
{
auto sharedFifo = std::make_shared<commbufferfifo>();
std::thread tA(&threadA, sharedFifo);
usleep(10000);
for(;;){
if (sharedFifo->getNewestPtr() == nullptr)
break;
std::cout << "sharedFifo->getNewestPtr()->at(0) = " << sharedFifo->getNewestPtr()->at(0) << "\n"; //use data
sharedFifo->doneWithNewest(); //data will be deleted
usleep(1000);
}
tA.join();
std::cout << "------------------------------------\n";
std::cout << "done" << std::endl;
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This is more of a stackoverflow question but whatever.</p>\n<ol>\n<li><p>There is no guarantee that <code>std::queue</code> is thread safe and methods <code>empty()/front()/push()</code> will properly interact in a multi-threaded environment. They most certainly cause data races. For this reason you need to use <code>std::mutex</code> to ensure that <code>std::queue</code> isn't accessed simultaneously from multiple threads ensuring that the data is read/written correctly.</p>\n</li>\n<li><p>What are you going to do when the queue is empty? What if you want to wait for next element? Will you put <code>sleep(10ms)</code> periodically? What if it isn't responsive enough and has too big of a lag? The proper method is to utilize <code>std::condition_variable</code> which has proper <code>wait/notify</code> methods.</p>\n</li>\n<li><p>It isn't worth to create a shared pointer to view some 100 bytes. You'd better transfer 100 bytes of data by copying it.</p>\n</li>\n<li><p>This isn't a C++ approach to transfer data by simply copying chunks of bytes. What you should do instead is to template your thread-safe queue over some class <code>T</code> so it moves <code>T</code>'s instances from sender to receiver in a safe way.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T18:37:19.080",
"Id": "253355",
"ParentId": "253335",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T12:33:26.777",
"Id": "253335",
"Score": "0",
"Tags": [
"c++",
"thread-safety"
],
"Title": "Class to share data between two threads implemented as FIFO with std::queue"
}
|
253335
|
<p><strong>Problem Description</strong></p>
<p>We are given 2 arrays: 1 array representing the image and containing the patterns to be match and another one representing the pattern. Each image is represented as an vector strings, where each element represents a line of pixels in the image, and each character represents a pixel.</p>
<p>The objective is to return the position <code>(x, y)</code> of the pattern in the image, or <code>[-1, -1]</code> if the pattern does not exist in the image. If the pattern appears several times in the image, return the highest position (the smallest x), in case of equality, then return the furthest left (the smallest y). The position of the pattern is determined by the <code>(x, y)</code> coordinates. <code>x</code> representing the row and <code>y</code> representing the column. the <code>[0, 0]</code> coordinates represent the top left corner.</p>
<hr />
<p><strong>Source Code</strong></p>
<p>In the following code. I added <strong>4 test cases</strong>: no pattern exists, 1 pattern exists, 2 pattern exists but at different levels or rows and 2 patterns exists at the same level or same row.</p>
<p>Since we might have patterns that are on the same level, I also added a <code>vector</code> called <code>visited</code>. In case of a pattern matching it will return all the pixels or points representing the location of the pattern in the image. We don't want to visit the same location multiple times.</p>
<p>As for the return of the coordinates. I thought that we will always want to return the first pattern in the image. Since it's the highest, so I added a check <code>firstMatch</code>. Always take the coordinates of the first pattern.</p>
<hr />
<p><strong>Expected Results</strong></p>
<pre><code>- Case 1: [-1, -1]
- Case 2: [2, 1]
- Case 3: [2, 1]
- Case 4: [0, 2]
</code></pre>
<hr />
<p><strong>Questions</strong></p>
<ul>
<li>Is the visited logic that I added to the code, correct? Or should tag as visited all the visited cells?</li>
<li>Is the logic that is used to return always the first match correct? I thought I really wanted to make it as simple as possible. I actually need to find all the patterns because I also need to know the number of matched patterns later on.</li>
</ul>
<hr />
<pre><code>// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include <string>
#include <utility>
struct Point{
int x;
int y;
};
bool isMatch(int row, int col, const std::vector<std::string> & pattern, const std::vector<std::string> & image,std::vector<Point> & visited) {
int k = 0;
int l = 0;
int tmpRow = row;
int tmpCol = col;
//Check for boundary
if(row + pattern.size() - 1 > image.size()) { return false; }
if(col + pattern[0].size() -1 > image[0].size()) { return false;}
while(k < pattern.size()) {
while(l < pattern[k].size()) {
if(image[row][col] != pattern[k][l]){
return false;
}
col++;
l++;
}
row++;
k++;
}
//Pattern match. Fill visited points
for(int i = tmpRow; i < row; ++i){
for(int j = tmpCol; j < col; ++j){
visited.push_back({i,j});
}
}
return true;
}
bool isPointVisited(int row, int column, const std::vector<Point> & visited) {
for(const auto& v:visited) {
if(row == v.x && column == v.y) {
return true;
}
}
return false;
}
std::pair<int,int> patternExists(const std::vector<std::string> & image, const std::vector<std::string> & pattern){
int firstX = -1;
int firstY = -1;
bool firstMatch = true;
std::vector<Point> visited;
for (int row = 0; row < image.size(); row++) {
for (int col = 0; col < image[row].size(); col++) {
if (!isPointVisited(row, col, visited) && image[row][col] == pattern[0][0]) {
int tmpx = row;
int tmpy = col;
if(isMatch(row, col, pattern, image, visited)) {
if(firstMatch) {
firstX = tmpx;
firstY = tmpy;
}
firstMatch = false;
}
}
}
}
return std::make_pair(firstX, firstY);
}
int main() {
//Case 1: Pattern doesn't exist
std::vector<std::string> rectangle = {"0000","0000","0000","0000","0000","0000","0000"};
std::vector<std::string> recPattern = {"11","11"};
std::pair<int, int> coordinates = patternExists(rectangle, recPattern);
std::cout << "First X: " << coordinates.first << std::endl;
std::cout << "First Y: " << coordinates.second << std::endl;
//Case 2: Pattern exists
rectangle = {"0000","0000","0110","0110","0000"};
recPattern = {"11","11"};
coordinates = patternExists(rectangle, recPattern);
std::cout << "First X: " << coordinates.first << std::endl;
std::cout << "First Y: " << coordinates.second << std::endl;
//Case 3: Multiple patterns exist at different levels
rectangle = {"0000","0000","0110","0110","0000","0110","0110"};
recPattern = {"11","11"};
coordinates = patternExists(rectangle, recPattern);
std::cout << "First X: " << coordinates.first << std::endl;
std::cout << "First Y: " << coordinates.second << std::endl;
//Case 4: Multiple patterns exist at same level
rectangle = {"00110011","00110011"};
recPattern = {"11","11"};
coordinates = patternExists(rectangle, recPattern);
std::cout << "First X: " << coordinates.first << std::endl;
std::cout << "First Y: " << coordinates.second << std::endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your solution is overly complicated and not very efficient. First, since we are dealing with strings, you can use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find\" rel=\"nofollow noreferrer\"><code>std::string::find()</code></a> to check if a row from <code>pattern</code> occurs withing a row of <code>image</code>. Once you have a match for the first row of <code>pattern</code>, you can then quickly check if the subsequent rows of <code>image</code> contain the subsequent rows of <code>pattern</code> in the same place, using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/compare\" rel=\"nofollow noreferrer\"><code>std::string::compare()</code></a>. If any match fails you should try the next position.</p>\n<p>There is also no need to keep track of which points you have visited, and the way you keep track of visited points is wrong anyway. Here is a test case that your code will give the wrong answer for:</p>\n<pre><code>rectangle = {"111","011"};\nrecPattern = {"11","11"};\n</code></pre>\n<p>The result should be <code>0, 1</code>, whereas your code outputs <code>0, 0</code>. Here is an example of how you can rewrite the code:</p>\n<pre><code>std::pair<int,int> patternExists(const std::vector<std::string> & image, const std::vector<std::string> & pattern) {\n // Loop over all rows of the image where the first row of pattern could match\n for (std::size_t row = 0; row <= image.size() - pattern.size(); ++row) {\n std::size_t col = 0;\n\n // Loop over all positions where the first row of the pattern matches\n while ((col = image[row].find(pattern[0], col)) != std::string::npos) {\n bool match = true;\n\n // Check that all subsequent rows of the pattern match as well\n for (std::size_t prow = 1; prow < pattern.size(); ++prow) {\n if (image[row + prow].compare(col, pattern[prow].size(), pattern[prow])) {\n match = false;\n break;\n }\n }\n\n // We found a match, return the coordinates\n if (match)\n return {row, col};\n\n // If not, find the next column with a potential match\n col++;\n }\n }\n\n // No matches found\n return {-1, -1};\n}\n</code></pre>\n<p>Note that I used <code>std::size_t</code> instead of <code>int</code>, since the size of a vector or string might be larger than an <code>int</code> can represent. Ideally, the return value should also be a pair of <code>std::size_t</code>'s. You can still use <code>-1</code> as the constant to indicate that there is no match, just like <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/npos\" rel=\"nofollow noreferrer\"><code>std::string::npos</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-14T08:47:59.777",
"Id": "499810",
"Score": "1",
"body": "I feel stupid. The solution u proposed is sooo beautiful. thank you!!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T20:21:39.923",
"Id": "253398",
"ParentId": "253339",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253398",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:36:33.247",
"Id": "253339",
"Score": "1",
"Tags": [
"c++",
"pattern-matching"
],
"Title": "Match Multiple Patterns in 2D Array and Return (x,y) Coordinates of the highest pattern"
}
|
253339
|
<p>This question is about swapping bytes of an <code>uint64_t</code> value, or in other words, about converting between endianness of an integer value:</p>
<pre><code>#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
uint64_t& swapBytes1(uint64_t& num) {
using std::swap;
union {
uint8_t bytes[8];
uint64_t num;
} transformer;
transformer.num = num;
swap(transformer.bytes[0], transformer.bytes[7]);
swap(transformer.bytes[1], transformer.bytes[6]);
swap(transformer.bytes[2], transformer.bytes[5]);
swap(transformer.bytes[3], transformer.bytes[4]);
return num = transformer.num;
}
uint64_t& swapBytes2(uint64_t& num) {
using std::swap;
union {
struct {
uint8_t b0;
uint8_t b1;
uint8_t b2;
uint8_t b3;
uint8_t b4;
uint8_t b5;
uint8_t b6;
uint8_t b7;
} bytes;
uint64_t num;
} transformer;
transformer.num = num;
swap(transformer.bytes.b0, transformer.bytes.b7);
swap(transformer.bytes.b1, transformer.bytes.b6);
swap(transformer.bytes.b2, transformer.bytes.b5);
swap(transformer.bytes.b3, transformer.bytes.b4);
return num = transformer.num;
}
void main() {
uint64_t num = 0x0123456789abcdef;
std::cout << std::hex << num << "\n";
std::cout << swapBytes1(num) << "\n";
swapBytes2(num);
std::cout << num << "\n";
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>As I am not a professional C++ developer, I would like to receive any comment/answer that could improve my C++ coding habits.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:56:18.850",
"Id": "499598",
"Score": "1",
"body": "See [this SO answer](https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:07:48.433",
"Id": "499611",
"Score": "0",
"body": "What are you doing with the answer? Obviously this has huge potential for being non-portable.\n\nDid you consider using `std::reverse` for the 1st version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:52:07.567",
"Id": "499617",
"Score": "0",
"body": "Though according to the standard this is technically UB (putting data in one side of a union and pulling it from another). If this did not work so much code that is live would break."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:53:01.383",
"Id": "499618",
"Score": "1",
"body": "There are already standard functions for doing this: `htonl()` and family. https://linux.die.net/man/3/htonl"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:55:49.597",
"Id": "499619",
"Score": "0",
"body": "Added reinventing-the-wheel tag."
}
] |
[
{
"body": "<p>Technically this is UB.</p>\n<p>Writing a value to one member of a union, then reading from another member (that was not written to) of the union is undefined behavior.</p>\n<p>You would be better off just casting to a <code>char*</code> and just reversing it.</p>\n<pre><code>swap(std::uint64_t& num)\n{\n // I like the use of reinterpret_cast here\n // it makes sure that somebody reading the code notices\n // and takes special care to review what is happening.\n //\n char* first = reinterpret_cast<char*>(&num);\n char* last = first + sizeof(num);\n\n // The advantage of reverse here:\n //\n // The standard library can have pre built optimizations\n // that will use hardware specific optimizations of this that\n // can convert it to a single instruction on some hardware.\n //\n std::reverse(first, last);\n}\n</code></pre>\n<hr />\n<p>The question becomes are you doing this to support endianness?</p>\n<p>If so then your code is only going to work on machines that have the same endianness as the platform you are currently working on.</p>\n<p>Normally people want to swap from platform byte order to network byte order (or the reverse). Depending on architecture this is either a swap (as you have above) or a NO-OP or for some weird hardware something completely different.</p>\n<p>To support this we have specific family of functions:</p>\n<pre><code>htonl() // host to network long (32 byte)\nhtons() // host to network short (16 byte)\n\nntohl() // network to host long (32 byte)\nntohs() // network to host short (16 byte)\n</code></pre>\n<p>These functions will do the appropriate conversion for your hardware.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T19:59:58.687",
"Id": "499629",
"Score": "0",
"body": "`htonl()` only does 32 bits, `htons()` 16 bits. There might be non-standard functions to handle 64 bits at a time, like `bswap_64()` in glibc, or builtins like `__builtin_bswap64()` in GCC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T01:23:35.517",
"Id": "499651",
"Score": "0",
"body": "@G.Sliepen Anyway, those functions solve a different problem, that *on little-endian platforms* reduces to this. On *big-endian platforms*, they are identity-functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T18:03:25.860",
"Id": "253353",
"ParentId": "253340",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "253353",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:42:07.837",
"Id": "253340",
"Score": "2",
"Tags": [
"c++",
"comparative-review",
"reinventing-the-wheel",
"integer",
"byte"
],
"Title": "C++: swapping bytes of an uint64_t"
}
|
253340
|
<h2>Presentation</h2>
<p>Here is an implementation of some pre processing logic. The real use case is to apply online augmentation in a neural network context, that applies a chain of transforms on a pair <code>(feature, ground_truth)</code>. I simplified in that example to chain transforms on a pair <code>(a,b) Tuple[int,float]</code>, but the idea is similar.</p>
<h3>What the code below does :</h3>
<ul>
<li>offers a <code>RandomTransform</code> object, that chains transform on a tuple of argument <code>(a,b)</code></li>
<li>those transforms are applied with a certain probability set by the user</li>
<li>an user can register a new transform using the provided decorators.</li>
</ul>
<p>There is a small usage example in the <code>if __name__ == "__main__":</code> part of the script.</p>
<h3>What I like about this implementation:</h3>
<ul>
<li>it is pretty flexible, as it is easy to register a new transform</li>
<li>it is light to use : no need to create subclass, etc.</li>
</ul>
<h3>What I don't like:</h3>
<ul>
<li>registered functions must follow a strict signature.</li>
<li>the constructor does not have a set of well defined argument: IDEs and language servers can't infer what <code>kwargs</code> are valid or not. Not cool for the developer using it.</li>
<li>That code does not look super adaptable : what if I need to apply a set of transform on a triplet <code>(a,b,c)</code> instead of the pair <code>(a,b)</code>.</li>
</ul>
<h2>Code:</h2>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python
# coding: utf-8
"""
Apply a chain of random transform to a pair (A,B)
"""
import math
import random
from typing import Callable, Tuple
_GLOBAL_TRANSFORM = {}
def register_transform_a(fct: Callable) -> Callable:
"""Register a transform for a, and adapt it to work on a tuple (a,b)
The function returned by the decorator will accept two arguments (a,b) and return
a tuple (fct(a), b).
Args:
fct (Callable): the transform function. Must accept one argument a and return
the single transformed argument
Returns:
Callable: The transform function adapted to a tuple (a,b)
"""
def adapted_fct(a, b):
return fct(a), b
_GLOBAL_TRANSFORM.update({fct.__name__: adapted_fct})
return fct
def register_transform_b(fct: Callable) -> Callable:
"""Register a transform for b, and adapt it to work on a tuple (a,b)
The function returned by the decorator will accept two arguments (a,b) and return
a tuple (a, fct(b)).
Args:
fct (Callable): the transform function. Must accept one argument b and return
the single transformed argument
Returns:
Callable: The transform function adapted to a tuple (a,b)
"""
def adapted_fct(a, b):
return a, fct(b)
_GLOBAL_TRANSFORM.update({fct.__name__: adapted_fct})
return fct
def register_transform_ab(fct: Callable) -> Callable:
"""Register a transform for a tuple (a,b)
Args:
fct (Callable): the transform function. Must accept two arguments a,b and return
a tuple (a,b)
Returns:
Callable: The transform function
"""
_GLOBAL_TRANSFORM.update({fct.__name__: fct})
return fct
@register_transform_a
def square_A(a: int) -> int:
"""Demo function: Square the argument"""
return a ** 2
@register_transform_b
def sqrt_B(b: float) -> float:
"""Demo function: return square root of the argument"""
return math.sqrt(b)
@register_transform_ab
def fct_with_AB(a: int, b: float) -> Tuple[int, float]:
"""Function where the transform of a depends on b and vice-versa"""
return int(a * b), a / b
class RandomTransformer:
"""An object chaining transforms, where each transform is applied with a probability
The transformer applies its transform on tuple (a,b)
Each available function is registered with a decorator.
The Constructor expects the name of a registred function and a probability of
applying that function
Example :
```
transformer = RandomTransformer(square_A=0.5)
```
will create a RandomTransformer object that applies the transorm `square_A` with a
50% probability.
Args:
**kwargs: key as registered function with the decorators `register_transform_a`
`register_transform_b`, `register_transform_ab`. Value as the probability
of applying that transform
Raise:
ValueError: if the key of **kwargs is not a registered function
"""
def __init__(self, **kwargs) -> None:
not_valid = [
fct_name for fct_name in kwargs if fct_name not in _GLOBAL_TRANSFORM
]
if not_valid:
raise ValueError(
f"The functions {not_valid} are not registered\n"
f"You can register them using the registering decorators\n"
f"Currently registered : {list(_GLOBAL_TRANSFORM.keys())}"
)
self.transform_fcts = {
_GLOBAL_TRANSFORM[fct_name]: prob
for fct_name, prob in kwargs.items()
if fct_name in _GLOBAL_TRANSFORM
}
def transform(self, a: int, b: float) -> Tuple[int, float]:
"""Chain transforms on the arguments a,b
The transform used are declared at the construction of the RandomTransformer
Args:
a (int): an int
b (float): a float
Returns:
Tuple[int, float]: a tuple (a,b) after various transforms applied on it
"""
for fct, prob in self.transform_fcts.items():
if random.random() < prob:
a, b = fct(a, b)
return a, b
if __name__ == "__main__":
tuple_to_transform = (2, 3.5)
transformer = RandomTransformer(square_A=0.5, sqrt_B=0.5, fct_with_AB=0.5)
a, b = transformer.transform(*tuple_to_transform)
print(a, b)
# I want to register a new transform
@register_transform_ab
def set_to_null(a, b):
return 0, 0.0
set_to_null_sometimes = RandomTransformer(set_to_null=0.01)
a, b = set_to_null_sometimes.transform(*tuple_to_transform)
print(a, b)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T17:20:22.173",
"Id": "499613",
"Score": "1",
"body": "Rather than providing `simplified code` please provide that actual working code from the project."
}
] |
[
{
"body": "<p>This is over-designed. There's not really a point to registering functions, and there's also not a point to distinguishing between "functions that only modify [a/b/both]". Given your current usage (which is all we can go on, in Code Review), just:</p>\n<ul>\n<li>make bare, undecorated functions</li>\n<li>pass references to them into your constructor as a sequence, not a dictionary. A dictionary misrepresents this data structure; lookup is never performed by key.</li>\n<li><code>func</code> is a friendlier abbreviation than <code>fnct</code>/<code>fct</code>.</li>\n</ul>\n<p>As an example,</p>\n<pre><code>#! /usr/bin/env python\n# coding: utf-8\n"""\nApply a chain of random transform to a pair (A,B)\n"""\nimport math\nimport random\nfrom typing import Callable, Tuple\n\nResultPair = Tuple[float, float]\nPairFunction = Callable[[float, float], ResultPair]\nFunctionProb = Tuple[PairFunction, float]\n\n\ndef square_A(a: float, b: float) -> ResultPair:\n """Demo function: Square the argument"""\n return a ** 2, b\n\n\ndef sqrt_B(a: float, b: float) -> ResultPair:\n """Demo function: return square root of the argument"""\n return a, math.sqrt(b)\n\n\ndef func_with_AB(a: float, b: float) -> ResultPair:\n """Function where the transform of a depends on b and vice-versa"""\n return int(a * b), a / b\n\n\nclass RandomTransformer:\n def __init__(self, *funcs: FunctionProb):\n self.transform_funcs = funcs\n\n def transform(self, a: float, b: float) -> ResultPair:\n for func, prob in self.transform_funcs:\n if random.random() < prob:\n a, b = func(a, b)\n return a, b\n\n\ndef main():\n tuple_to_transform = (2, 3.5)\n transformer = RandomTransformer(\n (square_A, 0.5),\n (sqrt_B, 0.5),\n (func_with_AB, 0.5),\n )\n a, b = transformer.transform(*tuple_to_transform)\n print(a, b)\n\n # I want to register a new transform\n def set_to_null(a, b):\n return 0, 0\n\n set_to_null_sometimes = RandomTransformer(\n (set_to_null, 0.01),\n )\n a, b = set_to_null_sometimes.transform(*tuple_to_transform)\n print(a, b)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>Using this simpler approach, you can even pass lambdas, i.e.</p>\n<pre><code> set_to_null_sometimes = RandomTransformer(\n (\n lambda a, b: (0, 0),\n 0.01\n ),\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-16T07:46:16.297",
"Id": "499943",
"Score": "0",
"body": "Thanks foir the reply. Your comments are spot on. `This is over-designed`: this is what I was afraid of. I guess allowing user to pass functions by references also allow them to use curried functions with `partial`, which is even more flexible. The only thing I don't like about your design is the fact that the signature of the function passed as an argument must follow a strict signature `func(a,b)` even if the function does not depends on `b`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-16T16:16:40.203",
"Id": "499978",
"Score": "0",
"body": "The last point is easy enough to work around: if you care so much about having univariate functions, make a `with_a` and `with_b` wrapper."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T20:12:46.333",
"Id": "253513",
"ParentId": "253342",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253513",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T14:42:01.257",
"Id": "253342",
"Score": "1",
"Tags": [
"python-3.x"
],
"Title": "Chaining transform on a tuple with a certain chance of applying the transform, with the possibility of registering new transforms"
}
|
253342
|
<p>This function works as such:</p>
<ul>
<li><code>Use_Inclusions</code> and Use_Exclusions are either true or false</li>
<li><code>File_Type_Exclusions</code> is a slice of files types</li>
<li><code>General_Inclusions</code> is a slice of directories/files</li>
<li><code>General_Exclusions</code> is a slice of directories/files</li>
</ul>
<p>The code:</p>
<pre><code>func FileCheck(file string)bool{
if InvalidExtension(config.Exclusions.File_Type_Exclusions,file) && config.Settings.Use_Inclusions{
return false
}
if !config.Settings.Use_Exclusions && !config.Settings.Use_Inclusions{
return true
}else if !config.Settings.Use_Exclusions && config.Settings.Use_Inclusions{
// Only backup if included
ok := IsSlice(config.Inclusions.General_Inclusions,file)
if !ok{
return false
}
}else if config.Settings.Use_Exclusions && !config.Settings.Use_Inclusions{
// Only backup if not excluded
if IsSlice(config.Exclusions.General_Exclusions,file){
return false
}else{
return true
}
}else if config.Settings.Use_Exclusions && config.Settings.Use_Inclusions{
//Backup if not exluded unless explicitly included
ok := IsSlice(config.Inclusions.General_Inclusions,file)
exclude := Is(config.Exclusions.General_Exclusions,file)
if !exclude && ok{
return true
}else if exclude && ok{
return true
}else if !ok && !exclude{
return true
}else{
return false
}
}else{
panic(errors.New(fmt.Sprintf("Error: The combinantion of %t,%t is not possible",config.Settings.Use_Exclusions,config.Settings.Use_Inclusions)))
}
return false
}
func Is(slice []string, value string)bool{
for _,elem := range slice{
if elem == value{
return true
}else if strings.Contains(value,elem){
return true
}
}
return false
}
//Checks if values in sliceA are in the file path at all
func IsSlice(sliceA []string , file string)bool{
files := strings.Split(file,"\\")
file = strings.Join(files[3:],"\\")
for _,elemA := range sliceA{
if strings.Contains(file,elemA){
return true//,strings.Replace(elemA,elemB,"",1)
}else if strings.Contains(elemA,file){
return true
}
}
return false//,""
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-16T15:00:46.403",
"Id": "499976",
"Score": "1",
"body": "Why don't you use `gofmt` to format the code, like everyone else?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T15:45:25.980",
"Id": "253346",
"Score": "0",
"Tags": [
"go"
],
"Title": "Go: Optimize Inclusion/exclusion check"
}
|
253346
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.