body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm brand new to Ruby.</p>
<p>The function takes in a string of any number of words, and reverses the order of the words. Also, for each word, it takes the vowels and moves it to the end of the word. It also downcases everything. Thus, <code>Hello World!</code> would become <code>wrld!o hlleo</code>.</p>
<p>I am trying to use some Ruby features, hence why it is a one-liner so to speak. Basically I am just looking for style suggestions. Is it appropriate to do such a thing in this manner (one line?). I'm sure there are functions that could accomplish the task quicker, so I am open to those suggestions too, since my code is very long and convoluted. Also I should mention I wanted to write this with only base Ruby, no extra packages/gems.</p>
<p>Someone suggested Rubocop and the Style Guide so I will check those out.</p>
<pre><code> def funky_words(s)
s.strip.gsub(/\s+/, " ").split(" ").reverse.instance_eval{map{|elt| elt.gsub(/([aeiou])/i,"")}}.
zip(s.strip.split(" ").reverse.map{|elt| elt.scan(/([aeiou])/i).flatten}.instance_eval{map{|elt| elt.join}}).
map(&:join).join(" ").downcase
#first "line" reverses word order removes vowels, second "line" captures vowels, last "line" joins vowels and all words
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T06:18:53.503",
"Id": "486006",
"Score": "1",
"body": "To those voting to close: please notify me if you still think it's unacceptable. This question was getting closed due to poor phrasing, it's not outside our scope IMO."
}
] |
[
{
"body": "<p>One-liners are good fun, but the world doesn't really need more of them. That said, they don't have to be so unreadable. What will your future brain say a year from now if you have to maintain that function?</p>\n<p>Here's an approach illustrating a scalable technique to make even long "one-liners" readable by (1) using lines generously, (2) indenting code in the manner of a pretty-printed data structure to convey the logic's hierarchy (code is data, after all), and (3) including comments to assist the reader with the logic and intent.</p>\n<pre><code>def funky_words(s)\n (\n # Split into words.\n s\n .split\n .reverse_each\n .map { |word|\n # Within each word, push vowels to the end, while preserving\n # original order within consonants and vowels.\n word\n .each_char\n .sort_by.with_index { |c, i| "aeiouAEIOU".include?(c) ? [1, i] : [0, i] }\n .join\n }\n # Rejoin the new words.\n .join(" ")\n )\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T21:32:43.050",
"Id": "486750",
"Score": "0",
"body": "Sweet! This is great, thank you! I need to learn Ruby's _index methods."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T01:45:25.680",
"Id": "248434",
"ParentId": "248143",
"Score": "3"
}
},
{
"body": "<p>Your solution does the following:</p>\n<ul>\n<li>downcase the string</li>\n<li>convert the resulting string to an array of words</li>\n<li>reverse the array of words</li>\n<li>convert each word in the array so that the vowels are at the end and order is preserved for both the vowels and non-vowels</li>\n<li>join the words in the resulting array to form a string</li>\n</ul>\n<p>Let's begin with the penultimate operation. To make the code more readable and speed testing let's make that a separate method.</p>\n<pre><code>VOWELS = 'aeiou'\n</code></pre>\n\n<pre><code>def shove_vowels_to_end(word)\n vowels = ''\n non_vowels = ''\n word.each_char do |char|\n if VOWELS.include?(char)\n vowels << char\n else\n non_vowels << char\n end\n end\n [non_vowels, vowels].join\nend\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/String.html#method-i-each_char\" rel=\"nofollow noreferrer\">String#each_char</a>, <a href=\"https://ruby-doc.org/core-2.7.0/String.html#method-i-include-3F\" rel=\"nofollow noreferrer\">String#include?</a> and <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-join\" rel=\"nofollow noreferrer\">String#join</a>.</p>\n<p>Aside: I could have written <code>word.chars do |char|...</code> instead of <code>word.each_char do |char|...</code>, but the former has the disadvantage that <code>word.chars</code> returns an intermediate array, whereas the latter returns an enumerator, thereby consuming less memory.</p>\n<p>Let's try it:</p>\n<pre><code>shove_vowels_to_end("atlastdisgonehurray!")\n #=> "tlstdsgnhrry!aaioeua" \n</code></pre>\n<p>If desired we could make <code>VOWELS</code> a set (to employ <a href=\"https://ruby-doc.org/stdlib-2.7.0/libdoc/set/rdoc/Set.html#method-i-include-3F\" rel=\"nofollow noreferrer\">Set#include?</a>, which may speed calculations a litte:</p>\n<pre><code>require 'set'\n\nVOWELS = 'aeiou'.each_char.to_set\n #<Set: {"a", "e", "i", "o", "u"}>\n</code></pre>\n<p>We can now write the rest of the method around <code>shove_vowels_to_end</code>:</p>\n<pre><code>def funky_words(str)\n str.downcase.split.map { |word| shove_vowels_to_end(word) }.join(' ')\nend\n</code></pre>\n<p>I will discuss the code but first let's try it:</p>\n<pre><code>str = "Little Miss Muffett sat on her tuffet"\n\nfunky_words str\n #=> "lttlie mssi mffttue sta no hre tfftue"\n</code></pre>\n<p>Depending on what is known about <code>str</code> we may need to change <code>str.split</code> to <code>str.strip.split</code>. <code>str.split</code> is the same as <code>str.split(/\\s+/)</code>, which is probably appropriate. See <a href=\"https://ruby-doc.org/core-2.7.0/String.html#method-i-split\" rel=\"nofollow noreferrer\">String#split</a>.</p>\n<p>The intermediate calculation is:</p>\n<pre><code>str.downcase.split.map { |word| shove_vowels_to_end(word) }\n #=> ["lttlie", "mssi", "mffttue", "sta", "no", "hre", "tfftue"]\n</code></pre>\n<p>which is why we need <code>.join(' ')</code> at the end.</p>\n<p>Notice that extra spaces are not preserved:</p>\n<pre><code>funky_words "some spaces"\n #=> "smoe spcsae"\n</code></pre>\n<hr />\n<p>Here is a more Ruby-like way of writing <code>shove_vowels_to_end</code>:</p>\n<pre><code>def shove_vowels_to_end(word)\n word.each_char.with_object(['', '']) do |char, (non_vowels, vowels)|\n if VOWELS.include?(char)\n vowels << char\n else\n non_vowels << char\n end\n end.join\nend\n</code></pre>\n<p>See <a href=\"https://ruby-doc.org/core-2.7.0/Enumerator.html#method-i-with_object\" rel=\"nofollow noreferrer\">Enumerator#with_object</a>.</p>\n<p>Notice how I used <a href=\"https://docs.ruby-lang.org/en/2.7.0/doc/syntax/assignment_rdoc.html#label-Array+Decomposition\" rel=\"nofollow noreferrer\">array decomposition</a> to advantage when writing the block variables:</p>\n<pre><code>|char, (non_vowels, vowels)|\n</code></pre>\n<hr />\n<p>Here's another way to write <code>funky_words</code>. I modify each sequence of non-spaces with <a href=\"https://ruby-doc.org/core-2.7.0/String.html#method-i-gsub\" rel=\"nofollow noreferrer\">String#gsub</a>.</p>\n<pre><code>require 'set'\n</code></pre>\n \n<pre><code>VOWELS = %w|a e i o u|.to_set\n #=> #<Set: {"a", "e", "i", "o", "u"}>\n</code></pre>\n \n<pre><code>def funky_words(str) \n str.downcase.gsub(/[^ ]+/) do |word|\n vowels = ''\n others = ''\n word.each_char do |char|\n if VOWELS.include?(char)\n vowels.prepend(char)\n else\n others.prepend(char)\n end\n end\n others + vowels\n end.reverse\nend\n</code></pre>\n \n<pre><code>str = "Little Miss Muffett sat on her tuffet"\nfunky_words(str)\n #=> "tfftue hre no sta mffttue mssi lttlie"\n</code></pre>\n<p>Consider modifying the word <code>'muffett'</code>. It is to become <code>'mffttue'</code>. However, since I reverse the string at the end I need to convert <code>'muffett'</code> to <code>'muffett'.reverse #=> 'euttffm'</code>. That is obtained in the following steps:</p>\n<pre><code>muffett\nvowels = ''\nothers = 'm'\n\nuffett\nvowels = 'u'\nothers = 'm'\n\nffett\nvowels = 'u'\nothers = 'fm'\n\nfett\nvowels = 'u'\nothers = 'ffm'\n\nett\nvowels = 'eu'\nothers = 'ffm\n\ntt\nvowels = 'eu'\nothers = 'tffm'\n\nt\nvowels = 'eu'\nothers = 'ttffm'\n\nvowels + others\n #=> `euttffm`\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T04:17:03.057",
"Id": "254932",
"ParentId": "248143",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:15:36.010",
"Id": "248143",
"Score": "3",
"Tags": [
"beginner",
"ruby"
],
"Title": "Reverse the words, move the vowels and downcase everything"
}
|
248143
|
<p>I've just finished implementing a Generic RecyclerView adapter in my Android app, written in Kotlin.</p>
<p><strong>BaseAdapter.kt</strong>:</p>
<pre><code>import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T>(
private var dataList: ArrayList<T>
) : RecyclerView.Adapter<BaseViewHolder<T>>() {
abstract fun setViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T>
fun swapDataList(dataList: ArrayList<T>) {
this.dataList = dataList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T> {
return setViewHolder(parent)
}
override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
holder.bind(dataList[position])
}
override fun getItemCount(): Int = dataList.size
}
</code></pre>
<p><strong>BaseViewHolder.kt</strong>:</p>
<pre><code>import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
abstract class BaseViewHolder<T>(override val containerView: View) : RecyclerView.ViewHolder(containerView),
LayoutContainer {
abstract fun bind(data: T)
}
</code></pre>
<p>All of my RecyclerView adapters extend <code>BaseAdapter</code> and have an inner ViewHolder class, which extends <code>BaseViewHolder</code>. I'm asking for suggestions and constructive criticism. What could I change to improve the overall performance of my class? Is there a better approach?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:22:57.843",
"Id": "248145",
"Score": "2",
"Tags": [
"android",
"generics",
"kotlin"
],
"Title": "Generic RecyclerView Adapter in Kotlin"
}
|
248145
|
<p>Recently I've been learning about concurrency/parallelism and I decided to implement the <a href="https://cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf" rel="nofollow noreferrer">Michael&Scott lock-free Linked queue (PDF)</a> as practice.</p>
<p>I'm not entirely sure how to test this data structure or even if my implementation is concurrency safe, but any feedback is appreciated.</p>
<pre class="lang-rust prettyprint-override"><code>#![crate_name = "cqi"]
//! # cqi
//!
//! `cqi` provides a concurrent, lock-free implementation of a Linked Queue. This implementation is modelled after the
//! classic algorithms described in Maged M. Michael's and Michael L. Scott's paper ["Simple, Fast, and Practical
//! Non-Blocking and Blocking Concurrent Queue Algorithms"](https://www.cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf).
//!
//! A Linked Queue is a FIFO (first-in-first-out) abstract data type that sequentially stores its elements. Like all
//! queues, `cqi`'s Linked Queue implementation allows for insertion and deletion in order `O(1)`, with the additional
//! benefit of atomic reads and writes across multiple threads.
use crossbeam::epoch::{self as epoch, Atomic, Collector, Guard, Owned, Shared};
use std::sync::atomic::Ordering;
struct Node<T> {
item: T,
next: Atomic<Node<T>>,
}
impl<T> Node<T> {
pub fn new(item: T) -> Self {
Self {
item,
next: Atomic::null(),
}
}
}
pub struct LinkedQueue<T> {
head: Atomic<Node<T>>,
tail: Atomic<Node<T>>,
collector: Collector,
}
impl<T> LinkedQueue<T> {
pub fn new() -> Self {
LinkedQueue {
head: Atomic::null(),
tail: Atomic::null(),
collector: epoch::default_collector().clone(),
}
}
/// Retrieves a thread guard for the current thread. While the given guard is still in scope, any operations that
/// involve mutating the queue will collect "garbage". This "garbage" is not freed until the guard has been dropped.
/// Either manually drop the `Guard` or let it fall out of scope to prevent a lot of garbage from piling up.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// ```
pub fn guard(&self) -> Guard {
self.collector.register().pin()
}
/// Inserts a new item at the back of the queue.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// lq.enqueue(42, &guard);
/// lq.enqueue(69, &guard);
/// assert_eq!(lq.peek(&guard), Some(&42));
/// ```
pub fn enqueue<'g>(&self, item: T, guard: &'g Guard) {
let new_node = Owned::new(Node::new(item)).into_shared(guard);
// Unlike the enqueue algorithm described in M&S's paper, we don't need to check if the tail is consistent
// between now and our CAS on the tail. Our `guard` ensures this.
let tail = self.tail.load(Ordering::Acquire, guard);
if tail.is_null() {
self.head.store(new_node, Ordering::Release);
self.tail.store(new_node, Ordering::Release);
} else {
let mut tail_node = unsafe { tail.deref() };
let mut next = tail_node.next.load(Ordering::Acquire, guard);
// Here we swing the tail forward if the last node in the queue is not the current node.
while !next.is_null() {
tail_node = unsafe { next.deref() };
next = tail_node.next.load(Ordering::Acquire, guard);
}
tail_node.next.store(new_node, Ordering::Release);
let _ = self
.tail
.compare_and_set(tail, new_node, Ordering::Release, guard);
}
}
/// Removes the first item of the queue.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// lq.enqueue(42, &guard);
/// assert_eq!(lq.peek(&guard), Some(&42));
/// lq.dequeue(&guard);
/// assert_eq!(lq.peek(&guard), None);
/// ```
pub fn dequeue<'g>(&self, guard: &'g Guard) -> bool {
let head = self.head.load(Ordering::Acquire, guard);
if !head.is_null() {
let head_node = unsafe { head.deref() };
let next = head_node.next.load(Ordering::Acquire, guard);
self.head.store(next, Ordering::Release);
return true;
}
false
}
/// Retrieves the first item in the queue.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// lq.enqueue(42, &guard);
/// assert_eq!(lq.peek(&guard), Some(&42));
/// ```
pub fn peek<'g>(&self, guard: &'g Guard) -> Option<&'g T> {
// Here we don't need to update the `mod_count` field in the `tail` node since we aren't doing any mutations.
let head = self.head.load(Ordering::Acquire, guard);
if head.is_null() {
None
} else {
let item = unsafe { &head.deref().item };
Some(item)
}
}
/// Retrieves and removes the first item in the queue. **This operation can be expensive** as it copies the value
/// being polled so it can be returned outside of the queue. Large types can impact performance here.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// lq.enqueue(42, &guard);
/// let item = lq.poll(&guard);
///
/// assert_eq!(item, Some(42));
/// assert_eq!(lq.peek(&guard), None);
/// ```
pub fn poll<'g>(&self, guard: &'g Guard) -> Option<T>
where
T: Copy,
{
let head = self.head.load(Ordering::Acquire, guard).to_owned();
if head.is_null() {
None
} else {
unsafe {
let head_node = head.deref();
let item = head_node.item.clone();
self.head.store(
head_node.next.load(Ordering::Acquire, guard),
Ordering::Release,
);
Some(item)
}
}
}
/// Retrieves the number of items currently in the queue.
///
/// As the queue can be concurrently updated, this will return the number of items in queue **at the time this
/// function is called**. This number cannot be heavily relied on as it can already be out of date directly after
/// this function is called.
///
/// # Example
/// ```
/// use cqi::LinkedQueue;
///
/// let lq = LinkedQueue::<usize>::new();
/// let guard = lq.guard();
/// lq.enqueue(42, &guard);
/// lq.enqueue(69, &guard);
/// assert_eq!(lq.len(&guard), 2);
/// ```
pub fn len<'g>(&self, guard: &'g Guard) -> usize {
let mut size: usize = 0;
let mut head = self.head.load(Ordering::SeqCst, guard);
while !head.is_null() {
size += 1;
head = unsafe { head.deref().next.load(Ordering::SeqCst, guard) };
}
size
}
}
#[cfg(test)]
mod tests {
use super::LinkedQueue;
#[test]
fn test_enqueue() {
let lq = LinkedQueue::<usize>::new();
let guard = lq.guard();
lq.enqueue(42, &guard);
assert_eq!(lq.peek(&guard), Some(&42));
lq.enqueue(69, &guard);
assert_eq!(lq.peek(&guard), Some(&42));
let _ = lq.poll(&guard);
assert_eq!(lq.peek(&guard), Some(&69));
}
#[test]
fn test_poll() {
let lq = LinkedQueue::<usize>::new();
let guard = lq.guard();
lq.enqueue(42, &guard);
lq.enqueue(69, &guard);
// Ensure the item polled and the new head of the queue are the correct items.
assert_eq!(lq.poll(&guard), Some(42));
assert_eq!(lq.peek(&guard), Some(&69));
}
#[test]
fn test_dequeue() {
let lq = LinkedQueue::<usize>::new();
let guard = lq.guard();
lq.enqueue(42, &guard);
lq.enqueue(69, &guard);
lq.dequeue(&guard);
assert_eq!(lq.peek(&guard), Some(&69));
lq.dequeue(&guard);
assert_eq!(lq.peek(&guard), None);
}
#[test]
fn test_len() {
let lq = LinkedQueue::<usize>::new();
let guard = lq.guard();
for i in 0..100 as usize {
lq.enqueue(i, &guard);
}
assert_eq!(lq.len(&guard), 100);
lq.dequeue(&guard);
assert_eq!(lq.len(&guard), 99);
for i in 0..99 as usize {
lq.dequeue(&guard);
}
assert_eq!(lq.len(&guard), 0);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T18:26:08.817",
"Id": "485968",
"Score": "0",
"body": "Welcome to CodeReview! I hope you get some nice reviews :)"
}
] |
[
{
"body": "<p>I am not fluent in Rust, so I cannot comment on the overall implementation. However, what I can say is that this implementation is <em>not</em> thread-safe, as it contains several race conditions.</p>\n<pre><code>let tail = self.tail.load(Ordering::Acquire, guard);\n if tail.is_null() {\n self.head.store(new_node, Ordering::Release);\n self.tail.store(new_node, Ordering::Release);\n</code></pre>\n<p>If two threads observe a null pointer in <code>tail</code>, both directly update <code>head</code>/<code>tail</code>. This is obviously a race condition. Instead, you need to create an empty dummy node during initialization of the queue (i.e., the queue always has to hold at least one node; it is empty if <code>head == tail</code>).</p>\n<p>I am not sure what you mean by this comment:</p>\n<pre><code>// Unlike the enqueue algorithm described in M&S's paper, we don't need to check if the tail is consistent\n// between now and our CAS on the tail. Our `guard` ensures this.\n</code></pre>\n<p>The <code>guard</code> is part of the reclamation scheme (epoch based reclamation in this case), and it only prevents you from deleting a node that might still be accessed by some other thread. But it does not prevent tail from getting changed right under your nose.</p>\n<pre><code> let mut tail_node = unsafe { tail.deref() };\n let mut next = tail_node.next.load(Ordering::Acquire, guard);\n\n // Here we swing the tail forward if the last node in the queue is not the current node.\n while !next.is_null() {\n tail_node = unsafe { next.deref() };\n next = tail_node.next.load(Ordering::Acquire, guard);\n }\n\n // this is a race condition!!\n tail_node.next.store(new_node, Ordering::Release);\n let _ = self\n .tail\n .compare_and_set(tail, new_node, Ordering::Release, guard);\n</code></pre>\n<p>You cannot directly store the new node into tail`s next! This is also a race condition since other threads might be doing the same, effectively overwritting the values written by some other threads. You have to use a CAS loop for that.</p>\n<p>The same goes for updating head in <code>dequeue</code>.</p>\n<p>You might want to take a look at my implementation of the Michael Scott queue: <a href=\"https://github.com/mpoeter/xenium/blob/master/xenium/michael_scott_queue.hpp\" rel=\"nofollow noreferrer\">https://github.com/mpoeter/xenium/blob/master/xenium/michael_scott_queue.hpp</a><br />\nIt is done in C++, but it uses a similar guard concept to solve the memory reclamation problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T09:57:52.900",
"Id": "486215",
"Score": "0",
"body": "This really helps a lot. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T08:40:53.003",
"Id": "248230",
"ParentId": "248151",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248230",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:15:38.600",
"Id": "248151",
"Score": "4",
"Tags": [
"rust",
"concurrency",
"queue",
"lock-free"
],
"Title": "A concurrent lock-free Linked Queue implementation"
}
|
248151
|
<p>I'm looking to simplify controller logic where multiple validation steps will either result in redirecting the browser or re-rendering the current view.</p>
<p>Overall I'm looking to:</p>
<ul>
<li>Avoid excessive nested if statements</li>
<li>Avoid multiple calls to Controller::redirect with the same arguments</li>
<li>Avoid using "return $this->render();"</li>
<li>Set view data that depends on the actions arguments (excludes using Controller::beforeRender)</li>
<li>Avoid generating/setting additional view data (ie dropdown list data) unless the view will render</li>
</ul>
<p>The sample below is CakePHP 2 but I assume this idea could apply to versions 3 or 4 as well.</p>
<p>Are there any potential issues or downsides with the generic sample I've provided below?</p>
<pre><code><?php
class MyController extends Controller {
public function my_action($id = null) {
try {
//test controller args
if (!$id) {
throw new RedirectException('Invalid id selected');
}
//form submitted
if ($this->request->is('post')) {
//check various things
if (!$this->validationStep1()) {
throw new AlertException('Please check something for step 1');
}
if (!$this->validationStep2()) {
throw new AlertException('Please check something for step 2');
}
//situation where the validation may throw
try {
$this->validateStep3MayThrowSomething();
}
catch (Exception $e) {
throw new AlertException('Please check something for step 3');
}
//more checks here
if (!$this->Model->save()) {
throw new AlertException('Error saving');
}
//successful completed if we are here
throw new RedirectException('Action completed successfully');
}
}
catch (RedirectException $e) {
if ($e->hasMessage()) {
$this->alert($e->getMessage());
}
$this->redirect(array('action' => 'index'));
}
catch (AlertException $e) {
$this->alert($e->getMessage());
}
//set any data needed to render this view
$this->set('someData', $this->Model->getSomeData());
$this->set('someSpecifcData', $this->Model->getDataById($id));
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T18:10:41.893",
"Id": "248155",
"Score": "1",
"Tags": [
"php",
"cakephp"
],
"Title": "Using exceptions inside CakePHP controller actions to simplify flow"
}
|
248155
|
<p>From HackerRank "Repeated String" challenge:</p>
<blockquote>
<p>Lilah has a string, <span class="math-container">\$s\$</span>, of lowercase English letters that she repeated
infinitely many times.</p>
<p>Given an integer, <span class="math-container">\$n\$</span>, find and print the number of letter a's in the
first <span class="math-container">\$n\$</span> letters of Lilah's infinite string.</p>
<p>For example, if the string <span class="math-container">\$s=abcac\$</span> and <span class="math-container">\$n=10\$</span>, the sub string we consider is <span class="math-container">\$abcacabcac\$</span>, the
first <span class="math-container">\$10\$</span> characters of her infinite string. There are <span class="math-container">\$4\$</span> occurrences of a
in the sub-string.</p>
</blockquote>
<p>Test case 1:</p>
<pre><code> string input = "aba";
long n = 10;
</code></pre>
<p>Test case 2:</p>
<pre><code> string input = "a";
long n = 1000000000000;
</code></pre>
<p>My Solution:</p>
<pre><code> string input = "aba";
long n = 10;
long numAs = input.Count(c => c.Equals('a'));
if (input.Length == 0)
{
return 0;
}
long rem = n % input.Length;
long reps = (n - rem) / input.Length;
long count = reps * numAs;
string sRem = input.Substring(0, (int)rem);
if (rem != 0)
{
count += sRem.Count(c => c.Equals('a'));
}
</code></pre>
<p>The results should be 7 and 1000000000000. This solution passed all test cases on HackerRank. It is based on other solutions, especially one I up-voted.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T02:47:09.433",
"Id": "485999",
"Score": "0",
"body": "`input` missing null validation. `n` missing negative integers && 0 validation."
}
] |
[
{
"body": "<p>I don't see a lot to improve. However, I did notice a couple of things:</p>\n<p>The shortcut conditional:</p>\n<pre><code>if (input.Length == 0)\n{\n return 0;\n}\n</code></pre>\n<p>should be the very first thing in your code right after <code>input</code></p>\n<p>Similarly with:</p>\n<pre><code>string sRem = input.Substring(0, (int)rem);\n\nif (rem != 0)\n{\n count += sRem.Count(c => c.Equals('a'));\n}\n</code></pre>\n<p>You don't need that string unless <code>rem</code> > 0, so include it in the conditional block. Even better yet, use the LINQ extension, <code>Take</code> and do everything in one statement:</p>\n<pre><code>if (rem != 0)\n{\n count += sRem.Take((int)rem).Count(c => c.Equals('a'));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:06:50.277",
"Id": "248163",
"ParentId": "248156",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Do you need to validate inputs ?</li>\n</ol>\n<p>If so, you should test all cases :</p>\n<ul>\n<li>input could be null</li>\n<li>input could be an empty string</li>\n<li>n could be negative or 0</li>\n</ul>\n<ol start=\"2\">\n<li>Variable names</li>\n</ol>\n<p>Variables names are important, they help understand the code better. You don't have to make them as small as possible. Especially when you have an IDE like VisualStudio that will help you select the proper one with InteliSense.</p>\n<ul>\n<li>numAs -> aCount</li>\n<li>rem -> remainder</li>\n<li>reps -> repetitions</li>\n<li>sRem -> remainderString</li>\n</ul>\n<ol start=\"3\">\n<li>Fail fast</li>\n</ol>\n<p>It is usually better to leave a method "as soon as possible". So you want to perform input validation before doing any work and exit the method if it doesn't validate.\nThe same way, if your remainder is 0, you can return your result right away.</p>\n<ol start=\"4\">\n<li>Integer division</li>\n</ol>\n<p>To calculate your repetition, you subtract the remainder from n. If you check <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#integer-division\" rel=\"nofollow noreferrer\">integer division in C#</a>, you don't have to :</p>\n<pre><code>long repetitions = n / input.length;\n</code></pre>\n<ol start=\"5\">\n<li>Use Linq</li>\n</ol>\n<p><a href=\"https://codereview.stackexchange.com/a/248163/101014\">As per tinstaafl solution</a>, you can use Linq to save a variable and a line :</p>\n<pre><code>count += remainderString.Take((int)remainder).Count(c => c.Equals('a'));\n</code></pre>\n<p>So, all in all, you get :</p>\n<pre><code>long aCount = input.Count(c => c.Equals('a'));\n\nif (input == null || input.Length == 0 || n <= 0)\n{\n return 0;\n}\n\nlong repetitions = n / input.Length;\nlong remainder = n % input.Length;\nlong count = repetitions * aCount;\n\nif (remainder == 0)\n{\n return count;\n}\n\nreturn count + remainderString.Take((int)remainder).Count(c => c.Equals('a'));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:37:07.393",
"Id": "487543",
"Score": "0",
"body": "Thank you for your comment. I like chaining link expressions but I split them up for readability. It should also be noted that this code was fed to a parser/compiler on the hackerrank.com website that must be able to parse and compile it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T14:46:20.797",
"Id": "248191",
"ParentId": "248156",
"Score": "4"
}
},
{
"body": "<p>Same points as other answers, however there is a simpler solution to this, you can simply replace <code>A</code> with empty string, and compare the length of both strings, which would give you the number of A's.</p>\n<p>Here is an example :</p>\n<pre><code>public static long RepeatedString(string s, long n)\n{\n if (string.IsNullOrWhiteSpace(s) || n <= 0) { return 0; }\n \n // Local function that would return the number of A's \n long CountA(string input) => input.Length - input.Replace("a", "").Length;\n \n var aCount = CountA(s);\n \n var reminder = n % s.Length; \n \n var repetition = (n - reminder) / s.Length;\n \n var count = repetition * aCount;\n\n var reminderStr = s.Substring(0, (int)reminder);\n \n var result = count + CountA(reminderStr);\n \n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:25:55.617",
"Id": "248217",
"ParentId": "248156",
"Score": "2"
}
},
{
"body": "<p>I can't add much to what have already been written, other than when it comes to performance, you'll often find Linq (<code>long numAs = input.Count(c => c.Equals('a'));</code>) to be rather slow compared to a more traditional <code>for</code> or <code>while</code> loop. But if you insists on Linq, you could go all in like:</p>\n<pre><code>long CountChars(string data, long length, char c = 'a')\n{\n if (string.IsNullOrEmpty(data) || length <= 0) return 0;\n\n long repetitions = length / data.Length;\n long remSize = length % data.Length;\n\n return data\n .Select((ch, i) => (ch, i))\n .Where(chi => chi.ch == c)\n .Sum(chi => chi.i < remSize ? repetitions + 1 : repetitions);\n}\n</code></pre>\n<p>Here is used the overload of <code>Select()</code> that provides the index along with each element to map to a value tuple, from which it is possible to filter by <code>'a'</code> and finally sums up the repetitions: if the index is lesser than the size of the reminder then <code>repetitions + 1</code> should be summed otherwise only the repetitions for each found <code>'a'</code>.</p>\n<hr />\n<p>A traditional approach using <code>while</code>-loops - essentially using the same approach as above could look like:</p>\n<pre><code>long CountChars(string data, long length, char c = 'a')\n{\n if (string.IsNullOrEmpty(data) || length <= 0) return 0;\n\n long count = 0;\n long repetitions = length / data.Length + 1; // + 1 for the possible extra 'a' in the reminder\n long remSize = length % data.Length;\n\n int i = 0;\n\n while (i < remSize)\n {\n if (data[i++] == c)\n count += repetitions;\n }\n\n repetitions--;\n while (i < data.Length)\n {\n if (data[i++] == c)\n count += repetitions;\n }\n\n return count;\n}\n</code></pre>\n<p>With this approach the string <code>s</code> (<code>data</code>) is only parsed once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:33:26.597",
"Id": "487540",
"Score": "0",
"body": "Thank you for your comment. I like the idea of using loops. I did try using loops. Unfortunately use of loops caused a literal stack overflow. I think the second test case is designed to break loop-based solutions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T18:50:54.607",
"Id": "248252",
"ParentId": "248156",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T19:08:28.223",
"Id": "248156",
"Score": "5",
"Tags": [
"c#",
"programming-challenge",
"strings"
],
"Title": "C#: Repeated String"
}
|
248156
|
<p>I've written working LZ77 algorithm implementation which uses linked lists (they help to look for matching substrings faster). I'd like to get some feedback on my code's quality and also information about mistakes and dubious places in my program (if I have any).</p>
<pre><code>#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
unsigned int max_buf_length=0;
unsigned int max_dict_length=0;
unsigned int cur_dict_length=0;
unsigned int cur_buf_length=0;
struct link {
unsigned short length;
unsigned short offset;
unsigned char next;
};
struct Node
{
Node* prev;
unsigned int index;
};
class LinkedList
{
public: Node* lastNode;
LinkedList()
{
lastNode=nullptr;
}
~LinkedList()
{
Node* temp;
while(lastNode!=nullptr)
{
temp=lastNode;
lastNode = lastNode->prev;
delete temp;
}
}
void PushBack(unsigned int val)
{
Node* myNode = new Node;
myNode->index=val;
myNode->prev=lastNode;
lastNode=myNode;
}
};
unsigned int readFile(unsigned char* &raw, fstream &inp)
{
inp.seekg(0, ios::beg);
unsigned int file_start = inp.tellg();
inp.seekg(0, ios::end);
unsigned int file_end = inp.tellg();
unsigned int file_size = file_end - file_start;
inp.seekg(0, ios::beg);
raw = new unsigned char[file_size];
inp.read((char*)raw, file_size);
return file_size;
}
void FindLongestMatch(unsigned char* s, unsigned int buf_start, unsigned short &len, unsigned short &off, LinkedList dict[])
{
Node* current = dict[s[buf_start]].lastNode;
unsigned int max_offset = buf_start - cur_dict_length;
unsigned int j = 0;
unsigned int k = 0;
if(current!=nullptr && (current->index)>=max_offset) { len=1; off=buf_start-(current->index); }
while(current!=nullptr && (current->index)>=max_offset)
{
j=1;
k=1;
while(k<cur_buf_length && s[(current->index)+j]==s[buf_start+k])
{
if((current->index)+j==buf_start-1) { j=0; }
else j++;
k++;
}
if(k>len)
{
len = k;
off = buf_start-(current->index);
if(len==cur_buf_length) break;
}
else
{
current=current->prev;
}
}
}
int UpdateDictionary(unsigned char* s, unsigned int shift_start, unsigned short Length, LinkedList dict[])
{
for(unsigned int i=shift_start; i<(shift_start+Length+1); i++)
{
dict[s[i]].PushBack(i);
}
return Length;
}
void compactAndWriteLink(link inp, vector<unsigned char> &out)
{
if(inp.length!=0)
{
out.push_back((unsigned char)((inp.length << 4) | (inp.offset >> 8)));
out.push_back((unsigned char)(inp.offset));
}
else
{
out.push_back((unsigned char)((inp.length << 4)));
}
out.push_back(inp.next);
}
void compressData(unsigned int file_size, unsigned char* data, fstream &file_out)
{
LinkedList dict[256];
link myLink;
vector<unsigned char> lz77_coded;
lz77_coded.reserve(2*file_size);
bool hasOddSymbol=false;
unsigned int target_size = 0;
file_out.seekp(0, ios_base::beg);
cur_dict_length = 0;
cur_buf_length = max_buf_length;
for(unsigned int i=0; i<file_size; i++)
{
if((i+max_buf_length)>=file_size)
{
cur_buf_length = file_size-i;
}
myLink.length=0;myLink.offset=0;
FindLongestMatch(data,i,myLink.length,myLink.offset, dict);
i=i+UpdateDictionary(data, i, myLink.length, dict);
if(i<file_size) {
myLink.next=data[i]; }
else { myLink.next='_'; hasOddSymbol=true; }
compactAndWriteLink(myLink, lz77_coded);
if(cur_dict_length<max_dict_length) {
while((cur_dict_length < max_dict_length) && cur_dict_length < (i+1)) cur_dict_length++;
}
}
if(hasOddSymbol==true) { lz77_coded.push_back((unsigned char)0x1); }
else lz77_coded.push_back((unsigned char)0x0);
target_size=lz77_coded.size();
file_out.write((char*)lz77_coded.data(), target_size);
lz77_coded.clear();
printf("Output file size: %d bytes\n", target_size);
printf("Compression ratio: %.3Lf:1\n", ((double)file_size/(double)target_size));
}
void uncompressData(unsigned int file_size, unsigned char* data, fstream &file_out)
{
if(file_size==0) { printf("Error! Input file is empty\n"); return; }
link myLink;
vector<unsigned char> lz77_decoded;
lz77_decoded.reserve(4*file_size);
unsigned int target_size = 0;
unsigned int i=0;
int k=0;
file_out.seekg(0, ios::beg);
while(i<(file_size-1))
{
if(i!=0) { lz77_decoded.push_back(myLink.next); }
myLink.length = (unsigned short)(data[i] >> 4);
if(myLink.length!=0)
{
myLink.offset = (unsigned short)(data[i] & 0xF);
myLink.offset = myLink.offset << 8;
myLink.offset = myLink.offset | (unsigned short)data[i+1];
myLink.next = (unsigned char)data[i+2];
if(myLink.offset>lz77_decoded.size()) {
printf("Error! Offset is out of range!");
lz77_decoded.clear();
return;
}
if(myLink.length>myLink.offset)
{
k = myLink.length;
while(k>0)
{
if(k>=myLink.offset)
{
lz77_decoded.insert(lz77_decoded.end(), lz77_decoded.end()-myLink.offset, lz77_decoded.end());
k=k-myLink.offset;
}
else
{
lz77_decoded.insert(lz77_decoded.end(), lz77_decoded.end()-myLink.offset, lz77_decoded.end()-myLink.offset+k);
k=0;
}
}
}
else lz77_decoded.insert(lz77_decoded.end(), lz77_decoded.end()-myLink.offset, lz77_decoded.end()-myLink.offset+myLink.length);
i++;
}
else {
myLink.offset = 0;
myLink.next = (unsigned char)data[i+1];
}
i=i+2;
}
unsigned char hasOddSymbol = data[file_size-1];
if(hasOddSymbol==0x0 && file_size>1) { lz77_decoded.push_back(myLink.next); }
target_size = lz77_decoded.size();
file_out.write((char*)lz77_decoded.data(), target_size);
lz77_decoded.clear();
printf("Output file size: %d bytes\n", target_size);
printf("Unpacking finished!");
}
int main(int argc, char* argv[])
{
max_buf_length=15; //16-1;
max_dict_length=4095; //4096-1
string filename_in ="";
string filename_out="";
fstream file_in;
fstream file_out;
unsigned int raw_size = 0;
unsigned char* raw = nullptr;
int mode = 0;
printf("Simple LZ77 compression/decompression program\n");
printf("Coded by MVoloshin, TSU, 2020\n");
if(argc==4) {
if(strcmp(argv[1], "-u")==0) mode = 0;
else if(strcmp(argv[1], "-c")==0) mode = 1;
else { printf("Unknown parameter, use -c or -u\n"); return 0; }
filename_in=std::string(argv[2]);
filename_out=std::string(argv[3]);
}
else
{
printf("Usage: [-c | -u] [input_file] [output_file]\n");
return 0;
}
file_in.open(filename_in, ios::in | ios::binary);
file_in.unsetf(ios_base::skipws);
file_out.open(filename_out, ios::out);
file_out.close();
file_out.open(filename_out, ios::in | ios::out | ios::binary);
file_out.unsetf(ios_base::skipws);
if(file_in && file_out) {
raw_size=readFile(raw, file_in);
printf("Input file size: %d bytes\n", raw_size);
}
else
{
if(!file_in) printf("Error! Couldn't open input file!\n");
if(!file_out) printf("Error! Couldn't open output file!\n");
mode = -1;
}
file_in.close();
if(mode==0)
{
uncompressData(raw_size, raw, file_out);
}
else if(mode==1)
{
compressData(raw_size, raw, file_out);
}
if(raw!=nullptr) delete[] raw;
file_out.close();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>welcome to code review! I have multiple remarks to your code and I try to build little chapters for each below. My impression is, that you already have programming experience in C and you're now trying to move to C++. While most C code can be compiled by a C++ compiler, the languages are somewhat different and everything that is idiomatic to C is very likely different in C++ ;-)\nThat being said, here are my remarks, if you have a question on anything, please ask and I'll elaborate:</p>\n<hr />\n<pre><code>using namespace std;\n</code></pre>\n<p>Don't do this, this is considered a very bad habit and in fact, no professional C++-developer I've seen so far writes this. This will add all identifiers from the <code>std</code> namespace to your scope and will prevent you from simply using those names otherwise.\nYou should also use the full qualified names of the type, eg. <code>std::fstream</code> instead of <code>fstream</code>.</p>\n<hr />\n<p>If you define a variable to be a reference or a pointer, stick the asterisk or the ampersand to the type, not the variable's identifier. So instead of writing</p>\n<pre><code>, unsigned short &len,\n</code></pre>\n<p>write</p>\n<pre><code>, unsigned short& len,\n</code></pre>\n<p>This is a difference to plain C, where the asterisk is written next to the identifier.</p>\n<hr />\n<p>In C++, use <code>std::cout</code> to write to <em>stdout</em>. Also, errors should be printed to <em>stderr</em> which is <code>std::cerr</code>:</p>\n<pre><code>std::cout << "Output file size: " << target_size << " bytes\\n";\n\n</code></pre>\n<pre><code>if(file_size==0) { \n std::cerr << "Error! Input file is empty\\n");\n return;\n}\n\n</code></pre>\n<hr />\n<p>When passing a structure to a function, pass it by reference. That way you save C++ from copying the structure's content. If you don't modify the structure's content, pass it by <code>const</code> reference:</p>\n<pre><code>int UpdateDictionary(unsigned char* s, unsigned int shift_start, unsigned short Length, std::list<unsigned>& dict);\n\nvoid compactAndWriteLink(const link& inp, vector<unsigned char> &out);\n</code></pre>\n<hr />\n<p>You're writing your own linked list, but I recommend using <code>std::list</code> instead. C++ standard library offers lots of containers for several use cases and it's always easier to use one of those while also producing more readable code. If you're interested in writing a linked list, I suggest doing this in a project <em>my own linked list</em> that way you don't get distracted with that LZZ stuff ;-)</p>\n<p>I'd even go a bit further and suggest that you create a <em>dictionary</em> class:</p>\n<pre><code>class dictionary\n{\npublic:\n unsigned short update(unsigned char* s, unsigned int shift_start, unsigned short length);\n void longest_match(unsigned char* s, unsigned int buf_start, unsigned short& len, unsigned short& off);\n\nprivate:\n std::list<unsigned int> dict[256]; // or even better, use std::array<std::list<unsigned int>, 256>\n};\n</code></pre>\n<hr />\n<p>You don't need to include <code><cstring></code>.</p>\n<hr />\n<p>As a hint: you should not use <code>new</code>. There's almost always a better way. For your linked list, I already pointed you to <code>std::list</code>, for the buffer returned from <code>readFile</code>, you could pass a vector to the function and use it to store the buffer:</p>\n<pre><code>unsigned int readFile(std::vector<char>& buffer, std::fstream& inp)\n{\n inp.seekg(0, ios::beg);\n unsigned int file_start = inp.tellg();\n inp.seekg(0, ios::end);\n unsigned int file_end = inp.tellg();\n unsigned int file_size = file_end - file_start;\n inp.seekg(0, ios::beg);\n\n buffer.reserve(file_size);\n inp.read(&buffer[0], file_size);\n return file_size;\n}\n</code></pre>\n<p>Note: there are better and more compact ways to read a file:\n<a href=\"https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring\">https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring</a></p>\n<hr />\n<p>Instead of passing around <code>unsigned char* data</code> and <code>unsigned int filesize</code> use an <code>std::vector<unsigned char></code> and pass it by reference. If you want to stick to pointer and size, make the pointer the first parameter.</p>\n<hr />\n<p>In <code>compressData</code> and <code>uncompressData</code> you don't need a <code>vector</code> to buffer the data. As you're only appending to it, you can simply write to the stream. I'd also rather use a generic stream, that way it's easier to control from the outside whether you want to write to a file or a buffer.</p>\n<hr />\n<p>If I compile your code with <code>g++ -Wall lzz.cc -o lzz</code> (gcc 8.3.0) I receive following warning:</p>\n<pre><code>lzz.cc: In function ‘void compressData(unsigned int, unsigned char*, std::fstream&)’:\nlzz.cc:154:11: warning: format ‘%Lf’ expects argument of type ‘long double’, but argument 2 has type ‘double’ [-Wformat=]\n printf("Compression ratio: %.3Lf:1\\n", ((double)file_size/(double)target_size));\n</code></pre>\n<p>This might be to me using a newer compiler, but in any case, always try to compile with <code>-Wall</code> to see if there are any warnings and fix those.</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T08:19:20.053",
"Id": "486012",
"Score": "0",
"body": "Thank you. P.S. LinkedList& dict[] gives me:\nC:\\compressor\\main.cpp|67|error: declaration of 'dict' as array of references"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T08:24:57.827",
"Id": "486013",
"Score": "0",
"body": "P.P.S. What kind of stream should I use to write the data? If I write directly to fstream it's too slow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T08:28:16.297",
"Id": "486014",
"Score": "0",
"body": "And I also have one more question: would be std::list fast enough in my case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T09:03:35.523",
"Id": "486015",
"Score": "0",
"body": "- Sorry about the LinkedList&, I just wanted to give a non-const example but didn't test it. You can think of it as `std::list<unsigned>&`, but I'll remove it from the post.\n- I suggest using generic `std::ostream`, that way you can give either `std::fstream` or `std::stringstream` or ... into the function. For fstream performance try the suggestion from here: https://stackoverflow.com/a/39387101/10415029\n- std::list<>::push_back has constant performance. I would prefer STL containers anytime over self-written data structures unless for very specific use cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T09:20:27.553",
"Id": "486016",
"Score": "0",
"body": "So, does the [] operator in function parameters mean passing by reference or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T09:29:55.390",
"Id": "486018",
"Score": "0",
"body": "Arrays aren't copied but passed as a pointer to the array itself, so the semantics are the same as for references."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T07:29:47.020",
"Id": "248180",
"ParentId": "248158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T19:45:36.477",
"Id": "248158",
"Score": "6",
"Tags": [
"c++",
"compression"
],
"Title": "LZ77 compressor and decompressor in C++"
}
|
248158
|
<p>An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].</p>
<p>Return true if and only if the given array A is monotonic.</p>
<pre><code>public class MonotonicArray {
public boolean IsMonotonic(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return false;
}
if (numbers.length == 1) {
return true;
}
boolean increasing = false;
boolean decreasing = false;
for (int index = 0; index < numbers.length - 1; index++) {
if (numbers[index + 1] == numbers[index]){
continue;
}
if (numbers[index + 1] > numbers[index]) {
if (!decreasing) {
increasing = true;
} else {
return false;
}
}
else {
if (!increasing) {
decreasing = true;
} else {
return false;
}
}
}
return increasing || decreasing;
}
}
</code></pre>
<p>Test cases:</p>
<pre><code>class MonotonicArrayTest extends MonotonicArray {
@org.junit.jupiter.api.Test
void isMonotonic1() {
int[] array = new int[]{1,2,3};
assertEquals(true,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic2() {
int[] array = new int[]{-1,-2,-3};
assertEquals(true,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic3() {
int[] array = new int[]{1,2,1};
assertEquals(false,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic4() {
int[] array = new int[]{-1,2,-9};
assertEquals(false,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic5() {
int[] array = new int[]{9,3,2};
assertEquals(true,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic6() {
int[] array = new int[]{};
assertEquals(false,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic7() {
int[] array = new int[]{1};
assertEquals(true,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic8() {
int[] array = new int[]{9,7,5,4,8,10};
assertEquals(false,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic9() {
int[] array = new int[]{1,1,2,3};
assertEquals(true,IsMonotonic(array));
}
@org.junit.jupiter.api.Test
void isMonotonic10() {
int[] array = new int[]{1,1,0,-1};
assertEquals(true,IsMonotonic(array));
}
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T21:40:42.283",
"Id": "485976",
"Score": "6",
"body": "It has bugs. Result for an empty array should be `true`. Result for an array of all-equal values should also be `true`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T04:22:50.110",
"Id": "486000",
"Score": "1",
"body": "@superbrain Can you justify why it should return true for the empty array? I am inclined to say that it should be UB or exception but I can't really make a solid argument about why that and not some other way..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T04:26:12.873",
"Id": "486001",
"Score": "3",
"body": "@superbrain Do you base it on the fact that \"for all (i,j) in an empty set\" is always satisified?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T11:04:45.653",
"Id": "486020",
"Score": "2",
"body": "@slepic Yes, that's why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:33:21.097",
"Id": "486051",
"Score": "2",
"body": "The real property is `forall i. A[i] <= A[i+1]` (or `>=` for decreasing). For an empty or singleton array, the domain of `i` is empty, so it property is vacuously satisfied."
}
] |
[
{
"body": "<h1>static</h1>\n<p><code>IsMonotonic(...)</code> does not need an instance of the <code>MonotonicArray</code> class to function, therefore it should be static.</p>\n<h1>Consistency</h1>\n<p>You special case an array of length 1 as monotonic. Is it really? It is neither increasing nor decreasing.</p>\n<p>What about <code>IsMonotonic(new int[]{1, 1, 1, 1})</code>? Seems to me that should be <code>true</code>, but it will return <code>false</code>. Definitely should be added as a test case. And if it should return <code>true</code>, then ...</p>\n<h1>Optimization</h1>\n<p>... checking for length 1 is too restrictive. Any length 2 array will always be monotonic as well. Perhaps:</p>\n<pre><code> if (numbers.length == 1) {\n return true;\n }\n</code></pre>\n<p>should be:</p>\n<pre><code> if (numbers.length <= 2) {\n return true;\n }\n</code></pre>\n<h1>Looping</h1>\n<p>This is ugly. Will Java optimize the <code>numbers.length - 1</code> calculation as a constant?</p>\n<pre><code> for (int index = 0; index < numbers.length - 1; index++) {\n\n if (numbers[index + 1] == numbers[index]){\n continue;\n }\n ...\n</code></pre>\n<p>It may be better to use Java's enhanced <code>for</code> loop to extract numbers, and rely on monotonic behaviour allowing equality to handle the first element:</p>\n<pre><code> int current = numbers[0];\n for(int value : numbers) {\n if (value != current) {\n if (value < current) {\n ...\n } else {\n ...\n }\n current = value;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T08:14:13.137",
"Id": "486011",
"Score": "0",
"body": "To avoid nesting `if` statements, another minor improvement would be `if (value == current) continue;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:13:40.203",
"Id": "486025",
"Score": "4",
"body": "What? You don't think a length-1 array should be considered monotonic? To me, it sounds like it should definitely be considered monotonic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:28:46.977",
"Id": "486029",
"Score": "5",
"body": "“[An array of length 1] is neither increasing nor decreasing.” It is both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:30:34.600",
"Id": "486050",
"Score": "2",
"body": "The monotonicity property vacuously holds for a single-element array, because there is no second element to invalidate it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T21:49:45.317",
"Id": "248162",
"ParentId": "248161",
"Score": "7"
}
},
{
"body": "<p>I'm not a big fan of having a single monolithic function that indiscriminately checks for both increasing and decreasing monotony. In most practical scenarios I would imagine you'd probably need to know if it's increasing or decreasing.</p>\n<p>Based on that I'd specifically define:</p>\n<pre><code>public static boolean isMonotonic(int[] numbers) {\n return isMonotonicIncreasing(numbers) || isMonotonicDecreasing(numbers);\n}\n\npublic static boolean isMonotonicIncreasing(int[] numbers) {\n return isXXX(numbers, (a, b) -> a <= b); // Not sure how to call this method\n}\n</code></pre>\n<p>Sure, there will be a couple of duplicate checks, but in the end IMO the code will be better structured, better readable and more re-usable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T10:52:22.833",
"Id": "486019",
"Score": "1",
"body": "Regarding the function name: as the second parameter is a `BiPredicate` and predicates use the standard method name `test()`, I'd go for `pairwiseTest(int[] numbers. BiPredicate<Integer, Integer> predicate)` or - moving away from the primitives `<T> pairwiseTest(List<T> objects, BiPredicate<T, T> predicate)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:51:06.780",
"Id": "486032",
"Score": "1",
"body": "Re \"a couple of duplicate checks\": on most inputs one or the other will indeed bail out quickly, but in the worst case it's twice the number of checks, for example 111111111111110."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:17:24.167",
"Id": "486049",
"Score": "0",
"body": "@Thomas Well the OP's solution has up to *three* checks at every element, while this has at worst two. (But yes, it's worse than the optimal solution, which only needs *one* check at every element.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T18:15:38.050",
"Id": "486064",
"Score": "0",
"body": "I combined our answers to [this](https://repl.it/repls/RawFatalSearch#Main.java). Do you see a way to make that nicer? (I'm not much of a Java guy.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:34:58.537",
"Id": "486094",
"Score": "1",
"body": "@superbrain: If you were serious about optimizing this for speed *without* a lot of care for keeping the source compact, you'd probably start by scanning for an element not equal to the first element (can be done very efficiently with SIMD), then depending on that one compare, enter one of two loops that only check for a single ordering. (Hard to vectorize with SIMD, but cheap with scalar so should compile to a loop with just a couple asm instructions that hopefully checks 1 element per clock cycle.) So one loop to start, possible early return, then if/else with a loop in each branch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:25:06.810",
"Id": "486099",
"Score": "0",
"body": "@PeterCordes Ugh... I wrote a lot of assembly in the '90s for years. Not going back to that ever again :-). Or do you mean the Java compiler would do it with SIMD for me? In any case, I like your start+branch idea, although I don't like the extra code for the start loop and I doubt it'll make a noteworthy difference in slow cases (like very long monotonic arrays) compared to my first-vs-last approach (unless you do get SIMD and the equality-prefix is long as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:48:47.503",
"Id": "486100",
"Score": "0",
"body": "@superbrain: A JIT might possible auto-vectorize the search-for-equal loop, but I wouldn't count on it. I think there is some limited HotSpot auto-vectorization for simple cases. If you wanted to manually vectorize this, you'd use C++ with intrinsics like `_mm_cmpeq_epi32` for that first loop (or experimental ISO C++ `std::simd`). The 2nd loop isn't as bad as I thought; you just need to compare each element to the next separately, not every combination, so that's just one load + 1 unaligned `_mm_loadu_si128` to feed `_mm_cmpgt_epi32`. (Or aligned loads + `_mm_alignr_epi8`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:51:40.240",
"Id": "486101",
"Score": "0",
"body": "@superbrain: Writing asm by hand is a terrible idea for almost every case, except sometimes for ARM because for some reason compilers are worse with ARM NEON intrinsics than with x86 SSE or PowerPC AltiVec. The initial loop is probably only has minor value since it turns out it should be possible to fairly efficiently vectorize a single-direction monotonicity check, mostly just avoiding touching the last element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T02:02:32.080",
"Id": "486104",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112049/discussion-between-superb-rain-and-peter-cordes)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T08:16:07.973",
"Id": "248181",
"ParentId": "248161",
"Score": "3"
}
},
{
"body": "<p>The loop is rather complicated. It is generally better to use simpler logic if possible, as that makes the loop simpler to reason about. For example, you can use <code>Integer.compare</code> to remove a lot of the logic from your loop.</p>\n<pre><code>public static boolean IsMonotonic(int[] numbers) {\n int lastCmp = 0;\n\n for (int i = 1; i < numbers.length; i++) {\n int cmp = Integer.compare(numbers[i], numbers[i - 1]);\n\n if (lastCmp == 0) {\n lastCmp = cmp;\n } else if (cmp != 0 && ((cmp > 0) != (lastCmp > 0))) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n<p>In each iteration the <code>cmp</code> variable is zero if the two numbers are equal, and either positive or negative depending on whether there was an increase or decrease.</p>\n<p>When <code>lastCmp</code> is zero, we have yet to see an increase or decrease, i.e. all integers have been equal. If <code>lastCmp</code> is nonzero, then we have seen either an increase or decrease. If the sequence is not monotonic, we will eventually reach a pair that moved in the opposite direction from the first change, which is what the second condition will detect.</p>\n<p>If the list is shorter than two elements, then the loop doesn't run at all, and just returns true.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:25:04.490",
"Id": "486040",
"Score": "1",
"body": "Due to integer overflow, `{ 0, Integer.MAX_VALUE, Integer.MIN_VALUE }` would erroneously test as monotonic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:02:50.713",
"Id": "486053",
"Score": "1",
"body": "I fixed the integer overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:06:53.473",
"Id": "486054",
"Score": "2",
"body": "This new version might not work, as [compare](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Integer.html#compare(int,int)) can return *any* positive or negative result. So your `-sign == lastSign` check isn't safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:09:08.443",
"Id": "486055",
"Score": "2",
"body": "Interesting. I initially wrote out the three-way case, but my IDE said it could be replaced with `Integer.compare`. It's annoying that they don't guarantee this behaviour for integer comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:20:06.973",
"Id": "486057",
"Score": "1",
"body": "@superbrain What do you think of this approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:24:29.190",
"Id": "486059",
"Score": "2",
"body": "Yeah, I agree it's annoying. I think they really only return 0, 1 or -1, just don't guarantee it. I think your newest version is correct, but it was a little prettier before. I'm almost sorry I pointed this issue out :-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:52:15.953",
"Id": "248188",
"ParentId": "248161",
"Score": "5"
}
},
{
"body": "<p>If you accept the <strong>consistency</strong> remark of @AJNeufeld (so that <code>[1]</code> being monotonic indicates that <code>[1,1,1]</code> may rather be monotonic too) and put the other remark about <code>[x,y]</code> being monotonic again, you may find it easier to have <code>true</code>-s by default and recognize when the array is not monotonic:</p>\n<pre><code>public static boolean IsMonotonic(int[] numbers) {\n if (numbers == null || numbers.length == 0) {\n return false;\n }\n boolean inc_or_const = true;\n boolean dec_or_const = true;\n int prev = numbers[0];\n for (int curr : numbers) {\n if (curr < prev) {\n inc_or_const = false;\n } else if (curr > prev) {\n dec_or_const = false;\n }\n prev = curr;\n }\n return inc_or_const || dec_or_const;\n}\n</code></pre>\n<p>Of course it looks that tidy only without short-circuiting, after that this will have a very similar structure to your original code again:</p>\n<pre><code>public static boolean IsMonotonic(int[] numbers) {\n if (numbers == null || numbers.length == 0) {\n return false;\n }\n boolean inc_or_const = true;\n boolean dec_or_const = true;\n int prev = numbers[0];\n for (int i = 1; i < numbers.length; i++) {\n int curr = numbers[i];\n if (curr < prev) {\n inc_or_const = false;\n if (!dec_or_const) {\n return false;\n }\n } else if (curr > prev) {\n dec_or_const = false;\n if (!inc_or_const) {\n return false;\n }\n }\n prev = curr;\n }\n return true;\n}\n</code></pre>\n<p>Here I went back to indexed access on the basis of my dislike against comparing the first element to itself (what the <code>for(:)</code> variant does). Also note that here, because of the short-circuit <code>return</code>s, completion of the loop means that the array is monotonic for sure. Plus the remark about the hazard of having <code>numbers.length-1</code> in the loop condition has been applied too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:50:13.090",
"Id": "248197",
"ParentId": "248161",
"Score": "0"
}
},
{
"body": "<ul>\n<li><p>You might get better performance and simplicity if you make up your mind right away: Comparing the <em>first</em> value with the <em>last</em> value immediately tells you which <strong>one</strong> of increasing/decreasing/constant you should check.</p>\n</li>\n<li><p>What you should do for <code>null</code> depends on the contract. <a href=\"https://leetcode.com/problems/monotonic-array/\" rel=\"nofollow noreferrer\">This problem is on LeetCode</a>, where you're even guaranteed that the array will have at least one element, so there you wouldn't need to cover <code>null</code> or an empty array. You "chose"(?) to return <code>false</code>, but you could just as well argue for <code>true</code>, since "no array" seems rather similar to "no elements", for which the correct answer is btw <code>true</code>, not <code>false</code>.</p>\n</li>\n</ul>\n<p>Here's one that uses a first-vs-last check (although I included "constant" in "increasing") and which puts the burden on the caller to provide a reasonable input (i.e., not <code>null</code>). I think it's better to have the user get an error than to silently pretend nothing's wrong.</p>\n<pre><code> public boolean isMonotonic(int[] numbers) {\n int last = numbers.length - 1;\n if (last >= 0 && numbers[0] <= numbers[last]) {\n for (int i = 0; i < last; i++) {\n if (numbers[i] > numbers[i+1]) {\n return false;\n }\n }\n } else {\n for (int i = 0; i < last; i++) {\n if (numbers[i] < numbers[i+1]) {\n return false;\n }\n }\n }\n return true;\n }\n</code></pre>\n<p>A <code>BiPredicate</code> version inspired by <a href=\"https://codereview.stackexchange.com/a/248181/228314\">RoToRa's answer</a>. This one distinguishes all three cases, as the <code>BiPredicate</code> avoids code duplication:</p>\n<pre><code> public boolean isMonotonic(int[] numbers) {\n int n = numbers.length;\n if (n <= 2) {\n return true;\n }\n BiPredicate<Integer, Integer> fail =\n numbers[0] < numbers[n-1] ? (a, b) -> a > b :\n numbers[0] > numbers[n-1] ? (a, b) -> a < b :\n (a, b) -> a != b;\n for (int i = 1; i < n; i++)\n if (fail.test(numbers[i-1], numbers[i]))\n return false;\n return true;\n }\n</code></pre>\n<p>Python version, just for fun :-)</p>\n<pre><code>from operator import eq, le, ge\n\ndef isMonotonic(numbers):\n first, last = numbers[:1], numbers[-1:]\n check = eq if first == last else le if first < last else ge\n return all(map(check, numbers, numbers[1:]))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:40:22.530",
"Id": "486096",
"Score": "0",
"body": "Your idea of looking at the last element to determine direction is interesting, but might touch a cache line that didn't need to be touched if the early part of the array is enough to prove it non-monotonic. But is simplifies startup so either strategy could be better depending on the inputs. (Assuming you're optimizing for speed, as discussed in [another comment thread](https://codereview.stackexchange.com/questions/248161/check-if-array-is-monotonic-i-e-either-monotone-increasing-or-monotone-decreasin#comment486094_248181).) But yes, 2 separate loops in if/else is efficient and readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:15:45.557",
"Id": "486098",
"Score": "0",
"body": "@PeterCordes Well, but it's only one cache-line. And the early-part argument is for best-case scenarios. I'm more interested in worst-case, i.e., where times matter more. Like very long arrays that *are* monotonic. I don't care much about super-duper-fast vs \"just\" super-fast in best-case scenarios :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:55:34.513",
"Id": "486102",
"Score": "0",
"body": "It's only one cache line, but if it's cold in cache that could stall the pipeline for long enough that it could have already finished looking at the first few cache lines of the array. I'm picturing a case where the first few cache lines of the array are hot in cache, but the end isn't. (Although if it was just written first to last, that's opposite). The separate loops only have a control dependency, not a data dependency, on that last line, so if the branch predicted correctly all that work can be already done under the latency of that cache miss. But if it mispredicts, it has to restart."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:58:51.533",
"Id": "486103",
"Score": "0",
"body": "Agreed for most cases it's fine, and doesn't impact the worst-case large monotonic array time by more than a couple hundred clock cycles in the worst case, negligible compared to the difference between SIMD and scalar code for this, especially on x86 where branching on SIMD compare results can be done efficiently. (Unlike on some ARM)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:03:45.750",
"Id": "248202",
"ParentId": "248161",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248162",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T21:00:58.357",
"Id": "248161",
"Score": "8",
"Tags": [
"java",
"array"
],
"Title": "Check if array is monotonic i.e either monotone increasing or monotone decreasing"
}
|
248161
|
<p>Posting my code for a LeetCode problem, if you'd like to review, please do so. Thank you for your time!</p>
<h2>Problem</h2>
<p>For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.</p>
<h3>Format</h3>
<p>The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).</p>
<p>You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.</p>
<h3>Example 1 :</h3>
<pre><code>Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
Output: [1]
</code></pre>
<h3>Example 2 :</h3>
<pre><code>Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
Output: [3, 4]
</code></pre>
<h3>Note:</h3>
<p>According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>
<h3>Code</h3>
<pre><code>// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_set>
#include <algorithm>
static const struct Solution {
using ValueType = std::uint_fast16_t;
static const std::vector<int> findMinHeightTrees(
const int n,
const std::vector<std::vector<int>>& edges
) {
std::vector<int> buff_a;
std::vector<int> buff_b;
std::vector<int>* ptr_a = &buff_a;
std::vector<int>* ptr_b = &buff_b;
if (n == 1) {
buff_a.emplace_back(0);
return buff_a;
}
if (n == 2) {
buff_a.emplace_back(0);
buff_a.emplace_back(1);
return buff_a;
}
std::vector<Node> graph(n);
for (const auto& edge : edges) {
graph[edge[0]].neighbors.insert(edge[1]);
graph[edge[1]].neighbors.insert(edge[0]);
}
for (ValueType node = 0; node < n; ++node) {
if (graph[node].isLeaf()) {
ptr_a->emplace_back(node);
}
}
while (true) {
for (const auto& leaf : *ptr_a) {
for (const auto& node : graph[leaf].neighbors) {
graph[node].neighbors.erase(leaf);
if (graph[node].isLeaf()) {
ptr_b->emplace_back(node);
}
}
}
if (ptr_b->empty()) {
return *ptr_a;
}
ptr_a->clear();
std::swap(ptr_a, ptr_b);
}
}
private:
static const struct Node {
std::unordered_set<ValueType> neighbors;
const bool isLeaf() {
return std::size(neighbors) == 1;
}
};
};
</code></pre>
<h3>References</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-height-trees/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-height-trees/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/Tree_(graph_theory)" rel="nofollow noreferrer">Wiki</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>A triply nested loops always look scary. Especially with <code>while (true)</code>.</p>\n<p>First thing first, trust yourself. The leaf node (and the <code>ptr_a</code> contains only leafs) has only one neighbour. The</p>\n<pre><code>for (const auto& node : graph[leaf].neighbors)\n</code></pre>\n<p>loop is effectively</p>\n<pre><code>auto& node = graph[leaf].neighbors.begin();\n</code></pre>\n<p>Second, no naked loops please. And more functions please. The</p>\n<pre><code>for (const auto& leaf : *ptr_a)\n</code></pre>\n<p>prunes leaves from the tree. Factor it out into a <code>prune_leaves</code> function, which would return a set (technically a vector) of the new leaves:</p>\n<pre><code>leaves = prune_leaves(leaves, graph);\n</code></pre>\n<p>Third, the outer loop shall naturally terminate when less than 3 leaves remain.</p>\n<p>Finally, separate IO from the business logic. That said, a code along the lines of</p>\n<pre><code> graph = build_graph();\n leaves = collect_leaves(graph);\n while (leaves.size() < 3) {\n leaves = prune_leaves(leaves, graph);\n }\n return leaves;\n</code></pre>\n<p>would win my endorsement. Notice how <code>ptr_a</code> and <code>ptr_b</code> - which are not the most descriptive names - disappear.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:20:50.360",
"Id": "248204",
"ParentId": "248165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:13:45.987",
"Id": "248165",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 310: Minimum Height Trees"
}
|
248165
|
<p>I have built a website in Django in which I tried for the first time to create a complex app. It's an app that scrapes weather conditions on a peak in mountains, which are 17. I wanted to show a detailed forecast in separate templates, so I have 17 views which look almost the same.</p>
<p>Only 4 views:</p>
<pre><code>class KasprowyWierchForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Kasprowy Wierch peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Kasprowy').order_by('date')
print(context['Peak'])
return context
class KoscielecForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Koscielec peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Koscielec').order_by('date')
return context
class KrivanForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for Krivan peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Krivan').order_by('date')
return context
class MieguszowieckiForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mieguszowiecki peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mieguszowiecki').order_by('date')
return context
class MnichForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mnich peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mnich').order_by('date')
return context
</code></pre>
<p>Only the name of the view class and <code>context['Peak']</code> are different. The rest of the code is redundant. As my experience is based only on my self learning process I've not found any nice solution on how to fix or refactor.</p>
|
[] |
[
{
"body": "<p>One option is to modify your <code>TemplateView</code> class to include the peak's name as an instance attribute (say <code>peak_name</code>) and make the <code>get_context_data</code> method make use of it:</p>\n<pre><code>class TemplateView():\n # Class attributes\n\n def __init__(self, peak_name):\n # Instance attributes\n # ...\n self.peak_name = peak_name\n\n # Class methods\n\n # Modification of the get_context_data method\n def get_context_data(self, **kwargs):\n context['Peak'] = PeakForecast.objects.filter(\n name_of_peak=self.peak_name).order_by('date') #<- Modification here\n print(context['Peak'])\n return context\n</code></pre>\n<p>And then you can generate your peak views as instances of that class:</p>\n<pre><code>krivan_view = TemplateView('Krivan')\nkrivan_view.get_context_data(arg1='arg1', arg2='arg2')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:10:11.737",
"Id": "486056",
"Score": "0",
"body": "Thanks that was really helpful. And I just made a class which inherit from TemplateView and in that class I made modification and then rest classes inherit from that one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:04:53.807",
"Id": "486079",
"Score": "0",
"body": "You're welcome. I'm glad this was helpful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T02:34:27.527",
"Id": "248173",
"ParentId": "248166",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248173",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:29:46.567",
"Id": "248166",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"django"
],
"Title": "Scraping weather conditions for mountain peeks"
}
|
248166
|
<p>I am creating a social network and I want to know if this is a secure way of uploading pics/gifs and videos.</p>
<pre><code>if(isset($_POST['post'])) {
$uploadOk = 1;
$imageName = $_FILES['postToUpload']['name'];
$errorMessage = "";
$picdate = date('Y-m-d_H-i-s');
if($imageName != "") {
$targetDir = "assets/images/posts/";
$imageName = $targetDir . uniqid() . basename($imageName);
$imageFileType = pathinfo($imageName, PATHINFO_EXTENSION);
if($_FILES['postToUpload']['size'] > 10971520) {
$errorMessage = "Your file is to large";
$uploadOk = 0;
}
if (strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" &&
strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "gif"
&& strtolower($imageFileType) != "mp4"&& strtolower($imageFileType) != "Ogg"
&& strtolower($imageFileType) != "WebM"){
$errorMessage = "File type not allowed.";
$uploadOk = 0;
}
if($uploadOk){
if(move_uploaded_file($_FILES['postToUpload']['tmp_name'], $imageName)) {
// image uploaded
} else{
// image did not upload
$uploadOk = 0;
}
}
}
if($uploadOk) {
$post = new Post($con, $userLoggedIn);
$post->submitPost(trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING))),
'none', $imageName);
} else {
echo "<div class='alert alert-danger'>
$errorMessage
</div>";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code is insecure because:</p>\n<ul>\n<li>It only relies on the file extension, so attackers can upload any backdoors.</li>\n<li>It accesses variable <code>$_FILES['postToUpload']['name']</code> without checking if it is defined and this may lead to Full Path Disclosure.</li>\n<li>It uses function <code>uniqid()</code> without any arguments, so uniqueness is not guaranteed and the files that are uploaded simultaneously and have the same file name will be overwritten.</li>\n<li>It stores the filename provided by user without removing potentially dangerous characters and this may lead to unexpected results.</li>\n</ul>\n<p>Some recommendations to improve your code:</p>\n<ul>\n<li>Get rid of the <code>$uploadOk</code> variable. You already have and handle the <code>$errorMessage</code> variable and this is enough to check if the file was uploaded successfully.</li>\n<li>You should define <code>$imageFileType</code> as lowercase, instead of calling <code>strtolower()</code> for each extension.</li>\n<li>You should define all accepted file extensions as lowercase, otherwise users won't able to upload some files (in your case <code>WebM</code> and <code>Ogg</code>, because <code>strtolower($imageFileType) != "Ogg"</code> and <code>strtolower($imageFileType) != "WebM"</code> will always be <code>FALSE</code>).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T13:56:11.410",
"Id": "249217",
"ParentId": "248167",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T23:24:33.850",
"Id": "248167",
"Score": "2",
"Tags": [
"php"
],
"Title": "Secure way of uploading php images and GIF"
}
|
248167
|
<p>ceil_constexpr is is based on: <a href="https://stackoverflow.com/questions/8377412/ceil-function-how-can-we-implement-it-ourselves/8378022#8378022">https://stackoverflow.com/questions/8377412/ceil-function-how-can-we-implement-it-ourselves/8378022#8378022</a></p>
<p>ceil_constexpr2 is a simpler version that takes advantage of truncation.</p>
<p>WARNING 1: Both ceil functions uses from c++20.</p>
<p>WARNING 2: ceil_constexpr uses bit_cast - a c++20 function that I believe only MSVC v14.27 supports at the current date, 20th August 2020.</p>
<pre><code>#include <cstdint>
#include <concepts>
#include <limits>
#include <bit>
#include <exception>
template<typename T>
concept FloatingPoint =
std::is_floating_point_v<T> &&
(sizeof(T) == 4 || sizeof(T) == 8) &&//Only 32/64 bit allowed. 80 bit fp not allowed
sizeof(float) == 4 && sizeof(double) == 8 &&//float must be 32 bit fp while double must be 64 bit fp
std::numeric_limits<T>::is_iec559 == true &&// Only IEEE 754 fp allowed
std::endian::native == std::endian::little;
template<FloatingPoint T>
constexpr bool isInf_constexpr(T inFp)//detect if infinity or -infinity
{
constexpr bool is_T_Float = std::is_same_v<T, float>;
using uintN_t = std::conditional_t<is_T_Float, uint32_t, uint64_t>;
using intN_t = std::conditional_t<is_T_Float, int32_t, int64_t>;
constexpr uintN_t mantissaBitNumber = is_T_Float ? 23 : 52;
constexpr uintN_t infinityExponentValue = is_T_Float ? 0xff : 0x7ff; //the value of the exponent if infinity
constexpr uintN_t positiveInfinityValue = infinityExponentValue << mantissaBitNumber;//the value of positive infinity
constexpr uintN_t signRemovalMask = std::numeric_limits<intN_t>::max();//the max value of a signed int is all bits set to one except sign
return ((std::bit_cast<uintN_t, T>(inFp) & signRemovalMask) == positiveInfinityValue);//remove sign before comparing against positive infinity value
}
template<FloatingPoint T>
constexpr bool isNaN_constexpr(T inFp)
{
constexpr bool is_T_Float = std::is_same_v<T, float>;
using uintN_t = std::conditional_t<is_T_Float, uint32_t, uint64_t>;
using intN_t = std::conditional_t<is_T_Float, int32_t, int64_t>;
constexpr uintN_t mantissaBitNumber = is_T_Float ? 23 : 52;
constexpr uintN_t NaNExponentValue = is_T_Float ? 0xff : 0x7ff;//the value of the exponent if NaN
constexpr uintN_t signRemovalMask = std::numeric_limits<intN_t>::max();//the max value of a signed int is all bits set to one except sign
constexpr uintN_t exponentMask = NaNExponentValue << mantissaBitNumber;
constexpr uintN_t mantissaMask = (~exponentMask) & signRemovalMask;//the bits of the mantissa are 1's, sign and exponent 0's.
return (
((std::bit_cast<uintN_t, T>(inFp) & exponentMask) == exponentMask) &&//if exponent is all 1's
((std::bit_cast<uintN_t, T>(inFp) & mantissaMask) != 0) //if mantissa is != 0
);
}
template<FloatingPoint T>
constexpr T ceil_constexpr(T inFp)
{
if (isInf_constexpr<T>(inFp))
{
throw std::invalid_argument("Input floating point is infinity.");
}
else if (isNaN_constexpr<T>(inFp))
{
throw std::invalid_argument("Input floating point is NaN.");
}
constexpr bool is_T_Float = std::is_same_v<T, float>;
constexpr uint32_t mantissaBitNumber = is_T_Float ? 23 : 52;
constexpr uint32_t exponentMask = is_T_Float ? 255 : 2047;//used to remove the sign bit after the exponent bits
constexpr uint32_t exponentBias = is_T_Float ? 127 : 1023;
using uintN_t = std::conditional_t<is_T_Float, uint32_t, uint64_t>;
using intN_t = std::conditional_t<is_T_Float, int32_t, int64_t>;
const uintN_t input = std::bit_cast<uintN_t, T>(inFp);//bitwise copy floating point to unsigned integer
const intN_t exponent = static_cast<intN_t>((input >> mantissaBitNumber) & exponentMask) - exponentBias;
if (exponent < 0)
{
return (inFp > 0);
}
// small numbers get rounded to 0 or 1, depending on their sign
const intN_t fractional_bits = static_cast<intN_t>(mantissaBitNumber) - exponent;
if (fractional_bits <= 0)
{
return inFp;
}
// numbers without fractional bits are mapped to themselves
//constexpr uintN_t uIntAllOnes = is_T_Float ? 0xffffffff : 0xffffffffffffffff;
constexpr uintN_t uIntAllOnes = std::numeric_limits<uintN_t>::max();//store the max value of an unsigned integer (all bits are 1's)
const uintN_t integral_mask = uIntAllOnes << fractional_bits;
const uintN_t output = input & integral_mask;
// round the number down by masking out the fractional bits
inFp = std::bit_cast<T, uintN_t>(output);//bitwise copy unsigned integer to floating point
if (inFp > 0 && output != input)
{
++inFp;
}
// positive numbers need to be rounded up, not down
return inFp;
}//algorithm from: https://stackoverflow.com/questions/8377412/ceil-function-how-can-we-implement-it-ourselves/8378022#8378022
template<FloatingPoint T>
constexpr T ceil_constexpr2(const T inFp)//simpler version
{
if (isInf_constexpr<T>(inFp))
{
throw std::invalid_argument("Input floating point is infinity.");
}
else if (isNaN_constexpr<T>(inFp))
{
throw std::invalid_argument("Input floating point is NaN.");
}
constexpr bool is_T_Float = std::is_same_v<T, float>;
using uintN_t = std::conditional_t<is_T_Float, uint32_t, uint64_t>;
using intN_t = std::conditional_t<is_T_Float, int32_t, int64_t>;
if (inFp > 0 && inFp != static_cast<intN_t>(inFp))
{
return static_cast<intN_t>(inFp + 1);
}
else
{
return static_cast<intN_t>(inFp);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T01:45:08.410",
"Id": "485995",
"Score": "4",
"body": "Welcome to CodeReview@CR. And thanks for providing the reference for the algorithm/procedure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T03:39:56.247",
"Id": "486294",
"Score": "0",
"body": "@G. Sliepen I added a check for integral input values."
}
] |
[
{
"body": "<p>You have misspelt the typenames from <code><cstdint></code> (they are all in the <code>std</code> namespace; it's a portability error to assume they are also in the global namespace).</p>\n<p>Although probably only of theoretical interest, given the conditions imposed by the <code>FloatingPoint</code> concept, but the exact-width types are usually a bad choice - prefer <code>std::uint_fast64_t</code> and friends where extra width won't hurt.</p>\n<p>I guess that throwing exceptions for infinities and NaNs is a valid design choice (I would prefer to return the value unchanged, like <code>std::ceil()</code> does on IEEE-754 platforms), but this behaviour should be clearly documented somewhere - probably at the start of the header file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T15:53:06.710",
"Id": "251711",
"ParentId": "248169",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T00:00:10.433",
"Id": "248169",
"Score": "10",
"Tags": [
"c++",
"c++20",
"constant-expression"
],
"Title": "Two constexpr ceil functions"
}
|
248169
|
<p>Seeking to learning and have fun, I wrote out this script (what I expected to be) self explanatory and would appreciate some comments on that.</p>
<p>I <a href="https://gist.github.com/artu-hnrq/bfe1df326b3ac70287961d8b54e0e904#file-setup-profile-picture-py" rel="nofollow noreferrer">published it as a gist</a> and tried to do my best on what I understand about object-orientation, documentation, code readability and python best practices, so to speak. The idea was practice and learn!</p>
<p>Any review in these or other concepts that could turn this result in a better solution is very welcome!</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
"""Update UNIX-like system user profile picture with its GitHub account's one
This script assumes same system and platform username, but a different one can be declared.
It downloads target GitHub account's picture and set it up to current system user
"""
import os
import requests
import configparser
import click
# Get system's logged username
USER = os.getlogin()
def save_github_picture(username, path):
"""Gets GitHub user account's profile picture and saves it into target path
:param username: GitHub account username
:param path: Picture's path destination
"""
with open(path, "wb") as picture:
gh_profile_picture = requests.get(f"https://github.com/{username}.png").content
picture.write(gh_profile_picture)
def set_user_profile_picture(path):
"""Edits logged user AccountsService file to setup its profile picture path
:param path: New profile picture path
"""
# UNIX-like system user settings file
accounts_service_path = f"/var/lib/AccountsService/users/{USER}"
cfg = configparser.ConfigParser()
cfg.read(accounts_service_path)
cfg['User']['Icon'] = path
with open(accounts_service_path, 'w') as accounts_service:
cfg.write(accounts_service)
@click.command()
@click.argument('github_username', default=USER)
@click.option('--path', default=f"/home/{USER}/.face", help='define picture target path.')
def run(github_username, path):
"""Command line interface to define script's arguments
:param github_username: GitHub account username (default: system user)
:param path: New profile picture path (default: ~/.face)
"""
try:
save_github_picture(github_username, path)
set_user_profile_picture(path)
except Exception:
raise
else:
print(f"User profile picture updated with {github_username}'s GitHub one")
if __name__ == '__main__':
if os.geteuid() != 0:
raise PermissionError("This action requires root privileges")
else:
run()
</code></pre>
|
[] |
[
{
"body": "<pre><code>try:\n ...\nexcept Exception:\n raise\nelse:\n ...\n</code></pre>\n<p>You're not doing anything with the captured exception, so this accomplish nothing more than the code in <code>...</code>. You can drop the try, the code in the else will never execute if there is an exception in the previous two functions anyway.</p>\n<p>Depending on the size of the downloaded images, you may also consider <a href=\"https://stackoverflow.com/q/16694907/5069029\">streaming the http response to a file</a> directly instead of using the memory as a buffer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T21:42:11.167",
"Id": "248256",
"ParentId": "248174",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T03:47:00.727",
"Id": "248174",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Update UNIX-like system user profile picture with its GitHub account's one"
}
|
248174
|
<p>On Linux there is the <code>cat</code> command which outputs files concatenated but on Windows there exists no such command. As a result I decided to attempt to recreate a simple version of it but with challenge which was that I could not use any part of the C runtime library.</p>
<pre><code>#include <windows.h>
/* global variables */
HANDLE stdout = NULL;
HANDLE stdin = NULL;
char *input_buffer = NULL;
CONSOLE_READCONSOLE_CONTROL crc = { .nLength = sizeof(crc), .dwCtrlWakeupMask = 1 << '\n' };
char *output_buffer = NULL;
DWORD output_capacity = 0;
/* There is only CommandLineToArgvW so a version for ascii is needed */
LPSTR *CommandLineToArgvA(LPWSTR lpWideCmdLine, INT *pNumArgs)
{
int retval;
int numArgs;
LPWSTR *args;
args = CommandLineToArgvW(lpWideCmdLine, &numArgs);
if (args == NULL)
return NULL;
int storage = numArgs * sizeof(LPSTR);
for (int i = 0; i < numArgs; ++i) {
BOOL lpUsedDefaultChar = FALSE;
retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, NULL, 0, NULL, &lpUsedDefaultChar);
if (!SUCCEEDED(retval)) {
LocalFree(args);
return NULL;
}
storage += retval;
}
LPSTR *result = (LPSTR *)LocalAlloc(LMEM_FIXED, storage);
if (result == NULL) {
LocalFree(args);
return NULL;
}
int bufLen = storage - numArgs * sizeof(LPSTR);
LPSTR buffer = ((LPSTR)result) + numArgs * sizeof(LPSTR);
for (int i = 0; i < numArgs; ++i) {
BOOL lpUsedDefaultChar = FALSE;
retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, buffer, bufLen, NULL, &lpUsedDefaultChar);
if (!SUCCEEDED(retval)) {
LocalFree(result);
LocalFree(args);
return NULL;
}
result[i] = buffer;
buffer += retval;
bufLen -= retval;
}
LocalFree(args);
*pNumArgs = numArgs;
return result;
}
static void lmemcpy(char *dest, const char *src, DWORD len)
{
/* copy 4 bytes at once */
for (; len > 3; len -= 4, dest += 4, src += 4)
*(long *)dest = *(long *)src;
while (len--)
*dest++ = *src++;
}
static void catstdin(void)
{
DWORD chars_read = 0;
ReadConsoleA(stdin, input_buffer, 2048, &chars_read, &crc);
WriteConsoleA(stdout, input_buffer, chars_read, NULL, NULL);
}
static void catfile(char *filepath)
{
HANDLE filehandle = CreateFileA(filepath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (filehandle == INVALID_HANDLE_VALUE) {
WriteConsoleA(stdout, "Error could not open file: ", 27, NULL, NULL);
WriteConsoleA(stdout, filepath, lstrlenA(filepath), NULL, NULL);
ExitProcess(GetLastError());
}
DWORD filelength = GetFileSize(filehandle, NULL);
if (filelength > output_capacity) { /* see if we need to allocate more memory */
char *new_buffer = HeapAlloc(GetProcessHeap(), 0, filelength * 2); /* copy the data from the old memory to the new memory */
lmemcpy(new_buffer, output_buffer, output_capacity);
HeapFree(GetProcessHeap(), 0, output_buffer); /* free old memory */
output_capacity = filelength * 2;
output_buffer = new_buffer;
}
ReadFile(filehandle, output_buffer, filelength, NULL, NULL);
WriteConsoleA(stdout, output_buffer, filelength, NULL, NULL);
CloseHandle(filehandle); /* close file */
}
void __cdecl mainCRTStartup(void)
{
/* setup global variables */
stdout = GetStdHandle(STD_OUTPUT_HANDLE);
stdin = GetStdHandle(STD_INPUT_HANDLE);
input_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 2048);
output_buffer = HeapAlloc(GetProcessHeap(), 0, 2048);
output_capacity = 2048;
/* get argc and argv */
int argc;
char **argv = CommandLineToArgvA(GetCommandLineW(), &argc) + 1;
argc--; /* the first arg is always the program name */
switch (argc) {
case 0:
for (;;) catstdin();
break;
default:
for (int i = 0; i < argc; ++i) {
if (!lstrcmpA(argv[i], "-"))
catstdin();
else
catfile(argv[i]);
}
}
/* free memory */
HeapFree(GetProcessHeap(), 0, input_buffer);
HeapFree(GetProcessHeap(), 0, output_buffer);
LocalFree(argv);
/* exit */
ExitProcess(0);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T07:08:42.393",
"Id": "486027",
"Score": "2",
"body": "the `type` command does what you want, one file at a time."
}
] |
[
{
"body": "<h1>Avoid converting command line arguments to ASCII</h1>\n<p>There is no good reason to convert the command line arguments to ASCII. All the functions you use that take pointers to ASCII strings also have variants that handle wide strings, for example <code>lstrcmpW()</code> and <code>CreateFileW()</code>. This way, you can get rid of <code>CommandLineToArgvA()</code>.</p>\n<h1>Use <code>stderr</code> to report errors</h1>\n<p>Consider that it is not unlikely that the user of your <code>cat</code> implementation redirects standard output to another file. If there is an error, instead of printing it to the console, you are writing the error message to that file instead. Just add <code>stderr = GetStdHandle(STD_ERROR_HANDLE)</code>, and use that for the error messages.</p>\n<h1>Avoid allocating a buffer as large as each input file</h1>\n<p>Disk space is typically at least an order of magnitude larger than RAM. If you want to cat a file larger than the amount of free RAM available, your program will fail. It is better to allocate a buffer with a fixed size of say 64 KiB, and use multiple calls to <code>ReadFile()</code> if necessary to read the input as chunks of up to 64 KiB. On one hand, it means more overhead from multiple calls to <code>ReadFile()</code>, on the other hand you will likely stay within the L2 cache of your CPU. In any case, I expect performance will not be changed dramatically by this, but now your program handles arbitrarily sized files.</p>\n<p>This will also simplify your code: you no longer have to get the file size and resize the buffer if necessary. Instead, just read until you reach the <a href=\"https://docs.microsoft.com/en-us/windows/win32/fileio/testing-for-the-end-of-a-file\" rel=\"nofollow noreferrer\">end of the file</a>.</p>\n<h1>Use a loop to read from <code>stdin</code> until your reach EOF</h1>\n<p>If you specify <code>-</code> as an argument, you read only up to 2048 bytes from <code>stdin</code> before continuing to the next command line argument. And if you don't specify any arguments at all, you have an infinite loop that reads from <code>stdin</code>, even if there is nothing to read anymore.</p>\n<p>Keep in mind that <code>stdin</code> might also have been redirected, and will actually read from a file, or reads the output from another program.</p>\n<h1>Use the same buffer for <code>stdin</code> as for files</h1>\n<p>There's no need to have two separate buffers, as you only handle either a file or <code>stdin</code> at a time. Just ensure it is large enough.</p>\n<h1>Handle read and write errors</h1>\n<p>Things can go wrong. If there is an error reading a file or writing to <code>stdout</code>, you should print an error message to <code>stderr</code> and then immediately exit with a non-zero exit code. This will notify the user of errors. Also, if your <code>cat</code> implementation is used in a batch script, the non-zero exit code will allow that script to detect the error, instead of blindly continuing with invalid data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T21:22:39.243",
"Id": "248291",
"ParentId": "248175",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248291",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T04:12:07.193",
"Id": "248175",
"Score": "3",
"Tags": [
"c",
"windows"
],
"Title": "Simple Windows implementation of the cat command"
}
|
248175
|
<p>I was inspired by <a href="https://mathematica.stackexchange.com/a/228709">this answer</a> to make this.</p>
<blockquote>
<pre><code>ex[0] = 1;
ex[n_] := ex[n] = ex[n - 1] + 0.5^n/n!;
</code></pre>
<p>The double assignment in the second line is very important. This causes all function calls to be evaluated only once. Once it has been initially evaluated, it will be saved in ex[n].</p>
</blockquote>
<p>After a little research, it looks like I just reinvented a memoizer.</p>
<pre><code>#include <unordered_map>
#include <functional>
template < auto callback,
typename data_t,
typename key_t = std::size_t >
class static_memoizer_t
{
public:
using map_t = std::unordered_map< key_t,
data_t >;
using callback_t = decltype( callback );
static_memoizer_t( ) = default;
static_memoizer_t( static_memoizer_t const & ) = default;
static_memoizer_t( static_memoizer_t && ) = default;
static_memoizer_t & operator =( static_memoizer_t const & ) = default;
static_memoizer_t & operator =( static_memoizer_t && ) = default;
~static_memoizer_t( ) = default;
data_t operator[ ]( key_t const & key )
{
if( map.end( ) == map.find( key ) )
return map[ key ] = callback( key );
return map[ key ];
}
data_t operator[ ]( key_t const & key ) const
{
return map.at( key );
}
private:
map_t map;
};
template < typename data_t,
typename key_t = std::size_t >
class dynamic_memoizer_t
{
public:
using map_t = std::unordered_map< key_t,
data_t >;
using callback_t = std::function< data_t( key_t const & ) >;
dynamic_memoizer_t( callback_t callback ):
callback( std::move( callback ) )
{ }
dynamic_memoizer_t( dynamic_memoizer_t const & ) = default;
dynamic_memoizer_t( dynamic_memoizer_t && ) = default;
dynamic_memoizer_t & operator =( dynamic_memoizer_t const & ) = default;
dynamic_memoizer_t & operator =( dynamic_memoizer_t && ) = default;
~dynamic_memoizer_t( ) = default;
data_t operator[ ]( key_t const & key )
{
if( map.end( ) == map.find( key ) )
return map[ key ] = callback( key );
return map[ key ];
}
data_t operator[ ]( key_t const & key ) const
{
return map.at( key );
}
private:
map_t map;
callback_t callback;
};
</code></pre>
<p>The basic gist is that it stores the results of expensive functions. I wanted to add support for expensive recursive functions for my initial inspiration, not sure how to approach that though.</p>
<p>Usage:</p>
<pre><code>int square_of( int i ) noexcept
{
return i * i;
}
// static usage
using memoizer_t = static_memoizer_t< square_of, int, int >;
memoizer_t memoizer;
memoizer[ 2 ]; // calculates 2*2, returns 4
memoizer[ 2 ]; // pulls 2*2 from map
// dynamic usage
using memoizer_t = dynamic_memoizer_t< int, int >;
memoizer_t memoizer( square_of );
memoizer[ 2 ]; // calculates 2*2, returns 4
memoizer[ 2 ]; // pulls 2*2 from map
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:13:58.217",
"Id": "486048",
"Score": "0",
"body": "can you provide some sample code of its usage? Also, where are your benchmarks, performance measurements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T03:29:35.217",
"Id": "486105",
"Score": "0",
"body": "@Peter I hoped the usage was straight-forward but I added some usage in the question. As for benchmarks, it's just a iso-standard map wrapper. I suppose I can benchmark using `map` vs `unordered_map`."
}
] |
[
{
"body": "<p>Some nitpicks:</p>\n<ul>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three#Rule_of_zero\" rel=\"nofollow noreferrer\">Rule of zero</a> — don't explicitly default the special member functions unless necessary.</p>\n</li>\n<li><p>This method always traverses the map twice, and sometimes unnecessarily default-constructs a value:</p>\n<pre><code> data_t operator[ ]( key_t const & key )\n {\n if( map.end( ) == map.find( key ) )\n return map[ key ] = callback( key );\n return map[ key ];\n }\n</code></pre>\n<p>The following version avoids most of the problems above, but still traverses the map twice when there is no cached value:</p>\n<pre><code> data_t operator[](const key_t& key) {\n if (auto it = map.find(key); it != map.end()) {\n return it->second;\n } else {\n return map.emplace(key, callback(key))->first->second;\n }\n }\n</code></pre>\n<p>An optimal version might involve using <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/try_emplace\" rel=\"nofollow noreferrer\"><code>try_emplace</code></a> and a wrapper around the callback that converts to the value type.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:45:50.650",
"Id": "487356",
"Score": "0",
"body": "Does `insert` traverse the list again like emplace?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T05:00:02.097",
"Id": "487362",
"Score": "0",
"body": "@lajoh90686 Yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T05:04:25.840",
"Id": "487363",
"Score": "0",
"body": "Okay, I've change it to have a lazy-eval type and it now uses `try_emplace`. I've also removed all the defaulted functions. Thanks for the input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:20:22.900",
"Id": "248747",
"ParentId": "248177",
"Score": "3"
}
},
{
"body": "<p>Unfortunately, a major weakness of your class is that it only allows functions with a single argument. Now, this can be alleviated by using <code>std::tuple</code> and <code>std::apply</code>, but it's an ugly solution because it forces the user of the class to specify the tuple type, and every invocation of the object requires a <code>std::make_tuple</code>.</p>\n<p>Fortunately, this can be solved using variadic templates.</p>\n<p>To start, here's a basic definition of our class.</p>\n<pre><code>#include<tuple>\ntemplate<typename ReturnType, typename ... Args>\nclass Memoizer\n{\n};\n</code></pre>\n<p>Now, we need a way to store variadic number and types of arguments. <code>std::tuple</code> is perfect for this.</p>\n<pre><code>using tuple_type = std::tuple<Args...>;\nusing return_type = ReturnType;\nusing callback_type = std::function<return_type(Args...)>;\nusing map_type = std::unordered_map<tuple_type, return_type>;\n</code></pre>\n<p>Now, <code>std::tuple</code> doesn't come with an overloaded <code>std::hash</code>. Fortunately, <a href=\"https://stackoverflow.com/a/21439212/4678128\">this SO answer provides a good implementation</a>.</p>\n<p>Your data members would then become</p>\n<pre><code>map_type map;\ncallback_type callback;\n</code></pre>\n<p>The meat of the implementation lies in <code>operator()</code>.</p>\n<pre><code>return_type operator()(Args&& ... args)\n{\n auto arguments_tuple = std::make_tuple<Args...>(std::forward<Args>(args)...);\n if(map.find(arguments_tuple) == map.end())\n {\n std::cout << "Invoking function\\n"; // for debugging\n map.insert({arguments_tuple, std::apply(callback, arguments_tuple)});\n }\n return map[arguments_tuple]; \n}\n</code></pre>\n<p>The method takes the arguments, create a tuple of them and then checks if the map already contains the tuple. If it doesn't, it inserts an entry into the map, using <code>std::apply</code> (C++17 feature).</p>\n<p>Usage might look like this:</p>\n<pre><code>int func(int x, int y)\n{\n return x * y;\n}\n\nint main()\n{\n Memoizer<int, int, int> mem{func};\n auto t1 = mem(2, 3);\n auto t2 = mem(2, 3);\n std::cout << t1 << '\\n';\n std::cout << t2 << '\\n';\n}\n</code></pre>\n<p>The output is:</p>\n<pre><code>Invoking function\n6\n6\n</code></pre>\n<p>The full implementation is here:</p>\n<p><a href=\"https://godbolt.org/z/Eczq93\" rel=\"noreferrer\">https://godbolt.org/z/Eczq93</a></p>\n<p>You can also use custom types as arguments, provided <code>std::hash</code> and <code>operator==</code> are overloaded for those types.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T07:03:59.793",
"Id": "487487",
"Score": "0",
"body": "Very advanced answer and certainly an improvement over the current version. Smart change of operator and abstraction. Unfortunately, it cannot support taking the memoizer as an argument, which makes recursion impossible (unless I force all callbacks to support it). Will need to consider further"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T07:10:32.287",
"Id": "490574",
"Score": "0",
"body": "For `operator()`: Since it's not a template function, we shouldn't use `std::forward`; we should take `args` by value and then use `std::move`. Also, the current logic does an extra (unnecessary) map lookup in the return statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T03:36:41.683",
"Id": "248792",
"ParentId": "248177",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T06:41:37.797",
"Id": "248177",
"Score": "9",
"Tags": [
"c++",
"c++17"
],
"Title": "Abstract Memoizer"
}
|
248177
|
<pre class="lang-cpp prettyprint-override"><code>#include <functional>
template<typename return_type, typename... argument_types>
struct stateful_function_pointer
{
using function_type = std::function<return_type(argument_types...)>;
using function_pointer_type = return_type (*) (argument_types..., void*);
function_pointer_type callback ()
{
return [ ] (argument_types... arguments, void* user_data)
{
return (*static_cast<function_type*>(user_data))(arguments...);
};
}
void* user_data()
{
return static_cast<void*>(&function);
}
function_type function;
};
</code></pre>
<p>The C style callback must be providing a <code>void*</code> user data as its final parameter (which is a de-facto standard). It may be possible to pass additional user data other than the function state, but I do not see the point as the lambda can already capture user state.</p>
<p>An eccentricity: It is instantiated as e.g. <code>stateful_function_pointer<void, int, char*></code> instead of <code>stateful_function_pointer<void(int, char*)></code>.</p>
<p>Example usage as requested (wrapping a HDF5 C function in C++):</p>
<pre><code>class link_access_property_list : public property_list
{
public:
using function_pointer_type = stateful_function_pointer<herr_t, const char*, const char*, const char*, const char*, unsigned*, hid_t>;
using callback_type = function_pointer_type::function_type;
bool set_external_link_callback(const callback_type& callback)
{
function_pointer_.function = callback;
return H5Pset_elink_cb(id_, function_pointer_.callback(), function_pointer_.user_data()) >= 0;
}
protected:
function_pointer_type function_pointer_;
};
</code></pre>
<p>Then I could:</p>
<pre><code>lapl.set_external_link_callback(
[CAPTURE_WHATEVER_YOU_WANT]
(const char*, const char*, const char*, const char*, unsigned*, hid_t)
{
USE_WHATEVER_YOU_WANT
return herr_t(0);
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:00:39.707",
"Id": "486078",
"Score": "1",
"body": "On the other end how do you intend to cast the `void*` back to its original type if you don't know the type information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:08:40.203",
"Id": "486093",
"Score": "2",
"body": "Please show us the C function you are using to convert this back. Also an example of how you think the callback is being used would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T03:32:14.427",
"Id": "487479",
"Score": "0",
"body": "This allows you to capture arbitrary state into the C callback via lambda closures. You don't cast anything. You capture what you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T17:38:35.703",
"Id": "487564",
"Score": "1",
"body": "But the callback is a C function. The only thing it knows is `void*`. So you have to convert it to a `void*` at some point and then you need to convert it back to the original type. You can't pass a lambda to be registered as a C function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T21:22:42.507",
"Id": "487595",
"Score": "0",
"body": "You already cast it into a std::function with return (*static_cast<function_type*>(user_data))(arguments...); in the stateful_function_pointer... Nevermind, I was just looking for people who would argue whether allowing the user to pass additional state in the user_data would be useful/meaningful."
}
] |
[
{
"body": "<p>When you have a C callback you usually pass two things</p>\n<ul>\n<li>A pointer to a C function</li>\n<li>A <code>void*</code> pointer that is passed to your C function.</li>\n</ul>\n<p>The C function must know the type of the original object so it can cast the pointer back to its original type. only after it has been cast back can it be used. And you must cast it back to the exact type it was before you converted to <code>void*</code> or you are in undefined behavior.</p>\n<p>So this means the C function must understand the original type.</p>\n<p>Since your original type is a templated type (i.e. you don't know the type in general) you can't cast it back (unless you templitize the function so that the function you pass to C has a understanding of the templitized types).</p>\n<p>The easy way to do this is to implement a virtual interface. Then you can get a pointer to the base class convert this to a <code>void*</code> then in the C function you can convert back to the base class pointer and call the appropriate virtual interface on this base pointer. Virtual dispatch will then take care of calling the correct implementation.</p>\n<hr />\n<p>OK found the reference you were eluding to:</p>\n<p>Next time just add it to the question.</p>\n<p>From: <a href=\"https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html#Property-SetELinkCb\" rel=\"nofollow noreferrer\">https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html#Property-SetELinkCb</a></p>\n<pre><code>herr_t elink_callback(const char* parent_file_name,\n const char* parent_group_name,\n const char* child_file_name,\n const char* child_object_name,\n unsigned* acc_flags,\n hid_t fapl_id,\n void* op_data)\n{\n puts(child_file_name);\n return 0;\n}\n\nint main(void) {\n hid_t lapl_id = H5Pcreate(H5P_LINK_ACCESS);\n H5Pset_elink_cb(lapl_id, elink_callback, NULL);\n ...\n}\n</code></pre>\n<p>Notice at the top of the document it talks about C functions: <a href=\"https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html\" rel=\"nofollow noreferrer\">https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html</a></p>\n<p>This library is robably built by a C compiler so the whole ABI is a C ABI. Thus you can not pass any functions of C++ linkage as a parameter to a callback (The C code does not know how to correctly set up the stack frame to make a correct C++ call). You can only pass functions with C linkage.</p>\n<p>Now some compilers use a very similar ABI for C and C++ and you may get lucky passing a function that uses C++ linkage, but that just means you are getting lucky.</p>\n<p>Things like exceptions (that's just the first thing I can think of) will not be properly tracked across the stack frame boundries when going into C built stack frame.</p>\n<p>As you are getting lucky it is likely that sometime in the future it will just suddenly stop working with no way to diagnose the problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T03:38:06.733",
"Id": "487480",
"Score": "0",
"body": "Much more convoluted solution than what is above. I don't think you understand what this is capable of. The std::function is being passed as user_data and it can capture whatever data the user wants as the callback is being called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T17:41:08.780",
"Id": "487565",
"Score": "1",
"body": "@demiralp Obviously I am not understanding your usage. Can you provide an exact example of it being used in some code. Personally I am still doubtful this will work. But I could be wrong and it will depend on the interfaces it is being used in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T17:42:08.800",
"Id": "487566",
"Score": "1",
"body": "What is this: `lapl.set_external_link_callback()` This does not look like a C callback interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T21:02:21.753",
"Id": "487589",
"Score": "0",
"body": "H5Pset_elink_cb is the C function I'm wrapping in the second code block. set_external_link_callback is the C++ function I wrap it into. Do you now understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T22:51:38.903",
"Id": "487601",
"Score": "1",
"body": "@demiralp Found the docs for HP5 stuff: https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5P.html#Property-SetELinkCb OK. It becomes clearer now. I pretty sure that is broken code. Note: There is a difference between working and **working by accident**. The `H5Pset_elink_cb()` call takes a C-function as an argument. Unfortunately you are not giving it a C-function (as you are passing a variadic template function). There is no gurantee provided by the C++ standard that a C++ function has the same ABI as a C function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T22:53:03.857",
"Id": "487603",
"Score": "1",
"body": "@demiralp To make this valid the function passed to `H5Pset_elink_cb()` **MUST** be declared as `extern \"C\" herr_t <funcName>(const char*,const char*,const char*,const char*, unsigned*, hid_t,void*)`. Sure you may be getting lucky but that does not make it legal or valid. Currently it is simply undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T11:03:24.900",
"Id": "487639",
"Score": "0",
"body": "You are correct sir. This is news to me as I rely on empiricality regarding what I can do with the language. I should perhaps read the standard. Joaquin M Lopez Munoz of Boost points out a potential solution at http://bannalia.blogspot.com/2016/07/passing-capturing-c-lambda-functions-as.html . He also notes that this is a hypothetical problem and I agree with him as this compiles on MSVC2019+, GCC9+ and Clang9+. Nevertheless, I'll now bug myself to see if it is possible to incorporate this without causing inconvenience to the user. And apologies for the earlier crudeness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T11:37:40.023",
"Id": "487642",
"Score": "0",
"body": "Now I actually do not understand why it works in the case above. The compilers must be creating multiple definitions of lambdas, one with and one without extern \"C\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T18:10:34.220",
"Id": "487693",
"Score": "1",
"body": "@demiralp: `The compilers must be creating multiple definitions of lambdas, one with and one without extern \"C\"?` definitely not. The code is simply undefined behavior. It works by accident."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T18:18:27.677",
"Id": "487696",
"Score": "1",
"body": "**hypothetical problem**: No its a real problem. It's a real enough problem that they actually tell you how to solve it in the article you linked. You have three compilers on a single architecture using probably only one set of flags. I don't think you have enough context to \"agree\" with anybody. Your ability to test this is simply too limited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:41:30.180",
"Id": "487732",
"Score": "0",
"body": "Not defending anything but https://godbolt.org/z/qW6E6G demonstrates many more compilers supporting this on many more architectures. In fact, all compilers supporting the C++ prerequisites were able to run the code on all the supported architectures. I think this is enough context to agree that it is a theoretical problem and not a practical one. The fact that it is bad practice to rely on undefined behavior remains."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:09:59.550",
"Id": "487775",
"Score": "1",
"body": "@demiralp That's not even a reasonable test. The problem here is that the code you would be linking with the i.e `H5P` library would be compiled with a C compiler (this is C code after all if they could use C++ feature it would be compiler with a C++ compiler). Now link that C library against your C++ code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T01:07:34.637",
"Id": "487811",
"Score": "0",
"body": "The test states: As long as the user can build the library from source, this will not cause any issues on any of the listed compilers. Right?\n\nHDF can be built from source (and you often have to when e.g. building against your local MPI implementation). And the binaries on their website are built with MSVC and GCC too.\n\nA question is: Does anyone really use anything other than Clang/GCC/MSVC today? Are there any pure C compilers left in 2020?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T01:09:43.510",
"Id": "487812",
"Score": "1",
"body": "`Does anyone really use anything other than Clang/GCC/MSVC today?`: Yes. Every SOC chip will have its own custom compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T01:11:56.280",
"Id": "487813",
"Score": "0",
"body": "This whole ABI thing is so far from me as a programmer who started in 2000s, directly with experimental features of C++11. And I am glad it is so. The only time I touch C is to wrap its horrid interfaces into C++ so others do not have to deal with it. This was a failed effort in that direction.\n\nIn a slightly joking manner: !@#$ C. !@#$ anyone who uses anything other than Clang/GCC/MSVC today. Long live modern C++. The anger excludes embedded developers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T16:28:42.327",
"Id": "487856",
"Score": "1",
"body": "@demiralp All those hardware manafactures out there are shit out of luck then. So you have only worked in environments with Linux or Windows servers installed. i.e. small metal shops. These places tend to use bottom end machines and get scale by horizontal scaling. At the other end of the spectrum you have big metal machines that get scale by vertical scaling. Think of any big hardware manufacturer that also has its own OS they have their own C++ compiler: IBM => AIX => xlC++, HP => HP UX => aC++, Cray => COS => BlueWaters etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T16:42:49.163",
"Id": "487857",
"Score": "1",
"body": "I worked for Veritas (now part of Symantic). We built key management software. We sold this to other manufacturers. Our code had to build on all platforms we supported. A platform was `Hardware/OS-V/Compiler-V`. I seem to remember we supported over 36 different combinations of platform. If you code was not 100% standard compliant (and even using obscure features was not a good idea) you were going to break on one or more platforms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T16:44:14.877",
"Id": "487858",
"Score": "1",
"body": "Linux/Windows were the simplest of these platforms as they did not tend to beak backward compatibility (apart from gcc.2.95 to gcc.3.01) moving between versions and hardware/OS/Compiler. Most other OS were not as forgiving and each version of the compiler was unique and had different bugs."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:06:49.803",
"Id": "248210",
"ParentId": "248182",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248210",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T09:40:48.083",
"Id": "248182",
"Score": "3",
"Tags": [
"c++",
"c",
"c++17",
"pointers",
"callback"
],
"Title": "Stateful function pointer for passing C++ capturing lambdas / std::functions to C style callbacks"
}
|
248182
|
<p>I need to set different <code>__table_args__</code> for the mapped class depending on the backend DBMS, e.g. <code>mssql</code> and <code>mysql</code> - and this attribute cannot be set after the class definition, e.g. <code>class Repository(Base)</code> has been evaluated.</p>
<p>Ideally, my <code>db/models.py</code> module would take a parameter <code>db_type</code>, when it's imported, but this is not possible with Python.</p>
<p>For the module to export the local (mapped) classes, I use the following code:</p>
<pre><code>tables = (Repository, Commit, Blob)
globals().update((t.__name__, t) for t in tables)
</code></pre>
<p>But with this approach, it's not possible for importing modules to write:</p>
<pre><code>from db.models import Repository, Commit, Blob
</code></pre>
<p>since the classes are not exported at that point, but only after <code>create_models()</code> has been called.</p>
<p>What's the best approach for setting these <code>__table_args__</code> in a way that other modules can import the mapped classes like above, and so that I avoid having to have local class definitions in a function?</p>
<p><strong>db/models.py</strong></p>
<pre><code>import sqlalchemy
from sqlalchemy import (
Table, Column, ForeignKey, Integer,
String, Text, Boolean, DateTime
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import ForeignKeyConstraint
from sqlalchemy.orm import relationship
from common.exc import WatchdogException
_Base = None
def create_models(db_type):
global _Base
if _Base:
return _Base
if db_type == 'mssql':
table_args = {}
elif db_type == 'mysql':
table_args = {'mysql_default_charset': 'utf8',
'mysql_collate': 'utf8_bin'}
else:
raise WatchdogException('The database type is not supported: {}'.format(db_type))
Base = declarative_base()
class Repository(Base):
__tablename__ = 'stash_repository'
id = Column(Integer, primary_key=True)
head_branch = Column(Text, nullable=False)
head_commit = Column(String(40), nullable=False)
slug = Column(Text, nullable=False)
name = Column(Text, nullable=False)
state = Column(Text, nullable=False)
href = Column(Text, nullable=False)
clone = Column(Text, nullable=False)
commits = relationship('Commit', back_populates='repository', cascade='all, delete-orphan') # post_update=True
__table_args__ = (
ForeignKeyConstraint([project_id], [Project.id], onupdate='CASCADE', ondelete='CASCADE'), # use_alter=True
table_args
)
def __repr__(self):
return f'<{self.__class__.__name__}(id=\'{self.id}\')>'
class Commit(Base):
__tablename__ = 'stash_commit'
id = Column(String(40), primary_key=True)
repository_id = Column(Integer, primary_key=True)
author_name = Column(Text, nullable=False)
author_email = Column(Text, nullable=False)
author_time = Column(DateTime, nullable=False)
committer_name = Column(Text, nullable=False)
committer_email = Column(Text, nullable=False)
commit_time = Column(DateTime, nullable=False)
message = Column(Text, nullable=False)
repository = relationship('Repository', back_populates='commits')
blobs = relationship('Blob', back_populates='commit', cascade='all, delete-orphan')
__table_args__ = (
ForeignKeyConstraint([repository_id], [Repository.id], onupdate='CASCADE', ondelete='CASCADE'),
table_args
)
def __repr__(self):
return f'<{self.__class__.__name__}(id=\'{self.id}\')>'
class Blob(Base):
__tablename__ = 'stash_blob'
id = Column(String(40), primary_key=True)
commit_id = Column(String(40), primary_key=True)
name = Column(Text, nullable=False)
path = Column(Text, nullable=False)
mime = Column(Text, nullable=False)
infer_mime = Column(Text, nullable=True)
size = Column(Integer, nullable=False)
commit = relationship('Commit', back_populates='blobs')
matches = relationship('Match', back_populates='blob')
__table_args__ = (
ForeignKeyConstraint([commit_id], [Commit.id], onupdate='CASCADE', ondelete='CASCADE'),
table_args
)
def __repr__(self):
return f'<{self.__class__.__name__}(id=\'{self.id}\')>'
tables = (Repository, Commit, Blob)
globals().update((t.__name__, t) for t in tables)
_Base = Base
return _Base
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T04:37:34.147",
"Id": "486106",
"Score": "0",
"body": "You define a mixin (or a base) and the models will derive from that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T08:24:00.767",
"Id": "486114",
"Score": "0",
"body": "@hjpotter92 - Can you some sample code? A mixin is just a fancy term for a base class, right, when multiple base classes are used? Would the base class set the `__table_args__`? Also, this still doesn't solve my issue of having to create the classes dynamically in a function, does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:32:12.410",
"Id": "486314",
"Score": "0",
"body": "What's refraining you from having `from db.models import create_models; Repository, Commit, Blob = create_models('mysql')`? Provided you return the right values."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T10:12:17.467",
"Id": "248183",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"database",
"orm"
],
"Title": "Providing different __table_args__ to SQLAlchemy mapped class depending on backend DBMS"
}
|
248183
|
<p>You can find my original post <a href="https://stackoverflow.com/questions/63502080/moving-mean-square-error-between-2-arrays-valid-where-they-fully-overlap/63502297?noredirect=1#comment112291823_63502297">here on SO</a>. I was very surprised that I couldn't find a pre-coded function doing a mean square error between a signal (array A, size a) and a pattern (array B, size b<a) in a sliding window fashion. Thus I made one... and obviously it needs a lot of code improvement. I don't really know how to vectorize the implementation.</p>
<p>The goal is to take the pattern, slide it across the signal one step at a time, and determine everytime the mean square error between the signal and the pattern.</p>
<pre><code>from sklearn.metrics import mean_squared_error
import numpy as np
def correlate_edge_pattern(signal, pattern):
ms_errors = list()
k=0
while True:
data = signal[k:k+pattern.size]
if data.size != pattern.size:
break
err = mean_squared_error(pattern, data)
ms_errors.append(err)
k+=1
m = np.argmin(ms_errors)
return m
</code></pre>
<p>As you can observe below, it works as expected:</p>
<p><a href="https://i.stack.imgur.com/zGIzb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zGIzb.png" alt="correlated pattern" /></a></p>
<p>Here is a small code sample to test it:</p>
<pre><code>signal = -np.ones(1000)*20
signal[:100] = 0
signal[900:] = 0
noise = np.random.normal(0,1,size=1000)
noisy_signal = signal + noise
pattern = np.zeros(50)
pattern[:25] = -20
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T10:34:23.897",
"Id": "248184",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Moving mean square error between 2 arrays, 'valid', where they fully overlap"
}
|
248184
|
<p>I'm trying to create a setup script for our projects in an ubuntu server. This is what I have now, but I don't know if its correct, or can I do it differently/better ? If someone could take a look pls. Thanks</p>
<pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash
set -e
# ==================
# Step Functions
# ==================
# create_user() {
# echo "
# ----------------------
# 1. Creating a new user with name `<user>` and gives correct access.
# ----------------------
# "
# # [ASK]: How to make <user> a variable I read from STDIN
# # and pass it around in the following commands
# # add new user with the name of `user`
# sudo "adduser --ingroup www-data --disabled-password $user"
# # copy ssh/ folder from `ubuntu` user to new user
# # and gives the right permissions/privileges
# sudo cp -R ".ssh/" "/home/$user/"
# sudo chown -R "$user:www-data" "/home/$user/.ssh/"
# }
function update_pkgs() {
echo "
----------------------
Prerequisites : Making sure everything is up to date
----------------------
"
# checks is all pkgs are up to date
sudo apt-get update -y
# installing necessary pkgs
sudo apt-get install build-essential libssl-dev -y
}
function installing_nginx() {
echo "
----------------------
3. Installing Nginx...
----------------------
"
sudo apt update
sudo apt install nginx
sudo ufw allow 'Nginx HTTP'
}
function installing_node() {
echo "
----------------------
4. Installing NVM & Node
----------------------
"
# install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
# verifies installation
nvm --version
# install node the latest stable version
nvm install stable
}
function installing_yarn() {
echo "
----------------------
6. Installing Yarn
----------------------
"
# updating pakages
sudo apt-get update
# installs yarn
sudo apt-get install yarn
# checks yarn version
which yarn
yarn --version
}
function installing_pm2() {
echo "
----------------------
7. Installing PM2 via YARN
----------------------
"
# install pm2 with npm
yarn global add pm2
# set pm2 to start automatically on system startup
pm2 startup systemd
}
function parting_words(){
echo "
----------------------
Things left to Do
1. Clone the repositories from devtools
2. Add the ssh keys of developers to the .ssh/ folder
3. Configure nginx
4. Install cerbot for nginx and generate certificates
5. Make sure everything is working correctly
6. Delete user ubuntu
7. Have a cup of coffee
----------------------
"
}
# ==================
# MAIN SCRIPT
# ==================
echo "
----------------------
Server Setup Bash Script
----------------------
"
read -p "Do You Wish to run this Script ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
update_pkgs
echo "
----------------------
Let's create a new user
----------------------
"
read -p "What should we call the new user ?" user
sudo "adduser --ingroup www-data --disabled-password $user"
sudo cp -R ".ssh/" "/home/$user/"
sudo chown -R "$user:www-data" "/home/$user/.ssh/"
echo "$user ALL=(ALL) NOPASSWD: ALL" >> "/etc/sudoers.d/90-cloud-init-users"
installing_nginx
installing_node
installing_yarn
installing_pm2
parting_words
fi
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:53:16.870",
"Id": "486033",
"Score": "0",
"body": "You might want to look into [Ansible](https://docs.ansible.com/ansible/latest/index.html). It has the advantage that any step that has already been done will not be run again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T18:20:22.803",
"Id": "486066",
"Score": "0",
"body": "Agreed, Ansible is the tool you need."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T11:09:59.930",
"Id": "248185",
"Score": "1",
"Tags": [
"bash",
"server"
],
"Title": "Light setup bash script for an ubuntu server"
}
|
248185
|
<p>I am working on a small internal app that works along an external API for provisioning purpose.</p>
<p>The code essentially is comprised of a series of forms where the user inputs data, this data is then sent to the API to register new customers.</p>
<p>This is somewhat quite a linear process I will try to explain:</p>
<ol>
<li>Contact Creation: Basic customer info (email, address...).</li>
<li>Customer Creation: More advanced info, for a customer to be created there must be a <code>contactId</code> belonging to this customer.</li>
<li>Subscriber Creation: Info linking customer to the service acquired. The previous step has to be completed and a <code>customerId</code> must exist.</li>
<li>Service Creation: Lasts bits of advanced info about the service. Once again, a <code>suscriberId</code> needs to exist in order to link the service.</li>
</ol>
<p>I've managed a more or less quick process with a few tweaks here and there, but the first step (Contact) has a method that I can't seem to improve, which in turn causes this process to take up to a full minute!</p>
<p>As the whole process described earlier, the creation of each one of these is very linear too.</p>
<p>The API documentation states that the results of any GET should be paginated to a max of 10 entries, but following this further increases the time over the minute. Manual experiments showed that the best ratio is about 500 entries per page or in some cases, even the whole number of entries proved to be the fastest way rather than going 10 by 10.</p>
<p>Since the contact email can't be duplicated, one of the first things to do is check for the email provided in the form and compare it to all of the already existing emails stored.</p>
<p>In order to provide the <code>$page</code> and <code>$entries</code> to the API call, I must first fetch the total number of contacts. This number appears when calling the API to get the contacts. So the first method I use is:</p>
<pre class="lang-php prettyprint-override"><code>function fetchTotalContacts($uri, $auth){
$ch = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $uri.'?page=1&rows=1',
CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Authorization: $auth')
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$response = json_decode($response, true);
$totalContacts = $response['total_count'];
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
echo "Error en fetchTotalContacts() - Código: $http_code | ";
}
curl_close($ch);
return $totalContacts;
}
</code></pre>
<p>Now having <code>$totalContacts</code>, I can proceed and search if the email has been already registered, and this is the step I suspect to be responsible for the high execution time. This method searches the contacts and their emails, if it finds no coincidence, proceeds to create the contact with the data provided.</p>
<pre class="lang-php prettyprint-override"><code>function checkDuplicatedEmail($uri, $totalContacts, $contactEmailArray, $auth, $contactEmail, $dataContact){
$ch = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $uri.'?page=1&rows='.$totalContacts,
CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Authorization: $auth')
);
curl_setopt_array($ch, $options);
$customers = curl_exec($ch);
$customers = json_decode($customers, true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200) {
echo "Error en checkDuplicatedEmail() - Código: $http_code | ";
}
curl_close($ch);
/*
foreach ($customers['_embedded']['ngcp:customercontacts'] as $customer) {
$email = $customer['email'];
array_push($contactEmailArray, $email);
}
if (in_array($contactEmail, $contactEmailArray)) {
echo('El email utilizado ya ha sido registrado en la base de datos');
die();
}else{
$contactCreated = createContact($uri, $dataContact);
return $contactCreated;
}
*/
$repeated = 0;
for ($i=0; $i < $totalContacts ; $i++) {
if ($contactEmail == $customer["_embedded"]["ngcp:customercontacts"][$i]["email"]) {
$repeated += 1;
}
}
if ($repeated > 0) {
die(echo('El email utilizado ya ha sido registrado en la base de datos'));
}else{
$contactCreated = createContact($uri, $dataContact, $auth);
return $contactCreated;
}
}
</code></pre>
<p>As you can see, these are the quickiest options I've found, both making the whole process take 40s, which is too much still.</p>
<p>The response for <code>createContact($uri, $dataContact, $auth);</code> is a success code (400, 201..), so when I want to go to the next step I do need to, again, search all the contacts to find the one I just created and get the id. Fortunately, here I can simply skip to the last 20 contacts (not the last one directly so it can be used simultaneously without issues) and search there, this makes it real quick, but for the email there is no such skip, all the entries must be analyzed.</p>
<p>I don't know how to drop the time here, the rest of the code consists of fetching the <code>contactId</code> and creating the customer so not much to do there as it is now.</p>
<p>If any of you deem necessary to see the rest of the page I wil update the post.</p>
<p>As a final reminder, I have manually tried with different configs of pages and entries and for this page, the fastest was <code>1 page - All entries</code>. I've also tried taking the for/each loop outside the method, to no avail.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T08:45:29.177",
"Id": "487998",
"Score": "0",
"body": "[Cross-posted at Stack Overflow](https://stackoverflow.com/q/63504653/1014587)"
}
] |
[
{
"body": "<p>The <code>for</code> loop is not going to be the bottleneck in your loop, but what seems obvious to me is that you don't benefit from counting higher than <code>$repeated = 1</code>. This means that you don't need a counter variable, you actually need a loop breaking event -- in this case <code>die()</code>. For your information, <code>die()</code> will print the text in its first parameter, so using <code>echo</code> is redundant.</p>\n<pre><code>for ($i=0; $i < $totalContacts; ++$i) {\n if ($contactEmail == $customer["_embedded"]["ngcp:customercontacts"][$i]["email"]) {\n die('El email utilizado ya ha sido registrado en la base de datos');\n }\n}\nreturn createContact($uri, $dataContact, $auth);\n</code></pre>\n<p>Or another way, which I assume will be slower (because <code>array_column()</code> will be collecting all emails) is this functional design:</p>\n<pre><code>if (in_array($contactEmail, array_column($customer["_embedded"]["ngcp:customercontacts"], "email"))) {\n die('El email utilizado ya ha sido registrado en la base de datos');\n}\nreturn createContact($uri, $dataContact, $auth);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:36:56.303",
"Id": "486052",
"Score": "0",
"body": "Thank you! I was heading back home and didn't have time to change the title! I changed it and it did improve the exec. time, I still feel like it's too much time, (little over 30s) but I don't really see more way for improvement, could this be because of the external API? I haven't used that many, but of the few ones I've worked with this one sure qualifies as the worst for other various reasons. It's 3rd party software so sadly there is not much I can do about it too. It is an internal app meant for very little people to use, but even so I don't feel quite happy about the job done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:07:33.697",
"Id": "486164",
"Score": "1",
"body": "@Berny Whenever I suspect an external API is at fault, I replace all calls to the externals with debug statements. If that reduces your execution time from 30s to 1s, you know enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:27:25.570",
"Id": "248189",
"ParentId": "248187",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248189",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T12:50:48.877",
"Id": "248187",
"Score": "4",
"Tags": [
"php",
"api",
"iteration",
"curl"
],
"Title": "Checking for duplicate email in api response data"
}
|
248187
|
<p>I have a block of code that is re-used and I want to use functional programming to remove this duplication.</p>
<p>My code takes an array of items, splits the items into batches of 500 and then does some kind of work on them.</p>
<p>In the first function it deletes items from a database:</p>
<p><strong>Delete function:</strong></p>
<pre><code>const deleteDocuments = async (documentReferences) => {
const batchesOf500 = Math.ceil(documentReferences.length / 500);
for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
const batch = getBatchWriter();
const startingIndex = batchNumber * 500;
const maxIndex = startingIndex + 500;
for(let index = startingIndex; index < maxIndex; index += 1) {
if(index < documentReferences.length) {
const documentPath = documentReferences[index];
batch.delete(documentPath);
}
}
await batch.commit();
}
}
</code></pre>
<p>The second function is almost identical but instead of deleting from a database, it writes to the database:</p>
<p><strong>Add function:</strong></p>
<pre><code>const writeToCollection = async (dataArray, collectionRef) => {
const batchesOf500 = Math.ceil(dataArray.length / 500);
for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
const batch = getBatchWriter();
const startingIndex = batchNumber * 500;
const maxIndex = startingIndex + 500;
for(let index = startingIndex; index < maxIndex; index += 1) {
if(index < dataArray.length) {
const [key, value] = dataArray[index];
const doc = getDocFromPath(key);
batch.set(doc, value);
}
}
}
await batch.commit();
}
}
</code></pre>
<p>These functions are almost identical, so I have write a higher order function to do most of the leg-work.</p>
<p><strong>Higher order function:</strong></p>
<pre><code>const runFunctionInBatchesOf500 = (func, dataArray) => {
const batchesOf500 = Math.ceil(dataArray.length / 500);
for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
const batch = this.firestore.batch();
const startingIndex = batchNumber * 500;
const maxIndex = startingIndex + 500;
for(let index = startingIndex; index < maxIndex; index += 1) {
const document = dataArray[index];
func(document, batch);
}
}
await batch.commit();
}
</code></pre>
<p>And to it you can create your own functionality to apply to each document and use it like this:</p>
<pre><code>const write = (document, batch) => {
const doc = getDocFromPath(key);
batch.set(doc, value);
};
await runFunctionInBatchesOf500(write, dataArray);
</code></pre>
<p>This all works but I think I am missing something. Is this an efficient use of higher order functions? What would a more elegant, FP-style solution be?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:22:53.797",
"Id": "486085",
"Score": "3",
"body": "Yes Konijn asked where `key` comes from but changing the code would invalidate that answer. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:48:11.813",
"Id": "486090",
"Score": "0",
"body": "I wasn't incorporating improvements, I was fixing a mistake that distracted from the overall code review. I removed some code before posting this question to make it shorter and easier to understand; this was a mistake that slipped through. Now you've re-edited my post and put the random `key` value back in but to what end? Other users will notice it and either mention it or be confused when my request is regarding functional programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:18:17.257",
"Id": "486119",
"Score": "0",
"body": "I have rolled back your changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T10:45:02.727",
"Id": "486127",
"Score": "2",
"body": "@MSOACC I have undone your rollback. Whilst it is unfortunate that you made a mistake when posting the question that is your fault not ours. It is unfair to answerers to invalidate their answers for any reason. Additionally it creates messes, which if you read Sam's links you'd know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T11:00:54.560",
"Id": "486128",
"Score": "0",
"body": "I did read the links Sam posted. Did you read the change to the code that I made? Or the question at all?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T11:10:55.447",
"Id": "486129",
"Score": "2",
"body": "Yes, yes and the answer too - otherwise I wouldn't know this is answer invalidation."
}
] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li>Why hardcode the batch length to 500 ?</li>\n<li>Why not have the batch length be a nice constant ?</li>\n<li>You have even hard coded the length in the function name, which is really unfortunate</li>\n<li><code>batchNumber++</code> is more canonical than <code>batchNumber += 1</code></li>\n<li>I would have gone for <code>maxIndex = Math.min(startingIndex + 500, dataArray.length);</code> because now you have a lot of calls to <code>func</code> with <code>undefined</code> as a <code>document</code> value</li>\n<li><code>await</code> requires <code>runFunctionInBatchesOf500</code> to be <code>async</code> (it is missing now)</li>\n<li>I would use <code>Array.prototype.slice()</code> to create batches as an array, and then use <code>forEach</code> on each slice/batch</li>\n<li><code>const doc = getDocFromPath(key);</code> <- where does <code>key</code> come from, an evil global?</li>\n</ul>\n<p>I personally would be mildly evil by adjusting the Array prototype so that I can keep chaining, FP style;</p>\n<pre><code>Array.prototype.mapSlice = function arrrayMapSlice(n){\n //Just return `this` if we get a non-sensical parameter\n if(isNaN(n) || n <= 0){\n return this;\n }\n let start = 0, out = [];\n while(start < this.length){\n out.push(this.slice(start, start+=n));\n }\n return out;\n} \n\nasync function runBatches(list, f, batchSize){\n batchSize = batchSize || 500;\n list.mapSlice(batchSize).forEach(batch => {\n const firestoreBatch = this.firestore.batch();\n batch.forEach(document => f(document, firestoreBatch ));\n });\n await batch.commit();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:19:19.547",
"Id": "486084",
"Score": "0",
"body": "Thanks for the feedback. I will answer each of your points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:24:06.463",
"Id": "486086",
"Score": "0",
"body": "**1.** The DB I am using (Firebase) has a hard limit of 500 documents per write so I have to adhere to that.\n**2.** It could be a constant yeah.\n**3.** The 500 number won't change so I'm not worried about putting the number in the name.\n**4.** My linter enforces incrementing via `+=1` rather than `++`. Check the \"no-plusplus\" rule.\n**5.** I do actually exit the function when the index exceeds the max; I just removed the code to make the example more succinct. Good spot though ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:25:52.180",
"Id": "486087",
"Score": "0",
"body": "**6.** Why would I *not* want to make the function async? I don't want the code to proceed until the write has completed.\n**7.** Yeah, using slice() probably is better.\n**8.** That's another mistake from me shortening the code for readability. I've updated the question to fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:27:13.383",
"Id": "486088",
"Score": "0",
"body": "This is good feedback; I am also looking for advice regarding the overall approach. This is the first time I have used higher order / FP in real-world usage and I still think there's room for improvement; I just can't put my finger on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T06:45:59.247",
"Id": "486110",
"Score": "0",
"body": "I was trying to say that you have to declare runFunctionInBatchesOf500 as `async`, you don't do that, so the code probably wont run right"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:45:37.183",
"Id": "486120",
"Score": "1",
"body": "Last comment since comments should not be a chat, but please post the actual code next time, dont simplify it for CodeReview, it is against the rules of CodeReview."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T14:59:09.830",
"Id": "248192",
"ParentId": "248190",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248192",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T14:35:52.413",
"Id": "248190",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"functional-programming"
],
"Title": "Converting duplicate JS code into a higher order function"
}
|
248190
|
<p>I was looking for a solution for a way to easily merge maps of serialized Yaml and came up with this.</p>
<p>Reference to a similar question (not asked by me):</p>
<p><a href="https://stackoverflow.com/questions/25773567/recursive-merge-of-n-level-maps">https://stackoverflow.com/questions/25773567/recursive-merge-of-n-level-maps</a></p>
<p>Here is my take on how to handle this.</p>
<p>MapUtil.java:</p>
<pre><code>import java.util.*;
static class MapUtil {
public static <K> Map<K, Object> merge(
Map<K, Object> l,
Map<K, Object> r)
{
for (K key : r.keySet()) {
Object lValue = l.get(key);
Object rValue = r.get(key);
if (lValue instanceof Map && rValue instanceof Map) {
Map<K, Object> lMap = (Map<K, Object>)lValue;
Map<K, Object> rMap = (Map<K, Object>)rValue;
l.put(key, merge(lMap, rMap));
continue;
}
if (lValue instanceof List || rValue instanceof List) {
if (lValue == null) {
l.put(key, rValue);
continue;
}
List<Object> lList = (List<Object>)lValue;
List<Object> rList = (List<Object>)rValue;
if (rList != null)
lList.addAll(rList);
continue;
}
if (rValue != null)
l.put(key, rValue);
}
return l;
}
}
</code></pre>
<p>Full code with basic example.</p>
<p>Run.java:</p>
<pre><code>import java.util.*;
public class Run {
public static Map<String, Object> referenceObject() {
Map<String, Object> object = new TreeMap<>();
Map<String, Object> properties = new TreeMap<>();
List<Object> frames = new LinkedList<>();
Map<String, Object> color = new TreeMap<>();
color.put("red", 0);
color.put("green", 0);
color.put("blue", 0);
properties.put("frames", frames);
properties.put("color", color);
object.put("properties", properties);
// {properties={color={blue=0, green=0, red=0}, position={x=0, y=0, z=0}}}
return object;
}
public static Map<String, Object> mixColor(
Integer red,
Integer green,
Integer blue)
{
Map<String, Object> object = new TreeMap<>();
Map<String, Object> properties = new TreeMap<>();
Map<String, Object> color = new TreeMap<>();
if (red != null)
color.put("red", red);
if (green != null)
color.put("green", green);
if (blue != null)
color.put("blue", blue);
properties.put("color", color);
object.put("properties", properties);
// {properties={color={red=?, green=?, blue=?}}}
return object;
}
public static Map<String, Object> addFramePosition(
Integer x,
Integer y,
Integer z)
{
Map<String, Object> object = new TreeMap<>();
Map<String, Object> properties = new TreeMap<>();
Map<String, Object> position = new TreeMap<>();
List<Object> frames = new LinkedList<>();
if (x != null)
position.put("x", x);
if (y != null)
position.put("y", y);
if (z != null)
position.put("z", z);
frames.add(position);
properties.put("frames", frames);
object.put("properties", properties);
// {properties={position={x=?, y=?, z=?}}}
return object;
}
public static void main(
String[] args)
{
Map<String, Object> object = referenceObject();
// Mix color red
MapUtil.merge(object, mixColor(1, 0, 0));
// Move object along x by 1
MapUtil.merge(object, addFramePosition(1, null, null));
// Move object along y by 2
MapUtil.merge(object, addFramePosition(null, 2, null));
// Move object along z by 3
MapUtil.merge(object, addFramePosition(null, null, 3));
// {properties={color={blue=0, green=0, red=1}, frames=[{x=1}, {y=2}, {z=3}]}}
System.out.println(object);
}
}
</code></pre>
<p>The example code creates a reference object which is then given color and a set of animation frames as a list.</p>
<hr />
<p><strong>UPDATE</strong></p>
<p>I was experimenting with this and found an interesting use case. Because each change is an additive, all changes can be logged and "played back" in sequence to reconstruct its creation. With some added effort, it would be possible to instead store each change as a delta, which would allow the log to be played back in reverse as well.</p>
<p>Full example</p>
<pre><code>import java.util.*;
public class Run {
public static class RawSceneObject extends TreeMap<String, Object> {
RawProperties properties = new RawProperties();
RawFrame frames = new RawFrame();
RawColor color = new RawColor();
private static final long serialVersionUID = 2643930719380807841L;
public static class RawProperties extends TreeMap<String, Object> {
private static final long serialVersionUID = 3107728026858104788L;
}
public static class RawPosition extends TreeMap<String, Object> {
private static final long serialVersionUID = 6707504298543339821L;
}
public static class RawColor extends TreeMap<String, Object> {
private static final long serialVersionUID = 8412996397177357214L;
}
public static class RawFrame extends LinkedList<Object> {
private static final long serialVersionUID = 8978167775407603695L;
}
public static RawSceneObject mixColor(
Integer red,
Integer green,
Integer blue)
{
RawSceneObject object = new RawSceneObject();
RawProperties properties = new RawProperties();
RawColor color = new RawColor();
if (red != null)
color.put("red", red);
if (green != null)
color.put("green", green);
if (blue != null)
color.put("blue", blue);
properties.put("color", color);
object.put("properties", properties);
// {properties={color={red=?, green=?, blue=?}}}
return object;
}
public static RawSceneObject addFramePosition(
Integer x,
Integer y,
Integer z)
{
RawSceneObject object = new RawSceneObject();
RawProperties properties = new RawProperties();
RawPosition position = new RawPosition();
RawFrame frames = new RawFrame();
if (x != null)
position.put("x", x);
if (y != null)
position.put("y", y);
if (z != null)
position.put("z", z);
frames.add(position);
properties.put("frames", frames);
object.put("properties", properties);
// {properties={position={x=?, y=?, z=?}}}
return object;
}
public RawSceneObject() {
color.put("red", 0);
color.put("green", 0);
color.put("blue", 0);
properties.put("frames", frames);
properties.put("color", color);
put("properties", properties);
// {properties={color={blue=0, green=0, red=0}, position={x=0, y=0, z=0}}}
}
}
public static class SceneObject {
RawSceneObject object = new RawSceneObject();
List<RawSceneObject> log = new LinkedList<>();
public void mixColor(
Integer red,
Integer green,
Integer blue)
{
RawSceneObject raw = RawSceneObject.mixColor(red, green, blue);
log.add(raw);
MapUtil.merge(object, raw);
}
public void addFramePosition(
Integer x,
Integer y,
Integer z)
{
RawSceneObject raw = RawSceneObject.addFramePosition(x, y, z);
log.add(raw);
MapUtil.merge(object, raw);
}
public void replayLog() {
System.out.println(" : " + new RawSceneObject());
for (RawSceneObject raw : log)
System.out.println(" + " + raw);
System.out.println(" = " + this);
}
public String toString() {
return object.toString();
}
}
public static void main(
String[] args)
{
SceneObject object = new SceneObject();
// Mix color red
object.mixColor(1, null, null);
// Move object along x by 1
object.addFramePosition(1, null, null);
// Move object along y by 2
object.addFramePosition(null, 2, null);
// Move object along z by 3
object.addFramePosition(null, null, 3);
System.out.printf("Replaying log for... [%s]\n",
object.getClass().getName());
object.replayLog();
}
}
</code></pre>
<p>The output is:</p>
<pre><code>Replaying log for... [package.Run$SceneObject]
: {properties={color={blue=0, green=0, red=0}, frames=[]}}
+ {properties={color={red=1}}}
+ {properties={frames=[{x=1}]}}
+ {properties={frames=[{y=2}]}}
+ {properties={frames=[{z=3}]}}
= {properties={color={blue=0, green=0, red=1}, frames=[{x=1}, {y=2}, {z=3}]}}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, very nice code I have to say, well written.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static <K> Map<K, Object> merge(\n Map<K, Object> l,\n Map<K, Object> r)\n{\n</code></pre>\n<p>I'd use more descriptive names, like <code>base</code> and <code>addition</code> or something like that. I'm just a little bit tired right now, sorry, to come up with better names. What you want the names to convey is "this is the base, and this one will override values in base".</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (lValue instanceof Map && rValue instanceof Map) {\n Map<K, Object> lMap = (Map<K, Object>)lValue;\n Map<K, Object> rMap = (Map<K, Object>)rValue;\n \n l.put(key, merge(lMap, rMap));\n \n continue;\n }\n \n if (lValue instanceof List || rValue instanceof List) {\n</code></pre>\n<p>I'd use <code>else if</code> instead of <code>continue</code>, would make it much easier to read.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if (lValue instanceof Map && rValue instanceof Map) {\n</code></pre>\n<p><code>instanceof</code> will throw a <code>NullPointerException</code> if the given object is <code>null</code>, so you want to check that first.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static <K> Map<K, Object> merge(\n Map<K, Object> l,\n Map<K, Object> r)\n {\n // ...\n return l;\n }\n</code></pre>\n<p>This is confusing. Either manipulate the given object, or return a copy of it, and make sure that you make the behavior clear in the documentation.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> List<Object> lList = (List<Object>)lValue;\n List<Object> rList = (List<Object>)rValue;\n \n if (rList != null)\n lList.addAll(rList);\n</code></pre>\n<p>You're manipulating the <code>List</code> instance, which might or might not be desired from the callers point of view.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T19:50:18.510",
"Id": "248334",
"ParentId": "248193",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:19:56.220",
"Id": "248193",
"Score": "5",
"Tags": [
"java",
"hash-map",
"yaml"
],
"Title": "Recursively merge n-level maps of values and lists"
}
|
248193
|
<p>I want to get my code cleanner and more efficient. This code gets variables form a PHP file and filters it to show the selected user name, all available usergroups on a list box and the groups he is currently into in another.</p>
<pre><code><script>
function saveGroup(type,id){
$('#useridgr').attr('placeholder', '').val('');
$("#usernamegr").attr('placeholder', 'Nome').val('');
$('#list_box').html('');
$('#list_box_ini').html('');
if (type == 1){
} else {
loadatagroup(id);
}
}
var loadatagroup = (uid) => {
$.ajax({
type: 'GET',
url: 'usergrupo/' + uid,
data: {'_token': $("input[name='_token']").val()},
success: function(data){
console.log("success");
var o = data[0];
$('#useridgr').attr('placeholder',o.id).val(o.id);
$("#usernamegr").attr('placeholder',o.name).val(o.name);
console.log('areaa');
var size = Object.size(data);
console.log(size);
for (var i=0; i<size; i++){
var o = data[i];
$("#list_box").append("<option value='"+o.idgrupo+"'>"+o.nome+"</option>");
}
}
})
}
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
</script>
</code></pre>
|
[] |
[
{
"body": "<p>Since you are using jquery, you can use its built in <code>each</code> function to loop through the <code>json</code> results, which will eliminate the need for the size function.</p>\n<p><strong>i = index, v = values</strong></p>\n<pre><code>$.each(data,function(i,v){\n $("#list_box").append("<option value='"+v.idgrupo+"'>"+v.nome+"</option>");\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:16:00.313",
"Id": "248211",
"ParentId": "248194",
"Score": "1"
}
},
{
"body": "<p>.Naming variables / constants properly would make your code more readable</p>\n<pre><code>var o = data[0];\n// becomes\nconst firstuser = data[0];\n</code></pre>\n<p>Magic numbers should be converted into named constants.</p>\n<pre><code>if (type == 1){\n \n \n} else {\n loadatagroup(id);\n}\n// becomes\nif (type!==TYPE_DONT_LOAD) loaddatagroup(id);\n</code></pre>\n<p>You mentioned efficiency. You're querying the DOM a lot. Since presumably none of these elements get removed, you can simply hold a reference to them for later.</p>\n<pre><code>const userIdText = document.getElementById('userIdText');\nconst userNameText = document.getElementById('userIdText');\nconst listBox = document.getElementById('list-box');\n</code></pre>\n<p>The entire <code>Object.size</code> polyfill is unecessary, as you just end up iterating over an array.</p>\n<p>The AJAX call requires you to use a callback function. ES6 Javascript provides a nicer alternative to this in the form of <code>async/await</code> and <code>fetch()</code>.</p>\n<pre><code>const userIdText = document.getElementById('userIdText');\nconst userNameText = document.getElementById('userIdText');\nconst listBox = document.getElementById('list-box');\n\nfunction createGroupOption(usergroup) {\n const option = document.createElement('option');\n option.value = usergroup.idgrupo;\n option.innerText = usergroup.name;\n return option;\n}\n\nfunction updateDisplay(usergroups) {\n const firstuser = usergroups[0] || {id:'',name:'Nome'};\n userIdText.value = firstuser.id;\n userNameText.value = firstuser.name;\n\n listBox.innerHTML='';\n const options = usergroups.map(createGroupOption);\n options.forEach(option=>{\n listBox.appendChild(option)\n });\n}\n\nconst TYPE_DONT_LOAD = 1;\nfunction saveGroup(type,uid) {\n updateDisplay([]);\n if (type!==TYPE_DONT_LOAD)\n loadGroup(uid);\n}\n\nasync function loadGroup(uid) {\n const token = $("input[name='_token']").val()\n const response = await fetch(`userGrupo/${uid}?_token=${token}`);\n const usergroups = await response.json();\n\n updateDisplay(usergroups);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:44:31.363",
"Id": "248213",
"ParentId": "248194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248211",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:26:24.470",
"Id": "248194",
"Score": "4",
"Tags": [
"javascript",
"ajax",
"laravel"
],
"Title": "Filtering from a file to show information"
}
|
248194
|
<p>I work as a front-end developer, mostly with Typescript.</p>
<p>But now i decided to learn Elm as well, more out of curiosity than for any practical reason.</p>
<p>My first program is a Connect 4 game, and in the code below i have implemented the following:</p>
<ul>
<li>Initialize a 7x6 grid of numbers (7 columns, 6 rows)</li>
<li>In the grid, 0s represent empty cells, 1s represent red tokens and 2s represent yellow tokens</li>
<li>Render it as a bunch of HTML divs</li>
<li>When a user clicks on a cell, a token is dropped into the corresponding column (on the next click a different color token is dropped)</li>
<li>When a column is full of tokens, no more tokens can be dropped into it</li>
</ul>
<p>There is much more to do before this becomes a practical game, but i decided to pause at this point and ask for tips on what i could improve in the code i have written so far. Hopefully somebody on here knows Elm :)</p>
<pre><code>module Main exposing (Model, Msg(..), init, main, update, view)
import Array exposing (Array)
import Browser
import Html exposing (Attribute, Html, div, node)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ field : Array (Array Int)
, nextToken : Int
}
init : Model
init =
{ field = Array.initialize 6 (always emptyRow), nextToken = 1 }
emptyRow : Array Int
emptyRow =
Array.initialize 7 (always 0)
-- UPDATE
type Msg
= ColumnClick Int
update : Msg -> Model -> Model
update msg model =
case msg of
ColumnClick columnIndex ->
{ model
| nextToken = 3 - model.nextToken
, field = throwToken model.nextToken columnIndex model.field
}
throwToken : Int -> Int -> Array (Array Int) -> Array (Array Int)
throwToken tokenType columnIndex field =
if getLowestFreeCell columnIndex field /= Nothing then
updateCell columnIndex (Maybe.withDefault 0 (getLowestFreeCell columnIndex field)) tokenType field
else
field
getLowestFreeCell : Int -> Array (Array Int) -> Maybe Int
getLowestFreeCell columnIndex field =
getLowestFreeCellAboveX columnIndex field 5
getLowestFreeCellAboveX : Int -> Array (Array Int) -> Int -> Maybe Int
getLowestFreeCellAboveX columnIndex field maxIndex =
if maxIndex < 0 then
Nothing
else if getCellValue columnIndex maxIndex field == 0 then
Just maxIndex
else
getLowestFreeCellAboveX columnIndex field (maxIndex - 1)
getCellValue : Int -> Int -> Array (Array Int) -> Int
getCellValue columnIndex rowIndex field =
Maybe.withDefault 0 (Array.get columnIndex (getRow rowIndex field))
updateCell : Int -> Int -> Int -> Array (Array Int) -> Array (Array Int)
updateCell columnIndex rowIndex newValue field =
updateRow rowIndex (Array.set columnIndex newValue) field
updateRow : Int -> (Array Int -> Array Int) -> Array (Array Int) -> Array (Array Int)
updateRow rowIndex updateFunction field =
Array.set rowIndex (updateFunction (getRow rowIndex field)) field
getRow : Int -> Array (Array Int) -> Array Int
getRow rowIndex field =
Maybe.withDefault emptyRow (Array.get rowIndex field)
-- VIEW
css path =
node "link" [ rel "stylesheet", href path ] []
gridView : Array (Array Int) -> Html Msg
gridView grid =
div [ class "connect_4__grid" ] (Array.toList (Array.map (\row -> rowView row) grid))
rowView : Array Int -> Html Msg
rowView row =
div [ class "connect_4__row" ] (Array.toList (Array.indexedMap (\i cellValue -> cellView i cellValue) row))
cellView : Int -> Int -> Html Msg
cellView index cellValue =
div (List.concat [ cellClass cellValue, [ onClick (ColumnClick index) ] ]) []
cellClass : Int -> List (Attribute Msg)
cellClass cellValue =
[ class "connect_4__cell", class (String.concat [ "connect_4__cell--value_", String.fromInt cellValue ]) ]
view : Model -> Html Msg
view model =
div []
[ css "css/styles.css"
, div
[ class "connect_4__grid_container" ]
[ gridView model.field
]
]
</code></pre>
<p>Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T16:25:59.267",
"Id": "248198",
"Score": "3",
"Tags": [
"elm"
],
"Title": "Elm: Connect 4 game"
}
|
248198
|
<p>(Also, see the <a href="https://codereview.stackexchange.com/questions/248274/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names-fo">next iteration</a>.)</p>
<p>I have this small program for terminating processes via their respective process image names (<code>.exe</code> files):</p>
<pre><code>#include <stdio.h>
#include <windows.h>
#include <TlHelp32.h>
int main(int argc, char* argv[]) {
if (argc != 2) {
puts("processkiller.exe PROCESS_NAME");
return EXIT_SUCCESS;
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE) {
while (Process32Next(snapshot, &entry) == TRUE) {
if (strcmp(entry.szExeFile, argv[1]) == 0) {
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,
FALSE,
entry.th32ProcessID);
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return EXIT_SUCCESS;
}
</code></pre>
<p>Note that you need to run <code>processkiller.exe</code> in administrator mode in order to actually terminate the requested processes.</p>
<p><strong>Critique request</strong></p>
<p>Please tell me anything that comes to mind.</p>
|
[] |
[
{
"body": "<p>There is a subtle bug:</p>\n<pre><code>Process32First(snapshot, &entry)\n</code></pre>\n<p>already fills <code>entry</code> with the information about the first process in the snapshot. Your code misses that entry because <code>Process32Next()</code> is called immediately. The loop structure should be</p>\n<pre><code>if (Process32First(snapshot, &entry) == TRUE) {\n do {\n // ... do something with `entry`...\n \n } while (Process32Next(snapshot, &entry) == TRUE);\n}\n</code></pre>\n<p>instead. Other things that come into my mind:</p>\n<ul>\n<li>If the program is called with the wrong number of arguments then the error/usage message should be printed to the <em>standard error</em> and the program should terminate with a <em>non-zero</em> exit code, e.g. <code>EXIT_FAILURE</code>.</li>\n<li>The return value of <code>CreateToolhelp32Snapshot()</code> is not checked.</li>\n<li><code>PROCESS_ALL_ACCESS</code> is not needed in the call to <code>OpenProcess</code>, only <code>PROCESS_TERMINATE</code>.</li>\n<li>The return values of <code>OpenProcess()</code> and <code>TerminateProcess()</code> are not checked. I would expect a diagnostic message if they fail. In particular, <code>TerminateProcess()</code> and <code>CloseHandle()</code> should only be called if <code>OpenProcess()</code> succeeded.</li>\n<li>It may be a matter of taste, but <code>== TRUE</code> can be omitted when checking a boolean condition.</li>\n<li>As a user of this tool I would expect some feedback to see if a matching process was found, and how many processes were killed.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:00:20.377",
"Id": "486117",
"Score": "0",
"body": "Thanks for debugging the loop! Nice answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T19:37:24.693",
"Id": "248208",
"ParentId": "248203",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248208",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:16:22.470",
"Id": "248203",
"Score": "5",
"Tags": [
"c",
"windows",
"winapi"
],
"Title": "A simple C WinAPI program for terminating processes via process image names"
}
|
248203
|
<p>I'm a beginner at C.
I'm currently implementing atof to build a raytracer, however I'm still learning how to efficiently write programs.</p>
<h1>Assignement</h1>
<h2>Instructions</h2>
<p>The program takes a scene description file as argument to generate objects. Some of these paramaters are float. Example of the file.</p>
<p><a href="https://i.stack.imgur.com/AD3xs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AD3xs.png" alt="Scene Description file" /></a></p>
<p>I'm parsing through the file. As I'm restricted in terms of lines allowed per function and I'm currently learning how double pointers work, I'm using a double char pointer. Example of one such function using <code>lc_atof</code>.</p>
<pre class="lang-c prettyprint-override"><code>int a_parsing(char *str, t_pars *data)
{
if (*(str++) == 'A')
{
if (((data->a_ratio = lc_atof(&str)) >= 0.0) && data->a_ratio <= 1.0 && errno == 0)
//
if (((data->a_R = lc_atoi(&str)) >= 0) && data->a_R <= 255 && errno == 0)
if (*(str++) = ',' && ((data->a_G = lc_atoi(&str)) >= 0) && data->a_G <= 255 && errno == 0)
if (*(str++) = ',' && ((data->a_B = lc_atoi(&str)) >= 0) && data->a_B <= 255 && errno == 0)
return (skip_space(&str));
}
return (0);
}
</code></pre>
<h2>Current code to review:</h2>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <float.h>
static float conversion(char **str)
{
double d_nbr;
double power;
d_nbr = 0.0;
power = 10.0;
while (isdigit(**str))
{
d_nbr = d_nbr * 10.0 + (**str - 48);
if (d_nbr > FLT_MAX)
{
errno = EIO;
return (-1);
}
(*str)++;
}
if (**str == '.')
{
(*str)++;
if (isdigit(**str))
{
d_nbr = d_nbr * 10.0 + (**str - 48);
if (d_nbr > FLT_MAX)
{
errno = EIO;
return (-1);
}
(*str)++;
return ((float)(d_nbr / power));
}
}
errno = EIO;
return (-1);
}
float lc_atof(char **str)
{
float n;
int sign;
n = 0.0;
sign = 1.0;
if (!str || !*str)
{
errno = EIO;
return (-1);
}
while (isspace(**str))
(*str)++;
if (**str == '+' || **str == '-')
{
if (**str == '-')
sign = -1.0;
(*str)++;
}
if (!isdigit(**str))
{
errno = EIO;
return (-1);
}
if ((n = conversion(str)) == 0 && errno != 0)
return (-1);
return (sign * n);
}
</code></pre>
<p>The only tweaks to the actual atof I've made is having a double char pointer as argument and returning -1 in case of errors.</p>
<p>Every input much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T18:12:33.377",
"Id": "486063",
"Score": "2",
"body": "You only process a single digit after the dot. Is it intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T18:18:10.570",
"Id": "486065",
"Score": "0",
"body": "@vnp Yes it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:54:42.980",
"Id": "486123",
"Score": "1",
"body": "Related: [\\`atof\\` implementation](https://codereview.stackexchange.com/q/119986)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T16:58:59.137",
"Id": "486163",
"Score": "1",
"body": "Perhaps you could explain why you're writing your own scanner, instead of using the facilities already provided by e.g. scanf, or doing the scanner in (f)lex?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:10:36.120",
"Id": "486167",
"Score": "0",
"body": "@jamesqf One of the side goals of my assignement is to learn how library functions work by retyping them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T04:34:50.930",
"Id": "486202",
"Score": "0",
"body": "@lcols19: Writing your own implementations is good practice, of course, but I would not be surprised if atof or the scanf functions weren't actually implemented as finite state machines, such as would be generated by flex, since they're often much more efficient than straightforward coding. I haven't looked at the source, though."
}
] |
[
{
"body": "<h2>Portability</h2>\n<p>There is no guarantee that this code will be using ASCII so it would be better to use <code>'0'</code> rather than <code>48</code> which is something of a magic number. Using <code>'0'</code> makes it more readable and easier to understand.</p>\n<h2><code>lc_atof</code> Doesn't Handle String Termination or End Of Line Correctly</h2>\n<p>This code doesn't handle a NULL terminated string or an end of line character. The function <code>isspace()</code> returns <code>true</code> for end of line so the code will walk right past it.</p>\n<pre><code> while (isspace(**str))\n (*str)++;\n if (**str == '+' || **str == '-')\n {\n if (**str == '-')\n sign = -1.0;\n (*str)++;\n }\n if (!isdigit(**str))\n {\n errno = EIO;\n return (-1);\n }\n</code></pre>\n<h2>Complexity</h2>\n<p>I reaize that you didn't ask for this to be review, but the complexity of each <code>if</code> statement in the example call function is too much and caused me to make an error in my review previously:</p>\n<pre><code>int a_parsing(char* str, t_pars* data)\n{\n if (*(str++) == 'A')\n {\n if (((data->a_ratio = lc_atof(&str)) >= 0.0) && data->a_ratio <= 1.0 && errno == 0)\n // \n if (((data->a_R = lc_atoi(&str)) >= 0) && data->a_R <= 255 && errno == 0)\n if (*(str++) = ',' && ((data->a_G = lc_atoi(&str)) >= 0) && data->a_G <= 255 && errno == 0)\n if (*(str++) = ',' && ((data->a_B = lc_atoi(&str)) >= 0) && data->a_B <= 255 && errno == 0)\n return (skip_space(&str));\n }\n return (0);\n}\n</code></pre>\n<p>I would rewrite the code as :</p>\n<pre><code>#define MAX_COLOR 0xFF\nint a_parsing_prime(char* str, t_pars* data)\n{\n if (*(str++) == 'A')\n {\n data->a_ratio = lc_atof(&str);\n if (!errno && data->a_R <= MAX_COLOR)\n {\n if (*(str++) = ',')\n {\n data->a_G = lc_atoi(&str);\n if (!errno && data->a_G <= MAX_COLOR)\n {\n if (*(str++) = ',')\n {\n data->a_B = lc_atoi(&str);\n if (!errno && data->a_B <= MAX_COLOR)\n {\n return (skip_space(&str));\n }\n }\n }\n }\n }\n }\n return (0);\n}\n</code></pre>\n<p>which truely shows the complexity of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:58:03.757",
"Id": "486125",
"Score": "3",
"body": "NULL is a pointer constant. Perhaps you meant ASCII NUL (`'\\0'`) as the string terminator? IMO it's clearer to just say 0-terminated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:06:58.457",
"Id": "486144",
"Score": "1",
"body": "@PeterCordes I'm don't think it's any less clear, or rarely used; I see null-terminated everywhere in the context of strings/ string_views: https://www.bing.com/search?q=null-terminated+site:cppreference.com&form=APMCS1&PC=APMC"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:45:14.833",
"Id": "486146",
"Score": "0",
"body": "Why adopt this style instead of early returns? Something like this: https://pastebin.com/997kVR4Q? The function stops looking so complex and is easier to understand and maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T15:03:36.930",
"Id": "486149",
"Score": "1",
"body": "@IsmaelMiguel That's really a question for the OP and not for me. I kept their logic intact as much as I could."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:17:01.660",
"Id": "486170",
"Score": "0",
"body": "I'm limited in terms of number of lines (25) a function is allowed to have. `a_parsing` is actually the shortest function I have. I understand it is not easy to read and will split it into several functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T18:55:39.583",
"Id": "486177",
"Score": "2",
"body": "@anki: Ok, \"clearer\" isn't the real reason. Being technically accurate without having to use the obscure term \"NUL\" is the reason. The fact that \"null-terminated\" is widely mis-used for strings (rather than pointer-based data structures like linked lists) doesn't mean you should, too. (Unlike natural language which does evolve new meanings and usage, technical language should be kept pure for maximum clarity.)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T18:38:49.403",
"Id": "248206",
"ParentId": "248205",
"Score": "10"
}
},
{
"body": "<ul>\n<li><p>Choosing <code>EIO</code> for error reporting is very dubious. <code>lc_atof</code> doesn't do any input or output; why should it report IO error? If the return type cannot represent the result (e.g. <code>d_nbr > FLT_MAX</code>), a logical choice is <code>ERANGE</code> or <code>EOVERFLOW</code>. If the conversion cannot complete because of the malformed argument (e.g. <code>!isdigit(**str)</code>), the logical choice would perhaps be <code>EINVAL</code>.</p>\n<p>That said, I do not endorse setting <code>errno</code> in the library function. A long standing tradition is to set <code>errno</code> in system calls only. I know that this tradition is more and more violated these days, but still. If you have other means of error reporting, stick with them.</p>\n</li>\n<li><p>Using inout parameter (<code>str</code> in your case) is not advisable. It unnecessarily complicates the code, both on the caller side and the callee side. The callee is forced to use extra indirection too many times, and to worry about parenthesizing <code>(**str)++</code>. In turn, the caller loses track on where the parsable began (say, it needs to log the malformed number). Look how <code>strtof</code> handles this:</p>\n<pre><code> float strtof(const char *restrict nptr, char **restrict endptr);\n</code></pre>\n<p>Here <code>nptr</code> is an in-only, and <code>endptr</code> is out-only.</p>\n</li>\n<li><p>I am surprised that you decided to limit the utility of the function by handling only one digit after the decimal dot. It is not a big effort to handle all of them, and the benefits are much greater.</p>\n</li>\n<li><p>There is no need to parenthesize the return value. <code>return</code> is an operator, not a function.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:47:56.710",
"Id": "486121",
"Score": "1",
"body": "*It is not a big effort to handle all of them* That's an overstatement, unless you just mean naive best-effort without actually getting the nearest `float` for every decimal string input. Real-world `atof` implementations typically use big-integer extended precision to handle integer and fractional parts. e.g. the MUSL libc implementation https://git.musl-libc.org/cgit/musl/tree/src/internal/floatscan.c?id=v1.1.20#n66 is ([according to the author](https://stackoverflow.com/questions/52391330/create-a-precise-atof-implementation-in-c#comment91728246_52391330)) pretty dense but self-contained."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:52:44.130",
"Id": "486122",
"Score": "0",
"body": "Eric Postpischil has an answer on an (unfortunately deleted) SO question with discussion and example code. https://stackoverflow.com/questions/51301315/what-is-the-proper-way-to-handle-ieee-754-string-to-float-rounding/51304463#51304463 Needs some more votes to undelete the question. It points out the potential difficulties with integer overflow of the integer part, and that you potentially need all the decimal digits for rounding decisions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:56:58.580",
"Id": "486124",
"Score": "0",
"body": "Whole articles have been written on accurately implementing `strtod`, such as https://www.exploringbinary.com/how-strtod-works-and-sometimes-doesnt/ about David Gay's widely-used implementation, vs. GLIBC's pure-integer version https://www.exploringbinary.com/how-glibc-strtod-works/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T23:19:38.877",
"Id": "248214",
"ParentId": "248205",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "248206",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T17:46:07.550",
"Id": "248205",
"Score": "9",
"Tags": [
"performance",
"beginner",
"c",
"reinventing-the-wheel",
"homework"
],
"Title": "C Implementation of atof"
}
|
248205
|
<p>I saw a guy who fit snake in a qr code and I wanted to do the same thing but with minesweeper. The maximum amount of data a qr code can hold is 3kb. My c program, without any compiler magic, takes up 58kb.</p>
<p>A <em>tiny</em> bit over the limit, haha. So before I started performing alchemy with the compiler and compression programs, I was wondering if there was a couple of stuff I could do beforehand and optimize it to make the process easier. My code can be seen below:</p>
<pre><code>#include <windows.h>
#define WIDTH 100
#define HEIGHT 100
#define BOMBS 799
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
HANDLE wHnd;
HANDLE rHnd;
void SetGrid(int grid[WIDTH][HEIGHT])
{
int bomb[2] = { abs(rand() % WIDTH-1) + 1,
abs(rand() % HEIGHT-1) + 1 };
for (int i = 0; i < BOMBS; i++)
{
while (grid[bomb[0]][bomb[1]] < -1 || bomb[0] == 0 || bomb[1] == 0 || bomb[0] >= WIDTH-1 || bomb[1] >= HEIGHT-1)
{
bomb[0] = abs(rand() % WIDTH-1) + 1;
bomb[1] = abs(rand() % HEIGHT-1) + 1;
}
grid[bomb[0]][bomb[1]] = -9;
grid[bomb[0] + 1][bomb[1] + 1]++;
grid[bomb[0] + 1][bomb[1]]++;
grid[bomb[0]][bomb[1] + 1]++;
grid[bomb[0] - 1][bomb[1] + 1]++;
grid[bomb[0]][bomb[1] - 1]++;
grid[bomb[0] + 1][bomb[1] - 1]++;
grid[bomb[0] - 1][bomb[1] - 1]++;
grid[bomb[0] - 1][bomb[1]]++;
}
}
void ExpandGrid(int fullGrid[WIDTH][HEIGHT], int knownGrid[WIDTH][HEIGHT], int blankPos[2])
{
int neighbors[8][2] = {{0,1}, {1,0}, {1,1},
{0,-1}, {-1,0},
{-1,-1},{-1,1},{1,-1}};
int curTile[2];
knownGrid[blankPos[0]][blankPos[1]] = 1;
if(fullGrid[blankPos[0]][blankPos[1]] != 0) return;
for(int blck = 0; blck < 8; ++blck)
{
curTile[0] = abs(blankPos[0]+neighbors[blck][0]);
curTile[1] = abs(blankPos[1]+neighbors[blck][1]);
if(curTile[0] > WIDTH-1 || curTile[1] > HEIGHT-1) continue;
if(fullGrid[curTile[0]][curTile[1]] == 0 && knownGrid[curTile[0]][curTile[1]] == 0)
{
knownGrid[curTile[0]][curTile[1]] = 1;
ExpandGrid(fullGrid, knownGrid, curTile);
}
else if(fullGrid[curTile[0]][curTile[1]] > 0) knownGrid[curTile[0]][curTile[1]] = 1;
}
}
int main(void)
{
SMALL_RECT windowSize = { 0, 0, WIDTH - 1, HEIGHT - 1 };
COORD characterBufferSize = { WIDTH, HEIGHT };
COORD characterPosition = { 0, 0 };
SMALL_RECT consoleWriteArea = { 0, 0, WIDTH - 1, HEIGHT - 1 };
CHAR_INFO consoleBuffer[WIDTH][HEIGHT];
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
rHnd = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleTitle("Minesweeper!");
SetConsoleWindowInfo(wHnd, TRUE, &windowSize);
srand((unsigned int)time(NULL));
int startGrid[WIDTH][HEIGHT] = { 0 };
int knownGrid[WIDTH][HEIGHT] = { 0 };
SetGrid(startGrid);
int startCoord[2] = {0, 0};
int arrowPos[2] = {0, 0};
ExpandGrid(startGrid, knownGrid, startCoord);
while(1)
{
if (arrowPos[0] > WIDTH-1) arrowPos[0] = WIDTH-1;
if (arrowPos[0] < 0) arrowPos[0] = 0;
if (arrowPos[1] > HEIGHT-1) arrowPos[1] = HEIGHT-1;
if (arrowPos[1] < 0) arrowPos[1] = 0;
for (int x = 0; x < WIDTH; ++x)
{
for (int y = 0; y < HEIGHT; ++y)
{
if (knownGrid[x][y] == 1)
{
if (startGrid[x][y] > 0)
{
consoleBuffer[x][y].Char.AsciiChar = '0' + startGrid[x][y];
consoleBuffer[x][y].Attributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
}
else
{
consoleBuffer[x][y].Char.AsciiChar = 'o';
consoleBuffer[x][y].Attributes = (startGrid[x][y] < 0 ? FOREGROUND_RED : FOREGROUND_BLUE) | FOREGROUND_INTENSITY;
}
}
else
{
consoleBuffer[x][y].Char.AsciiChar = 00;
consoleBuffer[x][y].Attributes = FOREGROUND_BLUE | FOREGROUND_INTENSITY;
}
if(arrowPos[0] == x && arrowPos[1] == y)
{
consoleBuffer[x][y].Attributes = BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN;
}
}
}
WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);
switch(getch())
{
case KEY_UP:
arrowPos[0]--;
break;
case KEY_DOWN:
arrowPos[0]++;
break;
case KEY_LEFT:
arrowPos[1]--;
break;
case KEY_RIGHT:
arrowPos[1]++;
break;
case '\r':
ExpandGrid(startGrid, knownGrid, arrowPos);
break;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:47:10.517",
"Id": "486089",
"Score": "4",
"body": "Your program is probably not the problem -- it's the libraries that are getting dragged in. You might want to see if there's a way to explore what symbols link in what other symbols. Could you, for example, gain anything by using different I/O calls? Or writing your own random?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T08:57:41.350",
"Id": "494126",
"Score": "0",
"body": "If possible, you could use a different file format for your executable file, or you could even use a custom file format. In that case, it might be better to program in assembler. Maybe you could also use some cheap compression algorithm."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:16:19.603",
"Id": "248212",
"Score": "4",
"Tags": [
"performance",
"c",
"memory-optimization"
],
"Title": "Reduce size of minesweeper program to fit in qr code"
}
|
248212
|
<p>I'm looking for critiques to see what I could have done better or different ways I could approach writing a script for finding even or odd numbers. I am new to programming with JavaScript, and programming in general. This is one of the first challenges I wrote for finding even or odd numbers.</p>
<pre><code> var numList = [];
while(numList.length < 5){
numList.push(window.prompt());
}
var evenNumbers = [];
numList.forEach(function(element){
if (element % 2 === 0){
evenNumbers.push(element);
}
})
document.write(evenNumbers);
</code></pre>
|
[] |
[
{
"body": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">Array.prototype.filter</a>.</p>\n<p>You can read like this: return an array that only has the elements which satisfies the return function expression.</p>\n<p>This way, you can avoid instantiating an array and only after this iteration to make the <code>push</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>var numList = [];\nwhile(numList.length < 5){\n numList.push(window.prompt());\n}\n\nvar evenNumbers = numList.filter(function (element) {\n return element % 2 === 0\n});\n// that's the same that \n// var evenNumbers = numList.filter(element => element % 2 === 0);\n\ndocument.write(evenNumbers);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Although, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a>, that has a cleaner syntax.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T01:34:33.263",
"Id": "486492",
"Score": "0",
"body": "Thanks for the reply, I did not know about arrow functions. I will start using them to make my syntax cleaner. Array-filter fits this situation and I will most likely be using it again if I end up in a similar scenario. Reading the MDN, forEach and filter both seem similar with exception that filter creates a new array. Filter seems to be more efficient and cleaner than forEach, especially in this case scenario as it seems more effective to the task at hand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:55:44.300",
"Id": "248221",
"ParentId": "248218",
"Score": "9"
}
},
{
"body": "<h2>Different ways for finding even or odd numbers.</h2>\n<p>While the modulo operator works fine for testing if a number is even or odd, a faster technique (which I would not expect a beginner to know about) is to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND\" rel=\"nofollow noreferrer\">bitwise AND - i.e. <code>&</code></a>. Refer to <a href=\"https://blog.karlpurk.com/finding-odd-even-numbers-with-javascript-bitwise-operators/\" rel=\"nofollow noreferrer\">this article for a thorough explanation of how it works</a>.</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>function isEven(number) {\n return !(number & 1);\n}\nfor (let x = 0; x < 6; x++) {\n console.log(x, ' is even: ', isEven(x));\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h1>Other review aspects</h1>\n<h2>Filtering the array</h2>\n<p>As Lucas already mentioned <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.prototype.filter()</code></a> can be used to simplify the addition of elements into <code>evenNumbers</code>. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce()</code></a> could be used though it wouldn’t be as concise as each iteration would need to return the cumulative array, and the initial value would need to be set to an array.</p>\n<p>While you didn't ask specifically about <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a>, if you want the code to be as efficient as possible (e.g. it will be run millions (or more) times in a short amount of time, then avoid iterators - e.g. functional techniques with <code>array.filter()</code>, <code>array.map()</code>, as well as <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loops</a> - use a <code>for</code> loop.</p>\n<h2>Declaring variables</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> could be used instead of <code>var</code> to avoid accidental re-assignment for both arrays, and if the variables were inside a block, the scope would be limited to the block. Note that "It's possible to push items into the array"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Examples\" rel=\"nofollow noreferrer\">1</a></sup> even if it is declared with <code>const</code>.</p>\n<h2>Promoting user for input</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt\" rel=\"nofollow noreferrer\"><code>window.prompt()</code></a> “displays a dialog with an optional message prompting the user to input some text.”<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt\" rel=\"nofollow noreferrer\">2</a></sup>. A friendly message could be passed as the first argument to give the user information about the expected input- e.g.</p>\n<pre><code>window.prompt(“Please enter a number”);\n</code></pre>\n<p>Additionally:</p>\n<blockquote>\n<p>Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if their answer should be a Number, you should cast the value to Number.</p>\n<pre><code> const aNumber = Number(window.prompt("Type a number", ""));\n</code></pre>\n</blockquote>\n<p><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Notes\" rel=\"nofollow noreferrer\">3</a></sup></p>\n<p>So the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number</code> constructor</a> could be used to store numbers in the array.</p>\n<pre><code>numList.push(Number(window.prompt("Please enter a number")));\n</code></pre>\n<h2>Sending output with <code>document.write()</code></h2>\n<blockquote>\n<p><strong>Note</strong>: Because <code>document.write()</code> writes to the document <strong>stream</strong>, calling <code>document.write()</code> on a closed (loaded) document automatically calls document.open(), <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/document.open#Notes\" rel=\"nofollow noreferrer\">which will clear the document</a>.</p>\n</blockquote>\n<p><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/write\" rel=\"nofollow noreferrer\">4</a></sup></p>\n<p>So don’t plan on using that function on scripts that run on webpages with DOM elements existing on the page, lest they get removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T08:52:32.463",
"Id": "486116",
"Score": "1",
"body": "The bitwise suggestion is unnecessary obfuscation. It is much clearer to use the modulus operator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T10:24:29.640",
"Id": "486126",
"Score": "0",
"body": "Is the bitwise operation beneficial in terms of time consumption over modulus operator? @MartinSmith If this is true, I would say that it will be okay, since its wrapped inside a function which clearly explains whats happening by its name. But in the end I guess it comes down to personal preference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:10:10.310",
"Id": "486564",
"Score": "1",
"body": "@MartinSmith while it isn't something a beginner would be expected to be aware of (unless maybe he/she had experience with logic-based programming or low-level programming) the OP stated \"_I'm looking for critiques to see what I could have done better or **different ways I could approach writing a script for finding even or odd numbers**._\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T05:55:34.033",
"Id": "248226",
"ParentId": "248218",
"Score": "6"
}
},
{
"body": "<h1>Use the let <a href=\"https://www.w3schools.com/js/js_es6.asp\" rel=\"nofollow noreferrer\">ES6</a> instead of var</h1>\n<blockquote>\n<pre><code>var numList = [];\n</code></pre>\n</blockquote>\n<pre><code>let numList = [];\n</code></pre>\n<p>etc.</p>\n<h1>Use the filter method</h1>\n<blockquote>\n<pre><code>numList.forEach(function(element){\n if (element % 2 === 0){ \n evenNumbers.push(element);\n }\n}) \n</code></pre>\n</blockquote>\n<p>As suggested by <a href=\"https://codereview.stackexchange.com/a/248221/229477\">Lucas Wauke</a></p>\n<pre><code>let evenNumbers = numList.filter(element => element % 2 === 0);\n</code></pre>\n<h1>Tell the user what to enter in the prompt</h1>\n<blockquote>\n<pre><code>numList.push(window.prompt());\n</code></pre>\n</blockquote>\n<pre><code>numList.push(window.prompt("Please enter a whole number"));\n</code></pre>\n<h1>You should definitely work on your code style to make it better readable</h1>\n<h3>Use indents</h3>\n<blockquote>\n<pre><code>while(numList.length < 5){\nnumList.push(window.prompt());\n}\n</code></pre>\n</blockquote>\n<pre><code>while(numList.length < 5){\n numList.push(window.prompt());\n}\n</code></pre>\n<h3>Leave whitespaces before braces</h3>\n<blockquote>\n<pre><code>numList.forEach(function(element){\n if (element % 2 === 0){ \n evenNumbers.push(element);\n }\n})\n</code></pre>\n</blockquote>\n<pre><code> numList.forEach(function(element) {\n if (element % 2 === 0) { \n evenNumbers.push(element);\n }\n })\n</code></pre>\n<h3>In my opinion its way better readable if you leave a whitespace within parentheses.</h3>\n<p>I personaly dont know many people doing this but try it out maybe it works for you</p>\n<blockquote>\n<pre><code>numList.forEach(function(element){\n if (element % 2 === 0){ \n evenNumbers.push(element);\n }\n})\n</code></pre>\n</blockquote>\n<pre><code> numList.forEach( function( element ) {\n if ( element % 2 === 0 ) { \n evenNumbers.push( element );\n }\n } )\n</code></pre>\n<p>This is especially helpful when working with <strong>many</strong> parentheses ( pseudo code ):</p>\n<blockquote>\n<pre><code>method(function(method(getter())).setSomething(getSomethingFromSomewhere(somewhere)))\n</code></pre>\n</blockquote>\n<pre><code>method( function( method( getter() ) ).setSomething( getSomethingFromSomewhere( somewhere ) ) )\n</code></pre>\n<p>As you can see its pretty easy to see which parentheses belong together</p>\n<h1>Conclusion</h1>\n<p><strong>Before</strong></p>\n<blockquote>\n<pre><code>var numList = [];\nwhile(numList.length < 5){\nnumList.push(window.prompt());\n}\n\nvar evenNumbers = [];\n\nnumList.forEach(function(element){\n if (element % 2 === 0){ \n evenNumbers.push(element);\n }\n})\ndocument.write(evenNumbers); \n</code></pre>\n</blockquote>\n<p><strong>After</strong></p>\n<pre><code>let numList = [];\n\nwhile ( numList.length < 5 ) {\n numList.push( window.prompt() );\n}\n\nlet evenNumbers = numList.filter(element => element % 2 === 0);\n\ndocument.write( evenNumbers ); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:31:14.777",
"Id": "486135",
"Score": "2",
"body": "I joined this stackexchange just to upvote this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:26:06.537",
"Id": "486139",
"Score": "3",
"body": "Actually 'const' is much more preferred than 'let' in this case. 'let' is used when you want to reassign a variable to a new value, for example when using an index in a loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T07:03:37.523",
"Id": "248227",
"ParentId": "248218",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T00:28:37.970",
"Id": "248218",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"array",
"functional-programming"
],
"Title": "Finding even or odd numbers"
}
|
248218
|
<p>I am looking for any feedback for this first script I have written. It is a mix of openpyxl and pandas, where it takes employee times from different Excel workbooks, then creates a weekly sheet for each person in a new workbook, and fills in the individual sheets.</p>
<p>Somewhere else that I had asked about this code suggested it should be written using classes instead to organize it better. Would it make it "cleaner" in the areas with the if/else statements or how would it be written that way? In this iteration of the code, the date and folder location is inputted by a separate GUI that I am working on using Tkinter.</p>
<pre><code># Imports
import pandas as pd
import os
from pathlib import Path
import glob
import xlrd
import openpyxl
import pprint
import datetime
import threading
import time
from employee_data_base import employee_db as db
from openpyxl.styles import Font, Alignment
start = time.time()
# dts_folder = ('/Users/Documents/PythonExcel/DTS/')
template_loc = '/Users/Documents/PythonExcel'
template_file = 'TCBlank.xlsx'
re_rates = [{'Position': 'Condor Op', 'Code': '5431'}, {'Position': 'S/O', 'Code': '5431'}]
occ_codes = {'CLT': '5401', 'ACLT': '5403', 'LCP': '5422', 'SLT': '5451', 'Condor Op': '5431', 'S/O': '5431'}
# xlsx_files = [path for path in Path(dts_folder).rglob('*.xlsx')]
# Get values from GUI
def get_data(dts_folder, selected_date):
# global end_date, file
file = dts_folder
end_date = selected_date
main(file, end_date)
# use the passed in arguments to do the work, not the hardcoded globals
# Import individual daily time sheets
def main(file, end_date):
xlsx_files = [path for path in Path(file).rglob('*.xlsx')]
col_names = ['Name', 'Position', 'Call', 'Lunch In', 'Lunch Out', 'Wrap']
cols = [1, 2, 4, 5, 7, 8]
skiprows = [0, 1, 2, 3, 21, 22, 23, 25, 25]
df = pd.DataFrame()
pd.set_option('max_r', None)
pd.set_option('display.max_columns', None)
df = pd.concat([pd.read_excel(f, usecols=cols, skiprows=skiprows, names=col_names,
header=None).assign(Date=os.path.basename(f)) for f in xlsx_files])
df['Date'] = df['Date'].str.rstrip(' Lucifer Lighting DTS.xlsx')
df = df.dropna()
# create_df_dict()
# return df
# Create dictionary from combined data frame
df_dict = df.to_dict('r')
# Create list of employee names
employee_names = sorted(list(set(df['Name'])))
for n in employee_names:
fl = n.split(" ")
first_name = fl[0]
last_name = fl[1]
lf_name = []
lf_name.append(f'{last_name}, {first_name}')
print(lf_name)
# Create workbook for weekly data
os.chdir(template_loc)
wb = openpyxl.load_workbook(template_file, data_only=True)
ws = wb.active
# Get the week ending date to fill in cell and then excel fills in the rest of the week column
template = wb['TC_Template']
print('What is the week ending date?')
# endDate = input()
# end_date = '03-07-2020'
weekEndDate = pd.date_range(end=end_date, periods=7)
# Name weekly time card file
weekly_tc = f"/Users/Desktop/Weekly_Time_Card_{end_date}.xlsx"
# Write dates to cells
template['F15'].value = weekEndDate[0].strftime('%m-%d')
template['F17'].value = weekEndDate[1].strftime('%m-%d')
template['F19'].value = weekEndDate[2].strftime('%m-%d')
template['F21'].value = weekEndDate[3].strftime('%m-%d')
template['F23'].value = weekEndDate[4].strftime('%m-%d')
template['F25'].value = weekEndDate[5].strftime('%m-%d')
template['F27'].value = weekEndDate[6].strftime('%m-%d')
template['AE6'].value = weekEndDate[6].strftime('%m-%d-%y')
print('Finished updating the template')
# Create sheets for each person from template
for copies in range(len(employee_names)):
target = wb.copy_worksheet(from_worksheet=template)
print('Copied sheets!')
# Rename the sheets based on the name of the person
sheets = wb.sheetnames
counter = 0
for sheet in sheets:
ss_sheet = wb[sheet]
ss_sheet.title = employee_names[counter - 1]
ss_sheet['B8'].value = employee_names[counter - 1]
counter += 1
wb.save(weekly_tc)
print('Sheets renamed!')
# Delete duplicate sheet
list_sheets = list(wb.sheetnames)
list_sheets_len = len(list_sheets) - 1
dup_sheet = list_sheets[list_sheets_len]
del wb[dup_sheet]
wb.save(weekly_tc)
print('Finished creating all the sheets!')
wtc_wb = openpyxl.load_workbook(weekly_tc)
# Function to match up employee weekly data and write it into the excel time card
def write_tc(emp):
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sunday = ws1['F15'].value
monday = ws1['F17'].value
tuesday = ws1['F19'].value
wednesday = ws1['F21'].value
thursday = ws1['F23'].value
friday = ws1['F25'].value
saturday = ws1['F27'].value
for d in df_dict:
if d['Name'] == name_cell and d['Date'] == sunday:
ws1['I15'].value = d['Call']
ws1['J15'].value = d['Lunch In']
ws1['K15'].value = d['Lunch Out']
ws1['O15'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == monday:
ws1['I17'].value = d['Call']
ws1['J17'].value = d['Lunch In']
ws1['K17'].value = d['Lunch Out']
ws1['O17'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == tuesday:
ws1['I19'].value = d['Call']
ws1['J19'].value = d['Lunch In']
ws1['K19'].value = d['Lunch Out']
ws1['O19'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == wednesday:
ws1['I21'].value = d['Call']
ws1['J21'].value = d['Lunch In']
ws1['K21'].value = d['Lunch Out']
ws1['O21'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == thursday:
ws1['I23'].value = d['Call']
ws1['J23'].value = d['Lunch In']
ws1['K23'].value = d['Lunch Out']
ws1['O23'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == friday:
ws1['I25'].value = d['Call']
ws1['J25'].value = d['Lunch In']
ws1['K25'].value = d['Lunch Out']
ws1['O25'].value = d['Wrap']
elif d['Name'] == f"{name_cell}" and d['Date'] == saturday:
ws1['I27'].value = d['Call']
ws1['J27'].value = d['Lunch In']
ws1['K27'].value = d['Lunch Out']
ws1['O27'].value = d['Wrap']
# print(f"Finished writing {emp}'s time card!")
# Fill in position code and last four of social
def fill_position(emp):
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sig = ws1['E45']
sig.font = Font(bold=False, name='Brush Script MT', size=36)
sig.alignment = Alignment(indent=1, horizontal='left', vertical='center')
ss_cell = ws1['O8'].value
position_cell = ws1['AM10'].value
for i in db:
if i['name'] == name_cell:
ws1['O8'].value = i['social']
ws1['AM10'].value = i['position']
sig.value = i['name']
# print(f"{emp} social and position filled in! Now filling in their times!")
def check_rerates(emp):
ws1 = wtc_wb[emp]
name_cell = ws1['B8'].value
sunday = ws1['F15'].value
monday = ws1['F17'].value
tuesday = ws1['F19'].value
wednesday = ws1['F21'].value
thursday = ws1['F23'].value
friday = ws1['F25'].value
saturday = ws1['F27'].value
position_cell = ws1['AM10'].value
for d in df_dict:
for p in re_rates:
if d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == sunday:
ws1['P15'].value = p['Position']
ws1['Q15'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Sunday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == monday:
ws1['P17'].value = p['Position']
ws1['Q17'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Monday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == tuesday:
ws1['P19'].value = p['Position']
ws1['Q19'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Tuesday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == wednesday:
ws1['P21'].value = p['Position']
ws1['Q21'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Wednesday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == thursday:
ws1['P23'].value = p['Position']
ws1['Q23'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Thursday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == friday:
ws1['P25'].value = p['Position']
ws1['Q25'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Friday.")
elif d['Position'] == p['Position'] and d['Name'] == name_cell and d['Date'] == saturday:
ws1['P27'].value = p['Position']
ws1['Q27'].value = p['Code']
print(f"{emp} was re-rated to {p['Position']} on Saturday.")
def run_program():
for emp in employee_names:
fill_position(emp)
write_tc(emp)
print(f"Finished writing {emp} time card!")
finished_cards = f'Finished writing {emp} time card!'
check_rerates(emp)
wtc_wb.save(weekly_tc)
run_program()
print('It took', time.time()-start, 'seconds.')
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>I don't see a huge benefit in adding classes here but there are other things you can do.</p>\n<p><strong>Avoid repetition 1</strong></p>\n<pre><code>template['F15'].value = weekEndDate[0].strftime('%m-%d')\ntemplate['F17'].value = weekEndDate[1].strftime('%m-%d')\ntemplate['F19'].value = weekEndDate[2].strftime('%m-%d')\ntemplate['F21'].value = weekEndDate[3].strftime('%m-%d')\ntemplate['F23'].value = weekEndDate[4].strftime('%m-%d')\ntemplate['F25'].value = weekEndDate[5].strftime('%m-%d')\ntemplate['F27'].value = weekEndDate[6].strftime('%m-%d')\n</code></pre>\n<p>Whenever you repeat a lot of code in many lines, there will be more elegant ways to write it instead.</p>\n<p>Since only the indexes change here, and the weekEndDate indexes are nicely lined up from 0 to 6, we can do:</p>\n<pre><code>date_cells = ['F15', 'F17', 'F19', 'F21', 'F23', 'F25', 'F27']\nfor index, cell in enumerate(date_cells):\n template[cell].value = weekEndDate[index].strftime('%m-%d')\n</code></pre>\n<p>You can do the same kind of changes in the other two parts of your code where you repeat the same things over and over for each weekday. Those are the major ugly parts in this code.</p>\n<p><strong>Avoid repetition 2</strong></p>\n<p>Assignments can be chained. Instead of</p>\n<pre><code>ss_sheet.title = employee_names[counter - 1]\nss_sheet['B8'].value = employee_names[counter - 1]\n</code></pre>\n<p>You can do</p>\n<pre><code>ss_sheet.title = ss_sheet['B8'].value = employee_names[counter - 1]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T13:04:42.253",
"Id": "486328",
"Score": "0",
"body": "Thank you for the advice. I was looking at the areas for each weekday and not really sure how to write it since each day is a specific cell with a letter and number? Also, is it better to do less specific functions and just do one larger function? I ran into trouble when I wanted to pass in variables from the gui or other parts and to try to avoid global variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T23:30:30.763",
"Id": "486390",
"Score": "0",
"body": "Yes, each day is a specific cell letter and number, and that's the only part of that code which changes. The other 98% is identical and repeated 7 times over, which means it can be made 7 times shorter. You need more practice with Python. Learn about dictionaries in Python. Create a dictionary mapping the weekday names to their cell ids. Then iterate over that. You could start reading here https://realpython.com/iterate-through-dictionary-python/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T23:33:56.787",
"Id": "486391",
"Score": "0",
"body": "`Also, is it better to do less specific functions and just do one larger function? I ran into trouble when I wanted to pass in variables from the gui or other parts and to try to avoid global variables.` In general, it is good to to very specific functions that are short and do one thing well. Avoid general functions with a lot of parameters. One important purpose of functions is to split up the program into small parts that are short, well defined and easy to maintain and to test. To do that, we want them short and very specific."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:50:44.847",
"Id": "248271",
"ParentId": "248222",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T01:46:58.393",
"Id": "248222",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Creating a weekly sheet for employees"
}
|
248222
|
<p>I am trying to create an application that on the front end presents the user with a text editor to input code into and then I will run that code and return the result. I thought it would be a fun project to try and build my own version of leetcode as a learning project.</p>
<p>Right now this is what I am doing to run the provided code. Let's say we are running python code, because that's all I have implemented right now.</p>
<p>First I take in the code that the user submits and create an a file that contains the given code:</p>
<pre><code>std::string python(std::string code){
std::string langCommand = "python3 ";
std::string outFile;
//I am hoping to parallelize this operation so I add threadID to output
outFile = createOutFileName("PythonRunner.py");
std::ofstream output;
output.open(outFile);
output << code;
output.close();
return langCommand + outFile;
}
</code></pre>
<p>The next thing I do is create an output file and run the previously created file but I send my stdout/stderr to another outputfile:</p>
<pre><code>std::string Program::run(){
std::string command = createFile(this->lang, this->code);
this->outputFile = createOutFileName("output.txt");
std::stringstream newCommand;
newCommand << command;
newCommand << ">> ";
newCommand << outputFile;
newCommand << " 2>&1";
system(newCommand.str().c_str());
std::string output = getOutputFileData(this->outputFile);
cleanupFiles(command);
return output;
}
</code></pre>
<p>Finally I return whatever I got from my output file and that is how I am executing my code.</p>
<p>I gotta think there is an easier way to do this. Especially since I am doing so much writing to a file and then reading from it is there anyway to get rid of that?</p>
<p>I also want to include more than one language in the future so I don't want to use any libraries that are specific to a certain language.</p>
<p>Lastly, this is my first C++ project so I would love any C++ tips!</p>
<p>Edit: I do want to eventually parallelize this code and find some way to encapsulate the program so it can't damage the system it is running on. If there is maybe some external program that would be good for that let me know and also gives me its stderr/stdout let me know.</p>
<p>Edit: As someone asked, here is the entire repo
<a href="https://github.com/lkelly93/coderunner" rel="nofollow noreferrer">https://github.com/lkelly93/coderunner</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T07:20:43.523",
"Id": "486111",
"Score": "2",
"body": "Could you add the full code, not bits and pieces, so that I can run it in my IDE ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:04:42.230",
"Id": "486132",
"Score": "0",
"body": "It's not super large but didn't want to put everything on the question here is the repo. https://github.com/lkelly93/coderunner"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:59:13.973",
"Id": "486245",
"Score": "0",
"body": "Arbitrarily running code from other people is very dangerous. Doing this properly is **exceedingly** hard."
}
] |
[
{
"body": "<p>Appreciable things:</p>\n<ul>\n<li>Documentation for implementations and sections made using comments.</li>\n<li>Classes, functions and files following <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>.</li>\n<li>Descriptive names of functions. (not variables as I note below)</li>\n<li>Testing framework! But the tests should check the inner functions too not just the whole program.</li>\n</ul>\n<hr>\n<p>The terminology of file streams and filenames is very confusing and makes me look-up function return types or variable declaration too often.</p>\n<p><code>Program::outputFile</code> is file<em>name</em> which is not clear here. I mistook it for <code>FILE*</code>.</p>\n<p>In another place, <code>std::ofstream output;</code> output sounds like the output content of the program but it's a stream!</p>\n<p><code>std::string output = getOutputFileData(this->outputFile);</code> And here it is a string again!</p>\n<hr>\n<p>The code doesn't take care of absolute and relative paths.</p>\n<p>The test fails with this:</p>\n<pre><code>runnerFiles/0x1005c05c0output.txt does not exist.\n</code></pre>\n<p>With such a code, I'd be very reluctant to use <code>rm</code>. At most, keep all the disposable files in a folder and ask user to delete it.</p>\n<hr>\n<pre><code>std::stringstream newCommand;\nnewCommand << command;\nnewCommand << ">> ";\nnewCommand << outputFile;\nnewCommand << " 2>&1";\n\nsystem(newCommand.str().c_str());\n</code></pre>\n<p><code>std::stringstream</code> can be avoided and you can use concatenate <code>std::string</code>s directly as long as the first item is a <code>std::string</code>.</p>\n<pre><code>std::string newCommand = command + ">> " + outputFile + "2>&1";\n</code></pre>\n<hr>\n<p>The code in <code>getOutputFileData</code> that uses <code>FILE*</code> and char buffer (which you didn't even allocate!) can be replaced with the following (add error handling)</p>\n<pre><code> std::ifstream run_output{outFileLocation};\n std::stringstream buffer;\n buffer << run_output.rdbuf();\n return buffer.str();\n</code></pre>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring?noredirect=1&lq=1\">https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring?noredirect=1&lq=1</a></li>\n</ul>\n<p>Since you don't need a fine control over lines, don't bother with <code>getline</code>.</p>\n<blockquote>\n<p>Prefer iostreams for I/O. iostreams are safe, flexible, and extensible.</p>\n</blockquote>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-streams\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-streams</a></li>\n</ul>\n<hr>\n<pre><code>std::ofstream output;\noutput.open(outFile);\noutput << code;\noutput.close();\n</code></pre>\n<p>Can be made shorter as</p>\n<pre><code>std::ofstream output(outFile);\noutput << code;\n</code></pre>\n<p>Don't bother with closing if not needed. When <code>output</code> goes out of scope, file will be closed by itself. It's the same reason you don't go around deleting every trivially destructible <code>std::vector</code> or array which will be cleaned up automatically.</p>\n<hr>\n<p>Use <code>const &</code> or <code>std::string_view</code> where strings are only read. They're cheap to pass around and indicate the intent that the content will not be modified.</p>\n<pre><code>std::string createFile(std::string lang, std::string code)\nstd::string getOutputFileData(std::string outFileLocation)\nbool isSupportedLanguage(std::string lang)\nvoid Program::cleanupFiles(std::string oldCommand)\n</code></pre>\n<hr>\n<pre><code>auto iter = supportedLanguages.find(lang);\n</code></pre>\n<p>C++20 will have <code>contains</code> so that saves you a few lines.</p>\n<ul>\n<li><a href=\"https://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/container/unordered_map</a></li>\n</ul>\n<hr>\n<pre><code>this->code\n</code></pre>\n<p>Instead of <code>this-></code>, consider appending or prepending <code>_</code> to the variables to indicate that they're private members.</p>\n<hr>\n<p>It's more readable IMO if implementation order follows the declaration order for functions.</p>\n<p>In <code>Program</code>, constructor can go to the top of the file, instead of the bottom.</p>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl16-use-a-conventional-class-member-declaration-order\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl16-use-a-conventional-class-member-declaration-order</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:49:11.973",
"Id": "486148",
"Score": "0",
"body": "Hi @anki I greatly appreciate your tips but they don't really answer my main question. Is there an easier way to execute foreign code in C++? That's why I only posted the two snippet of code because those are my main question. Thanks so much for the general tips though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:03:02.067",
"Id": "486246",
"Score": "0",
"body": "I bet using a stringstream is more efficient than normal string concatenation as the + operator will create a new string and two copies (to put the strings together) while streaming operator can resize the output string and append."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:41:18.190",
"Id": "486251",
"Score": "0",
"body": "@MartinYork I was trying to keep it in one line and not focus on performance. But yes it could be bad when the file output is huge. I'll still use `std::string::append` and not use `stringstream` as a glue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:56:57.010",
"Id": "248236",
"ParentId": "248224",
"Score": "1"
}
},
{
"body": "<p>Rather than <code>system()</code> you should <code>popen()</code>.</p>\n<p>The difference is that system runs the command in a sub process with no access to this processes, while popen runs the command in a sub processes <strong>but</strong> provides accesses to the input and output streams of the sub processes.</p>\n<p>This will allow you to run the sub-processes and stream input to the processes directly (from the input field you provided for standard input) and then read output from the processes and write it to the output field in your user interface.</p>\n<pre><code>FILE* proc = popen(command);\nstd::string inputFromUser = getUserInputFromUI();\n// Using fwrite() correctly left to user.\n// You need to check for errors and continue etc.\nfwrite(inputFromUser.c_str(), 1, inputFromUser.size(), proc);\n\nchar buffer[100];\nstd::size_t size;\nwhile((size = fread(buffer, 1, 100, proc)) != 0) {\n // Check for read errors here.\n sendToUserInterface(std::string(bufffer, buffer + size));\n}\n\npclose(proc);\n \n</code></pre>\n<hr />\n<p>Sorted of related you don't need to save your pythong script as a file. The python command accept the <code>-</code> as a name which means read the script from the standard input rather than from the named file.</p>\n<p>So you can run the python command (with popen()) then write the script you want to execute to the input stream of the file produced.</p>\n<p>This will remove the need for any intermediate files.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:13:04.357",
"Id": "248284",
"ParentId": "248224",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248284",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T03:35:08.967",
"Id": "248224",
"Score": "2",
"Tags": [
"c++",
"file"
],
"Title": "Execute external file from inside C++"
}
|
248224
|
<p>In order to learn web server programming in Node and JavaScript, I decided to implement a simple web server that only does one thing:</p>
<ul>
<li>Display data of the HTTP request as an HTML table.</li>
</ul>
<p>The actual data to display is arbitrary. In this example I'm displaying the contents of the header, along with the method, url, and http versions.</p>
<p>Here is the working solution:</p>
<pre><code>const http = require('http');
const port = 3344;
const htmlCSS = `
<style>
body {
font-family: sans-serif;
}
td {
border: 1px solid black;
padding: 0.5rem;
}
table {
margin: 0 auto;
}
</style>
`;
const server = http.createServer((req, res) => {
const {
headers,
method,
url
} = req;
console.log(`\n${headers['user-agent']}\n${method}\n${url}`);
console.log(new Date());
console.log();
writeResponse(req, res);
});
server.listen(port);
function writeResponse(req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
writeBody(req, res);
res.end();
}
function writeBody(req, res) {
const htmlTitle = '<title>Your Request Is</title>';
const htmlEncode = '<meta charset="UTF-8">';
const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`;
const htmlTop = `<html lang="en">${htmlHead}<body>`;
const htmlBot = '</body></html>';
res.write(htmlTop);
writeTable(req, res);
res.write(htmlBot);
}
function writeTable(req, res) {
const htmlTableTop = '<table><tbody>';
const htmlTableBot = '</tbody></table>';
res.write(htmlTableTop);
writeAllRows(req, res);
res.write(htmlTableBot);
}
function writeAllRows(req, res) {
const {
httpVersion,
httpVersionMinor,
httpVersionMajor,
headers,
method,
url
} = req;
for (const key in headers) {
writeRow(res, key, headers[key]);
}
writeRow(res, 'method', method);
writeRow(res, 'url', url);
writeRow(res, 'httpVersion', httpVersion);
writeRow(res, 'httpVersionMinor', httpVersionMinor);
writeRow(res, 'httpVersionMajor', httpVersionMajor);
}
function writeRow(res, key, val) {
const entry = `<tr><td>${key}</td><td>${val}</td></tr>`;
res.write(entry);
}
</code></pre>
<p>While I have some particular questions, I'm looking forward for all kinds of feedback! So if you see anything at all that can be improved, any comment is much appreciated!</p>
<ul>
<li>Can I use other modules to make this job easier?</li>
<li>For a job this simple, is it worth to work with HTML and CSS as separate files?</li>
<li>How are HTML and CSS normally handled inside JS files (edits, appends, etc)?</li>
<li>How well am I handling the construction of HTML and CSS?</li>
<li>Can this be done more concisely?</li>
<li>What would you do differently to improve this in any way?</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n<p>Can I use other modules to make this job easier?</p>\n</blockquote>\n<p>You can use some web framework like <a href=\"https://github.com/fastify/fastify\" rel=\"noreferrer\">fastify</a> or <a href=\"https://github.com/expressjs/express\" rel=\"noreferrer\">express</a>.\nThis would ease the code a lot</p>\n<blockquote>\n<p>For a job this simple, is it worth to work with HTML and CSS as separate files?</p>\n</blockquote>\n<p>Assumig your project will grown, it is a good approach to move some "static text" in a separated file.</p>\n<blockquote>\n<p>How are HTML and CSS normally handled inside JS files (edits, appends, etc)?</p>\n</blockquote>\n<p>You have made a server side rendering (SSR) by your hand.\nSince it would be hard to manage manually all those piece of strings and would be also dandgerous to\nsome script injection, you could use some fremework as <a href=\"https://vuejs.org/v2/guide/ssr.html\" rel=\"noreferrer\">vue</a>\nor other templating systems like <a href=\"https://handlebarsjs.com/\" rel=\"noreferrer\">handlebarsjs</a> or others - <a href=\"https://github.com/fastify/point-of-view#point-of-view\" rel=\"noreferrer\">here a list</a></p>\n<blockquote>\n<p>How well am I handling the construction of HTML and CSS?</p>\n</blockquote>\n<p>There could be some security issue for links like that if you start to process those values:</p>\n<p><code>http://localhost:3000/?user=%3Cimg%20src=%27aaa%27%20onerror=alert(1)%3E</code></p>\n<p>the framework protect you from these cases usually.</p>\n<p>This code:</p>\n<pre><code> const htmlTitle = '<title>Your Request Is</title>'\n const htmlEncode = '<meta charset="UTF-8">'\n const htmlHead = `<head>${htmlTitle}${htmlCSS}${htmlEncode}</head>`\n const htmlTop = `<html lang="en">${htmlHead}<body>`\n</code></pre>\n<p>produce every time the same output string, so you could do it once instead of every request:\nthis will stress less the nodejs garbage collector for high throughput site.</p>\n<blockquote>\n<p>Can this be done more concisely?</p>\n</blockquote>\n<p>You could write less code using some <code>Object</code> and <code>Array</code> functions:</p>\n<pre><code>function stringTemplates (request) {\n return `<html lang="en">\n<head>\n<title>Your Request Is</title>\n</head>\n<body>\n<table><tbody>\n${Object.entries(request.headers).map(processLine).join('')}\n${['httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'method', 'url'].map(prop => processLine([prop, request[prop]])).join('')}\n</tbody></table>\n</body>\n</html>\n`\n}\n\nfunction processLine ([header, value]) {\n return `<tr><td>${header}</td><td>${value}</td></tr>`\n}\n</code></pre>\n<blockquote>\n<p>What would you do differently to improve this in any way?</p>\n</blockquote>\n<p>This shows only GET, but in order to learn the HTTP standard it would useful to show in:</p>\n<ul>\n<li>query parameters</li>\n<li>form parameter (with different encoding)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:07:52.973",
"Id": "248238",
"ParentId": "248229",
"Score": "5"
}
},
{
"body": "<blockquote>\n<p>What would you do differently to improve this in any way?</p>\n</blockquote>\n<p>I am not sure how expensive it is but I would aim to minimize the number of times <code>res.write()</code> is called. For this I would have the functions to generate rows return a string and collect the strings for each row into an array, then join the array using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>Array.prototype.join()</code></a> to pass to a single call to <code>res.write()</code>.</p>\n<hr />\n<p>The code makes good use of <code>const</code> to keep the scope of variables limited and avoid accidental re-assignment. It can also be used for constant values that should never change during run-time.</p>\n<blockquote>\n<p>Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.\n<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Examples\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>Names like <code>htmlCSS</code> could be <code>HTML_CSS</code>, <code>port</code> could be <code>PORT</code>. That way anyone reading the code will know those values should not be changed. Bear in mind that any object/array declared with <code>const</code> is not immutable unless wrapped in a call to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\"><code>Object.freeze()</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T15:27:49.617",
"Id": "248245",
"ParentId": "248229",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T08:14:20.613",
"Id": "248229",
"Score": "7",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"http",
"server"
],
"Title": "Serving a webpage that displays the HTTP request information sent by the client"
}
|
248229
|
<p>I wrote a B-Tree implementation in C++20, based on my previous Red-Black Tree implementation.</p>
<p>Unit Test Demo : <a href="https://wandbox.org/permlink/Brw6TgAhdy89OIyj" rel="nofollow noreferrer">https://wandbox.org/permlink/Brw6TgAhdy89OIyj</a></p>
<p>Any feedback will be welcomed!</p>
<pre><code>#include <algorithm>
#include <cassert>
#include <concepts>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <numeric>
#include <random>
#include <ranges>
#include <utility>
#include <vector>
template <std::ranges::random_access_range R>
auto range_from(R&& r, int t) {
return std::ranges::subrange(std::begin(r) + t, std::end(r));
}
template <typename T>
concept Key = std::regular<T> && std::totally_ordered<T>;
template <Key T, std::size_t t, std::predicate<T, T> Comp = std::less<T>>
class BTree {
static_assert(t >= 2);
class Node {
std::size_t n = 0;
bool leaf = true;
Node* parent = nullptr;
std::size_t index = 0;
std::vector<T> key;
std::vector<std::unique_ptr<Node>> child;
public:
// modifying n must be done only with setN,
// for the invariants key.size() == n and child.size() == n + 1 (if exists)
void setN(std::size_t N) {
n = N;
key.resize(n);
if (!leaf) {
child.resize(n + 1);
}
}
void validateChild() {
if (leaf) {
return;
}
for (std::size_t i = 0; i <= n; i++) {
child[i]->index = i;
child[i]->parent = this;
}
}
[[nodiscard]] std::size_t getN() const {
return n;
}
[[nodiscard]] bool isFull() const {
return n == 2 * t - 1;
}
[[nodiscard]] bool canTakeKey() const {
return n > t - 1;
}
[[nodiscard]] bool hasMinimalKeys() const {
return n == t - 1;
}
[[nodiscard]] bool isEmpty() const {
return n == 0;
}
friend class BTree;
Node* RightmostLeaf() {
Node* curr = this;
while (!curr->leaf) {
curr = curr->child.back().get();
}
return curr;
}
Node* LeftmostLeaf() {
Node* curr = this;
while (!curr->leaf) {
curr = curr->child.front().get();
}
return curr;
}
// merge child[i + 1] and key[i] into child[i]
void Merge(std::size_t i) noexcept {
assert(!leaf && child[i]->hasMinimalKeys() && child[i + 1]->hasMinimalKeys());
child[i]->setN(2 * t - 1);
child[i]->key[t - 1] = key[i];
// bring keys of child[i + 1]
std::ranges::move(child[i + 1]->key, child[i]->key.begin() + t);
// bring children of child[i + 1]
if (!child[i]->leaf) {
std::ranges::move(child[i + 1]->child, child[i]->child.begin() + t);
}
// shift children from i + 1 left by 1 (because child[i + 1] is merged)
std::shift_left(child.begin() + i + 1, child.end(), 1);
// shift keys from i left by 1 (because key[i] is merged)
std::shift_left(key.begin() + i, key.end(), 1);
setN(n - 1);
validateChild();
child[i]->validateChild();
}
void LeftRotate() noexcept {
assert(index + 1 < parent->child.size());
auto sibling = parent->child[index + 1].get();
// left rotation
setN(n + 1);
key.back() = parent->key[index];
parent->key[index] = sibling->key.front();
// shift all keys of right sibling left by 1
std::shift_left(sibling->key.begin(), sibling->key.end(), 1);
if (!leaf) {
child[n] = std::move(sibling->child[0]);
// shift all children of right sibling left by 1
std::shift_left(sibling->child.begin(), sibling->child.end(), 1);
}
sibling->setN(sibling->getN() - 1);
validateChild();
sibling->validateChild();
}
void RightRotate() noexcept {
assert(index - 1 < parent->child.size());
auto sibling = parent->child[index - 1].get();
// right rotation
setN(n + 1);
// shift all keys of node right by 1
std::shift_right(key.begin(), key.end(), 1);
key.front() = parent->key[index - 1];
parent->key[index - 1] = sibling->key.back();
if (!leaf) {
// shift all children of node right by 1
std::shift_right(child.begin(), child.end(), 1);
child[0] = std::move(sibling->child[sibling->getN()]);
}
sibling->setN(sibling->getN() - 1);
validateChild();
sibling->validateChild();
}
};
struct BTreeIterator {
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::bidirectional_iterator_tag;
Node* node;
std::vector<T>::iterator it;
void Increment() {
if (it == node->key.end()) {
return;
}
if (node->leaf) {
++it;
while (node->parent && it == node->key.end()) {
it = node->parent->key.begin() + node->index;
node = node->parent;
}
} else {
auto i = std::distance(node->key.begin(), it);
node = node->child[i + 1]->LeftmostLeaf();
it = node->key.begin();
}
}
void Decrement() {
auto i = std::distance(node->key.begin(), it);
if (!node->leaf) {
node = node->child[i]->RightmostLeaf();
it = node->key.begin() + node->key.size() - 1;
} else {
if (i > 0) {
--it;
} else {
while (node->parent && node->index == 0) {
node = node->parent;
}
if (node->index > 0) {
it = node->parent->key.begin() + node->index - 1;
node = node->parent;
}
}
}
}
BTreeIterator(Node* node, std::size_t i) : node {node} {
assert(node && i <= node->key.size());
it = node->key.begin() + i;
}
reference operator*() const {
return *it;
}
pointer operator->() const {
return it;
}
BTreeIterator& operator++() {
Increment();
return *this;
}
BTreeIterator operator++(int) {
BTreeIterator temp = *this;
Increment();
return temp;
}
BTreeIterator& operator--() {
Decrement();
return *this;
}
BTreeIterator operator--(int) {
BTreeIterator temp = *this;
Decrement();
return temp;
}
friend bool operator==(const BTreeIterator& x, const BTreeIterator& y) {
return x.node == y.node && x.it == y.it;
}
friend bool operator!=(const BTreeIterator& x, const BTreeIterator& y) {
return !(x == y);
}
};
struct BTreeConstIterator {
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = const T*;
using reference = const T&;
using iterator_category = std::bidirectional_iterator_tag;
const Node* node;
std::vector<T>::const_iterator it;
void Increment() {
if (it == node->key.cend()) {
return;
}
if (node->leaf) {
++it;
while (node->parent && it == node->key.cend()) {
it = node->parent->key.cbegin() + node->index;
node = node->parent;
}
} else {
auto i = std::distance(node->key.cbegin(), it);
node = node->child[i + 1]->LeftmostLeaf();
it = node->key.cbegin();
}
}
void Decrement() {
auto i = std::distance(node->key.cbegin(), it);
if (!node->leaf) {
node = node->child[i]->RightmostLeaf();
it = node->key.cbegin() + node->key.size() - 1;
} else {
if (i > 0) {
--it;
} else {
while (node->parent && node->index == 0) {
node = node->parent;
}
if (node->index > 0) {
it = node->parent->key.cbegin() + node->index - 1;
node = node->parent;
}
}
}
}
BTreeConstIterator(const Node* node, std::size_t i) : node {node} {
assert(node && i <= node->key.size());
it = node->key.cbegin() + i;
}
reference operator*() const {
return *it;
}
pointer operator->() const {
return it;
}
BTreeConstIterator& operator++() {
Increment();
return *this;
}
BTreeConstIterator operator++(int) {
BTreeConstIterator temp = *this;
Increment();
return temp;
}
BTreeConstIterator& operator--() {
Decrement();
return *this;
}
BTreeConstIterator operator--(int) {
BTreeConstIterator temp = *this;
Decrement();
return temp;
}
friend bool operator==(const BTreeConstIterator& x, const BTreeConstIterator& y) {
return x.node == y.node && x.it == y.it;
}
friend bool operator!=(const BTreeConstIterator& x, const BTreeConstIterator& y) {
return !(x == y);
}
};
std::unique_ptr<Node> root;
using iterator = BTreeIterator;
using const_iterator = BTreeConstIterator;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
std::pair<const Node*, std::size_t> Search(const Node* x, const T& k) const {
std::size_t i = std::distance(x->key.begin(), std::ranges::lower_bound(x->key, k, Comp()));
if (i < x->getN() && k == x->key[i]) { // equal? key found
return {x, i};
} else if (x->leaf) { // no child, key is not in the tree
return {nullptr, 0};
} else { // search on child between range
return Search(x->child[i].get(), k);
}
}
void InsertNonFull(Node* x, const T& k) {
if (x->leaf) { // key should be inserted only at leaf
InsertToLeaf(x, k);
} else {
auto i = std::distance(x->key.begin(), std::ranges::upper_bound(x->key, k, Comp()));
if (x->child[i]->isFull()) { // is full? then split
SplitChild(x, i);
if (Comp()(x->key[i], k)) {
i++;
}
}
InsertNonFull(x->child[i].get(), k); // recursively insert
}
}
void InsertToLeaf(Node* node, const T& k) {
assert(node->leaf);
auto i = std::distance(node->key.begin(), std::ranges::upper_bound(node->key, k, Comp()));
node->setN(node->getN() + 1);
std::shift_right(node->key.begin() + i, node->key.end(), 1);
node->key[i] = k;
// n cannot exceeds 2t - 1, because in that case
// its parent should've called SplitChild on x before
assert(node->getN() < 2 * t);
}
// split x->child[i]
void SplitChild(Node* x, std::size_t i) noexcept {
if (!x) {
return;
}
auto y = x->child[i].get();
if (!y) {
return;
}
// x cannot be full, because in that case its parent should've called SplitChild on x before
assert(!x->isFull() && y->isFull());
auto z = std::make_unique<Node>(); // will be y's right sibling
z->leaf = y->leaf;
z->setN(t - 1);
// bring right half keys from y
std::ranges::move(range_from(y->key, t), z->key.begin());
if (!y->leaf) {
// bring right half children from y
std::ranges::move(range_from(y->child, t), z->child.begin());
z->validateChild();
}
x->setN(x->getN() + 1);
// shift children of x right by 1 from i + 1
std::shift_right(x->child.begin() + i + 1, x->child.end(), 1);
x->child[i + 1] = std::move(z);
// shift keys of x right by 1 from i
std::shift_right(x->key.begin() + i, x->key.end(), 1);
x->key[i] = y->key[t - 1];
y->setN(t - 1);
x->validateChild();
y->validateChild();
}
void Delete(Node* x, const T& k) noexcept {
std::size_t i = std::distance(x->key.begin(), std::ranges::lower_bound(x->key, k, Comp()));
if (i < x->getN() && k == x->key[i]) { // equal? key found
Delete(x, k, i);
} else if (x->leaf) { // no child, key is not in the tree
return;
} else { // search on child between range
Node* next = x->child[i].get();
if (x->child[i]->hasMinimalKeys()) {
if (i + 1 < x->child.size() && x->child[i + 1]->canTakeKey()) {
x->child[i]->LeftRotate();
} else if (i - 1 < x->child.size() && x->child[i - 1]->canTakeKey()) {
x->child[i]->RightRotate();
} else if (i + 1 < x->child.size()) {
x->Merge(i);
next = x->child[i].get();
if (x == root.get() && x->isEmpty()) {
// shrink tree in height, merged child should be a new root
root = std::move(x->child[i]);
root->parent = nullptr;
}
} else if (i - 1 < x->child.size()) {
x->Merge(i - 1);
next = x->child[i - 1].get();
if (x == root.get() && x->isEmpty()) {
// shrink tree in height, merged child should be a new root
root = std::move(x->child[i - 1]);
root->parent = nullptr;
}
}
}
Delete(next, k);
}
}
void Delete(Node* x, const T& k, std::size_t i) noexcept {
assert(x->key[i] == k);
if (x->leaf) {
// directly erase from leaf
DeleteToLeaf(x, i);
} else if (x->child[i]->canTakeKey()) {
// find predecessor and swap keys
auto predLeaf = x->child[i]->RightmostLeaf();
std::swap(predLeaf->key.back(), x->key[i]);
// now k is in left child, search there
Delete(x->child[i].get(), k);
} else if (x->child[i + 1]->canTakeKey()) {
// find successor and swap keys
auto succLeaf = x->child[i + 1]->LeftmostLeaf();
std::swap(succLeaf->key.front(), x->key[i]);
// now k is in right child, search there
Delete(x->child[i + 1].get(), k);
} else {
// merge two children
x->Merge(i);
Node* next = x->child[i].get();
if (x == root.get() && x->getN() == 0) {
// shrink tree in height, merged child should be a new root
root = std::move(x->child[i]);
root->parent = nullptr;
}
Delete(next, k);
}
}
void DeleteToLeaf(Node* node, std::size_t i) {
assert(node->leaf);
std::shift_left(node->key.begin() + i, node->key.end(), 1);
node->setN(node->getN() - 1);
assert(node == root.get() || node->getN() >= t - 1);
}
void ValidateIterators() {
begin_ = iterator(root->LeftmostLeaf(), 0);
cbegin_ = const_iterator(root->LeftmostLeaf(), 0);
end_ = iterator(root.get(), root->getN());
cend_ = const_iterator(root.get(), root->getN());
}
iterator begin_;
const_iterator cbegin_;
iterator end_;
const_iterator cend_;
public:
BTree() : root {std::make_unique<Node>()},
begin_ {root.get(), 0}, cbegin_ {root.get(), 0}, end_ {root.get(), 0}, cend_ {root.get(), 0} {
}
[[nodiscard]] std::pair<const Node*, std::size_t> Search(const T& k) const {
return Search(root.get(), k);
}
void Insert(const T& k) noexcept {
if (root->isFull()) { // if root is full then make it as a child of new root - and split
auto s = std::make_unique<Node>();
s->leaf = false;
s->setN(0);
s->child[0] = std::move(root);
root = std::move(s);
SplitChild(root.get(), 0);
InsertNonFull(root.get(), k);
} else {
InsertNonFull(root.get(), k);
}
ValidateIterators();
}
void Delete(const T& k) {
Delete(root.get(), k);
ValidateIterators();
}
iterator begin() {
return begin_;
}
const_iterator begin() const {
return cbegin_;
}
const_iterator cbegin() const {
return cbegin_;
}
iterator end() {
return end_;
}
const_iterator end() const {
return cend_;
}
const_iterator cend() const {
return cend_;
}
reverse_iterator rbegin() {
return reverse_iterator(end_);
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(cend_);
}
const_reverse_iterator crbegin() const {
return const_reverse_iterator(cend_);
}
reverse_iterator rend() {
return reverse_iterator(begin_);
}
const_reverse_iterator rend() const {
return const_reverse_iterator(cbegin_);
}
const_reverse_iterator crend() const {
return const_reverse_iterator(cbegin_);
}
};
int main() {
BTree<int, 2> tree;
constexpr std::size_t N = 100;
std::vector<int> v (N);
std::iota(v.begin(), v.end(), 1);
std::mt19937 gen(std::random_device{}());
std::ranges::shuffle(v, gen);
for (auto n : v) {
tree.Insert(n);
for (const auto& key : tree) {
std::cout << key << ' ';
}
std::cout << '\n';
}
assert(std::ranges::all_of(v, [&tree](auto n){return tree.Search(n).first != nullptr;}));
// should output 1 2 3 ... N
for (const auto& key : tree) {
std::cout << key << ' ';
}
std::cout << '\n';
std::ranges::shuffle(v, gen);
for (auto n : v) {
tree.Delete(n);
for (const auto& key : tree) {
std::cout << key << ' ';
}
std::cout << '\n';
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Don't restrict the type of key</h1>\n<p>You'll notice that ordered STL containers such as <a href=\"https://en.cppreference.com/w/cpp/container/map\" rel=\"noreferrer\"><code>std::map</code></a> put no constraints on the type of the key, neither using SFINAE, concepts nor a mention in the description. The reason is that you are allowed to specify your own compare function, which you can use to provide a way to order keys even if the keys themselves do not have a total order.</p>\n<p>As an example: suppose I want to store two-dimensional coordinates in a B-tree, and order them based on their x coordinate. Two-dimensional coordinates themselves do not have a well-defined ordering, so your <code>concept Key</code> would prevent it from being usable with <code>BTree</code>, even though it is trivial to write a comparison function that just compares the x coordinate of two keys.</p>\n<h1>Naming things</h1>\n<p>Avoid very short names for variables and types, unless it is a commonly used name. For example, <code>T</code> is fine for the template type of a key or value, <code>n</code> is a common abbreviation for a "number" of things. But <code>t</code> is a bad choice for the number of children of a node. I suggest you replace it with <code>fanout</code>.</p>\n<p>I also recommend you use the plural for names of containers that can hold multiple elements. So <code>keys</code> instead of <code>key</code>, <code>children</code> instead of <code>child</code>.</p>\n<p>Be consistent when naming things. I see both camelCase and PascalCase used for member functions.</p>\n<h1>Add more <code>assert()</code>s where appropriate</h1>\n<p>You already use <code>assert()</code> in a few cases, but it can be done in a lot more places. For example, in <code>BTree::Node::setN</code>, you can add:</p>\n<pre><code>assert(N <= 2 * t - 1);\n</code></pre>\n<p>The iterator operators could also use some <code>assert()</code> statements to check that you don't try to iterate past the beginning or end of the tree, and so on.</p>\n<h1>Optimize your iterators</h1>\n<p>There's a little bit of redundancy in your iterators:</p>\n<pre><code>Node* node;\nstd::vector<T>::iterator it;\n</code></pre>\n<p>Here, <code>it</code> also contains a pointer to <code>node->key</code>. It's better to just store the integer index into <code>node->key</code>. That way, you also don't have to jump through hoops to get an index into <code>node->child</code> as well:</p>\n<pre><code>Node *node;\nsize_t index;\n</code></pre>\n<h1>Optimize your <code>Node</code>s</h1>\n<p>You also store some redundant information in each <code>Node</code>. Consider that <code>key.size()</code> is equal to <code>n</code>, and <code>child.size()</code> is equal to <code>n + 1</code> for interior nodes, and <code>child.empty() == true</code> for leaf nodes. So <code>n</code> and <code>leaf</code> store redundant information. Removing those two variables gets rid of 16 bytes on 64-bit architectures, and there's less state that needs to be kept in sync.</p>\n<p>In principle you could also remove <code>parent</code> and <code>index</code>. This makes the iterators and the rotation operations more complex though, so I would probably keep it as it is now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T01:56:36.203",
"Id": "486290",
"Score": "0",
"body": "One more thing, I noticed that the key is mutable by non-const iterator, ruining the invariants of tree. So I'm planning to make keys immutable and provide a way to store (key, value) pair as std::map does, and provide a way to customize allocator using std::pmr things, to reduce memory fragmentation. Thanks for great feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:07:55.937",
"Id": "486312",
"Score": "0",
"body": "Sounds like good ideas! Post a new question when you want your changes to be reviewed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T20:12:03.307",
"Id": "248289",
"ParentId": "248231",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T09:09:41.293",
"Id": "248231",
"Score": "11",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++20"
],
"Title": "C++ : B-Tree in C++20 (+Iterator support)"
}
|
248231
|
<p>This bit of code is looking for the pair of integers that make up a product.</p>
<p>You can input any integer and it returns the pairs of numbers that, when multiplied together, make it up.</p>
<p>I have done a pretty bad job at explaining this, but the code it pretty simple.</p>
<p>All comments welcome.</p>
<pre><code>num = 498
num_1 = 1
while num_1 < num:
product = num / num_1
if product < num_1:
break
if product - int(product) == 0:
print(f"{num_1}, {int(product)}")
num_1 += 1
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Such <code>while</code>-loops that don't offer an advantage are unpythonic. And harder to understand. In your solution, the information about what the loop goes through is spread over six (!) lines. And I actually I need to read all 8 (!) lines, since I need to read the <code>if/print</code> as well in order to see that they <em>don't</em> affect the loop. Better use a <code>for</code>-loop, where it's all cleanly in one line.</p>\n</li>\n<li><p>If you do use such a <code>while</code>-loop, then there should be an empty line <em>above</em> your <code>num_1 = 1</code>, not <em>under</em> it. Because it belongs to the solution, not to the input.</p>\n</li>\n<li><p>Floating-point in general has precision issues, better avoid it if you can. Here it's simple to use just integers.</p>\n</li>\n<li><p>For <code>num = 1</code>, you don't print anything. You should print <code>1, 1</code>.</p>\n</li>\n<li><p>Unless you have an actual reason for that formatting, keep it simple and don't format. If you use the output of your program as input for something else, it might also very well be easier to parse without that extra comma.</p>\n</li>\n</ul>\n<p>Resulting code:</p>\n<pre><code>from math import isqrt\n\nnum = 498\n\nfor i in range(1, isqrt(num) + 1):\n if num % i == 0:\n print(i, num // i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:48:41.987",
"Id": "486243",
"Score": "0",
"body": "I was trying to work out why this wouldn't work for me, then realised that I am running 3.7 and isqrt is new for 3.8. Do you have a workaround for 3.7 without using isqrt?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:21:44.593",
"Id": "486259",
"Score": "2",
"body": "@JKRH Try `int(num**.5)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T13:33:47.570",
"Id": "486333",
"Score": "0",
"body": "@JKRH That btw seems to be correct until num=4,503,599,761,588,223, so presumably sufficient for you. But `int((67108865**2 - 1)**.5)` gives `67108865` when it should give `67108864`. With `isqrt` you wouldn't have that issue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:12:54.393",
"Id": "248239",
"ParentId": "248233",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T11:04:46.937",
"Id": "248233",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Integer pairs of a product in Python"
}
|
248233
|
<p>Similar to this <a href="https://codereview.stackexchange.com/questions/104803/independent-cascade-modelling-in-python">question</a>, I implemented the independent cascade model, but for a given <a href="https://networkx.github.io" rel="nofollow noreferrer">networkx</a> graph (including multigraph with parallel edges). My focus is on readability, pythonic-ness, and performance (although the problem itself is NP-hard).</p>
<p>I cannot wait to hear your feedback!</p>
<pre><code>def independent_cascade_model(G: nx.Graph, seed: list, beta: float=1.0):
informed_nodes = {n: None for n in seed}
updated = True
while updated:
for u, v, diffusion_time in G.edges(nbunch=informed_nodes, data='diffusion_time'):
updated = False
if informed_nodes[u] == None or informed_nodes[u] < diffusion_time:
if random.random() < beta:
if v not in informed_nodes or diffusion_time < informed_nodes[v]:
informed_nodes[v] = diffusion_time
updated = True
return informed_nodes
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T20:45:47.980",
"Id": "486191",
"Score": "0",
"body": "I'm not sure I can follow the problem from your code. From your naming, it seems like `seed` contains the nodes informed at `t = 0` and that `diffusion_time` is the time it takes the information to go from `u` to `v`. Hence, we infer that the time to inform `v` is `informed_nodes[u] + diffusion_time`, and that for each seed `s`, `informed_time[s] == 0`. This is different in your code, did I misunderstand the problem?"
}
] |
[
{
"body": "<h1>Correctness / Readability</h1>\n<p>I'm not sure if this is a bug, or just an unclearness of the algorithm.</p>\n<pre><code> while updated:\n for ... in ...:\n updated = False\n if ...:\n if ...:\n if ...:\n ...\n updated = True\n</code></pre>\n<p>If you want to loop over the edges, until no change is made, then the <code>updated = False</code> looks like it is in the wrong place. As it currently stands, if the last edge processed in the <code>for</code> loop fails any of the 3 if conditions, the <code>updated</code> flag is set to <code>False</code>, even if a prior edge set it to <code>True</code>.</p>\n<p>Wouldn't the correct implementation be:</p>\n<pre><code> while updated:\n updated = False\n for ... in ...:\n if ...:\n if ...:\n if ...:\n ...\n updated = True\n</code></pre>\n<p>Now, for each <code>while</code> loop iteration, we start by clearing the flag. Then, if any edge results in <code>updated = True</code>, a change has been made and the <code>while</code> loop is repeated.</p>\n<p>If the <code>updated = False</code> was in the correct place, then the readability of the code could be improved with comments explaining why <code>update = True</code> only matters for the last edge returned by the <code>for</code> loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:08:30.453",
"Id": "248250",
"ParentId": "248234",
"Score": "3"
}
},
{
"body": "<p>You should not use <code>==</code>/<code>!=</code> to compare to singletons like <code>None</code>, instead use <code>is</code>/<code>is not</code>.</p>\n<p>Here is one way to restructure your conditions. This reduces the amount of nesting, which hopefully increases the overall readability.</p>\n<pre><code>import math\n\ndef independent_cascade_model(G: nx.Graph, seed: list, beta: float=1.0): \n informed_nodes = {n: None for n in seed}\n updated = True\n while updated:\n updated = False\n for u, v, diffusion_time in G.edges(nbunch=informed_nodes, data='diffusion_time'):\n if informed_nodes.get(u, math.nan) <= diffusion_time:\n # node is already set up properly\n continue\n elif random.random() >= beta:\n continue\n elif informed_nodes.get(v, math.inf) > diffusion_time:\n informed_nodes[v] = diffusion_time\n updated = True\n return informed_nodes\n</code></pre>\n<p>Here I also used <code>dict.get</code> with the optional default argument set in such a way that the conditions are the right way around for missing data.</p>\n<pre><code>>>> n = 10 # works for any numeric n\n>>> math.nan <= n \n# False\n\n>>> import sys\n>>> n = sys.maxsize # works for any numeric n except for inf\n>>> math.inf > n\n# True\n</code></pre>\n<p>Just make sure you don't run into <code>math.inf > math.inf</code> -> <code>False</code> or <code>math.inf > math.nan</code> -> <code>False</code></p>\n<p>You should also add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> to your function explaining what it does and what the arguments are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T21:14:40.047",
"Id": "486274",
"Score": "1",
"body": "Using the `math.nan` and `math.inf` constants are preferable over using `float(\"...\")` to repeatedly convert strings into the special floating point singleton values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T06:12:55.813",
"Id": "486302",
"Score": "0",
"body": "@AJNeufeld You are right. I did not know of this convention, but it makes sense to not constantly arse a string..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:13:25.543",
"Id": "248270",
"ParentId": "248234",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T11:53:58.440",
"Id": "248234",
"Score": "3",
"Tags": [
"python",
"graph"
],
"Title": "Independent cascade model for networkx graphs"
}
|
248234
|
<p>Any improvements to this welcome, I have got it working and I'm happy with it. I'm not really all that proficient with bash shell scripts though.</p>
<p>Problem:
AWS can copy multiple files pretty much as quickly as it can copy one file, so if you have a lot of large files then the best way is to get Amazon to copy them in parallel.</p>
<p>Solution:
Run the <code>aws s3 cp</code> or <code>mv</code> commands as background processes, and monitor them for completion. Limit the number that can be run in parallel.</p>
<pre><code># Check for aws s3 commands running that are owned by this shell process
function counts3 #
{
local plist=( $( ps -ef | grep -E "aws s3 \w+ " | awk "<span class="math-container">\$3 == $$ { print \$</span>2 }" ) )
echo ${#plist[@]}
}
# Submit an aws s3 process in the background, if there are fewer than "n" currently running
function multis3 # (threads cp|mv source target [other params]...)
{
local threads=$1;shift
# Turn off monitor mode so you don't get the nohup completion output
set +m
local pcount=$(counts3)
# Wait until there are fewer s3 commands running than the threads limit
while (( ${pcount} > ${threads} )) || (( ${pcount} == ${threads} )) ; do
sleep 1
pcount=`counts3`
done
# Run the command, as there is now below the limit
nohup aws s3 $@ >& /dev/null &
# Introduce a small delay to stagger the start of the cp/mv commands
sleep 1
}
# Check if there are any aws s3 processes running, and wait until there aren't
function multis3wait #
{
local pcount=$(counts3)
# Wait until there are no s3 commands running
while (( ${pcount} > 0 )) ; do
sleep 1
pcount=`counts3`
done
# Turn monitor mode back on again
set -m
}
</code></pre>
<p>Usage example, instead of this:</p>
<pre><code>aws s3 cp s3://from_bucket/from_path/file-1.txt s3://to_bucket/to_path/file-1.txt
aws s3 cp s3://from_bucket/from_path/file-2.txt s3://to_bucket/to_path/file-2.txt
aws s3 cp s3://from_bucket/from_path/file-3.txt s3://to_bucket/to_path/file-3.txt
aws s3 cp s3://from_bucket/from_path/file-4.txt s3://to_bucket/to_path/file-4.txt
aws s3 cp s3://from_bucket/from_path/file-5.txt s3://to_bucket/to_path/file-5.txt
aws s3 cp s3://from_bucket/from_path/file-6.txt s3://to_bucket/to_path/file-6.txt
aws s3 cp s3://from_bucket/from_path/file-7.txt s3://to_bucket/to_path/file-7.txt
aws s3 cp s3://from_bucket/from_path/file-8.txt s3://to_bucket/to_path/file-8.txt
aws s3 cp s3://from_bucket/from_path/file-9.txt s3://to_bucket/to_path/file-9.txt
</code></pre>
<p>do this:</p>
<pre><code>multis3 3 cp s3://from_bucket/from_path/file-1.txt s3://to_bucket/to_path/file-1.txt
multis3 3 cp s3://from_bucket/from_path/file-2.txt s3://to_bucket/to_path/file-2.txt
multis3 3 cp s3://from_bucket/from_path/file-3.txt s3://to_bucket/to_path/file-3.txt
multis3 3 cp s3://from_bucket/from_path/file-4.txt s3://to_bucket/to_path/file-4.txt
multis3 3 cp s3://from_bucket/from_path/file-5.txt s3://to_bucket/to_path/file-5.txt
multis3 3 cp s3://from_bucket/from_path/file-6.txt s3://to_bucket/to_path/file-6.txt
multis3 3 cp s3://from_bucket/from_path/file-7.txt s3://to_bucket/to_path/file-7.txt
multis3 3 cp s3://from_bucket/from_path/file-8.txt s3://to_bucket/to_path/file-8.txt
multis3 3 cp s3://from_bucket/from_path/file-9.txt s3://to_bucket/to_path/file-9.txt
multis3wait
</code></pre>
<p>The <code>3</code> is the number of permitted threads. This can be as high as you like, 3 is just an example, but I have found that going over 50 doesn't really gain much. You can also do <code>mv</code> instead of or as well as <code>cp</code>.</p>
<p>Remember, if you put these functions in a shell library script (e.g. <code>multis3.sh</code>) you need to do this first to load the functions:</p>
<pre><code>. multis3.sh
</code></pre>
<p>Perhaps I should remove the <code>set +m</code> and <code>set -m</code> and leave that up to the calling script to decide.</p>
<p>Alternative approaches</p>
<ul>
<li>Gnu <code>parallel</code> can be used to run the <code>aws s3</code> commands</li>
<li>The <code>aws s3 sync</code> command will use the <code>max_concurrent_requests</code> setting to copy multiple files in parallel</li>
</ul>
<p>I still feel that this library has a place, as it allows finer control over what gets copied than <code>aws s3 sync</code> (and can do <code>mv</code> as well as <code>cp</code>), and the advantage over <code>parallel</code> is that you can kick off a buch of copy commands, do something else in the script, and then wait for them all to complete before doing something that needs the files.</p>
<p>Possible enhancements</p>
<p>This could be generalised to run any process, and just count the number of child processes without filtering for <code>aws s3</code>. The child process count would have to exclude the <code>ps</code> command that is counting child processes...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:17:41.397",
"Id": "486134",
"Score": "0",
"body": "It is great that you implemented this as a shell library. That will give you the most flexibility with reusing this code in the long term. Kudos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:34:08.503",
"Id": "486400",
"Score": "0",
"body": "Would you not get the same advantage with GNU Parallel simply by using `&` and `wait`: `parallel ... & do other stuff; wait; do stuff that need the cp to finish`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:03:40.790",
"Id": "486556",
"Score": "0",
"body": "GNU parallel might work, but I'd have to prepare a file or variable with all the commands and feed them all in at the same time. With this, I can drip feed the files in a shell. I sometimes do this manually, prepare a few hundred commands and paste 50 at a time into a shell and let the multis3 command manage it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:06:05.090",
"Id": "248235",
"Score": "3",
"Tags": [
"bash",
"amazon-web-services"
],
"Title": "Copying multiple S3 files in parallel using aws shell command"
}
|
248235
|
<p><strong>Description</strong></p>
<p>I've written the snake game using C++ and FLTK. For simplifying the use of FLTK, a built-up library written by Bjarne Stroustrup was used. Bellow located main parts of the code written by me, a whole project can be found on GitHub: <a href="https://github.com/WumpusHunter/Snake-game" rel="nofollow noreferrer">https://github.com/WumpusHunter/Snake-game</a>.</p>
<p><strong>Source.cpp</strong></p>
<pre><code>/*
Snake game
Revision history:
Written by Oleg Kovalevskiy in August 2020
*/
//------------------------------------------------------------------------------------
#include "Game_window.h"
using namespace Graph_lib;
//------------------------------------------------------------------------------------
int main()
try {
// Window with top-left angle at (100, 100), of size 600 * 400, labeled "Snake game"
Snake_window win{ Point{ 100, 100 }, 600, 400, "Snake game" };
return gui_main();
}
catch (const exception& e) {
cerr << "Error message: " << e.what() << '\n';
return 1;
}
catch (...) {
cerr << "Unknown error\n";
return 1;
}
//------------------------------------------------------------------------------------
</code></pre>
<p><strong>Game_window.h</strong></p>
<pre><code>// Snake game's window
//------------------------------------------------------------------------------
#pragma once
#include "GraphicsLib/Window.h"
#include "GraphicsLib/GUI.h"
#include "GraphicsLib/Graph.h"
#include "Game_graph.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
// Invariant: w > 0, h > 0
class Snake_window : public Window { // Game window
public:
// Construction
Snake_window(Point xy, int w, int h, const string& lab);
private:
// Callback functions
int handle(int event) override;
static void cb_game_loop(Address pw);
static void cb_pause(Address, Address pw);
static void cb_new_game(Address, Address pw);
static void cb_quit(Address, Address pw);
static void cb_game(Address, Address pw);
static void cb_help(Address, Address pw);
// Action functions
void start();
void game_loop();
bool is_pause();
void pause();
void new_game();
void quit();
void game();
void help();
int current_score();
void put_score();
void show_graphics();
void hide_graphics();
private:
// Graphics
Grid field;
Snake snake;
Rectangle fruit;
// GUI
Menu game_menu;
Button game_button;
Button help_button;
Text_box help_box;
Out_box score_box;
Out_box max_score_box;
};
//------------------------------------------------------------------------------
} // End of Graph_lib namespace
//------------------------------------------------------------------------------
</code></pre>
<p><strong>Game_window.cpp</strong></p>
<pre><code>// Snake game's window
//------------------------------------------------------------------------------
#include "Game_window.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
// Min possible size of window
constexpr int min_w = 400; // Window's min width
constexpr int min_h = 300; // Window's min height
// Size of cells
constexpr int cell_w = 50; // Cell's width
constexpr int cell_h = 50; // Cell's height
// Default parameters of snake
constexpr int snake_sz = 3; // Snake's length
// Default location of graphics
Point snake_xy = { 0, 0 }; // Snake's location
Point fruit_xy = { 0, 0 }; // Fruit's location
// Size of widgets
constexpr int widget_h = 25; // Widgets' height
constexpr int out_box_w = 30; // Output boxes' width
constexpr int button_w = 100; // Buttons' width
// Indexes of game menu's buttons
constexpr int new_game_ind = 0; // New game button's index
constexpr int pause_ind = 1; // Pause button's index
constexpr int quit_ind = 2; // Quit button's index
// Constructs window with top-left angle at xy, of size w * h (if
// it's not less than min, which is 400 * 300), labeled with lab
Snake_window::Snake_window(Point xy, int w, int h, const string& lab)
: Window{ xy, w >= min_w ? w - w % cell_w : min_w, h >= min_h ? h - h % cell_h : min_h, lab },
field{ Point{ 0, cell_h }, cell_w, cell_h, x_max() / cell_w, (y_max() - cell_h) / cell_h },
snake{ Point{ snake_sz * cell_w, y_max() / 2 }, cell_w, cell_h, snake_sz },
fruit{ Point{ x_max() - cell_w * 2, y_max() / 2 }, cell_w, cell_h },
game_menu{ Point{ 0, 0 }, button_w, widget_h, Menu::Kind::horizontal, "Game" },
game_button{ Point{ 0, 0 }, button_w, widget_h, "&Game", cb_game },
help_button{ Point{ button_w, 0 }, button_w, widget_h, "&Help", cb_help },
help_box{ Point{ 0, cell_h }, x_max(), y_max() - cell_h, "" },
score_box{ Point{ cell_w * 2, widget_h }, out_box_w, widget_h, "Current score: " },
max_score_box{ Point{ cell_w * 4 + out_box_w, widget_h }, out_box_w, widget_h, "Max score: " }
{
if (w <= 0 || h <= 0) // Error handling
throw invalid_argument("Bad Snake_window: non-positive size");
// Keep default location of graphics
snake_xy = snake.point(0);
fruit_xy = fruit.point(0);
// Attach graphics to window
attach(field);
attach(snake);
attach(fruit);
// Attach widgets to window
game_menu.attach(new Button{ Point{ 0, 0 }, 0, 0, "&New game", cb_new_game });
game_menu.attach(new Button{ Point{ 0, 0 }, 0, 0, "&Pause", cb_pause });
game_menu.attach(new Button{ Point{ 0, 0 }, 0, 0, "&Quit", cb_quit });
attach(game_menu);
attach(game_button);
attach(help_button);
attach(help_box);
attach(score_box);
attach(max_score_box);
// Default value for graphics
show_graphics();
put_on_top(snake);
// Default value for widgets
game_menu.hide();
help_box.put(" SNAKE GAME\n"
" Snake is a video game concept where the player maneuvers a line\n"
"that grows in length, with the line itself being a primary obstacle.\n"
"The concept originated in the 1976 arcade game Blockade.\n"
" GAMEPLAY\n"
" The player controls an object on a bordered plane. As it moves for-\n"
"ward, it leaves a trail behind, resembling a moving snake. The snake\n"
"has a specific length, so there is a moving tail a fixed number of units\n"
"away from the head. The player loses when the snake runs into the\n"
"screen border or itself.\n"
" A sole player attempts to eat items by running into them with the he-\n"
"ad of the snake. Each item eaten makes the snake longer, so con-\n"
"trolling is progressively more difficult.\n"
" CONTROL\n"
" The snake moves forward automatically, everything you need to do\n"
"is to choose the direction of moving. To choose the direction of mov-\n"
"ing use arrow-buttons, that is,\n"
"1) Left-arrow - to move in the left direction;\n"
"2) Up-arrow - to move in the up direction;\n"
"3) Right-arrow - to move in the right direction;\n"
"4) Down-arrow - to move in the down direction.\n"
"Remember: you can't rotate the snake's head to the opposite direc-\n"
"tion, for instance, from the left to the right, or from the up to the\n"
"down.\n"
" ADDITIONAL NOTES\n"
" Good luck on the game, try to eat as much as you can!\n");
help_box.hide();
score_box.put(0);
max_score_box.put(0);
}
// Handles passed to window event, for instance, pressed key
int Snake_window::handle(int event)
{
switch (event) {
case FL_FOCUS: case FL_UNFOCUS: // Focuses are skipped (required by system)
return 1;
case FL_KEYBOARD: { // Keys, pressed using keyboard
switch (Fl::event_key()) {
// Arrow-keys used to change snake's direction
case FL_Left: // Left-arrow
snake.set_direction(Snake::Direction::left);
cout << "Changed direction to the left (" << static_cast<int>(snake.direction()) << ")\n";
return 1;
case FL_Up: // Up-arrow
snake.set_direction(Snake::Direction::up);
cout << "Changed direction to the up (" << static_cast<int>(snake.direction()) << ")\n";
return 1;
case FL_Right: // Right-arrow
snake.set_direction(Snake::Direction::right);
cout << "Changed direction to the right (" << static_cast<int>(snake.direction()) << ")\n";
return 1;
case FL_Down: // Down-arrow
snake.set_direction(Snake::Direction::down);
cout << "Changed direction to the down (" << static_cast<int>(snake.direction()) << ")\n";
return 1;
}
}
}
return Window::handle(event); // Everything else is handled by base window
}
// Callback function for game_loop
void Snake_window::cb_game_loop(Address pw)
{
constexpr double delay = 0.25; // Delay of game's loop
reference_to<Snake_window>(pw).game_loop(); // Call of action function
Fl::repeat_timeout(delay, cb_game_loop, pw); // Execute delay of game's loop
}
// Callback function for pause
void Snake_window::cb_pause(Address, Address pw)
{
reference_to<Snake_window>(pw).pause();
reference_to<Snake_window>(pw).game();
}
// Callback function for new game
void Snake_window::cb_new_game(Address, Address pw)
{
reference_to<Snake_window>(pw).new_game();
reference_to<Snake_window>(pw).game();
}
// Callback function for quit
void Snake_window::cb_quit(Address, Address pw)
{
reference_to<Snake_window>(pw).quit();
reference_to<Snake_window>(pw).game();
}
// Callback function for game
void Snake_window::cb_game(Address, Address pw)
{
reference_to<Snake_window>(pw).game();
}
// Callback function for help
void Snake_window::cb_help(Address, Address pw)
{
reference_to<Snake_window>(pw).help();
}
// Starts game's loop
void Snake_window::start()
{
constexpr double delay = 1.0; // Delay before first timeout
Fl::add_timeout(delay, cb_game_loop, this); // Start game's loop and delay proccess
cout << "Started the game\n";
}
// Starts all proccesses of game's loop
void Snake_window::game_loop()
{
// Snake's bumping (obstacle is snake's body or field's borders)
if (snake.is_body_except_head(snake.body_head())) { // Snake's body as obstacle
cout << "Bumped into the snake's body\n";
// Pause after losed game
return Fl::add_timeout(0.0, [](Address pw) { cb_pause(nullptr, pw); }, this);;
}
if (!is_grid(field, snake.body_head())) { // Grid's border as obstacle
cout << "Bumped into the grid's border\n";
// Pause after losed game
return Fl::add_timeout(0.0, [](Address pw) { cb_pause(nullptr, pw); }, this);
}
// Snake's eating
if (snake.point(0) == fruit.point(0)) {
snake.grow_length();
put_score(); // Update score after eating
cout << "Ate the fruit; the length becomes equal to " << snake.length() << '\n';
// Randomly change location of fruit to everywhere, except snake's body
while (snake.is_body(fruit))
random_move(fruit, field.point(0), field.width() - fruit.width(), field.height() - fruit.height());
}
else snake.move_forward(); // Snake's moving
cout << "Moved to (" << snake.point(0).x << ", " << snake.point(0).y << ")\n";
redraw(); // Redraw window after made changes
}
// Determines either game is paused or not
bool Snake_window::is_pause()
{
return Fl::has_timeout(cb_game_loop, this) ? false : true;
}
// Pauses game if it's playing, or starts if it's already
// paused, that is, pause prevents snake's moves
void Snake_window::pause()
{
if (!is_pause()) {
Fl::remove_timeout(cb_game_loop, this); // Stop timeout
cout << "Paused the game\n";
}
else start(); // Start timeout
}
// Starts new game, that is, returns everything to initial state
void Snake_window::new_game()
{
if (!is_pause()) pause(); // Pause game
snake.shrink_length(current_score()); // Shrink length to default length
// Return graphics to default location
snake.set_direction(Snake::Direction::up);
snake.set_direction(Snake::Direction::right);
for (int i = 0; i < snake_sz; ++i)
snake.move_forward();
snake.move(-snake.point(0).x, -snake.point(0).y); // Top-left angle of window
snake.move(snake_xy.x, snake_xy.y);
fruit.move(-fruit.point(0).x, -fruit.point(0).y); // Top-left angle of window
fruit.move(fruit_xy.x, fruit_xy.y);
cout << "Started the new game; shrank the length to " << snake.length() << '\n';
put_score(); // Update score after shrinking
redraw(); // Redraw window after made changes
}
// Quits game, that is, closes window
void Snake_window::quit()
{
Window::hide(); // Hide window to close it
cout << "Quited the game\n";
}
// Hides game button and shows game menu, if game button is pressed,
// or shows game button and hides game menu, if game menu is pressed
void Snake_window::game()
{
// Hide game button and show game menu
if (game_button.visible()) { // Game button is pressed
game_button.hide();
game_menu.show();
help_button.move(game_menu.selection.size() * game_menu.width - help_button.width, 0);
cout << "Hid the game button and showed the game menu\n";
}
// Hide game menu and show game button
else { // Game menu is pressed
game_menu.hide();
game_button.show();
help_button.move(help_button.width - game_menu.selection.size() * game_menu.width, 0);
cout << "Hid the game menu and showed the game button\n";
}
}
// Shows help box if it's invisible, or hides it if it's visible
void Snake_window::help()
{
// Show help box
if (!help_box.visible()) { // Help box is invisible
if (!is_pause()) pause(); // Pause game
game_menu.selection[pause_ind].deactivate();
hide_graphics();
help_box.show();
cout << "Showed the help box\n";
}
// Hide help box
else { // Help box is visible
game_menu.selection[pause_ind].activate();
help_box.hide();
show_graphics();
cout << "Hid the help box\n";
}
}
// Determines current score
int Snake_window::current_score()
{
return snake.length() - snake_sz;
}
// Writes current score and max score into score boxes, if required
void Snake_window::put_score()
{
int score = current_score();
score_box.put(score); // Write current score
if (score > max_score_box.get_int()) { // New record
max_score_box.put(score); // Write max score
cout << "Updated the max score to " << score << '\n';
}
cout << "Updated the current score to " << score << '\n';
}
// Shows game's graphics, that is, makes field, snake, and fruit visible
void Snake_window::show_graphics()
{
// Modify color parameters of graphics
field.set_color(Color::black);
field.set_fill_color(Color::dark_green);
snake.set_color(Color::black);
snake.set_fill_color(Color::dark_yellow);
snake.head_set_fill_color(Color::yellow);
fruit.set_color(Color::black);
fruit.set_fill_color(Color::red);
cout << "Showed the graphics\n";
}
// Hides game's graphics, that is, makes field, snake, and fruit invisible
void Snake_window::hide_graphics()
{
// Modify color parameters of graphics
field.set_color(Color::invisible);
field.set_fill_color(Color::invisible);
snake.set_color(Color::invisible);
snake.set_fill_color(Color::invisible);
snake.head_set_fill_color(Color::invisible);
fruit.set_color(Color::invisible);
fruit.set_fill_color(Color::invisible);
cout << "Hid the graphics\n";
}
//------------------------------------------------------------------------------
} // End of Graph_lib namespace
//------------------------------------------------------------------------------
</code></pre>
<p><strong>Game_graph.h</strong></p>
<pre><code>// Snake game's graphics
//------------------------------------------------------------------------------
#pragma once
#include "GraphicsLib/Graph.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
// Invariant: cell_w > 0, cell_h > 0, sz > 0
class Snake : public Shape {
public:
enum class Direction { // Possible directions of head
left, up, right, down
};
// Construction
Snake(Point xy, int cell_w, int cell_h, int sz);
// Drawing
void draw_lines() const override;
void move(int dx, int dy) override;
void move_forward();
void grow_length();
void shrink_length(int num);
// Modification of parameters
void set_color(Color c);
void set_fill_color(Color c);
void set_style(Line_style ls);
void set_direction(Direction d);
void head_set_fill_color(Color c);
// Access to parameters
const Rectangle& body_head() const;
Direction direction() const { return head; }
int length() const { return body.size(); }
bool is_body(const Rectangle& cell) const;
bool is_body_except_head(const Rectangle& cell) const;
private:
Vector_ref<Rectangle> body;
Direction head; // Direction of head
};
//------------------------------------------------------------------------------
// Helper function
void random_move(Rectangle& rect, Point xy, int w, int h);
//------------------------------------------------------------------------------
} // End of Graph_lib namespace
//------------------------------------------------------------------------------
</code></pre>
<p><strong>Game_graph.cpp</strong></p>
<pre><code>// Snake game's graphics
//------------------------------------------------------------------------------
#include "Game_graph.h"
#include "RandomNumber/Generator.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
// Indexes of snake's body
constexpr int head_ind = 0;
// Constructs snake with top left-angle of its head at xy, of sz
// cells, and with size of each cell equal to cell_w * cell_h
Snake::Snake(Point xy, int cell_w, int cell_h, int sz)
: body{}, head{ Direction::right }
{
if (sz <= 0) // Error handling
throw invalid_argument("Bad Snake: non-positive length");
// Fill of body
for (int i = 0; i < sz; ++i) // Horizontal line
body.push_back(new Rectangle{ Point{ xy.x - i * cell_w, xy.y }, cell_w, cell_h });
add(xy); // Top-left angle of snake's head
}
// Draws snake and fills it with color if required
void Snake::draw_lines() const
{
// Draw each cell of body
for (int i = 0; i < body.size(); ++i)
body[i].draw();
}
// Moves snake by dx at x-coordinate and dy at y-coordinate
void Snake::move(int dx, int dy)
{
Shape::move(dx, dy);
// Move each cell of body
for (int i = 0; i < body.size(); ++i)
body[i].move(dx, dy);
}
// Moves snake forward, that is, moves each cell from tail to head
// to its next neighbor, and moves head one cell in its direction
void Snake::move_forward()
{
// Move each cell from tail to head to its next neighbour
for (int i = body.size() - 1; i > 0; --i) {
body[i].move(-body[i].point(0).x, -body[i].point(0).y); // Move to initial point
body[i].move(body[i - 1].point(0).x, body[i - 1].point(0).y); // Move to neigbhour's point
}
// Move head one cell in its direction
switch (head) {
case Direction::left: // Left-side
body[head_ind].move(-body[head_ind].width(), 0);
break;
case Direction::up: // Up-side
body[head_ind].move(0, -body[head_ind].height());
break;
case Direction::right: // Right-side
body[head_ind].move(body[head_ind].width(), 0);
break;
case Direction::down: // Down-side
body[head_ind].move(0, body[head_ind].height());
break;
}
set_point(0, body[head_ind].point(0)); // Update location of snake's head
}
// Grows snake in length, that is, adds one cell to its tail
void Snake::grow_length()
{
const Point tail = body[body.size() - 1].point(0); // Tail's coordinate
move_forward();
// Add new cell into body at previous tail's location
body.push_back(new Rectangle{ tail, body[head_ind].width(), body[head_ind].height() });
// Set same parameters for new tail as for all body
body[body.size() - 1].set_color(color());
body[body.size() - 1].set_fill_color(fill_color());
body[body.size() - 1].set_style(style());
}
// Shrinks snake in length, that is, removes num cells from its body, starting with tail
void Snake::shrink_length(int num)
{
if (num >= body.size()) // Error handling
throw invalid_argument("Bad Snake: can't shrink to non-positive length");
constexpr bool own = true; // Cells are owned by body
// Remove num cells from snake's body
for (int i = 0; i < num; ++i)
body.pop_back(own);
}
// Sets c as color of snake's lines
void Snake::set_color(Color c)
{
Shape::set_color(c);
// Set c as color of lines to each cell of body
for (int i = 0; i < body.size(); ++i)
body[i].set_color(c);
}
// Sets c as fill color of snake's body
void Snake::set_fill_color(Color c)
{
Shape::set_fill_color(c);
// Set c as fill color to each cell of body
for (int i = 0; i < body.size(); ++i)
body[i].set_fill_color(c);
}
// Sets c as fill color of snake's head
void Snake::head_set_fill_color(Color c)
{
if (body.begin() == body.end()) // Error handling
throw out_of_range("Bad Snake: can't set fill color to head of empty snake");
body[head_ind].set_fill_color(c);
}
// Sets ls as line style of snake's body
void Snake::set_style(Line_style ls)
{
Shape::set_style(ls);
// Set ls as line style to each cell of body
for (int i = 0; i < body.size(); ++i)
body[i].set_style(ls);
}
// Sets d as direction of snake's head
void Snake::set_direction(Direction d)
{
constexpr int opposite_diff = 2; // Module of opposite direction's difference
// Difference of directions
const int diff = abs(static_cast<int>(head) - static_cast<int>(d));
if (diff != opposite_diff) // Set direction if it's not opposite
head = d;
}
// Gets snake's head
const Rectangle& Snake::body_head() const
{
if (body.cbegin() == body.cend()) // Error handling
throw out_of_range("Bad Snake: can't get head of empty snake");
return body[head_ind];
}
// Determines either cell is one of snake's body's cells
bool Snake::is_body(const Rectangle& cell) const
{
// Search for cell in snake's body, located same as cell, and compare parameters
return find_if(body.cbegin(), body.cend(), [&cell](const Rectangle* rect)
{ return rect->point(0) == cell.point(0); }) != body.cend()
&& body[0].width() == cell.width() && body[0].height() == cell.height();
}
// Determines either cell is one of snake's body's cells, except its head
bool Snake::is_body_except_head(const Rectangle& cell) const
{
// Search for cell in snake's body, located same as cell, except snake's head, and compare parameters
return body.cbegin() != body.cend() ? find_if(next(body.cbegin()), body.cend(),
[&cell](const Rectangle* rect) { return rect->point(0) == cell.point(0); }) != body.cend()
&& body[0].width() == cell.width() && body[0].height() == cell.height() : false;
}
//------------------------------------------------------------------------------
// Moves rect randomly in range [xy.x; xy.x + w] for x-coordinate and [xy.y; xy.y + h] for
// y-coordinate, with xy as original point, w as width of range and h as height of range
void random_move(Rectangle& rect, Point xy, int w, int h)
{
if (w < 0 || h < 0) // Error handling
throw invalid_argument("Bad random_move: invalid range for coordinates");
// Move to original location, that is, xy
rect.move(-(rect.point(0).x - xy.x), -(rect.point(0).y - xy.y));
rect.move(rect.width() * randint(0, w / rect.width()), // Random x-coordinate
rect.height() * randint(0, h / rect.height())); // Random y-coordinate
}
//------------------------------------------------------------------------------
} // End of Graph_lib namespace
//------------------------------------------------------------------------------
</code></pre>
<p><strong>Question</strong></p>
<p>How can I improve my code in the future? Any tips are appreciated, but especially hope
to see your thoughts on the structuring of the code, its flexibility, and readability.</p>
<p><strong>Credits</strong></p>
<p>Thanks for your time and efforts.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:51:15.877",
"Id": "496340",
"Score": "0",
"body": "Great game! i was struggling with fltk callbacks without a button and this helped me out so thank you!"
}
] |
[
{
"body": "<h1>Don't <code>catch</code> errors you can't handle</h1>\n<p>You should catch exceptions if you can do something useful with them. However, just printing an error message and then quitting immediately is not useful. If you don't catch an exception, that is what will happen by default anyway.</p>\n<h1>Don't specify the window position</h1>\n<p>You should let the window manager decide the initial position of your window. It knows better where the user would like the window, and can use heuristics like where the mouse cursor is currently, where there is still unused space on the screen, and so on.</p>\n<h1>Make game menu buttons member variables</h1>\n<p>Why are the three buttons added to <code>game_menu</code> created with <code>new</code>, when other buttons are just member variables of <code>Snake_window</code>? Looking at your code it seems <code>Window::attach()</code> also has an overload that takes a reference to a <code>Button</code>, so that should just work, and will be more consistent.</p>\n<h1>Move the help text out of the constructor, use a raw string literal</h1>\n<p>The constructor of <code>Snake_window()</code> contains mostly logic for adding widgets to the window, but there's a huge blob of help text in the middle of it. It might make sense to move the text itself out of this function, and put it in a static variable. You can also use a raw <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">string literal</a> so you don't have to write quote characters and escape newlines anymore:</p>\n<pre><code>static const char *help_text =\nR"( SNAKE GAME\n Snake is a video game concept where the player maneuvers a line\nthat grows in length, with the line itself being a primary obstacle.\nThe concept originated in the 1976 arcade game Blockade.\n...\n ADDITIONAL NOTES\n Good luck on the game, try to eat as much as you can!\n)";\n\n...\n\nSnake_window::Snake_window(...)\n : ...\n{\n ...\n help_box.put(help_text);\n ...\n}\n</code></pre>\n<h1>Remove debug statements</h1>\n<p>In <code>Snake_window::handle()</code> you are printing something everytime the snake changes direction. It looks like you used this for debugging? You should remove this in production code. There are other examples throughout your code that prints to <code>cout</code> that should be removed.</p>\n<h1>Give a name to <code>reference_to<Snake_window>(pw)</code></h1>\n<p>It's a bit unfortunate that FLTK doesn't support callbacks to non-static member functions. So now you have to write <code>reference_to<Snake_window>(pw)</code> to get the class instance. But it's a bit long and cryptic. Consider giving it a name, like <code>self</code>, which should be reasonably self-explanatory:</p>\n<pre><code>void Snake_window::cb_pause(Address, Address pw)\n{\n auto self = reference_to<Snake_window>(pw);\n self.pause();\n self.game();\n}\n</code></pre>\n<h1>The body of the snake</h1>\n<p>This is where it went horribly wrong. Let's look at how the body is declared:</p>\n<pre><code>Vector_ref<Rectangle> body;\n</code></pre>\n<p>I see that <code>Vector_ref</code> is kind of a wrapper around <code>std::vector<T *></code>. But why do you need to store the <code>Rectangle</code>s by pointer or reference? Looking at your GitHub repository, it seems <code>Rectangle</code> derives from <code>Shape</code>, but you deleted the copy constructor and copy assignment operator. I don't see a reason for that. If you want to prevent someone from copying a bare <code>Shape</code>, it is better to make the copy operations <code>protected</code>, like so:</p>\n<pre><code>class Shape {\n ...\nprotected:\n Shape(const Shape &other) = default;\n Shape &operator=(const Shape &other) = default;\n ...\n};\n</code></pre>\n<p>Once you have that, you should be able to create a vector of <code>Rectangle</code>s like so:</p>\n<pre><code>std::vector<Rectangle> body;\n</code></pre>\n<p>But there are other issues, which I'll discuss below:</p>\n<h1>Use a <code>std::deque<></code> to store the body positions</h1>\n<p>You are using a vector, and whenever you remove the tail piece and add a new head piece, you have to shift all the positions in the body. That's quite an expensive operation. Your own <code>for</code>-loop is very inefficient, because you move each point twice. If you use a <code>std::vector</code>, you could use <code>pop_back()</code> and <code>emplace()</code> like so:</p>\n<pre><code>void Snake::move_forward() {\n body.pop_back();\n body.emplace(body.begin(), { /* new head constructor arguments */ });\n}\n</code></pre>\n<p>But then <code>std::vector</code> will just shift all element for you. What you ideally want is to keep all the body positions as they are, and then remove the tail and add a new head in O(1) time. That can be done by using either a <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a>, but if you want something that works more like a <code>std::vector</code>, a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a> is ideal. Your code would then look like:</p>\n<pre><code>void Snake::move_forward() {\n body.pop_back();\n body.emplace_front({ /* new head constructor arguments */ });\n}\n</code></pre>\n<p>And again:</p>\n<h1>Avoid moving points unnecessarily</h1>\n<p>I see this pattern being used in several places:</p>\n<pre><code>fruit.move(-fruit.point(0).x, -fruit.point(0).y); // Top-left angle of window\nfruit.move(fruit_xy.x, fruit_xy.y);\n</code></pre>\n<p>Basically what you want is setting the fruit position to <code>fruit_xy</code>. Why not create a member function of <code>Rectangle</code> that allows direct setting of the desired position, so you can write the following:</p>\n<pre><code>fruit.set_xy(fruit_xy);\n</code></pre>\n<h1>Simplifying growing the body</h1>\n<p>Instead of having a separate function to grow the body, which first moves the snake (which removes its old tail), and then add the old tail back, consider changing <code>Snake::move_forward()</code> to optionally not remove the tail. I would do this by adding a member variable to <code>Snake</code> that indicates how many elements the body needs to grow with:</p>\n<pre><code>class Snake {\n ...\npublic:\n void grow(size_t length) { to_grow += length; }\nprivate:\n size_t to_grow;\n};\n</code></pre>\n<p>And then in <code>Snake::move_forward()</code>, do something like this:</p>\n<pre><code>void Snake::move_forward() {\n if (to_grow)\n to_grow--;\n else\n body.pop_back();\n\n body.emplace_front({ /* new head constructor arguments */ });\n}\n</code></pre>\n<h1>Use <code>assert()</code> to check for things that shouldn't be possible</h1>\n<p>I see several member functions of <code>Snake</code> that check whether <code>body.begin() == body.end()</code>. That's only true if the length of the body is zero. But the constructor of <code>Snake</code> already throws an error if you specify a length that is less than 1. So this check if in principle unnecessary. But, it's good practice to encode your assumptions using <code>assert()</code> statements, so these assumptions can be checked in debug builds, but won't slow down release builds, like so:</p>\n<pre><code>#include <cassert>\n...\nconst Rectangle &Snake::body_head() const {\n assert(head_ind >= 0 && head_ind < body.size());\n return body[head_ind];\n}\n</code></pre>\n<p>Although it would be simpler to either use <code>body.front()</code> to get the head element, and write:</p>\n<pre><code>const Rectangle &Snake::body_head() const {\n assert(!body.empty());\n return body.front();\n}\n</code></pre>\n<p>Although personally, in this particular case, if it is clear that the Snake always has a non-zero body length, I wouldn't write those <code>assert()</code> statements at all; they just clutter the code, and tools like <a href=\"https://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a> can catch out-of-bounds errors as well.</p>\n<p>Regardless, I would use an assert in the constructor of <code>Snake</code> to check the length parameter instead of throwing an exception.</p>\n<p>Asserts should generally be used to check for assumptions about your own code. But use <code>if (...)</code> plus some kind of error reporting (like throwing an exception) when the condition is something that depends on user input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T04:22:25.553",
"Id": "486201",
"Score": "1",
"body": "Thank you a lot for your deep analysis! I'll take your notes into account, and will make changes in the code to make it better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T21:16:08.793",
"Id": "248255",
"ParentId": "248237",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248255",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:01:12.380",
"Id": "248237",
"Score": "4",
"Tags": [
"c++",
"game",
"snake-game",
"fltk"
],
"Title": "Snake game using C++ and FLTK"
}
|
248237
|
<p>I'm refactoring functions trying to do more of a in-line aproach.</p>
<pre><code> private int GetRandomNumberHigherThanHalf()
{
double randomNumber= Random.NextDouble();
if (randomNumber < 0.5)
throw new Exception("randomNumber is lower than 0.5");
return randomNumber;
}
</code></pre>
<p>Any ideas about how can I refactor the function above to one line? It has to trhow an Exception and return the number generated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:28:14.300",
"Id": "486140",
"Score": "0",
"body": "Not sure why you want to throw potentially half of the times. \n\n `return randomNumber > 0.5 ? randomNumber : 1 - randomNumber`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:50:32.727",
"Id": "486141",
"Score": "0",
"body": "I've possibly over-simplified the code to be more \"dummy\", it is actually a database connection beign stablished"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:57:28.093",
"Id": "486143",
"Score": "0",
"body": "Then I don't think it is worth it. Readability > concision ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:46:26.417",
"Id": "486147",
"Score": "2",
"body": "This question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T16:04:30.407",
"Id": "486160",
"Score": "0",
"body": "@Mast Thank you for the clarification"
}
] |
[
{
"body": "<p>I'm going to take your request at face value. Add an extension method:</p>\n<pre><code>public static class UselessExtensions\n{\n public static T ThrowIf<T>(this T input, Func<T, bool> predicate, string message)\n => predicate(input) ? throw new Exception(message) : input;\n}\n</code></pre>\n<p>Then use that in your method:</p>\n<pre><code>// One liner\nprivate double GetRandomNumberHigherThanHalf()\n => Random.NextDouble().ThrowIf(r => r < 0.5, "randomNumber is lower than 0.5");\n</code></pre>\n<p>Your original code doesn't compile, there is no implicit conversion from <code>double</code> to <code>int</code>.</p>\n<hr />\n<p>Would you want to do this? No. Lines of code is a bad metric. You want your code to be as readable as possible. Not to be as short as possible. In this case, it stays readable because the extension method is well-named. You want to aim for your code being as concise as possible without affecting how easy it is to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:53:09.873",
"Id": "486142",
"Score": "0",
"body": "It realy does not compile, my bad. But, why wouldn't I try to make it a one liner? I've got a quite few functions like that eventually increases the class file size."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:43:49.393",
"Id": "248241",
"ParentId": "248240",
"Score": "0"
}
},
{
"body": "<p>You are a new contributor and we try to be nice, but one can only be so nice when the code AND the most of your reasoning is so poor.</p>\n<p>THIS SOUNDS LIKE HOMEWORK with all the restrictions you are giving.</p>\n<p>You seem to be obsessed with making this a one-liner. Such obsessions will weigh you down and lead to poor code. Use one-liners where they make the best sense in a short, simple call.</p>\n<p>You return an int but use a double internally. If you cast the double to an int, your method will always (A) return 0 or (B) throw an exception.</p>\n<p>There is the Principle of Least Astonishment and your code violates in 2 ways. If a caller wants to GetRandomNumberHigherThanHalf, then it would astonish them to throw an exception. They would expect the method would correctly keep trying until it finds the right value to return. And the 2nd violation is that your method could return 0.5, which is NOT HIGHER than Half.</p>\n<p>Make up your mind if you really want a Double or an int. If you want an int, you may want it to fall within a range, so you could use this <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=netcore-3.1#System_Random_Next_System_Int32_System_Int32_\" rel=\"nofollow noreferrer\">Next overload</a>.</p>\n<p>If you take time to read the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netcore-3.1\" rel=\"nofollow noreferrer\">Random constructor</a> comments, look at the bottom at this text:</p>\n<blockquote>\n<p>Another option is to instantiate a single Random object that you use\nto generate all the random numbers in your application. This yields\nslightly better performance, since instantiating a random number\ngenerator is fairly expensive.</p>\n</blockquote>\n<p>With your method, if you quickly call it repeatedly, then it will not return a different random number, but rather the same number. If you instantiated a Random instance once for your class, then you would not have this problem.</p>\n<p>Again, if you clearly think out what you want ... do you want a Double > 0.5 but less than 1.0, or do you want a Double scaled between 2 values, or do you want an integer falling between 2 values, then pick the right Random method. And I would not throw if the value is less than 0.5; rather I would simply add 0.5 to the returned value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:33:11.867",
"Id": "486145",
"Score": "0",
"body": "I understand. Thank you for taking the time to write an response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:03:59.627",
"Id": "248242",
"ParentId": "248240",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "248241",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:14:03.103",
"Id": "248240",
"Score": "-1",
"Tags": [
"c#",
".net"
],
"Title": "How can I refactor a function to be inline?"
}
|
248240
|
<p>A day ago I started a c# project where I bruteforce passwords. Passwords can be both integers and strings. In the code I check how many characters the password has. Whilst this is kinda cheating it would take too long to crack otherwise. I am posting it here to see if it's good enough.</p>
<pre><code>using System;
namespace Hacking_Project
{
class Program
{
static void Main()
{
//Console Color
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
//If password is found
bool done = false;
//If the password is a string, not the best name but ok
bool yes = false;
//If the Guessed password is the same number of characters as the original password
int pass = 0;
//Guessed password
string pass_check = "";
//Possible characters for the password
char[] pos = {'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'};
Console.WriteLine("What is the password?");
//Asking for the password to crack
string password = Console.ReadLine();
//How much characters does the password has. I know that this is kinda cheating, but then the bruteforce would take to much
int digits = password.Length;
//Initialising the random number generator
Random rand = new Random();
//The choices that the calculator will take for the guessed password(int)
int[] choices = new int[digits];
//The choices that the calculator will take for the guessed password(string)
char[] choices1 = new char[digits];
//If the password is a string
for (int i = 0; i < pos.Length; i++)
{
if (password.Contains(pos[i]))
{
password = password.ToLower();
yes = true;
}
}
//The Cracking Part
while (done == false)
{
if (!yes)
{
for (int i = 0; i < digits; i++)
{
choices[i] = rand.Next(0, 9);
pass_check += choices[i];
pass++;
//Console Color
Console.ForegroundColor = ConsoleColor.DarkYellow;
if (pass != digits)
{
Console.Write(choices[i]);
}
else
{
Console.Write(choices[i] + ", ");
}
}
}
else
{
for (int i = 0; i < digits; i++)
{
choices1[i] = pos[rand.Next(pos.Length)];
pass_check += choices1[i];
pass++;
Console.ForegroundColor = ConsoleColor.DarkYellow;
if (pass != digits)
{
Console.Write(choices1[i]);
}
else
{
Console.Write(choices1[i] + ", ");
}
}
}
pass = 0;
if (pass_check == password)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\n\nThe password is: ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(pass_check);
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\n\nThe original password is: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(password);
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("\n\nDo you want to restart?");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(" => ");
string restart = Console.ReadLine();
restart = restart.ToLower();
if (restart == "yes")
{
Main();
}
else if (restart == "no")
{
done = true;
}
}
//If the password is not found, quessed password is set to empty
else
{
pass_check = "";
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T15:23:51.853",
"Id": "486153",
"Score": "1",
"body": "(This is not directed at you Dragos) I do not know why this has gained a close vote. Brute forcing a password is pretty common knowledge at this point, demanding a user explaining it in depth seems pretty unconstructive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T15:37:13.920",
"Id": "486156",
"Score": "1",
"body": "One tip on comments (e.g. `//Initialising the random number generator`) Don't explain what you are doing, explain **why** you are doing it. I didn't look at the code too much, but my first thought with seeing `Random` is that you're randomly generating the characters you're generating which can lead to both duplicate and missed guesses, which would add additional time to your algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T15:41:26.920",
"Id": "486157",
"Score": "0",
"body": "I wanted to update the post later, so that already guessed passwords wont be duplicated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:01:08.040",
"Id": "486238",
"Score": "0",
"body": "Do you really need to use randomization here? A rough estimate would be that half of the times you're going to need to check at least half of all the passwords anyway, so wouldn't it be usually faster to just check all of them in order (considering the time saved on randomization and duplicate guesses)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:03:28.263",
"Id": "486239",
"Score": "0",
"body": "Also, I think there's probably no need to specify the length in advance, since the vast majority of passwords of length \"up to N\" are of length exactly N. (so you can just iteratively increase the length of the password you're trying). For example, there are about 208 billion passwords of 8 lowercase english letters, but only 8 billion passwords of 1..7 letters."
}
] |
[
{
"body": "<p>Disclaimer: below is just my opinion, please do not treat it as a source of truth. Also, I am assuming that the code works exactly as expected - I will not dwell into performance or vailidity.</p>\n<ul>\n<li>Too many comments, instead try to refactor the code to be more explanatory. Uncle Bob said it best: 'A comment is a failure to express yourself in code' (unless it's a 'why' that cannot be explained of course).</li>\n<li>Devide the code to small and single responsibility functions/classes, see <a href=\"https://herbertograca.com/2016/09/03/clean-code-3-functions-by-robert-c-martin-uncle-bob/\" rel=\"nofollow noreferrer\">here</a> for guidance.</li>\n<li>Console related operations can be delegated to a separate class (a wrapper) so it can be easily extended in the future to handle input/output from other sources. Also, in order to avoid duplication (e.g. writing <code>\\n\\n</code> infront of strings can be abstracted away).</li>\n<li>Variable names should indicate the content (unless it's very obvious). You wrote a comment 'not the best name but ok', yes - it's not the best name but I don't think it is 'ok'. Half way through the code I had to scroll up to check what does this variable mean, this is not right.\nSimilar goes for variables like <code>choices1</code>, <code>digits</code>, <code>pos</code> and others.</li>\n<li><code>while (done == false)</code> could be <code>while(!done)</code> it's both shorter and more explanatory 'in english'.</li>\n<li>Use <code>Console.WriteLine</code> instead of adding <code>\\n\\n</code> (you can even do <code>Console.WriteLine("")</code>.</li>\n<li>Use while loop instead of recursion for <code>Main</code>. Two reasons for that: you can exceed the stacks (unlikely for humans but any bot can do it easily) AND it would be more expected by others to see a <a href=\"https://www.informit.com/articles/article.aspx?p=2167437&seqNum=2#:%7E:text=The%20game%20loop%20is%20the,again%20until%20the%20user%20quits.&text=If%20a%20game%20runs%20at,completes%2060%20iterations%20every%20second.\" rel=\"nofollow noreferrer\">game loop</a> rather than recursive function.</li>\n<li>Display possible input values for restart, user might try <code>Y</code>, which will not work.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T22:20:48.577",
"Id": "248294",
"ParentId": "248243",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:41:54.890",
"Id": "248243",
"Score": "2",
"Tags": [
"c#",
"security"
],
"Title": "Bruteforcing passwords"
}
|
248243
|
<p>I have a requirement where I get totalAmount and how much parts to divide that amount into as inputs. For the outputresponse i am using builder pattern and also avoiding null fields. Total amount is a big decimal (if null or less than 0, throw exception) and number of inputs can range between 1-3 (if outside of this range or non numeric, throw exception). I have written this code, but I am not convinced and think there may be a cleaner and better way that is also easy to understand just by looking at the code. Also while splitting, whatever additional cents are left, that would be added to 1st amount.</p>
<p>eg. if 100.01 is total amount that i have to divide into 3 parts, i should get 33.35 for first amount and 33.33 for recurring amounts. Please advise if there is a cleaner and better way to achieve this.</p>
<pre><code>public OutputResponse splitAmount(BigDecimal totalAmount, int divideInto) {
if (!(1 <= divideInto && 3 >= divideInto)) {
throw new Exception();
}
OutputResponse outputResponse;
if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal recurringAmounts = null;
BigDecimal firstAmount = totalAmount;
if (divideInto > 1) {
recurringAmounts = totalAmount.divide(BigDecimal.valueOf(divideInto), 2, RoundingMode.FLOOR);
firstAmount = totalAmount.subtract(recurringAmounts.multiply(new BigDecimal(divideInto - 1)));
}
outputResponse = OutputResponse.builder()
.firstAmt(firstAmount)
.secondPmtAmt(recurringAmounts)
.build();
if (divideInto > 2) {
outputResponse.setThirdPmtAmt(recurringAmounts);
}
} else {
throw new Exception();
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Format</h1>\n<p>Use proper indentation, after a curly brace use a tab or 4 spaces.</p>\n<h1>Readability</h1>\n<p>Add a message with your exceptions. It's a terrible practice to just throw a regular exception and no message. You'd have to look at the line numbers in the stack trace in order to know where the exception message came from. It's better to have a user-friendly message describing the issue that occurred.</p>\n<p>Do not mix <code>!</code> with <code>></code> or <code><</code>. It's confusing to read.</p>\n<p>Try to use negative or positive validation. For example, be consistent either checking if the inputs are wrong, or always check that their right. In other words have your error messages all at the top or bottom.</p>\n<p><code>OutputResponse</code> Is not a good name. It's meaningless. Assuming this is a class you made, consider changing the name. Also consider using an <code>ArrayList</code> rather than separate fields, that way you don't need to refactor to include a 4+ separations.</p>\n<h1>Example code:</h1>\n<pre><code>public OutputResponse splitAmount(BigDecimal totalAmount, int divideInto) {\n if ((1 > divideInto || 3 < divideInto)) {\n throw new Exception("Divide into must be between 1-3");\n }\n \n if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO <= 0) {\n throw new Exception("Total amount must be a number greater than 0!");\n }\n \n BigDecimal recurringAmounts = null;\n BigDecimal firstAmount = totalAmount;\n if (divideInto > 1) {\n recurringAmounts = totalAmount.divide(BigDecimal.valueOf(divideInto), 2, RoundingMode.FLOOR);\n firstAmount = totalAmount.subtract(recurringAmounts.multiply(new BigDecimal(divideInto - 1)));\n }\n\n OutputResponse outputResponse = OutputResponse.builder()\n .firstAmt(firstAmount)\n .secondPmtAmt(recurringAmounts)\n .build();\n\n if (divideInto > 2) {\n outputResponse.setThirdPmtAmt(recurringAmounts);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:24:24.637",
"Id": "248251",
"ParentId": "248249",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T17:04:36.527",
"Id": "248249",
"Score": "2",
"Tags": [
"java"
],
"Title": "Split amount into inputs passed"
}
|
248249
|
<p>I has <code>div</code> block <code>feedList</code> which contains <code>feedItems</code>. Now to fill <code>feedList</code> with data (<code>feedItems</code>) i am using while loop. In future it will js which get data from backend dynamically.</p>
<p>I created 2 buttons, which is used to border num of <code>feedItems</code> in <code>feedList</code>. One is "5", another is "10". To border num of <code>feedItems</code> i use function which called on each event of adding <code>feedItem</code> <code>div</code> in <code>feedList</code>. You can see that this function check how much <code>feedItems</code> now in <code>feedList</code>: if it more than 5 - it remove old <code>feedItem</code> from <code>feedList</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var removeIf5 = function (event) {
alert("last div removed if length more than 5");
};
var removeIf10 = function (event) {
alert("last div removed if length more than 10");
};
document.getElementById("list5Items")
.addEventListener("click" , function(e){
alert("1");
feedList.removeEventListener("DOMNodeInserted", removeIf5, false);
feedList.removeEventListener("DOMNodeInserted", removeIf10, false);
feedList.addEventListener("DOMNodeInserted", removeIf5, false);
});
document.getElementById("list10Items")
.addEventListener("click" , function(e){
alert("2");
feedList.removeEventListener("DOMNodeInserted", removeIf5, false);
feedList.removeEventListener("DOMNodeInserted", removeIf10, false);
feedList.addEventListener("DOMNodeInserted", removeIf10, false);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="feedField">
<div class="feedNav">
<div class="button-group-2">
<input type="submit" id="list10Items" value="10"/>
<input type="submit" id="list5Items" value="5"/>
</div>
</div>
<div class="feedList">
<div class="feedItem">itemA</div>
<div class="feedItem">itemB</div>
<div class="feedItem">itemC</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Problem in that i create 2 functions for same work: they used to remove elements, and different only in border number. One remove if <code>feedList</code> length is more than 5, another - more than 10.</p>
<p>How i can rewrite my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T22:30:03.370",
"Id": "486193",
"Score": "0",
"body": "When I click either button I see an error in the console: \"_Uncaught ReferenceError: feedList is not defined_\". Is the intention to reference the DOM element `<div class=\"feedList\"></div>`? (which might work if the `id` attribute was set)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T23:01:13.887",
"Id": "486195",
"Score": "0",
"body": "Honestly removing items from a list seems strange. Why not render a slice of the array? Also is the default behaviour to list all of the items?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:43:30.230",
"Id": "486212",
"Score": "0",
"body": "@TedBrownlow, thats why i am asking that question: i got some solution, but thing that it's ugly. What about array? You suggest save all items in array and regular render just some of them (slice of array)? Default behaviour is to list items in realtime: when you got new item you render that one in DOM and remove unneeded old."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T19:16:45.923",
"Id": "248253",
"Score": "1",
"Tags": [
"javascript",
"html",
"event-handling"
],
"Title": "Dynamic adding and removing div elements using event streams (eventlistners)"
}
|
248253
|
<p>In <a href="https://codereview.stackexchange.com/q/247936/228314">another question</a> the user was determining the probability of having a streak of 6 heads or 6 tails in 100 coin flips. To find the probability they would generate 100 random coin flips and determine if there was a streak. They would test 10,000 such sequences of 100 flips to find that there was about an 80% chance of there being a streak in 100 coin flips.</p>
<p>I decided to compute the exact probability. For 100 flips there are <span class="math-container">\$2^{100}\$</span> possible outcomes. To determine the percentage I compute how many of them have a streak, and then divide by <span class="math-container">\$2^{100}\$</span>.</p>
<p>My naive solution gets me the number for 20 flips in few seconds:</p>
<pre><code>from itertools import product
def naive(flips, streak):
return sum('h' * streak in ''.join(p) or
't' * streak in ''.join(p)
for p in product('ht', repeat=flips))
</code></pre>
<p>Result:</p>
<pre><code>>>> naive(20, 6)
248384
</code></pre>
<p>My fast solution gets me the number for 100 flips instantly:</p>
<pre><code>from collections import Counter
def fast(flips, streak):
needles = 'h' * streak, 't' * streak
groups = {'-' * streak: 1}
total = 0
for i in range(flips):
next_groups = Counter()
for ending, count in groups.items():
for coin in 'ht':
new_ending = ending[1:] + coin
if new_ending in needles:
total += count * 2**(flips - 1 - i)
else:
next_groups[new_ending] += count
groups = next_groups
return total
</code></pre>
<p>The idea is to have a pool of still ongoing games, but grouped by the last six flips, and counts for how often that group has appeared. Then do the 100 flips one at a time, updating the groups and their counts. Any group that at some point ends with a streak doesn't continue playing, instead I add it to the total result. The group occurred <code>count</code> times, there are <code>flips - 1 - i</code> flips left, and they can be anything, so multiply <code>count</code> with 2<sup>flips - 1 - i</sup>.</p>
<p>Results (note that the result for 20 flips is the same as with the naive solution):</p>
<pre><code>>>> fast(20, 6)
248384
>>> fast(100, 6)
1022766552856718355261682015984
</code></pre>
<p>And dividing by 2<sup>100</sup> gives me the percentage similar to those of the linked-to experiments:</p>
<pre><code>>>> 100 * fast(100, 6) / 2**100
80.68205487163246
</code></pre>
<p>Any comments, suggestions for improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T22:25:37.377",
"Id": "486192",
"Score": "0",
"body": "What is the aim, to make it as fast as possible? Is just using math an option?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T22:52:51.973",
"Id": "486194",
"Score": "1",
"body": "@Peilonrayz Yes, a math solution sounds very interesting. I'm not entirely sure what I'm looking for, as I believe it's already fairly good. But I've seen reviews with things that hadn't occurred to me, so maybe someone can surprise me here as well. Maybe style comments, as I've had people complain that my solutions are unreadable :-). It's kind of an experiment."
}
] |
[
{
"body": "<p>Your code looks good. It's a little hard to read, but given the context that is ok!\nWe can also see that if <code>new_ending</code> is never in <code>needles</code> then your code looks like it will run in <span class=\"math-container\">\\$O(f2^s)\\$</span> time, where <span class=\"math-container\">\\$f\\$</span> is <code>flips</code> and <span class=\"math-container\">\\$s\\$</span> is <code>streak</code>.</p>\n<p>Whilst I can see the code in <code>if new_ending in needles:</code> will reduce the the time your code takes to run.\nFor example when streak=2 it will allow your code to run in linear time, it's not going to help much on bigger numbers - the code will still tend to <span class=\"math-container\">\\$O(f2^s)\\$</span>.</p>\n<p>We can see how you're performing this optimization in the following.\nSince you are not searching the descendent of HH, TT, HTT, THH, etc. it cuts down how big the tree will get.</p>\n<p><a href=\"https://i.stack.imgur.com/no5gE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/no5gE.png\" alt=\"enter image description here\" /></a></p>\n<p>We can clearly see that tails is just the inverse of heads.\nIf we focus on heads and split the 'base' and 'tail' (the repeating results) we get the following:</p>\n<pre class=\"lang-none prettyprint-override\"><code> HH 1/2^2\nH TT 1/2^3\nHT HH 1/2^4\nHTH TT 1/2^5\nHTHT HH 1/2^6\n</code></pre>\n<p>Whilst it's cool it runs in linear time, it's not really that interesting.\nAnd so when streak=2 the total chance for <span class=\"math-container\">\\$f\\$</span> flips is:</p>\n<p><span class=\"math-container\">$$\\Sigma_{n=2}^f \\frac{2}{2^n}$$</span></p>\n<p>However when we look at streak=3 we can see the start of a distinguishing pattern.</p>\n<pre class=\"lang-none prettyprint-override\"><code> HHH 1/2^3\nH TTT 1/2^4\nHH TTT 1/2^5\nHT HHH 1/2^5\nHHT HHH 1/2^6\nHTH TTT 1/2^6\nHTT HHH 1/2^6\nHHTH TTT 1/2^7\nHHTT HHH 1/2^7\nHTHH TTT 1/2^7\nHTHT HHH 1/2^7\nHTTH TTT 1/2^7\n</code></pre>\n<p>If we take the count of each size then we get:</p>\n<pre class=\"lang-none prettyprint-override\"><code>3: 1\n4: 1\n5: 2\n6: 3\n7: 5\n</code></pre>\n<p>This is cool because it's the start of the <a href=\"https://oeis.org/search?q=1%2C1%2C2%2C3%2C5&sort=&language=&go=Search\" rel=\"nofollow noreferrer\">Fibonacci numbers</a>.\nI have verified that the first 30 values are the same.\nAnd so we now can assume we have an equation for streak=3:</p>\n<p><span class=\"math-container\">$$\\Sigma_{n=3}^f \\frac{2F(n-2)}{2^n}$$</span></p>\n<p>Doing the same thing for streak=4,5,6,10 give the following sequences:</p>\n<ul>\n<li>4 - <a href=\"https://oeis.org/search?q=1%2C1%2C2%2C4%2C7%2C13%2C24%2C44&sort=&language=&go=Search\" rel=\"nofollow noreferrer\">Tribonacci</a></li>\n<li>5 - <a href=\"https://oeis.org/search?q=1%2C1%2C2%2C4%2C8%2C15%2C29%2C56&sort=&language=&go=Search\" rel=\"nofollow noreferrer\">Tetranacci</a></li>\n<li>6 - <a href=\"https://oeis.org/search?q=1%2C1%2C2%2C4%2C8%2C16%2C31%2C61&sort=&language=&go=Search\" rel=\"nofollow noreferrer\">Pentanacci</a></li>\n<li>10 - <a href=\"https://oeis.org/search?q=1%2C+1%2C+2%2C+4%2C+8%2C+16%2C+32%2C+64%2C+128%2C+256%2C+511&sort=&language=&go=Search\" rel=\"nofollow noreferrer\">Fibonacci 9-step</a></li>\n</ul>\n<p>In all this is a pretty compelling pattern.\nAnd so we can write an algorithm to run in <span class=\"math-container\">\\$O(fs)\\$</span> time where <span class=\"math-container\">\\$f\\$</span> is flips and <span class=\"math-container\">\\$s\\$</span> is streaks.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport itertools\nfrom fractions import Fraction\n\n\ndef fibonacci_nth(size):\n store = collections.deque([0] * size, size)\n store.append(1)\n while True:\n yield store[-1]\n store.append(sum(store))\n\n\ndef coin_chance(flips, streak):\n if streak <= 0 or streak % 1:\n raise ValueError("streak must be a positive integer")\n if flips < 0 or flips % 1:\n raise ValueError("flips must be a non-negative integer")\n if streak == 1:\n return Fraction(flips != 0, 1)\n sequence = (\n Fraction(2 * numerator, 2 ** exponent)\n for exponent, numerator in enumerate(fibonacci_nth(streak - 1), streak)\n )\n return sum(itertools.islice(sequence, flips - streak + 1))\n\n\n# Code to get OEIS sequences\ndef funky_finder(depth, size):\n desired = (['H'] * size, ['T'] * size)\n stack = [iter("HT")]\n stack_value = []\n while stack:\n try:\n coin = next(stack[-1])\n except StopIteration:\n stack.pop()\n if stack_value:\n stack_value.pop()\n continue\n _stack_value = stack_value + [coin]\n if _stack_value[-size:] in desired:\n yield ''.join(_stack_value)\n elif len(stack) < depth:\n stack_value.append(coin)\n stack.append(iter('HT'))\n\n\n# I know, I know. But I was using this in a REPL!\nsize = 3; [i // 2 for i in sorted(collections.Counter(len(i) - size for i in funky_finder(20 + size, size)).values())]\n</code></pre>\n<pre><code>>>> 100 * fast(20, 6) / 2**20\n23.687744140625\n>>> 100 * float(coin_chance(20, 6))\n23.687744140625\n\n>>> 100 * fast(100, 6) / 2**100\n80.68205487163246\n>>> 100 * float(coin_chance(100, 6))\n80.68205487163246\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T02:25:15.340",
"Id": "486198",
"Score": "0",
"body": "Will have a closer look later, looks intriguing! Question already: Why \\$O(2^f)\\$? My `groups` never grows larger than \\$2^{streak}\\$, so I'd say \\$O(2^{streak}f)\\$ operations. And \\$O(2^{streak}f^2)\\$ time, as the operations are adding f-bit numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T02:31:34.690",
"Id": "486200",
"Score": "0",
"body": "@superbrain Yes, on second look your code looks like it may not be \\$O(2^f)\\$. Could possibly be, as you say, \\$O(f2^s)\\$ however I'm too tired to verify that. I'll edit my answer to address this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T13:05:35.123",
"Id": "486232",
"Score": "0",
"body": "To clarify: I wouldn't call my `if new_ending in needles:` an optimization. It's a simplification :-). Or rather a non-complification. With s=6, only two of 64 endings don't continue playing. You're right, that doesn't matter speed-wise. That was never the point. The point was that I didn't want to additionally keep track of whether a streak has been found already. Though I've [done that now](https://repl.it/repls/AnchoredWirelessFilename#main.py) and it was easier than I had guessed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T13:40:31.183",
"Id": "486234",
"Score": "0",
"body": "Cool observation about the 'naccis. Proof would be nice, if not too complicated, but I'm convinced enough :-). Using `deque` like that is neat. Slight nitpick: streak=0 should lead to probability 100%. My naive solution does that. Though I admit it's better to reject it (like you do) than to fail it (like I just realized my fast solution does)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T14:48:37.190",
"Id": "486235",
"Score": "0",
"body": "Could also init the deque with just `[1]`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T01:04:58.547",
"Id": "248258",
"ParentId": "248254",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248258",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T20:02:46.363",
"Id": "248254",
"Score": "4",
"Tags": [
"python"
],
"Title": "Exact probability for coin flip streaks"
}
|
248254
|
<p>This is <code>citty.py</code>, part of the <a href="https://gitlab.com/aghast/citty" rel="nofollow noreferrer"><code>citty</code> repository</a>. It's formatted using <a href="https://github.com/psf/black" rel="nofollow noreferrer"><code>black</code></a>, so I'm not super worried about small style items.</p>
<p>I'd like a review with suggestions for other, better practices -- choice of technologies or implementations (e.g., "use xml instead of json", or "use goodpackage instead of badpackage"), approach to structuring, etc.</p>
<p>(Note: I'm not going to start using XML, that was just an example.)</p>
<pre><code>#! /usr/bin/env python3
# vim: fileencoding: utf-8
""" citty -- CI driver in your terminal.
Implements basic test & wait continuous integration,
and codes the results to stdout using color escape
sequences.
Usage:
citty add <path> [--name=<name>] [-f | --force]
citty delete <name>
citty delete --all
citty list [<name> | <path>]
citty -h | --help
citty --version
citty
Options:
-f --force Force it! Overwrite an old project if needed.
-h --help Show this screen.
--name=<name> Project name (default: directory).
--version Show version.
"""
import json
import os
import platform
import subprocess
import sys
import time
from pathlib import Path
from pkg_resources import iter_entry_points as iter_ep
from docopt import docopt
__version__ = "0.0.3"
ON_WINDOWS = platform.system() == "Windows"
CITTY = "citty"
_CITTY = "_" + CITTY if ON_WINDOWS else "." + CITTY
ADD = "add"
APPDATA = "APPDATA"
COMMAND = "command"
DELETE = "delete"
FAILING = "FAILING"
LIST = "list"
MAKE_TEST = "make_test"
NAME = "name"
NORMAL = "NORMAL"
PASSING = "PASSING"
PATH = "path"
PENDING = "PENDING"
PROJECTS = "projects"
SLEEP = "sleep"
SLEEP_TIME = 60
STATUS = "status"
TESTFUNCS = "testfuncs"
VERSION = "citty version " + __version__
XDG_CONFIG_HOME = "XDG_CONFIG_HOME"
def citty_add(arguments):
""" Subcommand: 'add'.
Add a project to the citty config file.
"""
assert arguments[ADD], "'citty add' should be the command line"
assert arguments["<path>"], "<path> must be specified"
name = arguments["--name"]
path = Path(arguments["<path>"]).expanduser().resolve()
if not name:
name = path.name
config = load_config()
if any(proj[NAME] == name for proj in config[PROJECTS]):
if not arguments["--force"]:
print("Cannot add '{}' -- that project already exists!".format(name))
sys.exit(1)
config[PROJECTS][:] = [d for d in config[PROJECTS] if d[NAME] != name]
project = {NAME: name, PATH: str(path), COMMAND: MAKE_TEST, STATUS: PENDING}
config[PROJECTS].append(project)
save_config(config)
def citty_delete(arguments):
""" Subcommand: 'delete'.
Delete a project, or all projects, from the citty config file.
"""
assert arguments[DELETE], "'citty delete' must be specified."
config = load_config()
projects = config[PROJECTS]
if arguments["--all"]:
projects[:] = []
else:
name = arguments["<name>"]
projects[:] = [p for p in projects if p[NAME] != name]
save_config(config)
def citty_list(arguments):
""" Subcommand: 'list'.
List all projects, or projects matching a name, from the citty
config file.
"""
assert arguments[LIST], "'citty list' must be specified."
config = load_config()
name = arguments["<name>"]
homedir = Path().home().resolve()
for project in config[PROJECTS]:
path = project[PATH]
if name and not (
name == project[NAME] or path.startswith(name) or name in path
):
continue
try:
hp = Path(path).relative_to(homedir)
disp = "~" / hp
except ValueError:
disp = path
print("{:>15s} : {:<10s} : {}".format(project[NAME], project[COMMAND], disp))
def citty_loop(arguments):
""" Run a continuous-integration loop, forever. """
while True:
try:
config = load_config()
ci_build(config)
time.sleep(config[SLEEP])
except KeyboardInterrupt:
break
def config_file_path() -> Path:
""" Determine and return the path to where the citty config file *should*
be, whether it exists or not.
"""
def path_ok(varname: str):
nonlocal env
path = Path(env.get(varname, ""))
if path.is_dir():
return path / CITTY
return None
env = os.environ
path = path_ok(XDG_CONFIG_HOME)
if path:
return path
path = path_ok(APPDATA)
if path:
return path
path = Path.home()
if path.is_dir():
path /= _CITTY
return path
raise NotADirectoryError("Could not find a location to load/store" " config data.")
def load_testfuncs():
""" Load the entry points for test functions, build a name: function
mapping and return it.
"""
testfuncs = {ep.name: ep.load() for ep in iter_ep("citty_test_funcs")}
# Added for coderview -- this is normally handled using entrypoints
if not testfuncs:
testfuncs[MAKE_TEST] = make_test
return testfuncs
def load_config():
""" Load json config file data, if file exists."""
cfp = config_file_path()
if not cfp.exists():
config = {SLEEP: SLEEP_TIME, PROJECTS: []}
with open(cfp) as cfg:
config = json.load(cfg)
config[PROJECTS].sort(key=lambda x: x[NAME])
config[TESTFUNCS] = load_testfuncs()
return config
def save_config(config):
""" Write json config file data. """
cfp = config_file_path()
dump_config = {k: v for k, v in config.items() if k != TESTFUNCS}
with open(cfp, "w") as cf:
json.dump(dump_config, cf)
def make_test(project):
""" Run 'make test' to determine CI status. """
kwargs = dict(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if project[PATH] is not None:
kwargs["cwd"] = project[PATH]
argv_list = "make test".strip().split()
try:
rc = subprocess.run(argv_list, **kwargs)
retcode = rc.returncode
except OSError as e:
print("Error: could not start build of project '{}'".format(project[NAME]))
print(e)
retcode = 2
return retcode
ESC_BGCOLOR = "\x1B[{};48;5;{}m"
def show_status(config):
""" Print project names with corresponding background color. """
colors = {
FAILING: ESC_BGCOLOR.format(37, 196),
PASSING: ESC_BGCOLOR.format(30, 46),
PENDING: ESC_BGCOLOR.format(30, 228),
NORMAL: "\x1B[40;37m",
}
stats = [
"{} {} {}".format(colors[proj[STATUS]], proj[NAME], colors[NORMAL])
for proj in config[PROJECTS]
]
stats_line = " | ".join(stats)
print(stats_line, end="\r")
def ci_build(config):
""" Do one pass through all projects, updating status. """
for project in config[PROJECTS]:
project[STATUS] = PENDING
show_status(config)
command = project[COMMAND]
rc = config[TESTFUNCS][command](project)
project[STATUS] = PASSING if rc == 0 else FAILING
show_status(config)
def main():
arguments = docopt(__doc__, version=VERSION)
ops = {
ADD: citty_add,
DELETE: citty_delete,
LIST: citty_list,
}
for cmd, fn in ops.items():
if arguments[cmd]:
fn(arguments)
break
else:
citty_loop(arguments)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T00:44:23.293",
"Id": "248257",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "`citty` -- CI server in a TTY"
}
|
248257
|
<p>This exercise is from jshero.com.</p>
<p>Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.</p>
<p>Here is my working solution. I'm posting in hopes of receiving pointers on how I could have written the code more effectively.</p>
<pre><code>function parseFirstInt(str) {
if (Number.isNaN(str) === true) {
return NaN;
} else {
let searchFrom = str.search(/[-+]?[0-9]+/g);
let searched = str.substr(searchFrom);
return parseInt(searched, 10);
};
}
</code></pre>
<p>Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.
parseFirstInt('No. -3) should return -3.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>I believe you have either misunderstood the task, or misunderstood <code>Number.isNaN</code>. In any case the <code>if</code> doesn't do anything usefull. <code>Number.isNaN</code> returns <code>true</code> only when the value is exactly <code>NaN</code>, which is not a valid input for your function anyway.</p>\n<p>Then you are not checking if <code>search()</code> isn't matching anything (and thus <code>searchFrom</code> is <code>-1</code>). It doesn't really matter, because <code>substr(-1)</code> simply returns the last character, but it would make the code better to understand.</p>\n<p>Use <code>const</code> instead of <code>let</code> when the value doesn't change.</p>\n<p>Personnally I'd use <code>.match()</code> instead of <code>.search()</code>, because it returns the matched string directly (in an array):</p>\n<pre><code>function parseFirstInt(str) {\n // Check if the paramter is a object with the method `match`\n if (!str.match) {\n return NaN; \n }\n const match = str.match(/[-+]?[0-9]+/);\n if (match && match[0]) {\n return parseInt(match[0], 10);\n }\n return NaN;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T15:24:54.410",
"Id": "486236",
"Score": "0",
"body": "Thank you for your comment, I just have one question. Could you please explain what is happening here (!str.match) in the code you provided?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:21:39.810",
"Id": "248264",
"ParentId": "248259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T01:14:44.887",
"Id": "248259",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Improving function that parses string and returns first integer present"
}
|
248259
|
<p>I programmed a tic-tac-toe game using pygame. It's the first game I make. I'd really appreaciate any comments you have about the coding style and any improvements that could be made.</p>
<pre><code>import pygame
import graphics # External module graphics.py
import logic # External module logic.py
# Setting up window
HEIGHT = 600
WIDTH = 480
FPS = 30
TITLE = "Tic-tac-toe"
# Defining colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# Initializing pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
# Game settings
TOP = 100
SIZE = 450
CELL = SIZE // 3
CPU_SPEED = FPS // 2
class TicTacToe():
"""Main tic-tac-toe game object.
Attributes
----------
board : graphics.Board
pygame.Sprite object. Consists mainly of the lines that make
up the grid.
board_logic : logic.Board
Object that defines the game logic and AI.
cells : 3 x 3 nested list.
List containing individual graphics.Cell objects.
Each `Cell` object is a cell sprite.
player_score : graphics.Text
Sprite object that shows the player score.
cpu_score : graphics.Text
Sprite object that shows the cpu score.
end_message : graphics.Text
Sprite object that shows a message when the game ends:
win/lose/tie.
player_play : bool
Determine when it's the player's turn to play.
check : bool
Determine when the check the end of the game.
Set to `True` after each player or cpu move.
reset : bool
Determines when to reset the board after the end of game.
timer : int
Counter to limit cpu moves speed.
timer2 : int
Counter to limit end game reactions speed.
Methods
-------
add_to_group(sprites_group)
Add all of the sprite objects of the `TicTacToe` object
to `sprites_group`.
create_cells(CELL)
Create 9 `graphics.Cell` objects of size `SIZE` x `SIZE`
and append them to `self.cells`.
update()
Check if the game has ended or a player has won. Calls
methods accordingly. Verify when to check with `self.check`
and limit frequency using `self.timer2`.
Verifies it's the computer's turn to play by checking
`self.player_turn`. Calls `computer_turn` method when
corresponds. Limits computer's play speed using
`self.timer`.
computer_turn()
Use `graphics.board_logic.computer_turn()` method to determine
next case to fill.
Fill cell accordingly and update to check board end game
conditions and player's turn.
reset_game()
Reset `graphics.Board` to delete extra lines on the board.
Reset all `graphics.Cell` sprites to a blank surface.
Reset `self.end_message` to show an empty string.
update_score()
Add one point to the corresponding current player score.
Either `self.cpu_score` or `self.player_score`.
win_message()
Modify `self.end_message` to show a win or lose message.
tie_message()
Modify `self.end_message` to show a tied game message.
get_cells():
Return `self.cells` containing all the `graphics.Cell`
sprite objects.
is_player_turn():
Return `True` when player's turn conditions are met.
`False` otherwise.
to_reset():
Return `self.reset` attribute. Use to determine when
to reset the game board.
"""
def __init__(self):
self.board = graphics.Board()
self.board_logic = logic.Board()
self.cells = self.create_cells(CELL)
self.player_score = graphics.Text('P1 : 0',
(WIDTH * 4 // 5, TOP * 1 // 3))
self.cpu_score = graphics.Text('CPU : 0',
(WIDTH * 4 // 5, TOP * 2 // 3))
self.end_message = graphics.Text('',
(WIDTH * 2 // 5, TOP // 2))
self.player_play = False
self.check = False
self.reset = False
self.timer = 0
self.timer2 = 0
def add_to_group(self, sprites_group):
sprites_group.add(self.player_score)
sprites_group.add(self.cpu_score)
sprites_group.add(self.end_message)
for cell in self.cells:
sprites_group.add(cell)
sprites_group.add(self.board)
def create_cells(self, CELL=CELL):
cells = []
for i in range(3):
row = []
for j in range(3):
pos = (self.board.rect.left + j * CELL,
self.board.rect.top + i * CELL)
row.append(graphics.Cell(pos))
cells.append(row)
return cells
def update(self):
if self.check:
if self.timer2 > CPU_SPEED // 2:
self.timer2 = 0
self.check = False
if self.board_logic.check_winner():
self.board.draw_triple(self.board_logic.win_line_pos())
self.win_message()
self.update_score()
self.reset = True
elif self.board_logic.endgame():
self.tie_message()
self.reset = True
else:
self.timer2 += 1
if self.timer < CPU_SPEED:
self.timer += 1
else:
self.timer = 0
if not self.is_player_turn() and not self.to_reset():
self.computer_turn()
def computer_turn(self):
i, j = self.board_logic.computer_turn()
# print(self.board_logic)
self.cells[i][j].computer_fill()
self.check = True
self.player_play = True
def player_turn(self, ij):
self.timer = 0
self.board_logic.user_turn(ij)
i, j = ij
self.cells[i][j].player_fill()
self.player_play = False
self.check = True
def reset_game(self):
self.board.new_board()
self.board_logic.reset()
self.end_message.write('')
for i in range(3):
for j in range(3):
self.cells[i][j].reset()
self.reset = False
def update_score(self):
if self.board_logic.current_player() == 'o':
self.player_score.add1()
else:
self.cpu_score.add1()
def win_message(self):
if self.board_logic.current_player() == 'o':
self.end_message.write('You win!')
else:
self.end_message.write('You lose!')
def tie_message(self):
self.end_message.write(' Tie!')
def get_cells(self):
return self.cells
def is_player_turn(self):
return self.player_play and not self.board_logic.check_winner()
def to_reset(self):
return self.reset
all_sprites = pygame.sprite.Group()
game = TicTacToe()
game.add_to_group(all_sprites)
# Game loop
running = True
while running:
clock.tick(FPS)
# Process input
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
if game.to_reset():
game.reset_game()
elif game.is_player_turn():
pos = pygame.mouse.get_pos()
cells = game.get_cells()
for i in range(3):
for j in range(3):
if cells[i][j].hits(pos):
game.player_turn((i, j))
game.update()
# Draw / render
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
</code></pre>
<p>I separated the code in different modules. The <code>graphics</code> module includes the classes to create the different sprites used by the game (the game board, the board cells and the text messages).
The <code>logic</code> module is used for the computer AI.</p>
<p>I'm sharing only this "game part" of the code because this is where I'd appreciate your comments. If you'd like to check the other modules or get them in order to play the game, you can do it <a href="https://github.com/fabrizzio-gz/tic-tac-toe" rel="nofollow noreferrer">here</a>.</p>
<p>Thank you very much for your time.</p>
|
[] |
[
{
"body": "<h2>Static Code Analysis</h2>\n<p>Let me walk you through some of <a href=\"https://towardsdatascience.com/static-code-analysis-for-python-bdce10b8d287\" rel=\"nofollow noreferrer\">my favorite static code analysis tools</a>:</p>\n<ul>\n<li><strong><a href=\"https://medium.com/analytics-vidhya/type-annotations-in-python-3-8-3b401384403d\" rel=\"nofollow noreferrer\">Type annotations</a></strong>: You don't use any. They are awesome and everybody should use them for Python 3.6+. As nobody should use Python versions below 3.6, just everybody should use them^^</li>\n<li><a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a> and <a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\">isort</a>: For general formatting, I like to use the autoformatter black. Your code is already good when it comes to this / PEP8</li>\n<li><a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">Flake8</a>: May style checks. For example, the parameter to <code>create_cells</code> should be lowercase (<code>cell</code>, not <code>CELL</code>).</li>\n<li><a href=\"https://pypi.org/project/mccabe/\" rel=\"nofollow noreferrer\">McCabe</a>: To check if there are parts which are hard to understand, I use <code>python -m mccabe --min 5 yourscript.py</code>. It only complains about the game loop.</li>\n</ul>\n<h2>Other comments</h2>\n<h3>main function</h3>\n<p>I usually like to put everything in functions. You could put the game loop in a <code>main</code> function and then add:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n main()\n</code></pre>\n<p>This has the advantage that you can import parts of this file without executing it. This makes testing sometimes way easier.</p>\n<h3>Properties and YAGNI</h3>\n<p>Python has the <a href=\"https://www.mattlayman.com/blog/2017/pythonic-code-the-property-decorator/\" rel=\"nofollow noreferrer\">property decorator</a>. In your case, however, I would simply remove <code>get_cells</code> and access <code>.cells</code> directly. It makes the code easier to read and if you need it, you can still introduce the property later.</p>\n<p>There is <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> - you ain't gonna need it. Don't create abstractions if you don't need them. The method <code>to_reset</code> seems to be a good example.</p>\n<h3>Docstring Style</h3>\n<p>Your docstring style is very similar to <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">numpydoc</a>; maybe you can change it to be consistent with that. This especially means that you don't need to document all methods within the class docstring. Instead, you document the method within the method. Many editors can then also use this to show help about the method.</p>\n<h3>Naming</h3>\n<p>Good names are hard to find. We want names that are clear in the context, but also not Java-style overly long names.</p>\n<p>Here are some examples which I find hard to understand:</p>\n<ul>\n<li>timer2: Usually when you have to add numbers, that is a sign that it's not a good name</li>\n<li>player_play: Should be called <code>is_players_turn</code>, but that is already a method</li>\n<li>is_player_turn(): I'm not sure what <code>self.board_logic.check_winner</code> is doing, so I'm uncertain what a good name would be. But as this method is only called once, I'm wondering if the method itself is really necessary.</li>\n</ul>\n<h3>Enums</h3>\n<p>I don't know what <code>self.board_logic.current_player() == "o"</code> is doing, but maybe the method could return an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> and you could compare against an enum? String comparisons are prone to typo errors</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T17:32:28.297",
"Id": "486371",
"Score": "0",
"body": "Thanks a lot for your review. I agree with most of your observations and I think they will improve the code. About getting rid of unnecessary methods (YAGNI), I'm following a recommendation of not accessing class attributes from outside the class. So to access `self.cells`, I use the `self.get_cells()` method. What's your take on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T20:58:06.223",
"Id": "486377",
"Score": "0",
"body": "\"I'm following a recommendation of not accessing class attributes from outside the class\" - I only see instance attributes and no class attributes in your example. I guess you mean instance attribute. Where does the recommendation come from? Why is it recommended? Have you read the article about the property decorator I've shared above?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T21:35:41.523",
"Id": "486379",
"Score": "0",
"body": "Yes, I meant instance attributes. The recommendation came from a MIT course. They suggested using getters and setters for attributes, I assume for encapsulation purposes. Similar to the java coding style the decorator article criticizes, actually. Maybe the best way to do that is using decorators, as the article suggests. I'm not very familiar with them but I will try looking into it. I also found a bit burdensome to create methods just to retrieve attributes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:41:40.587",
"Id": "486401",
"Score": "0",
"body": "A lot of teachers come from the Java world and they are not aware of important differences to Python. For example, it is crucial to keep interfaces of a library constant (in any language**). Still, you want to be able to change something**. The only solution to that (in Java) is to make methods (getters and setters). In Python, you can use the property decorator. You can re-define what happens at attribute access. This removes the need for a getter / setter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T03:13:32.293",
"Id": "486498",
"Score": "0",
"body": "I agree. It seems the pythonic way of doing it. You have given me many resources to learn more and improve. Thank you very much."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:31:32.650",
"Id": "248322",
"ParentId": "248260",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248322",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T01:55:22.053",
"Id": "248260",
"Score": "2",
"Tags": [
"python",
"tic-tac-toe",
"pygame"
],
"Title": "Tic-tac-toe game using Pygame"
}
|
248260
|
<h2>Code review scope</h2>
<p>My goal with this review is to receive big-picture observations and suggestions for improving the efficiency / ease of writing the front end of a web application with this basic framework. I want to focus on what it looks like it should do rather than the details of what it may or may not unintentionally do. Limit scope to a big-picture overview, which should help save time since it is a good sized chunk of code for one review.</p>
<p>Focus should be on speed of scalable (maintainable, restructurable) development, over-arching code patterns and code design of the resulting applications.</p>
<blockquote>
<p>"Here's what it looks like you're trying to achieve, here's where you've succeeded, here's where you're lacking, or here's a
big-picture modification that might make the resulting code easier to
read, maintain, and faster to develop."</p>
</blockquote>
<hr />
<h2>The problem Manifest.JS is meant to address</h2>
<p>Designing <a href="https://en.wikipedia.org/wiki/Single-page_application" rel="nofollow noreferrer">single-page web apps</a> I found two things I didn't like about ReactJS (at least for my typical project scale):</p>
<ul>
<li>Had to write more code than I wanted to accomplish basic things</li>
<li>Was tedious to transport information through the app, you had to essentially pass a wire through the components to get information from point A to point B, which made the design feel tightly coupled and difficult to re-structure afterwards</li>
</ul>
<p>I also sort of felt this way about other JS app frameworks I tried. So I wrote two fairly simple classes that work together to create a development pattern that I preferred. My goal was for this to let me:</p>
<ol>
<li>Focus all of the process of building each individual component of an
app into modular JS without having to care much about how each component is connected to the
outside application.</li>
<li>Not have to go between multiple files or languages to edit JavaScript, HTML and CSS to build or maintain any one UI feature.</li>
</ol>
<p>Loose coupling, separation of concerns, pure JS workflow, predictable project structure, easy data flow, no more features than needed. That's the goal, whether this code achieves it or not, I'm not sure yet.</p>
<p><em>Note:</em> JSX sort of does some of <code>#2</code>, but having the two languages in one file felt a bit odd to me, I wanted my files to be a uniform language rather than JSX woven through it like with React.</p>
<hr />
<h2>Self critiques:</h2>
<p>So far some self-critiques I've considered:</p>
<ul>
<li><p>When it comes to modularizing a set of <code>Elements</code> into a class, I could provide a single, set way of doing it so there's a clear path forward for the developer and no freedom to develop accidental anti-patterns when deciding how to package the components into modular files.</p>
</li>
<li><p>Chaining is great. I should update <code>.use</code> to return <code>this</code> so we can then chain an action like</p>
<p><code>self.append(new InfoPage().use(subPage, { /* properties */ }).actions.select(true))</code></p>
<p>Create the InfoPage, use the subPage template, pass unique properties, and select it by default. Also can make <code>action</code>s return their <code>Element</code> so they can be chained.</p>
</li>
</ul>
<hr />
<h2>Components:</h2>
<ol>
<li><strong>Publisher.js</strong> - a simple message-passing class to implement the <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern" rel="nofollow noreferrer">Pub Sub pattern</a> because I wanted to be able to send namespace-separated events from any location in the app and read them anywhere else, like: <code>publisher.emit("header/select-nav/home", this)</code> and <code>publisher.on("header/select-nav/" + name, data => {})</code>. Additionally, I support a third <code>bool</code> argument to support sending and listening for events over an optionally passed in Socket.io socket, like <code>let publisher = new Publisher(io())</code>, so I could handle local and remote events in the same way.</li>
</ol>
<p>Usage:</p>
<pre><code>let publisher = new Publisher(io()) // or let publisher = new Publisher()
publisher.on("namespace1/subnamespace2/event-name", data => {}, false)
// third arg set to true tells the event handler to listen for Socket.io events
</code></pre>
<ol start="2">
<li><strong>Element.js</strong> - a wrapper for HTML elements that facilitates the entirety of the app's HTML generation and logic, so the logic associated with each visible component of the app is tightly coupled to it, while all the components individually remain loosely coupled to each-other. I also plan to maybe add support for generating CSS classes locally within each component too.</li>
</ol>
<p>Usage:</p>
<pre><code>new Element("div", { // create a div
id: "header", // set the id
traits: { publisher }, // assign data that will be inherited by any children
data: { name: "primary" }, // assign data to this element only
text: "My header text", // set text
innerHTML: false, // set innerHTML
classes: [], // assign classes
attributes: { // assign attributes
"contenteditable": "true"
},
styles: {}, // assign styles
actions: { // create actions, which will be wrapped in a
show: (self, arg1) => { // wrapper func and receive the Element as
self.clearStyle("opacity") // their first argument, followed by any
self.addClass("visible") // args passed with Element.action.name()
console.log("called with Element.actions.show(arg1)")
},
hide: self => {
self.removeClass("visible") // remove them
self.style("opacity", 0) // or set styles
}
},
callback: self => { // trigger as soon as the element is created
self.append(new Element("div", {
id: "important-icon",
classes: ["hidden", "header-icon"],
actions: {
select: () => {
self.addClass("visible")
self.removeClass("hidden")
self.updateText("Selected") // update text
}
},
ready: self => {
self.on("mouseover", evt => { // handle DOM events
self.addClass("highlight")
})
}
}))
},
ready: self => { // trigger after the element is appended to a parent
self.traits.publisher.on("events/header/" + self.data.name, data => {
self.select("#important-icon").actions.select();
// you could of course apply this listener to the icon itself,
// but the select feature is convenient in some cases
})
}
}).appendTo(document.body)
</code></pre>
<ol start="3">
<li><strong>Controller.js</strong> - validation of input during data flow grows more and more important the larger an application becomes. So it should be a choice of course, whether you want to use it, and I made it available and supported for validating the data flow both within the Element <em>and</em> in the Publisher. I didn't code in publisher support yet but it'll work the same at <code>Element</code>, with <code>publisher.use(controller)</code>. But I also wanted a pass to pass a blueprint input to a set of elements requiring the same properties, and it makes sense for a Controller to be able to override the current input passing through it for ease of testing / debugging, so I added an <code>insert</code> method to it, which (as you'll see in the code) can and should be used for templating Element properties.</li>
</ol>
<p>Usage:</p>
<pre><code>let page = new Controller({
data: data => { // pass a function to validate data however you want
if (!data.name) return false
else return true
},
traits: true, // pass true to simply ensure a setting is passed
actions: "object", // pass a string to test against typeof
}).insert({ // and insert specific default data
traits: {
publisher
},
actions: {
select: self => {
let target = "header/select-nav/" + self.data.name.toLowerCase()
self.traits.publisher.emit(target, this)
self.addClass("visible")
}
},
ready: self => {
self.traits.publisher.emit("header/add-nav", self)
}
});
</code></pre>
<h2>Element.js:</h2>
<pre><code>import Controller from "/js/classes/controller.js"
function isCyclic(obj) {
var seenObjects = [];
function detect(obj) {
if (obj && typeof obj === 'object') {
if (seenObjects.indexOf(obj) !== -1) {
return true;
}
seenObjects.push(obj);
for (var key in obj) {
if (obj.hasOwnProperty(key) && detect(obj[key])) {
//console.log(obj, 'cycle at ' + key);
return true;
}
}
}
return false;
}
return detect(obj);
}
function isObject(item) {
return item && typeof item === 'object' && !Array.isArray(item);
}
function isIterable(item) {
let type = false;
if (isObject(item)) type = 'obj';
else if (Array.isArray(item)) type = 'arr';
return type;
}
function mergeDeeper(source, target) {
let allProps = [];
let sourceProps;
let type;
let targetProps;
if (isObject(source)) {
sourceProps = Object.keys(source);
type = 'obj';
} else if (Array.isArray(source)) {
sourceProps = source;
type = 'arr';
} else {
return source;
}
if (isObject(target)) {
targetProps = Object.keys(target);
} else if (Array.isArray(target)) {
targetProps = target;
} else {
debugger
throw "target missing"
}
sourceProps.forEach(prop => {
allProps.push(prop);
});
targetProps.forEach(prop => {
allProps.push(prop);
});
allProps = [...new Set(allProps)];
let merged
if (type == 'obj') {
merged = {};
} else if (type == 'arr') {
merged = [];
}
allProps.forEach(prop => {
if (type == "obj") {
if (source[prop]) {
if (isIterable(source[prop])) {
if (isIterable(target[prop])) {
merged[prop] = mergeDeeper(source[prop], target[prop])
} else merged[prop] = source[prop]
} else {
merged[prop] = source[prop]
}
} else {
if (source[prop] !== undefined) {
merged[prop] = source[prop]
} else {
merged[prop] = target[prop]
}
}
} else {
let iterable = isIterable(prop);
if (iterable) {
let filler
if (iterable == "obj") filler = {};
else if (iterable == "arr") filler = [];
merged.push(mergeDeeper(prop, filler))
} else {
merged.push(prop)
}
}
})
return merged;
}
const collectChildSelectors = (elementWrapper, selectors) => {
elementWrapper.children.forEach(childWrapper => {
if (childWrapper.element.id) {
selectors[childWrapper.element.id] = childWrapper
}
if (childWrapper.selector) {
selectors[childWrapper.selector] = childWrapper
}
collectChildSelectors(childWrapper, selectors)
})
}
const applySettings = function(newSettings) {
if (!newSettings) throw "bad settings"
let settings = mergeDeeper(newSettings, {
text: false,
innerHTML: false,
classes: [],
actions: {},
data: {},
attributes: {},
styles: {},
traits: {},
id: false,
callback: false,
ready: false,
});
if (settings.id) {
this.element.id = settings.id
this.selector = settings.id
}
if (settings.text) this.element.textContent = settings.text
if (settings.innerHTML) this.element.innerHTML = settings.innerHTML
if (settings.selector) {
this.selector = settings.selector
this.selectors[settings.selector] = this;
}
settings.classes.forEach(className => this.element.classList.add(className))
Object.keys(settings.attributes).forEach(attributeName =>
this.element.setAttribute(attributeName,
settings.attributes[attributeName]))
Object.keys(settings.styles).forEach(styleName =>
this.element.style[styleName] = settings.styles[styleName])
Object.keys(settings.actions).forEach(actionName =>
this.actions[actionName] = () => settings.actions[actionName](this))
Object.keys(settings.data).forEach(propertyName =>
this.data[propertyName] = settings.data[propertyName])
Object.keys(settings.traits).forEach(propertyName =>
this.traits[propertyName] = settings.traits[propertyName])
if (settings.ready) this.ready = settings.ready
if (settings.callback) settings.callback(this);
}
export default class {
constructor(tag, settings) {
this.children = [];
this.data = {}
this.actions = {}
this.traits = {}
this.selectors = {}
this.element = document.createElement(tag)
applySettings.apply(this, [settings])
}
use(arg1, arg2) {
if (arg1 instanceof Controller) {
let controller = arg1;
let settings = arg2;
let mergedSettings = mergeDeeper(settings, controller.insertions);
controller.test(mergedSettings);
applySettings.apply(this, [mergedSettings])
} else if (arguments.length === 1) {
let settings = arg1;
applySettings.apply(this, [settings])
} else {
throw "bad settings passed to Element"
}
return this;
}
addEventListener(event, func) {
this.element.addEventListener(event, func)
}
delete() {
this.parent.removeChild(this.element)
}
style(styleName, value) {
this.element.style[styleName] = value
}
clearStyle(styleName) {
this.element.style[styleName] = ""
}
updateText(text) {
this.element.textContent = text
}
updateAttribute(attributeName, attributeContent) {
this.element.setAttribute(attributeName, attributeContent)
}
addClass(className) {
this.element.classList.add(className)
}
removeClass(className) {
this.element.classList.remove(className)
}
on(evt, func) {
this.element.addEventListener(evt, func)
}
select(id) {
let parts = id.split("#")
let selector = parts[parts.length - 1];
if (!this.selectors[selector]) debugger;
//throw "bad selector " + selector
return this.selectors[selector]
}
appendTo(elementWrapper) {
let element
if (elementWrapper.nodeName) element = elementWrapper
else {
element = elementWrapper.element
this.parent = element
collectChildSelectors(this, elementWrapper.selectors)
Object.keys(elementWrapper.traits).forEach(propertyName =>
this.traits[propertyName] = elementWrapper.traits[propertyName])
}
if (this.ready) this.ready(this)
element.appendChild(this.element)
return this
}
append(elementWrapper) {
let element
let wrapped = false
if (elementWrapper.nodeName) element = elementWrapper
else {
wrapped = true
element = elementWrapper.element
element.parent = this
if (element.id) this.selectors[element.id] = elementWrapper
if (elementWrapper.selector)
this.selectors[elementWrapper.selector] = elementWrapper
this.children.push(elementWrapper)
collectChildSelectors(elementWrapper, this.selectors)
Object.keys(this.traits).forEach(propertyName =>
elementWrapper.traits[propertyName] = this.traits[propertyName])
}
if (elementWrapper.ready) elementWrapper.ready(elementWrapper)
this.element.appendChild(element)
if (wrapped) return elementWrapper
}
}
</code></pre>
<h2>Controller.js:</h2>
<pre><code>export default class {
constructor(settings) {
this.tests = {};
Object.keys(settings).forEach(key => {
let val = settings[key];
if (typeof val == "boolean") {
this.tests[key] = input => {
return input !== undefined
}
} else if (typeof val == "string") {
this.tests[key] = input => {
return typeof input === val
}
} else if (typeof val == "function") {
this.tests[key] = val;
}
})
}
test(obj) {
Object.keys(obj).forEach(key => {
if (!this.tests[key] || !this.tests[key](obj[key])) {
console.log("Controller test failed");
debugger;
}
});
}
insert(insertion) {
this.insertions = insertion;
return this;
}
}
</code></pre>
<h2>Publisher.js</h2>
<pre><code>export default class {
constructor(socket) {
if (socket) this.socket = socket;
this.events = {};
}
on(command, func, socket = false) {
if (!this.events[command]) this.events[command] = [];
this.events[command].push(func);
if (socket && this.socket) socket.on(command, func);
}
emit(command, data = {}, socket = false) {
if (this.events[command]) {
this.events[command].forEach(func => func(data));
}
if (socket && this.socket) socket.emit(command, data);
}
}
</code></pre>
<hr />
<h2>Implementation</h2>
<p><strong><code>app.js</code>:</strong></p>
<pre><code>import Publisher from "/js/classes/publisher.js"
import Controller from "/js/classes/controller.js"
let publisher = new Publisher(io())
import Header from "/js/classes/header/header.js"
import Home from "/js/classes/pages/home/home.js"
import News from "/js/classes/pages/news/news.js"
import Leaderboard from "/js/classes/pages/leaderboard/leaderboard.js"
import Account from "/js/classes/pages/account/account.js"
import Builder from "/js/classes/pages/builder/builder.js"
let header = new Header(publisher)
let page = new Controller({
data: true, // () => { } // validate the value however you choose
traits: true, // It's good to have this capability for debugging
actions: true, // or for if your boss wants all your data interfaces
ready: true // validated because he read it in a hip dev blog
}).insert({ // <- But insertion is the feature you'll be using
traits: { // more often to test input data, debug, and like with
publisher // this case, apply a single input object to multiple
}, // Elements
actions: {
select: self => {
let target = "header/select-nav/" + self.data.name.toLowerCase()
self.traits.publisher.emit(target, this)
self.addClass("visible")
}
},
ready: self => {
self.traits.publisher.emit("header/add-nav", self)
}
});
new Home().use(page, {
data: {
name: "Home",
iconPath: "/assets/home/home-1.png",
cornerPath: "/assets/corners/corner-1.png",
}
}).appendTo(document.body)
new News().use(page, {
data: {
name: "News",
iconPath: "/assets/news/news-1.png",
cornerPath: "/assets/corners/corner-5.png"
}
}).appendTo(document.body)
new Leaderboard().use(page, {
data: {
name: "Leaderboard",
iconPath: "/assets/leaderboard/leaderboard-1.png",
cornerPath: "/assets/corners/corner-3.png",
}
}).appendTo(document.body)
new Account().use(page, {
data: {
name: "Account",
iconPath: "./assets/profile/profile-1.png",
cornerPath: "/assets/corners/corner-4.png",
}
}).appendTo(document.body)
new Builder().use(page, {
data: {
name: "Builder",
iconPath: "./assets/builder/builder-1.png",
cornerPath: "/assets/corners/corner-2.png",
}
}).appendTo(document.body).actions.select()
</code></pre>
<p><strong><code>/js/classes/pages/builder/builder.js</code>:</strong></p>
<p>Here I used a sort of odd <code>return</code> statement in the constructor, purely for visual purposes because I like using <code>new ModuleName()</code> in the file where it's used, as opposed to a function call, but you can do it either way.</p>
<pre><code>import Element from "/js/classes/element.js"
import NavBar from "/js/classes/pages/builder/nav-bar.js"
export default class {
constructor() {
return new Element("div", {
id: "builder",
classes: ["page"],
actions: {
select: self => {
let target = "header/select-nav/" + self.data.name.toLowerCase()
self.traits.publisher.emit(target, this)
self.addClass("visible")
}
},
ready: self => {
self.traits.publisher.emit("header/add-nav", self)
self.actions.select()
},
callback: self => {
self.append(new NavBar());
// add more elements
}
})
}
}
</code></pre>
<p><strong><code>/js/classes/pages/header/header.js</code></strong></p>
<pre><code>import Element from "/js/classes/element.js"
import NavIcon from "./header-nav-icon.js"
export default class {
constructor(publisher) {
return new Element("div", {
id: "header",
traits: { publisher },
ready: self => {
self.append(new Element("div", {
selector: "title-wrapper",
classes: ["title-wrapper"],
ready: self => {
self.append(new Element("div", {
selector: "location-wrapper",
classes: ["location-wrapper"],
ready: self => {
self.traits.publisher.on("header/add-nav", data => {
self.append(new Element("div", {
selector: "location-item-wrapper",
classes: ["location-item-wrapper"],
ready: self => {
self.traits.publisher.on("header/select-nav/" +
data.data.name.toLowerCase(), data => {
self.addClass("visible")
});
self.append(new Element("div", {
id: data.data.name.toLowerCase() + "-nav",
classes: ["location-item", "heading"],
text: data.data.name
}))
self.append(new Element("img", {
classes: ["location-item-icon"],
attributes: {
"src": data.data.iconPath.split(".png")[0] + "-flat.png"
}
}))
self.append(new Element("img", {
selector: "corner",
classes: ["corner"],
attributes: {
"src": data.data.cornerPath
}
}))
}
}))
})
}
}))
self.append(new Element("div", {
selector: "sub-location-wrapper",
classes: ["sub-location-wrapper", "subheading"]
}))
}
}))
self.append(new Element("div", {
selector: "nav-wrapper",
classes: ["nav-wrapper", "center-contents"],
ready: self => {
self.traits.publisher.on("header/add-nav", data => {
console.log("header/add-nav, data", data.data)
console.log("adding nav-item")
self.append(new NavIcon().use({
data: data.data
}))
});
self.append(new Element("div", {
classes: ["title-bg-wrapper"],
ready: self => {
self.append(new Element("img", {
classes: ["title-bg-icon"],
attributes: {
"src": "./assets/header.png"
}
}))
self.append(new Element("div", {
classes: ["title-bg-text"],
innerHTML: "BIDRATE <br/> RENAISSANCE"
}))
}
}))
}
}))
}
}).appendTo(document.body)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T07:37:25.467",
"Id": "486204",
"Score": "1",
"body": "Been a few years since Ive been on this site. Did I do ok presenting / scoping the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T07:56:23.463",
"Id": "486205",
"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."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T07:56:48.470",
"Id": "486206",
"Score": "0",
"body": "For more tips about how to present your question, see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:17:21.610",
"Id": "486208",
"Score": "0",
"body": "Is Manifest.JS the name of your program? Did you write it as a layer over React to be re-used in later projects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:18:46.777",
"Id": "486209",
"Score": "0",
"body": "Did you look at alternatives like Gatsby before building this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:18:59.200",
"Id": "486210",
"Score": "1",
"body": "@Mast It's the name of what I'm calling the lightweight framework that these three components make up. No it doesn't involve React at all. I mentioned react as a popular solution that I wanted an alternative to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:21:01.950",
"Id": "486211",
"Score": "2",
"body": "@Mast I dont think anything light weight enough exists that implements the kind of (simple) application structure I'm looking to create. A look at https://www.gatsbyjs.com/tutorial/ shows me far more bells and whistles than I'm interested in. Its layered on top of React which is already not a structure I find attractive."
}
] |
[
{
"body": "<h2>Big picture overview</h2>\n<blockquote>\n<p>Limit scope to a big-picture overview, which should help save time since it is a good sized chunk of code for one review.</p>\n</blockquote>\n<p>While I plugged the modules into a plunker, it is still difficult for me to determine if the framework would help me with a SPA with limited code. I see a lot of methods that accept <code>self</code> as the first (and often only) parameter. Why can't they operate on <code>this</code>? Is the context not bound correctly for that?</p>\n<p>I created an <a href=\"https://codereview.stackexchange.com/q/201326/120114\">event emitter module</a> for an interview. The requirements sound like the Pub-Sub pattern and I implemented similar methods as the Publisher. The requirements called for a way to have a "one-time" handler, as well as a way to un-register a registered handler function. You might consider offering such functionality with your publisher module.</p>\n<p>The bottom line is: if you feel like this framework allows you to write less code than you otherwise might with many other frameworks then go ahead and use it.</p>\n<h2>Targeted JS feedback</h2>\n<p>I noticed the <code>const</code> keyword only appears in your code twice - for two function expressions i.e. <code>collectChildSelectors</code> and <code>applySettings</code>. It is recommended that <code>const</code> be the default keyword for all variables, and then if re-assignment is necessary, switch to using <code>let</code>. Also, avoid <code>var</code>, unless there is a need for something like a global variable but that is also frowned upon.</p>\n<p>Some parts of the code use <code>===</code> for comparing values but others use <code>==</code>. A recommended practice is always using strict type comparison .</p>\n<p>For readability, use a consistent quote style for string literals- either single or double quotes but not both.</p>\n<p><code>mergeDeeper()</code> could use spread operator instead of forEach() -> push for <code>sourceProps</code> and <code>targetProps</code></p>\n<pre><code>allProps.push(...sourceProps, ...targetProps)\n</code></pre>\n<p>Name of function <code>isIterable</code> seems somewhat strange given that it can return a string or boolean. Maybe a more appropriate name would be <code>iterableType</code> - even if it returns <code>false</code> then the caller would know the value is not iterable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T23:20:51.967",
"Id": "486974",
"Score": "0",
"body": "All good points. To answer your question, I was passing this to the first param so an arrow function could be used. But I dont remember the other specifics of why I wanted that. Definitely not a permanent choice I'm decided on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T13:00:15.260",
"Id": "487242",
"Score": "0",
"body": "I just read your answer, some of our answer is eerily similar, especially the `iterableType` part"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T19:07:17.033",
"Id": "487295",
"Score": "0",
"body": "\"_Great minds think alike..._\"... I wonder if there is a pizza somewhere thinking about me..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T22:56:53.450",
"Id": "248580",
"ParentId": "248261",
"Score": "2"
}
},
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p><code>isCyclic</code> -> I would consider throwing <code>obj</code> into <code>JSON.stringify</code> and catch the relevant exception</p>\n</li>\n<li><p><code>function detect</code> is not a great name, it's okay because of the context, but could be better</p>\n</li>\n<li><p><code>//console.log(obj, 'cycle at ' + key);</code> <- bad comment</p>\n</li>\n<li><p>The code is using both <code>var</code> and <code>set</code> and <code>const</code>, there is true value in analyzing code and using only <code>set</code>/<code>const</code></p>\n</li>\n<li><p><code>function isObject(item)</code> <- an icky name since really you check whether it's an object but not an Array (which is also an object), hence why you could not use this function in <code>if (obj && typeof obj === 'object')</code></p>\n</li>\n<li><p><code>function isIterable(item) {</code> <- very icky name, the reader assumes it returns a boolean, especially with the first line being <code>false</code> but then you also return <code>obj</code> or <code>arr</code>, perhaps call it <code>iterableType</code> that return <code>undefined</code>, <code>'obj'</code>, or <code>'arr'</code>?</p>\n</li>\n<li><p>You are skipping on curly braces in <code>isIterable</code>, you should not</p>\n</li>\n<li><p><code>debugger</code> does not belong in production code</p>\n</li>\n<li><p>this</p>\n<pre><code>sourceProps.forEach(prop => {\n allProps.push(prop);\n});\ntargetProps.forEach(prop => {\n allProps.push(prop);\n});\n</code></pre>\n<p>could be</p>\n<pre><code>allProps = allProps.concat(sourceProps).concat(targetProps);\n</code></pre>\n</li>\n<li><p>You know that only Object and Array are iterable, and that the property is iterable so</p>\n<pre><code>let filler\nif (iterable == "obj") filler = {};\n else if (iterable == "arr") filler = [];\n</code></pre>\n<p>can be</p>\n<pre><code>let filler = iterable=="obj"?{}:[];\n</code></pre>\n</li>\n<li><p>On the whole I would read up on the ternary operator, this</p>\n<pre><code> if (source[prop] !== undefined) {\n merged[prop] = source[prop]\n } else {\n merged[prop] = target[prop]\n }\n</code></pre>\n<p>could be shorted and more readable (to me);</p>\n<pre><code> merged[prop] = source[prop]?source[prop]:target[prop];\n</code></pre>\n<p>and in this case it could even be shortened down to</p>\n<pre><code> merged[prop] = source[prop] || target[prop];\n</code></pre>\n</li>\n<li><p>The code has inconsistent use of semicolons, very annoying to read</p>\n</li>\n<li><p>You should pick a naming/coding standard and stick to it, before this the <code>function</code> keyword was used, and now the code switches to this;</p>\n<pre><code> const collectChildSelectors = (elementWrapper, selectors) => {\n</code></pre>\n</li>\n<li><p>Not sure why you are not providing all the possible parameters to <code>addEventListener</code></p>\n<pre><code> addEventListener(event, func) {\n this.element.addEventListener(event, func)\n }\n</code></pre>\n</li>\n<li><p>You do the below 5 times with different parameters, this could use a helper function to make this more readable;</p>\n<pre><code> Object.keys(settings.styles).forEach(styleName => \n this.element.style[styleName] = settings.styles[styleName])\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T11:55:28.540",
"Id": "487234",
"Score": "0",
"body": "All good points. I was hoping for a review of the code patterns created by the usage side of things, but now that I see how sloppy my code is on the micro scale, I realize that needs just as much work as the macro scale. Maybe I'll clean this all up and post a second review iteration so the focus can then be on the \"macro\" scale of things (review of the code patterns / anti-patterns created by the usage of the classes, and potential improvements)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T12:47:06.260",
"Id": "487240",
"Score": "2",
"body": "Looking forward, I would strongly suggest to have your code on github, and then create a working example with this code as library (there is a 'add external library' link). Then we can review the working app and also provide design suggestions for the library you use."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T11:09:17.900",
"Id": "248694",
"ParentId": "248261",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T04:36:23.740",
"Id": "248261",
"Score": "9",
"Tags": [
"javascript",
"ecmascript-6",
"framework"
],
"Title": "Manifest.JS: A lightweight front-end structural framework"
}
|
248261
|
<p>My code writes data and then receives data back. I want to log that this has happened, and I also want to inject a delegate so that I can get a callback to trace the data that is going in and out. This is example of the classes for reading and writing data in a request-response style.</p>
<pre><code>public class IOExample
{
private readonly ILogger _logger;
private readonly Action<DataPacket> _writeData;
private readonly Func<DataPacket> _readData;
public IOExample(
ILoggerFactory loggerFactory,
Action<DataPacket> writeData,
Func<DataPacket> readData
)
{
_logger = loggerFactory.CreateLogger<IOExample>();
_writeData = writeData;
_readData = readData;
}
public DataPacket WriteAndRead(DataPacket writePacket)
{
_writeData(writePacket);
_logger.LogTrace(new Trace { IsWrite = true, DataPacket = writePacket });
var readPacket = _readData();
_logger.LogTrace(new Trace { IsWrite = false, DataPacket = readPacket });
return readPacket;
}
}
</code></pre>
<p>The <code>LogTrace</code> method is an extension method on <code>ILogger</code>:</p>
<pre><code>public static class LoggingExtensions
{
public static void LogTrace<T>(this ILogger logger, T state)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
logger.Log(LogLevel.Trace, default, state, null, (a, b) => $"Trace\r\nState: {state}");
}
}
</code></pre>
<p>Here's where it gets tricky. I really don't feel like I should have to write this code. It feels like there should be a class to do this already. I basically just want a logger that calls back when a log occurs. But, anyway, this is the code so far:</p>
<pre><code>public class DelegateLogger : ILogger
{
#region Fields
private readonly Action<LogMessage> _action;
private readonly ConcurrentDictionary<Type, DelegateLoggerScope> _currentScopes = new ConcurrentDictionary<Type, DelegateLoggerScope>();
#endregion
#region Constructor
public DelegateLogger(Action<LogMessage> action)
{
_action = action ?? throw new ArgumentNullException(nameof(action));
}
#endregion
#region Implementation
public IDisposable BeginScope<TState>(TState state)
{
if (_currentScopes.ContainsKey(typeof(TState)))
{
throw new ScopeExistsException($"Scope already exists for type of {typeof(TState)}");
}
var scope = GetScope(state);
Callback(null, default, state, null, true);
return scope;
}
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (_currentScopes.ContainsKey(typeof(TState)))
{
var delegateLoggerScope = (DelegateLoggerScope<TState>)_currentScopes[typeof(TState)];
Callback(null, default, delegateLoggerScope.State, null, true);
}
Callback(logLevel, eventId, state, exception, false);
}
#endregion
#region Non Public Methods
internal void ReleaseScope<T>() => _currentScopes.Remove(typeof(T), out _);
private void Callback<TState>(LogLevel? logLevel, EventId eventId, TState state, Exception? exception, bool isScope)
{
if (state == null) throw new ArgumentNullException(nameof(state));
_action(new LogMessage(logLevel, eventId, state, exception, isScope, this));
}
private DelegateLoggerScope<TState> GetScope<TState>(TState state) => (DelegateLoggerScope<TState>)_currentScopes.GetOrAdd(typeof(TState), (t) => new DelegateLoggerScope<TState>(_action, state, this));
#endregion
}
</code></pre>
<p>These are the scopes:</p>
<pre><code>internal class DelegateLoggerScope
{
protected Action<LogMessage> _action;
protected DelegateLogger _DelegateLogger;
public DelegateLoggerScope(
Action<LogMessage> action,
DelegateLogger delegateLogger
)
{
_action = action;
_DelegateLogger = delegateLogger;
}
}
internal class DelegateLoggerScope<TState> : DelegateLoggerScope, IDisposable
{
public TState State { get; private set; }
public DelegateLoggerScope(
Action<LogMessage> action,
TState state,
DelegateLogger delegateLogger
) : base(action, delegateLogger)
{
State = state;
}
public void Dispose()
{
_DelegateLogger.ReleaseScope<TState>();
_action = null;
_DelegateLogger = null;
State = default;
}
}
</code></pre>
<p>This is a generic provider:</p>
<pre><code>public class GenericLoggerProvider : ILoggerProvider
{
private Func<string, ILogger> _createLogger;
public GenericLoggerProvider(Func<string, ILogger> createLogger)
{
_createLogger = createLogger;
}
public ILogger CreateLogger(string categoryName) => _createLogger(categoryName);
public void Dispose() => _createLogger = null;
}
</code></pre>
<p>Here's a very basic unit test that shows how it can be used:</p>
<pre><code>[TestMethod]
public void TestBeginScope()
{
Dog? state = null;
var scopeCount = 0;
var logCount = 0;
using var loggerFactory = LoggerFactory.Create((builder) =>
{
_ = builder.SetMinimumLevel(LogLevel.Trace)
.AddDebug()
.AddProvider(new GenericLoggerProvider((name) =>
new DelegateLogger((m) =>
{
state = (Dog)m.State;
if (m.IsScope)
{
scopeCount++;
}
else
{
logCount++;
}
}
)
));
});
var callbackLogger = loggerFactory.CreateLogger<UnitTest1>();
using (var scope = callbackLogger.BeginScope(new Dog { Name = dogName }))
{
callbackLogger.LogTrace(new Dog { Name = dogName });
}
callbackLogger.LogTrace(new Dog { Name = dogName });
if (state == null) throw new Exception();
Assert.AreEqual(dogName, state.Name);
Assert.AreEqual(2, logCount);
Assert.AreEqual(2, scopeCount);
}
</code></pre>
<p>Isn't there some out of the box way of doing this? Why do I have to write all this code?</p>
<p>If not, please help me to poke some holes in this so I can feel confident in using it.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T06:18:57.517",
"Id": "248262",
"Score": "1",
"Tags": [
"c#",
"logging",
"dependency-injection",
"delegates"
],
"Title": "ILogger with Delegate Callback"
}
|
248262
|
<p>My first attempt at writing a Python application to solve a real problem is a one way connector between ERPNext and MYOB AccountRight.</p>
<p>This is the module I have written to connect to the API and get all the tokens. The user fills out a form in ERPNext containing the relevant keys, authorization code, redirect URI etc. which this module reads in and then sends requests for the tokens.</p>
<p>I'm sure it's a terribly primitive approach, but so far I'm happy.</p>
<p>I have a few questions. I seem to find I'm repeating myself quite a bit with the requests, and now that I've also started making other modules that will POST the various documents. I'm wondering if there is some way that I should approach refactoring the requests?</p>
<p>My other question is about the exceptions. I've never used them in a practical setting. Do I have the right idea? Should I be trying to catch the 400 error and inform the user? Are there other request exceptions I should try to catch?</p>
<pre><code>import json
import requests
import frappe
TOKEN_URL = "https://secure.myob.com/oauth2/v1/authorize/"
# Retrieve the API settings saved by the user
client_id = frappe.db.get_single_value('MYOB Settings', 'api_key')
client_secret = frappe.db.get_single_value('MYOB Settings', 'api_secret')
redirect_uri = frappe.db.get_single_value('MYOB Settings', 'redirect_uri')
def get_tokens(doc, method):
# Get the authorization code saved by the user
auth_url = frappe.db.get_single_value('MYOB Settings',
'authorization_url')
# split the authorization code from the url
separator = "code="
try:
auth_code = auth_url.split(separator, 1)[1]
except IndexError as e:
frappe.log_error(frappe.get_traceback(), 'MYOB Authentication '
'Failed')
raise IndexError("Invalid url entered. Check entire url has been paste"
"d.") from e
payload = 'client_id=' + client_id + '&client_secret=' + client_secret +\
'&scope=CompanyFile&grant_type=authorization_code&code='\
+ auth_code + '&redirect_uri=' + redirect_uri
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + auth_code
}
# Send request for tokens
try:
response = requests.request("POST", TOKEN_URL, headers=headers,
data=payload)
response.raise_for_status()
except Exception as e:
if e.args and e.args[0].startswith("400"):
frappe.msgprint("400 Error: Bad Request. You may have entered "
"incorrect settings")
else:
frappe.msgprint("An unexpected error occurred. Check Error Log.")
frappe.log_error(frappe.get_traceback(), 'MYOB Authentication '
'Failed')
# Save tokens to database
frappe.db.set_value('MYOB Settings',
'MYOB Settings', 'access_token',
response.json()['access_token'])
frappe.db.set_value('MYOB Settings', 'MYOB Settings', 'refresh_token',
response.json()['refresh_token'])
def refresh_tokens(doc, method):
# Get the refresh token from the database
refresh_token = frappe.db.get_single_value('MYOB Settings',
'refresh_token')
payload = 'client_id=' + client_id + '&client_secret=' + client_secret + \
'&grant_type=refresh_token&refresh_token=' + refresh_token
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
# Send request for new tokens
try:
response = requests.request("POST", TOKEN_URL, headers=headers,
data=payload)
except Exception as e:
if e.args and e.args[0].startswith("400"):
frappe.msgprint("400 Error: Bad Request. You may have entered "
"incorrect settings")
else:
frappe.msgprint("An unexpected error occurred. Check Error Log.")
frappe.log_error(frappe.get_traceback(), 'MYOB Refreshing Tokens '
'Failed')
# Save tokens to database
frappe.db.set_value('MYOB Settings', 'MYOB Settings', 'access_token',
response.json()['access_token'])
frappe.db.set_value('MYOB Settings', 'MYOB Settings', 'refresh_token',
response.json()['refresh_token'])
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T08:58:20.320",
"Id": "248266",
"Score": "1",
"Tags": [
"python",
"beginner",
"error-handling",
"oauth"
],
"Title": "Oauth2 Connector Frappe Framework"
}
|
248266
|
<p>The following codes purpose is to generate an array of bytes that represents some user defined data. This array of bytes will later be used for sending over a network.</p>
<p><code>WelcomePacketWriter</code> is a concrete subclass of <code>PacketWriter</code>. Subclasses of <code>PacketWriter</code> can use methods provided by <code>PacketWriter</code> to write to the list of bytes (methods such as <code>WriteInt</code>, <code>WriteString</code> and <code>InsertShort</code>). The user can generate and get an array of bytes from a <code>PacketWriter</code> subclass by calling the <code>GetBytes</code> method which calls the abstract method <code>GenerateBufferContent</code> (which should make changes to the buffer field) and converts the buffer field from a list to an array.</p>
<p>My main concern is that in PacketWriter.cs there is a lot of duplicate code for handling different types of data (<code>GetBytes(short _value)</code>, <code>GetBytes(int _value)</code>, <code>GetBytes(float _value)</code>, etc...). I thought about using a generic method for <code>GetBytes</code>, however as the <code>BitConverter.GetBytes</code> method is not generic so I can't pass in a generic type. Using a switch statement based on the type in the generic method will still result in duplicate code and it may be unclear what types of data can be passed in without throwing an error.</p>
<p><strong>PacketWriter.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
namespace test
{
public abstract class PacketWriter
{
private List<byte> buffer;
internal PacketWriter()
{
buffer = new List<byte>();
}
public byte[] GetBytes()
{
GenerateBufferContent();
byte[] bytes = buffer.ToArray();
buffer.Clear();
return bytes;
}
protected abstract void GenerateBufferContent();
protected void Write(byte[] _value)
{
buffer.AddRange(_value);
}
protected void Insert(byte[] _value)
{
buffer.InsertRange(0, _value);
}
protected void WriteByte(byte _value)
{
Write(new byte[1] { _value });
}
protected void WriteShort(short _value)
{
Write(GetBytes(_value));
}
protected void WriteInt(int _value)
{
Write(GetBytes(_value));
}
protected void WriteFloat(float _value)
{
Write(GetBytes(_value));
}
protected void WriteBool(bool _value)
{
Write(GetBytes(_value));
}
protected void InsertByte(byte _value)
{
Insert(new byte[1] { _value });
}
protected void WriteString(string _value)
{
WriteInt(_value.Length);
Write(GetBytes(_value));
}
protected void InsertShort(short _value)
{
Insert(GetBytes(_value));
}
protected void InsertInt(int _value)
{
Insert(GetBytes(_value));
}
protected void InsertFloat(float _value)
{
Insert(GetBytes(_value));
}
protected void InsertBool(bool _value)
{
Insert(GetBytes(_value));
}
protected void InsertString(string _value)
{
Insert(GetBytes(_value));
InsertInt(_value.Length);
}
private byte[] GetBytes(short _value)
{
return BitConverter.GetBytes(_value);
}
private byte[] GetBytes(int _value)
{
return BitConverter.GetBytes(_value);
}
private byte[] GetBytes(float _value)
{
return BitConverter.GetBytes(_value);
}
private byte[] GetBytes(bool _value)
{
return BitConverter.GetBytes(_value);
}
private byte[] GetBytes(string _value)
{
return Encoding.ASCII.GetBytes(_value);
}
}
}
</code></pre>
<p><strong>WelcomePacket.cs</strong></p>
<pre><code>namespace ConsoleAppTest
{
public class WelcomePacketWriter : PacketWriter
{
private string message;
private short clientId;
public WelcomePacketWriter(short _clientId, string _message)
{
message = _message;
clientId = _clientId;
}
protected override void GenerateBufferContent()
{
WriteShort(clientId);
WriteString(message);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:48:08.013",
"Id": "486216",
"Score": "0",
"body": "How are you going to extract the data later?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:48:53.700",
"Id": "486217",
"Score": "1",
"body": "What's wrong with `BinaryWriter`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:04:56.073",
"Id": "486227",
"Score": "0",
"body": "@AlexanderPetrov I was planning on extracting the data with another class similar to PacketWriter but I thought that whatever the solution for reducing duplicate code in this class could be applied to the PacketReader as well so I decided not to mention it in the question. I did not know about BinaryReader and BinaryWriter but they seems to solve my problem quite well so thanks for mentioning it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:13:15.047",
"Id": "486228",
"Score": "0",
"body": "@AlexanderPetrov if you add some to explanation to your comment it would be a good answer."
}
] |
[
{
"body": "<p>You can use <code>Unsafe</code> class and make it generic.</p>\n<p>Here is the code:</p>\n<pre><code>using System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing System.Text;\n\nnamespace Test\n{\n public abstract class PacketWriter\n {\n private readonly List<byte> _buffer;\n\n internal PacketWriter()\n {\n _buffer = new List<byte>();\n }\n\n public byte[] GetBytes()\n {\n GenerateBufferContent();\n byte[] bytes = _buffer.ToArray();\n _buffer.Clear();\n return bytes;\n }\n\n protected abstract void GenerateBufferContent();\n\n // Edited, Added Encoding Parameter\n protected void Write(string value, Encoding encoding)\n {\n var bytes = encoding.GetBytes(value);\n\n _buffer.AddRange(bytes);\n }\n\n protected void Write<T>(T value) where T : unmanaged\n {\n var bytes = GetBytes(value);\n\n _buffer.AddRange(bytes);\n }\n\n // Edited, Added Encoding Parameter\n protected void Insert(string value, Encoding encoding)\n {\n var bytes = encoding.GetBytes(value);\n\n _buffer.InsertRange(0, bytes);\n }\n\n protected void Insert<T>(T value) where T : unmanaged\n {\n var bytes = GetBytes(value);\n\n _buffer.InsertRange(0, bytes);\n }\n\n private byte[] GetBytes<T>(T value) where T : unmanaged\n {\n var bytes = new byte[Unsafe.SizeOf<T>()];\n\n Unsafe.As<byte, T>(ref bytes[0]) = value;\n\n return bytes;\n }\n }\n}\n</code></pre>\n<p>Important note here is you can't use <code>String</code> with this generic method. You have to use <code>Encoding.UTF8.GetBytes</code> or <code>Encoding.ASCII.GetBytes</code>.</p>\n<p>I believe we must add a <code>where T : struct</code> or <code>where T : unmanaged</code> constraint to prevent someone from using <code>Unsafe.SizeOf<T>()</code> and <code>Unsafe.As<TFrom, TTo>(ref byte source)</code> with a managed reference type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:49:45.270",
"Id": "486218",
"Score": "0",
"body": "Don't use ASCII in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T10:55:02.290",
"Id": "486219",
"Score": "1",
"body": "@AlexanderPetrov If you have any suggestions, please explain further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T11:01:19.003",
"Id": "486220",
"Score": "0",
"body": "`Write(\"Удачи!\");` - good luck with that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T11:15:45.987",
"Id": "486221",
"Score": "3",
"body": "`Insert(string value)` if we just add `Encoding` as an argument, it would give more fixability to change the encoding whenever needed. Or Perhaps keeping a default encoding, and adding an overload method with encoding if it's required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T11:20:45.343",
"Id": "486223",
"Score": "2",
"body": "Good point, we can parameterize Encoding here. Something like `Write(string value, Encoding encoding)` would be better. And use it like `var bytes = encoding.GetBytes(value);`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T09:38:27.180",
"Id": "248269",
"ParentId": "248268",
"Score": "5"
}
},
{
"body": "<p>Would treating the types as an object and then serializing them with BinaryFormatter be a suitable way forward.</p>\n<p>Object is the base type of all C# types, even value types.</p>\n<p>Like this?</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n PacketWriter writer = new PacketWriter();\n writer.Write("Hello, World");\n writer.Write(1);\n writer.Write(true);\n\n byte[] bytes = writer.GetBytes();\n\n }\n}\n\nclass PacketWriter\n{\n private List<byte> buffer;\n\n internal PacketWriter()\n {\n buffer = new List<byte>();\n }\n\n public byte[] GetBytes()\n {\n return this.buffer.ToArray();\n }\n\n public void Write(object value)\n {\n this.Write(this.GetBytes(value));\n }\n\n protected void Write(byte[] value)\n {\n buffer.AddRange(value);\n }\n\n private byte[] GetBytes(object value)\n {\n using (MemoryStream stream = new MemoryStream())\n {\n BinaryFormatter serialiser = new BinaryFormatter();\n serialiser.Serialize(stream, value);\n\n return stream.ToArray();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T20:41:35.343",
"Id": "486272",
"Score": "0",
"body": "strings should be serialized as utf-16"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T08:32:43.633",
"Id": "486306",
"Score": "1",
"body": "This does not seem to produce very compact results. If I run your example after removing `writer.Write(\"Hello, World\");`. The length of the bytes array is 107. I would only expect 5 bytes (4 for the int and 1 for the bool)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:26:19.070",
"Id": "486322",
"Score": "1",
"body": "Yeah, that is because it treats the value as an object that can be de-serialised again. Contains additional type information, like metadata. https://stackoverflow.com/questions/4865104/convert-any-object-to-a-byte"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T20:40:10.273",
"Id": "248290",
"ParentId": "248268",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248269",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T09:18:48.863",
"Id": "248268",
"Score": "3",
"Tags": [
"c#",
".net",
"networking"
],
"Title": "Build byte array from multiple different types of data for sending over a network"
}
|
248268
|
<p>I was working on writing a fast implementation of a simple Huffman code compression of text. The idea was to write it using only the standard library, but I can't seem to find a way to make it faster. I am also looking for advise on how to write it more "Pythonic", without sacrificing speed.</p>
<p>I am aware that if I want speed I shouldn't use Python, but I've taken it as an exercise to test pure Python performance.</p>
<pre><code>from collections import Counter, defaultdict
def huffman_compress(input_file, output_file, encoding='utf8'):
"""This functions compresses a txt file using Huffman code compression."""
# Store the text in memory since it is faster than reading twice
text = open(input_file, "r", encoding=encoding).read()
# Count the times each letter appears on the text
letter_freq = Counter(text)
alphabet = defaultdict(str)
# Obtain the huffman code for each letter
while len(letter_freq) > 1:
(letter1, count1), (letter2, count2) = letter_freq.most_common(2)
letter_freq[letter1+letter2] = count1 + count2
for bit, combination in enumerate([letter1, letter2]):
for letter in combination:
alphabet[letter] = str(bit) + alphabet[letter]
del letter_freq[combination]
# Save the transformation to ascii for possible the 256 characters
bit_to_ascii = {format(x, '08b'): chr(x) for x in range(256)}
with open(output_file, 'w') as output:
# Transform each letter to its huffman code
me = ''.join(alphabet[ch] for ch in text)
# Add 0's so that the string is multiple of 8
extra_bits = 8 - len(me) % 8
me += extra_bits * '0'
# Write the number of letters compressed and the number of bits added
output.write(f'{chr(len(alphabet))}{extra_bits}')
# Write the letters compressed and their huffman code for the decompression
output.write('|'.join(c for item in alphabet.items() for c in item))
# Transform the huffman bits to ascii and save them on the compressed file.
output.write(''.join(bit_to_ascii[me[j:j+8]] for j in range(0, len(me), 8)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:03:13.470",
"Id": "486226",
"Score": "2",
"body": "How long does it take? Have you tried writing the same algorithm in a different language to check the difference in time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:51:05.577",
"Id": "486253",
"Score": "0",
"body": "Use a [profiler](https://docs.python.org/3/library/profile.html#the-python-profilers) from the stdlib to see where your code is spending most of its time. Then you know where to optimize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:25:02.620",
"Id": "486261",
"Score": "4",
"body": "As an aside note: it's probably better to separate the input reading, output writing and the huffman encoding algorithm separated. You function 'huffman_compress' only need to take text as input and returns text as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T21:14:07.883",
"Id": "486273",
"Score": "2",
"body": "There should also be a *decompression* function. Right now I can't simply do a little test to see whether it might be correct at all. And why would we care about speed when we don't even know whether it's correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:55:14.030",
"Id": "486342",
"Score": "0",
"body": "Do you have an example file to use for testing (input and expected output?)"
}
] |
[
{
"body": "<p>I started with your code, added <code>sys.argv</code> so I could pass file paths on the\ncommand line, downloaded a big text file (<em>War and Peace</em>, of course), ran your\nprogram, and checked files sizes:</p>\n<pre><code>$ curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt -k\n\n$ time python huffman.py war-peace.txt encoded\n\nreal 0m11.052s\nuser 0m10.462s\nsys 0m0.389s\n\n$ ls -lh\n-rw-r--r-- 1 fmc staff 40M Aug 24 13:51 encoded\n-rw-r--r-- 1 fmc staff 3.3M Aug 24 13:50 war-peace.txt\n</code></pre>\n<p>Looks like you have inadvertently invented an expansion algorithm: it creates a\nfile roughly 12x bigger! Also, 11 seconds seems slow to process a meager 40M of\ntext. Normally Python can crunch data of that size much more quickly.</p>\n<p>I temporarily assigned a short string (<code>huffman</code>) to the <code>text</code> variable,\nbypassing file reading, and printed out some of your intermediate variables.\nAlthough <code>letter_freq</code> looked fine, <code>alphabet</code> was the opposite of what we\nwant:</p>\n<pre><code>f 00000 # The most frequent letter has the longest code.\nh 00001\nu 0001\nm 001\na 01\nn 1\n</code></pre>\n<p>The Huffman algorithm combines the 2 elements with the <strong>least common</strong>\nfrequency, but you are doing the opposite. So I tweaked your code like this:</p>\n<pre><code>(letter1, count1), (letter2, count2) = letter_freq.most_common()[:-3:-1]\n</code></pre>\n<p>With that change, <code>alphabet</code> at least looks more plausible, the output file\nends up being smaller than the input file (although not by as much as I expect,\nso there are probably other problems in your code), and it finishes in about 1\nsecond rather than 11 (most likely because it's writing a much smaller output\nfile).</p>\n<p>Some suggestions:</p>\n<ul>\n<li><p><strong>Focus on correctness first</strong>. Worry about speed later -- and only if it\ntruly matters (and it might, if for no other reason that educational).</p>\n</li>\n<li><p><strong>Algorithms and side effects don't mix</strong>. Reorganize your code to facilitate\ntesting and debugging. The <code>huffman_compress()</code> function itself should not\nconcern itself with file reading and writing. It should take a blob of text and\nreturn a blob of bytes, period. Highly algorithmic code (as Huffman is) should\nnever have side effects; it should live in the realm of pure functions.</p>\n</li>\n<li><p><strong>Roundtrip the data</strong>. Also write a <code>huffman_expand()</code> function: take bytes,\nreturn text. Without that, you cannot have any confidence in the process. In\nparticular, you want to be able to do the following: <code>assert original_text == huffman_expand(huffman_compress(original_text))</code>. That doesn't prove that\nyou've correctly implemented Huffman (perhaps you will invent your own special\nencoding scheme, which could be cool), but at least it will prove that you can make a lossless roundtrip.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T07:24:00.547",
"Id": "486510",
"Score": "0",
"body": "What's the output file size after your change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:45:09.280",
"Id": "486560",
"Score": "0",
"body": "@superbrain I don't recall exactly, but I think it was on the order of 70% of original size -- not nearly the amount of compression I would expect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:20:06.270",
"Id": "486566",
"Score": "0",
"body": "Thanks. Should get down to about 47% when not using UTF-8 as I mentioned in my answer. What amount would you expect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:44:54.160",
"Id": "486567",
"Score": "0",
"body": "@superbrain I'm far from an expert on this topic, but default `gzip` gets the file down to 36% of original size. Seems like Huffman should be closer to `gzip` than to the roughly 70% I observed from the partly-fixed OP's code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T22:08:53.603",
"Id": "248389",
"ParentId": "248273",
"Score": "8"
}
},
{
"body": "<blockquote>\n<p>Save the transformation to ascii for possible the 256 characters</p>\n</blockquote>\n<p>ASCII doesn't have 256 characters. It has 128.</p>\n<p>And you write with the default encoding, which is UTF-8, so you write the non-ASCII half of your 256 characters as <em>two</em> bytes for no good reason whatsoever, making your file about 1.5 times as large as it should be.</p>\n<p>You should really just produce <em>bytes</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T07:49:39.907",
"Id": "248400",
"ParentId": "248273",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248389",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T11:34:15.623",
"Id": "248273",
"Score": "3",
"Tags": [
"python",
"performance",
"compression"
],
"Title": "Slow Huffman Code in pure Python"
}
|
248273
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/248203/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names">previous (i.e. first)</a> version of this tool.)</p>
<p>(See the <a href="https://codereview.stackexchange.com/questions/250150/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names-fo">next</a> follow-up.)</p>
<p>After taking into consideration all the advice by <a href="https://codereview.stackexchange.com/users/35991/martin-r">Martin R</a>, I ended up with the following tool for terminating all the processes with given process image names:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <TlHelp32.h>
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "processkiller.exe PROCESS_NAME");
return EXIT_FAILURE;
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (snapshot == INVALID_HANDLE_VALUE) {
fputs("Error: could not get the process snapshot.", stderr);
return EXIT_FAILURE;
}
size_t totalProcessesMatched = 0;
size_t totalProcessesTerminated = 0;
if (Process32First(snapshot, &entry)) {
do {
if (strcmp(entry.szExeFile, argv[1]) == 0) {
totalProcessesMatched++;
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,
FALSE,
entry.th32ProcessID);
if (hProcess == NULL) {
fprintf(stderr,
"Error: could not open the process with ID = %d, "
"called \"%s\".\n",
entry.th32ProcessID,
entry.szExeFile);
} else {
BOOL terminated = TerminateProcess(hProcess, 0);
if (terminated) {
totalProcessesTerminated++;
BOOL closed = CloseHandle(hProcess);
if (!closed) {
fprintf(stderr,
"Warning: could not close a handle "
"for process ID = %d, called \"%s\".\n",
entry.th32ProcessID,
entry.szExeFile);
}
printf("Terminated process ID %d\n", entry.th32ProcessID);
}
}
}
} while (Process32Next(snapshot, &entry));
}
BOOL snapshotHandleClosed = CloseHandle(snapshot);
if (!snapshotHandleClosed) {
fputs("Warning: could not close the process snapshot.", stderr);
}
printf("Info: total matching processes: %d, total terminated: %d.\n",
totalProcessesMatched,
totalProcessesTerminated);
return EXIT_SUCCESS;
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>Am I going anywhere? Is this tool coded properly? Am I sufficiently verbose about statistics/error information?</p>
|
[] |
[
{
"body": "<p>Regarding:</p>\n<pre><code>size_t totalProcessesMatched = 0;\nsize_t totalProcessesTerminated = 0;\n...\nprintf("Info: total matching processes: %d, total terminated: %d.\\n", \n totalProcessesMatched, \n totalProcessesTerminated);\n</code></pre>\n<p>the <code>printf()</code> is trying to output a <code>int</code>, but the variables to output are <code>size_t</code> which should be output using a <code>%zu</code> format specifier.</p>\n<p>If you compiler is not telling you about these kinds of problems, then enable the warnings until it does.</p>\n<p>regarding;</p>\n<pre><code>fprintf(stderr, "processkiller.exe PROCESS_NAME"); \n</code></pre>\n<p>This would be 1) left in the <code>stderr</code> output stream because the format string does not have a <code>\\n</code> on the end of it. 2) any program can be executed via any name so hard coding the name is a bad idea. Suggest:</p>\n<pre><code>fprintf(stderr, "%s PROCESS_NAME\\n", argv[0] );\n</code></pre>\n<p>regarding:</p>\n<pre><code>fputs("Error: could not get the process snapshot.", stderr);\n</code></pre>\n<p>strongly suggest making use of the <code>get_last_error()</code> facility and printing the actual error text to <code>stderr</code> rather than some 'random' error message</p>\n<p>regarding;</p>\n<pre><code>if (strcmp(entry.szExeFile, argv[1]) == 0) {\n</code></pre>\n<p>this does not compile because the statement:</p>\n<pre><code>#include <string.h>\n</code></pre>\n<p>is missing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T21:33:26.053",
"Id": "248292",
"ParentId": "248274",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:20:30.570",
"Id": "248274",
"Score": "2",
"Tags": [
"c",
"windows",
"winapi"
],
"Title": "A simple C WinAPI program for terminating processes via process image names - follow-up"
}
|
248274
|
<p>The question is:</p>
<blockquote>
<p>Given a non-negative int n, compute recursively (no loops) the count
of the occurrences of 8 as a digit, except that an 8 with another 8
immediately to its left counts double, so 8818 yields 4. Note that mod
(%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
by 10 removes the rightmost digit (126 / 10 is 12).</p>
<p>count8(8) → 1 count8(818) → 2 count8(8818) → 4</p>
</blockquote>
<p>My solution looked something like this:</p>
<pre><code>public int count8(int n) {
if(n == 0) return 0;
int faith = count8(n/10);
int c = 0;
if(n%10 == 8){
n /= 10;
if(n%10 == 8){
c++;
}
c++;
}
return c + faith;
}
</code></pre>
<p>Is there any way I can remove the multiple if conditions and make this cleaner and more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:51:27.880",
"Id": "486231",
"Score": "4",
"body": "Welcome to Code Review! 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. Also you'll get much better reviews if you post more of the code so that reviewers can see the context."
}
] |
[
{
"body": "<p>When dealing with recursion, its important to note down what your base and recursive cases are and go from there. These different cases will essentially become the structure of your function.</p>\n<p>You've already figured out the different cases for your problem:</p>\n<ol>\n<li>If <code>n == 0</code></li>\n<li>If 8 is in the ones digit place (<code>n % 10 == 8</code>)</li>\n<li>If 8 isn't in the ones digit place (<code>n % 10 != 8</code>)</li>\n</ol>\n<p>If <code>n == 0</code>, then we just return 0.</p>\n<p>If <code>n % 10 == 8</code>, then we know we have one 8, but we need to call <code>count8</code> again with <code>n / 10</code> as our input parameter to <code>count8</code>. <s>When we return out of this call, we add 1 to our result before returning it since we had already found one 8.</s> Now add 1 (the 8 we already found) to the result of the <code>count8</code> call.</p>\n<ul>\n<li>In this case, you will want to check if the next digit is an 8 as well. If it is, then you will want to increment your result by 1 before you return. You can do this before or after the first recursive call. Just make sure to pass in <code>n / 10</code> after you've "removed" the back-to-back 8's.</li>\n</ul>\n<p>If <code>n % 10 != 8</code>, then we simply call <code>count8</code> with <code>n / 10</code> as our input parameter and return the result from this call.</p>\n<p>Hopefully this paints a picture in how you can structure your function in a clearer way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:52:30.630",
"Id": "486266",
"Score": "0",
"body": "This answer does not consider this case: \"...except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T22:31:46.453",
"Id": "486277",
"Score": "0",
"body": "You are right, I read over that part. I will fix my answer @N.Dogac"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T15:22:36.830",
"Id": "248278",
"ParentId": "248275",
"Score": "2"
}
},
{
"body": "<p>Variable names. Name your variables after what they do, no exceptions.</p>\n<hr />\n<p>As a sidenote, note that that you're relying on how integer division works in Java.</p>\n<hr />\n<p>Having said that, you can improve the code by being explicit.</p>\n<pre class=\"lang-java prettyprint-override\"><code>// As I've said, always name your variables and functions after\n// what they are doing. Don't be afraid to use longer names,\n// longer names which tell you what the class does are a good\n// thing, even if they sound "funny".\npublic int countEights(int value) {\n // Early exit conditions are a good thing.\n if(value == 0) {\n return 0;\n }\n \n // We could also skip the declaration and instead return\n // the right count together with the function call. From\n // the viewpoint of the JVM it doesn't make a difference,\n // but here in the code it means that we have the logic\n // for stripping the last digit only once.\n int countedEights = 0;\n \n // We are testing explicitly for the mentioned "double eights",\n // this has the upside that the intent is clearly visible\n // when reading the code.\n if ((value % 100) == 88) {\n countedEights = 2;\n } else if ((value % 10) == 8) {\n countedEights = 1;\n }\n \n // And finally we call the function again in the return\n // statement, as it is easier to follow the recursion when\n // it is being called at the end of the function.\n return countedEights + countEights(value / 10);\n}\n</code></pre>\n<p>As you can see, we can completely get rid of the nested <code>if</code> by being explicit about our intent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:01:55.767",
"Id": "486712",
"Score": "0",
"body": "What do you mean with \"relying on how integer division works in Java\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T16:25:23.797",
"Id": "486817",
"Score": "0",
"body": "Dividing two integers yields an integer, dividing an integer by a float or the other way round yields a float, same for double. So if you'd happen to have a float/double instead of an integer, you'd get a float/double as result. Just something to be aware of. While we're at it, `n /= 10` is shorthand for `n = (T)(n / 10)`, with \"T\" being that type of `n`. So if we'd assume `n` to be an `int`, and you'd divide by a long `n /= 10l` the result would be silently truncated to `int`. Another small detail to be aware of."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T06:53:09.647",
"Id": "248307",
"ParentId": "248275",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248307",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T12:26:57.467",
"Id": "248275",
"Score": "1",
"Tags": [
"java",
"recursion"
],
"Title": "How to increase efficiency of recursion algorithm?"
}
|
248275
|
<p>I've been writing a modular sandbox that has a web front end. Modules are discovered with reflection and could have parameters to them. When parameters are presented to the UI, I pass them through a set of JavaScript utility methods that map them to display elements which utilize Bootstrap 5 for styling.</p>
<pre><code>function createDisplayElementForParameter(parameter) {
var displayElement = undefined;
var container = createContainer(parameter);
switch (parameter.displayElement) {
case DisplayElement.Checkbox: displayElement = createCheckbox(parameter); break;
case DisplayElement.Slider: displayElement = createSlider(parameter); break;
case DisplayElement.Textbox: displayElement = createTextbox(parameter); break;
case DisplayElement.RichTextbox: displayElement = createRichTextbox(parameter); break;
default: displayElement = createTextbox(parameter); break;
}
if (displayElement != undefined)
container.appendChild(displayElement);
container.classList.add("mb-3");
return container;
}
// Display Elements
function createHelpText(helpID, helpText) {
var container = createContainer();
container.id = helpID;
container.classList.add("form-text");
container.innerText = helpText;
return container;
}
function createCheckbox(parameter) {
var container = createContainer();
container.classList.add("form-check");
var inputID = "de-cb-" + parameter.name;
container.appendChild(createInput(inputID, "checkbox", "form-check-input", undefined));
container.appendChild(createLabel(parameter.requestMessage, inputID, "form-check-label"));
return container;
}
function createSlider(parameter) {
var container = createContainer();
var inputID = "de-rng-" + parameter.name;
var helpID = inputID + "-help";
var range = createInput(inputID, "range", "form-range", helpID);
range.setAttribute("min", parameter.minValue.toString());
range.setAttribute("max", parameter.maxValue.toString());
range.setAttribute("step", "1");
container.appendChild(createLabel(parameter.displayName, inputID, "form-label"));
container.appendChild(range);
container.appendChild(createHelpText(helpID, parameter.requestMessage));
return container;
}
function createTextbox(parameter) {
var container = createContainer();
var inputID = "de-tb-" + parameter.name;
var helpID = inputID + "-help";
container.appendChild(createLabel(parameter.displayName, inputID, "form-label"));
container.appendChild(createInput(inputID, "text", "form-control", helpID));
container.appendChild(createHelpText(helpID, parameter.requestMessage));
return container;
}
function createRichTextbox(parameter) {
var container = createContainer();
var inputID = "de-rtb-" + parameter.name;
var helpID = inputID + "-help";
var richTextbox = createInput(inputID, "textarea", "form-control", helpID);
richTextbox.setAttribute("rows", "3");
container.appendChild(createLabel(parameter.displayName, inputID, "form-label"));
container.appendChild(range);
container.appendChild(createHelpText(helpID, parameter.requestMessage));
return container;
}
// Natural Elements
function createContainer() {
var container = document.createElement("DIV");
return container;
}
function createInput(id, type, bootstrapClass, describedBy) {
var input = document.createElement("INPUT");
input.id = id;
input.setAttribute("type", type);
input.classList.add(bootstrapClass);
if (describedBy != null && describedBy != undefined)
input.setAttribute("aria-describedby", describedBy);
return input;
}
function createLabel(innerText, forID, bootstrapClass) {
var label = document.createElement("LABEL");
label.setAttribute("for", forID);
label.classList.add(bootstrapClass);
label.innerText = innerText;
return label;
}
</code></pre>
<ul>
<li>What are some negative impacts of this implementation?</li>
<li>Are there any hidden gotchas?</li>
<li>What are some things to think about as I expand this to support more elements?</li>
<li>For example <code>select</code>, <code>file</code> etc.</li>
</ul>
<p>Feel free to view the live version of this code <a href="https://galacticsandbox.azurewebsites.net/" rel="nofollow noreferrer">here</a>. You'll have to click <code>Modules</code> in the nav bar, then select a module (AES Cryptography and Display Element are two good ones for parameter testing), and the details page will appear which utilizes the code in this post to display parameters. There are a lot of items that I have to rewire today due to the recent style changes I made, but it's for a better user experience overall, so I'm okay with it.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T14:22:37.687",
"Id": "248277",
"Score": "2",
"Tags": [
"javascript",
"html5",
"twitter-bootstrap"
],
"Title": "Generating display elements with JavaScript"
}
|
248277
|
<p>I recently gave a coding test for a job which failed. It had two problems and one of them is shared in this question along with my solution.</p>
<p><strong>Problem:</strong> Get balance of all transactions in a given category within specified period.</p>
<p>This is how a typical transaction looks like:</p>
<pre><code>{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'grocery_shop',
amount: -30,
category: 'groceries',
time: '2018-03-12T12:34:00Z'
}
</code></pre>
<p>Negative value for amount means amount has been spent in that transaction.</p>
<p><strong>Input</strong></p>
<ol>
<li><strong>transactions</strong> an array of transactions.</li>
<li><strong>category</strong> it can be eating_out, groceries or any other type</li>
<li><strong>start</strong> it is the start date (inclusive)</li>
<li><strong>end</strong> it is the end date. (exclusive)</li>
</ol>
<p><strong>General Requirements</strong></p>
<p>Here is what they said they are looking for in my solution:</p>
<blockquote>
<p>This is a coding challenge which tests your coding abilities and to make sure you can present us with <strong>well written</strong>, <strong>well tested</strong> and <strong>not over-engineered</strong> code. We're looking for a <strong>well structured</strong>, <strong>tested</strong>, <strong>simple</strong> solution. As mentioned before the engineering teams work in a TDD environment and code is driven by the testing methodology as we are deploying code on a daily basis. It's a very collaborative environment so there is a lot of pair and mob programming happening which is why the code that is written needs to be able to be <strong>understood by others in your team</strong>.</p>
</blockquote>
<p><strong>My Solution</strong></p>
<pre><code>const moment = require('moment')
function getBalanceByCategoryInPeriod(transactions = [], category, start, end) {
let balance = 0
if (moment(start).isSame(end)) {
end = moment(end).endOf('day')
}
// Filters the transactions based on category and given duration
let filteredTransactions = transactions
.filter(transaction => transaction.category === category)
.filter(transaction => {
let transactionDate = transaction.time
return (moment(transactionDate).isSameOrAfter(start) &&
moment(transactionDate).isBefore(end))
})
// Calculates the balance
balance = filteredTransactions
.map(transaction => transaction.amount)
.reduce((total, amount) => total + amount, 0)
return balance
}
</code></pre>
<p>All the unit tests for this function pass. The summarized feedback of my both solutions was that the code is <em>inefficient</em>.</p>
<p>Here is the detailed feedback to me by those who reviewed my submitted code:</p>
<ul>
<li>Solutions are overall inefficient. Naming convention is good the idea behind some unitary functions is well intended but badly executed. (negative feedback)</li>
<li>Easy to Maintain, (positive feedback)</li>
<li>Easy to Read, (positive feedback)</li>
<li>Advanced Grasp of Language (positive feedback)</li>
<li>Inefficient Solution (negative feedback)</li>
<li>There is actually no need to have two loops for this exercise. But it's well structured and readable. Since it's doing two different things a better result of this approach would have been to have two different functions. (General Feedback)</li>
</ul>
<p>I am understanding part of the feedback. It is overall feedback to both coding problems and I have only presented one of them here. I am not sure to which one the feedback applies. I will publish the second problem in next question.</p>
<p>Please let me know what else can be improved in my code and how can I make it efficient. Please give me your complete feedback regarding efficiency, performance etc.</p>
<p>Thank you.</p>
<p><strong>EDIT</strong></p>
<p>Here are my tests as requested in comments:</p>
<pre><code>const assert = require("chai").assert;
describe("getBalanceByCategoryInPeriod()", function() {
it("returns 0 if there are no transactions", function() {
assert.equal(
getBalanceByCategoryInPeriod(
[],
"groceries",
new Date("2018-03-01"),
new Date("2018-03-31")
),
0
);
});
it("returns 0 if there are no transactions for given category", function() {
assert.equal(
getBalanceByCategoryInPeriod(
[{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -30,
category: 'eating_out',
time: '2018-03-12T12:34:00Z'
}],
"groceries",
new Date("2018-03-01"),
new Date("2018-03-31")
),
0
);
});
it("returns 0 if there are no transactions within specified time period", function() {
assert.equal(
getBalanceByCategoryInPeriod(
[{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -30,
category: 'groceries',
time: '2018-02-12T12:34:00Z'
}],
"groceries",
new Date("2018-03-01"),
new Date("2018-03-31")
),
0
);
});
it("returns correct balance if specified period is just one day", function() {
assert.equal(
getBalanceByCategoryInPeriod(
[{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'grocery_shop',
amount: -30,
category: 'groceries',
time: '2018-03-12T12:34:00Z'
},
{
id: 124,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -40,
category: 'groceries',
time: '2018-03-12T12:44:00Z'
}],
"groceries",
new Date("2018-03-12"),
new Date("2018-03-12")
),
-70
);
});
it("returns correct balance and exlude the end date day as it is exlusive", function() {
assert.equal(
getBalanceByCategoryInPeriod(
[{
id: 123,
sourceAccount: 'my_account',
targetAccount: 'grocery_shop',
amount: -40,
category: 'groceries',
time: '2018-03-12T12:34:00Z'
},
{
id: 124,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -40,
category: 'groceries',
time: '2018-03-16T12:44:00Z'
},
{
id: 125,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -40,
category: 'eating_out',
time: '2018-03-17T12:44:00Z'
},
{
id: 126,
sourceAccount: 'my_account',
targetAccount: 'coffee_shop',
amount: -40,
category: 'groceries',
time: '2018-03-30T12:44:00Z'
}],
"groceries",
new Date("2018-03-01"),
new Date("2018-03-30")
),
-80
);
});
// add your tests here
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:09:49.813",
"Id": "486248",
"Score": "0",
"body": "Where are your own tests? If they're looking for a TDD approach, it's customary to supply the tests used during your **test** driven development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:57:18.607",
"Id": "486267",
"Score": "1",
"body": "I have not added tests to this post here to make the post simple and short. I have tests written somewhere else. Let me add these here if they help."
}
] |
[
{
"body": "<p>It is inefficient and overengineered because the code</p>\n<ol>\n<li><p>loops through the transactions several times when once would be enough, both by the multiple filters and the two separate loops.</p>\n</li>\n<li><p>uses more memory than needed, partly due to the above and partly due to the creation of the array "filteredTransactions"</p>\n</li>\n<li><p>calls <code>moment()</code> up to twice to convert the timestamp, when once would suffice.</p>\n</li>\n</ol>\n<p>It is less maintainable / understandable by others in the team because</p>\n<ol start=\"4\">\n<li>some may not commonly use map/filter and most may not commonly use <code>reduce</code> which is particularly complex. (See also any article on <a href=\"https://dzone.com/articles/software-design-principles-dry-and-kiss\" rel=\"nofollow noreferrer\">KISS</a>)</li>\n</ol>\n<p>You are overthinking this with filter and reduce and consuming more memory and cpu than needed in the process. If I got this code I would think that the interviewee was trying to impress me that they know about <code>filter</code> and <code>reduce</code> but the code ends up way longer and more complex than needed.</p>\n<p>A simpler version would be</p>\n<pre><code>sum = 0\ntransactions.forEach(t => {\n if (t.category == category) {\n let d = moment(transactionDate)\n if (d.isSameOrAfter(start) && d.isBefore(end)) {\n sum += d.amount\n }\n }\n})\nreturn sum\n</code></pre>\n<p>This code is half the lines and almost no intermediate variables.</p>\n<p>It does not require the next guy to understand filter, map or reduce.</p>\n<p>It does not look at any transaction more than once.</p>\n<p>It does not create 3 intermediate lists of transactions / numbers.</p>\n<p>See also <a href=\"https://stackoverflow.com/questions/45691907/is-using-several-filter-calls-on-a-big-array-bad-for-performance-in-javascrip\">this</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T02:42:42.673",
"Id": "486291",
"Score": "0",
"body": "Thanks. I will dry run your solution. It looks simpler than mine. I used the maps and filters as interviewer had asked me to demonstrate your knowledge of modern programming language structs too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T03:46:14.790",
"Id": "486296",
"Score": "0",
"body": "I worked on this with few variable name changes. It works like a charm. You are right. I just over-engineered it. When they said, you need to use modern programming language features, my just shifted on using them instead of thinking of simple solution for the problem. How stupid I became!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T23:22:27.173",
"Id": "486389",
"Score": "0",
"body": "I don't know of course what they meant by \"modern programming language features\" , that could mean almost anything. But I think shortness, easy to read and maintainable code is a higher priority in any multi-developer commercial team, than modern features used for the sake of being modern. One modern feature might be using \"forEach\" rather than the older style for loop where you do `for (x = 0 ; x < array.size; x++)` , where *forEach* certainly is more readable and maintainable as well as being modern."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T00:00:54.777",
"Id": "248296",
"ParentId": "248279",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248296",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T15:29:29.670",
"Id": "248279",
"Score": "4",
"Tags": [
"javascript",
"array"
],
"Title": "Interview Coding Test: Transaction Processing: Get balance by category in given period"
}
|
248279
|
<p>I have decided to create a program that can factor and solve quadratic expressions in micropython, where the standard library is limited, and i have no idea how to implement external modules onto it, so i had to bake this program from scratch.</p>
<p>The simple premise is, that it can factor and solve most quadratic expressions, and displays the solutions in ways to make it easier to check your solution.</p>
<p>I have documented part of the program to make it easier to understand what each part of the program does.
I would like some advice on optimizing and making the program more efficient and compact, based on the idea of micropython.</p>
<pre><code># quadratic factorer, and solver
from math import sqrt
def is_integer(n):
"""
checks if the float given is an integer
True - float can be an integer
False - float is not an integer
"""
return int(n) == n
def gcd(*values):
"""
finds the greatest common divisor of values
and returns the absolute value of the divisor
"""
x, *b = values
for y in b:
while y != 0:
(x, y) = (y, x % y)
return abs(x)
def isclose(a, b, tolerance):
"""
checks whether the difference between the two values are smaller or equal to the tolerance
return True - yes
return False - no
"""
return abs(a-b) <= tolerance
def fraction(a, factor=0, tolerance=0.01):
"""
Uses brute force, to turn a float into a fraction
if a is a whole number, then it is returned.
if a is a float, then the closest possible fraction to tolerance level of difference
and returns a fraction in string format.
"""
while True:
factor += 1
a_rounded = int(round(a*factor))
if isclose(a*factor, a_rounded, tolerance):
break
if factor == 1:
return a_rounded
else:
return "{}/{}".format(a_rounded, factor)
def simplify_fraction(numer, denom):
"""
simplifies a fraction, to a simpler form
"""
if denom == 0:
return None, None
# Remove greatest common divisor:
common_divisor = gcd(numer, denom)
return numer // common_divisor, denom // common_divisor
def get_determinant(a, b, c):
"""
returns the determinant of a polynomial ax^2 + bx + c
"""
return b**2 - 4*a*c
def factors(n):
"""
finds the factors of n, and returns a list of factors (unordered)
"""
return list(set(x for tup in ([i, n//i]
for i in range(1, int(sqrt(n))+1) if n % i == 0) for x in tup))
def simplify_sqrt(n):
"""
simplifies the n in sqrt(n)
and turns it into a surd
return values:
(x, y) --> xsqrt(y)
- x is the coefficient of the surd
- y is the value remaining in the sqrt
(0, y) --> sqrt(y)
(y, 0) --> y
"""
perfect_square = None
float_to_int = lambda x: int(x) if is_integer(x) else x
for factor in sorted(factors(n), reverse=True)[:-1]:
if is_integer(sqrt(factor)):
perfect_square = factor
break
if perfect_square == n:
return (int(sqrt(perfect_square)), 0)
elif perfect_square:
factor1 = sqrt(perfect_square)
factor2 = n / perfect_square
return (float_to_int(factor1), float_to_int(factor2))
else:
return (0, n)
def format_tuple_to_sqrt(A, B): # Asqrt(B)
"""
turns a tuple from simplify_sqrt to an actual string representation.
"""
if A == 0:
A = ""
elif B == 0:
return str(A)
return "{}sqrt({})".format(A, B)
def solve_completing_the_square(a, b, c):
"""
( x +- ysqrt(B) )/z
acquires the values of x, y, B, and z by reverse engineering the solutions
and returns them
"""
f = simplify_sqrt(get_determinant(a, b, c))
g = gcd(f[0], 2*a, -b)
# x, y, B, z
return -b/g, [int(f[0]/g), f[1]], (2*a)/g # x, (h[0], h[1]), z
def format_complete_the_square_solutions(x, h, z):
"""
h = (y, B) --> ysqrt(B)
acquires the x, h, and z
and formats a proper string representation for the solution using complete the square
if z is 1
then no '/1' is shown.
"""
# ( x +- h[0]sqrt(h[1]) )/z
h[0] = 0 if h[0] == 1 else h[0]
h = format_tuple_to_sqrt(*h)
if z < 0:
x, z = x*-1, z*-1
sol1 = "( {} + {} )/{}".format(int(x), h, int(z))
sol2 = "( {} - {} )/{}".format(int(x), h, int(z))
if z == 1:
return sol1[:-2], sol2[:-2]
return sol1, sol2
def solve_quadratic_equation(a, b, c):
"""
returns a tuple of solutions, if a polynomial abc, has atleast 1 solution, else returns None
formula = (-b+-sqrt(b^2-4ac))/2a
"""
# two solutions, or one solution
if get_determinant(a, b, c) >= 0:
return ( (-b+sqrt(get_determinant(a, b, c))) / (2*a), (-b-sqrt(get_determinant(a, b, c))) / (2*a)) # (x1, x2)
# no solutions
else:
return None, None
def factor_quadratic_equation(a, b, c):
"""
factors the quadratic polynomial a, b, c on multiple conditions
support when
1) c = 0
2) b = 0 (if perfect square)
3) a, b, c present
4) complete the square is involved
"""
get_sign = lambda x: "+" if x > 0 else "-" # set the sign based on x's value
flip_sign_if_negative = lambda x, sign: -x if sign == '-' else x # switch the signs for formatting if sign == '-'
float_to_int = lambda x: int(x) if is_integer(x) else x # only if the float is actually an integer like 3.0
if a < 0:
a, b, c = a/-1, b/-1, c/-1
if c == 0: # factor by gcf 6x^2 - 2x
gcf = gcd(a, b)
a, b = a/gcf, b/gcf
gcf = "" if gcf == 1 else gcf
sign = get_sign(b)
b = flip_sign_if_negative(b, sign)
return "{}x({}x{}{})".format(float_to_int(gcf), fraction(a), sign, fraction(b))
else:
denom = 2*a
x1, x2 = solve_quadratic_equation(a, b, c)
if x1 and x2:
x1_numer, x2_numer = x1*denom, x2*denom
else:
x1_numer = x2_numer = None
if (not x1 and not x2) or not (is_integer(x1_numer) and is_integer(x2_numer)) or not is_integer(denom):
# factor by completing the square 2(x+3) + 1
# (x+p)^2 + q
global completing_the_square
completing_the_square = True
if a != 1:
a, b, c = a/a, b/a, c/a
p = b/(2*a)
q = c - (b**2)/(4*a)
sign1 = get_sign(p)
sign2 = get_sign(q)
p = flip_sign_if_negative(p, sign1)
q = flip_sign_if_negative(q, sign2)
return "(x{}{})^2 {} {}".format(sign1, fraction(p), sign2, fraction(q))
else:
# normal factoring (x+3)(x+3)
x1_gcd, x2_gcd = gcd(x1_numer, denom), gcd(x2_numer, denom)
x1_numer, x2_numer = -x1_numer/x1_gcd, -x2_numer/x2_gcd
x1_denom, x2_denom = denom/x1_gcd, denom/x2_gcd
gcf = gcd(a, b, c)*a/abs(a)
sign1 = get_sign(x1_numer)
sign2 = get_sign(x2_numer)
x1_numer = flip_sign_if_negative(x1_numer, sign1)
x2_numer = flip_sign_if_negative(x2_numer, sign2)
return "{}({}x{}{})({}x{}{})".format(float_to_int(gcf) if gcf != 1 else "", fraction(x1_denom) if x1_denom != 1 else "", sign1, fraction(x1_numer), fraction(x2_denom) if x2_denom != 1 else "", sign2, fraction(x2_numer))
while True:
completing_the_square = False
a = float(input("insert a: "))
b = float(input("insert b: "))
c = float(input("insert c: "))
factored_form = factor_quadratic_equation(a, b, c)
solutions = solve_quadratic_equation(a, b, c)
print(factored_form) if factored_form else print("No Factored Form")
if solutions[0]:
if completing_the_square:
solution0_fraction, solution1_fraction \
= format_complete_the_square_solutions(*solve_completing_the_square(a, b, c))
else:
solution0_fraction = "" if is_integer(solutions[0]) else fraction(solutions[0])
solution1_fraction = "" if is_integer(solutions[1]) else fraction(solutions[1])
solution1 = "x1 = {}".format(round(solutions[0], 5)) if solution0_fraction == "" else "x1 = {} or\n{}".format(round(solutions[0], 5), solution0_fraction)
solution2 = "x2 = {}".format(round(solutions[1], 5)) if solution1_fraction == "" else "x2 = {} or\n{}".format(round(solutions[1], 5), solution1_fraction)
print(solution1)
print(solution2) if solutions[0] != solutions[1] else None
else:
print("No Solution")
stop = input("'x' to stop: ")
if stop == 'x':
break
</code></pre>
|
[] |
[
{
"body": "<p>Some of your comments are superfluous, try to express intent in code. Some of your comments also lie.</p>\n<p>"checks if the float given is an integer"\nWhat if I didn't pass in a float, should you guard for it?</p>\n<p>"False - float is not an integer"\nRead that again, that is just nonsense</p>\n<p>"finds the greatest common divisor of values"\nmaybe just call the function greatest_common_divisor and remove the comment</p>\n<p>"\nreturn True - yes\nreturn False - no\n"\nOh really?</p>\n<p>"simplifies a fraction, to a simpler form"\nWhat simple form?</p>\n<p>You call one function is_integer with snake case, but another isclose, why not is_close?</p>\n<p>"turns a tuple from simplify_sqrt to an actual string representation."\nThis comment leads be to believe that these functions has to be called in very specific order, in that case, should they instead be put in a class and private and only used by the internal algorithm? What is the public interface of your solver?</p>\n<p>"if (not x1 and not x2) or not (is_integer(x1_numer) and is_integer(x2_numer)) or not is_integer(denom)"\nCould this be extracted into a function with a better, e.g. if should_factor_by_completing_square(...)</p>\n<p>Could completing_the_square not be global and be returned in the response from factor_quadratic_equation ?</p>\n<p>Could factor_quadratic_equation be split up into multiple functions, e.g. if should_factor_by_completing_square: factor_by_square(...) else normal_factoring(...)</p>\n<p>return "{}({}x{}{})({}x{}{})".format(float_to_int(gcf) if gcf != 1 else "", fraction(x1_denom) if x1_denom != 1 else "", sign1, fraction(x1_numer), fraction(x2_denom) if x2_denom != 1 else "", sign2, fraction(x2_numer))</p>\n<p>Way too long a line, split this up, what is happening?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T19:04:56.117",
"Id": "486268",
"Score": "0",
"body": "Welcome to Code Review! Technically, this is not a terrible review, but there are things that could be improved. For example, instead of saying \"Some of your comments are superfluous, try to express intent in code. Some of your comments also lie.\" it would be better to point the specific comments, explain (gently!) what could be improved and why, and perhaps suggest better ones. You might also want to read https://codereview.stackexchange.com/conduct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T20:14:41.037",
"Id": "486270",
"Score": "0",
"body": "Hi Edward that is what I am doing in the following paragraphs. Thank you for the welcoming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T01:02:40.057",
"Id": "486286",
"Score": "3",
"body": "How is \"False - float is not an integer\" nonsense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T09:34:02.473",
"Id": "486308",
"Score": "0",
"body": "is_integer is a function that takes input of any type and tries to convert it to integer, it returns false if \"float is not an integer\" which would mean it would always return false? And what does it mean \"float can be an integer\" any float can become an integer if we round it to nearest integer, so should the function always return true?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:05:19.937",
"Id": "486320",
"Score": "1",
"body": "Well **that's** nonsense. First, it's documented with \"float given\". So it's not for \"any type\" but for floats. Why would it always return false? Many floats **are** integers. They'll even tell you themselves if you ask them, for example `(3.0).is_integer()` tells you `True` (on normal Python, apparently not on micropython, otherwise they wouldn't need to reimplement it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:09:43.107",
"Id": "486350",
"Score": "1",
"body": "yeah, i knew is_integer() existed, but sadly micropython does not support it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T16:14:44.947",
"Id": "486364",
"Score": "0",
"body": "A floating-point (float) is never an integer (int) in the sense of how it is implemented in a computer. (3.0).is_integer() == true in python yet type(3.0) == <type 'float'> and type(3) == <type 'int'>, how is that so? is_integer documentation explains it, but it's a bad (imo lying) name and different than other languages such as C#, C++, JS etc. By understanding the difference on how ints (sign bit + integer value) and floats (sign bit, exponent and manissa) are implemented in a computer it will become clear.\nSome floats can be converted to ints without losing any information and vice versa."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T16:32:33.857",
"Id": "486366",
"Score": "1",
"body": "Integer-datatypes don't have a monopoly on the word [integer](https://en.wikipedia.org/wiki/Integer)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:41:43.240",
"Id": "248285",
"ParentId": "248281",
"Score": "-1"
}
},
{
"body": "<p>Is there any place in <code>factor_quadratic_equation</code> where the return value of <code>flip_sign_if_negative(x,sign)</code> is something other than the absolute value of <code>x</code>?\nIf not, I would recommend using absolute value, since that's a familiar function already.</p>\n<p>Why <code>a/-1</code> rather than <code>-a</code>?</p>\n<p>The simple parts are well documented (though most of them would be easy to understand even without documentation), but then there are complicated parts with little or no explanation. And I'm not convinced that you've given much thought to what you really want <code>factor_quadratic_equation</code> to do.</p>\n<p>You've written a fairly complicated algorithm here. Have you tested it to see whether the results are what you expected?</p>\n<p>I copied your functions into in Python 3.8.3 and tried some examples of my own.</p>\n<p><code>factor_quadratic_equation(1,4,3)</code> returned '(x+1)(x+3)'.\nThat's good.</p>\n<p><code>factor_quadratic_equation(0.5,2,1.5)</code> returned '0.5(x+1)(x+3)'.\nAlso good.</p>\n<p><code>factor_quadratic_equation(0.125,0.5,0.375)</code> returned\n'(x+2)^2 - 1'. <strong>What?</strong>\nWhy isn't the answer '0.125(x+1)(x+3)'?\nHow is '(x+2)^2 - 1' even considered the same polynomial as\n(1/8)x^2+(1/2)x+(3/8), let alone being considered a <strong>factorization</strong> of that polynomial?</p>\n<p>I can understand that when a real quadratic has no zeros, and hence literally <strong>cannot</strong> be factored into real monomials, you might fall back to the vertex representation as a useful explanation, but this function seems all too eager to fall back to that representation for quadratics with zeros.</p>\n<p><code>factor_quadratic_equation(1.33,1.2,0)</code> returns<br />\n'1.1102230246251565e-15x(1197957500880552x+1080863910568919)'.<br />\nI suppose this has something to do with the inexact representations of 1.33 and 1.2 in IEEE 754, but it seems bizarre.</p>\n<p><code>factor_quadratic_equation(133,120,0)</code> produced a traceback, at the bottom of which was</p>\n<blockquote>\n<p>ValueError: invalid literal for int() with base 10: ''</p>\n</blockquote>\n<p>And yet <code>factor_quadratic_equation(133/2,120/2,0)</code> returns '0.5x(133x+120)', as one might expect.</p>\n<p><code>factor_quadratic_equation(6,5,0)</code> also produced a traceback.</p>\n<p>What do you think the results <strong>should</strong> be in all these cases?\nI still have some questions about coding style, but I think correct behavior is an even higher priority.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:52:24.593",
"Id": "486341",
"Score": "0",
"body": "i believe the results are accurate for the vertex form, and the result returned \"'1.1102230246251565e-15x(1197957500880552x+1080863910568919)'\" is a consequence of my fraction function being unable to find the proper fraction to represent the answer as."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:57:36.987",
"Id": "486344",
"Score": "0",
"body": "'(x+2)^2 - 1' is not accurate for 0.125x^2+0.5x+0.375. It has the same zeros but the wrong vertex: (-2,-1) when it should be (-2,-0.125). And the fact your fraction function is having trouble finding a good representation just means your fraction function performs poorly. Test the gcd function; it also shows this kind of behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:08:35.133",
"Id": "486349",
"Score": "0",
"body": "i see, do you think finding the least common multiple which is an integer, would solve this issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:11:57.150",
"Id": "486351",
"Score": "0",
"body": "It might help, but notice how when we change `factor_quadratic_equation(1.33,1.2,0)` to `factor_quadratic_equation(133,120,0)` it breaks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:13:46.777",
"Id": "486354",
"Score": "0",
"body": "To be honest I was surprised how well the gcd function worked for non-integer values. The `%` operator in python is more versatile than I realized. You learn something new every day!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T19:20:24.737",
"Id": "486375",
"Score": "0",
"body": "i have fixed most of the problems mentioned, by adding a gcd that works with floats, and changing the values so that they are whole."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T02:27:17.037",
"Id": "248299",
"ParentId": "248281",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248299",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:06:05.773",
"Id": "248281",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel",
"mathematics"
],
"Title": "Quadratic Expression Factorer and Solver"
}
|
248281
|
<p>I would like a code-review. Not so much on if the implementation is good or effecient, it's probably not, more on code style and readability.</p>
<pre><code>import java.lang.Exception
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.util.*
import kotlin.math.abs
fun main() {
val filterSize = 1_000_000
val numberOfEntries = 100_000
val filter = BloomFilter(filterSize, numberOfHashes = 4)
val entriesInFilter = Array(numberOfEntries) { randomString() }
val entriesNotInFilter = Array(numberOfEntries) { randomString() }
for (entry in entriesInFilter)
filter.add(entry)
val confusionMatrix = ConfusionMatrix(filter, entriesInFilter, entriesNotInFilter)
confusionMatrix.printReport()
if (confusionMatrix.falseNegativeRate > 0.0) {
throw Exception("This should not happen, if it does the implementation of the bloom filter is wrong.")
}
}
class BloomFilter(private val size: Int, numberOfHashes: Int) {
private val flags = BitSet(size)
private val salts = IntArray(numberOfHashes) { it }.map { it.toString() }
private val sha = MessageDigest.getInstance("SHA-1")
fun add(entry: String) {
for (salt in salts) {
val index = hashedIndex(entry, salt)
flags.set(index)
}
}
fun maybeExists(entry: String): Boolean {
for (salt in salts) {
val index = hashedIndex(entry, salt)
if (!flags[index]) {
return false
}
}
return true
}
private fun hashedIndex(entry: String, salt: String): Int {
val salted = entry + salt
val hash = sha.digest(salted.toByteArray())
val wrapped = ByteBuffer.wrap(hash)
return abs(wrapped.int) % size
}
}
class ConfusionMatrix(filter: BloomFilter, entriesInFilter: Array<String>, entriesNotInFilter: Array<String>) {
private val inFilterCount = entriesInFilter.size
private val notInFilterCount = entriesNotInFilter.size
private var truePositiveCount = 0
private var trueNegativeCount = 0
private var falsePositiveCount = 0
private var falseNegativeCount = 0
val accuracyRate by lazy { (truePositiveCount + trueNegativeCount).toDouble() / (notInFilterCount + inFilterCount) }
val misclassificationRate by lazy { 1.0 - accuracyRate }
val truePositiveRate by lazy { truePositiveCount.toDouble() / inFilterCount }
val trueNegativeRate by lazy { trueNegativeCount.toDouble() / notInFilterCount }
val falsePositiveRate by lazy { falsePositiveCount.toDouble() / notInFilterCount }
val falseNegativeRate by lazy { falseNegativeCount.toDouble() / inFilterCount }
init {
countTruePositiveAndFalseNegative(entriesInFilter, filter)
countFalsePositiveAndTrueNegative(entriesNotInFilter, filter)
}
private fun countTruePositiveAndFalseNegative(entriesInFilter: Array<String>, filter: BloomFilter) {
for (entryInFilter in entriesInFilter) {
if (filter.maybeExists(entryInFilter)) {
truePositiveCount++
} else {
falseNegativeCount++
}
}
}
private fun countFalsePositiveAndTrueNegative(entriesNotInFilter: Array<String>, filter: BloomFilter) {
for (entryNotInFilter in entriesNotInFilter) {
if (filter.maybeExists(entryNotInFilter)) {
falsePositiveCount++
} else {
trueNegativeCount++
}
}
}
fun printReport() {
val dataRows = mapOf(
"Accuracy" to accuracyRate,
"Misclassification rate" to misclassificationRate,
"True positive rate" to truePositiveRate,
"True negative rate" to trueNegativeRate,
"False positive rate" to falsePositiveRate,
"False negative rate" to falseNegativeRate
)
val printer = Printer(dataRows)
printer.print()
}
}
class Printer(private val dataRows: Map<String, Double>) {
private val spacing = 2
private val longestLabelLength = getLongestString(dataRows.keys, default=50) + spacing
private val stringBuilder = StringBuilder()
private fun getLongestString(labels: Set<String>, default: Int): Int {
return labels.map { it.length }.max() ?: default
}
fun print() {
for ((label, value) in dataRows) {
printLabel(label)
printPadding(label)
printFormattedValue(value)
println()
}
}
private fun printLabel(label: String) {
print("$label:")
}
private fun printPadding(label: String) {
val paddingNeeded = longestLabelLength - label.length
stringBuilder.clear()
for (x in 0 until paddingNeeded) stringBuilder.append(" ")
print(stringBuilder.toString())
}
private fun printFormattedValue(value: Double) {
val width6digits2 = "%6.2f"
val percentage = String.format(width6digits2, value * 100) + "%"
print(percentage)
}
}
private fun randomString(): String {
return UUID.randomUUID().toString()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T18:18:05.890",
"Id": "486725",
"Score": "1",
"body": "Why are you using `lazy` for trivial division operations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T19:16:06.160",
"Id": "486831",
"Score": "0",
"body": "Yes it's probably overkill. I don't like them to be var or even private set as var, as they are only set once which is exactly was lazy does when called and then saves for later. In C# we have the readonly modifier where fields can be set only in object initialization, but then still remain public and communicate clearly that this is constant after initialization. Does Kotlin have similar, what would you suggest?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T19:18:57.677",
"Id": "486832",
"Score": "1",
"body": "`=` is uglier than `by lazy { }`? Or if you just define them as Doubles, you can set them one time in the `init` block, like you described doing in C#."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T19:28:45.733",
"Id": "486834",
"Score": "0",
"body": "But then I have to make them var with private set. Which 1) gives two lines instead of one for each property and 2) gives the impression that accuracyRate can change after initialization.\n `var accuracyRate = 0.0\n private set`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T19:31:26.180",
"Id": "486835",
"Score": "1",
"body": "You don't have to make it a var. https://pl.kotl.in/1yNSwYOwh"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T19:38:25.937",
"Id": "486836",
"Score": "0",
"body": "I did not know that! Thanks a bunch, I like that much better. I updated the code on gist. https://gist.github.com/peheje/98070f0b065c1ed10917b40dab30bd29"
}
] |
[
{
"body": "<p><strong>After looking at it a bit</strong></p>\n<p>hashedIndex does many things. It salts the input, hashes it, wraps it and makes sure it fits into the size. Could it be split up and more clear what is happening?</p>\n<p>The confusion matrix seems like a general mathy thing, why does it have a direct dependency on a BloomFilter and its data? Try to come up with some way of decoupling these so the confusion matrix can be reused for other statistical purposes.</p>\n<p>countTruePositiveAndFalseNegative and countFalsePositiveAndTrueNegative looks a lot like repetition, can the logic be moved to a single implementation?</p>\n<p>None of the classes implement interfaces or abstract methods, so using them would require a dependency to the concrete implementation, making the depende unnecessarily difficult to test and change.</p>\n<p>There is a possible divide by zero issue if inFilterCount or notInFilterCount is zero.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T19:02:36.113",
"Id": "486591",
"Score": "0",
"body": "I got around the dependency from ConfusionMatrix to Bloomfilter by using a lambda that \"predicts\", which I think is a good use of lambdas compared to a solution using e.g. adapter pattern, where a lot of boilerplate would be created."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T16:32:24.203",
"Id": "248325",
"ParentId": "248286",
"Score": "0"
}
},
{
"body": "<p>Here's how I'd clean up the ConfusionMatrix class. I don't know anything about this algorithm, but this should be equivalent code. You can calculate and set these read-only values at their declaration sites if you do them in order. So all parameters can be <code>val</code> and you don't need <code>lazy</code>, which wraps your property in a <code>Lazy</code> class. There are no custom getters and there are no setters, so the whole class is immutable and compact with no references to anything else once it's instantiated.</p>\n<pre><code>class ConfusionMatrix(filter: BloomFilter, entriesInFilter: Array<String>, entriesNotInFilter: Array<String>) {\n private val inFilterCount = entriesInFilter.size\n private val notInFilterCount = entriesNotInFilter.size\n\n private val truePositiveCount = entriesInFilter.count { filter.maybeExists(it) }\n private val falseNegativeCount = entriesInFilter.size - truePositiveCount\n private val falsePositiveCount = entriesNotInFilter.count { filter.maybeExists(it) }\n private val trueNegativeCount = entriesNotInFilter.size - truePositiveCount\n\n val accuracyRate = (truePositiveCount + trueNegativeCount).toDouble() / (notInFilterCount + inFilterCount)\n val misclassificationRate = 1.0 - accuracyRate\n val truePositiveRate = truePositiveCount.toDouble() / inFilterCount \n val trueNegativeRate = trueNegativeCount.toDouble() / notInFilterCount\n val falsePositiveRate = falsePositiveCount.toDouble() / notInFilterCount\n val falseNegativeRate = falseNegativeCount.toDouble() / inFilterCount\n\n fun printReport() {\n val dataRows = mapOf(\n "Accuracy" to accuracyRate,\n "Misclassification rate" to misclassificationRate,\n "True positive rate" to truePositiveRate,\n "True negative rate" to trueNegativeRate,\n "False positive rate" to falsePositiveRate,\n "False negative rate" to falseNegativeRate\n )\n val printer = Printer(dataRows)\n printer.print()\n }\n}\n</code></pre>\n<p>Knowing nothing of the algorithm, I'd say BloomFilter is pretty clean, but you could more naturally write the declaration of <code>salts</code> like this:</p>\n<pre><code>private val salts = (0..numberOfHashes).map { it.toString() }\n</code></pre>\n<p>or</p>\n<pre><code>private val salts = (0..numberOfHashes).map(Int::toString)\n</code></pre>\n<p>The second form is usually preferred to lambdas when there's a function that exactly matches the required signature because it shows the type. Not really helpful here, but helpful in a chain of functional calls to make it more readable later.</p>\n<p>In your main method, a couple of little tips...</p>\n<p>When you want to do some sort of logging type of action without side effects as you are assigning something to a variable, you can use <code>also</code>. It kind of de-emphasizes it for someone reading your code, especially if it's some action that takes a few lines of code. It's not all that useful here since this is so simple, but might be handy for you in other situations.</p>\n<pre><code>val confusionMatrix = ConfusionMatrix(filter, entriesInFilter, entriesNotInFilter)\n also { it.printReport() }\n</code></pre>\n<p>And there's a function for asserting something and throwing a runtime exception if it fails, so your last bit can be cleaned up:</p>\n<pre><code>require(confusionMatrix.falseNegativeRate > 0.0) {\n "This should not happen, if it does the implementation of the bloom filter is wrong."\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T20:04:25.300",
"Id": "248517",
"ParentId": "248286",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:44:53.223",
"Id": "248286",
"Score": "2",
"Tags": [
"kotlin",
"bloom-filter"
],
"Title": "Bloomfilter in Kotlin"
}
|
248286
|
<p>I am working on a turtle project where the user can draw their own avatar.</p>
<p>The thing is, I want the user to be able to decide whether the turtle they drew will be filled, or not.</p>
<p>The filled part is simple, as by default, the polies will get filled,
but the only way I know how to avoid filling is to retrace the lines so that the end of the line meets the start of the line.</p>
<p>Is there a built-in method or a more efficient way to keep the polies empty?
The problem with my current method is that the more lines (parameter) is used for turtle, the more rocky the program runs (the area doesn't influence the smoothness of the program).</p>
<pre><code>import turtle
wn = turtle.Screen()
pen = turtle.Turtle('circle')
pen.shapesize(0.1, 0.1)
cor = []
# function to draw with the pen
def drag(x, y):
wn.tracer(0)
pen.goto(x, y)
cor.append(pen.pos())
# function to break out of while loop
def fill():
global done
done = True
# function to break out of while loop and set fill to False
def nofill():
global done, fill
done = True
fill = False
wn.listen()
wn.onkeypress(fill, 'f')
wn.onkeypress(nofill, 'n')
pen.ondrag(drag)
done = False
fill = True
while not done:
wn.update()
pen.begin_poly()
if fill:
for c in cor:
pen.goto(c)
else:
for c in cor[::-1]: # first go backards, then forward to avoid fill
pen.goto(c)
for c in cor:
pen.goto(c)
pen.end_poly()
wn.register_shape("mypen", pen.get_poly())
wn.clear()
example = turtle.Turtle('mypen')
</code></pre>
<p>Example with fill:</p>
<ul>
<li><p>Run the above code.</p>
</li>
<li><p>Draw a shape.</p>
</li>
<li><p>Press f</p>
</li>
</ul>
<p><a href="https://i.stack.imgur.com/lO95i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lO95i.png" alt="enter image description here" /></a></p>
<p>Example without fill:</p>
<ul>
<li><p>Run the above code.</p>
</li>
<li><p>Draw a shape.</p>
</li>
<li><p>Press n</p>
</li>
</ul>
<p><a href="https://i.stack.imgur.com/tbrPm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbrPm.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T23:45:00.167",
"Id": "486281",
"Score": "0",
"body": "What does this do? Could you explain how to use this, how do you change from fill to no fill? Can you show an example of both filled and nofill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T01:18:46.017",
"Id": "486287",
"Score": "0",
"body": "@Peilonrayz Added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:03:02.247",
"Id": "486311",
"Score": "0",
"body": "For some reason whenever I press f or n it just kicks me out of the program. I can't see the filled / no filled diamond. Looking at the code this seems about right, have you missed a little bit of code off the bottom?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:09:15.393",
"Id": "486321",
"Score": "0",
"body": "@Peilonrayz It works for me, but you might need to add `wn.mainloop()` to the bottom. And just in case, you need to draw the diamond first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T13:14:40.310",
"Id": "486329",
"Score": "0",
"body": "Hmm, I've done that now and whilst the window stays around, the lines and pen(?) disappear. Hmm, I don't think I can help with this since I can't get it to work :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:39:37.853",
"Id": "486339",
"Score": "0",
"body": "@Peilonrayz Did you include `example = turtle.Turtle('mypen')`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:55:37.810",
"Id": "486343",
"Score": "0",
"body": "Ooops! Yeah that's got it working. It flips the image I draw but yeah that works."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T19:03:18.133",
"Id": "248288",
"Score": "3",
"Tags": [
"python",
"performance",
"turtle-graphics"
],
"Title": "Allowing a user to draw their own avatar in turtle"
}
|
248288
|
<p><em>Using only Python 2.7 and the standard library (no imports):</em></p>
<p><a href="https://stackoverflow.com/a/63537720/10936066">Determine if a point is inside the rotated rectangle.</a></p>
<pre><code>Test point 1: 670831 4867989
Test point 2: 675097 4869543
Rectangle:
Vertex 1: 670273 4879507
Vertex 2: 677241 4859302
Vertex 3: 670388 4856938
Vertex 4: 663420 4877144
</code></pre>
<hr />
<p>Can the following code be improved?</p>
<pre><code>vertices = [(670273, 4879507), (677241, 4859302), (670388, 4856938), (663420, 4877144)]
def dot_pdt(point1, point2, pointT):
return ((point2[0] - point1[0]) * (pointT[0] - point1[0])) + ((point2[1] - point1[1]) * (pointT[1] - point1[1]))
def check_point(pointT):
for i in range(len(vertices)):
k = dot_pdt(vertices[i], vertices[(i + 1) % len(vertices)], pointT)
if k <= 0:
return False
return True
point1 = (676455.270, 4861545.437)
print(check_point(point1))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T04:00:49.633",
"Id": "486297",
"Score": "1",
"body": "`return not any(dot_pdt(v, v_next, pointT) <= 0 for v, v_next in zip(vertices, vertices[1:] + vertices[:0]))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T17:24:45.500",
"Id": "486823",
"Score": "0",
"body": "The answer provided by Yves Daoust in the link you gave is pretty much as good as you'll find. Is there a reason you don't believe so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T18:05:17.040",
"Id": "486825",
"Score": "0",
"body": "@IEatBagels : It's a good answer, but Yves Daoust didn't actually provide code, so that's why I made my own. I'm not a great coder so I thought I'd get it reviewed."
}
] |
[
{
"body": "<h2>Code Review</h2>\n<ul>\n<li><strong>Main guard</strong></li>\n</ul>\n<p>When running code outside a function / class, it is a good practice to put the code inside the <em>main guard</em>. See <a href=\"https://docs.python.org/2/library/__main__.html\" rel=\"nofollow noreferrer\">here</a> for more explanation.</p>\n<ul>\n<li><strong>Docstrings</strong></li>\n</ul>\n<p>It is a good practice to provide docstrings for functions. See <a href=\"https://www.datacamp.com/community/tutorials/docstrings-python\" rel=\"nofollow noreferrer\">here</a> for more details. In Python 3.5+, adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> to function parameters and return values is also a good habit. (As a side remark, Python 2 has officially <a href=\"https://www.python.org/dev/peps/pep-0373/#maintenance-releases\" rel=\"nofollow noreferrer\">reached the end of life</a>. It is recommended to move to Python 3.)</p>\n<ul>\n<li><strong>Variable & function names should be clear, descriptive, and unambiguous</strong></li>\n</ul>\n<p>For example, <code>check_point</code> could be named as <code>is_inside_rectangle</code>.</p>\n<ul>\n<li><strong>Function definition should include all necessary parameters</strong></li>\n</ul>\n<p><code>vertices</code> should be a parameter of the function <code>check_point</code>.</p>\n<ul>\n<li><strong>Other minor improvements</strong></li>\n</ul>\n<p>By exploiting the fact that <code>vertices[-1]</code> is the same as <code>vertices[len(vertices)-1]</code>, the explicit modulo operation <code>vertices[(i + 1) % len(vertices)]</code> could be avoided.</p>\n<p>The <code>for</code>-loop logic can be simplified using an <code>all</code> statement.</p>\n<p>Here is an improved version of the code:</p>\n<pre><code>def dot_prod_with_shared_start(start, end1, end2):\n """\n Compute the dot product of the vectors pointing from start to end1 and end2\n\n Parameters\n start: starting point of both vectors\n end1: end point of first vector\n end2: end point of second vector\n\n Returns\n dot product of (end1 - start) and (end2 - start)\n """\n return (end1[0] - start[0]) * (end2[0] - start[0]) + (end1[1] - start[1]) * (end2[1] - start[1])\n\ndef is_inside_rectangle(vertices, point):\n """\n Given the vertices of a rectangle, determine whether a point is inside it.\n\n Parameters\n vertices: a list of tuples representing rectangle vertices in clockwise or\n counter-clockwise order\n point: a tuple representing the point to check\n\n Returns\n True if the point is inside the rectangle. False otherwise.\n """\n return all(dot_prod_with_shared_start(vertices[i - 1], v, point) > 0 for i, v in enumerate(vertices))\n\nif __name__ == "__main__":\n rect_vertices = [(670273, 4879507), (677241, 4859302), (670388, 4856938), (663420, 4877144)]\n test_point = (676455.270, 4861545.437)\n\n print(is_inside_rectangle(rect_vertices, test_point))\n</code></pre>\n<h2>Another Solution</h2>\n<p>An alternative solution is to represent the vertices and the point as complex values, and apply complex number arithmetics to solve the problem.</p>\n<pre><code>def is_directed_angle_acute(start, end1, end2):\n """\n Check whether the directed angle from (end1 - start) to (end2 - start) is an acute angle, \n i.e. within (0, pi / 4).\n\n Parameters\n start: a complex value representing the starting point of both vectors\n end1: a complex value representing the end point of first vector\n end2: a complex value representing the end point of second vector\n\n Returns\n True if the directed angle from (end1 - start) to (end2 - start) is within (0, pi / 4).\n False otherwise.\n """\n q = (end2 - start) / (end1 - start)\n return q.real > 0 and q.imag > 0\n\ndef is_inside_rectangle(vertices, point):\n """\n Given the vertices of a rectangle, determine whether a point is inside it.\n\n Parameters\n vertices: a list of complex values representing rectangle vertices in clockwise order\n point: a complex value representing the point to check\n\n Returns\n True if the point is inside the rectangle. False otherwise.\n """\n v0, v1, v2, v3 = vertices\n return is_directed_angle_acute(v0, point, v1) and is_directed_angle_acute(v2, point, v3)\n\nif __name__ == "__main__":\n rect_vertices = [670273 + 4879507j, 677241 + 4859302j, 670388 + 4856938j, 663420 + 4877144j]\n test_point = 676455.270 + 4861545.437j\n\n print(is_inside_rectangle(rect_vertices, test_point))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T10:39:23.570",
"Id": "248449",
"ParentId": "248297",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T01:10:16.993",
"Id": "248297",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"mathematics",
"jython"
],
"Title": "Determine if points are within a rotated rectangle"
}
|
248297
|
<p>To learn the ropes of Node.js and Express, I'm trying to implement a very simple REST API. The API says what it should do instead of doing it, so I can focus on the framework's structure. The requirement for the API is the following:</p>
<ul>
<li>Mock API for a question and answer game.</li>
<li>/qanda endpoint: Repository of all question-answer pairs.</li>
<li>/qanda/questionId endpoint: A specific question-answer pair.</li>
<li>Should handle HTTP verbs GET, POST, PUT, DELETE.</li>
<li>Assume HTTP request body is JSON.</li>
</ul>
<p>All this is arbitrary. I'm just trying to get the hang of dealing with and parsing of HTTP requests and responses. To keep things organized I'm also using Express Router and Node.js modules.</p>
<p>Here is index.js</p>
<pre><code>'use strict';
const express = require('express');
const qanda = require('./routes/qanda.js');
const port = 9999;
const app = express();
app.use('/qanda', qanda);
app
.all('/', (req, res, nxt) => {
res
.status(200)
.send('Welcome!');
})
.listen(port, () => {
console.log(`Listening to localhost:${port}`);
});
</code></pre>
<p>And here is ./routes/qanda.js</p>
<pre><code>'use strict';
const express = require('express');
const qandaRouter = express.Router();
qandaRouter.use(express.json());
qandaRouter
.route('/')
.get((req, res, nxt) => {
res
.status(200)
.send('Sending all the qandas!');
})
.post((req, res, nxt) => {
res
.status(200)
.send(`Adding ${req.body.q} = ${req.body.a}`);
})
.put((req, res, nxt) => {
res
.status(405)
.send('PUT not supported.');
})
.delete((req, res, nxt) => {
res
.status(200)
.send('Deleting all qands!');
});
qandaRouter
.route('/:qId')
.get((req, res, nxt) => {
res
.status(200)
.send(`Sending qanda ${req.params.qId}`);
})
.post((req, res, nxt) => {
res
.status(405)
.send('POST not supported.');
})
.put((req, res, nxt) => {
res
.status(200)
.send(`Updating ${req.params.qId} with ${req.body.q} = ${req.body.a}`);
})
.delete((req, res, nxt) => {
res
.status(200)
.send(`Deleting qanda ${req.params.qId}`);
});
module.exports = qandaRouter;
</code></pre>
<p>I'm looking forward to all kind of feedback! From style, to best practices, anti-patterns, whatever you can think of is very much appreciated! I do have some specific questions:</p>
<ul>
<li>Is method chaining the usual way to handle something like this in Express?</li>
<li>Is the method chaining style readable and maintainable?</li>
<li>Is there a more concise way to achieve this?</li>
<li>What would you do differently?</li>
</ul>
|
[] |
[
{
"body": "<p>After I examine the codes you have written, I could see some things that are not rightly done. Below are the few things I highlighted:</p>\n<ul>\n<li>The structuring of the codebase is not okay hence it can be maintainable and scalable if the codebase grows.</li>\n<li>The RESTful API naming convention is not an acceptable one. Endpoints of any REST API should contain only resources (nouns) and use HTTP methods (verbs) for actions. You named your endpoint as <strong>/qanda</strong> instead of <strong>/qandas</strong>. I recommend you read this <a href=\"https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9\" rel=\"noreferrer\">RESTful API Designing guidelines</a> by Mahesh Haldar posted at Hackernoon. It's a great resource for developers.</li>\n<li>Thirdly, you did not separate your server from express; they are both coupled together. It's not best practice to do so.</li>\n<li>When API is being consumed by other applications, upgrading the APIs with some changes would also lead to breaking the existing services contract - this has been noticed by a lot of applications that provide API services. It is a best practice to always prefix all your URLs with <strong>/api/v1/users</strong> . If there is any major breaking update, we can name the new set of APIs as <strong>v2, v3, or v1.X.X</strong>. respectively.</li>\n</ul>\n<p>From my experience, this is how I would approach it:</p>\n<ul>\n<li>Firstly, I will create a directory called, <strong>qanda-api</strong>, inside it, I'll create other directories called <strong>src</strong> and two files <strong>app.js and server.js</strong> that reside inside the root directory with <strong>src</strong></li>\n<li>Secondly, inside <strong>src</strong> I will create two sub-directories called <strong>routes and controllers</strong></li>\n<li>Thirdly, I will initialize an npm registry in the root of the project directory that keeps track of all <strong>npm</strong> installed packages by typing the command below via the terminal:</li>\n</ul>\n<blockquote>\n<p>npm init</p>\n</blockquote>\n<ul>\n<li>After that, I will install the three dependencies that I will be using via the same terminal, but this time you must have internet access:</li>\n</ul>\n<blockquote>\n<p>npm install express dotenv morgan</p>\n</blockquote>\n<ul>\n<li>If the above process executes successfully, you will see the installed packages inside a file called <strong>package.json</strong></li>\n</ul>\n<h1>Now let's do the coding by getting our hands dirty</h1>\n<ul>\n<li>Let's first create a file named <strong>controllers/qandaController.js</strong> in other to write our qanda logic that will be exported to its route file.</li>\n</ul>\n<pre><code>exports.getAllQandas = (req, res) => {\n res.status(200).json({\n status: 'success',\n message: 'Documments retrieved successfully',\n data: 'The data goes here from the data!'\n });\n};\n\nexports.getQanda = (req, res) => {\n res.status(200).json({\n status: 'success',\n message: 'Doc retrieved successfully',\n data: 'The data goes here from the data!'\n });\n};\n\nexports.createQanda = (req, res) => {\n res.status(201).json({\n status: 'success',\n message: 'Qanda created successfully',\n data: 'Return the created data here!'\n });\n};\n\nexports.updateQanda = (req, res) => {\n res.status(200).json({\n status: 'success',\n message: 'Doc updated successfully',\n data: 'The updated data goes here!'\n });\n};\n\nexports.deleteQanda = (req, res) => {\n res.status(200).json({\n status: 'success',\n message: 'Doc deleted!',\n data: 'Return the Deleted data'\n });\n};\n</code></pre>\n<ul>\n<li>Now, it's time for us to create our <strong>qanda</strong> route in <strong>routes/qandaRoutes.js</strong>. We will then import the controller logic in its route handler below.</li>\n</ul>\n<pre><code>const express = require('express');\n/**\n * import the qanda controller\n */\nconst qandaController = require('./../controllers/qandaController');\n\nconst router = express.Router();\n\nrouter\n .route('/')\n .get(qandaController.getAllQandas)\n .post(qandaController.createQanda);\n\nrouter\n .route('/:id')\n .get(qandaController.getQanda)\n .patch(qandaController.updateQanda)\n .delete(qandaController.deleteQanda);\n\nmodule.exports = router;\n</code></pre>\n<ul>\n<li>Let's open the file we created earlier on called <strong>app.js</strong> in other to make use of the express we had installed. The content of this file is only for express which is then exported to its server:</li>\n</ul>\n<pre><code>const express = require('express');\nconst morgan = require('morgan');\n\nconst qandaRouter = require('./routes/qandaRoutes');\n\nconst app = express();\n \nif (process.env.NODE_ENV === 'development') app.use(morgan('dev'));\n\n// ROUTES\napp.use('/api/v1/qandas', qandaRouter);\n \n/*\n ** HANDLING UNHANDLED ROUTES\n */\napp.all('*', (req, res, next) => {\n res.status(404).json({\n status: 'fail',\n message: `Can't find ${req.originalUrl} on this Server!`\n });\n});\n \nmodule.exports = app;\n</code></pre>\n<ul>\n<li>Let's create our server which becomes our entry point to the application. This where the actual execution happens whereby the exported <strong>app.js</strong> get used by inserting it as an argument in the createServer() function.</li>\n</ul>\n<pre><code>require('dotenv').config({ path: '.env' });\nconst http = require('http');\n\nconst app = require('./app');\n\nconst port = process.env.PORT || 5000;\n\nconst server = http.createServer(app);\n\nserver.listen(port, () => console.log(`App running on port ${port}`));\n</code></pre>\n<h2>Conclusion</h2>\n<p>It's highly recommended to always have separation of concerns while writing codes and to aptly have a clean codebase that is maintainable and scalable over time. There's more to code organization when it comes to API design, one of it is the <strong>DRY</strong> principle (Don't Repeat Yourself). If you want to learn more about API design in Node.JS I recommend you take this course by <a href=\"https://www.udemy.com/course/nodejs-express-mongodb-bootcamp/\" rel=\"noreferrer\">Jonas</a>. He demystifies the abstract concepts and taught best practices to the core. I've wrapped this answer with API design projects in Github: <a href=\"https://github.com/akeren/stackoverflow-answer\" rel=\"noreferrer\">API</a> and <a href=\"https://github.com/akeren/nodejs-tours-api\" rel=\"noreferrer\">Tourism API</a>. Feel free to clone or modify as you need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T03:53:02.610",
"Id": "486398",
"Score": "1",
"body": "I move the all routes in its own file called router.js as they grow over the time when we have mulitple versions of API. I then use that file in `app.js` like this `require('./routes')(app)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T13:44:09.550",
"Id": "248316",
"ParentId": "248298",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248316",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T01:18:06.147",
"Id": "248298",
"Score": "2",
"Tags": [
"javascript",
"api",
"rest",
"express.js"
],
"Title": "Using Node.js, Express, and Express Router to implement a very simple REST API"
}
|
248298
|
<p>I am writing a lambda function to make a request and fetch data from API.
I am using as a class based approach which I think could refactor it and write in correct way.
May be we can change this class based approach if required. Below is the approach which I have implemented.</p>
<p><strong>app.js</strong></p>
<pre><code>const apiService = require('./apiService.js');
exports.handler = (async(event, context, callback) => {
if ((event["type"]) && event["type"] != "" ){
let apiServices = new apiService(event["type"], context);
let successResponse = await apiServices.beginProcess();
let response = return {
'body': JSON.stringify(successResponse),
'statusCode': 200
};
} else {
response = {
'body':"invalid request",
'statusCode': 200
};
return response
}
});
</code></pre>
<p><strong>apiService.js</strong></p>
<pre><code>const getCredentialsService = require('./modules/getCredentials')
let getCredentials = new getCredentialsService();
class apiService {
constructor(eventType, event, context) {
this.event = event;
this.context = context;
}
beginProcess() {
return new Promise(async (resolve, reject) => {
if (this.event["type"] == "getcredentials") {
let credentialsData = await this.fetchCredentials();
resolve(credentialsData);
}
});
}
fetchCredentials() {
return new Promise(async (resolve, reject) => {
let response = await getCredentials.getCredentialsData(this.event);
resolve(response);
});
}
}
module.exports = apiService;
</code></pre>
<p><strong>getCredentials.js</strong></p>
<pre><code>var request = require('request');
var moment = require('moment');
const AWS = require("aws-sdk");
let sts = new AWS.STS();
class getCredentialsService {
getCredentialsData = async (event) => {
const data = await sts.assumeRole(params1).promise();
const athena = new AWS.Athena({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
});
// Next athena query exectuion
await athena.startQueryExecution(queryParams, async function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
var QueryExecutionId = data["QueryExecutionId"];
const data1 = await getQueryResult(QueryExecutionId, data)
resolve(data1);
}
});
};
}
module.exports = getCredentials;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T03:31:12.930",
"Id": "486397",
"Score": "0",
"body": "remove apiService.js entirely and turn getCredentialsData() into a async function outside of any class"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T03:12:33.203",
"Id": "248300",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Refactor class based approach in NodeJS"
}
|
248300
|
<p>I have three main questions:</p>
<ol>
<li><p>Am I using <code>std::unique_ptr</code> correctly here? Using <code>std::move</code> and <code>get</code>?</p>
</li>
<li><p>Is there any way for me to make my <code>_insert</code> and <code>_delete</code> functions iterative?
I'd like for it to be something similar to my <code>search</code> function.</p>
</li>
<li><p>Do I need a destructor? Or since I am using automatic memory management, will all my pointers be freed when the <code>BinarySearchTree</code> object goes out of scope?</p>
</li>
</ol>
<p>Thank you!</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <stdexcept>
template <typename T> struct Node {
T value;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
explicit Node(const T &val){value=val; left=nullptr; right=nullptr;}
} ;
template <typename T> class BinarySearchTree{
public:
BinarySearchTree(){root = nullptr;};
explicit BinarySearchTree(const T &value){
root = std::make_unique<Node<T>>(value);
}
explicit BinarySearchTree(const std::vector<T> &array){
for(auto &it: array) insert(it);
}
// Do I need a destructor?
void insert(const T& value){
_insert(root, value);
}
bool search(const T& value){
auto curr = root.get();
while(curr != nullptr){
if(value == curr->value)
return true;
else if(value <= curr->value)
curr = curr->left.get();
else
curr = curr->right.get();
}
return false;
}
void del(const T& value){
_delete(root, value);
}
T min() {
auto curr = root.get();
while(curr->left){
curr = curr->left.get();
}
return curr->value;
}
T max() {
auto curr = root.get();
while(curr->right){
curr = curr->right.get();
}
return curr->value;
}
private:
std::unique_ptr<Node<T>> root;
// Is there anyway to make this iterative?
void _insert(std::unique_ptr<Node<T>> &curr, int searchVal){
if(!curr)
curr = std::make_unique<Node<T>> (searchVal);
else if(searchVal <= curr->value)
_insert(curr->left, searchVal);
else
_insert(curr->right, searchVal);
}
void _delete(std::unique_ptr<Node<T>> &curr, int deleteVal){
// Throw error if key is not in the tree
if(!curr){
std::string errorVal = std::to_string(deleteVal);
throw std::invalid_argument("Cannot find value: " + errorVal);
}
// Replace node if we found the key
else if(curr->value == deleteVal)
_deleteNode(curr);
// Iterate down to correct key otherwise
else if(deleteVal <= curr->value)
_delete(curr->left, deleteVal);
else
_delete(curr->right, deleteVal);
}
void _deleteNode(std::unique_ptr<Node<T>> &toDelete){
// Simple if it's a leaf or has only one child
if(!toDelete->left)
toDelete = std::move(toDelete->right);
else if(!toDelete->right)
toDelete = std::move(toDelete->left);
// Replacement algorithm using inorder successor
else{
toDelete->value = _findSuccessor(toDelete->right);
}
}
T _findSuccessor(std::unique_ptr<Node<T>> &curr){
if(curr->left)
return _findSuccessor(curr->left);
else{
T rv = curr->value;
curr = std::move(curr->right);
return rv;
}
}
} ;
int main(int argc, char** argv){
std::vector<int> example {23,2,11,2,5,-5,6,34,8,9,42,0};
BinarySearchTree<int> bst (example);
std::cout << "INPUT: ";
for(auto &it: example) std::cout << it << " ";
std::string search47 = bst.search(47) ? " found" : " not found";
std::string search42 = bst.search(42) ? " found" : " not found";
std::cout << "\nSEARCHING... " << 47 << search47;
std::cout << "\nSEARCHING... " << 42 << search42;
std::cout << "\nMIN: " << bst.min();
std::cout << "\nMAX: " << bst.max() << std::endl;
std::cout << "\nDeleting minimum";
bst.del(bst.min());
std::cout << "\nNEW MIN: " << bst.min();
std::cout << "\nDeleting maximum";
bst.del(bst.max());
std::cout << "\nNEW MAX: " << bst.max();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<ol>\n<li>Am I using <code>std::unique_ptr</code> correctly here? Using std::move and get?</li>\n</ol>\n</blockquote>\n<p>Yes, you are using those correctly.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Is there any way for me to make my <code>_insert</code> and <code>_delete</code> functions iterative? I'd like for it to be something similar to my search function.</li>\n</ol>\n</blockquote>\n<p>Sure. An iterative solution would indeed look like your search function. However, the trick is that instead of having <code>curr</code> be a pointer to a <code>Node<T></code>, you want <code>curr</code> to be a pointer to a <code>std::unique_ptr<Node<T>></code>. So change <code>curr</code> from being a reference to being a pointer, and then you can write something like:</p>\n<pre><code>void _insert(std::unique_ptr<Node<T>> *curr, int searchVal){\n while (*curr) {\n if (searchVal <= (*curr)->value)\n curr = &(*curr)->left;\n else\n curr = &(*curr)->right;\n }\n\n *curr = std::make_unique<Node<T>>(searchVal);\n}\n</code></pre>\n<blockquote>\n<p>Do I need a destructor? Or since I am using automatic memory management, will all my pointers be freed when the BinarySearchTree object goes out of scope?</p>\n</blockquote>\n<p>Memory will automatically be freed correctly if you don't write your own destructor. However, you have to be aware that when a node is destructed, it first needs to destruct its two children, and this goes on recursively until a node doesn't have any more children. If your tree is perfectly balanced, that means O(log N) stack space is used, where N is the number of elements in the tree. But if your tree is maximally unbalanced, it will take O(N) stack space.\nYou can avoid this by destructing one node at a time in a loop, until all the nodes are destroyed:</p>\n<pre><code>~BinarySearchTree() {\n while (root) {\n deleteOneNode(&root);\n }\n};\n</code></pre>\n<p>However now the problem is how to delete a single node without using recursion. You can cannot delete a node with two children, since this will cause recursion. So a possible implementation is:</p>\n<pre><code>void deleteOneNode(std::unique_ptr<Node> *root) {\n // iterate down until we find a node with less than two children\n while ((*root)->left && (*root)->right) {\n root = root->left; // arbitrary choice\n }\n \n if ((*root)->left)\n (*root) = std::move((*root)->left);\n else if ((*root)->right)\n (*root) = std::move((*root)->right);\n else\n (*root)->reset(nullptr);\n}\n</code></pre>\n<p>The drawback is that this might take O(N²) time for some trees (for the above example, one where ever left child has two children of its own, but every right child is a leaf node).</p>\n<h1>Move <code>struct Node</code> inside <code>class BinarySearchTree</code></h1>\n<p>A <code>Node</code> is just an implementation detail of your <code>BinarySearchTree</code>, so declare the former inside the latter, like so:</p>\n<pre><code>template <typename T> class BinarySearchTree {\n struct Node {\n T value;\n ...;\n };\n\npublic:\n ...\n};\n</code></pre>\n<p>A nice advantage is that you no longer have to write <code>Node<T></code>, but can just write <code>Node</code>. It also no longer pollutes the global namespace with a <code>Node</code>, which is important if you want to use other classes that have their own <code>Node</code> types.</p>\n<h1>There's no need to initialize a <code>std::unique_ptr</code></h1>\n<p>The default constructor of <code>std::unique_ptr</code> will already set the pointer to <code>nulltpr</code>, you don't have to do this yourself.</p>\n<h1>Prefer using member initialization lists</h1>\n<p>When initializing a member value in the constructor, use <a href=\"https://en.cppreference.com/w/cpp/language/constructor\" rel=\"nofollow noreferrer\">member initialization lists</a> if possible. For example:</p>\n<pre><code>class Node {\n T value;\n ...\n explicit Node(const T &val): value(val) {}\n};\n</code></pre>\n<h1>Add a constructor that takes a pair of iterators</h1>\n<p>You have a constructor that takes a <code>std::vector<T></code>, but what if I want to initialize the binary tree using data from a <code>std::list</code> or another STL container? You can easily make this possible by doing the same thing many STL containers do: have a constructor that takes a pair of iterators, like so:</p>\n<pre><code>template <class InputIt>\nBinarySearchTree(InputIt first, InputIt last) {\n while (first != last) {\n insert(*first++);\n }\n}\n</code></pre>\n<h1>Consider adding iterators to your binary tree</h1>\n<p>It's quite common to want to iterate over all the elements of a container. If you add an iterator type, and provide <code>begin()</code> and <code>end()</code> member functions that return iterators, you can iterate over your <code>BinarySearchTree</code> just like other STL containers. To do it properly, you want to add other functions such as <code>empty()</code>, <code>size()</code>, <code>cbegin()/cend()</code>, <code>rbegin()/rend()</code> and so on. If you can make it work like any other STL container, that would be very nice.</p>\n<h1>Avoid starting names with underscores</h1>\n<p>There are rules governing the <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">allowed use of underscores in C++ identifiers</a>. Unless you want to learn all the rules by head, I would advise you to just follow these two rules:</p>\n<ol>\n<li>Never start a name with an underscore.</li>\n<li>Never use two consecutive underscores in a name.</li>\n</ol>\n<p>In your code, there is no need to have separate names for the public and private functions that peform insertion and deletion. They can be distinguished by the number of arguments. So:</p>\n<pre><code>public:\n void delete(const T& value) {\n delete(&root, value);\n }\n\nprivate:\n void delete(std::unique_ptr<Node> *curr, const T& value) {\n ...\n }\n</code></pre>\n<h1>Don't cast values to <code>int</code></h1>\n<p>Your public functions correctly use <code>T</code> for the type of values, but your private functions cast the values to <code>int</code>. That is quite bad! What if I want to store floating point values in your tree? If I insert <code>{1.1, 1.2, 1.3}</code> then internally it is converted to <code>{1, 1, 1}</code>. That doesn't sound very useful! Use <code>T</code> everywhere you handle a value.</p>\n<p>But that also brings me to:</p>\n<h1>Allow a custom comparison function to be used</h1>\n<p>It is quite possible to have value types that themselves don't allow comparison using <code>==</code> and <code><</code>, or that just don't provide the order in which you want them sorted in the search tree. You will notice that ordered containers like <a href=\"https://en.cppreference.com/w/cpp/container/map\" rel=\"nofollow noreferrer\"><code>std::map</code></a> allow you to specify a custom comparison function. You can easily add that to your class as well:</p>\n<pre><code>template <typename T, class Compare = std::less<T>>\nclass BinarySearchTree {\n Compare comp;\n ...\npublic:\n BinarySearchTree(const Compare &comp = Compare()): comp(comp), ...;\n ...\n bool search(const T& value) {\n ...\n while (...) {\n if (comp(value, curr->value)\n curr = curr->left.get();\n else if (comp(curr->value, value))\n curr = curr->right.get();\n else\n return true;\n }\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T00:22:44.513",
"Id": "486392",
"Score": "0",
"body": "Thank you for your excellent pointers! (heh) I'm still a little confused on your destructor -- how does having a custom destructor avoid the worst-case scenario of a bst degenerating into a linked list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T05:33:12.333",
"Id": "486399",
"Score": "1",
"body": "The default destructor will first destruct `left` and `right` before freeing memory for the node. But when destructing the node pointed to by `left` or `right`, it will first have to destruct their `left` and `right` nodes, and so on. The custom destructor avoids this by *moving* one of the children of the root node to `root`, so they won't be destructed, only the old `root` will be freed. So there won't be any recursion in that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T12:24:48.970",
"Id": "486427",
"Score": "0",
"body": "Hmm, okay, does that mean that the new destructor will avoid worst-case O(n) recursive calls? But to me it seems like it will incur additional time complexity costs in having to find the inorder successor each time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T16:43:52.933",
"Id": "486451",
"Score": "1",
"body": "Ah, `findSuccessor()` can actually recurse `O(n)` in an unbalanced tree, so my idea was too simple for a binary tree. But what could work is to check if a node has only one child, if so `std::move()` that child up, otherwise call `.reset(nullptr)`, which will recursively destruct it. That should be O(log N)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T17:22:18.673",
"Id": "486456",
"Score": "1",
"body": "Hm with unbalanced trees it could still be O(N). You *can* do it purely iteratively but it might be O(N²) worst case if you do it naively. I think it should be possible to do it in O(N log N) time and O(log N) space, even with an unbalanced tree."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:05:58.633",
"Id": "248313",
"ParentId": "248306",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "248313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T06:39:42.837",
"Id": "248306",
"Score": "9",
"Tags": [
"c++",
"tree",
"pointers",
"binary-search-tree"
],
"Title": "Using smart pointers to construct Binary Search Tree"
}
|
248306
|
<p>Before you read the code below, note the following explanation:
I have three classes: <code>Driver</code>, <code>Vehicle</code>, and <code>Itinerary</code>.</p>
<p>They have attributes <code>Driver.behavior</code>, <code>Vehicle.pRange</code>, <code>Vehicle.pBattery</code>, <code>Itinerary.destinations</code>, and <code>Itinerary.startTime</code>.</p>
<p>The function <code>findCand</code> takes all these class attributes as input and returns as an output a dataframe with three columns.</p>
<p>So here is the code that I use to run my simulation:</p>
<pre><code>n = 1000
m = 1000
agentA = []
iterationA = []
itineraryA = [None]*n
behaviorA = [None]*n
rangeA = [None]*n
batteryA = [None]*n
startTimeA = [None]*n
df = pd.DataFrame(columns = ['Loc', 'Amount', 'Time'])
for j in range(m):
for i in range(n):
x = Itinerary()
y = Vehicle()
z = Driver()
itineraryA[i] = x.destinations
behaviorA[i] = z.behavior
rangeA[i] = y.pRange
batteryA[i] = y.pBattery
startTimeA[i] = x.startTime
dfi = findCand(itineraryA[i], behaviorA[i], rangeA[i], batteryA[i], startTimeA[i])
df = df.append(dfi)
agentA = agentA + [i]*len(dfi)
iterationA = iterationA + [j]*len(dfi)
df['Ag'] = agentA
df['It'] = iterationA
</code></pre>
<p>I run it n times, m iterations. For each dataframe I get from <code>findCand</code>, I append it to the dataframe <code>df</code>.</p>
<p>The code works, but it's taking a crazy amount of time to run.</p>
<p>If <code>n=10</code> and <code>m=10</code>, it takes about a second.</p>
<p>If <code>n=100</code> and <code>m=100</code>, it takes around 97 seconds.</p>
<p>I put <code>n=1000</code> and <code>m=1000</code> and it was running for more than 3 hours before I stopped it.</p>
<p>I need to do this for a way higher value of both n and m. I realize that it takes a lot of time to append a dataframe so often but I've tried a few other methods</p>
<ul>
<li>I used a dictionary and appended larger dataframes fewer times.</li>
<li>I used lists instead of dataframes and then made one large dataframe in the end.</li>
</ul>
<p>But these methods took just as long or even longer than the one above. So my question is, can anyone suggest areas that I can improve that might shorten the runtime?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T23:10:37.820",
"Id": "486387",
"Score": "0",
"body": "Use a [profiler](https://docs.python.org/3/library/profile.html#the-python-profilers) to run your program and see where it is spending the most time. for n = m = 1000, the loop runs a million times. It looks like each time through the loop an average of 500 items are appended to agentA and iterationA. I think they end up being 500 million elements long."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:38:17.957",
"Id": "248310",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas",
"simulation"
],
"Title": "How can I shorten the runtime of my simulation?"
}
|
248310
|
<p>I have overridden setAnchorView() of MediaController class to display full screen option icon using below code.The code seems to be working fine in devices I tested but I have few doubts for which I need review-</p>
<ul>
<li>The class assumes the anchor view is a FrameLayout to position full
screen imageview.</li>
<li>Should I use try catch inside setAnchorView?</li>
</ul>
<hr />
<pre><code>public class FullScreenMediaController extends MediaController {
private final Boolean isFullScreen;
private final Listener listener;
public FullScreenMediaController(Context context, Listener listener, Boolean isFullScreen) {
super(context);
this.listener = listener;
this.isFullScreen = isFullScreen;
}
@Override
public void setAnchorView(View view) {
super.setAnchorView(view);
//image view for full screen to be added to media controller
ImageView fullScreen = new ImageView(super.getContext());
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
params.rightMargin = 50;
params.topMargin = 20;
fullScreen.setPadding(10, 10, 10, 10);
addView(fullScreen, params);
if (isFullScreen) {
fullScreen.setImageResource(R.drawable.ic_fullscreen_exit);
} else {
fullScreen.setImageResource(R.drawable.ic_fullscreen);
}
//add listener to image view to handle full screen and exit full screen events
fullScreen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
listener.onFullScreenClick();
}
});
}
public interface Listener {
void onFullScreenClick();
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T11:58:52.717",
"Id": "248312",
"Score": "2",
"Tags": [
"java",
"performance",
"android",
"error-handling",
"generics"
],
"Title": "Custom MediaController with full screen video image option"
}
|
248312
|
<p>I tried to parse command line arguments. The program requires four arguments. I iterate over the arguments. If the argument is an option, I process the option. Otherwise the argument is one of the required arguments. In order to read the required arguments I need some kind of state machine. In the first case the first argument should be read. In the second case the second argument and so on.</p>
<p>I wrote a <code>Proc</code> class with just one method, which returns again a <code>Proc</code> class.</p>
<pre><code>static abstract class Proc {
abstract Proc exec (String arg);
}
</code></pre>
<p>By this I can execute some action and define what should be done next.</p>
<ol>
<li>save db host and then read name</li>
<li>save db name and then read user</li>
<li>save db user and then read xml file</li>
<li>save xml file and then nothing</li>
</ol>
<p>But because of all the class overhead it is hard to read.</p>
<pre><code>Proc proc = new Proc () {
Proc exec (String arg) {
db_host = arg;
return new Proc () {
Proc exec (String arg) {
db_name = arg;
return new Proc () {
Proc exec (String arg) {
db_user = arg;
return new Proc () {
Proc exec (String arg) {
xml_file = arg;
return null;
}
};
}
};
}
};
}
};
</code></pre>
<p>Is there a way to simplify the code? I tried Lambdas, but it seems to me that Lambdas can use only final variables, which is a bit useless, when I want to store a value.</p>
<p>Complete example:</p>
<pre><code>public class Import
{
static String db_host = null;
static String db_port = "5432";
static String db_name = null;
static String db_user = null;
static String xml_file = null;
static void usage ()
{
System.err.println ("Usage: Import [-p PORT] HOST DATABASE USER FILE");
}
static abstract class Proc {
abstract Proc exec (String arg);
}
static void parse_args (String[] args)
{
Proc proc = new Proc () {
Proc exec (String arg) {
db_host = arg;
return new Proc () {
Proc exec (String arg) {
db_name = arg;
return new Proc () {
Proc exec (String arg) {
db_user = arg;
return new Proc () {
Proc exec (String arg) {
xml_file = arg;
return null;
}
};
}
};
}
};
}
};
try {
for (int i = 0; i < args.length; i++)
switch (args[i]) {
case "-p":
db_port = args[++i];
break;
case "-h":
usage ();
break;
default:
proc = proc.exec (args[i]);
}
}
catch (Exception ex) {
throw new Error ("Can not parse args!", ex);
}
}
public static void main (String[] args)
{
parse_args (args);
System.err.println ("db_host: " + db_host);
System.err.println ("db_port: " + db_port);
System.err.println ("db_name: " + db_name);
System.err.println ("db_user: " + db_user);
System.err.println ("xml_file: " + xml_file);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First, you should follow the <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">Java naming conventions</a>.</p>\n<hr />\n<p>Second, don't shorten names just because you can. Example, what does "Proc" stand for? Procedure? Processor? Even if names become longer, the readability is worth it!</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>static String db_host = null;\n</code></pre>\n<p>Your members should not be <code>static</code>, and should ideally be qualified with something else than <code>package-private</code>, like <code>protected</code> or <code>private</code> to show the intent clearly.</p>\n<hr />\n<blockquote>\n<p>In order to read the required arguments I need some kind of state machine.</p>\n</blockquote>\n<p>Is that a requirement you've been given or is that an assumption you had? Because that's not true at all. Overall, your system is completely unnecessarily complex without an obvious reason or benefit. Neither does it seem like a state-machine at all, it's just an overly complex chain of function calls.</p>\n<p>A state-machine for your command-argument parsing would be something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int index = 0; index < args.length; index++) {\n String arg = args[index];\n \n if (arg.equals("-p") && databaseHost == null) {\n arg = args[++index];\n \n databasePort = arg;\n } else if (databaseHost == null) {\n databaseHost = arg;\n } else if (databaseUsername == null) {\n databaseUsername = arg;\n } else if (databasePassword == null) {\n databasePassword = arg;\n } else if (inputFile == null) {\n inputFile = arg;\n }\n}\n</code></pre>\n<p>And even that is oddly complex.</p>\n<p>What you want is the most simplest solution that works, and that would be a hardcoded extracting of arguments:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (args[0].equals("-h")) {\n printHelp();\n return;\n}\n\nint portProvidedOffset = 0;\n\nif (args[0].equals("-p")) {\n databasePort = args[1];\n \n portProvidedOffset = 2;\n}\n\ndatabaseHost = args[portProvidedOffset + 0];\ndatabaseUsername = args[portProvidedOffset + 1];\ndatabasePassword = args[portProvidedOffset + 2];\ninputFile = args[portProvidedOffset + 3];\n</code></pre>\n<p>Which is, of course, not pretty, but the most simplest solution you can get away with. Of course, the length of the array should be checked beforehand, whether it is 4 elements or more. Afterwards you'd check whether all parameters are set, if not, exit with an error.</p>\n<p>If you want a more sophisticated solution, you'd need to write yourself a complete argument parser, a not-so-trivial exercise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:57:39.337",
"Id": "486403",
"Score": "0",
"body": "About \"Proc\". Everything is an abbreviation. \"Proc\" stands for: `TheClassWithTheMethodExecTakingAnStringAndReturningAnInstanceOfTheSameClass`. It is not a matter whether you abbreviate. It is just a matter how much you abbreviate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:04:33.417",
"Id": "486690",
"Score": "0",
"body": "You can argue about it however you wish, my experience is that the more descriptive the names, the less abbreviations or \"shortcuts\" are used, the better is the readability and maintainability of the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T16:46:16.853",
"Id": "248326",
"ParentId": "248315",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T13:25:52.813",
"Id": "248315",
"Score": "3",
"Tags": [
"java",
"state-machine"
],
"Title": "Sequence state machine"
}
|
248315
|
<p>The code below will store a base64 image on another website and create an event to display the image on a Vue page in <em>real time</em>. It works fine and all.</p>
<p>My question is, is this a good way of doing it or there's a better way to structure the code? I've thought about placing the logic in a listener but it doesn't seem that I need to use one. For queues, I'll add them later on.</p>
<p><strong>Controller</strong></p>
<pre><code>public function store(Request $request)
{
$base64 = $request->image;
$image = str_replace('data:image/png;base64,', '', $base64);
$imageName = 'draw'.time().'.png';
$response = $this->guzzleClient()->post(config('archiving.api_postBase64_file'),
[
'multipart' => [
[
'name' => 'file',
'contents' => $image
],
[
'name' => 'file_name',
'contents' => $imageName
],
[
'name' => 'file_folder',
'contents' => 'drawings'
],
],
]
);
if($response->getStatusCode() >= 500){
return response($response->getBody(), $response->getStatusCode());
}else{
$drawing = Drawing::create([
'user_id'=>Auth::id(),
'file_name'=>$imageName,
]);
event(new NewDrawing($drawing));
return response('Drawing created!',200);
}
}
</code></pre>
<p><strong>NewDrawing Event</strong></p>
<pre><code>class NewDrawing implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $drawing;
public function __construct(Drawing $drawing)
{
$this->drawing = $drawing;
}
public function broadcastOn()
{
return new Channel('channel-drawing');
}
}
</code></pre>
<p><strong>Frontend (Vue)</strong></p>
<pre><code><script>
export default {
data(){
return{
images:'',
}
},
methods:{
listen() {
Echo.channel('channel-drawing')
.listen('NewDrawing', res => {
this.images.push(res.drawing);
})
}
},
mounted() {
this.listen()
}
}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:12:03.250",
"Id": "486514",
"Score": "0",
"body": "Always OR Never use semis at end of statements. Either is fine but be consistent. You can always implement a strict linter to keep your code quality high."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T08:49:03.140",
"Id": "487008",
"Score": "0",
"body": "Your question title describes your concern, but it is expected to uniquely describe what your script does."
}
] |
[
{
"body": "<p>I'm mostly a back-end guy who fusses his way through front end code. Here's my advice:</p>\n<ul>\n<li><p>Keep the controller code as close as possible to handling the response only. Delegate the creation of objects to their own classes. Think of the S in SOLID - Single Responsibility.</p>\n<pre><code>public function store(Request $request)\n{\n $image = new ImageMeta($base64);\n $archiver = new ImageArchiver($image);\n $response = $archiver->post();\n\n if($response->getStatusCode() >= 500){\n return response($response->getBody(), $response->getStatusCode());\n }else{\n $drawing = Drawing::create([\n 'user_id'=>Auth::id(),\n 'file_name'=>$imageName,\n ]);\n //There's a few different ways to look at this which might be part of a larger conversation, \n // so I won't touch this part yet. But is this something specific to drawings? Or is the broadcast\n // of model creation something that will happen for lots of different models? Regardless, I would \n // change the name from NewDrawing to something like DrawingCreationBroadcast, or something like that\n // NewDrawing gets confusing since its too close to new Drawing();\n event(new NewDrawing($drawing));\n return response('Drawing created!',200);\n }\n }\n</code></pre>\n</li>\n</ul>\n<p>ImageMeta class</p>\n<pre><code> /** For all classes assume property declarations, and getters are included. \n * Lean toward immutable classes where possible, so don't include setters \n * unless it becomes necessary. Code re-use != object instance re-use.\n **/\n\n class ImageMeta {\n public function __construct($base64) {\n $this->image = str_replace('data:image/png;base64,', '', $base64);\n $this->imageName = 'draw'.time().'.png';\n }\n }\n</code></pre>\n<p>ImageArchiver class</p>\n<pre><code> class ImageArchiver {\n private $config;\n \n public function __construct(ImageMeta $image) {\n $this->image = $image;\n $this->makeConfig();\n }\n \n private function makeConfig() {\n $this->config = [ \n 'multipart' => [\n [\n 'name' => 'file',\n 'contents' => $image->getImage()\n ],\n [\n 'name' => 'file_name',\n 'contents' => $imageName->getName()\n ],\n [\n 'name' => 'file_folder',\n 'contents' => 'drawings'\n ],\n ],\n ]\n }\n \n //use type hinting here. Off the top of my head I don't know the parent class of guzzleClient\n public function archive($guzzleClient) {\n return $guzzleClient->post($this->config);\n }\n\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:45:03.160",
"Id": "486439",
"Score": "0",
"body": "where should i store the ImageMeta and ImageArchiever class file ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:12:37.170",
"Id": "486440",
"Score": "0",
"body": "my bad, so ur suggesting to use service right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T18:40:37.607",
"Id": "486459",
"Score": "0",
"body": "I'm not necessarily suggesting a service, but it might make sense depending on how often this is used.\n\nPut it where it makes sense. I don't just dump everything into a models folder, but use the Models folder as the root of all classes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:33:26.363",
"Id": "248367",
"ParentId": "248320",
"Score": "4"
}
},
{
"body": "<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about many ways to keep code lean - like avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n<p>It is wise to avoid the <code>else</code> keyword - especially when it isn't needed - e.g. when a previous block contains a <code>return</code> statement:</p>\n<blockquote>\n<pre><code> if($response->getStatusCode() >= 500){\n return response($response->getBody(), $response->getStatusCode());\n }else{\n $drawing = Drawing::create([\n 'user_id'=>Auth::id(),\n 'file_name'=>$imageName,\n ]);\n event(new NewDrawing($drawing));\n return response('Drawing created!',200);\n }\n</code></pre>\n</blockquote>\n<hr />\n<p>In the Frontend code, it appears that <code>images</code> is set to an empty string:</p>\n<blockquote>\n<pre><code> data(){\n return{\n images:'',\n }\n},\n</code></pre>\n</blockquote>\n<p>Yet in the listen callback it is used like an array:</p>\n<blockquote>\n<pre><code> Echo.channel('channel-drawing')\n .listen('NewDrawing', res => {\n this.images.push(res.drawing);\n }) \n</code></pre>\n</blockquote>\n<p>It should be initialized as an array in <code>data()</code>.</p>\n<p>Is the method <code>listen()</code> called anywhere other than the <code>mounted()</code> callback? If not, then it may be simpler just to move the code from that method into the <code>mounted()</code> callback.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:41:33.520",
"Id": "248370",
"ParentId": "248320",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:54:52.683",
"Id": "248320",
"Score": "2",
"Tags": [
"javascript",
"php",
"ecmascript-6",
"laravel",
"vue.js"
],
"Title": "Structuring code logic for events on laravel controller"
}
|
248320
|
<p>I'm working on my first Rust project of any particular size, a rudimentary IRC bot. So far I've found solutions to most of the problems I've encountered, but something I'm now getting tangled up in as the project grows is my attempts to apply DI/IoC principles for testability. (I'm coming to Rust from PHP, so I may be overapplying PHP best practices here.)</p>
<p>The full repository is <a href="https://github.com/MikkelPaulson/irustc-bot/tree/865e1fc2d11d632e598e32f48f65e665e9e2e5ad" rel="nofollow noreferrer">here</a> (link to current HEAD), but I'll reproduce some snippets below. I'm currently getting tangled up in the lifetimes of the structs I'm using for IoC purposes, and every struct seems to require a different combination of <code>Box</code>/<code>Rc</code>/<code>RefCell</code>. Is this a case where it's okay for everything to be <code>'static</code>? My immediate problem is that attempting to register callback functions with the Dispatcher fails because the Dispatcher (by design) outlives the function doing the registering as well as its parent class.</p>
<p>I've tried to trim out all of the irrelevant code for clarity such as 300 lines of Reply matching, but my apologies if I've thrown out some baby with the bathwater. This <em>should</em> all compile and run as written, but if you want to play around with the code, I suggest going to GitHub and following the setup instructions in the readme. It should work out of the box (IRC server and all) with a couple of Docker commands.</p>
<p>Yes, I'm aware that <code>async</code> exists now, and I'll attempt a refactor using async instead of threads at some point.</p>
<pre class="lang-rust prettyprint-override"><code>// lib.rs
use crate::connection::Connect;
use std::cell::RefCell;
use std::io;
use std::net;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
mod client;
mod connection;
mod dispatcher;
pub fn run<A: net::ToSocketAddrs>(addr: A) -> io::Result<()> {
let stream = net::TcpStream::connect(addr).expect("Could not connect to server.");
let dispatcher = Rc::new(RefCell::new(dispatcher::Dispatcher::new()));
let connection = Rc::new(RefCell::new(connection::Connection::new(
&stream,
dispatcher.clone(),
)));
let client = client::Client::new(connection.clone(), dispatcher.clone());
loop {
if connection.borrow_mut().poll() {
continue;
}
thread::sleep(Duration::from_millis(100));
}
//Ok(())
}
</code></pre>
<p>Since the IRC protocol is asynchronous, a dispatcher is used to notify interested parties about events received from the server. This could either be commands like incoming messages, or replies to commands sent by the client (not shown).</p>
<pre class="lang-rust prettyprint-override"><code>// dispatcher.rs
use crate::connection;
use std::collections::HashMap;
pub trait Dispatch {
fn register_command_listener(
&mut self,
command_type: connection::CommandType,
command_listener: Box<dyn Fn(&connection::Command)>,
);
fn handle_command(&mut self, command: connection::Command);
}
pub struct Dispatcher {
command_listeners: HashMap<connection::CommandType, Vec<Box<dyn Fn(&connection::Command)>>>,
}
impl Dispatcher {
pub fn new() -> Dispatcher {
Dispatcher {
command_listeners: HashMap::new(),
}
}
}
impl Dispatch for Dispatcher {
fn register_command_listener(
&mut self,
command_type: connection::CommandType,
command_listener: Box<dyn Fn(&connection::Command)>,
) {
self.command_listeners
.entry(command_type)
.or_insert(Vec::new())
.push(command_listener);
}
fn handle_command(&mut self, command: connection::Command) {
let command_type = command.to_command_type();
for command_listener in self.command_listeners.entry(command_type).or_default() {
command_listener(&command);
}
}
}
</code></pre>
<p>The Connection translates raw strings received over the TCP connection into instances of the Command or Reply (not shown) enums, then sends them for the Dispatcher to handle.</p>
<pre class="lang-rust prettyprint-override"><code>// connection.rs
use crate::dispatcher;
use std::cell::RefCell;
use std::io;
use std::io::prelude::*;
use std::net;
use std::rc::Rc;
pub trait Connect {
fn poll(&mut self) -> bool;
fn send_command(&mut self, command: Command) -> std::io::Result<()>;
}
pub struct Connection<'a> {
reader: Box<dyn 'a + io::BufRead>,
writer: Box<dyn 'a + Write>,
dispatcher: Rc<RefCell<dyn 'a + dispatcher::Dispatch>>,
}
impl<'a> Connection<'a> {
pub fn new(
stream: &'a net::TcpStream,
dispatcher: Rc<RefCell<dispatcher::Dispatcher>>,
) -> Connection<'a> {
stream.set_nonblocking(true).unwrap();
let reader = io::BufReader::new(stream);
Connection {
reader: Box::new(reader),
writer: Box::new(stream),
dispatcher: dispatcher,
}
}
fn dispatch_message(&mut self, mut raw_message: String) {
let mut dispatcher = self.dispatcher.borrow_mut();
if let Some(command) = raw_to_command(&raw_message) {
dispatcher.handle_command(command);
}
}
}
impl<'a> Connect for Connection<'a> {
fn poll(&mut self) -> bool {
let mut buffer = String::new();
match self.reader.read_line(&mut buffer) {
Ok(len) => {
if len == 0 {
panic!("Stream disconnected");
} else {
print!("< {}", buffer);
self.dispatch_message(buffer);
true
}
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => false,
Err(e) => panic!("IO error: {}", e),
}
}
fn send_command(&mut self, command: Command) -> std::io::Result<()> {
let mut raw_command = command_to_raw(command);
raw_command.push_str("\r\n");
print!("> {}", raw_command);
self.writer.write(raw_command.as_bytes())?;
Ok(())
}
}
fn raw_to_command(raw_command: &str) -> Option<Command> {
let command_parts: Vec<&str> = raw_command.split(' ').collect();
match command_parts.first()?.as_ref() {
"PING" => Some(Command::Ping { server: command_parts.get(1)?.to_string() }),
"PONG" => Some(Command::Pong { server: command_parts.get(1)?.to_string() }),
// snip
_ => None,
}
}
fn command_to_raw(command: Command) -> String {
match command {
Command::Ping { server } => format!("PING {}", server),
Command::Pong { server } => format!("PONG {}", server),
// snip
}
}
#[derive(Debug)]
pub enum Command {
Ping { server: String },
Pong { server: String },
// snip
}
impl Command {
pub fn to_command_type(&self) -> CommandType {
match self {
Command::Ping { .. } => CommandType::Ping,
Command::Pong { .. } => CommandType::Pong,
// snip
}
}
}
#[derive(Hash, Eq, PartialEq, Debug)]
pub enum CommandType {
Ping,
Pong,
// snip
}
</code></pre>
<p>The Client understands the semantic meaning of the Command/Reply enums, and will provide methods like <code>send_message_to(user, message)</code>, which is translated into a Command instance and sent on to the server. It will also be responsible for interpreting protocol-level messages from the Server, eg. responding to PING and maintaining an up-to-date list of the users in a channel.</p>
<pre><code>// client.rs
use crate::connection;
use crate::dispatcher;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Client<'a> {
connection: Rc<RefCell<dyn 'a + connection::Connect>>,
dispatcher: Rc<RefCell<dyn 'a + dispatcher::Dispatch>>,
}
impl<'a> Client<'a> {
pub fn new(
connection: Rc<RefCell<connection::Connection<'a>>>,
dispatcher: Rc<RefCell<dyn 'a + dispatcher::Dispatch>>,
) -> Client<'a> {
// TODO: register with dispatcher to be notified when a PING is received
Client {
connection,
dispatcher,
}
}
fn pong(&self, command: &connection::Command) {
if let connection::Command::Ping { server } = command {
self.connection
.borrow_mut()
.send_command(connection::Command::Pong {
server: "Me".to_string(),
})
.ok();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>pub trait Dispatch {\n fn register_command_listener(\n &mut self,\n command_type: connection::CommandType,\n command_listener: Box<dyn Fn(&connection::Command)>,\n );\n\n fn handle_command(&mut self, command: connection::Command);\n}\n</code></pre>\n<p>You define a few traits like this. Generally, we don't do this in Rust. Just use the concrete types. So, have references to the <code>Dispatcher</code> struct in your code and not the <code>Dispatch</code> trait.</p>\n<pre><code>pub struct Connection<'a> {\n reader: Box<dyn 'a + io::BufRead>,\n writer: Box<dyn 'a + Write>,\n dispatcher: Rc<RefCell<dyn 'a + dispatcher::Dispatch>>,\n}\n</code></pre>\n<p>The use of the dyn is slightly inefficient relative to using generics. Generics would also handle lifetimes a bit more easily due to type inference.</p>\n<pre><code>fn poll(&mut self) -> bool {\n let mut buffer = String::new();\n\n match self.reader.read_line(&mut buffer) {\n Ok(len) => {\n if len == 0 {\n panic!("Stream disconnected");\n } else {\n print!("< {}", buffer);\n self.dispatch_message(buffer);\n true\n }\n }\n Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => false,\n Err(e) => panic!("IO error: {}", e),\n }\n}\n</code></pre>\n<p>This work by registering and calling function handlers. That's common in other languages, but not the best solution in Rust. What you want to do is return an <code>Option<Command></code> from this function instead of calling dispatch_message. The calling code can than <code>match</code> on the returned value to decide how to respond to it.</p>\n<pre><code>let dispatcher = Rc::new(RefCell::new(dispatcher::Dispatcher::new()));\n\nlet connection = Rc::new(RefCell::new(connection::Connection::new(\n &stream,\n dispatcher.clone(),\n)));\n</code></pre>\n<p><code>Rc</code> and <code>RefCell</code> are escape hatches that let you avoid the borrow checker. Using them is usually a sign that your design is insufficiently rusty. In this case, you should have <code>Connection</code> take ownership of <code>Dispatcher</code> and then have <code>Client</code> take ownership of <code>Connection</code>. Then you don't need the Rc/RefCell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T02:14:05.423",
"Id": "486636",
"Score": "0",
"body": "Thanks for the review! If my understanding is correct, using concrete types would prevent me from mocking classes, would it not? Is there a different pattern that I should be using to support unit testing? The Dispatcher (and the poll method) are intended to implement the [observer pattern](https://en.wikipedia.org/wiki/Observer_pattern), which is why it requires multiple mutable ownership. Insofar as the Client is the public interface of the module, I suppose it could expose the callback logic on behalf of the Dispatcher, but it involves a lot of boilerplate to bubble up that functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:28:15.050",
"Id": "486642",
"Score": "0",
"body": "@Mikkel, don't mock classes, don't implement the observer pattern. Those are bad habits you learned in inferior languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:31:14.987",
"Id": "486643",
"Score": "0",
"body": "@Mikkel, as it stands, you don't appear to have any tests that use mocks and you don't have anything actually registering with the dispatcher. So its a bit tricky to give concrete advice on what to do instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:38:04.447",
"Id": "486644",
"Score": "0",
"body": "@Mikkel, on testing I can give some general notes: Rust's powerful type system makes some tests simply unnecessary. Mocking is overrated, unless it is unbearably slow just use the real implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T19:50:47.317",
"Id": "486742",
"Score": "0",
"body": "Interesting. The idea of unit testing without mocks is going to take some wrapping my head around. I'm not sure how it's possible to test a unit of code without first isolating that unit. I guess the point of Rust is to keep your packages small enough that integration tests are enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T01:00:16.697",
"Id": "486978",
"Score": "0",
"body": "@Mikkel, think about this way, your Dispatcher uses a HashMap. Do you isolate your Dispatcher from the HashMap by mocking it? No, that would be silly. Instead, you trust that HashMap is well tested and working, and use it directly in your dispatcher. Just apply the same logic to Connection. It doesn't need to be isolated from Dispatcher, you have desperate tests that verify that Dispatcher does the right thing. But that doesn't hamper your ability to test Connection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T01:02:27.507",
"Id": "486979",
"Score": "0",
"body": "@Mikkel, it may be that you've been told that doing that is an integration test and not a unit test. But the truth is that different developers use the terms differently. And its doesn't matter whether its an integration or unit test, it matters whether its useful.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T16:51:36.257",
"Id": "487439",
"Score": "0",
"body": "Ripping out the dispatcher and traits definitely made Rust happier (got rid of a ton of lifetime annotations), but now I have no way of asserting that the client is sending the correct command without first setting up a TCP connection. I have integration tests now that do just that, but there's plenty of overhead from a performance and code standpoint to do that for every test. I've rationalized the structure to three components that could eventually be separate crates: a protocol layer (`Connection`), a client, and maybe eventually a server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:37:07.397",
"Id": "487542",
"Score": "1",
"body": "@Mikkel, in this case, I'd use a substitute implementation of Read/Write. Your Connection code is already holding a `dyn io::BufRead` and `dyn io::Write`, so you can simply allow passing in a custom `Read` and `Write`. In particular, you might like to use the `pipe` crate which allow the creation of paired Read/Writes that talk to each other via memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T14:26:14.513",
"Id": "488131",
"Score": "0",
"body": "Thanks, that worked perfectly without bleeding lifetimes all over the place again!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T05:58:45.357",
"Id": "248397",
"ParentId": "248323",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:34:30.900",
"Id": "248323",
"Score": "1",
"Tags": [
"rust",
"dependency-injection"
],
"Title": "Inversion of control in Rust"
}
|
248323
|
<p>I'm learning Rust and have decided to code up a toy <a href="https://www.rfc-editor.org/rfc/rfc7950#section-6" rel="nofollow noreferrer">YANG</a> parser as an exercise. In case it's relevant, I mainly work in C and Python.</p>
<p>While working on the tokenizer/lexer, I tried to make it Rust-y, but have ended up with some rather clunky-looking match statements. They're of the form:</p>
<pre class="lang-rust prettyprint-override"><code>match fn_which_returns_result_my_type() {
Err(err_str) => Err(err_str),
Ok(MyType0(MyArg0)) => Ok(MyType0(MyArg0)), // This seems especially clunky :(
Ok(MyType1) => Ok(MyType1),
Ok(MyType2) => Ok(MyType2),
Ok(_) => unreachable!() // Catch all other instances of the MyType Enum
}
</code></pre>
<p>I've highlighted the section I'm interested in feedback for. However, any general tips where I seem to be going down the wrong route (considering this is a work-in-progress) are welcome.</p>
<pre class="lang-rust prettyprint-override"><code>// @@@REMOVE
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use std::convert::TryFrom;
use std::default::Default;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
/// This module takes a YANG file and tokenizes it (i.e. splits it into a series of tokens suitable
/// for the yang_parser module)
static YANG_KEYWORDS: [&str; 86] = [
...truncated for clarity...
];
#[derive()]
struct Tokenizer {
file: BufReader<File>,
}
impl Tokenizer {
fn new(input: BufReader<File>) -> Self {
Self { file: input }
}
}
enum ExpectedToken {
Keyword,
ArgumentOrSemicolonOrOpenBrace,
SemicolonOrOpenBrace,
KeywordOrCloseBrace,
}
enum ActualToken {
Keyword(String),
Argument(String),
Semicolon,
OpenBrace,
CloseBrace,
EOF,
}
#[derive()]
pub struct YangTokens {
tokens: Vec<ActualToken>,
}
impl YangTokens {
fn get_keyword(&self, cursor: &mut Tokenizer) -> Result<ActualToken, &'static str> {
todo!()
}
fn get_argument_or_semicolon_or_open_brace(
&self,
cursor: &mut Tokenizer,
) -> Result<ActualToken, &'static str> {
todo!()
}
fn get_semicolon_or_close_brace(
&self,
cursor: &mut Tokenizer,
) -> Result<ActualToken, &'static str> {
todo!()
}
fn get_keyword_or_close_brace(
&self,
cursor: &mut Tokenizer,
) -> Result<ActualToken, &'static str> {
todo!()
}
// ==============================================================================
// THIS IS WHERE I WANT SPECIFIC FEEDBACK
fn get_next_token(
&self,
cursor: &mut Tokenizer,
next_exp_token: &mut ExpectedToken,
) -> Result<ActualToken, &'static str> {
match next_exp_token {
ExpectedToken::Keyword => {
*next_exp_token = ExpectedToken::ArgumentOrSemicolonOrOpenBrace;
match self.get_keyword(cursor) {
Err(err_str) => Err(err_str),
Ok(ActualToken::Keyword(kw)) => Ok(ActualToken::Keyword(kw)),
Ok(ActualToken::EOF) => Ok(ActualToken::EOF),
Ok(_) => unreachable!(),
}
}
ExpectedToken::ArgumentOrSemicolonOrOpenBrace => {
match self.get_argument_or_semicolon_or_open_brace(cursor) {
Err(err_str) => Err(err_str),
Ok(ActualToken::Argument(arg)) => {
*next_exp_token = ExpectedToken::SemicolonOrOpenBrace;
Ok(ActualToken::Argument(arg))
},
Ok(ActualToken::Semicolon) => {
*next_exp_token = ExpectedToken::KeywordOrCloseBrace;
Ok(ActualToken::Semicolon)
},
Ok(ActualToken::OpenBrace) => {
*next_exp_token = ExpectedToken::KeywordOrCloseBrace;
Ok(ActualToken::OpenBrace)
},
Ok(_) => unreachable!(),
}
}
ExpectedToken::SemicolonOrOpenBrace => {
*next_exp_token = ExpectedToken::KeywordOrCloseBrace;
match self.get_semicolon_or_close_brace(cursor) {
Err(err_str) => Err(err_str),
Ok(ActualToken::Semicolon) => Ok(ActualToken::Semicolon),
Ok(ActualToken::CloseBrace) => Ok(ActualToken::CloseBrace),
Ok(_) => unreachable!(),
}
}
ExpectedToken::KeywordOrCloseBrace => {
*next_exp_token = ExpectedToken::ArgumentOrSemicolonOrOpenBrace;
match self.get_keyword_or_close_brace(cursor) {
Err(err_str) => Err(err_str),
Ok(ActualToken::Keyword(kw)) => Ok(ActualToken::Keyword(kw)),
Ok(ActualToken::EOF) => Ok(ActualToken::EOF),
Ok(ActualToken::CloseBrace) => Ok(ActualToken::CloseBrace),
Ok(_) => unreachable!(),
}
}
}
}
// END OF WHERE I WANT SPECIFIC FEEDBACK
// ==============================================================================
}
impl TryFrom<&mut Tokenizer> for YangTokens {
type Error = &'static str;
fn try_from(cursor: &mut Tokenizer) -> Result<Self, Self::Error> {
let mut next_exp_token = ExpectedToken::Keyword;
todo!()
}
}
pub fn tokenize_yang_file(filename: &Path) -> Result<YangTokens, &str> {
let file = File::open(&filename).unwrap(); //@@@ THIS SHOULDN'T PANIC
let mut file = BufReader::new(file);
let mut cursor = Tokenizer::new(file);
YangTokens::try_from(&mut cursor)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn new() {
todo!()
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:41:43.997",
"Id": "486359",
"Score": "0",
"body": "One thing I've noticed immediately upon posting it is that the responsibilities feel wrong - I don't think I need my `Tokenizer`, or it should be the one with all the `impl` functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:22:04.180",
"Id": "486436",
"Score": "0",
"body": "One of my colleagues has reminded me of the `@` syntax in pattern matching (which I'd read about in the Rust book). Will refactor accordingly when I'm done at work and post a sample answer in case people are interested - other improvements definitely welcome though!"
}
] |
[
{
"body": "<p>For the function in question, the key thing was to remember <a href=\"https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#-bindings\" rel=\"nofollow noreferrer\">@ bindings</a> from the Rust book section 18.3.</p>\n<p>They allow you to bind the matched value to a variable for use in the match arm.</p>\n<pre class=\"lang-rust prettyprint-override\"><code> fn get_next_token(\n &self,\n cursor: &mut Tokenizer,\n next_exp_token: &mut ExpectedToken,\n ) -> Result<ActualToken, &'static str> {\n match next_exp_token {\n ExpectedToken::Keyword => {\n *next_exp_token = ExpectedToken::ArgumentOrSemicolonOrOpenBrace;\n match self.get_keyword(cursor) {\n val @ Err(_) => val,\n val @ Ok(ActualToken::Keyword(_)) => val,\n val @ Ok(ActualToken::EOF) => val,\n Ok(_) => unreachable!(),\n }\n }\n ExpectedToken::ArgumentOrSemicolonOrOpenBrace => {\n match self.get_argument_or_semicolon_or_open_brace(cursor) {\n val @ Err(_) => val,\n val @ Ok(ActualToken::Argument(_)) => {\n *next_exp_token = ExpectedToken::SemicolonOrOpenBrace;\n val\n },\n val @ Ok(ActualToken::Semicolon) => {\n *next_exp_token = ExpectedToken::KeywordOrCloseBrace;\n val\n },\n val @ Ok(ActualToken::OpenBrace) => {\n *next_exp_token = ExpectedToken::KeywordOrCloseBrace;\n val\n },\n Ok(_) => unreachable!(),\n }\n }\n ExpectedToken::SemicolonOrOpenBrace => {\n *next_exp_token = ExpectedToken::KeywordOrCloseBrace;\n match self.get_semicolon_or_close_brace(cursor) {\n val @ Err(_) => val,\n val @ Ok(ActualToken::Semicolon) => val,\n val @ Ok(ActualToken::CloseBrace) => val,\n Ok(_) => unreachable!(),\n\n }\n }\n ExpectedToken::KeywordOrCloseBrace => {\n *next_exp_token = ExpectedToken::ArgumentOrSemicolonOrOpenBrace;\n match self.get_keyword_or_close_brace(cursor) {\n val @ Err(_) => val,\n val @ Ok(ActualToken::Keyword(_)) => val,\n val @ Ok(ActualToken::EOF) => val,\n val @ Ok(ActualToken::CloseBrace) => val,\n Ok(_) => unreachable!(),\n }\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T09:35:38.460",
"Id": "248446",
"ParentId": "248324",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248446",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T15:39:24.620",
"Id": "248324",
"Score": "2",
"Tags": [
"rust",
"lexer"
],
"Title": "Tokenizer FSM in Rust - better way to do match statements?"
}
|
248324
|
<p>A Sudoku solver that works recursively. I'd appreciate your comments about coding style, structure and how to improve it. Thank you very much for your time.</p>
<p><strong>Code structure</strong></p>
<p>The Solver works by accepting a string of 81 digits for the Sudoku puzzle input. Zeros are taken as empty cells. It parses it into a 9x9 Numpy array.</p>
<p>The <code>get_candidates</code> function creates lists of possible digits to fill each cell following Sudoku's rules (no repeating 1-9 digit along rows, columns and 3x3 sub-grids).</p>
<p>The main solver function is <code>solve</code>. First, it discards wrong candidates with the <code>filter-candidates</code> function. "Wrong candidates" are those that when filled to a empty cell, led to another cell having no more candidates elsewhere on the Sudoku grid.</p>
<p>After filtering candidates, <code>fill_singles</code> is called to fill empty cells that have only one remaining candidate. If this process leads to a completely filled Sudoku grid, it's returned as a solution. There's a clause to return <code>None</code> which is used to backtrack changes by the <code>make_guess</code> function. This function will fill the next empty cell with the least quantity of candidates with one of its candidates, a "guess" value. It then recursively calls <code>solve</code> to either find a solution or reach a no-solution grid (in which case <code>solve</code> returns <code>None</code> and the last guess changes are reverted).</p>
<pre><code>from copy import deepcopy
import numpy as np
def create_grid(puzzle_str: str) -> np.ndarray:
"""Create a 9x9 Sudoku grid from a string of digits"""
# Deleting whitespaces and newlines (\n)
lines = puzzle_str.replace(' ','').replace('\n','')
digits = list(map(int, lines))
# Turning it to a 9x9 numpy array
grid = np.array(digits).reshape(9,9)
return grid
def get_subgrids(grid: np.ndarray) -> np.ndarray:
"""Divide the input grid into 9 3x3 sub-grids"""
subgrids = []
for box_i in range(3):
for box_j in range(3):
subgrid = []
for i in range(3):
for j in range(3):
subgrid.append(grid[3*box_i + i][3*box_j + j])
subgrids.append(subgrid)
return np.array(subgrids)
def get_candidates(grid : np.ndarray) -> list:
"""Get a list of candidates to fill empty cells of the input grid"""
def subgrid_index(i, j):
return (i//3) * 3 + j // 3
subgrids = get_subgrids(grid)
grid_candidates = []
for i in range(9):
row_candidates = []
for j in range(9):
# Row, column and subgrid digits
row = set(grid[i])
col = set(grid[:, j])
sub = set(subgrids[subgrid_index(i, j)])
common = row | col | sub
candidates = set(range(10)) - common
# If the case is filled take its value as the only candidate
if not grid[i][j]:
row_candidates.append(list(candidates))
else:
row_candidates.append([grid[i][j]])
grid_candidates.append(row_candidates)
return grid_candidates
def is_valid_grid(grid : np.ndarray) -> bool:
"""Verify the input grid has a possible solution"""
candidates = get_candidates(grid)
for i in range(9):
for j in range(9):
if len(candidates[i][j]) == 0:
return False
return True
def is_solution(grid : np.ndarray) -> bool:
"""Verify if the input grid is a solution"""
if np.all(np.sum(grid, axis=1) == 45) and \
np.all(np.sum(grid, axis=0) == 45) and \
np.all(np.sum(get_subgrids(grid), axis=1) == 45):
return True
return False
def filter_candidates(grid : np.ndarray) -> list:
"""Filter input grid's list of candidates"""
test_grid = grid.copy()
candidates = get_candidates(grid)
filtered_candidates = deepcopy(candidates)
for i in range(9):
for j in range(9):
# Check for empty cells
if grid[i][j] == 0:
for candidate in candidates[i][j]:
# Use test candidate
test_grid[i][j] = candidate
# Remove candidate if it produces an invalid grid
if not is_valid_grid(fill_singles(test_grid)):
filtered_candidates[i][j].remove(candidate)
# Revert changes
test_grid[i][j] = 0
return filtered_candidates
def merge(candidates_1 : list, candidates_2 : list) -> list:
"""Take shortest candidate list from inputs for each cell"""
candidates_min = []
for i in range(9):
row = []
for j in range(9):
if len(candidates_1[i][j]) < len(candidates_2[i][j]):
row.append(candidates_1[i][j][:])
else:
row.append(candidates_2[i][j][:])
candidates_min.append(row)
return candidates_min
def fill_singles(grid : np.ndarray, candidates=None) -> np.ndarray:
"""Fill input grid's cells with single candidates"""
grid = grid.copy()
if not candidates:
candidates = get_candidates(grid)
any_fill = True
while any_fill:
any_fill = False
for i in range(9):
for j in range(9):
if len(candidates[i][j]) == 1 and grid[i][j] == 0:
grid[i][j] = candidates[i][j][0]
candidates = merge(get_candidates(grid), candidates)
any_fill = True
return grid
def make_guess(grid : np.ndarray, candidates=None) -> np.ndarray:
"""Fill next empty cell with least candidates with first candidate"""
grid = grid.copy()
if not candidates:
candidates = get_candidates(grid)
# Getting the shortest number of candidates > 1:
min_len = sorted(list(set(map(
len, np.array(candidates).reshape(1,81)[0]))))[1]
for i in range(9):
for j in range(9):
if len(candidates[i][j]) == min_len:
for guess in candidates[i][j]:
grid[i][j] = guess
solution = solve(grid)
if solution is not None:
return solution
# Discarding a wrong guess
grid[i][j] = 0
def solve(grid : np.ndarray) -> np.ndarray:
"""Recursively find a solution filtering candidates and guessing values"""
candidates = filter_candidates(grid)
grid = fill_singles(grid, candidates)
if is_solution(grid):
return grid
if not is_valid_grid(grid):
return None
return make_guess(grid, candidates)
# # Example usage
# puzzle = """100920000
# 524010000
# 000000070
# 050008102
# 000000000
# 402700090
# 060000000
# 000030945
# 000071006"""
# grid = create_grid(puzzle)
# solve(grid)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Numpyification</h1>\n<p><code>get_subgrids</code> essentially rearranges a numpy array with a minimum of numpy. It could be done with numpy itself, for example:</p>\n<pre><code>def get_subgrids(grid: np.ndarray) -> np.ndarray:\n """Divide the input grid into 9 3x3 sub-grids"""\n\n swapped = np.swapaxes(np.reshape(grid, (3, 3, 3, 3)), 1, 2)\n return np.reshape(swapped, (9, 9))\n</code></pre>\n<p>The downside I suppose is that swapping the middle two axes of a 4D array is a bit mind-bending.</p>\n<h1>Performance</h1>\n<p>Almost all time is spent in <code>get_candidates</code>. I think the reasons for that are mainly:</p>\n<ul>\n<li>It gets called too often. For example, after filling in a cell (such as in <code>fill_singles</code>), rather than recompute the candidates from scratch, it would be faster to merely remove the new value from the candidates in the same row/col/house.</li>\n<li>If a cell is filled, the list of candidates is just the filled-in value, but the expensive set computation is done anyway. That's easy to avoid just by moving those statement inside the <code>if</code>.</li>\n</ul>\n<h1>Algorithmic performance</h1>\n<p>This solver only makes use of Naked Singles as a "propagation technique", adding Hidden Singles is in my experience a very large step towards an efficient solver.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:19:45.443",
"Id": "486380",
"Score": "0",
"body": "Thank you very much for your review. I couldn't find of way to numpify the sub-grids and your recommendation is spot on. One question, how did you find that the `get_candidates` function is the most used? Was it by simple checking of the code or did you use any tool? Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:26:06.767",
"Id": "486381",
"Score": "1",
"body": "@fabrizzio_gz I used [`%%prun`](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-prun) in a jupyter notebook, if you're running the code as standalone script you could use [one of these](https://docs.python.org/3/library/profile.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T03:22:01.133",
"Id": "486396",
"Score": "0",
"body": "Great to know. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T20:41:33.550",
"Id": "248337",
"ParentId": "248330",
"Score": "2"
}
},
{
"body": "<p>I was able to improve the performance of the program by about 900% without understanding or changing much of the algorithm in about an hour. Here's what I did:</p>\n<p>First of all, you need a benchmark. It's very simple, just time your program</p>\n<pre class=\"lang-py prettyprint-override\"><code>start = time.time()\nsolve(grid)\nprint(time.time()-start)\n</code></pre>\n<p>On my computer, it took about 4.5 seconds. This is our baseline.</p>\n<p>The next thing is to profile. The tool I chose is VizTracer, which is developed by myself :) <a href=\"https://github.com/gaogaotiantian/viztracer\" rel=\"nofollow noreferrer\">https://github.com/gaogaotiantian/viztracer</a></p>\n<p>VizTracer will generate an HTML report(or json that could be loaded by chrome:://tracing) of timeline of your code execution. It looks like this in your original version:</p>\n<p><a href=\"https://i.stack.imgur.com/Ltzmm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ltzmm.png\" alt=\"Original version\" /></a></p>\n<p>As you can tell, there are a lot of calls on there. The thing we need to do is to figure out what is the bottleneck here. The structure is not complicated, a lot of <code>fill_singles</code> are called, and we need to zoom in to check what's in there.</p>\n<p><a href=\"https://i.stack.imgur.com/47nAc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/47nAc.png\" alt=\"Original Zoom in\" /></a></p>\n<p>It's very clear that <code>get_candidates</code> is the function that caused most of the time in <code>fill_singles</code>, which is occupying most of the timeline. So that's the function we want to take a look at first.</p>\n<pre><code>def get_candidates(grid : np.ndarray) -> list:\n """Get a list of candidates to fill empty cells of the input grid"""\n\n def subgrid_index(i, j):\n return (i//3) * 3 + j // 3\n\n subgrids = get_subgrids(grid)\n grid_candidates = []\n for i in range(9):\n row_candidates = []\n for j in range(9):\n # Row, column and subgrid digits\n row = set(grid[i])\n col = set(grid[:, j])\n sub = set(subgrids[subgrid_index(i, j)])\n common = row | col | sub\n candidates = set(range(10)) - common\n # If the case is filled take its value as the only candidate\n if not grid[i][j]:\n row_candidates.append(list(candidates))\n else:\n row_candidates.append([grid[i][j]])\n grid_candidates.append(row_candidates)\n return grid_candidates\n</code></pre>\n<p>The thing that caught my eyes first was the end of your nested for loop. You checked whether <code>grid[i][j]</code> is filled. If it is, then that's the only candidate. However, if it's filled, then it has nothing to do with <code>candidates</code>, which you computed very hard in your nested for loop.</p>\n<p>So the first thing I did was moving the check to the beginning of the for loop.</p>\n<pre><code> for i in range(9):\n row_candidates = []\n for j in range(9):\n if grid[i][j]:\n row_candidates.append([grid[i][j]])\n continue\n # Row, column and subgrid digits\n row = set(grid[i])\n col = set(grid[:, j])\n sub = set(subgrids[subgrid_index(i, j)])\n common = row | col | sub\n candidates = set(range(10)) - common\n row_candidates.append(list(candidates)) \n</code></pre>\n<p>This optimization alone cut the running time in half, we are at about 2.3s now.</p>\n<p>Then I noticed in your nested for loop, you are doing a lot of redundant set operations. Even row/col/sub only needs to be computed 9 times, you are computing it 81 times, which is pretty bad. So I moved the computation out of the for loop.</p>\n<pre><code>def get_candidates(grid : np.ndarray) -> list:\n """Get a list of candidates to fill empty cells of the input grid"""\n\n def subgrid_index(i, j):\n return (i//3) * 3 + j // 3\n\n subgrids = get_subgrids(grid)\n grid_candidates = []\n\n row_sets = [set(grid[i]) for i in range(9)]\n col_sets = [set(grid[:, j]) for j in range(9)]\n subgrid_sets = [set(subgrids[i]) for i in range(9)]\n total_sets = set(range(10))\n\n for i in range(9):\n row_candidates = []\n for j in range(9):\n if grid[i][j]:\n row_candidates.append([grid[i][j]])\n continue\n # Row, column and subgrid digits\n row = row_sets[i]\n col = col_sets[j]\n sub = subgrid_sets[subgrid_index(i, j)]\n common = row | col | sub\n candidates = total_sets - common\n # If the case is filled take its value as the only candidate\n row_candidates.append(list(candidates))\n grid_candidates.append(row_candidates)\n return grid_candidates\n</code></pre>\n<p>This cut the running time to about 1.5s. Notice that, I have not try to understand your algorithm yet. Thing only thing I did was to use VizTracer to find the function that needs to be optimized and do same-logic transform. I improved performance by about 300% in like 15 minutes.</p>\n<p>To this point, the overhead of VizTracer on WSL is significant, so I turned off the C function trace. Only Python functions were left and the overhead was about 10%.</p>\n<p><a href=\"https://i.stack.imgur.com/byr2G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/byr2G.png\" alt=\"first fix\" /></a></p>\n<p>Now the <code>get_candidates</code> was improved(although it can be done better), we need to take a bigger picture of this. What I can observe from VizTracer's result was that <code>fill_singles</code> called <code>get_candidates</code> very frequently, just too many calls. (This is something that's hard to notice on cProfiler)</p>\n<p>So the next step was to figure out if we can make <code>fill_singles</code> call <code>get_candidates</code> less often. Here it requires some level of algorithm understanding.</p>\n<pre><code> while any_fill:\n any_fill = False\n for i in range(9):\n for j in range(9):\n if len(candidates[i][j]) == 1 and grid[i][j] == 0:\n grid[i][j] = candidates[i][j][0]\n candidates = merge(get_candidates(grid), candidates)\n any_fill = True\n</code></pre>\n<p>It looks like here you tried to fill in one blank with only one candidate, and recalculate the candidates of the whole grid, then find the next blank with one candidate. This is a valid method, but this caused too many calls to <code>get_candidates</code>. If you think about it, when we fill in a blank with a number <code>n</code>, all the other blanks with only one candidate that's not <code>n</code> won't be affected. So during one pass of the grid, we could actually try to fill more blanks in, as long as we do not fill in the same number twice. This way, we can call <code>get_candidates</code> less often, which is a huge time consumer. I used a set to do this.</p>\n<pre><code> filled_number = set()\n for i in range(9):\n for j in range(9):\n if len(candidates[i][j]) == 1 and grid[i][j] == 0 and candidates[i][j][0] not in filled_number:\n grid[i][j] = candidates[i][j][0]\n filled_number.add(candidates[i][j][0])\n any_fill = True\n candidates = merge(get_candidates(grid), candidates)\n</code></pre>\n<p>This brought the running time to 0.9s.</p>\n<p>Then I looked at the VizTracer report, I realized <code>fill_singles</code> is almost always called by <code>filter_candidates</code> and the only thing <code>filter_candidates</code> is interested in, is whether <code>fill_singles</code> returns a valid grid. This is an information we might know early, as long as <code>fill_singles</code> finds a position with no candidates. If we return early, we don't need to calculate <code>get_candidates</code> that many times.</p>\n<p>So I changed the code structure a little bit, made <code>fill_singles</code> return <code>None</code> if it can't find a valid grid.</p>\n<p>Finally I was able to make the run time to 0.5s, which is 900% faster than the original version.</p>\n<p>It was actually a fun adventure because I was testing my project VizTracer and tried to figure out if it was helpful to locate the time consuming part. It worked well :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T03:43:50.573",
"Id": "486499",
"Score": "0",
"body": "That's amazing! Your modifications are quite simple but they vastly improve performance. I'll perform try performing similar analyses in the future. Congratulations on VizTracer! Great tool. I'll use it in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T05:17:47.650",
"Id": "486501",
"Score": "1",
"body": "Thanks! I was hoping that VizTracer can help people on problems like this. My boss once told me, never optimize without profiling. A good profiler is indeed very helpful to improve the performance :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T05:57:08.137",
"Id": "248348",
"ParentId": "248330",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T18:12:57.690",
"Id": "248330",
"Score": "2",
"Tags": [
"python",
"sudoku"
],
"Title": "Recursive Sudoku solver using Python"
}
|
248330
|
<p>I got this test online last week.
here is an example:</p>
<p>given this array:</p>
<blockquote>
<p>{ 1 , 2 , 4 , 5 , 1 , 4 , 6 , 2 , 1 , 4 }</p>
</blockquote>
<p>on condition that</p>
<blockquote>
<p>index(x) < index (y)</p>
</blockquote>
<p>find the number of possible pairs (x,y).</p>
<p>where x = y.</p>
<p>the answer would be:</p>
<blockquote>
<p>count = 7 - (0,4), (0,8), (4,8), (1,7), (2,5), (2,9), (5,9)</p>
</blockquote>
<p><strong>Edit3:</strong> added picture to clarify the pairs are elements from the same array. the picture has the first 3 pairs.</p>
<p><a href="https://i.stack.imgur.com/ZtfTL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZtfTL.png" alt="enter image description here" /></a></p>
<p>the first solution I came up with which was obviously bad:</p>
<pre><code>public static int solution(int[] A)
{
int count = 0;
for (int i = 0; i < A.Length; i++)
{
for (int j = i + 1; j < A.Length; j++)
{
if (A[i] == A[j])
count++;
}
}
return count;
}
</code></pre>
<p>basically, just count the number of possible pairs in each loop.</p>
<p>then after a bit of struggle I managed to do this:</p>
<pre><code>public static int solution(int[] A)
{
int count = 0;
var dict = new Dictionary<int, int>();
for (int i = 0; i < A.Length; i++)
{
if (!dict.Any(x => x.Key == A[i]))
dict.Add(A[i], 1);
else
dict[A[i]]++;
}
foreach (var item in dict)
{
count += Factorial(item.Value) / 2 * Factorial(item.Value - 2);
}
return count;
}
</code></pre>
<p>1- count how many times the number is present.</p>
<p>2- calculate the possible pairs for each number which is given by this formula:</p>
<p><a href="https://i.stack.imgur.com/e78Cg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e78Cg.png" alt="enter image description here" /></a></p>
<p>where n is the number of repetitions and r = 2 (pair, 2 items)</p>
<p><strong>Factorial</strong> is just a simple implementation of the function.</p>
<p>I feel like there is a lot to improve on this. what do you think?</p>
<p><strong>Edit:</strong> added the Factorial Function as requested:</p>
<pre><code>public static int Factorial(int N)
{
return N == 0
? 1
: Enumerable.Range(1, N).Aggregate((i, j) => i * j);
}
</code></pre>
<p><strong>Edit2:</strong>
I tested both and got <strong>20s</strong> for the first method and <strong>500ms</strong> for the second improved method.</p>
<p>the 100000 was the limit set by the test details.</p>
<p>here is the code for the test:</p>
<pre><code>int[] testArray = new int[100000];
Random x = new Random();
for (int i = 0; i < testArray.Length; i++)
{
testArray[i] = x.Next(1, 10);
}
Stopwatch sw = new Stopwatch();
sw.Start();
solution(testArray);
sw.Stop();
</code></pre>
<p><strong>Edit4:</strong></p>
<p>Well, it seems like I messed up!</p>
<p>calculating factorial for numbers bigger 19 in intger is not possible, out of range.</p>
<p>the worse is I didn't even have to calculate it.</p>
<p>in my formula since r is a constant I could simplify it to</p>
<blockquote>
<p>n* (n -1) / 2</p>
</blockquote>
<p>thus avoiding the entire thing.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:59:56.333",
"Id": "486404",
"Score": "0",
"body": "It appears that your question is missing the Y array as stated by the condition index(x) < index (y). That indicates to me that the size of x has to be less than the size of y. Can you post a link to the test and/or check/edit your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T07:08:03.343",
"Id": "486405",
"Score": "0",
"body": "the y is from the same array,\nalso where could I post the code online?\n@AlexLeo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T07:12:16.400",
"Id": "486407",
"Score": "0",
"body": "In other words Y = X+ 1 ? or Y is all the other elements with index greater than X? Add a link to the test in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T07:16:59.233",
"Id": "486408",
"Score": "0",
"body": "@AlexLeo I edited the question to add a clarification."
}
] |
[
{
"body": "<p>Based on the calculation of the number of pairs -your assertion is correct.\nThe whole calculation method could be simplified by:</p>\n<pre><code> public static List<KeyValuePair<int,int>> solution(int[] A)\n {\n\n //n(n-1)/2 number of pairs by a given set\n return A.GroupBy(x => x).ToList().\n Select(y => new KeyValuePair<int, int>((y.Count() * (y.Count() - 1)) / 2, y.Key)).ToList();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T10:42:50.200",
"Id": "486416",
"Score": "0",
"body": "testing the performance, it seems like it did not suffer this was simple and fast just needed to sum the keys at the end since the method is required to return an integer so\n\nreturn A.GroupBy(x => x).ToList().\n Sum(y => (y.Count() * (y.Count() - 1) / 2));\n\ngreat answer, Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T07:06:35.490",
"Id": "248350",
"ParentId": "248333",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248350",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T19:29:55.843",
"Id": "248333",
"Score": "3",
"Tags": [
"c#",
"array"
],
"Title": "Finding the possible number of equal pairs in an array"
}
|
248333
|
<p>I stumbled upon a post on Reddit a few days ago and I thought I make my own! It's a program to extract from a movie file (.mkv, .mp4, etc.) and stack them horizontally next to each other and make one picture of all the frames available in the movie file. how can I make it more pythonic, readable, and sufficient?</p>
<p>Also, <a href="https://github.com/blackdead263/framez" rel="nofollow noreferrer">THIS</a> is the GitHub link, pull requests are welcome.</p>
<p>Also, the default frame rate (the number of frames to extract one from, to stack up in the output image) is 5.</p>
<pre><code>from natsort import natsorted
from ffprobe import FFProbe
from time import sleep
from tqdm import tqdm
from PIL import Image
import cv2
import os
# get and format file path
path = input('All modules loaded, press enter to proceed...\nEnter file path to the file(w/ filename, w/out the last backslash):\n')
if not os.path.exists(path):
print("Path is incorrect, quitting")
exit(0)
if path[0] == "~":
os.path.expanduser(path) # replace ~ with literal home address
meta = FFProbe(path)
# get metadata
video_duration = meta.metadata["Duration"][:-3]
rate = meta.video[0].framerate
height = int(meta.video[0].width)
# one shot per 5 seconds
freq = int(rate) * 5
# info for the process bar
hours = int(video_duration[1]) * 3600
minutes = int(video_duration[3:5]) * 60
seconds = int(video_duration[-2:])
duration_seconds = hours + minutes + seconds
frames = rate * duration_seconds
output_images = frames // freq # number of extracted images
(directory, video_name) = os.path.split(path)
dst_path = directory + "/images/"
os.system("mkdir " + dst_path)
os.system("mkdir " + dst_path + "resized")
print("Destination folder created.\n")
print("Extracting frames...")
cap = cv2.VideoCapture(path)
i = 1 # current captured frame, how many 24's has already been iterated
os.system('clear')
with tqdm(total=frames) as pbar:
while cap.isOpened():
frame_id = cap.get(1) # first frame in the current stream
ret, frame = cap.read()
if ret != True: # if run out of frames, video finished
break
if frame_id % freq == 0: # if frame# is a multiplicand of freq=24
filename = dst_path + str(i) + ".jpg"
i += 1
cv2.imwrite(filename, frame) # create the image
pbar.update(1)
print(str(output_images) + " images extracted successfully.")
cap.release()
del pbar
src_path = directory + "/images/"
dst_path = src_path + "resized/"
images = natsorted(os.listdir(src_path))
os.system("clear")
i = 1
max_counter = len(images) - 1 # all images count
with tqdm(total=output_images) as pbar:
for image in images:
if i <= max_counter: # process until all images are done
read_path = src_path + image
img = cv2.imread(read_path, cv2.IMREAD_UNCHANGED)
w = 2 # convert to 2px
h = img.shape[1] # unchanged
dim = (w, h)
resized = cv2.resize(img, dim)
filename = dst_path + str(i) + "_re.jpg"
cv2.imwrite(filename, resized) # create the image
if i == 1: # do only once
print(str(img.shape) + " convert to " + str(dim))
i += 1
pbar.update(1)
else:
print("Finished " + str(len(images) - 1) + " pictures.")
images_list = natsorted(os.listdir(dst_path))
images_list = [Image.open(dst_path + x) for x in images_list]
# we have the height, user input #3
width = len(images_list) * 2 # number of small pictures, each 2px
out = Image.new("RGB", (width, height)) # create an empty image
x_offset = 0
for im in images_list:
out.paste(im, (x_offset, 0))
x_offset += im.size[0]
out.save(directory + "/" + video_name[:-4] + ".jpg")
print("Cleaning Up...")
os.system("rm -rf " + src_path)
print("All set, finishing now.")
</code></pre>
|
[] |
[
{
"body": "<p>Some suggestions aimed at more general issues rather than specific details in\nyour lines of code:</p>\n<ul>\n<li><p><strong>Computers are not our friends, no need to chat</strong>. Get user input from the command line, not from <code>input()</code>. Interactive user\ninput is a bad usage model for the default behavior of a script -- with rare\nexceptions. Use interactivity only for special circumstances, and always\nprovide a command-line option to bypass that interactivity. In addition,\n<code>input()</code> is terrible for development because it requires you (the coder) to go\ninto a dialogue with your script <strong>every damn time</strong> you run it. Super\nannoying. One option for handling command-line input is\n<a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\">argparse</a>. See the script\nbelow for the template that I usually follow in my scripts.</p>\n</li>\n<li><p><strong>But functions are our friends</strong>. Organize your code into functions. Have each function do one thing. Among\nother things, this approach allows you to test each small piece of behavior as\nyou write it.</p>\n</li>\n<li><p><strong>Either do or talk</strong>. Do not <code>print()</code> inside your functions that do the actual work (aside from some quite rare exceptions). Functions should take arguments, calculate something or do\nsomething, and return some meaningful data (or <code>None</code>). If the larger program\nrequires printing ultimately, use the data returned from functions to do that\nprinting. But keep computation and printing in separate realms.</p>\n</li>\n<li><p><strong>No magical tokens in the castle</strong>. Keep literal strings and values out of your code. Instead put them in one\nor more containers. In many situations, I usually just use a <code>Constants</code> class\nand module-level global (<code>con</code>), as shown below. Good practice, but easy and\nlow-tech.</p>\n</li>\n</ul>\n<p>The script template:</p>\n<pre><code>import argparse\nimport sys\n\nclass Constants:\n\n EXIT_OK = 0\n EXIT_FAIL = 1\n\n NEWLINE = '\\n'\n NAMES = 'names'\n BAR = 'BAR'\n BAR_PROPAGANDA = 'Sucker, should have picked --bar!'\n\n OPTS_CONFIG = (\n {\n NAMES: 'path',\n },\n {\n NAMES: '-b --bar',\n 'action': 'store_true',\n },\n )\n\ncon = Constants()\n\ndef main(args):\n ap, opts = parse_args(args)\n if opts.bar:\n print(con.BAR, opts)\n exit()\n else:\n print(opts)\n exit(con.EXIT_FAIL, con.BAR_PROPAGANDA)\n\ndef parse_args(args):\n ap = argparse.ArgumentParser()\n for oc in con.OPTS_CONFIG:\n kws = dict(oc)\n xs = kws.pop(con.NAMES).split()\n ap.add_argument(*xs, **kws)\n opts = ap.parse_args(args)\n return (ap, opts)\n\ndef exit(code = None, msg = None):\n code = con.EXIT_OK if code is None else code\n fh = sys.stderr if code else sys.stdout\n if msg:\n nl = con.NEWLINE\n msg = msg if msg.endswith(nl) else msg + nl\n fh.write(msg)\n sys.exit(code)\n\ndef your_function_foo(opts):\n pass\n\ndef your_function_bar(opts):\n pass\n\n# Etc.\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:54:09.777",
"Id": "486402",
"Score": "0",
"body": "I always learn something here. Thank you for mentioning argparse. I am currently working on a project that needs this sorely. I was trying to roll my own solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T16:50:07.400",
"Id": "486453",
"Score": "2",
"body": "why create an instance of `Constants`, when you can just reference the static members inside without one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T17:15:21.873",
"Id": "486455",
"Score": "1",
"body": "@lights0123 Laziness and readability: `con` is easier to type, read, and visually scan."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T06:46:07.647",
"Id": "486504",
"Score": "0",
"body": "'Constans` class is very interesting, never seen that before. I usually just define constants after import like `TOKEN = \"asd\"`. Is it a bad practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:43:33.757",
"Id": "486559",
"Score": "0",
"body": "@politicalscientist No, your approach is fine too. I slightly prefer bundling them under `Constants` for ease of importing. In larger projects, you can end up have a lot of constants, and it can become a drag to import each one you need. (And I dislike `import *`, for different reasons.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:47:16.220",
"Id": "486562",
"Score": "0",
"body": "@FMc, it totally makes sense. thank you!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T01:05:41.557",
"Id": "248344",
"ParentId": "248338",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T20:55:09.187",
"Id": "248338",
"Score": "9",
"Tags": [
"python",
"python-3.x"
],
"Title": "Stacking frames of a video file horizontally into a single image"
}
|
248338
|
<p>Was a tiny bit bored reading authentication protocols.<br />
Needed to clear the mind and read some base64 encode text.</p>
<p>So I implemented these iterators that will encode or decode base64 text.</p>
<p>Not sure about:</p>
<ul>
<li>Interface is there a better way</li>
<li>Iterator Implementation (its been a while since I did one)</li>
<li>How easy to make this work with Ranges?</li>
</ul>
<p>Usage:</p>
<pre><code> int main()
{
std::string data = getBase64Message(); // retrieves a message base 64 encoded.
std::string message(make_decode64(std::begin(data)),
make_decode64(std::end(data)));
std::cout << message << "\n";
std::copy(make_encode64(std::istream_iterator<char>(std::cin)),
make_encode64(std::istream_iterator<char>()),
std::ostream_iterator<char>(std::cout));
}
</code></pre>
<p>The basic concept is that they are iterators that are constructed with other iterators. So you can decode any type of container as long as you can get a readable iterator to it (technically the iterator has to be an input iterator).</p>
<hr />
<p>Nobody has submitted a review. So I am adding version 2 the cleaned up (and commented) version to the question. I will leave the original version at the bottom for comparison:</p>
<pre><code>#ifndef THORS_ANVIL_CRYPTO_BASE_H
#define THORS_ANVIL_CRYPTO_BASE_H
namespace ThorsAnvil::Crypto
{
template<typename I>
class Base64DecodeIterator
{
I iter = I{};
int bits = 0;
int buffer = 0;
public:
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = char*;
using reference = char&;
using iterator_category = std::input_iterator_tag;
Base64DecodeIterator() {}
Base64DecodeIterator(I iter)
: iter(iter)
{}
// Check state of iterator.
// We are not done until all the bits have been read even if we are at the end iterator.
bool operator==(Base64DecodeIterator const& rhs) const {return (iter == rhs.iter) && (bits == 0);}
bool operator!=(Base64DecodeIterator const& rhs) const {return !(*this == rhs);}
// Increment Simply remove bits.
// Note: The interface for input iterator required a * before each ++ operation.
// So we don't need to do any work on the ++ operator but do it all in the * operator
Base64DecodeIterator& operator++() {bits -= 8;return *this;}
Base64DecodeIterator operator++(int) {Base64DecodeIterator result(this);++(*this);return result;}
char operator*()
{
// If nothing in the buffer than fill it up.
if (bits == 0)
{
static constexpr char convert[]
= "\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F" // 0 - 15 00 - 0F
"\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F" // 16 - 31 10 - 1F
"\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x8F\x3E\x8F\x8F\x8F\x3F" // 32 - 47 20 - 2F + /
"\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x8F\x8F\x8F\x40\x8F\x8F" // 48 - 63 30 - 3F 0-9
"\x8F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E" // 64 - 79 40 - 4F A-O
"\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x8F\x8F\x8F\x8F\x8F" // 80 - 95 50 - 5F P-Z
"\x8F\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28" // 96 -111 60 - 6F a-o
"\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x8F\x8F\x8F\x8F\x8F"; // 112 -127 70 - 7F p-z
int extra = 0;
// Base64 input is based on the input being 3 input bytes => 4 output bytes.
// There will always be a multiple of 3 bytes on the input. So read 3 bytes
// at a time.
while (bits != 24)
{
unsigned char tmp = *iter++;
unsigned char b64 = convert[tmp & 0x7F];
if (b64 == 0x8F || tmp > 0x7F)
{
throw std::runtime_error("Base64DecodeIterator::operator*: invalid input");
}
if (b64 == 0x40) // We found a padding byte '='
{
extra += 8;
b64 = 0;
}
buffer = (buffer << 6) | b64;
bits = bits + 6;
}
// Remove any padding bits we found.
buffer = buffer >> extra;
bits -= extra;
}
char result = (buffer >> (bits - 8)) & 0xFF;
return result;
}
};
template<typename I>
class Base64EncodeIterator
{
I iter = I{};
mutable int bits = 0;
mutable int buffer = 0;
public:
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = char*;
using reference = char&;
using iterator_category = std::input_iterator_tag;
Base64EncodeIterator() {}
Base64EncodeIterator(I iter)
: iter(iter)
{}
enum Flags
{
EndFlag = 0x8000,
FillFlag = 0x4000,
Data = 0x3FFF,
};
bool operator==(Base64EncodeIterator const& rhs) const
{
// Note: That we have reached the end of the input stream.
// That means we can not read more data in the * operator.
// Note: The input iterator interface requires you to the check␣
// the iterator against end before continuing.
if (iter == rhs.iter)
{
buffer = buffer | EndFlag;
}
// We are not finished even if we have reached the end iterator
// if there is still data left to decode in the buffer.
return (iter == rhs.iter) && (bits == 0);
}
bool operator!=(Base64EncodeIterator const& rhs) const {return !(*this == rhs);}
// Increment the current position.
Base64EncodeIterator& operator++() {bits -= 6;return *this;}
Base64EncodeIterator operator++(int) {Base64EncodeIterator result(this);++(*this);return result;}
char operator*()
{
// We convert three 8 bit values int four 6 bit values.
// But the input can be any size (i.e. it is not padded to length).
// We must therefore detect then end of stream (see operator ==) and
// insert the appropriate padding on the output. But this also means
// we can not simply keep reading from the input as we cant detect
// the end here.
//
// Therefor we only reads 1 byte at a time from the input. We don't
// need to read a byte every call as we have 2 bits left over from
// each character read thus every four call to this function will
// return a byte without a read.
//
// Note this means the buffer will only ever have a maximum of 14 bits (0-13)␣
// of data in it. We re-use bits 14/15 as flags. Bit 15 marks the end
// Bit 14 indicates that we should return a padding character.
// Check if we should return a padding character.
bool fillFlag = buffer & FillFlag;
if (bits < 6)
{
if (buffer & EndFlag)
{
// If we have reached the end if the input
// we simply pad the data with 0 value in the buffer.
// Note we add the FillFlag here so the next call
// will be returning a padding character
buffer = EndFlag | FillFlag | ((buffer << 8) & Data);
}
else
{
// Normal operation. Read data from the input
// Add it to the buffer.
unsigned char tmp = *iter++;
buffer = ((buffer << 8) | tmp) & Data;
}
bits += 8;
}
static constexpr char convert[]
= "ABCDEFGHIJKLMNOP" // 00 - 0F
"QRSTUVWXYZabcdef" // 10 - 1F
"ghijklmnopqrstuv" // 20 - 2F
"wxyz0123456789+/"; // 30 - 3F
// Output is either padding or converting the 6 bit value into an encoding.
char result = fillFlag ? '=' : convert[(buffer >> (bits - 6)) & 0x3F];
return result;
}
};
template<typename I>
Base64DecodeIterator<I> make_decode64(I iter)
{
return Base64DecodeIterator<I>(iter);
}
template<typename I>
Base64EncodeIterator<I> make_encode64(I iter)
{
return Base64EncodeIterator<I>(iter);
}
}
#endif
</code></pre>
<hr />
<p>The original version is below:</p>
<pre><code>#ifndef THORS_ANVIL_CRYPTO_BASE_H
#define THORS_ANVIL_CRYPTO_BASE_H
namespace ThorsAnvil::Crypto
{
template<typename I>
class Base64DecodeIterator
{
I iter;
int bits;
int value;
public:
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = char*;
using reference = char&;
using iterator_category = std::input_iterator_tag;
Base64DecodeIterator()
: iter(I{})
, bits(0)
, value(0)
{}
Base64DecodeIterator(I iter)
: iter(iter)
, bits(0)
, value(0)
{}
bool operator==(Base64DecodeIterator const& rhs) const
{
return (iter == rhs.iter) && (bits == 0);
}
bool operator!=(Base64DecodeIterator const& rhs) const
{
return !(*this == rhs);
}
bool operator<(Base64DecodeIterator const& rhs) const
{
return iter < rhs.iter || (iter == rhs.iter && bits != 0);
}
char operator*()
{
if (bits == 0)
{
int extra = 0;
while (bits != 24)
{
unsigned char tmp = *iter++;
unsigned char b64;
if (tmp >= 'A' && tmp <= 'Z')
{
b64 = tmp - 'A';
}
else if (tmp >= 'a' && tmp <= 'z')
{
b64 = tmp - 'a' + 26;
}
else if (tmp >= '0' && tmp <= '9')
{
b64 = tmp - '0' + 52;
}
else if (tmp == '+')
{
b64 = 63;
}
else if (tmp == '/')
{
b64 = 64;
}
else if (tmp == '=')
{
b64 = 0;
extra += 8;
}
else
{
throw std::runtime_error("Bad Input");
}
value = (value << 6) | b64;
bits = bits + 6;
}
value = value >> extra;
bits -= extra;
}
char result = (value >> (bits - 8)) & 0xFF;
return result;
}
Base64DecodeIterator& operator++()
{
bits -= 8;
return *this;
}
Base64DecodeIterator operator++(int)
{
Base64DecodeIterator result(this);
bits -= 8;
return result;
}
};
template<typename I>
class Base64EncodeIterator
{
I iter;
mutable int bits;
mutable int value;
public:
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = char*;
using reference = char&;
using iterator_category = std::input_iterator_tag;
Base64EncodeIterator()
: iter(I{})
, bits(0)
, value(0)
{}
Base64EncodeIterator(I iter)
: iter(iter)
, bits(0)
, value(0)
{}
enum Flags
{
EndFlag = 0x8000,
FillFlag = 0x4000,
Data = 0x3FFF,
};
bool operator==(Base64EncodeIterator const& rhs) const
{
if (iter == rhs.iter)
{
value = value | EndFlag;
}
return (iter == rhs.iter) && (bits == 0);
}
bool operator!=(Base64EncodeIterator const& rhs) const
{
return !(*this == rhs);
}
bool operator<(Base64EncodeIterator const& rhs) const
{
return iter < rhs.iter || (iter == rhs.iter && bits != 0);
}
char operator*()
{
bool fillFlag = value & FillFlag;
if (bits < 6)
{
if (value & EndFlag)
{
value = EndFlag | FillFlag | ((value << 8) & Data);
}
else
{
unsigned char tmp = *iter++;
value = ((value << 8) | tmp) & Data;
}
bits += 8;
}
char result = '=';
if (!fillFlag)
{
int tmp = (value >> (bits - 6)) & 0x3F;
if (tmp < 26)
{
result = 'A' + tmp;
}
else if (tmp < 52)
{
result = 'a' + (tmp - 26);
}
else if (tmp < 62)
{
result = '0' + (tmp - 52);
}
else if (tmp == 62)
{
result = '+';
}
else
{
result = '/';
}
}
bits -= 6;
return result;
}
Base64EncodeIterator& operator++()
{
return *this;
}
Base64EncodeIterator operator++(int)
{
Base64EncodeIterator result(this);
return result;
}
};
template<typename I>
Base64DecodeIterator<I> make_decode64(I iter)
{
return Base64DecodeIterator<I>(iter);
}
template<typename I>
Base64EncodeIterator<I> make_encode64(I iter)
{
return Base64EncodeIterator<I>(iter);
}
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:47:36.567",
"Id": "486445",
"Score": "0",
"body": "where is the function `getBase64Message`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T17:14:30.360",
"Id": "486454",
"Score": "1",
"body": "@Peter It represents your code that retrieves a base 64 message from some part of your system. `std::string getBase64Message() {return \"AAAA\";}`"
}
] |
[
{
"body": "<h1>Avoid repeating yourself</h1>\n<p>I see a few cases where you can avoid repeating type names. For example:</p>\n<pre><code>I iter = I{};\n</code></pre>\n<p>This can be written as:</p>\n<pre><code>I iter{};\n</code></pre>\n<p>And:</p>\n<pre><code>Base64DecodeIterator operator++(int) {Base64DecodeIterator result(this); ++(*this); return result;}\n</code></pre>\n<p>Can be written as:</p>\n<pre><code>Base64DecodeIterator operator++(int) {auto result{*this}; ++(*this); return result;}\n</code></pre>\n<h1>Avoid writing multiple statements on one line</h1>\n<p>Since it is so customary in C and C++ to write one statement per line, when you combine multiple statements on one line, especially without whitespace between the statements, it can be confusing. Just split multi-statement one-liners into multiple lines, like:</p>\n<pre><code>Base64DecodeIterator operator++(int) {\n auto result{*this};\n ++(*this);\n return result;\n}\n</code></pre>\n<h1>Consider supporting different input and output types</h1>\n<p>Consider a situation where you have a blob of binary data, to which you have a <code>char *</code> or <code>uint8_t *</code>, but you need to the base64-encoded string to use <code>wchar_t</code>. You could support this relatively easy by adding another template parameter to describe the output type, like so:</p>\n<pre><code>template<typename I, typename CharT = char>\nclass Base64EncodeIterator\n{\n ...\n using value_type = CharT;\n using pointer = CharT*;\n using reference = CharT&;\n ...\n CharT operator*()\n {\n ...\n }\n};\n</code></pre>\n<p>You would make the same change for <code>Base64DecodeIterator</code>. The <code>make_*</code> functions can look like:</p>\n<pre><code>template<typename CharT = char, typename I>\nBase64DecodeIterator<I, CharT> make_encode64(I iter)\n{\n return Base64EncodeIterator<I, CharT>(iter);\n}\n</code></pre>\n<p>Then you could use it like so:</p>\n<pre><code>std::vector<uint8_t> original(...);\n\nstd::wstring message(make_encode64<wchar_t>(std::begin(original)), \n make_encode64<wchar_t>(std::end(original)));\n\nstd::vector<uint8_t> recovered(make_decode64<uint8_t>(std::begin(message)),\n make_decode64<uint8_t>(std::end(message)));\n</code></pre>\n<h1>Consider <code>I::value_type</code> not being an 8 bit integer type during encoding</h1>\n<p>Your code will accept the following:</p>\n<pre><code>std::vector<float> data{1.1, 42, 9.9e99};\nmake_encode64(data.begin());\n</code></pre>\n<p>But what this will do is cast each element of the vector to an <code>unsigned char</code> before encoding it. That is not what you would expect. Use SFINAE or Concepts to limit the allowed iterators to those that have a <code>value_type</code> that is an 8-bit integer type.</p>\n<p>When encoding you have the same problem if you allow the output type to be specified as mentioned in the previous point.</p>\n<h1>Making it work with ranges</h1>\n<p>The problem is that your classes do not implement a <a href=\"https://en.cppreference.com/w/cpp/ranges/range\" rel=\"nofollow noreferrer\"><code>std::ranges::range</code></a>. So you would need to introduce some class that provides both the begin and end iterator. But that could be as simple as:</p>\n<pre><code>template<typename I>\nclass Base64Decoder {\n Base64DecodeIterator begin_it;\n Base64DecodeIterator end_it;\n\npublic:\n Base64Decoder(const I &begin, const I &end): begin_it(begin), end_it(end) {}\n\n template<typename T>\n Base64Decoder(T &container): begin_it(std::begin(container)), end_it(std::end(container)) {}\n\n auto& begin() {\n return begin_it;\n }\n \n auto& end() {\n return end_it;\n }\n};\n</code></pre>\n<p>And then you could write:</p>\n<pre><code>std::string input = "SGVsbG8sIHdvcmxkIQo=";\nBase64Decoder decoder(input);\nfor (auto c: input | std::ranges::views::take(5))\n std::cout << c;\nstd::cout << '\\n';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:10:55.880",
"Id": "486480",
"Score": "1",
"body": "Thanks for the review. Not sure wide characters is a good idea as base64 is 1 octet encoding scheme."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T05:59:04.327",
"Id": "486502",
"Score": "1",
"body": "Well on Windows it is common to use `wchar_t` to encode things like file names and so on, so there is some merit for it on some platforms. And it's templated, so it's just a few extra lines and no run-time overhead as far as I can tell."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:59:43.573",
"Id": "486570",
"Score": "1",
"body": "So I understand what the result should look like. I decode the base64 to octet then I place 1 octet per wchar_t character or do I place multiple octets into a single character. When converting back do I treat each wchar_t as a single 8 bit value or multiple 8 bit values."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T20:14:11.663",
"Id": "248383",
"ParentId": "248339",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248383",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T21:24:49.160",
"Id": "248339",
"Score": "8",
"Tags": [
"c++",
"iterator",
"base64"
],
"Title": "base64 iterators"
}
|
248339
|
<p>Over on Stack Overflow, I read <a href="https://stackoverflow.com/a/63541389/2402272">an answer</a> asserting that Insertion Sort was inferior to Selection Sort for array data (as opposed to linked list data) on account of the larger amount of data movement that insertion sort performs on average. This claim was new to me, running counter to many assertions I have read and accepted over the years of the general superiority of Insertion sort among its comparison-sort peers. Moreover, my own algorithmic analysis supports Insertion sort as being slightly better on average for random data, assuming efficient implementations of both algorithms and an environment where memory writes are not appreciably more expensive than reads.</p>
<p>But inasmuch as the two algorithms have the same asymptotic cost, all the argumentation is so much smoke without testing. Therefore, I wrote a selection sort, an insertion sort, and a test harness to put some actual data in play. I was surprised by the results: my Insertion sort was <em>way</em> faster than my Selection sort on random input (about one fourth the running time), and Insertion was a clear winner even for its worst case of reverse-sorted input. I didn't expect Insertion to perform so much better in the average case, and I didn't expect it to win at all in the reverse-sorted input case.</p>
<p>And that brings me here. I present my two sort functions and the test harness for your review and commentary. I am particularly interested in insights on how the selection sort's performance might be improved, so as to ensure that the test is a fair one. I am also interested in commentary on any flaws in the test harness that might bias the results.</p>
<p><strong>selection.c</strong></p>
<pre><code>void selection(int data[], unsigned int count) {
for (unsigned int i = 0; i < count - 1; i++) {
int min_value = data[i];
unsigned int min_index = i;
for (unsigned int j = i + 1; j < count; j++) {
if (data[j] < min_value) {
min_index = j;
min_value = data[j];
}
}
data[min_index] = data[i];
data[i] = min_value;
}
}
</code></pre>
<hr />
<p><strong>selection.h</strong></p>
<pre><code>void selection(int data[], unsigned int count);
</code></pre>
<hr />
<p><strong>insertion.c</strong></p>
<pre><code>void insertion(int data[], unsigned int count) {
for (unsigned int i = 1; i < count; i++) {
int test_value = data[i];
unsigned int j;
for (j = i; j > 0; j--) {
if (data[j - 1] > test_value) {
data[j] = data[j - 1];
} else {
break;
}
}
if (j != i) {
data[j] = test_value;
}
}
}
</code></pre>
<hr />
<p><strong>insertion.h</strong></p>
<pre><code>void insertion(int data[], unsigned int count);
</code></pre>
<hr />
<p><strong>main.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "insertion.h"
#include "selection.h"
#define NUM_ITEMS 16384
#define RANDOM_SEED 17231
#define ITERATIONS 32
#define CLOCKS_PER_MS (CLOCKS_PER_SEC / 1000)
int original_items[NUM_ITEMS];
int selection_items[NUM_ITEMS];
int insertion_items[NUM_ITEMS];
int main(void) {
clock_t start_time;
clock_t total_time;
int num_distinct;
srand(RANDOM_SEED);
for (int i = 0; i < NUM_ITEMS; i++) {
original_items[i] = rand() % NUM_ITEMS;
}
// test selection
total_time = 0;
for (int i = 0; i < ITERATIONS; i++) {
memcpy(selection_items, original_items, sizeof(original_items));
start_time = clock();
selection(selection_items, NUM_ITEMS);
total_time += clock() - start_time;
}
// Validation / sanity check
num_distinct = 1;
for (int i = 1; i < NUM_ITEMS; i++) {
if (selection_items[i] < selection_items[i - 1]) {
printf("Selection result validation failed.\n");
}
if (selection_items[i] != selection_items[i - 1]) {
num_distinct++;
}
}
printf("%d distinct values sorted\n", num_distinct);
printf("Selection sort on %d items: %ld ms\n", NUM_ITEMS, (long) (total_time / ITERATIONS / CLOCKS_PER_MS));
// test insertion
total_time = 0;
for (int i = 0; i < ITERATIONS; i++) {
memcpy(insertion_items, original_items, sizeof(original_items));
start_time = clock();
insertion(insertion_items, NUM_ITEMS);
total_time += clock() - start_time;
}
// Validation
for (int i = 0; i < NUM_ITEMS; i++) {
if (insertion_items[i] != selection_items[i]) {
printf("Insertion result differs from selection result.\n");
}
}
printf("Insertion sort on %d items: %ld ms\n", NUM_ITEMS, (long) (total_time / ITERATIONS / CLOCKS_PER_MS));
}
</code></pre>
<hr />
<p><strong>Makefile</strong></p>
<pre><code>PROG = sort_test
OBJS = main.o selection.o insertion.o
CFLAGS = -O3 -Wall -Wextra -pedantic -std=c11
$(PROG) : $(OBJS)
$(CC) -o $@ $(CFLAGS) $(LDFLAGS) $^
main.o selection.o: selection.h
main.o insertion.o: insertion.h
clean:
rm $(PROG) $(OBJS)
.PHONY: clean
</code></pre>
<hr />
<p>I built and tested the code in a WSL container running SUSE Leap 42.3, featuring GCC 4.8.5.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T10:49:40.867",
"Id": "486417",
"Score": "1",
"body": "I notice your test tests the selection sort first then the insertion sort. Could it be that all the page faults necessary to make either of them function were resolved on the selection sort? I would shut my computer off cold, boot it from scratch, maybe do some other stuff first, run the selection-then-insetion test, then modify the program to do it the other way around and repeat the tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T16:39:50.207",
"Id": "486450",
"Score": "0",
"body": "Fair question, @Jennifer. I tried testing them in the opposite order, and it made no appreciable difference in their computed timing."
}
] |
[
{
"body": "<h2>Observations</h2>\n<p>Very interesting question.</p>\n<p>The numbers I came up with when running the program are</p>\n<blockquote>\n<p>10248 distinct values sorted<br />\nSelection sort on 16384 items: 353 ms<br />\nInsertion sort on 16384 items: 176 ms</p>\n</blockquote>\n<p>Which makes the insertion sort twice as fast as the selection sort.\nThis is on Windows 10 using Visual Studio 2019 on a 4 year old Lenovo Thinkpad P50\nwith 32GB and an Intel i7-6820HQ processor.</p>\n<p>After I rewrote the code to use functions, here are my results. Notice that the selection sort time went up slightly:</p>\n<blockquote>\n<p>10248 distinct values sorted by insertion<br />\n10248 distinct values sorted by selection<br />\nselection sort on 16384 items: 355 ms<br />\ninserstion sort on 16384 items: 176 ms</p>\n</blockquote>\n<p>I was going to add a section on global variables but when I first tried to rewrite the code I discovered a reason for them, the arrays are too large and the stack can't support them, at least on my laptop. I also used memory allocation to put as much of the data as possible on the heap rather than on the stack. That would be one way to get around any global variables.</p>\n<p>You might want to see if you can optimize both <code>selection</code> and <code>insertion</code> to bring the numbers down.</p>\n<p>Declare variables as you need them, the C programming language no longer requires all variables to be declared at the top of a code block.</p>\n<h2>Improvements to the Code</h2>\n<p>You worked too hard or at least wrote too much code in <code>main()</code>.</p>\n<p>I see 3 distinct functions possible, and one of them would have reduced the repetition of the existing code.</p>\n<p>You can use pointers to the sort functions to make common functions for testing.</p>\n<p>I decided to validate the sorts before testing for time, if one of the sorts doesn't work timing it doesn't make sense.</p>\n<p>Given the implementation below you could test more sorts to find the best one by adding new sort functions.</p>\n<p>Here are the functions I see:</p>\n<pre><code>int original_items[NUM_ITEMS];\n\nstatic void generate_unsorted_data(void)\n{\n srand(RANDOM_SEED);\n for (int i = 0; i < NUM_ITEMS; i++) {\n original_items[i] = rand() % NUM_ITEMS;\n }\n}\n\nstatic void validate_results(void(*ptr_to_sort_function)(int data[], unsigned int count), char *func_name)\n{\n int *sorted_items = calloc(NUM_ITEMS, sizeof(*sorted_items));\n if (!sorted_items)\n {\n fprintf(stderr, "calloc failed in validate_results\\n");\n return;\n }\n memcpy(sorted_items, original_items, sizeof(original_items));\n\n ptr_to_sort_function(sorted_items, NUM_ITEMS);\n\n int num_distinct = 1;\n for (int i = 1; i < NUM_ITEMS; i++) {\n if (sorted_items[i] < sorted_items[i - 1]) {\n printf("%s result validation failed.\\n", func_name);\n }\n if (sorted_items[i] != sorted_items[i - 1]) {\n num_distinct++;\n }\n }\n\n printf("%d distinct values sorted by %s\\n", num_distinct, func_name);\n free(sorted_items);\n}\n\nstatic void time_test_sort(void(*ptr_to_sort_function)(int data[], unsigned int count), char* func_name)\n{\n clock_t start_time;\n clock_t total_time;\n int* sorted_items = calloc(NUM_ITEMS, sizeof(*sorted_items));\n if (!sorted_items)\n {\n fprintf(stderr, "calloc failed in validate_results\\n");\n return;\n }\n\n total_time = 0;\n for (int i = 0; i < ITERATIONS; i++) {\n memcpy(sorted_items, original_items, sizeof(original_items));\n start_time = clock();\n ptr_to_sort_function(sorted_items, NUM_ITEMS);\n total_time += clock() - start_time;\n }\n\n printf("%s sort on %d items: %ld ms\\n", func_name, NUM_ITEMS, (long)(total_time / ITERATIONS / CLOCKS_PER_MS));\n free(sorted_items);\n}\n\nint main(void) {\n\n generate_unsorted_data();\n\n validate_results(insertion, "insertion");\n\n validate_results(selection, "selection");\n\n time_test_sort(selection, "selection");\n\n time_test_sort(insertion, "insertion");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T03:12:03.467",
"Id": "486395",
"Score": "1",
"body": "Thank you. I agree that your version of the test harness is nicely factored and readily adaptable to testing additional alternatives. As for optimizing `selection` and `insertion`, I take it that you do not see any specific improvements to suggest -- is that fair? I do not see any myself, but one of my reasons for requesting review was to let another set of eyes verify (or refute!) that my sort implementations faithfully represent their respective algorithms, and do not unfairly handicap either one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T10:53:44.513",
"Id": "486418",
"Score": "1",
"body": "It's not about optimizing these sorts. It's about deciding which is inherently faster; all that's needed optimization-wise is that they should each be optimized, if possible, to the same degree."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T01:02:45.010",
"Id": "248343",
"ParentId": "248340",
"Score": "8"
}
},
{
"body": "<p>Insertion sort allows a little known optimization. As coded, each iteration of an inner loop performs <em>two</em> comparisons: <code>j > 0</code> and <code>data[j - 1] > test_value</code>. It is possible to get away with <em>one</em>:</p>\n<pre><code>if (test_value < data[0]) {\n // No need to compare data anymore. Just shift.\n for (j = i; j > 0; j--) {\n data[j] = data[j - 1];\n }\n} else {\n // No need to check for indices anymore. data[0] is a natural sentinel.\n while (data[j - 1] > test_value) {\n data[j] = data[j - 1];\n --j;\n }\n}\ndata[j] = test_value;\n</code></pre>\n<p>As a <strong>no naked loops</strong> mantra dictates, the loops shall be refactored into function, <code>shift</code> and <code>unguarded_insert</code> respectively.</p>\n<p><sub>To be clear, <a href=\"https://stackoverflow.com/users/3403834/user58697\">user58697</a> who commented on <a href=\"https://stackoverflow.com/a/63542585/3403834\">John Bollinger's answer</a> to the linked question is me.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T12:32:42.340",
"Id": "486428",
"Score": "1",
"body": "Curious about the \"no naked loops mantra\" (and skeptical about mantras in general) I cannot find good references about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:25:38.917",
"Id": "486437",
"Score": "0",
"body": "@edc65 Every loop represents an important algorithm, and thus deserves a name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T16:14:06.610",
"Id": "486447",
"Score": "0",
"body": "For the record, I wrote this Code Review question before looking into the optimization described in this answer. When I did look into it, I found that it didn't make a significant difference in the random-input test case presented in this question, but it yielded a tremendous improvement for some other kinds of inputs, such as reverse-sorted ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T20:40:18.377",
"Id": "486478",
"Score": "1",
"body": "@edc65 \"No raw loops\" -- Sean Parent. I can't remember which conference talk specifically. It might be _C++ Seasoning_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T06:57:00.377",
"Id": "486505",
"Score": "0",
"body": "@Justin thx for the reference. It's Seasoning indeed"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T04:47:57.197",
"Id": "248347",
"ParentId": "248340",
"Score": "8"
}
},
{
"body": "<p>I'm running this on an Haswell (4770K but the specific model shouldn't matter). I compiled with MSVC 2017 version 15.9 .. and MASM I suppose, you will see. The performance difference between the selection sort and insertion sort was 5x: 166ms vs 33ms. That difference is simmilar to what you saw, so it may be for the same reason.</p>\n<blockquote>\n<p>I am particularly interested in insights on how the selection sort's performance might be improved, so as to ensure that the test is a fair one.</p>\n</blockquote>\n<p>As it turns out, there may be, but whether a comparison with that version is <em>more fair</em> is not a simple question.</p>\n<p>An other fairness concern in benchmarks is ensuring that what gets measures is what was intended to be measured. C code is not what actually runs, so looking at it does not necessarily give much insight into that question. With that in mind, here are the annotated "most important blocks" from both algorithms, and analyzed with Intel VTune. So here is, from <code>selection</code>, the important part:</p>\n<pre><code>Address Instruction Clock ticks\n0x140001040 mov edx, dword ptr [r11] 1,862,000,000\n0x140001043 lea r11, ptr [r11+0x4] 7,000,000\n0x140001047 cmp edx, eax 700,000,000\n0x140001049 mov ecx, r10d 1,736,000,000\n0x14000104c cmovnl ecx, r8d 1,837,500,000\n0x140001050 cmovnl edx, eax 7,217,000,000\n0x140001053 inc r10d 4,140,500,000\n0x140001056 mov r8d, ecx 7,000,000\n0x140001059 mov eax, edx 693,000,000\n0x14000105b cmp r10d, 0x4000 1,683,500,000\n0x140001062 jb 0x140001040\n</code></pre>\n<p>The distribution of clock ticks does not entirely make sense when taken at face value (that <code>inc r10d</code> should be innocent), but some slight "smearing out" of slowdowns is normal. Anyway, <code>cmov</code> was used, and <code>cmov</code> is the main culprit according to VTune. Maybe <code>cmov</code> <em>should</em> take a lot of time, after all, it is what's really doing the work (the selection part of selection sort).</p>\n<p>Whether <code>cmov</code> or a branch is used is unfortunately not up to the source code, from the point of view of C code it is an uncontrollable variable with a potentially huge impact. For completeness, it should be looked into anyway. So as an additional experiment, which I suggest you also try to replicate, I took the code that MSVC emitted for <code>selection</code> and modified it to use a branch (and did a minimal modification to make it work, MSVC is cheating just a little bit and not actually passing a pointer into the function but directly refers to a global):</p>\n<pre><code>_text SEGMENT\n\nselection2 PROC FRAME\n.endprolog\n mov qword ptr [rsp+8],rbx \n mov qword ptr [rsp+10h],rsi \n mov qword ptr [rsp+18h],rdi \n mov rsi,rcx \n mov r9d,1 \n mov rbx,rsi \n_block2:\n mov eax,dword ptr [rbx] \n mov edi,eax \n lea r8d,[r9-1] \n mov r10d,r9d \n cmp r9d,4000h \n jae _block5 \n mov ecx,r9d \n lea r11,[rsi+rcx*4] \n_block4:\n mov edx,dword ptr [r11] \n lea r11,[r11+4] \n cmp edx,eax \n jge _skip\n mov r8d, r10d\n mov eax, edx\n_skip:\n inc r10d\n cmp r10d,4000h \n jb _block4\n_block5:\n inc r9d \n mov ecx,r8d \n mov dword ptr [rsi+rcx*4],edi \n mov dword ptr [rbx],eax \n add rbx,4 \n lea eax,[r9-1] \n cmp eax,3FFFh \n jb _block2 \n mov rbx,qword ptr [rsp+8] \n mov rsi,qword ptr [rsp+10h] \n mov rdi,qword ptr [rsp+18h] \n ret \nselection2 ENDP\n\nEND\n</code></pre>\n<p>(various modifications would be needed to port this to linux, re-doing the <code>cmov</code>-to-branch conversion would be easier)</p>\n<p>Imported on the C side with <code>extern void selection2(int* data);</code>.</p>\n<p>Result: 72ms. Much faster! It's still twice as slow as insertion sort, but it's a huge improvement compared to the <code>cmov</code> version.</p>\n<p>But what is fair, is the <code>cmov</code> version fair? That is what MSVC outputs by default, so in that sense it is representative of the "real life performance of selection sort", maybe.. but the <code>cmov</code> is not inherent to the algorithm, it's an artifact from an (apparently mistaken!) compiler optimization. A different compiler can just as well decide to use a branch, which could be why @pacmaninbw reports a similar 2x perf gap rather than a 4x or 5x gap.</p>\n<p>Fortunately (maybe?) Selection Sort lost both ways, so all of this doesn't change the winner, but it could have.</p>\n<p>The code MSVC outputs for <code>insertion</code> is actually not that interesting to look at. The assembly code does exactly what you'd expect, no curve balls. It's good to look, though, just in case.</p>\n<p>Finally, I'll note that both algorithms can be optimized using SIMD, which has the potential to upset the balance. It could be seen as "unlocking the true potential" of those algorithms, so maybe it is fair in that sense. Or it could be seen as "going too far" - is that still representative of the algorithms or gone way past that into comparing specific snippets of assembly code, and unfair in that sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T23:24:13.140",
"Id": "486487",
"Score": "0",
"body": "Interestingly, I found that with a newer GCC, the relative performance of the selection sort improved to the same factor of 2 slower that seems to be showing up in others' tests. In all cases I am compiling with a high optimization level enabled, on the assumption -- not necessarily fulfilled, as you point out -- that that will yield comparably good results for both algorithms."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T22:52:59.833",
"Id": "248390",
"ParentId": "248340",
"Score": "3"
}
},
{
"body": "<p>As the main point of the question is about performance and not refactoring, I will address the performance of the code.</p>\n<p>Unfortunately, the question doesn't include actual numbers, just</p>\n<blockquote>\n<p>my Insertion sort was way faster than my Selection sort on random input (about one fourth the running time), and Insertion was a clear winner even for its worst case of reverse-sorted input.</p>\n</blockquote>\n<p>I compiled the above code with GCC 9.2.1 on Linux, because it is the version on the computer I'm currently using.</p>\n<p>The results are:</p>\n<ul>\n<li><p>For the code in the question, random order:</p>\n<pre><code> 10350 distinct values sorted\n Selection sort on 16384 items: 78 ms\n Insertion sort on 16384 items: 38 ms\n</code></pre>\n</li>\n<li><p>For inverse sorted input:</p>\n<pre><code> 16384 distinct values sorted\n Selection sort on 16384 items: 77 ms\n Insertion sort on 16384 items: 77 ms\n</code></pre>\n</li>\n</ul>\n<p>Variation when running it multiple times is around 1ms, so the results should be sufficiently exact.</p>\n<p>That means:</p>\n<ul>\n<li>Your compiler is probably not as good at optimizing the selection sort, or better at optimizing the insertion sort.</li>\n<li>It is to be expected that the insertion sort is faster on random data. That is because the insertion sort has a break condition in the inner loop. While both have a complexity of O(n^2), insertion sort will on average for random data only need to check half of the already sorted data, while selection sort must always check the complete unsorted rest of the data. In the case of reverse sorted input data, both algorithms need the same number inner loop executions.</li>\n</ul>\n<p>It is correct that insertion moves more data around, but the way you are doing it, you get it basically for free. What that means is that the value to be moved has already been read and available for the following write, and the write goes to a memory location that is already in the cache.<br />\nOther architectures and compilers may lead to different results.</p>\n<p>In case someone is interested in the math, the number of comparisons for the selection sort is n*(n-1)/2. This is also the worst case number for insertion sort, while the average number for insertion sort on random data is just half that value, n*(n-1)/2/2</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:14:33.970",
"Id": "248414",
"ParentId": "248340",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "248343",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:08:25.687",
"Id": "248340",
"Score": "10",
"Tags": [
"c",
"sorting",
"benchmarking"
],
"Title": "Insertion sort vs Selection Sort benchmarking"
}
|
248340
|
<p>I'm currently implementing permissions into an application and are trying to save this onto a database using Hibernate. There are modules with commands and the permissions are also categorized using possible-null role, text channel and role+text channel.</p>
<p>Therefore I want to achieve the following:</p>
<ul>
<li>You can either deny/allow modules or commands</li>
<li>You can allow/deny them by server, by server role, by text channel, or by server role and text channel or for a specific user</li>
<li>There are also general permissions, that are plain string key-value</li>
</ul>
<p>I created the following class for it:</p>
<pre><code>@Entity
public class Permission implements IPermission {
@Id
@GeneratedValue
private long id;
@Column
private long guildId;
@Column
@Enumerated(EnumType.STRING)
private Permission.Type type; // GENERAL, GLOBAL, SERVER, ROLE, ROLECHANNEL
@Column
private String permissionKey;
@Column(nullable = false)
private long channelId;
@Column(nullable = false)
private long roleId;
@Column(nullable = false)
private long userId;
@Column
@Enumerated(EnumType.STRING)
private Tribool action; // TRUE, NEUTRAl, FALSE
@Override
public long getId() {
return this.id;
}
@Override
public long getGuildId() {
return this.guildId;
}
@Override
public long getChannelId() {
return this.channelId;
}
@Override
public long getRoleId() {
return this.roleId;
}
@Override
public long getUserId() {
return this.userId;
}
@Override
public Optional<String> getModule() {
if(this.permissionKey.startsWith("module.")) {
return Optional.of(this.permissionKey.split(".")[1]);
} else {
return Optional.empty();
}
}
@Override
public Optional<String> getCommand() {
if(this.permissionKey.startsWith("command.")) {
return Optional.of(this.permissionKey.split(".")[1]);
} else {
return Optional.empty();
}
}
@Override
public Tribool getAction() {
return this.action;
}
public static enum Type {
GENERAL,
GLOBAL,
SERVER,
ROLE,
CHANNEL,
ROLECHANNEL
}
}
</code></pre>
<p>But I don't know if this a good way of saving it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T06:57:48.867",
"Id": "486506",
"Score": "1",
"body": "How would this be used? For a proper review, we'll need to see how you're currently using this to make sense of whether it's a good system or not."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:29:33.047",
"Id": "248341",
"Score": "2",
"Tags": [
"java",
"hibernate",
"jpa"
],
"Title": "Permission Representation"
}
|
248341
|
<p>I implemented concepts for container and allocator types. I referenced type requirements from <a href="https://en.cppreference.com/w/cpp/named_req/Container" rel="nofollow noreferrer">here</a> for container and <a href="https://en.cppreference.com/w/cpp/named_req/Allocator" rel="nofollow noreferrer">here</a> for allocator.</p>
<p>For the sake of simplicity, there are a lot of type aliases declared in the template because <a href="https://stackoverflow.com/questions/40332980/c-concepts-lite-and-type-alias-declaration">concept itself does not allow declaration</a>.</p>
<p>I'm also concerned that many parts of the code are duplicate or irrelevant as of C++20.</p>
<p>For example, I excluded <code>A::template rebind<U>::other</code> from the requirements since it is removed in C++20. And, the allocator itself no longer requires methods other than <code>allocate</code> and <code>deallocate</code>.</p>
<p>Here is the entire code. Thanks in advance.</p>
<pre><code>#include <utility>
#include <memory>
#include <iterator>
#include <type_traits>
#include <concepts>
namespace phd {
template<typename T>
concept copy_assignable = std::is_copy_assignable_v<T>;
template<typename T>
concept move_assignable = std::is_move_assignable_v<T>;
template<typename T>
concept nullable_pointer =
std::equality_comparable<T> &&
std::default_initializable<T> &&
std::copy_constructible<T> &&
copy_assignable<T> &&
std::destructible<T> &&
requires (T p, T q) {
{ T(nullptr) } -> std::same_as<T>;
{ p = nullptr } -> std::same_as<T&>;
{ p != q } -> std::convertible_to<bool>;
{ p == nullptr } -> std::convertible_to<bool>;
{ nullptr == p } -> std::convertible_to<bool>;
{ p != nullptr } -> std::convertible_to<bool>;
{ nullptr != p } -> std::convertible_to<bool>;
};
template<
typename Alloc,
typename T = Alloc::value_type,
typename pointer = std::allocator_traits<Alloc>::pointer,
typename const_pointer = std::allocator_traits<Alloc>::const_pointer,
typename void_pointer = std::allocator_traits<Alloc>::void_pointer,
typename const_void_pointer =
std::allocator_traits<Alloc>::const_void_pointer,
typename size_type = std::allocator_traits<Alloc>::size_type,
typename difference_type = std::allocator_traits<Alloc>::difference_type
>
concept allocator =
nullable_pointer<pointer> &&
std::random_access_iterator<pointer> &&
std::contiguous_iterator<pointer> &&
nullable_pointer<const_pointer> &&
std::random_access_iterator<const_pointer> &&
std::contiguous_iterator<const_pointer> &&
std::convertible_to<pointer, const_pointer> &&
nullable_pointer<void_pointer> &&
std::convertible_to<pointer, void_pointer> &&
nullable_pointer<const_void_pointer> &&
std::convertible_to<pointer, const_void_pointer> &&
std::convertible_to<const_pointer, const_void_pointer> &&
std::convertible_to<void_pointer, const_void_pointer> &&
std::unsigned_integral<size_type> &&
std::signed_integral<difference_type> &&
std::copy_constructible<Alloc> &&
std::move_constructible<Alloc> &&
copy_assignable<Alloc> &&
move_assignable<Alloc> &&
std::equality_comparable<Alloc> &&
requires(Alloc a) {
typename T;
// *p
{*std::declval<pointer>()} -> std::same_as<T&>;
// *cp
{*std::declval<const_pointer>()} -> std::same_as<const T&>;
// static_cast<Alloc::pointer>(vp)
requires
std::same_as<
decltype(static_cast<T*>(std::declval<void_pointer>())),
pointer
>;
// static_cast<Alloc::const_pointer>(cvp)
requires
std::same_as<
decltype(static_cast<const_pointer>(
std::declval<const_void_pointer>())),
const_pointer
>;
// std::pointer_traits<Alloc::pointer>::pointer_to(r)
{std::pointer_traits<pointer>::pointer_to(*std::declval<pointer>())}
-> std::same_as<pointer>;
{a.allocate(std::declval<size_type>())} -> std::same_as<pointer>;
{a.deallocate(std::declval<pointer>(), std::declval<size_type>())}
-> std::same_as<void>;
};
template<typename T, typename Alloc>
concept erasable = requires(Alloc m, T* p) {
{std::allocator_traits<Alloc>::destroy(m, p)} -> std::same_as<void>;
};
template<typename T, typename Alloc>
concept move_insertable = requires(Alloc m, T* p, T&& rv) {
{std::allocator_traits<Alloc>::construct(m, p, rv)} -> std::same_as<void>;
};
template<typename T, typename Alloc>
concept copy_insertable =
move_insertable<T, Alloc> &&
requires(Alloc m, T* p, const T& v) {
{std::allocator_traits<Alloc>::construct(m, p, v)}
-> std::same_as<void>;
};
template<typename Iter, typename Container>
concept container_iterator =
std::same_as<Iter, typename Container::iterator> ||
std::same_as<Iter, typename Container::const_iterator>;
template<
typename Container,
typename C = Container,
typename T = C::value_type,
typename Alloc = C::allocator_type,
typename value_type = T,
typename reference = C::reference,
typename const_reference = C::const_reference,
typename iterator = C::iterator,
typename const_iterator = C::const_iterator,
typename difference_type = C::difference_type,
typename size_type = C::size_type
>
concept container =
erasable<T, Alloc> &&
requires() {
typename reference;
typename const_reference;
} &&
std::forward_iterator<iterator> &&
std::convertible_to<iterator, const_iterator> &&
std::forward_iterator<const_iterator> &&
std::signed_integral<difference_type> &&
std::same_as<difference_type,
typename std::iterator_traits<iterator>::difference_type> &&
std::same_as<difference_type,
typename std::iterator_traits<const_iterator>::difference_type> &&
std::unsigned_integral<size_type> &&
std::default_initializable<C> &&
std::copy_constructible<C> &&
std::equality_comparable<C> &&
std::swappable<C> &&
copy_insertable<T, Alloc> &&
std::equality_comparable<T> &&
std::destructible<T> &&
requires (C a) {
{ a.~C() } -> std::same_as<void>;
{ a.begin() } -> container_iterator<C>;
{ a.end() } -> container_iterator<C>;
{ a.cbegin() } -> std::same_as<const_iterator>;
{ a.cend() } -> std::same_as<const_iterator>;
{ a.size() } -> std::same_as<size_type>;
{ a.max_size() } -> std::same_as<size_type>;
{ a.empty() } -> std::convertible_to<bool>;
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T07:52:06.013",
"Id": "503550",
"Score": "0",
"body": "Add `requires` before `requires (C a)`. Explanation: https://stackoverflow.com/questions/54200988/why-do-we-require-requires-requires"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:46:10.357",
"Id": "503576",
"Score": "0",
"body": "@isnullxbh `requires requires` only applies to function and class. When declaring `concept`, a single `requires` clause serves as a boolean expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:05:36.730",
"Id": "503578",
"Score": "0",
"body": "Check the following [example](https://wandbox.org/permlink/2h1nHRCCya5GKap4). GCC doesn't compile it (without second requires), Clang generates a warning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:28:53.907",
"Id": "503582",
"Score": "0",
"body": "@isnullxbh I think you misunderstood what I said. A single `requires` clause is used to apply constraints on subsequent stuff (function, class). The first `requires` from `requires requires` also does the same thing. But the latter one is a boolean constant expression. Unless you intentionally nest `requires` inside `requires` block just like the example you gave, a single `requires` is valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:31:35.857",
"Id": "503583",
"Score": "0",
"body": "As stated [here](https://en.cppreference.com/w/cpp/language/constraints), `requires` does two things: specifying constraints and boolean expression. The one used in my code represents the latter. Therefore, there's nothing wrong with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:59:59.880",
"Id": "503588",
"Score": "0",
"body": "Sorry, you're right. I was inattentive and thought that this `requires` is nested in other `requires`. Sorry again."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T03:57:25.893",
"Id": "248345",
"Score": "4",
"Tags": [
"c++",
"c++20"
],
"Title": "C++20 concepts for container and allocator"
}
|
248345
|
<p>I've tried to make a snake game. I think it works. But I really need your help to improve the code in terms of [readability - maintainability - efficiency, and so on]. Is my code spaghetti? Any criticism is appreciated.</p>
<p>Here's what's done:</p>
<pre><code>#include <iostream>
#include <vector>
#include <conio.h>
#include <cassert>
const int height = 25;
const int width = 90;
char board[height][width];
bool snake_pos[height][width];
std::vector<std::pair<int, int>> body; // body[0] head position
int cnt = 1;
void reset_board();
void draw_board();
void handle_input();
int foodX, foodY;
void reset_board() {
for (int i = 0; i < width; i++)
board[0][i] = '#';
for (int i = 1; i < height; i++) {
for (int j = 0; j < width; j++) {
// is border?
if (j == 0 || j == width - 1) {
board[i][j] = '#';
}
else {
board[i][j] = ' ';
}
}
}
for (int i = 0; i < width; i++) {
board[24][i] = '#';
}
board[body[0].first][body[0].second] = 'O';
for (int i = 1; i < body.size(); i++)
board[body[i].first][body[i].second] = 'o';
for (auto x : body)
snake_pos[x.first][x.second] = true;
board[foodX][foodY] = 'X';
}
void draw_board() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
std::cout << board[i][j];
}
std::cout << '\n';
}
}
int rand(int a, int b) {
return a + rand() % (b - a + 1);
}
void food() {
int x = rand(1, 23);
int y = rand(1, 88);
// while food pos is part of the snake
while (snake_pos[x][y]) {
x = rand(1, 23);
y = rand(1, 88);
}
foodX = x;
foodY = y;
}
#define KEY_UP 'w'
#define KEY_DOWN 's'
#define KEY_LEFT 'a'
#define KEY_RIGHT 'd'
bool game_over(int x, int y) {
// check if head ate body
for (int i = 1; i < body.size(); i++) {
if (std::make_pair(x, y) == body[i])
return true;
}
return false;
}
bool valid_move(char key) {
// check if move is not in opposite direction
// 0, 1, 2, 3 [left, right, up, down] respectively
if (cnt == 3 && key == KEY_UP)
return false;
if (cnt == 2 && key == KEY_DOWN)
return false;
if (cnt == 1 && key == KEY_LEFT)
return false;
if (cnt == 0 && key == KEY_RIGHT)
return false;
switch (key) {
case KEY_LEFT:
cnt = 0;
break;
case KEY_RIGHT:
cnt = 1;
break;
case KEY_UP:
cnt = 2;
break;
case KEY_DOWN:
cnt = 3;
break;
default:
assert(false);
}
return true;
}
bool food_eaten() {
return body[0].first == foodX && body[0].second == foodY;
}
void handle_input() {
char key = _getch();
if (key == KEY_UP && valid_move(key)) {
std::pair<int, int> prev = body[0];
body[0].first--;
if (body[0].first == 0)
body[0].first = 23;
if (game_over(body[0].first, body[0].second)) {
std::cout << "Game is over\n";
exit(0);
}
if (food_eaten()) {
board[foodX][foodY] = ' ';
// add tail
body.push_back({ body.back().first + 1, body.back().second });
reset_board();
// draw new food
food();
}
for (int i = 1; i < body.size(); i++) {
std::pair<int, int> tmp = body[i];
body[i] = prev;
prev = tmp;
}
}
else if (key == KEY_DOWN && valid_move(key)) {
std::pair<int, int> prev = body[0];
body[0].first++;
if (body[0].first == 24)
body[0].first = 1;
if (game_over(body[0].first, body[0].second)) {
std::cout << "Game is over\n";
exit(0);
}
if (food_eaten()) {
board[foodX][foodY] = ' ';
body.push_back({body.back().first - 1, body.back().second});
reset_board();
food();
}
for (int i = 1; i < body.size(); i++) {
std::pair<int, int> tmp = body[i];
body[i] = prev;
prev = tmp;
}
}
else if (key == KEY_LEFT && valid_move(key)) {
if (cnt == 1) return;
cnt = 0;
std::pair<int, int> prev = body[0];
body[0].second--;
if (body[0].second == 0) {
body[0].second = 88;
}
if (game_over(body[0].first, body[0].second)) {
std::cout << "Game is over\n";
exit(0);
}
if (food_eaten()) {
board[foodX][foodY] = ' ';
body.push_back({ body.back().first, body.back().second + 1 });
reset_board();
food();
}
for (int i = 1; i < body.size(); i++) {
std::pair<int, int> tmp = body[i];
body[i] = prev;
prev = tmp;
}
}
else if (key == KEY_RIGHT && valid_move(key)) {
std::pair<int, int> prev = body[0];
body[0].second++;
if (body[0].second == 89) {
body[0].second = 1;
}
if (game_over(body[0].first, body[0].second)) {
std::cout << "Game is over\n";
exit(0);
}
if (food_eaten()) {
board[foodX][foodY] = ' ';
body.push_back({ body.back().first, body.back().second - 1 });
reset_board();
food();
}
for (int i = 1; i < body.size(); i++) {
std::pair<int, int> tmp = body[i];
body[i] = prev;
prev = tmp;
}
}
system("cls");
reset_board();
draw_board();
}
int main()
{
food();
// initial snake
snake_pos[4][81] = snake_pos[4][80] = snake_pos[4][79] = snake_pos[4][82] = true;
body.push_back({ 4, 82 });
body.push_back({ 4, 81 });
body.push_back({ 4, 80 });
body.push_back({ 4, 79 });
while (true) {
handle_input();
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T20:18:27.957",
"Id": "486475",
"Score": "0",
"body": "Just so you know, there are several code reviews on this site for [C++ implementations of Snake](https://codereview.stackexchange.com/search?q=C%2B%2B+Snake). Consider having a look through them."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T04:21:15.093",
"Id": "248346",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Console Snake Game C++"
}
|
248346
|
<p>I wrote a Compressor utility class to generate 7zip files containing everything in a specific directory. The problem is that it's an order of magnitude slower than both archiving the directory using the native Windows 7zip.exe AND archiving to a .zip file using a ZipCompressor that uses the same algorithm but with the default Java zip classes.</p>
<pre><code>/*
* SevenZipCompressor.java
*
* Date 20/08/2020
*
* Copyright Ikan Software N.V. 2003 - 2020, All Rights Reserved.<br><br>
*
* This software is the proprietary information of Ikan Software N.V. .
* Use is subject to license terms.
*/
package lib.util.compressors.sevenzip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import lib.util.compressors.Compressor;
import lib.util.compressors.CompressorException;
import lib.util.compressors.Entry;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* The SevenZipCompressor class supplies a simple way of writing 7zip files.
*
* @author nak
*/
public class SevenZipCompressor extends Compressor {
/**
* @see lib.util.compressors.Compressor#compress
*/
public void compress(String fileName, String dirName) throws CompressorException {
// Zip the directory
File sevenZipFile = new File(fileName);
try (SevenZOutputFile out = new SevenZOutputFile(sevenZipFile)){
// loop over all files and add them plus their content recursively to the 7zip archive
// Zip the directory
File dir = new File(dirName);
compress(sevenZipFile, out, dir, dir);
} catch (IOException e) {
throw new CompressorException(e);
}
}
/**
* @see lib.util.compressors.Compressor#uncompress
*/
public void uncompress(String fileName, String dirName) throws CompressorException {
// Open the zipfile
try(SevenZFile zipFile = new SevenZFile(new File(fileName));) {
// Get the size of each entry
Map<String, Integer> zipEntrySizes = new HashMap<String, Integer> ();
Iterable<SevenZArchiveEntry> e = zipFile.getEntries();
for(Iterator<SevenZArchiveEntry> iterator = e.iterator(); iterator.hasNext();) {
SevenZArchiveEntry zipEntry = (SevenZArchiveEntry) iterator.next();
zipEntrySizes.put(zipEntry.getName(), Integer.valueOf((int) zipEntry.getSize()));
}
// Start reading zipentries
SevenZArchiveEntry zipEntry = null;
while ((zipEntry = zipFile.getNextEntry()) != null) {
// Zipentry is a file
if (!zipEntry.isDirectory()) {
// Get the size
int size = (int) zipEntry.getSize();
if (size == -1) {
size = ((Integer) zipEntrySizes.get(zipEntry.getName())).intValue();
}
// Get the content
byte[] buffer = new byte[size];
int bytesInBuffer = 0;
int bytesRead = 0;
while (((int) size - bytesInBuffer) > 0) {
bytesRead = zipFile.read(buffer, bytesInBuffer, size - bytesInBuffer);
if (bytesRead == -1) {
break;
}
bytesInBuffer += bytesRead;
}
String zipEntryName = zipEntry.getName();
// replace all "\" with "/"
zipEntryName = zipEntryName.replace('\\', '/');
// Get the full path name
File file = new File(dirName, zipEntryName);
// Create the parent directory
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// Save file
FileOutputStream fos = new FileOutputStream(file.getPath());
fos.write(buffer, 0, bytesInBuffer);
fos.close();
// Set modification date to the date in the zipEntry
file.setLastModified(zipEntry.getLastModifiedDate().getTime());
}
// Zipentry is a directory
else {
String zipEntryName = zipEntry.getName();
// replace all "\" with "/"
zipEntryName = zipEntryName.replace('\\', '/');
// Create the directory
File dir = new File(dirName, zipEntryName);
dir.setLastModified(zipEntry.getLastModifiedDate().getTime());
if (!dir.exists()) {
dir.mkdirs();
}
}
}
} catch (IOException ioe) {
throw new CompressorException(ioe);
}
}
/**
* @see lib.util.compressors.Compressor#getEntries
*/
public List<Entry> getEntries(String fileName, boolean calculateCrc) throws CompressorException {
// List to return all entries
List<Entry> entries = new ArrayList<Entry>();
try {
// Open the zipfile
SevenZFile zipFile = new SevenZFile(new File(fileName));
// Get the size of each entry
Iterable<SevenZArchiveEntry> iterable = zipFile.getEntries();
for(Iterator<SevenZArchiveEntry> iterator = iterable.iterator(); iterator.hasNext();) {
SevenZArchiveEntry zipEntry = iterator.next();
Entry entry = new Entry();
entry.setName(zipEntry.getName());
if (calculateCrc) {
entry.setCrc(zipEntry.getCrcValue());
} else {
entry.setCrc(-1);
}
entry.setDirectory(zipEntry.isDirectory());
// 7z is a very Windows specific format, using NTFSTimestamps instead of Java time.
entry.setTime(zipEntry.getLastModifiedDate().getTime());
entry.setSize(zipEntry.getSize());
entries.add(entry);
}
// Close zipFile
zipFile.close();
// Sort entries by ascending name
sortEntries(entries);
// Return entries
return entries;
} catch (IOException ioe) {
throw new CompressorException(ioe);
}
}
/**
* Add a new entry to the zip file.
*
* @param zos the output stream filter for writing files in the ZIP file format
* @param name the name of the entry.
* @param lastModified the modification date
* @param buffer an array of bytes
* @throws IOException
*/
private void addEntry(SevenZOutputFile zos, String name, File inputFile, byte[] buffer) throws IOException {
SevenZArchiveEntry zipEntry = zos.createArchiveEntry(inputFile, name);
if (buffer != null) {
zipEntry.setSize(buffer.length);
}
zipEntry.setLastModifiedDate(new Date(inputFile.lastModified()));
zos.putArchiveEntry(zipEntry);
if (buffer != null) {
zos.write(buffer);
}
zos.closeArchiveEntry();
}
/**
* Zip the files of the given directory.
*
* @param zipFile the File which is used to store the compressed data
* @param zos the output stream filter for writing files in the ZIP file format
* @param dir the directory to zip
* @param relativeDir the name of each zip entry will be relative to this directory
* @throws FileNotFoundException
* @throws IOException
*/
private void compress(File zipFile, SevenZOutputFile zos, File dir, File relativeDir) throws FileNotFoundException, IOException {
// Create an array of File objects
File[] fileList = dir.listFiles();
// Directory is not empty
if (fileList.length != 0) {
// Loop through File array
for (int i = 0; i < fileList.length; i++) {
// The zipfile itself may not be added
if (!zipFile.equals(fileList[i])) {
// Directory
if (fileList[i].isDirectory()) {
compress(zipFile, zos, fileList[i], relativeDir);
}
// File
else {
byte[] buffer = getFileContents(fileList[i]);
if (buffer != null) {
// Get the path names
String filePath = fileList[i].getPath();
String relativeDirPath = relativeDir.getPath();
// Convert the absolute path name to a relative path name
if (filePath.startsWith(relativeDirPath)) {
filePath = filePath.substring(relativeDirPath.length());
if (filePath.startsWith("/") || filePath.startsWith("\\")) {
if (filePath.length() == 1) {
filePath = "";
} else {
filePath = filePath.substring(1);
}
}
}
// Add the entry
addEntry(zos, filePath, fileList[i], buffer);
}
}
}
}
}
// Directory is empty
else {
// Get the path names
String filePath = dir.getPath();
String relativeDirPath = relativeDir.getPath();
// Convert the absolute path name to a relative path name
if (filePath.startsWith(relativeDirPath)) {
filePath = filePath.substring(relativeDirPath.length());
if (filePath.startsWith("/") || filePath.startsWith("\\")) {
if (filePath.length() == 1) {
filePath = "";
} else {
filePath = filePath.substring(1);
}
}
}
// Add the entry
if (!filePath.endsWith("\\") && !filePath.endsWith("/")) {
addEntry(zos, filePath + "/", dir, null);
}
else {
addEntry(zos, filePath, dir, null);
}
}
}
/**
* Read the contents of a file for zipping.
*
* @param file the File to read
* @return an array of bytes
* @throws FileNotFoundException
* @throws IOException
*/
private byte[] getFileContents(File file) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(file);
long len = file.length();
byte[] buffer = new byte[(int) len];
fis.read(buffer);
fis.close();
return buffer;
}
}
</code></pre>
<p>I doubt that Commons-Compress is so significantly slower than just the native 7zip.exe written by Igor Pavlov when used properly, so any feedback on how to speed this up is appreciated. For reference: a directory with 900 MB of data that would take roughly 45 seconds to compress using 7zip.exe takes over 5 minutes with this code.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T06:48:27.860",
"Id": "248349",
"Score": "2",
"Tags": [
"java",
"compression"
],
"Title": "SevenZipCompressor Utility class that uses Commons-Compress to compress and uncompress 7zip archives"
}
|
248349
|
<p>I am working on an e-commerce website. In this specific scenario, people can upload their CV to apply for a job. The job application is sent to <code>ApplyForJob</code> action method:</p>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> ApplyForJob(JobApplicationViewModel jobApplicationViewModel)
{
if (ModelState.IsValid)
{
// store the CV as the user's most recent CV inside his specific folder (S3 bucket)
_jobApplicationService.UpdateUserJobProfile(jobApplicationViewModel);
var adHeadline = GetAdHeadlineOrRedirectWithWarning(jobApplicationViewModel.AdBaseId);
// build JobApplicationEmail model
JobApplicationEmail jobApplicationDetails = new JobApplicationEmail(
jobApplicationViewModel.ApplicantFullName,
jobApplicationViewModel.ApplicantEmail,
adHeadline.UserProfileViewModel.FirstName,
adHeadline.GetBestContactEmail(),
adHeadline.Title,
ShoplessUrlHelper.GetCanonicalUrl(adHeadline.GetRelativeLink()),
jobApplicationViewModel.MessageHtmlString,
jobApplicationViewModel.CvByteArray,
jobApplicationViewModel.CvFileName,
jobApplicationViewModel.ApplicantPhoneNumber,
jobApplicationViewModel.ApplicantLinkedinUrl);
// send the email to the employer
await _emailService.SendEmailAsync(jobApplicationDetails);
return Json(new { Success = "true" });
}
return Json(new { Success = "false" });
}
</code></pre>
<p>This is the <code>JobApplicationViewModel</code>. As you can see the <code>CvFile</code> is uploaded in <code>HttpPostedFileBase</code>. This model has two additional getters, <code>CvByteArray</code> and <code>CvFileName</code>, to get the details of uploaded CV file:</p>
<pre><code>public class JobApplicationViewModel : ContactBaseViewModel
{
private string _applicantLinkedinUrl;
private byte[] _cvBytes = null;
public JobApplicationViewModel()
{
AdBaseId = 0;
}
public JobApplicationViewModel(long adBaseId, string applicantFullName, string applicantEmail)
{
AdBaseId = adBaseId;
ApplicantFullName = applicantFullName;
ApplicantEmail = applicantEmail;
}
public long ApplicantUserId { get; set; }
[Required]
[Display(Name = "Full name")]
[StringLength(GlobalConstants.MaxLengthForFullName, ErrorMessage = "{0} must be between {2} and {1} characters long", MinimumLength = GlobalConstants.MinLengthForFullName)]
public string ApplicantFullName { get; set; } // FullName that was used in prev job application and can be different from user's account FirstName/LastName
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string ApplicantEmail { get; set; } // Email that was used in prev job application, this can be different from user's account email
[Display(Name = "Phone number")]
public string ApplicantPhoneNumber { get; set; }
[Display(Name = "LinkedIn URL")]
[StringLength(GlobalConstants.MaxLengthForUrl)]
[RegularExpressionWithOptions(GlobalConstants.LinkedinValidationRegEx, ErrorMessage = "Not a valid LinkedIn URL", RegexOptions = RegexOptions.IgnoreCase)]
public string ApplicantLinkedinUrl
{
get
{
return ShoplessUrlHelper.PrependHttpsIfMissing(_applicantLinkedinUrl);
}
set
{
_applicantLinkedinUrl = value;
}
}
[Display(Name = "CV")]
[RegularExpressionWithOptions(GlobalConstants.CvFileNameRegEx, ErrorMessage = "Invalid file format, use: doc, docx, pdf, odt or txt", RegexOptions = RegexOptions.IgnoreCase)]
public string UploadedCvFileName { get; set; }
public string ExistingCvFileName { get; set; } // <-- The CV file name from prev job application, it comes from DB (not from user)
/// <summary>
/// Use CvByteArray and CvFileName properties for getting these values
/// </summary>
public HttpPostedFileBase CvFile { get; set; }
public byte[] CvByteArray
{
get
{
if (_cvBytes != null)
{
return _cvBytes;
}
using (Stream inputStream = CvFile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
_cvBytes = memoryStream.ToArray();
}
return _cvBytes;
}
}
public string CvFileName
{
get
{
return Path.GetFileName(CvFile.FileName);
}
}
}
</code></pre>
<p>This is the <code>JobApplicationEmail</code> model... the main thing about this model is that cv (the byte array) is copied into <code>Attachment</code> and <code>cvFileName</code> is copied to <code>AttachmentFileName</code></p>
<pre><code>[Serializable]
public class JobApplicationEmail : EmailBase
{
private static string _inlineHtmlTemplate = "Email's HTML template, this string contains serveral -PlaceHolders-";
private StringBuilder _htmlBuilder;
public JobApplicationEmail(string fromFullName, string fromEmail, string toFirstName, string toEmail, string adTitle, string adLink, string messageHtmlString, byte[] cv = null, string cvFileName = "", string phoneNumber = "", string linkedinUrl = "")
: base()
{
_htmlBuilder = new StringBuilder(_inlineHtmlTemplate);
ToFullName = ToDisplayName = toFirstName;
ToEmail = toEmail;
FromDisplayName = fromFullName;
FromFullName = EmailConfig.MailerFullName;
FromEmail = EmailConfig.MailerEmail;
ReplyToEmail = fromEmail;
ReplyToFullName = fromFullName;
Attachment = cv;
AttachmentFileName = cvFileName;
Subject = $"Job Application from {fromFullName}";
_htmlBuilder.Replace("-applicantFullName-", fromFullName);
_htmlBuilder.Replace("-adTitle-", adTitle);
_htmlBuilder.Replace("-adLink-", adLink);
_htmlBuilder.Replace("-messageHtmlString-", string.IsNullOrWhiteSpace(messageHtmlString) == false ? messageHtmlString : "The applicant has not included any message");
_htmlBuilder.Replace("-fromEmail-", fromEmail);
if (string.IsNullOrEmpty(phoneNumber))
{
_htmlBuilder.Replace("-phoneNumberDisplayValue-", "none");
}
else
{
_htmlBuilder.Replace("-phoneNumberDisplayValue-", "block");
_htmlBuilder.Replace("-phoneNumber-", phoneNumber);
_htmlBuilder.Replace("-phoneNumberNoSpace-", phoneNumber.RemoveAllWhiteSpaces());
}
if (string.IsNullOrEmpty(linkedinUrl))
{
_htmlBuilder.Replace("-linkedinDisplayValue-", "none");
}
else
{
_htmlBuilder.Replace("-linkedinDisplayValue-", "block");
_htmlBuilder.Replace("-linkedinUrl-", linkedinUrl);
_htmlBuilder.Replace("-linkedinProfileDisplayText-", "LinkedIn profile");
}
HtmlContent = _htmlBuilder.ToString();
}
}
</code></pre>
<p>Now, there are 2 actions which need to take place on the CV:</p>
<ol>
<li><p>The CV file should be stored in user's folder (inside an S3 bucket) so that the user can reuse it for his next application)</p>
</li>
<li><p>The CV should be attached to an email and be sent to the employer</p>
</li>
</ol>
<p>I want to make this process as efficient as possible, that's why I am converting the CV to a byte array inside the model and pass this byte array to both of the above methods:</p>
<ol>
<li>Save CV inside S3 bucket... I have not included all the function calls, but this is the final step where CV gets stored inside user's folder inside S3 bucket... this code is called from <code>_jobApplicationService.UpdateUserJobProfile</code>:</li>
</ol>
<pre><code>public string UploadCv(byte[] cvBytes, string cvFileName, long userId)
{
var userCvFolderRelativePath = SecureDocumentsFolderHelper.GetUserCvFolderRelativePath(userId);
var cvfileNameRelativePath = S3PathMapper.CombineHighLevelPath(userCvFolderRelativePath, cvFileName);
// if it's the first time this user is applying for a job, create a folder for him
S3DirectoryInfo di = new S3DirectoryInfo(_cdnClient, _cdnBucketName, cvfileNameRelativePath);
if (!di.Exists)
{
di.Create();
}
else
{
ClearFolder(userCvFolderRelativePath);
}
// copy the CV as the most up to date version
S3FileInfo s3FileInfo = new S3FileInfo(_cdnClient, _cdnBucketName, cvfileNameRelativePath);
if (!s3FileInfo.Exists)
{
using (var s3Stream = s3FileInfo.Create())
{
s3Stream.Write(cvBytes, 0, cvBytes.Length);
}
}
return cvFileName;
}
</code></pre>
<ol start="2">
<li>Here is the second step which is called from <code>_emailService.SendEmailAsync</code>, sends the email to the employer.</li>
</ol>
<pre><code>if (email.Attachment != null && !string.IsNullOrEmpty(email.AttachmentFileName))
{
using (WebClient webClient = new WebClient())
{
var base4File = Convert.ToBase64String(email.Attachment);
sendGridMessage.AddAttachment(email.AttachmentFileName, base4File);
}
}
</code></pre>
<p>As you can <code>email.Attachement</code> is the byte array which is converted to <code>Base64String</code> and is added to the email...</p>
<p>I am not sure if is a more efficient way of dealing with CV file? The CV file is uploaded inside <code>HttpPostedFileBase</code> class and this class has an <code>Stream</code> property... I am not sure if it would be more efficient to just pass the <code>Stream</code> property to the above methods? i.e. directly use the <code>Stream</code> for writing to S3 and email attachment, instead of converting it to byte array?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T22:13:09.810",
"Id": "487599",
"Score": "0",
"body": "Consider `HtmlAgilityPack` NuGet package to build or parse HTML, it's much faster than regular string operations. Also the email template can be `const string` or stored in a file and loaded once."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T07:29:45.733",
"Id": "248351",
"Score": "2",
"Tags": [
"c#",
"file-system",
"email"
],
"Title": "Uploading CV file to an e-commerce website and sending the CV to employer's email"
}
|
248351
|
<p>I'm new to java and I have just finished my very first game - Arkanoid. I would appreciate, if anyone could look at this and tell me some advice and tips how can I optimize my code. Thank you. :)</p>
<p>I have 5 classes - Breaker, BlockBreakerPanel, Ball, Paddle, Block. Look:</p>
<p>This is the main classs:</p>
<pre><code>public class Breaker {
private BlockBreakerPanel panel;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Breaker b = new Breaker();
b.show();
}
private void show() {
JFrame frame = new JFrame("Block Breaker");
frame.setSize(490, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.panel = new BlockBreakerPanel(this);
frame.add(this.panel);
frame.setVisible(true);
}
public BlockBreakerPanel getPanel() {
return this.panel;
}
}
class BlockBreakerPanel extends JPanel implements KeyListener, ActionListener
{
private ArrayList<Blocks> blocks = new ArrayList<>();
private final Paddle player;
private final Ball ball;
private final Breaker game;
private boolean gameOver;
private int score;
private boolean start;
public BlockBreakerPanel(Breaker game) {
setBackground(Color.BLACK);
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 8; i++) {
this.blocks.add(new Blocks(i * 60 + 2, j * 40 + 5, 50, 30));
}
}
this.player = new Paddle(game);
this.ball = new Ball(game);
this.gameOver = false;
this.score = 0;
this.start = false;
Timer t = new Timer(5, this);
t.start();
addKeyListener(this);
setFocusable(true);
this.game = game;
}
public void addPoint() {
this.score++;
}
public void isGameOver() {
this.gameOver = true;
}
public ArrayList<Blocks> getBlocks() {
return this.blocks;
}
public Paddle getPlayer() {
return this.player;
}
public void paint(Graphics g) {
super.paintComponent(g);
this.blocks.forEach((block) -> {
block.paint(g);
});
this.player.paint(g);
this.ball.paint(g);
if (!this.start) {
g.setFont(new Font("Calibri", Font.BOLD, 35));
g.setColor(Color.WHITE);
g.drawString("Pressed enter to start a game", 20, 300);
}
g.setFont(new Font("Calibri", Font.BOLD, 20));
g.setColor(Color.WHITE);
g.drawString(String.valueOf(this.score), 450, 540);
if (this.gameOver) {
g.setFont(new Font("Calibri", Font.BOLD, 80));
g.setColor(Color.WHITE);
g.drawString("Game Over", 60, 300);
} else if (this.blocks.isEmpty()) {
this.gameOver = true;
g.setFont(new Font("Calibri", Font.BOLD, 80));
g.setColor(Color.WHITE);
g.drawString("You won", 80, 300);
}
}
private void update() {
this.ball.move();
repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
this.start = true;
}
this.player.pressed(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void actionPerformed(ActionEvent e) {
if (!this.gameOver && this.start) {
this.update();
}
}
}
class Blocks {
private final int x;
private final int y;
private final int width;
private final int height;
public Blocks(int a, int b, int w, int h) {
this.x = a;
this.y = b;
this.width = w;
this.height = h;
}
public void paint(Graphics g) {
g.setColor(Color.pink);
g.drawRect(this.x, this.y, this.width, this.height);
g.fillRect(this.x, this.y, this.width, this.height);
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
}
public class Paddle {
private int x;
private final int y;
private final int width;
private final int height;
private final int posun;
private final Breaker game;
/**
*
* @param game
*/
public Paddle(Breaker game) {
this.x = 245 - (60/2);
this.y = 540;
this.width = 100;
this.height = 15;
this.posun = 10;
this.game = game;
}
public int getWidth() {
return this.width;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void paint(Graphics g) {
g.setColor(Color.CYAN);
g.drawRect(this.x, this.y, this.width, this.height);
g.fillRect(this.x, this.y, this.width, this.height);
}
void pressed(int keyCode) {
this.collision();
if (keyCode == KeyEvent.VK_RIGHT) {
this.x += this.posun;
} else if (keyCode == KeyEvent.VK_LEFT) {
this.x -= this.posun;
}
}
private void collision() {
if ((this.x + this.width) >= 490) {
this.x = 490 - this.width;
} else if (this.x <= 0) {
this.x = 0;
}
}
}
public class Ball {
private final int DIAMETER = 20;
private int x;
private int y;
private int dx;
private int dy;
private final Breaker game;
/**
*
* @param game
*/
public Ball(Breaker game) {
this.x = 245 - (DIAMETER / 2);
this.y = 500;
this.dx = 2;
this.dy = 2;
this.game = game;
}
void paint(Graphics g) {
g.setColor(Color.PINK);
g.drawOval(this.x, this.y, DIAMETER, DIAMETER);
g.fillOval(this.x, this.y, DIAMETER, DIAMETER);
}
private void checkCollision() {
boolean collision = false;
if (((this.y+DIAMETER) >= this.game.getPanel().getPlayer().getY()) && ((this.x) >= this.game.getPanel().getPlayer().getX()-2) && ((this.x+DIAMETER) <= (this.game.getPanel().getPlayer().getX()+this.game.getPanel().getPlayer().getWidth()+2))) {
collision = true;
} else if ((this.y + DIAMETER) >= 560) {
this.game.getPanel().isGameOver();
return;
}
for (Blocks block : this.game.getPanel().getBlocks()) {
if ((this.y+5 <= (block.getY() + block.getHeight())) && (this.x+5 >= block.getX()) && ((this.x+DIAMETER-5) <= block.getX()+block.getWidth())) {
this.game.getPanel().getBlocks().remove(block);
collision = true;
this.game.getPanel().addPoint();
break;
}
}
if (collision) {
this.dy = - this.dy;
}
}
public void move() {
if (this.x <= 0 || this.x >= (460 + DIAMETER)) {
this.dx = -this.dx;
} else if (this.y <= 0 || this.y >= (540 + DIAMETER)) {
this.dy = -this.dy;
}
this.checkCollision();
this.x += this.dx;
this.y += this.dy;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T22:10:31.513",
"Id": "486485",
"Score": "0",
"body": "Welcome to Code Review! While one user has corrected formatting for the closing braces, refer to [Tips for formatting code using markdown](https://codereview.stackexchange.com/editing-help#code)"
}
] |
[
{
"body": "<p>Nice, one of my favorite games.</p>\n<p>What you got now is all the responsibilities of a program mixed together into same classes merrily violating the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Study the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC</a> model. Then start by separating your game physics into their own set of classes and the graphical representation to another set. Put the key and action listeners into their own classes and create a main class that connects all the components together.</p>\n<p>Move all the magic numbers (such as screen size) into variables so that you can change them easily. Make the object sizes relative to the screen size so that you can scale the game for different screen resolutions. Take into account that not all screens have the same width to height aspect ratio.</p>\n<p>Avoid arbitrary abbreviations like <code>posun</code>. What is a posun?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:31:28.643",
"Id": "248436",
"ParentId": "248354",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T08:05:29.227",
"Id": "248354",
"Score": "8",
"Tags": [
"java",
"beginner",
"object-oriented",
"game"
],
"Title": "My first game - Arkanoid"
}
|
248354
|
<p>The flask endpoint is supposed to take a table name as a parameter, and then return the entire contents of the table as JSON. The table has 200,000 rows and I was wondering if there is any way to improve the response time which is currently about 7 seconds.</p>
<pre><code>@app.route('/tableToJson')
def retrieve_dataset():
'''
Accepts a table name as a parameter and returns the output of the table as JSON
'''
table_name = request.args.get('table', type = str)
if not table_name:
content = {'success':False,'message':'A table name must be provided','status':400}
return make_response(jsonify(content), 400)
db = PGConnect()
result = db.query_table(table_name)
content = {'success':False,'data':result,'status':200}
return make_response(jsonify(content), 200)
</code></pre>
<p>The function querying the table looks like this:</p>
<pre><code>def query_table(self, table_name):
query = f'''SELECT jsonb_agg(to_jsonb(t))
FROM (
SELECT *
from {table_name}
) t'''
self.cursor.execute(query)
return self.cursor.fetchall()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T09:11:19.160",
"Id": "248357",
"Score": "1",
"Tags": [
"python",
"flask"
],
"Title": "Improving response time of flask endpoint"
}
|
248357
|
<p>I'm working on a menu for my poker game console app. I've conceptualized the menu(s) as a class with menu items that have their own position. I would like to get pointers on how I could improve on what I have done as I would like to add a settings menu in the future.</p>
<p>Here's a gif of how the menu works:</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-html lang-html prettyprint-override"><code><blockquote class="imgur-embed-pub" lang="en" data-id="a/q11Is71"><a href="//imgur.com/a/q11Is71"></a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script></code></pre>
</div>
</div>
</p>
<p>Here's my main menu class, just so that you have an example:</p>
<pre><code> public class MainMenu
{
int _currentItemIndex;
int _selectorOffset;
IMenuItem[] _menuItems;
public MainMenu()
{
_currentItemIndex = 0;
_selectorOffset = 15;
_menuItems = new IMenuItem[] { new StartGameItem(48, 11), new TutorialItem(48, 13), new ExitGameItem(48, 15) };
}
public void Open()
{
Console.Clear();
GraphicsHelper.SetConsoleColor();
bool optionSelected = false;
Console.CursorVisible = false;
Console.WriteLine(Resources.MainMenuContent);
Console.CursorTop = _menuItems[_currentItemIndex].Y;
GraphicsHelper.DrawSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
while (!optionSelected)
{
if (Console.KeyAvailable)
{
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.UpArrow:
GraphicsHelper.EraseSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
_currentItemIndex--;
if (_currentItemIndex < 0)
_currentItemIndex = _menuItems.Length - 1;
break;
case ConsoleKey.DownArrow:
GraphicsHelper.EraseSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
_currentItemIndex++;
if (_currentItemIndex > _menuItems.Length - 1)
_currentItemIndex = 0;
break;
case ConsoleKey.Spacebar:
case ConsoleKey.Enter:
optionSelected = true;
break;
}
Console.CursorTop = _menuItems[_currentItemIndex].Y;
GraphicsHelper.DrawSelector(_menuItems[_currentItemIndex].X, _selectorOffset);
}
}
while (_currentItemIndex != -1)
{
_menuItems[_currentItemIndex].Select();
Open();
}
}
}
</code></pre>
<p>IMenu code as requested:</p>
<pre><code> public interface IMenuItem
{
int X { get; set; }
int Y { get; set; }
void Select();
}
</code></pre>
<p>Graphics helper code:</p>
<pre><code> // EraseSelector is just a space in the Write method.
public static void DrawSelector(int x, int dx)
{
Console.CursorLeft = x;
Console.Write(">");
Console.CursorLeft = x + dx;
Console.Write("<");
}
public static void SetConsoleColor()
{
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T12:19:51.213",
"Id": "486426",
"Score": "1",
"body": "A lot of your logic seems to rely on `GraphicsHelper` but you don't have any code for that. Also what is in `IMenuItem`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T02:47:08.310",
"Id": "486496",
"Score": "0",
"body": "There isn't that much code in IMenuItem as I only wanted each item to have a position and a method that executes when the item is selected or launched. The graphics helper usage in the main menu class is just responsible for changing the background and foreground colors, and drawing the \"selectors\" around the menu items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T21:47:00.483",
"Id": "487597",
"Score": "0",
"body": "`if (Console.KeyAvailable)` executes billion of times per second and may cause high CPU load. Add something like `Thread.Sleep(10)` to the loop."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T09:28:33.773",
"Id": "248358",
"Score": "3",
"Tags": [
"c#",
"beginner"
],
"Title": "Poker Game: Building a console menu"
}
|
248358
|
<p>I have currently 600 CSV files (and this number will grow) of 50K lines each i would like to put in one single dataframe.
I did this, it works well and it takes 3 minutes :</p>
<pre><code>colNames = ['COLUMN_A', 'COLUMN_B',...,'COLUMN_Z']
folder = 'PATH_TO_FOLDER'
# Dictionnary of type for each column of the csv which is not string
dictTypes = {'COLUMN_B' : bool,'COLUMN_D' :int, ... ,'COLUMN_Y':float}
try:
# Get all the column names, if it's not in the dict of type, it's a string and we add it to the dict
dictTypes.update({col: str for col in colNames if col not in dictTypes})
except:
print('Problem with the column names.')
# Function allowing to parse the dates from string to date, we put in the read_csv method
cache = {}
def cached_date_parser(s):
if s in cache:
return cache[s]
dt = pd.to_datetime(s, format='%Y-%m-%d', errors="coerce")
cache[s] = dt
return dt
# Concatenate each df in finalData
allFiles = glob.glob(os.path.join(folder, "*.csv"))
finalData = pd.DataFrame()
finalData = pd.concat([pd.read_csv(file, index_col=False, dtype=dictTypes, parse_dates=[6,14],
date_parser=cached_date_parser) for file in allFiles ], ignore_index=True)
</code></pre>
<p>It takes one minute less without the parsing date thing. So i was wondering if i could improve the speed or it was a standard amount of time regarding the number of files. Thanks !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T18:38:01.387",
"Id": "486458",
"Score": "1",
"body": "I don't expect much of a speed boost from this comment, but it's useful to understand nonetheless. Like any reasonable function of this kind, the `pd.concat()` function will take not only sequences (eg, `list` or `tuple`) but any iterable, so you don't need to create a never-used list. Instead, just give `pd.concat()` a generator expression -- a lightweight piece of code that `pd.concat()` will execute on your behalf to populate the data frame. Like this: `pd.concat((pd.read_csv(...) for file in allFiles), ...)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T07:52:43.627",
"Id": "486512",
"Score": "0",
"body": "It's a little bit slower with this but at least i've learned something !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:26:16.877",
"Id": "486515",
"Score": "0",
"body": "Where do you get `colNames` and `folder` from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:48:21.933",
"Id": "486520",
"Score": "0",
"body": "Sorry forgot those, one is a list of names, the other one is the path of the folder in a string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T10:36:43.027",
"Id": "486530",
"Score": "0",
"body": "Did you try it without the cached date parser? Does it actually make it faster (because you have a lot of duplicates)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T10:50:31.273",
"Id": "486531",
"Score": "0",
"body": "Yes as i said at the end of my question, it takes approximately one minute less without the cached date parser"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:02:35.300",
"Id": "486689",
"Score": "0",
"body": "@FMc Generator expressions do not always lead to a speedup. In cases where the function needs to read all input data before creating the output, constructing a list first would not be slower. Sometimes it could even be slightly faster (see [this example](https://stackoverflow.com/questions/11964130/list-comprehension-vs-generator-expressions-weird-timeit-results/11964478#11964478)) because list comprehensions avoid the function call overhead in `list(<gen_exp>)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:15:00.170",
"Id": "486691",
"Score": "1",
"body": "Have u tried replacing `date_parser=cached_date_parser` with `infer_datetime_format=True` in the `read_csv` call? The API document says reading could be faster if the format is correctly inferred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:27:02.720",
"Id": "486695",
"Score": "0",
"body": "@GZ0 True enough, but as noted in the first sentence, my comment was aimed less at speed than general understanding. If memory is the primary constraint, for example, a generator expression can help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:48:33.813",
"Id": "486702",
"Score": "0",
"body": "@FMc In this case, which is probably the same as what I mentioned in my earlier comment, the function needs to consume all the inputs (and create a list) from the generator expression first before generating the output (because the size of the output dataframe needs to be known before memory allocation). Therefore I do not expect memory usage to be lower with generator expressions either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:37:17.157",
"Id": "486779",
"Score": "0",
"body": "@GZ0 Good shot, it reduces by 30 seconds, thanks !"
}
] |
[
{
"body": "<p>Here is my untested feedback on your code. Some remarks:</p>\n<ul>\n<li>Encapsulate the functionality as a named function. I assumed <code>folder_path</code> as the main "variant" your calling code might want to vary, but your use case might "call" for a different first argument.</li>\n<li>Use PEP8 recommandations for variable names.</li>\n<li>Comb/separate the different concerns within the function:\n<ol>\n<li>gather input files</li>\n<li>handle column types</li>\n<li>read CSVs and parse dates</li>\n</ol>\n</li>\n<li>Depending on how much each of those concerns grows in size over time, multiple separate functions could organically grow out of these separate paragraphs, ultimately leading to a whole utility package or class (depending on how much "instance" configuration you would need to preserve, moving the <code>column_names</code> and <code>dtypes</code> parameters to object attributes of a <code>class XyzCsvReader</code>'s <code>__init__</code> method.)</li>\n<li>Concerning the date parsing: probably the bottleneck is not caused by caching or not, but how often you invoke the heavy machinery behind <code>pd.to_datetime</code>. My guess is that only calling it once in the end, but with <code>infer_datetime_format</code> enabled will be much faster than calling it once per row (even with your manual cache).</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import glob\nimport os\nimport pandas as pd\n\ndef read_xyz_csv_folder(\n folder_path,\n column_names=None,\n dtypes=None):\n all_files = glob.glob(os.path.join(folder_path, "*.csv"))\n\n if column_names is None:\n column_names = [\n 'COLUMN_A',\n 'COLUMN_B', # ...\n 'COLUMN_Z']\n if dtypes is None:\n dtypes = {\n 'COLUMN_B': bool,\n 'COLUMN_D': int,\n 'COLUMN_Y': float}\n dtypes.update({col: str for col in column_names \n if col not in dtypes})\n\n result = pd.concat((\n pd.read_csv(file, index_col=False, dtype=dtypes)\n for file in all_files),\n ignore_index=True)\n \n # untested pseudo-code, but idea: call to_datetime only once\n result['date'] = pd.to_datetime(\n result[[6, 14]],\n infer_datetime_format=True,\n errors='coerce')\n \n return result\n \n# use as\nread_xyz_csv_folder('PATH_TO_FOLDER')\n</code></pre>\n<p><em>Edit: as suggested by user FMc in their comment, switch from a list comprehension to a generator expression within <code>pd.concat</code> to not create an unneeded list.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:40:09.923",
"Id": "486780",
"Score": "0",
"body": "thanks, same idea than GZ0 in the comment with the `infer_datetime_format=True` but it's better by a few seconds with your untested idea"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T14:49:25.933",
"Id": "248465",
"ParentId": "248359",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248465",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T09:34:03.823",
"Id": "248359",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"csv",
"pandas"
],
"Title": "Concatenate several CSV files in a single dataframe"
}
|
248359
|
<p>I'm writing login system in Go(Golang) using cookies.I think it's isn't safe enough. Can you provide some suggestions on how to improve the security.<br />
Main file:</p>
<pre><code>package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
"html/template"
"math/rand"
"net/http"
"strings"
"time"
)
var (
runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890")
t *template.Template
)
func init() {
rand.Seed(time.Now().Unix())
t, _ = template.ParseFiles("main.html","signup.html","signin.html")
}
type User struct {
Login, Email string
}
func genToken() string {
s := make([]rune, 15)
for i := range s {
s[i] = runes[rand.Intn(len(runes))]
}
return string(s)
}
func setCookie(w http.ResponseWriter, name, value string,d int) {
cookie := http.Cookie{
Name: name,
Value: value,
}
if d != 0{
expires := time.Now().AddDate(0,0,d)
cookie.Expires = expires
}
http.SetCookie(w, &cookie)
}
func getCookie(r *http.Request, name string) string {
c, err := r.Cookie(name)
if err != nil {
return ""
}
return c.Value
}
func deleteCookie(w http.ResponseWriter,name string){
cookie := http.Cookie{
Name: name,
MaxAge: -1,
}
http.SetCookie(w, &cookie)
}
func signup(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
t.ExecuteTemplate(w,"signup.html",nil)
case "POST":
r.ParseForm()
data := r.Form
var error string
if data["login"][0] == ""{
error = "Login can't be empty"
} else if data["email"][0] == ""{
error = "Email can't be empty"
} else if data["password"][0] == ""{
error = "Password cant't be empty"
} else if len(data["login"][0]) < 4{
error = "Login must be at least 4 characters"
} else if DB.checkLogin(data["login"][0]){
error = "User with such login already exists"
} else if !strings.ContainsRune(data["email"][0],'@'){
error = "Email must contain @"
} else if DB.checkEmail(data["email"][0]) {
error = "User with such email already exists"
} else if len(data["password"][0]) < 8{
error = "Password must be at least 8 characters"
} else if data["password2"][0] != data["password"][0]{
error = "Passwords don't match"
}
if error != ""{
values :=&User{}
values.Login = data["login"][0]
values.Email = data["email"][0]
t, err := template.ParseFiles("signup.html")
if err != nil{
http.Error(w,"Internal server error",500)
}
t.Execute(w,values)
fmt.Fprintln(w,"<hr><span style='color:red;'>" + error + "</span>")
} else {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(data["password"][0]),10)
if err != nil{
http.Error(w,"Internal server error",500)
}
DB.newUser(data["login"][0],data["email"][0],string(hashedPassword))
http.Redirect(w,r,"/login",http.StatusSeeOther)
}
}
}
func signin(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
t.ExecuteTemplate(w,"signin.html",nil)
case "POST":
r.ParseForm()
data := r.Form
var error string
if !DB.checkLogin(data["login"][0]){
error = "User with such login doesn't exists"
} else {
if !DB.checkPassword(data["login"][0],data["password"][0]){
error = "Wrong password"
}
}
if error != ""{
values :=&User{}
values.Login = data["login"][0]
t, err := template.ParseFiles("signin.html")
if err != nil{
http.Error(w,"Internal server error",http.StatusInternalServerError)
}
t.Execute(w,values)
fmt.Fprintln(w,"<hr><span style='color:red;'>" + error + "</span>")
} else {
expiresAfter := 0
if r.FormValue("remember") == "1"{
expiresAfter = 30
}
token := genToken()
setCookie(w,"login",data["login"][0],expiresAfter)
setCookie(w,"session_token",token,expiresAfter)
DB.newSession(data["login"][0],token)
http.Redirect(w,r,"/",http.StatusSeeOther)
}
}
}
func mainPage(w http.ResponseWriter, r *http.Request) {
login := getCookie(r,"login")
token := getCookie(r,"session_token")
if !DB.checkToken(login,token){
http.Redirect(w,r,"/login",http.StatusSeeOther)
}
user := DB.getUser(login)
t.ExecuteTemplate(w,"main.html",user)
}
func logout(w http.ResponseWriter,r *http.Request){
login := getCookie(r,"login")
token := getCookie(r,"session_token")
deleteCookie(w,"login")
deleteCookie(w,"session_token")
DB.deleteSession(login,token)
http.Redirect(w,r,"/login",http.StatusSeeOther)
}
func main() {
http.HandleFunc("/register", signup)
http.HandleFunc("/login", signin)
http.HandleFunc("/", mainPage)
http.HandleFunc("/logout",logout)
http.ListenAndServe(":8080", nil)
}
</code></pre>
<p>Database file:</p>
<pre><code>package main
import (
"database/sql"
"golang.org/x/crypto/bcrypt"
"log"
_ "github.com/go-sql-driver/mysql"
)
var DB = newDB("root:root574@/signin")
type db struct {
DB *sql.DB
}
func newDB(name string) *db {
conn, err := sql.Open("mysql", name)
if err != nil {
log.Fatal(err)
}
if err = conn.Ping(); err != nil {
log.Fatal(err)
}
return &db{DB: conn}
}
func (db db) newUser(login, email, password string) {
db.DB.Exec("INSERT INTO users(login,email,password) VALUES (?,?,?)", login, email, password)
}
func (db db) newSession(login, token string) {
db.DB.Exec("INSERT INTO sessions(login,token) VALUES (?,?)",login,token)
}
func (db db) deleteSession(login, token string) {
db.DB.Exec("DELETE FROM sessions WHERE login = ? and session_token = ?",login,token)
}
func (db db) checkLogin(login string) bool {
var rows, _ = db.DB.Query("SELECT id FROM users WHERE login = ?", login)
if rows.Next() {
return true
}
rows.Close()
return false
}
func (db db) checkEmail(email string) bool {
var rows, _ = db.DB.Query("SELECT id FROM users WHERE email = ?", email)
if rows.Next() {
return true
}
rows.Close()
return false
}
func (db db) checkPassword(login, password string) bool{
var rows, _ = db.DB.Query("SELECT password FROM users WHERE login = ?", login)
var dbpassword string
rows.Next()
rows.Scan(&dbpassword)
rows.Close()
if bcrypt.CompareHashAndPassword([]byte(dbpassword),[]byte(password)) != nil{
return false
}
return true
}
func (db db) checkToken(login, token string) bool {
var rows, _ = db.DB.Query("SELECT token FROM sessions WHERE login = ? and token = ?",login,token)
if rows.Next(){
return true
}
rows.Close()
return false
}
func (db db) getUser(login string) *User {
var rows, _ = db.DB.Query("select email FROM users WHERE login = ?",login)
user := &User{}
rows.Next()
rows.Scan(&user.Email)
rows.Close()
user.Login = login
return user
}
</code></pre>
<p>Database users table:</p>
<pre><code>+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| login | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
</code></pre>
<p>Database sessions table:</p>
<pre><code>+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| login | varchar(255) | YES | | NULL | |
| token | varchar(15) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:34:42.607",
"Id": "486627",
"Score": "0",
"body": "I'm looking through main.go now, a couple quick pointers would be to create a global variable t *template.Template and set it equal to ParseFile/ParseGlob in init() so you don't need to call ParseFile 3 separate times. You could just use t.ExecuteTemplate(). Also, pulling that big if/else clause out into a separate validate function using switch would also improve readability"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T08:37:45.530",
"Id": "486889",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p><strong>Never user PSEUDO random values for secrets!</strong></p>\n<p>This could be exploited by an attacker by guessing the seed value, in this case:</p>\n<pre><code>rand.Seed(time.Now().Unix())\n</code></pre>\n<p>And then generating a possible Cookie value to login.</p>\n<p>Instead use cryptographically secure implementations, in golang you should use <a href=\"https://golang.org/pkg/crypto/rand/\" rel=\"nofollow noreferrer\"><code>crypto/rand</code></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T09:35:17.943",
"Id": "486893",
"Score": "0",
"body": "New [question](https://codereview.stackexchange.com/questions/248540/security-of-cookie-based-authorization-golang)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T13:17:19.120",
"Id": "248500",
"ParentId": "248362",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T11:16:12.997",
"Id": "248362",
"Score": "1",
"Tags": [
"go",
"authentication",
"authorization"
],
"Title": "Cookie authorization Golang"
}
|
248362
|
<p>I am currently implementing this paper on generalised end to end loss: <a href="https://arxiv.org/pdf/1710.10467.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1710.10467.pdf</a></p>
<p>A batch of N speakers and M utterances are fed to the model which outputs an embedding vector of size P for each utterance.</p>
<p>The first step for calculating loss is constructing a cosine similarity matrix between each embedding vector and each centroid (for all speakers). [5]</p>
<p>Additionally when calculating the centroid for a true speaker (embedding speaker == centroid speaker), the embedding itself is removed from the centroid calculation to prevent trivial solutions. [8]</p>
<p>I have attempted to do this using matrices to maximise model training performance, however it's my first time working solely with linear algebra and would really appreciate if somebody could verify that my solution is correct given the requirements above.</p>
<p>The code runs and produces a value, I would like to make sure this value is correct.</p>
<pre><code>@tf.function
def optim_similarity(embedded,w,b, N=64, M=10, P=256):
# Create a view of the batch with an dimension for each "class" (speaker)
embedded_split = tf.reshape(embedded,(N,M,P))
# Calculate false speaker centroids
centers = tf.reduce_mean(embedded_split,axis=1)
# Calculate true speaker centroids
center_except = (tf.reduce_sum(tf.repeat(embedded_split,M,0),axis=1) - embedded) / M-1
# Consruct equal shape matrices for centroids and embedding vectors
center_matrix = tf.reshape(tf.repeat(centers,N*M),(N,N*M,P))
embedded_matrix = tf.broadcast_to(embedded,(N,N*M,P))
# Create a boolean mask for true speaker centroids
mask = tf.cast(tf.reshape(tf.repeat(tf.eye(N),P*M),(N,N*M,P)),bool)
# Construct correct center matrix
center_matrix = tf.where(mask,center_except,center_matrix)
# Calculate loss and scale by weights and bias
return w*tf.keras.losses.cosine_similarity(center_matrix,embedded_matrix) + b
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:06:18.350",
"Id": "486433",
"Score": "0",
"body": "Have you considered how to test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:19:58.650",
"Id": "486435",
"Score": "0",
"body": "I don't have a working example to compare the results with. Unless I attempt it with dummy data manually for a small sample size, which might be the best option."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T12:14:05.150",
"Id": "248363",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"matrix",
"tensorflow"
],
"Title": "Cosine Similarity Matrix Loss Function"
}
|
248363
|
<p>I really liked the close tray program that CD-ROM drivers programs used to include in MS-DOS days.
Since I live in a place where even getting an internship is impossible, I've decided to learn by myself.</p>
<p>I implemented this "Hello World" C# script to do that with a twist.
It will check the optical drive status and if open, it will close it, otherwise it will tell you that a disk is present.</p>
<p>Note, I went through Stack Overflow and couldn't find a way to programmatically find if the tray is open.
Another note, it will not close the tray on most laptops where such mechanism does not exist.</p>
<p>And finally, I used an online code beautifier for indentation.</p>
<pre><code>using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Management;
class Program {
[DllImport("winmm.dll")] protected static extern int mciSendString(string Cmd, StringBuilder StrReturn, int ReturnLength, IntPtr HwndCallback);
static void Main(string[] args) {
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MediaLoaded FROM Win32_CDROMDrive");
ManagementObjectCollection moc = searcher.Get();
var enumerator = moc.GetEnumerator();
if (!enumerator.MoveNext()) throw new Exception("No elements");
ManagementObject obj = (ManagementObject) enumerator.Current;
bool status = (bool) obj["MediaLoaded"];
if (!status) {
MessageBox.Show("The drive is either open or empty", "Optical Drive Status");
mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
}
else MessageBox.Show("The drive is closed and contains an optical media", "Optical Drive Status");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T10:35:49.197",
"Id": "486529",
"Score": "1",
"body": "Have you tested it on a computer with more than one CD drive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T16:59:51.730",
"Id": "486573",
"Score": "0",
"body": "Excellent suggestion, I tried to connect my old IDE DVD to my PC to test it, but sadly Windows 10 is seeing it as a USB device, oddly PCs with a single optical drive are less common let alone two, but your comment is legit and hopefully I (or a kind soul) will be able to see the outcome."
}
] |
[
{
"body": "<p>Note that the Visual Studio C# code editor has an integrated code beautifier. Depending on your setup, it can be executed with different shortcut keys. Call it from the menu for the first time, so that you can see the active shortcut keys (it is Ctrl-E-D for me). Menu: <code>Edit > Advanced > Format Document</code>.</p>\n<p>By using a technique called <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/\" rel=\"noreferrer\">LINQ (Language INtegrated Query)</a>, you can get the management object easier. It uses <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods\" rel=\"noreferrer\">extension methods</a> from the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/\" rel=\"noreferrer\">namespace</a> <code>System.Linq</code>. Therefore, you must include a <code>using System.Linq;</code> at the top of your code. Then you can query with</p>\n<pre><code>ManagementObject managementObject = moc.FirstOrDefault();\nif (managementObject == null) {\n // Handle error (output text or throw exception)\n Console.WriteLine("Could not find a management object!");\n} else {\n ...\n}\n</code></pre>\n<p>This <code>FirstOrDefault</code> extension method calls <code>GetEnumerator</code> and <code>MoveNext</code> internally and returns <code>null</code> if no object is available.</p>\n<p>Do not give it the name <code>obj</code>. Almost everything is an object, so this name is not very informative.</p>\n<p>Exceptions are a complex matter. It raises a lot of questions like "should I throw an exception or output a message to the user?", "should I create my own exception types?", "should I log the exception?" etc., etc. There is no single best answer to these questions. Therefore, I content myself with giving you a link: <a href=\"https://stackify.com/csharp-exception-handling-best-practices/\" rel=\"noreferrer\">C# Exception Handling Best Practices</a>.</p>\n<p>If you intend to reuse this functionality, you could encapsulate it into your own class:</p>\n<pre><code>public enum OperationResult\n{\n Failure,\n NoDriveFound,\n DriveIsOpenOrEmpty,\n MediaIsLoaded\n}\n\npublic class OpticalDriveCloser\n{\n public OperationResult CloseFirst()\n {\n ...\n }\n\n public OperationResult[] CloseAll()\n {\n ...\n }\n}\n</code></pre>\n<p>It returns an operation status as <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum\" rel=\"noreferrer\">enumeration type</a> and lets the calling application decide how to proceed. I.e. it does neither call <code>Console.WriteLine</code> nor throw exceptions and focuses on pure, non-UI logic. A console application will have a different UI-logic than a windows forms application or a web application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:56:12.620",
"Id": "248368",
"ParentId": "248366",
"Score": "11"
}
},
{
"body": "<p>There's quite a bit to unpack here. I'm just going to line-by-line it and then show the final version at the end:</p>\n<p><code>[DllImport("winmm.dll")] protected static extern int mciSendString(string Cmd, StringBuilder StrReturn, int ReturnLength, IntPtr HwndCallback);</code></p>\n<p>Couple things with this one: 1. I don't see why this needs to be <code>protected</code>. Especially in a "main" class like this. 2. The parameter names are not C# idiomatic: capitalization rules and Hungarian notation is not desired.</p>\n<p><code>ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MediaLoaded FROM Win32_CDROMDrive");</code></p>\n<p>This is an <code>IDisposable</code>-implementing class and it should be wrapped in a <code>using</code> construct.</p>\n<p><code>ManagementObjectCollection moc = searcher.Get();</code></p>\n<p>This is <em>also</em> an <code>IDisposable</code>-implementing class and should also be wrapped in a <code>using</code> construct.</p>\n<p><code>var enumerator = moc.GetEnumerator();</code></p>\n<p>Okay, <code>GetEnumerator()</code> and <code>MoveNext()</code> are what as known as <em>mechanism domain</em> (focuses on HOW something gets done) constructs. Most folks never need to be at this level. There are many abstractions that exist that better represent the <em>business domain</em> (focuses on WHAT needs to be done). LINQ is a fantastic way to do this sort of abstraction.</p>\n<p><code>if (!enumerator.MoveNext()) throw new Exception("No elements");</code></p>\n<p>I do not see any benefit to throwing an exception here. What is the consumer supposed to do with it?</p>\n<p><code>bool status = (bool) obj["MediaLoaded"];</code></p>\n<p>Naming (along with off-by-one errors and cache invalidation) is one of the hardest problems in computing. If the variable indicates that media is loaded, name it just like the WMI object.</p>\n<p><code>MessageBox.Show("The drive is either open or empty", "Optical Drive Status");</code></p>\n<p>Don't mix your business logic (determine if the door needs closing, then close) it with UI logic. Same goes for the other <code>MessageBox.Show()</code> call.</p>\n<p><code>if (!status) {</code></p>\n<p>Minor, but when you have an <code>if</code>..<code>else</code> construct, it's easier to read a positive test versus a negative test.</p>\n<p>Ok, let's take these notes and put together a possible enhancement:</p>\n<pre><code> [DllImport("winmm.dll")] private static extern int mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr callback);\n\n static void Main(string[] args) {\n if (CloseMedia() {\n MessageBox.Show("The drive is closed and contains an optical media", "Optical Drive Status");\n }\n else {\n MessageBox.Show("The drive is either open or empty", "Optical Drive Status");\n }\n }\n\n static bool CloseMedia()\n {\n using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MediaLoaded FROM Win32_CDROMDrive"))\n using (ManagementObjectCollection moc = searcher.Get())\n {\n var managementObjects = moc.Cast<ManagementObject>();\n\n if (managementObjects.Any())\n {\n ManagementObject obj = (ManagementObject)managementObjects.First();\n bool mediaLoaded = (bool) obj["MediaLoaded"];\n\n if (mediaLoaded) {\n return false;\n }\n else {\n mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);\n return true;\n }\n }\n }\n\n return false;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T03:00:09.093",
"Id": "486497",
"Score": "7",
"body": "I mostly disagree with your first point. When using a native function I prefer to keep the import as close to the win32 original, with all its grossness in casing and Hungarian notation as possible, to make it easier for maintainers to find documentation if needed. (Because the types are inevitably mutated from their C equivalents, I want the names the same.) I'll often add an idiomatic C# wrapper function if I'm calling it from multiple places. For single uses I'm ambivalent on if a clean looking wrapper function is worth the mental price in adding an indirections worth of complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T09:33:00.483",
"Id": "487503",
"Score": "0",
"body": "Great answer, especially the walkthrough, but a note, if the drive is open it will close and gives me \"The Drive is closed and contains an optical media\" even if it is empty."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:18:33.853",
"Id": "248369",
"ParentId": "248366",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248368",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:05:50.357",
"Id": "248366",
"Score": "10",
"Tags": [
"c#",
"beginner"
],
"Title": "Programmatically close optical drive tray"
}
|
248366
|
<p>This small piece of code shows the value of different fields of an array.
I'm looking for a way to improve this nested ternary function. An <code>if statement</code> solution would be obvious, so I'm wondering if there is something more elegant to solve it.</p>
<pre><code><button type="button" onclick="myFunction()">Check</button>
<p id="demo"></p>
<script>
function getArray(value){
var showValue = (value.value1 > 0) ? value.value1 :
(value.value2 > 0) ? value.value2 :
(value.value3 > 0) ? value.value3 : 0;
document.getElementById("demo").innerHTML += value.system + ": "+ showValue + " ";
}
function myFunction() {
var array = [
{system:"Abba", value1:0, value2:1, value3:0},
{system:"Mars", value1:0, value2:4, value3:0},
{system:"Nexus", value1:0, value2:0, value3:6},
];
array.map(getArray);
}
</script>
</code></pre>
<p>Output</p>
<pre><code>Abba: 1 Mars: 4 Nexus: 6
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p><strong>I'm looking for a way to improve this nested ternary function</strong></p>\n</blockquote>\n<p>They keys to check could be iterated over - e.g.</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>function getArray(value) {\n var showValue = 0;\n for (let key of ['value1', 'value2', 'value3']) {\n if (value[key] > 0) {\n showValue = value[key];\n break;\n }\n }\n\n document.getElementById(\"demo\").innerHTML += value.system + \": \" + showValue + \" \";\n}\n\nfunction myFunction() {\n var array = [\n {system:\"Abba\", value1:0, value2:1, value3:0},\n {system:\"Mars\", value1:0, value2:4, value3:0},\n {system:\"Nexus\", value1:0, value2:0, value3:6},\n {system:\"Zeroes\", value1:0, value2:0, value3:0}\n ];\n\n array.forEach(getArray);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button type=\"button\" onclick=\"myFunction()\">Check</button>\n<p id=\"demo\"></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>And this could be simplified using the array method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>find()</code></a> combined with logical OR - i.e. <code>||</code> for a fall-back value using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR#Short-circuit_evaluation\" rel=\"nofollow noreferrer\">Short-circuit evaluation</a> for the case when no values are greater than zero:</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>function getArray(value){\n //find the key that has a value greater than zero\n const key = ['value1', 'value2', 'value3'].find(key => value[key] > 0); \n //return the value that is greater than zero, or else zero in case no value is greater than zero\n const showValue = value[key] || 0;\n document.getElementById(\"demo\").innerHTML += value.system + \": \"+ showValue + \" \";\n}\n\nfunction myFunction() {\n var array = [\n {system:\"Abba\", value1:0, value2:1, value3:0},\n {system:\"Mars\", value1:0, value2:4, value3:0},\n {system:\"Nexus\", value1:0, value2:0, value3:6},\n {system:\"Zeroes\", value1:0, value2:0, value3:0}\n ];\n \n array.forEach(getArray);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button type=\"button\" onclick=\"myFunction()\">Check</button>\n<p id=\"demo\"></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Other review points</h2>\n<h3>Improper use of <code>map</code> method</h3>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map()</code></a> method "<em>creates a new array populated with the results of calling a provided function on every element in the calling array</em>"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">1</a></sup>. For this code <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>forEach()</code></a> can be used (as it is in the two snippets above) since the return value of each iteration is not used after the callback is executed. <code>.map()</code> could be used to return a string for each object and then update the DOM element only once, which would be better for multiple reasons:</p>\n<ul>\n<li>fewer DOM lookups - remember those aren't cheap</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>Array.join()</code></a> can be used to separate each string with a space, without adding an excess space at the end of the output</li>\n<li>the function would only have one responsibility - in-line with the Single Responsibility principle</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getArray(value){\n const key = ['value1', 'value2', 'value3'].find(key => value[key] > 0);\n const showValue = value[key] || 0;\n return value.system + \": \"+ showValue;\n}\n\nfunction myFunction() {\n var array = [\n {system:\"Abba\", value1:0, value2:1, value3:0},\n {system:\"Mars\", value1:0, value2:4, value3:0},\n {system:\"Nexus\", value1:0, value2:0, value3:6},\n {system:\"Zeroes\", value1:0, value2:0, value3:0}\n ];\n \n document.getElementById(\"demo\").innerHTML = array.map(getArray).join(\" \");\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button type=\"button\" onclick=\"myFunction()\">Check</button>\n<p id=\"demo\"></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Keep HTML and JavaScript separate</h3>\n<p>The HTML has an <code>onclick</code> attribute:</p>\n<blockquote>\n<pre><code><button type="button" onclick="myFunction()">Check</button>\n</code></pre>\n</blockquote>\n<p>Instead of using that attribute, the event handling can be setup in Javascript - e.g. using <code>document.addEventListener()</code>:</p>\n<pre><code>document.getElementById('checkBtn').addEventListener('click', myFunction);\n</code></pre>\n<p>this would require an <em>id</em> attribute be added to the element - e.g.</p>\n<pre><code><button type="button" id="checkBtn">Check</button>\n</code></pre>\n<p>though other ways to detect it are possible (e.g. class name, elements of <code>document.forms</code>, etc. With this separation the JavaScript (logic) can be modified without ever needing to alter the HTML (markup) - especially helpful in larger projects where one person might update HTML and another the JS.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T16:30:59.940",
"Id": "248374",
"ParentId": "248371",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248374",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:44:55.933",
"Id": "248371",
"Score": "3",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Showing values from different fields in an array with ternary"
}
|
248371
|
<p>I want to get my code cleaner and more efficient. This code gets variables form a PHP file and filters it to show the selected user name, all available usergroups on a list box and the groups he is currently into another.</p>
<p>Currently it's working great but it has a lot of delay between the modal shows up and the groups being shown.</p>
<h3>JS:</h3>
<pre><code> function saveUserGroup(id){
$('#useridgr').attr('placeholder','').val('');
$("#usernamegr").attr('placeholder', 'Nome').val('');
$('#list_box').html(''); $('#list_box_ini').html('');
$.ajax({
type: 'GET',
url: 'users/' + id + '/users' + '/id',
data: {'_token': $("input[name='_token']").val()},
success: function(data){
$('#useridgr').attr('placeholder',data.id).val(data.id);
$("#usernamegr").attr('placeholder',data.name).val(data.name);
loadgroupsdata(data.id, 0);
} }); }
var loadgroupsdata = (uid, type) => {
$.ajax({
type: 'GET',
url: 'usergrupo/' + uid + '/' + type,
data: {'_token': $("input[name='_token']").val()},
success: function(data){
if (type == 0) listbox = '#list_box';
else listbox = '#list_box_ini';
loadgroups(uid, listbox, type, data);
}
}) }
function loadgroups(uid, location, type, data){
$.each(data,function(i,v){
$(location).append("<option value='"+v.idgrupo+"'>"+v.nome+"</option>"); })
if(type == 0) loadgroupsdata(uid, 1);
}
function sendData(type){
uid = document.getElementById("useridgr").value;
if(type == 1) listname = 'list_box_ini'; else listname = 'list_box';
var e = document.getElementById(listname);
var value = e.options[e.selectedIndex].value;
$.ajax({
type: 'GET',
url: 'savegroup/' + uid + '/' + type + '/' + value,
data: {'_token': $("input[name='_token']").val()},
success: function(data){
saveUserGroup(uid);
}
})
}
</code></pre>
<h3>PHP:</h3>
<pre><code>public function getData($uid, $tablename, $index)
{
$data = \DB::table($tablename)->where($index, $uid)->first();
return response()->json($data, 200);
}
public function getGroups($id, $type)
{
if ($type == 0){
$data = \DB::table('grupoutilizador')
-> join ('users', function ($join) use ($id){
$join->on('users.id', '=', 'grupoutilizador.iduser')
->where('users.id', "=", $id );
}) -> join ('grupo', 'grupo.idgrupo', "=", 'grupoutilizador.idgrupo') ->
select('users.id', 'users.name', 'grupo.idgrupo', 'grupo.nome')
-> get();
} else {
include 'config.php';
$usergroups = mysqli_query($conn2, 'SELECT grupo.idgrupo FROM grupo, grupoutilizador WHERE grupoutilizador.idgrupo = grupo.idgrupo AND grupoutilizador.iduser =' .$id);
$i = 0;
if ($usergroups->num_rows != 0){
foreach ($usergroups as $usergroup) {
$ids[$i] = $usergroup;
$i++;
}
} else {
$ids[$i] = 0-1;
}
$data = \DB::table('grupo')
->whereNotIn('grupo.idgrupo', $ids)
-> get();
}
return response()->json($data, 200);
}
public function saveGroups($uid, $type, $value){
if ($type == 1){
DB::table('grupoutilizador')->insert([
'iduser' => $uid,
'idgrupo' => $value,
]);
} else {
$result = DB::table('grupoutilizador') -> where([
['iduser', '=', $uid],
['idgrupo', '=', $value],
]) -> delete();
echo $result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T23:46:44.470",
"Id": "486488",
"Score": "1",
"body": "The title of your question should not express your concern for the script, it should uniquely describe what your code does. If your code does not reflect your understanding of basic code spacing/tabbing, then please polish up your code so that it represents your best attempt -- this way reviewers won't waste their time telling you what you already know (like each line of code should be on a separate line; and tabbing should be consistent)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T14:09:13.767",
"Id": "486676",
"Score": "0",
"body": "Yikes , why are mixing `mysqli_query()` into your model?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T12:10:36.547",
"Id": "486802",
"Score": "0",
"body": "I would recommend you use promises rather than endless nested callbacks. axios is an alternative to jquery.ajax that uses promises out of the box"
}
] |
[
{
"body": "<p>Have you tested the server response time independently of your frontend code? The page being slow might not be because of your code being inefficient, if the server or database takes a long time then there's nothing you can do to fix that on the frontend side.</p>\n<p>That being said, first thing you should do with this code is to look up some standards for PHP and JS and follow those.</p>\n<p>Get a code editor, for example PHPStorm where you can autoformat the code (indent lines among other things) and remove extra empty lines, so that your code becomes readable.</p>\n<p>Also, avoid things like this</p>\n<pre><code>if(type == 1) listname = 'list_box_ini'; else listname = 'list_box';\n</code></pre>\n<p>Always use curly braces and proper line breaks and indentation</p>\n<pre><code>if (type == 1) {\n listname = 'list_box_ini';\n} else {\n\n}\n</code></pre>\n<p>I suggest you do such basic fixes to your code and then post it again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T08:52:04.503",
"Id": "248444",
"ParentId": "248372",
"Score": "0"
}
},
{
"body": "<p>The fact that you are making three separate trips to the server stands out as an obvious refinement opportunity.</p>\n<p>We don't know exactly where your performance bottleneck is, but you can be sure that best practice is to reduce your total trips to ...well, anywhere.</p>\n<p>Think about it like this:</p>\n<blockquote>\n<p>Your mother tells you to go to the shop and get a dozen eggs.</p>\n<p>You get on your bicycle and make 12 trips to the shop and deliver one egg to your mother per trip.</p>\n<p>Your sister shakes her head disapprovingly.</p>\n<p>Your mother tells the neighbors that she loves you because you are "special".</p>\n</blockquote>\n<p>If you know that the full flow of this task is to write data to the db ...then get some data from one table ...then get some data from another table, then the sensible thing is to dictate this flow entirely on the server side then only return to the client-side when everything is finished.</p>\n<p>Effectively, I recommend using a single ajax request (with POST instead of GET because you are writing data to your database).</p>\n<p>The dedicated server-side receiving script should execute the database writing query, then immediately execute the database fetching queries, then generate a single json string which contains all of the necessary user and usergroup data to satisfy your client-side processes.</p>\n<p>If the bottleneck is isolated to the database interactions, then we don't have enough information to assist with optimizing the schema.</p>\n<hr />\n<p>General advice:</p>\n<ul>\n<li><p>Don't use <code>mysqli_query()</code> when you have a project that provides querying helper methods. You whole application should use consistent techniques.</p>\n</li>\n<li><p>Only use concatenation when necessary. <code>'/users' + '/id'</code> should be <code>'/users/id'</code></p>\n</li>\n<li><p>When sending data to the server to fetch/read data from the db, use <code>$_GET</code>. When sending to write/insert/update/delete data, use <code>$_POST</code>. There are exceptions, but this is the rule.</p>\n</li>\n<li><p>Use consistent spacing and tabbing in your code so that it is easier to maintain.</p>\n</li>\n<li><p>Don't use old school comma-join syntax -- use JOINs.</p>\n</li>\n<li><p>This is weird:</p>\n<pre><code>$i = 0;\nif ($usergroups->num_rows != 0){\n foreach ($usergroups as $usergroup) {\n $ids[$i] = $usergroup;\n $i++;\n }\n} else {\n $ids[$i] = 0-1;\n\n}\n</code></pre>\n<p>Why declare a counter? Why subtract 1 from 0? You should probably trash most this section of code, and maybe entertain something closer to...</p>\n<pre><code>foreach ($usergroups as $usergroup) {\n $ids[] = $usergroup;\n}\n\n$data = \\DB::table('grupo')\n ->whereNotIn('grupo.idgrupo', $ids ?? -1)\n ->get();\n</code></pre>\n</li>\n<li><p>Never omit curly braces in an attempt to reduce the size of your code. If you have a simple condition and like ternary expressions, use those instead.</p>\n</li>\n<li><p>Try to avoid declaring single-use variables.</p>\n</li>\n<li><p>If <code>type</code> dictates <code>location</code>, then don't send both parameters to the next function scope. Generate <code>location</code> conditionally when you get there.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T10:14:12.280",
"Id": "248496",
"ParentId": "248372",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248496",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:58:42.877",
"Id": "248372",
"Score": "1",
"Tags": [
"javascript",
"php",
"ajax",
"laravel"
],
"Title": "Displaying filtered user data using Ajax and PHP"
}
|
248372
|
<p>I'm a new Rust programmer, primarily coming from Ruby experience.
I started working on a small project to scrape vehicle specifications from <a href="https://carfolio.com" rel="nofollow noreferrer">https://carfolio.com</a></p>
<p>I chose to write it in Rust and actually got the code working, but I had some questions regarding async, performance, as well as code organization and abstraction.</p>
<p>The general gist of my code is that it scrapes the <a href="https://carfolio.com/specifications" rel="nofollow noreferrer">Carfolio specifications</a> page for a list of automobile makes. It'll grab the name of the make, the country of the make, as well as the link to the make's page.</p>
<p>The make's page will have each of the make's models listed there. The next thing my code does is iterate thru the list of makes, and grab all the data from the makes' page for the models. This currently just includes the name of the model, the year, and the link to the models' details pages.</p>
<p>I haven't done the part of the details for the models, because I wanted to get some feedback on performance here, since this essentially is a 3rd level of a nested loop, and I want to take advantage of the <code>async</code> web requests I'm making to make it faster.</p>
<p>Here are the few files that comprise my project:</p>
<p><code>src/main.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>extern crate pretty_env_logger;
#[macro_use] extern crate log;
use scraper::html::Html;
mod carfolio;
fn main() {
pretty_env_logger::init();
carfolio::scrape();
}
async fn fetch_page(url: &str) -> Result<Html, reqwest::Error> {
info!("Scraping HTML from {}", url);
let resp = reqwest::get(url).await?;
let body = resp.text().await?;
Ok(Html::parse_document(&body))
}
</code></pre>
<p><code>src/carfolio/mod.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>mod make;
mod model;
pub(crate) fn scrape() {
make::makes().unwrap().iter()
.map(|make| model::models(make.to_owned()).unwrap())
.collect::<Vec<_>>();
}
</code></pre>
<p><code>src/carfolio/make.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use scraper::html::Html;
use scraper::Selector;
use scraper::element_ref::ElementRef;
const BASE_URL: &str = "https://carfolio.com/specifications";
#[derive(Clone)]
pub struct Make {
pub name: String,
pub country: String,
pub url: String
}
fn divs(html: &Html) -> Vec<ElementRef<'_>> {
let selector = Selector::parse("div.grid div[class^=\"m\"]").unwrap();
html.select(&selector).collect()
}
fn extract_link(div: ElementRef) -> ElementRef {
let selector = Selector::parse("a.man").unwrap();
div.select(&selector).next().unwrap()
}
fn extract_url(div: ElementRef) -> String {
let link = extract_link(div);
let path = link.value().attr("href").unwrap().to_string();
format!("{}/{}", BASE_URL, path)
}
fn extract_name(div: ElementRef) -> String {
let link = extract_link(div);
link.inner_html()
}
fn extract_country(div: ElementRef) -> String {
let selector = Selector::parse("div.footer").unwrap();
div.select(&selector).next().unwrap().inner_html()
}
#[tokio::main]
pub async fn makes() -> Result<Vec<Make>, reqwest::Error> {
info!("Requesting Makes data");
let html = match crate::fetch_page(BASE_URL).await {
Ok(html) => html,
Err(e) => return Err(e),
};
let makes = divs(&html).iter().map(|div| {
let url = extract_url(*div);
let name = extract_name(*div);
let country = extract_country(*div);
debug!("Make: {} ({}) - {}", name, country, url);
Make { name: name, country: country, url: url }
}).collect::<Vec<Make>>();
Ok(makes)
}
</code></pre>
<p><code>src/carfolio/model.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use scraper::html::Html;
use scraper::Selector;
use scraper::element_ref::ElementRef;
const BASE_URL: &str = "https://carfolio.com";
use super::make::Make;
pub struct Model {
pub make: Make,
pub name: String,
pub year: Option<u16>,
pub url: String
}
fn divs(html: &Html) -> Vec<ElementRef<'_>> {
let selector = Selector::parse("div.grid div.grid-card").unwrap();
html.select(&selector).collect()
}
fn extract_data(div: ElementRef) -> ElementRef {
let selector = Selector::parse("div.card-head a span.automobile").unwrap();
div.select(&selector).next().unwrap()
}
fn extract_url(div: ElementRef) -> String {
let selector = Selector::parse("div.card-head a").unwrap();
let link = div.select(&selector).next().unwrap();
let path = link.value().attr("href").unwrap().to_string();
format!("{}/{}", BASE_URL, path)
}
fn extract_name(div: ElementRef) -> String {
let selector = Selector::parse("span.model.name").unwrap();
let data = extract_data(div);
match data.select(&selector).next() {
Some(inner) => inner.inner_html(),
None => "".to_string()
}
}
fn extract_year(div: ElementRef) -> Option<u16> {
let selector = Selector::parse("span.Year").unwrap();
let alt_selector = Selector::parse("span.model-year").unwrap();
let data = extract_data(div);
match data.select(&selector).next() {
Some(inner) => Some(inner.inner_html().parse::<u16>().unwrap()),
None => match data.select(&alt_selector).next() {
Some(inner) => Some(inner.inner_html().parse::<u16>().unwrap()),
None => {
error!("Could not find year info in {:?}", data.inner_html());
None
}
}
}
}
#[tokio::main]
pub async fn models(make: Make) -> Result<Vec<Model>, reqwest::Error> {
info!("Requesting Models data for {}", make.name);
let html = match crate::fetch_page(&make.url).await {
Ok(html) => html,
Err(e) => return Err(e),
};
let models = divs(&html).iter().map(|div| {
let year = extract_year(*div);
let name = extract_name(*div);
let url = extract_url(*div);
debug!("Model: {:?} {} {} - {}", year, make.name, name, url);
Model {
make: make.clone(),
name: name,
year: year,
url: url
}
}).collect::<Vec<Model>>();
Ok(models)
}
</code></pre>
<p>The biggest questions I have are:</p>
<ol>
<li>The <a href="https://github.com/seanmonstar/reqwest" rel="nofollow noreferrer">reqwest</a> library states that if I'm making multiple connections, I should instantiate a <code>reqwest::Client</code> and re-use that. How might I do that in Rust? Right now my <code>fetch_page</code> function doesn't do that, and I'm not even sure abstracting that as a function is worth anything, besides less LoC.</li>
<li>How might I take advantage of the <code>async</code>-ness <code>fetch_page</code> function? Currently, when I run the code, it's pretty clear that everything is running sequentially, and I know that with <code>async</code> I can probably get better performance than just running it like that.</li>
<li>Wondering about how I structured my code, whether having the <code>carfolio</code>, <code>carfolio::make</code> and <code>carfolio::model</code> modules are even worth it? To me it looks cleaner, but I'm not sure what the general organization of experience Rust developers would be.</li>
<li>Abstracting out all the <code>extract_*</code> functions... similar to question 3, looks cleaner to me, but not sure how experienced developers would do it.</li>
</ol>
<p>Any other general feedback is greatly welcome as well!
Thanks in advance for your time!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T17:03:50.467",
"Id": "248375",
"Score": "3",
"Tags": [
"performance",
"web-scraping",
"rust"
],
"Title": "Performance and abstraction questions re: scraper for carfolio.com"
}
|
248375
|
<p>Playing around with pointers in <code>C++</code>, implemented an adjacency list graph.</p>
<p>Am I going too far/extreme trying to place data onto the heap?</p>
<h1>graph.h</h1>
<pre class="lang-cpp prettyprint-override"><code>#include <memory>
#include <unordered_map>
#include <forward_list>
#include <utility>
template <typename TKey, typename TWeight>
class Graph{
struct Adjacent {
TKey key;
TWeight weight;
Adjacent(const TKey key, const TWeight weight): key(key), weight(weight) {};
};
struct Vertex {
TKey value;
std::unique_ptr<std::forward_list<Adjacent>> adjVertexList;
explicit Vertex(const TKey value){
this->value = value;
adjVertexList = std::make_unique<std::forward_list<Adjacent>>();
}
};
private:
// Since keys can be non-numeric,
// use a hashmap to index into individual adj lists
std::unordered_map<TKey, std::unique_ptr<Vertex>> vertices;
public:
void addVertex(TKey value);
// Everything other than addDirectedEdge is just for a nicer API
void addDirectedEdge(TKey src, TKey dst, TWeight weight);
void addUndirectedEdge(TKey src, TKey dst, TWeight weight);
void addDirectedEdge(TKey src, TKey dst);
void addUndirectedEdge(TKey src, TKey dst);
};
</code></pre>
<h1>graph.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>#include <stdexcept>
#include "graph.h"
template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addVertex(TKey value) {
vertices.insert(std::make_pair(value, std::make_unique<Vertex>(value)));
}
template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addDirectedEdge(TKey src, TKey dst, TWeight weight) {
auto srcPtr = vertices.find(src);
if(srcPtr == vertices.end())
throw std::invalid_argument("Cannot find source");
else if(vertices.find(dst) == vertices.end())
throw std::invalid_argument("Cannot find destination");
Vertex* vertex = srcPtr->second.get();
vertex->adjVertexList->push_front(Adjacent(dst, weight));
}
template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addUndirectedEdge(TKey src, TKey dst, TWeight weight) {
addDirectedEdge(src, dst, weight);
addDirectedEdge(dst, src, weight);
}
template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addDirectedEdge(TKey src, TKey dst) {
addDirectedEdge(src, dst, 0);
}
template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addUndirectedEdge(TKey src, TKey dst){
addUndirectedEdge(src, dst, 0);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>Am I going too far/extreme trying to place data onto the heap?</p>\n</blockquote>\n<p>Yes. Containers like <code>std::unordered_map</code> and <code>std::forward_list</code> already store contents on the heap. If you declare a <code>std::unordered_map</code> on the stack, only a little bit of administrative data goes on the stack. But the same happens with <code>std::unique_ptr</code>. So in your code, the use of <code>std::unique_ptr</code> is superfluous and only increases indirection, which might be bad for performance. So just write:</p>\n<pre><code>template <typename TKey, typename TWeight>\nclass Graph {\n ...\n struct Vertex {\n ...\n std::forward_list<Adjacent> adjVertexList;\n ...\n };\n ...\n std::unordered_map<TKey, Vertex> vertices;\n ...\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T19:32:35.390",
"Id": "248380",
"ParentId": "248376",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "248380",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T17:19:08.053",
"Id": "248376",
"Score": "4",
"Tags": [
"c++",
"linked-list",
"graph",
"pointers"
],
"Title": "Extreme use of pointers in adjacency list graph construction?"
}
|
248376
|
<p>I come from a C++ background, and I recently got into C, and one of the first things I made was a double linked list since I though it would be good practice for me with pointers and memory allocation. It isn't too complex though, it's just with some basic functions.</p>
<p>Here's the overview of my list:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int val;
struct Node* prev;
struct Node* next;
} Node;
typedef struct
{
int length;
Node* head;
Node* tail;
} double_list;
double_list* create_list(); // constructor
void destroy_list(double_list* const list); // destructor
void insert_pos(double_list* const list, int index, int val);
void insert_front(double_list* const list, int val);
void insert_back(double_list* const list, int val);
void remove_pos(double_list* const list, int index);
void remove_front(double_list* const list);
void remove_back(double_list* const list);
void sort_list(double_list* const list); // selection sort
void reverse_list(double_list* const list);
</code></pre>
<p>It just has basic insertion and removal, as well as a constructor, destructor, sort, and reverse functions.</p>
<p>Here's the actual definition for the functions:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int val;
struct Node* prev;
struct Node* next;
} Node;
typedef struct
{
int length;
Node* head;
Node* tail;
} double_list;
double_list* create_list()
{
double_list* list = malloc(sizeof(*list));
list->length = 0;
list->head = NULL;
list->tail = NULL;
return list;
}
void destroy_list(double_list* const list)
{
list->length = 0;
Node* node_ptr = list->head;
while (node_ptr != NULL)
{
node_ptr = node_ptr->next;
free(list->head);
list->head = node_ptr;
}
}
void insert_pos(double_list* const list, int index, int val)
{
if (index < 0 || index > list->length)
return;
list->length += 1;
if (list->head == NULL)
{
list->head = malloc(sizeof(*(list->head)));
list->head->val = val;
list->head->prev = NULL;
list->head->next = NULL;
list->tail = list->head;
return;
}
if (index == 0)
{
Node* new_node = malloc(sizeof(*new_node));
new_node->val = val;
new_node->prev = NULL;
new_node->next = list->head;
list->head->prev = new_node;
list->head = new_node;
return;
}
if (index == list->length - 1)
{
Node* new_node = malloc(sizeof(*new_node));
new_node->val = val;
new_node->prev = list->tail;
new_node->next = NULL;
list->tail->next = new_node;
list->tail = new_node;
return;
}
Node* node_ptr = list->head;
for (int a = 0; a < index; ++a)
node_ptr = node_ptr->next;
Node* new_node = malloc(sizeof(*new_node));
new_node->val = val;
new_node->next = node_ptr;
new_node->prev = node_ptr->prev;
node_ptr->prev->next = new_node;
node_ptr->prev = new_node;
}
void insert_front(double_list* const list, int val)
{
insert_pos(list, 0, val);
}
void insert_back(double_list* const list, int val)
{
insert_pos(list, list->length, val);
}
void remove_pos(double_list* const list, int index)
{
if (index < 0 || index >= list->length)
return;
list->length -= 1;
if (index == 0)
{
Node* node_ptr = list->head;
list->head = list->head->next;
list->head->prev = NULL;
free(node_ptr);
return;
}
if (index == list->length)
{
Node* node_ptr = list->tail;
list->tail = list->tail->prev;
list->tail->next = NULL;
free(node_ptr);
return;
}
Node* node_ptr = list->head;
for (int a = 0; a < index; ++a)
node_ptr = node_ptr->next;
node_ptr->prev->next = node_ptr->next;
node_ptr->next->prev = node_ptr->prev;
free(node_ptr);
}
void remove_front(double_list* const list)
{
remove_pos(list, 0);
}
void remove_back(double_list* const list)
{
remove_pos(list, list->length - 1);
}
void sort_list(double_list* const list)
{
Node* index_ptr = list->head;
Node* small_ptr = list->head;
Node* node_ptr = list->head;
while (index_ptr->next != NULL)
{
while (node_ptr != NULL)
{
if (node_ptr->val < small_ptr->val)
small_ptr = node_ptr;
node_ptr = node_ptr->next;
}
int hold = index_ptr->val;
index_ptr->val = small_ptr->val;
small_ptr->val = hold;
index_ptr = index_ptr->next;
node_ptr = index_ptr;
small_ptr = index_ptr;
}
}
void reverse_list(double_list* const list)
{
Node* node_ptr = list->head;
list->head = list->tail;
list->tail = node_ptr;
while (node_ptr != NULL)
{
Node* temp = node_ptr->prev;
node_ptr->prev = node_ptr->next;
node_ptr->next = temp;
node_ptr = node_ptr->prev;
}
}
</code></pre>
<p>And here's a small sample of how my list would be used:</p>
<pre class="lang-c prettyprint-override"><code>double_list* list = create_list();
insert_back(list, 1);
insert_back(list, 2);
insert_back(list, 3);
sort_list(list);
destroy_list(list);
</code></pre>
<p>My main area's of concern are:</p>
<ol>
<li><p>Are the constructor and destructor doing their job properly? Is the destructor leaking memory, and is there a better way to do the constructor?</p>
</li>
<li><p>Are the <code>remove()</code> and <code>insert()</code> functions efficient? Is there a better way to do that, like making a more generic <code>remove()</code> function so I don't have to have special test cases for index of 0 and stuff like that?</p>
</li>
<li><p>Are the <code>sort()</code> and <code>reverse()</code> functions okay at least? I know selection sort isn't the best algorithm to use. And is the <code>reverse()</code> function implemented correctly? Is there a better way to reverse the list?</p>
</li>
</ol>
<p>Sorry I'm being a little too broad with my question. I can edit it to focus on a more specific question if needed.</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:14:34.710",
"Id": "487450",
"Score": "0",
"body": "_Side note:_ After just a quick glance ... In `insert_pos` [and `delete_pos`] at the point where you actually traverse the list using the `next` pointer ... Since your list has a `length`, you could check for `index > (list->length / 2)` and if that's true, traverse [backwards] from `list->tail` using the `prev` link"
}
] |
[
{
"body": "<p>Good question, well formatted, well worked out and implementation seems to work!</p>\n<p>First to answer your questions:</p>\n<h1>Q1:</h1>\n<h2>Constructor:</h2>\n<ul>\n<li>Check return value of malloc, it could be <code>NULL</code> if it failed (out of memory)</li>\n</ul>\n<h2>Destructor:</h2>\n<ul>\n<li>just pass <code>double_list *list</code>, the <code>const</code> there doesn't make sense (not sure why you put it there).</li>\n<li>you leak memory, because you don't free <code>list</code>, which you have allocated in the constructor</li>\n</ul>\n<p>Edit 1:</p>\n<p>If you pass in <code>double_list *const list</code> that means the value of list (the pointer) cannot be changed, which doesn't make sense here because the user of this interface holds on to the pointer.</p>\n<p>If the <code>const</code> is before the type <code>const double_list *list</code> this means the content of where list is pointing cannot change.</p>\n<p>For example if you have a function that takes a string and you want to communicate to the user of this function that the content of the string is not going to change, you should do <code>void foo(const char *bar)</code>. If the function is only <code>foo(char *bar)</code> the user cannot be sure that the content of the string <code>bar</code> is still the same afterwards.</p>\n<h1>Q2:</h1>\n<ul>\n<li>I don't see any issues with the <code>remove</code> and <code>insert</code> functions regarding performance. Insert in the middle is\nalways going to be O(n). Removing/inserting at head and tail is O(1) which you achieve in your code.</li>\n<li>It would be a bit more intuitive if you implemented the simple case of removing head/tail in the function <code>remove_front</code>/<code>remove_back</code>\nand used these functions in the generic <code>remove_pos</code> function.</li>\n</ul>\n<h1>Q3:</h1>\n<h2>sorting</h2>\n<ul>\n<li><code>sort_list</code>: what you could do is setting a flag when the list is ordered so that if it gets ordered again, it's fast (unset the flag when an element is added)</li>\n<li>otherwise I don't see any issues with the sorting implementation</li>\n</ul>\n<h2>reverse</h2>\n<p>Your list reverse implementation is O(n) but since you have a doubly linked list you could simple make use of this. You could have two sets of operations on the list, one operates in forward direction, the other one in reverse. Whenever the <code>reverse_list</code> is called you would swap the function set. See the example below:</p>\n<pre><code>\nstruct list_operations\n{\n void (*insert_front)(double_list* const list, int val);\n // more functions\n};\n\nstatic const struct list_operations list_operations_forward = \n{\n .insert_front = insert_front_forward,\n // more functions\n};\n\nstatic const struct list_operations list_operations_reverse = \n{\n .insert_front = insert_front_reverse,\n // more functions\n};\n\nvoid reverse_list(double_list* list)\n{\n if (NULL == list)\n {\n return\n }\n\n list->operations = (list->operations == &list_operations_forward)?&list_operations_reverse:&list_operations_forward;\n}\n\n</code></pre>\n<h1>More general feedback:</h1>\n<h2>Hide private information</h2>\n<p>You leak some of the the details in the h file. You probably don't want that a user of your <code>double_list</code> library\ncan mess with the nodes, therefore you should hide it and add functions to get the value.\nThe h file would look like follows:</p>\n<pre><code>typedef struct double_list_s double_list_t;\n\ndouble_list* create_list();\nvoid destroy_list(double_list* list);\n\nvoid insert_pos(double_list *list, int index, int val);\nvoid insert_front(double_list *list, int val);\nvoid insert_back(double_list *list, int val);\n\nvoid remove_pos(double_list *list, int index);\nvoid remove_front(double_list *list);\nvoid remove_back(double_list *list);\n\nint get_pos(double_list *list, pos);\nint get_front(double_list *list);\nint get_back(double_list *list);\n\nvoid sort_list(double_list *list); // selection sort\nvoid reverse_list(double_list *list);\n</code></pre>\n<h2>Remove the const</h2>\n<p>You are passing <code>double_list* const list</code>, what are you exactly trying to achieve with the <code>const</code>?</p>\n<h2>Inclusion guard missing</h2>\n<p>You should add the following:</p>\n<pre><code>\n#ifndef __DOUBLE_LIST_H__\n#define __DOUBLE_LIST_H__\n\n// snip\n\n#endif\n\n</code></pre>\n<h2>Remove the includes in the h file</h2>\n<p>The includes should go in the c files only. Otherwise you can run into cyclic inclusions.</p>\n<h2>the pointer star sticks to the variable</h2>\n<p>e.g. not good: <code>char* b</code></p>\n<p>better: <code>char *b</code></p>\n<p>otherwise it looks weird if you have following declaration:</p>\n<p><code>char* b, *a</code> vs (<code>char *b, *a</code>)</p>\n<h2>Check for NULL</h2>\n<p>Check the <code>list</code> argument for NULL in the functions</p>\n<h2>Check for NULL after allocating</h2>\n<p>When you allocate the nodes, you should also check if <code>malloc</code> returned <code>NULL</code>.</p>\n<h2>Testing</h2>\n<p>When you add to your list, you add the element in 1,2,3 order, so <code>sort_list</code> is not doing much.</p>\n<h2>Naming the functions</h2>\n<p>When it comes to naming functions it certainly comes down to personal taste but I would stick with\ncommon expressions. For example <code>back</code> and <code>front</code> are a bit uncommon, I think <code>head</code> and <code>tail</code>\ndescribe better what the functions to.</p>\n<p>Also it makes your interface a bit cleaner if you name them consistently</p>\n<pre><code>list_create()\nlist_destroy()\n\nlist_pos_insert()\nlist_head_insert()\nlist_tail_insert()\n\nlist_pos_remove()\nlist_head_remove()\nlist_tail_remove()\n\nlist_sort()\nlist_reverse()\n</code></pre>\n<p>Just let me know if something is unclear, codereview "forgot" half of my text so I rushed it a bit to write it down again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T18:07:54.523",
"Id": "486580",
"Score": "0",
"body": "Oh cool thanks! Just a question though, I have the `const` there since I though it prevent the pointer from begin reassigned? Isn't that good practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T00:33:54.530",
"Id": "486635",
"Score": "0",
"body": "@DynamicSquid I've added a short paragraph about the `const`, It's certainly good to use `const` when possible but in your case it doesn't make sense since the user holds on to the `list` pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T11:54:10.340",
"Id": "486662",
"Score": "2",
"body": "@DynamicSquid It doesn't make sense to use `type * const name` on parameters because that pointer is a local copy of the original, and nobody cares if your function reassigns that local copy somewhere. It doesn't affect the original pointer on the caller side."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:10:17.963",
"Id": "248408",
"ParentId": "248381",
"Score": "3"
}
},
{
"body": "<p>regarding:</p>\n<pre><code>typedef struct\n{\n int length;\n Node* head;\n Node* tail;\n} double_list;\n</code></pre>\n<p>Most debuggers use the 'tag' name of a struct to be able to access the individual fields. Suggest inserting a 'tag' name</p>\n<p>the <code>main()</code> function is missing. Perhaps that is where you would place the calls:</p>\n<pre><code>double_list* list = create_list();\ninsert_back(list, 1);\ninsert_back(list, 2);\ninsert_back(list, 3);\nsort_list(list);\ndestroy_list(list);\n</code></pre>\n<p>strongly suggest keeping the list sorted at 'insert()' rather than as a separate operation</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:38:09.877",
"Id": "486628",
"Score": "1",
"body": "you probably don't want to sort when adding an item. If you add at the tail you want to get the same item when you get an item from the tail. Otherwise, the list should be called `sorted_double_list` (and functions like `insert_pos`, `insert_back`, `insert_front` would be superfluous (replace by simple `insert` function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T02:53:28.040",
"Id": "486637",
"Score": "0",
"body": "simplicity of code is always a very desirable objective"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:19:19.290",
"Id": "248430",
"ParentId": "248381",
"Score": "0"
}
},
{
"body": "<p>I would treat <code>Node</code> as a class, as you did with <code>double_list</code>. I.e. create functions <code>node_create()</code>, <code>node_destroy()</code> etc.<br />\nLet <code>node_...()</code> functions modify/sanity check the Node's content.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T16:08:29.203",
"Id": "248771",
"ParentId": "248381",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248408",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T19:44:49.223",
"Id": "248381",
"Score": "5",
"Tags": [
"c",
"linked-list"
],
"Title": "Doubly linked-list implementation"
}
|
248381
|
<p>How's my code? Works perfectly for what I'm trying to do :)</p>
<pre><code>#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<fstream>
#include<assert.h>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 }, number;
vector<int> numbers;
string word;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof()) {
numbers.push_back(number);
break;
}
else if (file.fail()) {
file.clear();
file >> word;
}
else if (file.bad()) exit(1);
else numbers.push_back(number);
}
for (int x : numbers) sum += x;
cout << sum << "\n";
}
</code></pre>
<p>Here's the file I'm reading from:</p>
<pre><code>words 32 jd: 5 alkj 3 12 fjkl: 23 / 32
hey 332 2 jk 23 k 23 ksdl 3
32 kjd 3 klj 332 c 32
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:13:45.563",
"Id": "486534",
"Score": "3",
"body": "You say \"sum of all white space separated integers\" and that your code \"Works perfect\". Does it really? Because if the file contained for example `foo 332bar baz`, you'd use the `332` even though it's not separated from `bar`."
}
] |
[
{
"body": "<pre><code>#include<iostream>\n#include<string>\n#include<vector>\n#include<algorithm>\n#include<cmath>\n#include<fstream>\n#include<assert.h>\n</code></pre>\n<p>This would be easier to read with some spaces between <code>#include</code> and the header name.</p>\n<p><code><assert.h></code> is a C standard library header file. C++ supplies its own version of the C headers which put their content into the <code>std</code> namespace, and we should use that version instead. These headers have <code>c</code> added to the front, and no extension, e.g. <code>#include <cassert></code>.</p>\n<p>It's nice to arrange includes in alphabetical order.</p>\n<p>Note also that we don't need all these headers - include only what you need.</p>\n<hr />\n<pre><code>using namespace std;\n</code></pre>\n<p>This is a bad habit to get into. It can lead to name collisions for large projects. It's best to avoid it and type the namespace where you need to (e.g. <code>std::vector</code>).</p>\n<hr />\n<pre><code>inline void keep_window_open() { char ch; cin >> ch; }\n</code></pre>\n<p>This function isn't used! If you're using visual studio (or the microsoft compilers in general), you can set the linker subsystem to <code>CONSOLE</code>, which keeps the console window open after the program finishes running.</p>\n<hr />\n<pre><code>int sum{ 0 }, number;\nvector<int> numbers;\nstring word;\n</code></pre>\n<p>Variables should be declared as close to the point of use as possible:</p>\n<ul>\n<li>We don't need <code>sum</code> until much later.</li>\n<li><code>number</code> can be declared inside the loop.</li>\n<li><code>numbers</code> is only needed after we've opened the file (just before the loop).</li>\n<li><code>word</code> isn't needed until an inner scope of the loop.</li>\n</ul>\n<p>Variables should not be reused (unless there is a significant performance hit - e.g. allocating large objects in memory), as it makes it harder to spot mistakes.</p>\n<hr />\n<pre><code>fstream file;\nfile.open("file1.txt", fstream::in);\n</code></pre>\n<p>We can use the <code>fstream</code> constructor to open the file, instead of opening the file in a separate step.</p>\n<p>We could use <code>ifstream</code>, since we're only interested in file input.</p>\n<hr />\n<pre><code>while (true) {\n file >> number;\n if (file.eof()) {\n numbers.push_back(number);\n break;\n }\n else if (file.fail()) { \n file.clear();\n file >> word;\n }\n else if (file.bad()) exit(1);\n else numbers.push_back(number);\n}\n</code></pre>\n<p>There's nothing wrong with <code>while (true)</code>. It's often much clearer than trying to cram lots of logic into the loop condition.</p>\n<p>There's also nothing wrong with multiple exit points, or <code>return</code> statements. We should <code>return</code> (or <code>break</code> or <code>continue</code>) as soon as possible in our code to simplify the logic and avoid unnecessary branching and nesting.</p>\n<p>There are a couple of things we can simplify here:</p>\n<ul>\n<li>We should only have one point where we add a number to the vector (duplicate code is harder to maintain).</li>\n<li>If we exit the loop with <code>break</code> or <code>return</code> (or start a new loop iteration with <code>continue</code>), we don't need to use an <code>else if</code> because the <code>else</code> is implicit. We can just use a separate <code>if</code> statement.</li>\n</ul>\n<p>There's also a subtle bug here. <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/bad\" rel=\"nofollow noreferrer\">When the <code>bad</code> bit on a stream is set, the <code>fail()</code> function also returns <code>true</code></a>! So instead of <code>exit()</code>ing, we'll try to clear the (unrecoverable) error, the <code>bad</code> bit will be set again, and we end up in an infinite loop. So we need to check <code>bad()</code> before we check <code>fail()</code>.</p>\n<hr />\n<p>It would be nice to print some error messages to <code>std::cerr</code> if something goes wrong (the file doesn't open, or reading from it fails).</p>\n<p>It would be nice to have a comment or two where the purpose of the code isn't immediately clear (e.g. what <code>word</code> is used for).</p>\n<hr />\n<p>Applying this we might end up with the following:</p>\n<pre><code>#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main() {\n \n std::string filename = "file1.txt";\n std::ifstream file(filename);\n \n if (!file.is_open()) {\n std::cerr << "failed to open file: " << filename << "\\n";\n return EXIT_FAILURE;\n }\n\n std::vector<int> numbers;\n \n while (true) {\n \n int number;\n file >> number;\n \n if (file.bad()) {\n std::cerr << "unrecoverable error while reading from file: " << filename << "\\n";\n return EXIT_FAILURE;\n }\n \n if (file.fail()) {\n // input was not an integer! \n // clear the error, and discard input until the next whitespace\n file.clear();\n std::string word;\n file >> word;\n continue;\n }\n \n numbers.push_back(number);\n \n if (file.eof()) {\n break;\n }\n }\n\n int sum = 0;\n for (int x : numbers) sum += x;\n \n std::cout << sum << "\\n";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:14:47.147",
"Id": "486538",
"Score": "0",
"body": "*\"There's also nothing wrong with multiple exit points, or return statements! We should return (or break or continue) as soon as possible in our code to simplify the logic and avoid unnecessary branching and nesting.\"* **Re** I find the statements contradictory. Multiple exit points introduce branching which you say is unnecessary! // \"*Contrary to what the other answer says, there's nothing wrong with while (true)! It's often much clearer than trying to cram lots of logic into the loop condition.*\" **Re** If the design is good, the cramming can be reduced to just function calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T09:48:48.233",
"Id": "486655",
"Score": "0",
"body": "1. Consider the code above, and try to rewrite it using a single `return` at the end of `main()` and you'll see what I mean. You'll probably end up with extra `else` branches, and a ternary statement to figure out what value to return at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T09:54:16.910",
"Id": "486656",
"Score": "0",
"body": "2. Sure, sometimes. But you can do lots of things in the loop body that you can't do in the loop condition (e.g. declare and use variables). If it's anything other than a simple function call, I'd suggest it's better to put it in the loop body."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T11:45:36.467",
"Id": "248406",
"ParentId": "248382",
"Score": "1"
}
},
{
"body": "<p>You collect all numbers but then use the collection only for the sum. Better just update the sum. And I find the whole trying int and if fails use word a bit complicated. How about just always reading words and then reading numbers from them? (The <code>>></code> writes zero if there's no number.)</p>\n<pre><code>#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\nusing namespace std;\n\nint main() {\n int sum = 0;\n ifstream file("file1.txt");\n string word;\n while (file >> word) {\n int number;\n istringstream(word) >> number;\n sum += number;\n }\n cout << sum << endl;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:10:26.167",
"Id": "248409",
"ParentId": "248382",
"Score": "2"
}
},
{
"body": "<p>Here's an answer with less complex while loop and no use of <code>stringstream</code>s.</p>\n<p>I've found <code>std::stoi</code>/<code>std::stof</code> faster than <code>>></code> operator to convert strings to numbers. Also, we have a clear indication of failure in the form of exceptions.</p>\n<hr>\n<p>If you only need the sum, don't store all numbers. If the file is big, it's just memory waste.</p>\n<hr>\n<pre><code>#include<cmath>\n#include<assert.h>\n</code></pre>\n<p>Unused headers.</p>\n<ul>\n<li><a href=\"https://github.com/include-what-you-use/include-what-you-use\" rel=\"nofollow noreferrer\">https://github.com/include-what-you-use/include-what-you-use</a></li>\n</ul>\n<hr>\n<pre><code>#include <fstream>\n#include <iostream>\n#include <string>\n\nint main() {\n int sum = 0;\n std::ifstream file_s("file1.txt");\n if (file_s.bad()) {\n return -1;\n }\n\n std::string word;\n while (std::getline(file_s, word, ' ')) {\n try {\n sum += std::stoi(word);\n }\n catch(const std::invalid_argument& ex) {\n std::cout << ex.what() << ":" << word << std::endl;\n }\n }\n\n std::cout << sum << std::endl;\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:31:01.970",
"Id": "486547",
"Score": "0",
"body": "Did you get the correct sum for their example? Your code [gives me 857](https://repl.it/repls/GreedyThoseBlogware#main.cpp) instead of the correct 889."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:32:36.633",
"Id": "486548",
"Score": "0",
"body": "Ah thanks! Your file contains newline which the question doesn't specify: only space-separated words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:34:03.657",
"Id": "486551",
"Score": "0",
"body": "You can see the newlines if you open the question editor. They're there, the OP just didn't make them visible (sigh)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:36:43.920",
"Id": "486553",
"Score": "0",
"body": "Oh. Then to use `std::stoi` one should split a line (read by `std::getline` + `'\\n'`) using the splitter written here: https://codereview.stackexchange.com/a/247292/205955 // There's no need to store words as `std::string_view`s either but they're cheap, so its fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:54:55.503",
"Id": "486555",
"Score": "1",
"body": "How about `sum += std::stoi(word);`?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:11:39.153",
"Id": "248411",
"ParentId": "248382",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248409",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T20:00:12.293",
"Id": "248382",
"Score": "3",
"Tags": [
"c++",
"stream"
],
"Title": "Produce the sum of all white space separated integers in a given file"
}
|
248382
|
<p>Here is the chess class for my very own chess game. Everything is in this class. Generating moves, getting a move from the computer, printing the board etc etc. This is a follow up question to <a href="https://codereview.stackexchange.com/questions/247811/c-generator-function-for-a-chess-game">C++ generator function for a Chess game</a>.</p>
<p>these are the values for each piece in the board, also used in the <code>int board[8][8];</code></p>
<p>pawn = 1</p>
<p>bishop = 2</p>
<p>knight = 3</p>
<p>rook = 5</p>
<p>queen = 6</p>
<p>king = 10</p>
<p>The same values apply for black pieces too, except this time they are negative. For example;
A white pawn holds a value of <strong>1</strong></p>
<p>A black pawn holds a value of <strong>-1</strong></p>
<p>The move generation is done for each piece simply by adding or subtracting values to <strong>row</strong> and <strong>column</strong> , referring to the two dimensions of the array inside the class. For example if a pawn is at <code>board[6][0]</code>, If you look at the board you can see moving up means going to the next row, In this case going up would be reducing values in row, that means 6,0 now becomes 5,0. Once I have a logic for how the pieces move I need to check whether It is a valid move, that means I am only moving to an empty square or capturing an opponent's piece. The final validation layer is from the rule in chess, which is a <a href="https://en.wikipedia.org/wiki/Check_(chess)" rel="nofollow noreferrer">check</a> in chess.</p>
<p>In simple words, It is a threat to your king. If your king is under a threat, that means if a piece is attacking it, you need to block that path, or move the king before you can play any other move.</p>
<p>Let's assume I have this position .</p>
<p><a href="https://i.stack.imgur.com/wddfG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wddfG.jpg" alt="This is also called A pin in chess" /></a></p>
<p>If it is the Black player's turn, he cannot move his bishop, as my rook will give a check to his king if he does. As the bishop is blocking the king from a check. That's why before I generate the final moves. I generate <em>pseudolegalmoves</em> which are basically just following all the individual rules. Then I go through each move in the container, perform it. After performing, if the function <code>bool check(int turn</code> returns true, simply means it's an invalid move. I dump it.</p>
<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<vector>
#include<string>
typedef std::vector<std::string> buff;
typedef std::string str;
// Pawn - 1, Knight - 3, Bishop - 2, rook - 5,queen - 6,king - 10
str push(int row,int col,int desrow,int descol){
using std::to_string;
str mystr = to_string(row) + to_string(col) + to_string(desrow) + to_string(descol);
return mystr;
}
class Chess{
public:
short int board[8][8] = // This array represents the chess board
{
{-2,0,0,0,0,0,-10,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,-1,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,6,0,0,0,0,0},
{0,10,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
};
buff pseudomoves;
buff legal_moves;
private:
void undomove(int original,str Move){
board[Move[0]-48][Move[1]-48] = board[Move[2]-48][Move[3]-48];
board[Move[2]-48][Move[3]-48] = original;
}
public:
int perform(str Move){
int original;
original = board[Move[2]-48][Move[3]-48];
board[Move[2]-48][Move[3]-48] = board[Move[0]-48][Move[1]-48];
board[Move[0]-48][Move[1]-48] = 0;
return original;
}
private:
bool check(bool turn){
if (turn == true){
int row,col;
//Finding the king on the board
for (int i = 0;i < 8;i++){
for (int j = 0;j < 8;j++){
if (board[i][j] == 10){
row = i;
col = j;
}
}
}
//Finding the king on the board
if (row != 0 && col != 0 && board[row-1][col-1] == -1) return true;
else if (row != 0 && col != 7 && board[row-1][col+1] == -1) return true;
int a,b;
a = row;
b = col;
if (a != 0 && b != 0){
for(;;){
a-=1;
b-=1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 0 || b == 0) break;
}
}
a = row;
b = col;
if (a != 0 && b != 7){
for(;;){
a-=1;
b+=1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 0 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7 && b != 0){
for(;;){
a+=1;
b-=1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 7 || b == 0) break;
}
}
a = row;
b = col;
if (a != 7 && b != 7){
for(;;){
a+=1;
b+=1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 7 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7){
for(;;){
a+=1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || a == 7 ) break;
}
}
a = row;
b = col;
if (a != 0){
for(;;){
a-=1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || a == 0 ) break;
}
}
a = row;
b = col;
if (b != 7){
for(;;){
b+=1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || b == 7 ) break;
}
}
a = row;
b = col;
if (b != 0){
for(;;){
b-=1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || b == 0 ) break;
}
}
if (row > 0 && col < 6 && board[row-1][col+2] == -3)return true;
if (row > 1 && col < 7 && board[row-2][col+1] == -3)return true;
if (row < 7 && col < 6 && board[row+1][col+2] == -3)return true;
if (row < 6 && col < 7 && board[row+2][col+1] == -3)return true;
if (row < 6 && col > 0 && board[row+2][col-1] == -3)return true;
if (row < 7 && col > 1 && board[row+1][col-2] == -3)return true;
if (row > 1 && col > 0 && board[row-2][col-1] == -3)return true;
if (row > 0 && col > 1 && board[row-1][col-2] == -3)return true;
if (row != 7 && board[row+1][col] == -10)return true;
if (row != 0 && board[row-1][col] == -10)return true;
if (col != 7 && board[row][col+1] == -10) return true;
if (col != 0 && board[row][col-1] == -10) return true;
if (row != 7 && col != 7 && board[row+1][col+1] == -10)return true;
if (row != 7 && col != 0 && board[row+1][col-1] == -10) return true;
if (row != 0 && col != 7 && board[row-1][col+1] == -10) return true;
if (row != 0 && col != 0 && board[row-1][col-1] == -10) return true;
}
else if(turn == false){
int row,col;
//Finding the king on the board
for (int i = 0;i < 8;i++){
for (int j = 0;j < 8;j++){
if (board[i][j] == -10){
row = i;
col = j;
}
}
}
//Finding the king on the board
if (row != 7 && col != 0 && board[row+1][col-1] == 1) return true;
else if (row != 7 && col != 7 && board[row+1][col+1] == 1) return true;
int a,b;
a = row;
b = col;
if (a != 0 && b != 0){
for(;;){
a-=1;
b-=1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 0 || b == 0) break;
}
}
a = row;
b = col;
if (a != 0 && b != 7){
for(;;){
a-=1;
b+=1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 0 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7 && b != 0){
for(;;){
a+=1;
b-=1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 7 || b == 0) break;
}
}
a = row;
b = col;
if (a != 7 && b != 7){
for(;;){
a+=1;
b+=1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 7 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7){
for(;;){
a+=1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || a == 7 ) break;
}
}
a = row;
b = col;
if (a != 0){
for(;;){
a-=1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || a == 0 ) break;
}
}
a = row;
b = col;
if (b != 7){
for(;;){
b+=1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || b == 7 ) break;
}
}
a = row;
b = col;
if (b != 0){
for(;;){
b-=1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || b == 0 ) break;
}
}
if (row > 0 && col < 6 && board[row-1][col+2] == 3)return true;
if (row > 1 && col < 7 && board[row-2][col+1] == 3)return true;
if (row < 7 && col < 6 && board[row+1][col+2] == 3)return true;
if (row < 6 && col < 7 && board[row+2][col+1] == 3)return true;
if (row < 6 && col > 0 && board[row+2][col-1] == 3)return true;
if (row < 7 && col > 1 && board[row+1][col-2] == 3)return true;
if (row > 1 && col > 0 && board[row-2][col-1] == 3)return true;
if (row > 0 && col > 1 && board[row-1][col-2] == 3)return true;
if (row != 7 && board[row+1][col] == 10)return true;
if (row != 0 && board[row-1][col] == 10)return true;
if (col != 7 && board[row][col+1] == 10) return true;
if (col != 0 && board[row][col-1] == 10) return true;
if (row != 7 && col != 7 && board[row+1][col+1] == 10)return true;
if (row != 7 && col != 0 && board[row+1][col-1] == 10) return true;
if (row != 0 && col != 7 && board[row-1][col+1] == 10) return true;
if (row != 0 && col != 0 && board[row-1][col-1] == 10) return true;
}
return false;
}
void getdiagonalmoves(bool turn,int row,int col){
int a,b;
if(turn){
a = row;
b = col;
if (a != 0 && b != 0){
for (;;){
a-=1;
b-=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 0 && b != 7){
for (;;){
a-=1;
b+=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 7 && b != 7){
for (;;){
a+=1;
b+=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 7 && b != 0){
for (;;){
a+=1;
b-=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
}
else if(!turn){
a = row;
b = col;
if (a != 0 && b != 0){
for (;;){
a-=1;
b-=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 0 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 0 && b != 7){
for (;;){
a-=1;
b+=1;
if (board[a][b] < 0)
break;
if (board[a][b] > 0 || a == 0 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(board[a][b] == 0)
pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 7 && b != 7){
for (;;){
a+=1;
b+=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a != 7 && b != 0){
for (;;){
a+=1;
b-=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b])pseudomoves.push_back(push(row,col,a,b));
}
}
}
}
void getstraigtmoves(bool turn ,int row,int col){
int a,b;
if (turn) {// white player
a = row;
b = col;
if (a != 0){
for (;;){
a-=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a!=7){
for(;;){
a+=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (b!= 0){
for(;;){
b-=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a =row;
b = col;
if (b != 7){
for(;;){
b+=1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
}
else if(!turn) // black player
{
a = row;
b = col;
if (a != 0){
for (;;){
a-=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (a!=7){
for(;;){
a+=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a = row;
b = col;
if (b!= 0){
for(;;){
b-=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || b == 0){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
a =row;
b = col;
if (b != 7){
for(;;){
b+=1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || b == 7){
pseudomoves.push_back(push(row,col,a,b));
break;
}
if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b));
}
}
}
//returnpseudomoves;
}
void getknightmoves(bool turn,int row,int col){
if (turn) {
if (row > 0 && col < 6 && board[row-1][col+2] <= 0) // one up two right
pseudomoves.push_back(push(row,col,row-1,col+2));
if (row > 1 && col < 7 && board[row-2][col+1] <= 0) // two up one right
pseudomoves.push_back(push(row,col,row-2,col+1));
if (row < 7 && col < 6 && board[row+1][col+2] <= 0) // one down two right
pseudomoves.push_back(push(row,col,row+1,col+2));
if (row < 6 && col < 7 && board[row+2][col+1] <= 0) // two down one right
pseudomoves.push_back(push(row,col,row+2,col+1));
if (row < 6 && col > 0 && board[row+2][col-1] <= 0) //two down one left
pseudomoves.push_back(push(row,col,row+2,col-1));
if (row < 7 && col > 1 && board[row+1][col-2] <= 0) // one down two left
pseudomoves.push_back(push(row,col,row+1,col-2));
if (row > 1 && col > 0 && board[row-2][col-1] <= 0) // two up one left
pseudomoves.push_back(push(row,col,row-2,col-1));
if (row > 0 && col > 1 && board[row-1][col-2] <= 0) // one up two left
pseudomoves.push_back(push(row,col,row-1,col-2));
}
else if (!turn){
if (row > 0 && col < 6 && board[row-1][col+2] >= 0)pseudomoves.push_back(push(row,col,row-1,col+2));
if (row > 1 && col < 7 && board[row-2][col+1] >= 0)pseudomoves.push_back(push(row,col,row-2,col+1));
if (row < 7 && col < 6 && board[row+1][col+2] >= 0)pseudomoves.push_back(push(row,col,row+1,col+2));
if (row < 6 && col < 7 && board[row+2][col+1] >= 0)pseudomoves.push_back(push(row,col,row+2,col+1));
if (row < 6 && col > 0 && board[row+2][col-1] >= 0)pseudomoves.push_back(push(row,col,row+2,col-1));
if (row < 7 && col > 1 && board[row+1][col-2] >= 0)pseudomoves.push_back(push(row,col,row+1,col-2));
if (row > 1 && col > 0 && board[row-2][col-1] >= 0)pseudomoves.push_back(push(row,col,row-2,col-1));
if (row > 0 && col > 1 && board[row-1][col-2] >= 0)pseudomoves.push_back(push(row,col,row-1,col-2));
}
//returnpseudomoves;
}
void getpawnmoves(bool turn,int row,int col){
if (turn) {
if (row == 6 && board[row-1][col] == 0 && board[row-2][col] == 0)
pseudomoves.push_back(push(row,col,row-2,col));
if (board[row-1][col] == 0)
pseudomoves.push_back(push(row,col,row-1,col));
if (col != 0 && board[row-1][col-1] < 0)
pseudomoves.push_back(push(row,col,row-1,col-1));
if (col != 7 && board[row-1][col+1] < 0)
pseudomoves.push_back(push(row,col,row-1,col+1));
}
else if(!turn){
if (row == 7) //returnpseudomoves;
if (row == 1 && board[row+1][col] == 0 && board[row+2][col] == 0)
pseudomoves.push_back(push(row,col,row+2,col));
if (board[row+1][col] == 0)
pseudomoves.push_back(push(row,col,row+1,col));
if (col != 0 && board[row+1][col-1] > 0)
pseudomoves.push_back(push(row,col,row+1,col-1));
if (col != 7 && board[row+1][col+1] > 0)
pseudomoves.push_back(push(row,col,row+1,col+1));
}
//returnpseudomoves;
}
void getkingmoves(bool turn,int row,int col){
if (!turn){
if (row != 7 && board[row+1][col] >=0) pseudomoves.push_back(push(row,col,row+1,col));
if (row != 0 && board[row-1][col] >=0) pseudomoves.push_back(push(row,col,row-1,col));
if (col != 7 && board[row][col+1] >=0) pseudomoves.push_back(push(row,col,row,col+1));
if (col != 0 && board[row][col-1] >=0) pseudomoves.push_back(push(row,col,row,col-1));
if (row != 7 && col != 7 && board[row+1][col+1] >=0) pseudomoves.push_back(push(row,col,row+1,col+1));
if (row != 7 && col != 0 && board[row+1][col-1] >=0) pseudomoves.push_back(push(row,col,row+1,col-1));
if (row != 0 && col != 7 && board[row-1][col+1] >=0) pseudomoves.push_back(push(row,col,row-1,col+1));
if (row != 0 && col != 0 && board[row-1][col-1] >=0) pseudomoves.push_back(push(row,col,row-1,col-1));
}
else if (turn){
if (row != 7 && board[row+1][col] <=0) pseudomoves.push_back(push(row,col,row+1,col));
if (row != 0 && board[row-1][col] <=0) pseudomoves.push_back(push(row,col,row-1,col));
if (col != 7 && board[row][col+1] <=0) pseudomoves.push_back(push(row,col,row,col+1));
if (col != 0 && board[row][col-1] <=0) pseudomoves.push_back(push(row,col,row,col-1));
if (row != 7 && col != 7 && board[row+1][col+1] <=0) pseudomoves.push_back(push(row,col,row+1,col+1));
if (row != 7 && col != 0 && board[row+1][col-1] <=0) pseudomoves.push_back(push(row,col,row+1,col-1));
if (row != 0 && col != 7 && board[row-1][col+1] <=0) pseudomoves.push_back(push(row,col,row-1,col+1));
if (row != 0 && col != 0 && board[row-1][col-1] <=0) pseudomoves.push_back(push(row,col,row-1,col-1));
}
//returnpseudomoves;
}
int evaluation(){
int score;
for (int i = 0;i < 8;i++){
for(int j =0;j < 8;j++){
if(!board[i][j]) continue;
if (board[i][j] == 1) score-=10;
else if (board[i][j] == 2)score-=30;
else if (board[i][j] == 3)score-=30;
else if (board[i][j] == 5)score-=50;
else if (board[i][j] == 6)score-=90;
else if (board[i][j] == 10)score-=900;
else if (board[i][j] == -1)score+=10;
else if (board[i][j] == -2)score+=30;
else if (board[i][j] == -3)score+=30;
else if (board[i][j] == -5)score+=50;
else if (board[i][j] == -6)score+=60;
else if (board[i][j] == -10)score+=900;
}
}
return score;
}
int miniMax(int depth,bool ismax,int alpha,int beta){
if (depth == 0){
return evaluation();
}
int maxeval = -999999;
int mineval = 999999;
buff possiblemoves;
int original;
int eval;
if (ismax == true){
possiblemoves = getallmoves(false);
for (long unsigned int i = 0;i < possiblemoves.size();i++){
original = perform(possiblemoves[i]);
eval = miniMax(depth-1,false,alpha,beta);
undomove(original,possiblemoves[i]);
if(eval > maxeval)
maxeval = eval;
if (alpha >= eval)
alpha = eval;
if (beta <= alpha)
break;
}
return maxeval;
}
else{
possiblemoves = getallmoves(true);
for (long unsigned int i = 0;i < possiblemoves.size();i++){
original = perform(possiblemoves[i]);
eval = miniMax(depth-1,true,alpha,beta);
undomove(original,possiblemoves[i]);
if (eval < mineval)
mineval = eval;
if (beta <= eval)
beta = eval;
if (beta <= alpha)
break;
}
return mineval;
}
}
str miniMaxroot(int depth,bool turn){
str bestmove;
int maxeval = -9999999;
buff allmoves = getallmoves(turn);
int original;
int eval;
for (long unsigned int i = 0;i < allmoves.size();i++){
original = perform(allmoves[i]);
eval = miniMax(depth-1,false,-99999999,99999999);
std::cout << "Move: " << allmoves[i] << " Points: " << eval << "\n";
undomove(original,allmoves[i]);
if (eval > maxeval){
maxeval = eval;
bestmove = allmoves[i];
}
}
return bestmove;
}
public:
void printboard(){
for(int i = 0; i< 8;i++){
for(int j = 0;j < 8;j++){
if (board[i][j] == 1)
std::cout << "P ";
else if (board[i][j] == 5)
std::cout << "R ";
else if (board[i][j] == 3)
std::cout << "K ";
else if (board[i][j] == 2)
std::cout << "B ";
else if (board[i][j] == 6)
std::cout << "Q ";
else if(board[i][j] == 10)
std::cout << "KI ";
else if (board[i][j] == 0)
std::cout << ". ";
else if (board[i][j] == -1)
std::cout << "p ";
else if (board[i][j] == -5)
std::cout << "r ";
else if (board[i][j] == -3)
std::cout << "k ";
else if (board[i][j] == -2)
std::cout << "b ";
else if (board[i][j] == -6)
std::cout << "q ";
else if(board[i][j] == -10)
std::cout << "ki ";
else if (board[i][j] == -109)
std::cout << "X";
}
std::cout << std::endl;
}
}
buff getallmoves(bool turn){
pseudomoves.clear();
legal_moves.clear();
int original;
if (turn){
for(int i = 0;i < 8;i++){
for(int j = 0;j < 8;j++){
if (!board[i][j]) continue;
else if(board[i][j] == 1) getpawnmoves(true,i,j);
else if(board[i][j] == 2) getdiagonalmoves(true,i,j);
else if(board[i][j] == 3) getknightmoves(true,i,j);
else if(board[i][j] == 5) getstraigtmoves(true,i,j);
else if(board[i][j] == 6){
getdiagonalmoves(true,i,j);
getstraigtmoves(true,i,j);
}
else if(board[i][j] == 10) getkingmoves(true,i,j);
}
}
return pseudomoves;
for(long unsigned int i = 0;i < pseudomoves.size();i++){
original = perform(pseudomoves[i]);
if(check(true) == false){
legal_moves.push_back(pseudomoves[i]);
}
undomove(original,pseudomoves[i]);
}
return legal_moves;
}
else if(!turn){
for(int i = 0;i < 8;i++){
for(int j = 0;j < 8;j++){
if (!board[i][j]) continue;
else if(board[i][j] == -1) getpawnmoves(false,i,j);
else if(board[i][j] == -2) getdiagonalmoves(false,i,j);
else if(board[i][j] == -3) getknightmoves(false,i,j);
else if(board[i][j] == -5) getstraigtmoves(false,i,j);
else if(board[i][j] == -6){
getdiagonalmoves(false,i,j);
getstraigtmoves(false,i,j);
}
else if(board[i][j] == -10) getkingmoves(false,i,j);
}
}
for(long unsigned int i = 0;i < pseudomoves.size();i++){
original = perform(pseudomoves[i]);
if(check(false) == false){
legal_moves.push_back(pseudomoves[i]);
}
undomove(original,pseudomoves[i]);
}
return legal_moves;
}
return legal_moves;
}
str computer_move(unsigned short int depth){
str bestmove;
bestmove = miniMaxroot(depth,false);
std::cout << "Bestmove: " << bestmove << "\n";
perform(bestmove);
return bestmove;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:34:32.857",
"Id": "486481",
"Score": "3",
"body": "Using magic numbers everywhere makes it hard to understand your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:59:12.763",
"Id": "486483",
"Score": "0",
"body": "I added some short information in the top that should cover all of it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T22:07:28.997",
"Id": "486484",
"Score": "0",
"body": "Is this related to [this question](https://codereview.stackexchange.com/q/247811/47529)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T22:44:25.460",
"Id": "486486",
"Score": "4",
"body": "Seems so. And there the tip \"Use an `enum` for clarity\" was already given... (@Aryan if this is a follow up you should link to the previous one in your question. You may even edit the first question or link to this one via a comment)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:39:40.047",
"Id": "486516",
"Score": "0",
"body": "Yes how can I link it. It is like a follow up"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:40:51.937",
"Id": "486535",
"Score": "0",
"body": "I added the link to the previous question for you."
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>Unlike some more modern languages such as C# and Java, a C++ class is generally implemented as 2 files: a header file generally with the file extension <code>.h</code> and a source file generally with the files extensions <code>.cpp</code> or <code>.cc</code>. This is due primarily to the fact that C++ grew out the C programming language which had header files and source files as well.</p>\n<p>In C++ the classes declarations are in the header file and the member function implementations are in the source file. There are or were benefits to this arrangement. As long as the declarations remained the same, the underlying member functions could be modified as needed, recompiled and shipped to the client or customer to be installed without changing a major version number. Changes to class declarations required version number changes.</p>\n<p>The second possible benefit of separating the declarations from the source is that the entire implementation can be refactored as long as the class declarations do not change. This could allow for major changes to take place to improve performance or memory usage without the outside code needing to change.</p>\n<p>The code in this question is all in one file and that makes it more difficult to maintain. It also means that all of the code needs to be included in whatever file needs to use it using an include statement, which leads to unnecessarily long compile and build times.</p>\n<p>At the end of the answer I've included the possible header and source file for this code. <em>None of the logic was changed.</em></p>\n<p><strong>Definitely follow any suggestions @Edward made in the previous review.</strong></p>\n<h2>Put Public Declarations First</h2>\n<p>Within the header file the list of all public members starting with the constructors should go first, then the protected members and finally private members. This organization is so that the users of the class can quickly find what they need. This is not enforced by the language or the compilers but is general custom. C++ also differs from at least C# (I haven't programmed in Java so I don't know) in that public members can be grouped.</p>\n<pre><code>class CLASSNAME {\npublic:\n Public_Member_0;\n Public_Member_1;\n Public_Constructor_2(){}\n Public_Member_3(){}\nprotected:\n Private_Member_0;\n Private_Member_1(){}\n Private_Member_2(){}\nprivate:\n Private_Member_0;\n Private_Member_1(){}\n Private_Member_2(){}\n}\n</code></pre>\n<h2>Make Items That Should Not Be Access Externally Private</h2>\n<p>There is no reason that the data representation of the board should be public, at most it should be protected so that classes that inherit for the <code>Chess</code> class can access it. It would be even better if it was private, and protected members provided access. It could also be declared as a static variable in the <code>Chess.cpp</code> file, which would allow easy change of the data representation.</p>\n<h2>Complexity!</h2>\n<p>The class as a whole as well as most of the member functions are too complex (do too much). Functions should only attempt to solve one problem and they shouldn't be larger than a screen in an editor or a sheet of paper if printed. Anything larger is very difficult to understand, write, read and thus maintain.</p>\n<p>I suggest you read up on the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> which states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>This is one of the main principles of Object Oriented Programming, in fact it is the <code>S</code> in <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"noreferrer\">SOLID Programming</a>.</p>\n<blockquote>\n<p>In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. It is not related to the GRASP software design principles. The principles are a subset of many principles promoted by American software engineer and instructor Robert C. Martin. Though they apply to any object-oriented design, the SOLID principles can also form a core philosophy for methodologies such as agile development or adaptive software development. The theory of SOLID principles was introduced by Martin in his 2000 paper Design Principles and Design Patterns, although the SOLID acronym was introduced later by Michael Feathers.</p>\n</blockquote>\n<p>It might be better to have multiple classes, one class to implement the board, an abstract base class for all the types of pieces with an abstract function for getting the move, each piece could then be implemented by a subclass that inherits from the base class. The board class would own the <code>printboard()</code> function.</p>\n<h2>Initialize All Local Variables</h2>\n<p>A best practice is to initialize each variable as it is declared. C++ does not initialize local variables to a default value and the lack of initialization can lead to undefined behavior.</p>\n<p>The variable <code>score</code> in the function <code>evaluation</code> is not initialized.</p>\n<h2>Reformated Into 2 Files</h2>\n<p>** chess2.h **</p>\n<pre><code>#ifndef CHESS2_H\n#define CHESS2_H\n#include<vector>\n#include<string>\n\ntypedef std::vector<std::string> buff;\ntypedef std::string str;\n\nclass Chess2\n{\npublic:\n buff pseudomoves;\n buff legal_moves;\n short int board[8][8] = // This array represents the chess board\n {\n {-2,0,0,0,0,0,-10,0},\n {0,0,0,0,0,0,0,0},\n {0,0,0,0,-1,0,0,0},\n {0,0,0,0,0,0,0,0},\n {0,0,6,0,0,0,0,0},\n {0,10,0,0,0,0,0,0},\n {0,0,0,0,0,0,0,0},\n {0,0,0,0,0,0,0,0},\n };\n int perform(str Move);\n void printboard();\n str push(int row, int col, int desrow, int descol); \n buff getallmoves(bool turn);\n str computer_move(unsigned short int depth);\n\nprivate:\n bool check(bool turn);\n void getdiagonalmoves(bool turn, int row, int col);\n void getstraigtmoves(bool turn, int row, int col);\n void getknightmoves(bool turn, int row, int col);\n void getpawnmoves(bool turn, int row, int col);\n void getkingmoves(bool turn, int row, int col);\n int evaluation();\n int miniMax(int depth, bool ismax, int alpha, int beta);\n str miniMaxroot(int depth, bool turn);\n void undomove(int original, str Move);\n};\n\n#endif // CHESS2_H\n</code></pre>\n<p>** chess2.cpp **</p>\n<pre><code>#include "Chess2.h"\n#include<iostream>\n\nint Chess2::perform(str Move) {\n int original;\n original = board[Move[2] - 48][Move[3] - 48];\n board[Move[2] - 48][Move[3] - 48] = board[Move[0] - 48][Move[1] - 48];\n board[Move[0] - 48][Move[1] - 48] = 0;\n return original;\n}\n\nvoid Chess2::printboard()\n{\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 1)\n std::cout << "P ";\n else if (board[i][j] == 5)\n std::cout << "R ";\n else if (board[i][j] == 3)\n std::cout << "K ";\n else if (board[i][j] == 2)\n std::cout << "B ";\n else if (board[i][j] == 6)\n std::cout << "Q ";\n else if (board[i][j] == 10)\n std::cout << "KI ";\n else if (board[i][j] == 0)\n std::cout << ". ";\n\n else if (board[i][j] == -1)\n std::cout << "p ";\n else if (board[i][j] == -5)\n std::cout << "r ";\n else if (board[i][j] == -3)\n std::cout << "k ";\n else if (board[i][j] == -2)\n std::cout << "b ";\n else if (board[i][j] == -6)\n std::cout << "q ";\n else if (board[i][j] == -10)\n std::cout << "ki ";\n else if (board[i][j] == -109)\n std::cout << "X";\n\n }\n std::cout << std::endl;\n }\n}\n\nstr Chess2::push(int row, int col, int desrow, int descol) {\n using std::to_string;\n\n str mystr = to_string(row) + to_string(col) + to_string(desrow) + to_string(descol);\n return mystr;\n}\n\nstr Chess2::computer_move(unsigned short int depth) {\n str bestmove;\n bestmove = miniMaxroot(depth, false);\n std::cout << "Bestmove: " << bestmove << "\\n";\n perform(bestmove);\n return bestmove;\n}\n\nbuff Chess2::getallmoves(bool turn) {\n pseudomoves.clear();\n legal_moves.clear();\n int original;\n if (turn) {\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (!board[i][j]) continue;\n else if (board[i][j] == 1) getpawnmoves(true, i, j);\n else if (board[i][j] == 2) getdiagonalmoves(true, i, j);\n else if (board[i][j] == 3) getknightmoves(true, i, j);\n else if (board[i][j] == 5) getstraigtmoves(true, i, j);\n else if (board[i][j] == 6) {\n getdiagonalmoves(true, i, j);\n getstraigtmoves(true, i, j);\n }\n else if (board[i][j] == 10) getkingmoves(true, i, j);\n }\n }\n return pseudomoves;\n for (long unsigned int i = 0; i < pseudomoves.size(); i++) {\n original = perform(pseudomoves[i]);\n if (check(true) == false) {\n legal_moves.push_back(pseudomoves[i]);\n }\n undomove(original, pseudomoves[i]);\n }\n return legal_moves;\n }\n else if (!turn) {\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (!board[i][j]) continue;\n else if (board[i][j] == -1) getpawnmoves(false, i, j);\n else if (board[i][j] == -2) getdiagonalmoves(false, i, j);\n else if (board[i][j] == -3) getknightmoves(false, i, j);\n else if (board[i][j] == -5) getstraigtmoves(false, i, j);\n else if (board[i][j] == -6) {\n getdiagonalmoves(false, i, j);\n getstraigtmoves(false, i, j);\n }\n else if (board[i][j] == -10) getkingmoves(false, i, j);\n }\n }\n for (long unsigned int i = 0; i < pseudomoves.size(); i++) {\n original = perform(pseudomoves[i]);\n if (check(false) == false) {\n legal_moves.push_back(pseudomoves[i]);\n }\n undomove(original, pseudomoves[i]);\n }\n return legal_moves;\n }\n return legal_moves;\n}\n\nbool Chess2::check(bool turn) {\n if (turn == true) {\n int row, col;\n //Finding the king on the board\n\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 10) {\n row = i;\n col = j;\n }\n }\n }\n\n //Finding the king on the board\n if (row != 0 && col != 0 && board[row - 1][col - 1] == -1) return true;\n else if (row != 0 && col != 7 && board[row - 1][col + 1] == -1) return true;\n int a, b;\n a = row;\n b = col;\n if (a != 0 && b != 0) {\n for (;;) {\n a -= 1;\n b -= 1;\n if (board[a][b] == -6 || board[a][b] == -2) return true;\n if (board[a][b] != 0 || a == 0 || b == 0) break;\n }\n }\n a = row;\n b = col;\n if (a != 0 && b != 7) {\n for (;;) {\n a -= 1;\n b += 1;\n if (board[a][b] == -6 || board[a][b] == -2) return true;\n if (board[a][b] != 0 || a == 0 || b == 7) break;\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 0) {\n for (;;) {\n a += 1;\n b -= 1;\n if (board[a][b] == -6 || board[a][b] == -2) return true;\n if (board[a][b] != 0 || a == 7 || b == 0) break;\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 7) {\n for (;;) {\n a += 1;\n b += 1;\n if (board[a][b] == -6 || board[a][b] == -2) return true;\n if (board[a][b] != 0 || a == 7 || b == 7) break;\n }\n }\n\n a = row;\n b = col;\n if (a != 7) {\n for (;;) {\n a += 1;\n if (board[a][b] == -6 || board[a][b] == -5) return true;\n if (board[a][b] != 0 || a == 7) break;\n }\n }\n a = row;\n b = col;\n if (a != 0) {\n for (;;) {\n a -= 1;\n if (board[a][b] == -6 || board[a][b] == -5) return true;\n if (board[a][b] != 0 || a == 0) break;\n }\n }\n\n a = row;\n b = col;\n if (b != 7) {\n for (;;) {\n b += 1;\n if (board[a][b] == -6 || board[a][b] == -5) return true;\n if (board[a][b] != 0 || b == 7) break;\n }\n }\n a = row;\n b = col;\n if (b != 0) {\n for (;;) {\n b -= 1;\n if (board[a][b] == -6 || board[a][b] == -5) return true;\n if (board[a][b] != 0 || b == 0) break;\n }\n }\n\n if (row > 0 && col < 6 && board[row - 1][col + 2] == -3)return true;\n if (row > 1 && col < 7 && board[row - 2][col + 1] == -3)return true;\n if (row < 7 && col < 6 && board[row + 1][col + 2] == -3)return true;\n if (row < 6 && col < 7 && board[row + 2][col + 1] == -3)return true;\n if (row < 6 && col > 0 && board[row + 2][col - 1] == -3)return true;\n if (row < 7 && col > 1 && board[row + 1][col - 2] == -3)return true;\n if (row > 1 && col > 0 && board[row - 2][col - 1] == -3)return true;\n if (row > 0 && col > 1 && board[row - 1][col - 2] == -3)return true;\n\n if (row != 7 && board[row + 1][col] == -10)return true;\n if (row != 0 && board[row - 1][col] == -10)return true;\n if (col != 7 && board[row][col + 1] == -10) return true;\n if (col != 0 && board[row][col - 1] == -10) return true;\n if (row != 7 && col != 7 && board[row + 1][col + 1] == -10)return true;\n if (row != 7 && col != 0 && board[row + 1][col - 1] == -10) return true;\n if (row != 0 && col != 7 && board[row - 1][col + 1] == -10) return true;\n if (row != 0 && col != 0 && board[row - 1][col - 1] == -10) return true;\n\n\n }\n else if (turn == false) {\n int row, col;\n //Finding the king on the board\n\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == -10) {\n row = i;\n col = j;\n }\n }\n }\n\n //Finding the king on the board\n if (row != 7 && col != 0 && board[row + 1][col - 1] == 1) return true;\n else if (row != 7 && col != 7 && board[row + 1][col + 1] == 1) return true;\n\n int a, b;\n a = row;\n b = col;\n if (a != 0 && b != 0) {\n for (;;) {\n a -= 1;\n b -= 1;\n if (board[a][b] == 6 || board[a][b] == 2) return true;\n if (board[a][b] != 0 || a == 0 || b == 0) break;\n }\n }\n a = row;\n b = col;\n if (a != 0 && b != 7) {\n for (;;) {\n a -= 1;\n b += 1;\n if (board[a][b] == 6 || board[a][b] == 2) return true;\n if (board[a][b] != 0 || a == 0 || b == 7) break;\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 0) {\n for (;;) {\n a += 1;\n b -= 1;\n if (board[a][b] == 6 || board[a][b] == 2) return true;\n if (board[a][b] != 0 || a == 7 || b == 0) break;\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 7) {\n for (;;) {\n a += 1;\n b += 1;\n if (board[a][b] == 6 || board[a][b] == 2) return true;\n if (board[a][b] != 0 || a == 7 || b == 7) break;\n }\n }\n\n a = row;\n b = col;\n if (a != 7) {\n for (;;) {\n a += 1;\n if (board[a][b] == 6 || board[a][b] == 5) return true;\n if (board[a][b] != 0 || a == 7) break;\n }\n }\n a = row;\n b = col;\n if (a != 0) {\n for (;;) {\n a -= 1;\n if (board[a][b] == 6 || board[a][b] == 5) return true;\n if (board[a][b] != 0 || a == 0) break;\n }\n }\n\n a = row;\n b = col;\n if (b != 7) {\n for (;;) {\n b += 1;\n if (board[a][b] == 6 || board[a][b] == 5) return true;\n if (board[a][b] != 0 || b == 7) break;\n }\n }\n a = row;\n b = col;\n if (b != 0) {\n for (;;) {\n b -= 1;\n if (board[a][b] == 6 || board[a][b] == 5) return true;\n if (board[a][b] != 0 || b == 0) break;\n }\n }\n\n if (row > 0 && col < 6 && board[row - 1][col + 2] == 3)return true;\n if (row > 1 && col < 7 && board[row - 2][col + 1] == 3)return true;\n if (row < 7 && col < 6 && board[row + 1][col + 2] == 3)return true;\n if (row < 6 && col < 7 && board[row + 2][col + 1] == 3)return true;\n if (row < 6 && col > 0 && board[row + 2][col - 1] == 3)return true;\n if (row < 7 && col > 1 && board[row + 1][col - 2] == 3)return true;\n if (row > 1 && col > 0 && board[row - 2][col - 1] == 3)return true;\n if (row > 0 && col > 1 && board[row - 1][col - 2] == 3)return true;\n\n if (row != 7 && board[row + 1][col] == 10)return true;\n if (row != 0 && board[row - 1][col] == 10)return true;\n if (col != 7 && board[row][col + 1] == 10) return true;\n if (col != 0 && board[row][col - 1] == 10) return true;\n if (row != 7 && col != 7 && board[row + 1][col + 1] == 10)return true;\n if (row != 7 && col != 0 && board[row + 1][col - 1] == 10) return true;\n if (row != 0 && col != 7 && board[row - 1][col + 1] == 10) return true;\n if (row != 0 && col != 0 && board[row - 1][col - 1] == 10) return true;\n\n }\n\n return false;\n}\n\nvoid Chess2::getdiagonalmoves(bool turn, int row, int col) {\n\n int a, b;\n if (turn) {\n a = row;\n b = col;\n if (a != 0 && b != 0) {\n for (;;) {\n a -= 1;\n b -= 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 0 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 0 && b != 7) {\n for (;;) {\n a -= 1;\n b += 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 0 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 7) {\n for (;;) {\n a += 1;\n b += 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 7 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 0) {\n for (;;) {\n a += 1;\n b -= 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 7 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n }\n else if (!turn) {\n\n a = row;\n b = col;\n if (a != 0 && b != 0) {\n for (;;) {\n a -= 1;\n b -= 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || a == 0 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 0 && b != 7) {\n for (;;) {\n a -= 1;\n b += 1;\n if (board[a][b] < 0)\n break;\n if (board[a][b] > 0 || a == 0 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (board[a][b] == 0)\n pseudomoves.push_back(push(row, col, a, b));\n\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 7) {\n for (;;) {\n a += 1;\n b += 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || a == 7 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 7 && b != 0) {\n for (;;) {\n a += 1;\n b -= 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || a == 7 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b])pseudomoves.push_back(push(row, col, a, b));\n }\n }\n\n }\n}\n\nvoid Chess2::getstraigtmoves(bool turn, int row, int col)\n{\n int a, b;\n if (turn) {// white player\n a = row;\n b = col;\n if (a != 0) {\n for (;;) {\n a -= 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 7) {\n for (;;) {\n a += 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || a == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (b != 0) {\n for (;;) {\n b -= 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (b != 7) {\n for (;;) {\n b += 1;\n if (board[a][b] > 0) break;\n if (board[a][b] < 0 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n }\n\n else if (!turn) // black player\n {\n a = row;\n b = col;\n if (a != 0) {\n for (;;) {\n a -= 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || a == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (a != 7) {\n for (;;) {\n a += 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || a == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (b != 0) {\n for (;;) {\n b -= 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || b == 0) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n a = row;\n b = col;\n if (b != 7) {\n for (;;) {\n b += 1;\n if (board[a][b] < 0) break;\n if (board[a][b] > 0 || b == 7) {\n pseudomoves.push_back(push(row, col, a, b));\n break;\n }\n if (!board[a][b]) pseudomoves.push_back(push(row, col, a, b));\n }\n }\n }\n //returnpseudomoves;\n}\n\nvoid Chess2::getknightmoves(bool turn, int row, int col) {\n\n if (turn) {\n\n if (row > 0 && col < 6 && board[row - 1][col + 2] <= 0) // one up two right\n pseudomoves.push_back(push(row, col, row - 1, col + 2));\n\n if (row > 1 && col < 7 && board[row - 2][col + 1] <= 0) // two up one right\n pseudomoves.push_back(push(row, col, row - 2, col + 1));\n\n if (row < 7 && col < 6 && board[row + 1][col + 2] <= 0) // one down two right\n pseudomoves.push_back(push(row, col, row + 1, col + 2));\n\n if (row < 6 && col < 7 && board[row + 2][col + 1] <= 0) // two down one right\n pseudomoves.push_back(push(row, col, row + 2, col + 1));\n\n if (row < 6 && col > 0 && board[row + 2][col - 1] <= 0) //two down one left\n pseudomoves.push_back(push(row, col, row + 2, col - 1));\n\n if (row < 7 && col > 1 && board[row + 1][col - 2] <= 0) // one down two left\n pseudomoves.push_back(push(row, col, row + 1, col - 2));\n\n if (row > 1 && col > 0 && board[row - 2][col - 1] <= 0) // two up one left\n pseudomoves.push_back(push(row, col, row - 2, col - 1));\n\n if (row > 0 && col > 1 && board[row - 1][col - 2] <= 0) // one up two left\n pseudomoves.push_back(push(row, col, row - 1, col - 2));\n }\n\n else if (!turn) {\n if (row > 0 && col < 6 && board[row - 1][col + 2] >= 0)pseudomoves.push_back(push(row, col, row - 1, col + 2));\n if (row > 1 && col < 7 && board[row - 2][col + 1] >= 0)pseudomoves.push_back(push(row, col, row - 2, col + 1));\n if (row < 7 && col < 6 && board[row + 1][col + 2] >= 0)pseudomoves.push_back(push(row, col, row + 1, col + 2));\n if (row < 6 && col < 7 && board[row + 2][col + 1] >= 0)pseudomoves.push_back(push(row, col, row + 2, col + 1));\n if (row < 6 && col > 0 && board[row + 2][col - 1] >= 0)pseudomoves.push_back(push(row, col, row + 2, col - 1));\n if (row < 7 && col > 1 && board[row + 1][col - 2] >= 0)pseudomoves.push_back(push(row, col, row + 1, col - 2));\n if (row > 1 && col > 0 && board[row - 2][col - 1] >= 0)pseudomoves.push_back(push(row, col, row - 2, col - 1));\n if (row > 0 && col > 1 && board[row - 1][col - 2] >= 0)pseudomoves.push_back(push(row, col, row - 1, col - 2));\n }\n\n //returnpseudomoves;\n}\n\nvoid Chess2::getpawnmoves(bool turn, int row, int col) {\n if (turn) {\n if (row == 6 && board[row - 1][col] == 0 && board[row - 2][col] == 0)\n pseudomoves.push_back(push(row, col, row - 2, col));\n if (board[row - 1][col] == 0)\n pseudomoves.push_back(push(row, col, row - 1, col));\n if (col != 0 && board[row - 1][col - 1] < 0)\n pseudomoves.push_back(push(row, col, row - 1, col - 1));\n if (col != 7 && board[row - 1][col + 1] < 0)\n pseudomoves.push_back(push(row, col, row - 1, col + 1));\n }\n\n else if (!turn) {\n if (row == 7) //returnpseudomoves;\n\n if (row == 1 && board[row + 1][col] == 0 && board[row + 2][col] == 0)\n pseudomoves.push_back(push(row, col, row + 2, col));\n if (board[row + 1][col] == 0)\n pseudomoves.push_back(push(row, col, row + 1, col));\n if (col != 0 && board[row + 1][col - 1] > 0)\n pseudomoves.push_back(push(row, col, row + 1, col - 1));\n if (col != 7 && board[row + 1][col + 1] > 0)\n pseudomoves.push_back(push(row, col, row + 1, col + 1));\n }\n\n //returnpseudomoves;\n}\n\nvoid Chess2::getkingmoves(bool turn, int row, int col) {\n\n if (!turn) {\n if (row != 7 && board[row + 1][col] >= 0) pseudomoves.push_back(push(row, col, row + 1, col));\n if (row != 0 && board[row - 1][col] >= 0) pseudomoves.push_back(push(row, col, row - 1, col));\n if (col != 7 && board[row][col + 1] >= 0) pseudomoves.push_back(push(row, col, row, col + 1));\n if (col != 0 && board[row][col - 1] >= 0) pseudomoves.push_back(push(row, col, row, col - 1));\n if (row != 7 && col != 7 && board[row + 1][col + 1] >= 0) pseudomoves.push_back(push(row, col, row + 1, col + 1));\n if (row != 7 && col != 0 && board[row + 1][col - 1] >= 0) pseudomoves.push_back(push(row, col, row + 1, col - 1));\n if (row != 0 && col != 7 && board[row - 1][col + 1] >= 0) pseudomoves.push_back(push(row, col, row - 1, col + 1));\n if (row != 0 && col != 0 && board[row - 1][col - 1] >= 0) pseudomoves.push_back(push(row, col, row - 1, col - 1));\n }\n else if (turn) {\n if (row != 7 && board[row + 1][col] <= 0) pseudomoves.push_back(push(row, col, row + 1, col));\n if (row != 0 && board[row - 1][col] <= 0) pseudomoves.push_back(push(row, col, row - 1, col));\n if (col != 7 && board[row][col + 1] <= 0) pseudomoves.push_back(push(row, col, row, col + 1));\n if (col != 0 && board[row][col - 1] <= 0) pseudomoves.push_back(push(row, col, row, col - 1));\n if (row != 7 && col != 7 && board[row + 1][col + 1] <= 0) pseudomoves.push_back(push(row, col, row + 1, col + 1));\n if (row != 7 && col != 0 && board[row + 1][col - 1] <= 0) pseudomoves.push_back(push(row, col, row + 1, col - 1));\n if (row != 0 && col != 7 && board[row - 1][col + 1] <= 0) pseudomoves.push_back(push(row, col, row - 1, col + 1));\n if (row != 0 && col != 0 && board[row - 1][col - 1] <= 0) pseudomoves.push_back(push(row, col, row - 1, col - 1));\n }\n //returnpseudomoves;\n}\n\nint Chess2::evaluation() {\n int score;\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (!board[i][j]) continue;\n if (board[i][j] == 1) score -= 10;\n else if (board[i][j] == 2)score -= 30;\n else if (board[i][j] == 3)score -= 30;\n else if (board[i][j] == 5)score -= 50;\n else if (board[i][j] == 6)score -= 90;\n else if (board[i][j] == 10)score -= 900;\n else if (board[i][j] == -1)score += 10;\n else if (board[i][j] == -2)score += 30;\n else if (board[i][j] == -3)score += 30;\n else if (board[i][j] == -5)score += 50;\n else if (board[i][j] == -6)score += 60;\n else if (board[i][j] == -10)score += 900;\n\n }\n }\n return score;\n}\n\nint Chess2::miniMax(int depth, bool ismax, int alpha, int beta) {\n if (depth == 0) {\n return evaluation();\n }\n int maxeval = -999999;\n int mineval = 999999;\n buff possiblemoves;\n int original;\n int eval;\n if (ismax == true) {\n possiblemoves = getallmoves(false);\n for (long unsigned int i = 0; i < possiblemoves.size(); i++) {\n original = perform(possiblemoves[i]);\n eval = miniMax(depth - 1, false, alpha, beta);\n undomove(original, possiblemoves[i]);\n if (eval > maxeval)\n maxeval = eval;\n if (alpha >= eval)\n alpha = eval;\n if (beta <= alpha)\n break;\n }\n return maxeval;\n }\n else {\n possiblemoves = getallmoves(true);\n for (long unsigned int i = 0; i < possiblemoves.size(); i++) {\n original = perform(possiblemoves[i]);\n eval = miniMax(depth - 1, true, alpha, beta);\n undomove(original, possiblemoves[i]);\n if (eval < mineval)\n mineval = eval;\n if (beta <= eval)\n beta = eval;\n if (beta <= alpha)\n break;\n }\n return mineval;\n }\n\n}\n\nstr Chess2::miniMaxroot(int depth, bool turn) {\n str bestmove;\n int maxeval = -9999999;\n buff allmoves = getallmoves(turn);\n int original;\n int eval;\n for (long unsigned int i = 0; i < allmoves.size(); i++) {\n original = perform(allmoves[i]);\n eval = miniMax(depth - 1, false, -99999999, 99999999);\n std::cout << "Move: " << allmoves[i] << " Points: " << eval << "\\n";\n undomove(original, allmoves[i]);\n if (eval > maxeval) {\n maxeval = eval;\n bestmove = allmoves[i];\n }\n }\n return bestmove;\n}\nvoid Chess2::undomove(int original, str Move) {\n board[Move[0] - 48][Move[1] - 48] = board[Move[2] - 48][Move[3] - 48];\n board[Move[2] - 48][Move[3] - 48] = original;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:45:20.213",
"Id": "486518",
"Score": "0",
"body": "I really appreciate this a lot! Could you please link any articles or any information on How I can define stuff in other files and then use it somewhere else using header files ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:47:59.593",
"Id": "486519",
"Score": "0",
"body": "Also , I wasn't sure how I could link this post to the last one, As i added almost all of @edward's suggestions and improved its computer generation speed from about 20 seconds to 4 seconds!,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:50:52.320",
"Id": "486521",
"Score": "2",
"body": "Minor nitpick: I'd say it is as common if not more common to use `.hpp` for C++ headers. I usually expect `.h` to be pure C. Then there's also less common `.tpp` for templates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:55:47.580",
"Id": "486522",
"Score": "0",
"body": "This post is full of suggestions which I WILL implement, but still I wanted to ask, currently my data structure is a `std::vector<std::string>`, A move would look like this. 'vector < \"0011\">`, Where the first two correspond to the initial positions and the last two correspond to the desired positions, Is there a faster way I can achieve the same task?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:45:14.033",
"Id": "486536",
"Score": "0",
"body": "@AryanParekh that will be pretty fast, numbers would be faster because they would be direct indexes into the board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:53:15.270",
"Id": "486537",
"Score": "0",
"body": "I'd say it depends on the IDE you use and which you are more comfortable with. I haven't seen `.tpp`but it makes sense. I don't write `.hpp` but I've used libraries that do, and I did mean to mention it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:21:45.040",
"Id": "486545",
"Score": "0",
"body": "@AryanParekh I use the [Unified Modeling Language (UML)](https://en.wikipedia.org/wiki/Unified_Modeling_Language) to design my objects. I'd start with the reading the books by the 3 creators of UML and at least one book by Martin as well. The 2 articles I referenced should also provide you with a good reading least. If books don't work for you find online articles for object oriented design."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T00:21:58.790",
"Id": "248391",
"ParentId": "248387",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248391",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:30:36.643",
"Id": "248387",
"Score": "5",
"Tags": [
"c++",
"object-oriented",
"classes"
],
"Title": "chess game Class"
}
|
248387
|
<p>Our monolithic WinForm application is getting a face lift. One current challenge that we are restructuring how we setup events. I rolled my own event manager class to handle the subscriptions and unsubscriptions to prevent leaks whenever developers write code.</p>
<p>I ran into several challenges with storing generic values in non-generic types. So I came up with a pattern that allowed me to do it. Not sure if I am creating a code smell while doing it so I wanted someone to review and ask questions.</p>
<p><strong>Base View</strong></p>
<pre><code>public abstract class View : Form, IView
{
protected readonly EventManager EventManager;
public View()
{
EventManager = new EventManager(this);
}
protected abstract void RegisterEvents();
}
</code></pre>
<p><strong>Concrete Class</strong></p>
<pre><code>public class MyView : View
{
protected override void RegisterEvents()
{
EventManager.Attach(button1_Click, handler => button1.Click += handler, button1.Click -= handler);
}
}
</code></pre>
<p><strong>Event Viewer</strong></p>
<pre><code>public class EventManager : IDisposable
{
private IList<TrackedEvent> Events = new List<TrackedEvent>();
private IDisposable Owner;
public EventManager(IDisposable owner)
{
Owner = owner;
}
public void Attach<TEventArgs>(EventHandler<TEventArgs> handler, Action<EventHandler<TEventArgs>> addEvent, Action<EventHandler<TEventArgs>> removeEvent = null)
{
Events.Add(GenericTrackedEvent<TEventArgs>.Register(@delegate, handler.Method.Name, removeEvent));
}
public void Attach(EventHandler handler, Action<EventHandler> addEvent, Action<EventHandler> removeEvent = null)
{
Events.Add(TrackedEvent.Register(@delegate, handler.Method.Name, removeEvent));
}
public void Dispose() { ... }
private class TrackedEvent : IDisposable
{
protected EventHandler Handler { get; set; }
protected string MethodName { get; set; }
protected Action<EventHandler> Unsubscription { get; set; }
protected TrackedEvent() { }
private TrackedEvent(EventHandler handler, string methodName, Action<EventHandler> removeEvent)
{
Handler = handler;
MethodName = methodName;
Unsubscription = removeEvent;
}
internal virtual void Remove()
{
Unsubscription(Handler);
}
internal static TrackedEvent Register(EventHandler handler, string methodName, Action<EventHandler> removeEvent)
{
return new TrackedEvent(handler, methodName, removeEvent);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
Handler = null;
Unsubscription = null;
}
}
private class GenericTrackedEvent<T> : TrackedEvent
{
protected new EventHandler<T> Handler { get; private set; }
protected new Action<EventHandler<T>> Unsubscription { get; private set; }
internal override void Remove()
{
Unsubscription(Handler);
}
private GenericTrackedEvent(EventHandler<T> handler, string methodName, Action<EventHandler<T>> removeEvent)
{
Handler = handler;
MethodName = methodName;
Unsubscription = removeEvent;
}
internal static TrackedEvent Register(EventHandler<T> handler, string methodName, Action<EventHandler<T>> removeEvent)
{
return new GenericTrackedEvent<T>(handler, methodName, removeEvent);
}
protected override void Dispose(bool disposing)
{
Handler = null;
Unsubscription = null;
base.Dispose(disposing);
}
}
}
</code></pre>
<p>So several things to point out and as to why:</p>
<ol>
<li><strong>Some methods have been shortened for brevity.</strong></li>
<li>TrackedEvent holds onto the unsubscription e.g: the removeEvent handler.</li>
<li>Previously implementations I struggled with storing generic types in a non-generic class without constant boxing/unboxing.</li>
<li>The two static methods "Register" will return a TrackedEvent class because its constructors are private. I don't want anyone creating one outside of my implementation.</li>
<li>TrackedEvent only handles non-generics.</li>
<li>GenericTrackedEvent handles generics by hiding our base properties and overriding key properties.</li>
<li>Unexpectedly, inheritance is working correctly when calling the remove method. My initial expectation was the GenericTrackedEvent was going to use the underlying TrackedEvent.Unsubscription and TrackedEvent.Handler properties but I was wrong - and that was okay.</li>
<li>Someone is going to ask - why are you passing over the MethodName? Because I actually wrap my handlers in a new delegate so I can capture when event fire and log them to any source I choose. When I wrap my delegates in the attach method it carries that name over instead of the original one passed in the handler parameter. Instead of masking that method, I figured I'd keep it. Again some code was remove because I do not deem it relevant to the initial question.</li>
</ol>
<p>Seems like we've implemented a duck typing but its usage is abstracted away from developers so I think its okay but wanted several other opinions to weight in.</p>
<p>Thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T03:52:24.417",
"Id": "486500",
"Score": "1",
"body": "The `View` and `MyView` classes are somehow 'lazy' clases (according to what you are showing us) however if in the future they will contain and provide more operations then it isn't a bad design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T06:33:28.223",
"Id": "486503",
"Score": "1",
"body": "You should correct the names: Neither `TrackedEvent.Register`, `GenericTrackedEvent<TEventArgs>.Register` nor `@delegate` exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:15:37.947",
"Id": "486539",
"Score": "0",
"body": "@Henrik right - sorry had some last minute edits before writing this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T13:19:16.520",
"Id": "486543",
"Score": "0",
"body": "@HenrikHansen furthermore, `@delegate` does exist in the full implementation. I wrap the original handler with logging so we can track the usage of the event for debugging purposes Doing this causes the new delegate's `MethodName` to attach itself to that class, instead of the original handler.\n\n\n`void @delegate(object s, TEventArgs e)\n {\n Debug.WriteLine($\"\\t{Owner.GetType()} event {handler.Method.Name}<{typeof(TEventArgs)}> has fired with {e}...\");\n\n handler(s, e);\n }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:15:54.307",
"Id": "486565",
"Score": "0",
"body": "Why the duplicate code, when the generic version can just be passed `EventArgs.Empty` if there isn't any event data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T20:41:47.797",
"Id": "486609",
"Score": "0",
"body": "@tinstaafl At the time, I didn't realize that EventHandler is actually equal to EventHandler<EventArgs>. Knowing that this can easily be simplified, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:45:29.280",
"Id": "486722",
"Score": "1",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. It simply gets too messy if we'd allow it. Feel free to ask a follow-up question instead and to add links to both questions back-and-forth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T22:22:08.640",
"Id": "486751",
"Score": "0",
"body": "@mast Fair enough - but then how do others learn of the solution that was derived from the review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T22:26:01.177",
"Id": "486752",
"Score": "0",
"body": "You can write a self-answer, as long as it reviews the code provided. Code-only answers are not reviews. If the points in those review are already made by other reviewers, please state so in the answer. Perhaps making it community-wiki and adding links in that answer would be helpful."
}
] |
[
{
"body": "<p>I would question what you intend with this system. In my personal experience, when someone writes something like this it's because they have no actual work assigned to them, but don't want their managers to realize that.</p>\n<p>Take a step back and ask yourself what is the improvement you gain from:</p>\n<ol>\n<li>Requiring an additional class to be present in every form inheritance tree.</li>\n<li>Making it so user controls aren't handled by this system (from the inside I mean, since your base class derives from <code>Form</code>).</li>\n<li>Requiring a manual line of code to handle creation and removal of events in one specific function (what if I want to add a handler at run-time? What if I want to use post-2002 lambda expressions instead of 6 lines of code for a simple handler? What if I want to use the designer, which handles renaming for me?)</li>\n<li>I don't think you even considered early event removal.</li>\n</ol>\n<p>You say you want to avoid forgetting to remove event handlers. Any properly written handler doesn't need to be removed, only handlers that strongly root the form object require this (and in this case it's not a memory leak exactly, it's your form not closing). And this system doesn't solve strong rooting, since it stores a non-weak-referenced list of these unsubscribe handlers, which reference your form, thus rooting the form in your object. You're literally creating the problem you're claiming to solve (refer back to my first statement).</p>\n<p>You don't show this, but what triggers the unsubscribe? The form's own dispose call? I hope not, because that won't trigger in a problem scenario with this code, and the fact that you mark this "manager" as <code>IDisposable</code> worries me greatly. The <code>FormClosing</code> event? I hope not, because that would prevent close cancellation. Yet another manual call to something? I hope not, because you're supposedly trying to automate ..something, not throw in more manual calls that always have to happen or BOOM.</p>\n<p>As to the actual code presented, it's not much, but at the very least write a bit of smart code to handle subscribing and unsubscribing automatically from a handle to the event and handler. You have expressions to parse code provided to your function and generate changed executable code from it, and you have code emitting, between those two you should be able to call your function like this at least:</p>\n<pre><code>EventManager.Attach(button1_Click, button1.Click);\n</code></pre>\n<p>Edit: Oh god I just noticed your <code>new</code> field modifier. Use proper OOP and you won't need a <code>GenericTrackedEvent<T></code> that's literally twice as large as the thing it "derives" from, since it has the previous fields as well as the <code>new</code> ones. And at the very least don't mark them <code>protected</code>, there's no reason for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T19:04:07.547",
"Id": "486592",
"Score": "1",
"body": "You cannot pass an event handler as you suggested. You'll receive an error that events can only be assigned on the left hand side of the operator. That was my first approach but it doesn't work. Playing devils advocate - maybe I missed something. How did you get that to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T15:11:13.590",
"Id": "486680",
"Score": "0",
"body": "It's one thing to ask how it's done, it's another to absolutely say \"you cannot do this\". I didn't implement this because it's rather trivial, but here you go, event attachment by reference: https://dotnetfiddle.net/9RLRsN. I trust you can do the unsubscription yourself from this, but if not feel free to ask (though Stack Overflow is really the place to ask *how* to do things, this is just code review)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T15:35:26.353",
"Id": "486683",
"Score": "0",
"body": "I probably didn't explain it correctly - trying to do this on an event in the same class works, but on a control's event does not. I should have cleared that part up. Expanding on your current suggestion to show the problem:\n\nhttps://dotnetfiddle.net/7L9wcV\n\nThat's why I suggested that it couldn't be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T15:56:05.407",
"Id": "486688",
"Score": "0",
"body": "Still doable with very minimal changes: https://dotnetfiddle.net/zZ0R0W"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:26:07.157",
"Id": "486693",
"Score": "0",
"body": "When I went down that path I didn't like the fact I had to pass in a string for the event name. Either it had a raw string so no direct reference to the event or the nameof expression which felt too clunky. So I was eager to find a solution without either.\n\nThen I was met with another impass. Either forego the control reference, or just accept the EventHandler/Delegate. As you already know, I went with the latter.\n\nBased on your feedback and several others, I went ahead and refactored the EventManager with more OOP's and features. I'll post it here shortly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:50:09.470",
"Id": "486704",
"Score": "0",
"body": "The pros of this method are that 1. you don't need to always specify `+=` and `-=` with the same code, 2. you don't need to have an external function handler, you can use lambas, as in my code, 3. while `nameof` is not ideal, it is checked at compile time so it's always correct and 4. there's absolutely no repetition in the call (DRY): you specify the object once, the event once and the handler once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:15:51.253",
"Id": "486717",
"Score": "0",
"body": "I suspect there's no reason why I can't provide more overloads to do both. At the end they funnel into the same internal tracker to unsubscribe them. So following up on your other previous comment. This example only shows a form but we allow it on forms and custom controls for sure. Next I intended to wire this up in the forms Dispose(bool disposing) method. You made it seems like a bad idea. Why? Other than abrupt unhandled errors - where's the downside? I read that its recommended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:20:06.627",
"Id": "486718",
"Score": "0",
"body": "It doesn't solve the problem you're trying to solve. `Dispose` is called when the form is garbage collected, sometime after it's closed. For it to get to that point naturally, your events have to not root the form (or the GC won't try to clean it), and if it gets to be disposed naturally, then there's no need to remove event handlers, they get automatically removed by the controls' `Dispose` logic (or more accurately cleaned up, since the Win32 API doesn't care about events)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T18:56:26.483",
"Id": "486728",
"Score": "1",
"body": "Might be best to move this to chat. Till then I checked out the code and close calls dispose directly.\nhttps://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Form.cs,3563"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T18:59:41.580",
"Id": "486729",
"Score": "0",
"body": "So the reason why the push for cleanups is this legacy application runs the entire business. It is a desktop level application that sits in front of our staff on the counter checking out customers or working with backend staff. They open and close hundreds of different forms each day and may not recycle the application for days/weeks/months."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T01:37:24.670",
"Id": "486855",
"Score": "0",
"body": "@Blindy Just a note for any future answers that you may provide: Being overwhelming condescending to the OP is not helpful and does not make you look more intelligent.\n\nThank you and good day."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:11:22.120",
"Id": "248413",
"ParentId": "248395",
"Score": "1"
}
},
{
"body": "<p>Look into the C# <strong>dynamic</strong> type which indicates that the variables type can change at runtime.</p>\n<p>For example,</p>\n<pre><code>dynamic event= "get_credentials";\n...\nevent= 5;\n...\nevent= someFunction;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:32:23.113",
"Id": "248474",
"ParentId": "248395",
"Score": "-4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T03:39:26.813",
"Id": "248395",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"generics",
"event-handling"
],
"Title": "C# One type to represent multiple types (including generics)"
}
|
248395
|
<p>In the past I created a <a href="https://codereview.stackexchange.com/questions/246089/compile-time-base64-converter">compile-time base64 converter</a> which I enjoyed doing as a challenge. As a result I wanted to do the challenge again causing me to create a compile-time Morse code translator.</p>
<p>here is the code:</p>
<pre><code>#include <iostream>
#include <numeric>
namespace morse
{
template<std::size_t N>
struct FixedString
{
wchar_t buf[N + 1]{};
constexpr FixedString() = default;
constexpr FixedString(wchar_t const *s)
{
std::copy(s, s + N, buf);
}
template<std::size_t S>
constexpr FixedString(FixedString<S> const &other)
{
std::copy(other.buf, other.buf + std::min(S, N), buf);
}
auto constexpr operator==(FixedString const &other) const
{
return std::equal(buf, buf + N, other.buf);
}
auto constexpr operator[](std::size_t index) const
{ return buf[index]; }
auto constexpr &operator[](std::size_t index)
{ return buf[index]; }
std::size_t constexpr size() const
{ return N; }
friend auto &operator<<(std::wostream &stream, const FixedString &string)
{
stream << string.buf;
return stream;
}
auto constexpr begin() { return buf; }
auto constexpr end() { return buf + N;}
auto const constexpr begin() const { return buf; }
auto const constexpr end() const { return buf + N;}
};
template<std::size_t N>
FixedString(wchar_t const (&)[N]) -> FixedString<N - 1>;
/* a linear binary tree of morse code */
FixedString static constexpr decode_map { L"<ETIANMSURWDKGOHVFÜL<PJBXCYZQÖ<54Ŝ3É<<2<È+<<<<16=/<<<<<7<<<8<90<<<<<<<<<<<<?_<<<<\"<<.<<<<@<<<'<<-<<<<<<<<;!<()<<<<<,<<<<:<<<<<<<" };
template<FixedString string>
auto constexpr encode()
{
/* std::toupper is not constexpr */
auto constexpr to_upper = [](auto const& ch) { return (L'a' < ch && ch < L'z') ? ch - (L'a' - L'A') : ch; };
auto constexpr find_letter_index = [](auto const& ch) {
return std::distance(decode_map.buf, std::find(decode_map.buf, decode_map.buf + decode_map.size(), ch));
};
auto constexpr letter_length = [](auto const &ch) {
std::size_t letter_index = std::distance(decode_map.buf, std::find(decode_map.buf, decode_map.buf + decode_map.size(), ch));
std::size_t result = 0;
for(;letter_index; --letter_index /= 2) result++;
return result;
};
std::size_t constexpr result_size = std::accumulate(string.buf, string.buf + string.size(), std::size_t {0},
[&](std::size_t total_size, auto const& ch) { return total_size + letter_length(to_upper(ch)) + 1; }) - !!string.size();
FixedString<result_size> result{};
std::size_t write_index = 0;
std::size_t old_write_index = 0;
std::size_t current_index = 0;
for(auto const &ch : string)
{
current_index = find_letter_index(to_upper(ch));
old_write_index = write_index;
for(;current_index; current_index /= 2)
result[write_index++] = L"-."[current_index--%2];
/* reverse */
std::reverse(result.buf + old_write_index, result.buf + write_index);
/* add a ' ' if we have enough space left */
if(write_index < result.size()) result[write_index++] = ' ';
}
return result;
}
template<FixedString string>
auto constexpr decode()
{
auto constexpr find_token_count = [] {
std::size_t result = 0;
for(std::size_t i = 0; i < string.size(); ++i)
{
result += i + 1 >= string.size() || (string[i] + 1 >> 1 == 23 && string[i + 1] == L' ');
}
return result;
};
std::size_t constexpr result_size = find_token_count();
FixedString<result_size> result{};
/* find first char that is not a space */
std::size_t read_index = std::distance(string.begin(), std::find_if(string.begin(), string.end(),
[](auto const& ch) { return ch != L' '; }));
std::size_t current_index = 0;
for(auto& ch : result)
{
current_index = 1;
for (;read_index < string.size() && string[read_index] != L' '; ++read_index)
current_index = current_index * 2 + (string[read_index] == L'-');
/* go over ' ' */
++read_index;
/* if char was not found replace it with a space */
ch = current_index > decode_map.size() ? L' ' : decode_map[current_index - 1];
}
return result;
}
}
int main()
{
constexpr morse::FixedString input_text { L"ABCDEFGHIJKLMNOP Q"};
auto constexpr encoded = morse::encode<input_text>();
auto constexpr decoded = morse::decode<encoded>();
static_assert(decoded == input_text);
std::wcout << decoded << L'\n';
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T07:28:58.253",
"Id": "248399",
"Score": "3",
"Tags": [
"c++"
],
"Title": "A compile-time morse code translator"
}
|
248399
|
<p>So I am currently doing an Assignment where I have to make a code that when someone opens the page, they input the weight of an egg and it comes back with what "size" it is.</p>
<p>I got the code working and I sent it to my teacher for feedback. However, she came back with telling me I should make the code more "Elegant and Efficient". But she did not instruct me how to do so. Any help on this topic will be greatly appreciated. Code is below</p>
<pre><code><script>
var eggWeight = prompt("Please enter an egg weight in grams: ");
parseInt(eggWeight);
while (isNaN(eggWeight)) {
eggWeight = prompt("This is not a valid number. Please an enter egg weight in grams: ");
parseInt(eggWeight);
}
if (eggWeight > 69)
alert('Jumbo');
else if (eggWeight > 63 && eggWeight <= 69)
alert('Extra Large');
else if (eggWeight > 55 && eggWeight <= 63)
alert('Large');
else if (eggWeight > 48 && eggWeight <= 55)
alert('Medium');
else if (eggWeight > 42 && eggWeight <= 48)
alert('Small');
else
alert('Peewee');
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T09:14:05.990",
"Id": "486524",
"Score": "11",
"body": "*\"But she did not instruct me how to do so.\"* Err, \"elegance\" is a very personal opinion. Note that reviewers might come up with more \"elegant\" versions, which still won't fit her definition. Please keep that in mind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T09:30:53.867",
"Id": "486525",
"Score": "2",
"body": "I'd probably start with showing the result at the website itself, insttead of using an `alert()` message box. Also were you explicitely assigned to use `prompt()` for this task? Otherwise I agree with @Zeta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T21:53:33.570",
"Id": "486623",
"Score": "2",
"body": "As a side note, you should never use `var` in Javascript. It breaks all sensible scoping rules. Use `let` or `const`, never `var`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T09:59:26.733",
"Id": "486657",
"Score": "3",
"body": "@CarsonGraham _Unless_ you have to support older browsers. [let support](https://caniuse.com/#feat=let) / [const support](https://caniuse.com/#feat=const) :("
}
] |
[
{
"body": "<p>Since you already checked <code>> 69</code> , if you get to the next <code>else if</code> you don't need to check that it is <code>&& eggWeight <= 69</code>, that is already known. The same applies to all of your <code><=</code> checks, so you can just remove them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T11:51:40.350",
"Id": "248407",
"ParentId": "248402",
"Score": "13"
}
},
{
"body": "<p>The <code>parseInt(eggWeight);</code> calls are not doing anything, because you are not using its return value. And since you aren't using the return value, the comparisons are all comparing a string against a number, which are only working by luck because the strings are automatically converted to numbers. Its always better to explicitly convert the strings to numbers by using <code>parseInt</code> properly and using its return value.</p>\n<p>Another thing: Always use braces with <code>if</code> in order to avoid errors:</p>\n<pre><code>if (eggWeight > 69) {\n alert('Jumbo');\n} else if (eggWeight > 63 && eggWeight <= 69) {\n /// etc...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T18:18:18.960",
"Id": "486581",
"Score": "0",
"body": "You write brackets, I guess from the snippet you mean braces? Bracket refers to []."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T19:37:12.393",
"Id": "486595",
"Score": "3",
"body": "@AlexanderWolters Both are valid names, see [wikipedia](https://en.wikipedia.org/wiki/Bracket#Curly_brackets) and [wiktionary](https://en.wiktionary.org/wiki/curly_bracket)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T19:59:35.063",
"Id": "486597",
"Score": "0",
"body": "@Klaycon If you had written curly bracket, sure. Not that it matters, the example makes it quite clear that it cannot mean the square brackets, but I still had to compare it to the snippet in the question to see the difference. Also, remember, most people will be familiar with US names, so bracket would refer to square ones by default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T07:05:57.253",
"Id": "486646",
"Score": "0",
"body": "\"Brackets\" was a typo. I've corrected it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:38:19.830",
"Id": "486697",
"Score": "3",
"body": "@AlexanderWolters \"brackets\" is often used as a general term for any kind of surrounding punctuation, encompassing parentheses, square brackets, curly braces, and angle braces (aka less-than and greater-than). But I agree that in this instance it's best to be specific."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T12:55:32.330",
"Id": "248410",
"ParentId": "248402",
"Score": "14"
}
},
{
"body": "<h1>Use form controls if in scope for the assignment</h1>\n<p>If it's in scope for the assignment, use an <code>input</code> field to take in the weight and an HTML element like a <code>div</code> or <code>span</code> to show the result. You could add a button to submit your response, or make it automatic. You can do this by hand or use a popular framework like React (though frameworks take a while to learn, so if you're short on time you might not want to go that route). But if you aren't expected to have learned form controls yet, then <code>prompt</code> and <code>alert</code> are fine. You'll need to judge that for yourself, asking your teacher if you're unsure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T18:14:54.560",
"Id": "248422",
"ParentId": "248402",
"Score": "5"
}
},
{
"body": "<p>This is a bit of an expansion from existing answers, applying some of the suggestions given before.</p>\n<hr>\n<p>First, pick a style of quotes. Dont flip-flop between single and double quotes.</p>\n<p>Here are 2 examples of it:</p>\n<pre><code>prompt("Please enter an egg weight in grams: ");\nalert('Peewee');\n</code></pre>\n<p>Due to <strong>personal preferences</strong>, I will be sticking to single-quotes.</p>\n<hr>\n<p>Something that everybody forgot was that everything can be turned into a function:</p>\n<pre><code>function getWeight()\n{\n var eggWeight = prompt('Please enter an egg weight in grams: ');\n eggWeight = parseInt(eggWeight);\n while(isNaN(eggWeight))\n {\n eggWeight = prompt('This is not a valid number. Please enter an egg weight in grams: ');\n eggWeight = parseInt(eggWeight);\n }\n \n return eggWeight;\n}\n\nfunction getEggDesignation(eggWeight)\n{\n if (eggWeight > 69)\n return 'Jumbo';\n else if (eggWeight > 63 && eggWeight <= 69)\n return 'Extra Large';\n else if (eggWeight > 55 && eggWeight <= 63)\n return 'Large';\n else if (eggWeight > 48 && eggWeight <= 55)\n return 'Medium';\n else if (eggWeight > 42 && eggWeight <= 48)\n return 'Small';\n else\n return 'Peewee';\n}\n\nfunction calculateEggDesignation()\n{\n var eggWeight = getWeight();\n \n var designation = getEggDesignation(eggWeight);\n \n alert(designation);\n}\n</code></pre>\n<p>This way, if you want to, say, receive input from a known element, you can just change the function related to gathering input.</p>\n<hr>\n<p>You make absolutely no efforts at all to see if the <code>prompt()</code> was cancelled.</p>\n<p>You can easily change it to detect if <a href=\"https://stackoverflow.com/a/12864637/\">the result is <code>null</code></a>:</p>\n<pre><code>function getWeight()\n{\n var eggWeight = prompt('Please enter an egg weight in grams: ');\n if(eggWeight === null)\n {\n return false;\n }\n eggWeight = parseInt(eggWeight);\n \n while(isNaN(eggWeight))\n {\n eggWeight = prompt('This is not a valid number. Please enter an egg weight in grams: ');\n if(eggWeight === null)\n {\n return false;\n }\n \n eggWeight = parseInt(eggWeight);\n }\n \n return eggWeight;\n}\n\nfunction getEggDesignation(eggWeight)\n{\n [...]\n}\n\nfunction calculateEggDesignation()\n{\n var eggWeight = getWeight();\n if(eggWeight === false)\n {\n // alert('You cancelled the calculation');\n return;\n }\n \n var designation = getEggDesignation(eggWeight);\n \n alert(designation);\n}\n</code></pre>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\">strict equality (<code>===</code>) operator</a> is <strong>required</strong>, due to being possible to accept <code>0</code> as an input.</p>\n<hr>\n<p>Now, focusing on the <code>getEggDesignation()</code> function, you can see a non-elegant <code>if</code> lasagna. Yuck.</p>\n<p>You can try to change it to use an object with the minimum weight per "designation":</p>\n<pre><code>function getEggDesignation(eggWeight)\n{\n var eggWeights = {\n 70: 'Jumbo',\n 64: 'Extra Large',\n 56: 'Large',\n 49: 'Medium',\n 43: 'Small',\n 0: 'Peewee'\n };\n\n var last_step = 0;\n var result = eggWeights[last_step];\n\n for(var k in eggWeights)\n {\n if(eggWeights.hasOwnProperty(k) && eggWeight >= k && k >= last_step)\n {\n result = eggWeights[k];\n last_step = k;\n }\n }\n \n return result;\n}\n</code></pre>\n<p>Isn't it a beauty? </p>\n<p>An alternative could be:</p>\n<pre><code>function getEggDesignation(eggWeight)\n{\n var eggWeights = {\n 70: 'Jumbo',\n 64: 'Extra Large',\n 56: 'Large',\n 49: 'Medium',\n 43: 'Small',\n 0: 'Peewee'\n };\n \n var newWeight = Object.keys(eggWeights)\n .map(function(weight){ return +weight; })\n .sort()\n .filter(function(weight){ return eggWeight >= weight; })\n .slice(-1);\n \n return eggWeights[newWeight];\n}\n</code></pre>\n<p>Basically, it grabs the keys, converts to integers, sorts them (ascending), removes the ones that are higher than <code>eggWeight</code> and picks the last one.</p>\n<p>This new value is then used to get the value from <code>eggWeights</code>.</p>\n<p><strong>Warning:</strong> Depending on the execution environment, you may need a polyfill for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\"><code>Object.keys()</code></a>, for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map()</code></a> and for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.prototype.filter()</code></a>. Possibly <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\"><code>Array.prototype.sort()</code></a> if you intend to run this on <strong>very</strong> old browsers.</p>\n<p><strong>For ES6:</strong></p>\n<p>If your execution environment is recent enough, you can just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>:</p>\n<pre><code>function getEggDesignation(eggWeight)\n{\n const eggWeights = {\n 70: 'Jumbo',\n 64: 'Extra Large',\n 56: 'Large',\n 49: 'Medium',\n 43: 'Small',\n 0: 'Peewee'\n };\n \n const newWeight = Object.keys(eggWeights)\n .map(weight => +weight})\n .sort()\n .filter(weight => eggWeight >= weight})\n .slice(-1);\n \n return eggWeights[newWeight];\n}\n</code></pre>\n<p>For compatibility sake, I will use the first alternative, despite needing a polyfill for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow noreferrer\"><code>Object.prototype.hasOwnProperty()</code></a> for <strong>very</strong> old browsers.</p>\n<hr>\n<p>Another thing I've noticed is that you do not validate the range of inputs at all.</p>\n<p>I can say that my egg is a black hole (-10000) and you'll say it is a Peewee.</p>\n<p>It's always good to verify if the value is <em>acceptable</em>.</p>\n<p>Changing part of the <code>getWeight()</code> function:</p>\n<pre><code>while(isNaN(eggWeight) || eggWeight < 0)\n{\n eggWeight = prompt('This is not a valid positive number. Please enter an egg weight in grams: ');\n [...]\n}\n</code></pre>\n<hr>\n<h1>The final code:</h1>\n<p>This is the final implementation, after all the changes:</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>function getWeight()\n{\n var eggWeight = prompt('Please enter an egg weight in grams: ');\n if(eggWeight === null)\n {\n return false;\n }\n eggWeight = parseInt(eggWeight);\n \n while(isNaN(eggWeight) || eggWeight < 0)\n {\n eggWeight = prompt('This is not a valid positive number. Please enter an egg weight in grams: ');\n if(eggWeight === null)\n {\n return false;\n }\n \n eggWeight = parseInt(eggWeight);\n }\n \n return eggWeight;\n}\n\nfunction getEggDesignation(eggWeight)\n{\n var eggWeights = {\n 70: 'Jumbo',\n 64: 'Extra Large',\n 56: 'Large',\n 49: 'Medium',\n 43: 'Small',\n 0: 'Peewee'\n };\n\n var last_step = 0;\n var result = eggWeights[last_step];\n\n for(var k in eggWeights)\n {\n if(eggWeights.hasOwnProperty(k) && eggWeight >= k && k >= last_step)\n {\n result = eggWeights[k];\n last_step = k;\n }\n }\n \n return result;\n}\n\nfunction calculateEggDesignation()\n{\n var eggWeight = getWeight();\n if(eggWeight === false)\n {\n // alert('You cancelled the calculation');\n return;\n }\n \n var designation = getEggDesignation(eggWeight);\n \n alert(designation);\n}\n\ncalculateEggDesignation();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:42:16.700",
"Id": "486699",
"Score": "2",
"body": "I'm surprised that the `for` loop works as intended. I thought that numeric object properties are ordered numericically, not the order that the properties were created."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T16:54:14.060",
"Id": "486706",
"Score": "0",
"body": "@Barmar The properties are actually re-ordered numerically. If you run `var eggWeights = {56: 'Large', 49: 'Medium', 64: 'Extra Large', 43: 'Small', 70: 'Jumbo', 0: 'Peewee'};`, it returns `{0: \"Peewee\", 43: \"Small\", 49: \"Medium\", 56: \"Large\", 64: \"Extra Large\", 70: \"Jumbo\", 105: \"barge\", 110: \"captain\"}`. At least in Blink-based browsers and Firefox."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:00:40.290",
"Id": "486709",
"Score": "1",
"body": "Oh, now I see that you don't break out of the loop when setting `result`. So you actually depend on them being in increasing order, not the order you wrote them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:01:51.137",
"Id": "486711",
"Score": "0",
"body": "@Barmar Yeah, I do. I can easily change it to be order-agnostic. Just 1 variable and 3 lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:02:41.760",
"Id": "486713",
"Score": "2",
"body": "I'm not sure how \"elegant\" that dependency is. It's not intuitive, and I don't think most JS experts recommend depending on it, even though it's now specified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:04:06.230",
"Id": "486714",
"Score": "1",
"body": "The general idea is right, but an array of `{weight: ##, designation: \"XXX\"}` objects is preferred, IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:12:28.617",
"Id": "486716",
"Score": "0",
"body": "@Barmar I've changed it to be order-agnostic. While I like your approach, I feel that the way I have is a lot easier to write and understand. It goes through the object, checks the key, sees if it is higher, assigns to the variable `result`, returns `result` at the end. However, an array like that can help a lot. There are other ways to make mine work, but well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T18:10:28.937",
"Id": "486724",
"Score": "1",
"body": "Many ways to skin the cat. The extra `last_step` variable solves the order problem, but feels \"ugly\" to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T06:22:44.123",
"Id": "486771",
"Score": "0",
"body": "you don't need to use hasOwnProperty here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T07:26:08.690",
"Id": "486775",
"Score": "0",
"body": "A short code review: There is a bug in `getWeight()`: You run `parseInt` before checking for `null`. You should prefer `const`/`let` over `var`. You shouldn't reuse variables. You could consider using a `do`/`while` loop in `getWeight()` in order to avoid duplicate code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:23:31.050",
"Id": "486776",
"Score": "0",
"body": "@Barmar I agree. I have an idea on how to write it in a pretty way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:25:09.953",
"Id": "486777",
"Score": "0",
"body": "@12Me21 I actually do. The O.P. didn't specify in which environment the code is meant to run. It could be Netscape, Internet Explorer or even on an old Mac. Do you know? I don't. I have to think about compatibility then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:27:07.147",
"Id": "486778",
"Score": "1",
"body": "@RoToRa I agree, I didn't notice the position of the `prseInt()`. I'm not going to use `const` or `let`. O.P. didn't specify in which environment this is meant to run. And I though about it, but that would change the code that the O.P. posted and change it's functionality. If you see, the message on the `prompt()` is different inside and outside the `while` loop. I can't change that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:45:25.050",
"Id": "486781",
"Score": "0",
"body": "Do you know of any old browsers where hasOwnProperty would be necessary, or is this just speculation? I've tested this in many different places and haven't had any problems. hasOwnProperty should only be needed if Object.prototype has enumerable properties (and if you can't trust Object.prototype then I'm not sure it's safe to rely on Object.prototype.hasOwnProperty either)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T08:59:25.240",
"Id": "486782",
"Score": "0",
"body": "@12Me21 Properties added to the prototype can be enumerable. The `.hasOwnProperty()` method tells you if the property is part of the object or the prototype chain. You can read more on https://stackoverflow.com/a/32422910/"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T10:49:41.537",
"Id": "248450",
"ParentId": "248402",
"Score": "8"
}
},
{
"body": "<p>There you go! It was the unnecessary over checking in the if statements. (the more efficient part)</p>\n<pre><code>const eggWeightString = prompt("Please enter an egg weight in grams: ");\nlet eggWeight = parseInt(eggWeightString);\nwhile (isNaN(eggWeight)) {\n eggWeight = parseInt(\n prompt("This is not a valid number. Please an enter egg weight in grams: ")\n );\n}\n\nif (eggWeight > 69)\n alert('Jumbo');\nelse if (eggWeight > 63)\n alert('Extra Large');\nelse if (eggWeight > 55)\n alert('Large');\nelse if (eggWeight > 48)\n alert('Medium');\nelse if (eggWeight > 42)\n alert('Small');\nelse\n alert('Peewee');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:05:18.683",
"Id": "486667",
"Score": "0",
"body": "you could use var instead of let and const"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:06:45.830",
"Id": "486668",
"Score": "0",
"body": "plus don't forget that parseInt returns a new number value and doesn't change the argument you pass it. So you must capture that return value and pass it to the isNaN function instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:07:37.397",
"Id": "486669",
"Score": "0",
"body": "I'd say don't use braces here because it's clear and using them will make things unclear"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T15:49:55.083",
"Id": "486685",
"Score": "0",
"body": "Instead of commenting, please [edit] your answer with the intended content."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:04:48.160",
"Id": "248458",
"ParentId": "248402",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:38:39.680",
"Id": "248402",
"Score": "7",
"Tags": [
"javascript",
"performance",
"homework"
],
"Title": "Egg size Prompt Box"
}
|
248402
|
<p>I recently wrote a piece of code to parallelise some code with goroutines and I was wondering if I could get some feedback. It looks overly complex... but I'm not sure how I could make it simpler.</p>
<p>It's self contained, so you can just copy-paste it into the Go Playground and run it. Here's a link if anybody's interested: <a href="https://play.golang.org/p/Dyg4kZXCS9b" rel="nofollow noreferrer">https://play.golang.org/p/Dyg4kZXCS9b</a></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
"sync"
)
func main() {
fmt.Println("Hello World")
input := []string{"foo", "bar", "baz"}
products, err := findProducts(input)
if err != nil {
panic(err)
}
fmt.Printf("\n %d", len(products))
}
type productInfo struct{}
func findProduct(productCode string) (*productInfo, error) {
return &productInfo{}, nil
}
func findProducts(productCodes []string) ([]*productInfo, error) {
wg := sync.WaitGroup{}
wg.Add(len(productCodes))
output := make(chan []*productInfo)
input := make(chan *productInfo)
errInput := make(chan error)
errOutput := make(chan []error)
// consumer goroutine
go func(input <-chan *productInfo, output chan<- []*productInfo, errInput <-chan error, errOutput chan<- []error, wg *sync.WaitGroup) {
var results []*productInfo
var errors []error
for {
select {
case result, ok := <-input:
if !ok {
input = nil
break
}
wg.Done()
fmt.Println("input received through channel: appending productInfo")
results = append(results, result)
case err, ok := <-errInput:
if !ok {
errInput = nil
break
}
wg.Done()
fmt.Println("error received through channel: appending err")
errors = append(errors, err)
}
if input == nil && errInput == nil {
break
}
}
output <- results
errOutput <- errors
}(input, output, errInput, errOutput, &wg)
for _, code := range productCodes {
go func(code string, input chan<- *productInfo, errInput chan<- error) {
p, err := findProduct(code)
if err != nil {
fmt.Println("sending error through channel")
errInput <- err
} else {
fmt.Println("sending input through channel")
input <- p
}
}(code, input, errInput)
}
wg.Wait()
close(input)
close(errInput)
products := <-output
errs := <-errOutput
// Just return the first one for simplicity
if len(errs) > 0 {
return nil, errs[0]
}
return products, nil
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T14:30:38.393",
"Id": "486911",
"Score": "0",
"body": "It's overly complex. One simpler way is https://play.golang.org/p/Uw9PxIn88bn if you can cancel the \"find\"s then using an [error group](https://godoc.org/golang.org/x/sync/errgroup) is probably worthwhile: https://play.golang.org/p/3Ai3ts3DZiQ"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T11:02:32.800",
"Id": "248405",
"Score": "1",
"Tags": [
"go",
"concurrency"
],
"Title": "Orchestrating an unknown number of goroutines"
}
|
248405
|
<p>preface: I have a part of my code that is repeated more than once and I want to create a generic method or follow a design pattern to make the code cleaner.</p>
<p><strong>What I'm trying to achieve is:</strong></p>
<ul>
<li>I have a JSON array each array represents a different type of employee.</li>
<li>I want to sort them by <code>joiningDate</code> then convert each List to JSON again then send them to the server.</li>
</ul>
<p>this following class represents data record for an employee.
<code>records</code> denotes the data and it's in JSON format.
I parse the records data depending on the <code>employeeType</code></p>
<pre><code>data class EmployeeRecord(
val recordId: Long?,
val employeeType: EmployeeType,
val records: String)
</code></pre>
<p>This is the employee type class</p>
<pre><code>@JsonClass(generateAdapter = false)
enum class EmployeeType(val role: String) {
CEO("CEO"),
CTO("CTO"),
Accountant("Accountant"),
Developer("Developer");
companion object {
val tierOneTypes: List<EmployeeType>
get() = listOf(
Developer,
Accountant
)
val tierTwoTypes: List<EmployeeType>
get() = listOf(
CEO,
CTO
)
}
}
</code></pre>
<p>this is the employee types</p>
<pre><code>sealed class EmployeeDataRecord(open val employeeType: EmployeeType)
@JsonClass(generateAdapter = true)
internal data class CeoData(
@Json(name = "JoiningDate") val joiningDate: Long,
@Json(name = "NumberOfBranches") val numberOfBranches: Int,
@Json(name = "Address") val address: String,
@Json(name = "Salary") val salary: Long
) : EmployeeDataRecord(EmployeeType.CEO) {
companion object {
fun create(
joiningDate: Long,
numberOfBranches: Int,
address: String,
salary: Long
): CeoData {
return CeoData(
joiningDate = joiningDate,
numberOfBranches = numberOfBranches,
address = address,
salary = salary
)
}
}
}
@JsonClass(generateAdapter = true)
internal data class CtoData(
@Json(name = "HiringDate") val joiningDate: Long,
@Json(name = "NumberOfTeams") val numberOfTeams: Int,
@Json(name = "Address") val address: String,
@Json(name = "Salary") val salary: Long
) : EmployeeDataRecord(EmployeeType.CTO) {
companion object {
fun create(
joiningDate: Long,
numberOfTeams: Int,
address: String,
salary: Long
): CtoData {
return CtoData(
joiningDate = joiningDate,
numberOfTeams = numberOfTeams,
address = address,
salary = salary
)
}
}
}
@JsonClass(generateAdapter = true)
internal data class AccountantData(
@Json(name = "JoiningDate") val joiningDate: Long,
@Json(name = "Address") val address: String,
@Json(name = "Salary") val salary: Long
) : EmployeeDataRecord(EmployeeType.Accountant) {
companion object {
fun create(
joiningDate: Long,
address: String,
salary: Long
): AccountantData {
return AccountantData(
joiningDate = joiningDate,
address = address,
salary = salary
)
}
}
}
@JsonClass(generateAdapter = true)
internal data class DeveloperData(
@Json(name = "JoiningDate") val joiningDate: Long,
@Json(name = "TeamName") val teamName: String,
@Json(name = "Address") val address: String,
@Json(name = "Salary") val salary: Long
) : EmployeeDataRecord(EmployeeType.Developer) {
companion object {
fun create(
joiningDate: Long,
teamName: String,
address: String,
salary: Long
): DeveloperData {
return DeveloperData(
joiningDate = joiningDate,
teamName = teamName,
address = address,
salary = salary
)
}
}
}
</code></pre>
<p>here is the function that has the repeated code; as you can see <code>createTierOneData</code> and <code>createTierTwoData</code> have the same logic and it's repeated</p>
<pre><code>class DataTest {
private fun <T> listAdapter(modelClass: Class<T>): JsonAdapter<List<T>> {
val type = Types.newParameterizedType(List::class.java, modelClass)
return moshi.adapter(type)
}
private fun createTierOneData(employeeRecords: List<EmployeeRecord>):
Pair<List<ServerAData>, List<ServerBData>> {
val serverADataList = mutableListOf<ServerAData>()
val serverBDataList = mutableListOf<ServerBData>()
val accountantDataList = mutableListOf<AccountantData>()
val developerDataList = mutableListOf<DeveloperData>()
employeeRecords.forEach {
if (it.employeeType in EmployeeType.tierOneTypes) {
when (it.employeeType) {
EmployeeType.Accountant -> listAdapter(AccountantData::class.java).fromJson(
it.records
)?.let { records -> accountantDataList.addAll(records) }
EmployeeType.Developer -> listAdapter(DeveloperData::class.java).fromJson(
it.records
)?.let { records -> developerDataList.addAll(records) }
}
}
}
if (accountantDataList.isNotEmpty()) {
if (accountantDataList.size > 1) {
accountantDataList.sortBy { it.joiningDate }
}
val serverAData = ServerAData(
EmployeeType.Accountant,
listAdapter(AccountantData::class.java).toJson(accountantDataList)
)
val serverBData = ServerBData(
EmployeeType.Developer, developerDataList.size,
159025890000
)
serverADataList.add(serverAData)
serverBDataList.add(serverBData)
}
if (developerDataList.isNotEmpty()) {
if (developerDataList.size > 1) {
developerDataList.sortBy { it.joiningDate }
}
val serverAData = ServerAData(
EmployeeType.Developer,
listAdapter(DeveloperData::class.java).toJson(developerDataList)
)
val serverBData = ServerBData(
EmployeeType.Developer, developerDataList.size,
159025890000
)
serverADataList.add(serverAData)
serverBDataList.add(serverBData)
}
return Pair(serverADataList, serverBDataList)
}
private fun createTierTwoData(employeeRecords: List<EmployeeRecord>):
Pair<List<ServerAData>, List<ServerBData>> {
val serverADataList = mutableListOf<ServerAData>()
val serverBDataList = mutableListOf<ServerBData>()
val ctoDataList = mutableListOf<CtoData>()
val ceoDataList = mutableListOf<CeoData>()
employeeRecords.forEach {
if (it.employeeType in EmployeeType.tierTwoTypes) {
when (it.employeeType) {
EmployeeType.CTO -> listAdapter(CtoData::class.java).fromJson(
it.records
)?.let { records -> ctoDataList.addAll(records) }
EmployeeType.CEO -> listAdapter(CeoData::class.java).fromJson(
it.records
)?.let { records -> ceoDataList.addAll(records) }
}
}
}
if (ctoDataList.isNotEmpty()) {
if (ctoDataList.size > 1) {
ctoDataList.sortBy { it.joiningDate }
}
val serverAData = ServerAData(
EmployeeType.CTO,
listAdapter(CtoData::class.java).toJson(ctoDataList)
)
val serverBData = ServerBData(
EmployeeType.CTO, ctoDataList.size,
159025890000
)
serverADataList.add(serverAData)
serverBDataList.add(serverBData)
}
if (ceoDataList.isNotEmpty()) {
if (ceoDataList.size > 1) {
ceoDataList.sortBy { it.joiningDate }
}
val serverAData = ServerAData(
EmployeeType.CEO,
listAdapter(CeoData::class.java).toJson(ceoDataList)
)
val serverBData = ServerBData(
EmployeeType.CEO, ceoDataList.size,
159025890000
)
serverADataList.add(serverAData)
serverBDataList.add(serverBData)
}
return Pair(serverADataList, serverBDataList)
}
}
</code></pre>
<p>and finally here are the ServersData classes</p>
<pre><code>data class ServerAData(
val type: EmployeeType,
val dataRecord: String
)
data class ServerBData(
val type: EmployeeType,
val numberOfDataRecord: Int,
val hiringDate: Long
)
</code></pre>
<p>so I am trying to find a way to refactor <code>createTierOneData</code> and <code>createTierTwoData</code> to apply DRY. I tried to make a generic function and I failed to do it properly.
is there an approach to make these methods generic?</p>
<p>or if you can guide me to a design pattern that I can apply here that would be great.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T20:52:21.130",
"Id": "486610",
"Score": "0",
"body": "@Tenfour04 the point here is the logic is the same, for each list I have to check if is not empty then sort it the construct two objects. so I want to remove this repeated code or do it in a smarter way."
}
] |
[
{
"body": "<p>I'd add the data class type to the enum entries (or alternatively you could put these in a global map).</p>\n<pre><code>@JsonClass(generateAdapter = false)\nenum class EmployeeType(val role: String, val dataType: Class<out EmployeeDataRecord>) {\n CEO("CEO", CeoData::class.java),\n CTO("CTO", CtoData::class.java),\n Accountant("Accountant", AccountantData::class.java),\n Developer("Developer", DeveloperData::class.java);\n\n companion object {\n //...\n }\n}\n</code></pre>\n<p>Since we're using covariant Class type, update the parameter for <code>listAdapter()</code> as well:</p>\n<pre><code>private fun <T> listAdapter(modelClass: Class<out T>): JsonAdapter<List<T>> {\n</code></pre>\n<p>Also, you are sorting all the data types by <code>joiningDate</code>, so it would help to make that a member of the super class:</p>\n<pre><code>sealed class EmployeeDataRecord(open val employeeType: EmployeeType){\n abstract val joiningDate: Long\n}\n\n@JsonClass(generateAdapter = true)\ninternal data class CeoData(\n @Json(name = "JoiningDate") override val joiningDate: Long,\n @Json(name = "NumberOfBranches") val numberOfBranches: Int,\n @Json(name = "Address") val address: String,\n @Json(name = "Salary") val salary: Long\n) : EmployeeDataRecord(EmployeeType.CEO) { \n //...\n}\n//etc.\n</code></pre>\n<p>Then you can add a parameter for a list of the types to process. When you call this function you can pass <code>EmployeeType.tierOneTypes</code> or <code>EmployeeType.tierTwoTypes</code>. This makes it flexible if you modify the input types. You can loop through this list (even though it's just a list of two) since you're doing the same thing to both input types. But you could change it to a list of any size and this function would still work.</p>\n<p>To process the input, you could set up MutableLists and <code>forEach</code> like you're already doing, but it's more concise (and easier to read) to use <code>associateWith</code> and <code>flatMap</code>.</p>\n<pre><code>private fun createData(employeeRecords: List<EmployeeRecord>, typesToProcess: Iterable<EmployeeType>):\n Pair<List<ServerAData>, List<ServerBData>> {\n\n val employeeDataListsByType = typesToProcess.associateWith { type ->\n employeeRecords.filter { it.employeeType == type }\n .flatmap { listAdapter(type.dataType).fromJson(it.records) ?: emptyList() }\n .sortedBy(EmployeeDataRecord::joiningDate)\n }\n\n val serverADataList = employeeDataListsByType.mapNotNull { (type, list) ->\n if (list.isEmpty())\n null\n else\n ServerAData(type, listAdapter(type.dataType).toJson(list))\n }\n\n val serverBDataList = employeeDataListsByType.mapNotNull { (type, list) ->\n if (list.isEmpty())\n null\n else\n ServerBData(type, list.size, 159025890000)\n }\n\n return Pair(serverADataList, serverBDataList)\n\n}\n</code></pre>\n<p>Depending on the size of your data, it might be more efficient to insert <code>.toSequence()</code> before the <code>filter</code> call, and then add <code>.toList()</code> after the <code>sortedBy</code> call</p>\n<p>I didn't test this so I might have a few syntax errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T15:54:46.730",
"Id": "486686",
"Score": "0",
"body": "Thanks for answering. I like what you did with the emum ```EmployeeType``` the only thing that didn't work out for me is that I want the map to contain the value of the sub data type, not the super data type. for example, the map is of type ```<EmployeeType, List<EmployeeDataRecord>>```, but I want it to be ```<EmployeeType, List<CeoData>>```, because when I try to create ServerAData the listAdapter doesn't work because it expects subtype. I get an error that ```toJson``` expects `Nothing`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T17:38:35.133",
"Id": "486720",
"Score": "0",
"body": "Try changing the type of the `modelClass` parameter of `listAdapter()` to `Class<out T>`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:27:39.717",
"Id": "248460",
"ParentId": "248415",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248460",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T16:30:59.020",
"Id": "248415",
"Score": "4",
"Tags": [
"object-oriented",
"design-patterns",
"generics",
"kotlin"
],
"Title": "Representation of data record for an employee (generic method vs design pattern)"
}
|
248415
|
<p>Looking around for modern Crypto libraries.<br />
Could not find anything good.</p>
<p>I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:</p>
<ol>
<li>Hashing</li>
<li><a href="https://codereview.stackexchange.com/q/248417/507">Hashed Key</a></li>
<li><a href="https://codereview.stackexchange.com/q/248418/507">Password Key</a></li>
<li><a href="https://codereview.stackexchange.com/q/248419/507">Salted Challenge Response</a></li>
</ol>
<p>This is the hashing code and provides a simple wrapper around SHA-1 and SHA-256 but the pattern is simple enough that we can expand it for other hashing mechanisms.</p>
<p>The data structures and implementation presented in these questions are based on <a href="https://www.rfc-editor.org/rfc/rfc2104" rel="nofollow noreferrer">RFC2104</a> and this post on <a href="https://www.codeproject.com/Articles/22118/C-Class-Implementation-of-HMAC-SHA" rel="nofollow noreferrer">codeproject</a>.</p>
<h2>Usage Example:</h2>
<pre><code>DigestStore<Sha1> hash; // <- destination of hash
Sha1 hasher;
hasher.hash("This string can be hashsed", hash);
</code></pre>
<h2>hash.h</h2>
<pre><code>#ifndef THORS_ANVIL_CRYPTO_HASH_H
#define THORS_ANVIL_CRYPTO_HASH_H
#ifdef __APPLE__
#define COMMON_DIGEST_FOR_OPENSSL
#include <CommonCrypto/CommonDigest.h>
#define THOR_SHA1(data, len, dst) CC_SHA1(data, len, dst)
#define THOR_SHA256(data, len, dst) CC_SHA256(data, len, dst)
#else
#include <openssl/sha.h>
#define THOR_SHA1(data, len, dst) SHA1(data, len, dst)
#define THOR_SHA256(data, len, dst) SHA256(data, len, dst)
#endif
#include <string>
#include <array>
//
// Wrapper for sha1 and sha256 hashing algorithms
//
// Provides a simple wrapper class with the appropriates types and size
// for the resulting "digest" object. Also provides several type safe
// versions of the hashing algorithm to allow multiple know types to
// be safely hashed.
namespace ThorsAnvil::Crypto
{
using Byte = char unsigned;
using DigestPtr = Byte*;
template<typename Hash>
using Digest = typename Hash::DigestStore;
template<std::size_t size>
class DigestStore
{
std::array<Byte, size> data;
public:
using iterator = typename std::array<Byte, size>::iterator;
operator Digest() {return &data[0];}
std::string_view view() {return std::string_view(reinterpret_cast<char const*>(&data[0]), std::size(data));}
Byte& operator[](std::size_t i) {return data[i];}
iterator begin() {return std::begin(data);}
iterator end() {return std::end(data);}
};
// These versions of the hashing function are good for hashing short
// amounts of text. Use these for passwords and validation hashes
// do not use them for hashing large documents.
struct Sha1
{
static constexpr std::size_t digestSize = SHA_DIGEST_LENGTH;
using DigestStore = DigestStore<SHA_DIGEST_LENGTH>;
void hash(DigestStore& src, DigestStore& dst) {THOR_SHA1(src, SHA_DIGEST_LENGTH, dst);}
void hash(std::string_view src, DigestStore& dst) {THOR_SHA1(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
void hash(std::string const& src, DigestStore& dst) {THOR_SHA1(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
// Use only if you know the destination is large enough!!
void hashUnsafe(std::string_view src, DigestPtr dst) {THOR_SHA1(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
};
struct Sha256
{
static constexpr std::size_t digestSize = SHA256_DIGEST_LENGTH;
using DigestStore = DigestStore<SHA256_DIGEST_LENGTH>;
void hash(DigestStore& src, DigestStore& dst) {THOR_SHA256(src, SHA256_DIGEST_LENGTH, dst);}
void hash(std::string_view src, DigestStore& dst) {THOR_SHA256(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
void hash(std::string const& src, DigestStore& dst) {THOR_SHA256(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
// Use only if you know the destination is large enough!
void hashUnsafe(std::string_view src, Digestptr dst) {THOR_SHA256(reinterpret_cast<Byte const*>(&src[0]), std::size(src), dst);}
};
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T21:02:12.770",
"Id": "486613",
"Score": "1",
"body": "@Emma I had not. Looks like I will need to start using one of those. But I just hate reading these badly written C++ (which is why I started this hack) projects that are crappy wrappers around C rather than using good type safety and nice clean C++ interfaces and techniques. Though I did enjoy writting these if I do any hard core stuff I will definetly use a proper library but these simple classes will let me do some quick checks (which is currently writting a C++ Mongo interface (and yes I know one exists but I can write a better one). Using ThorsSerializer to automate the serialization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:23:58.163",
"Id": "486625",
"Score": "1",
"body": "`too clean`. I'll take it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:24:55.150",
"Id": "486626",
"Score": "1",
"body": "@Emma: Priority 1: Impossible (or really hard for the user to break) to break. 2: Ease of use. 3: Speed."
}
] |
[
{
"body": "<p>I think I am going to change the interface.</p>\n<p>Currently the usage patter is:</p>\n<pre><code>typename Sha1::DigestStore digest;\nSha1 hasher;\n\nhasher.hash("Bob", digest);\n</code></pre>\n<p>There does not seem a need to create a <code>Sha1</code> object. I think a better interface may be to make all the methods <code>static</code> so the usage becomes:</p>\n<pre><code>typename Sha1::DigestStore digest;\n\nSha1::hash("Bob", digest);\n</code></pre>\n<p>The <code>DigestStore</code> may need some other accesses functions. It currently allows <code>iteration</code> but there can be a use case where we have a <code>const_iterator</code>.</p>\n<p>Still trying to understand when best to use <code>string_view</code>. Unfortunately it still does not play well with normal strings. So we may have to provide a way to also extract a string from the buffer. In that case it would be nice if we could have the data from the DigestStore into a string (which means not using <code>std::array</code>) but need to have a good use case to make that work better.</p>\n<p>Not sure how that will work yet. Please provide a hint if you have am idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:27:27.907",
"Id": "248431",
"ParentId": "248416",
"Score": "1"
}
},
{
"body": "<h1>Proper capitalization of SHA1</h1>\n<p>The algorithm's name is SHA1, not Sha1, so I think it is better to use all caps here. That makes grepping the code for a particular algorithm easier.</p>\n<h1>You only need one class per hash algorithm</h1>\n<p>Indeed, as you mentioned in your own answer, the <code>Sha1</code> class seems superfluous, since it doesn't store any state. However, instead of creating static functions inside a <code>Sha1</code> namespace, you could make those functions member functions of the class that holds the actual state. This avoids repeating the type; for example:</p>\n<pre><code>Sha1::DigestStore digest;\nSha1::hash("Bob", digest)\n</code></pre>\n<p>Becomes:</p>\n<pre><code>Sha1::DigestStore digest;\ndigest.hash("Bob");\n</code></pre>\n<h1><code>Sha1::Digest</code> vs. <code>Digest<Sha1></code></h1>\n<p>I think having a namespace <code>Sha1</code> with a <code>DigestStore</code> and functions inside it is a bad choice. There is more you can do with SHA1 than just create plain hashes, for example you might want to create a <a href=\"https://en.wikipedia.org/wiki/HMAC\" rel=\"nofollow noreferrer\">HMAC</a> instead of a plain hash. So you would have to add functions to create a HMAC to each namespace that implements a hash algorithm. It's much better to have classes <code>Digest</code> and <code>HMAC</code> that are templated on the hash algorithm.</p>\n<h1>Allow hashes to be updated</h1>\n<p>The code you wrote only performs one-shot conversions of some input to a hash. However, it is not uncommon for programs to not have all the data they want to create a hash for in a single, contiguous memory region. In those cases, you want to write:</p>\n<pre><code>std::ostream output;\nDigest<SHA1> digest;\n\ndigest.add("Header");\ndigest.add("Data");\ndigest.add("Footer");\n\noutput << digest.view();\n</code></pre>\n<p>Some digest algorithms might require you to call some function to calculate the final hash value after adding all the data. You could add an explicit <code>finish()</code> function or call this implicitly when accessing the digest result.</p>\n<h1>Getting the result out</h1>\n<p>You internally store the hash as a <code>std::array<std::byte, size></code>. That's the proper thing to do. I don't think it is necessary to provide any member functions other than one that gets you a <code>const</code> reference to that array. It's up to the caller to convert it to whatever form they way. A <code>std::array</code> is already implicitly convertible to a <code>std::span</code>. And once you have a reference to the array, it's easy to get the begin and end iterators from it.</p>\n<h1>Add comparison operators</h1>\n<p>It's quite common to want to check whether two hashes are identical, so it would be helpful to at least define <code>operator==()</code> and <code>operator!=()</code> to the class that holds the digest result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T17:22:20.510",
"Id": "486821",
"Score": "0",
"body": "I had to think about it overnight. But I think I like the idea of putting the `hash()` method on the `Digest` object. Not 100% sure how to design it yet. But look for a review soon. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T17:23:35.513",
"Id": "486822",
"Score": "0",
"body": "I wanted to name the types `SHA1` but an all uppercase name makes my skin crawl (thinking of Macros). Not sure how to proceed here, I have to overcome my dread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T17:26:17.353",
"Id": "486824",
"Score": "0",
"body": "I was planning on adding an ability to update (add more text) as its a common feature for hashing. Currently I did not do it because I was only doing it for short pieces of text not document sized text. But long term that is definitely something I want to add; I just don't have a use case that I can experiment on with the interface."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T20:58:08.227",
"Id": "248481",
"ParentId": "248416",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T16:59:41.880",
"Id": "248416",
"Score": "4",
"Tags": [
"c++",
"cryptography",
"authentication",
"server",
"client"
],
"Title": "C++ Crypto: Part 1- Hash"
}
|
248416
|
<p>Looking around for modern Crypto libraries.<br />
Could not find anything good.</p>
<p>I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:</p>
<ol>
<li><a href="https://codereview.stackexchange.com/q/248416/507">Hashing</a></li>
<li>Hashed Key</li>
<li><a href="https://codereview.stackexchange.com/q/248418/507">Password Key</a></li>
<li><a href="https://codereview.stackexchange.com/q/248419/507">Salted Challenge Response</a></li>
</ol>
<p>The data structures and implementation presented in these questions are based on <a href="https://www.rfc-editor.org/rfc/rfc2104" rel="nofollow noreferrer">RFC2104</a> and this post on <a href="https://www.codeproject.com/Articles/22118/C-Class-Implementation-of-HMAC-SHA" rel="nofollow noreferrer">codeproject</a>.</p>
<p>This review is for an implementation of HMAC. This is a technique for hashing password using a Key.</p>
<h2>Usage Exmple:</h2>
<pre><code>Digest<HMac<Sha1>> digest;
HMac<Sha1> hasher;
hasher.hash("This is the Key", "This is the message", digest);
</code></pre>
<h2>hmac.h</h2>
<pre><code>#ifndef THORS_ANVIL_CRYPTO_HMAC_H
#define THORS_ANVIL_CRYPTO_HMAC_H
#include "hash.h"
// HMAC: Keyed-Hashing for Message Authentication RFC-2104
namespace ThorsAnvil::Crypto
{
// Look in hash.h for good examples of THash
// ThorsAnvil::Crypto::Sha1
template<typename THash>
struct HMac
{
static constexpr std::size_t digestSize = THash::digestSize;
using Hash = THash;
using DigestStore = typename Hash::DigestStore;
void hash(std::string_view key, std::string_view message, DigestStore& digest)
{
Hash hasher;
enum { BLOCK_SIZE = 64 };
/* STEP 1 */
std::array<Byte, BLOCK_SIZE> SHA1_Key{'\x00'};
if (key.size() > BLOCK_SIZE)
{
hasher.hashUnsafe(key, &SHA1_Key[0]);
}
else
{
std::copy(std::begin(key), std::end(key), &SHA1_Key[0]);
}
/* STEP 2 */
std::string ipad;
std::string opad;
ipad.reserve(BLOCK_SIZE + std::size(message));
opad.reserve(BLOCK_SIZE + digestSize);
ipad.resize(BLOCK_SIZE, '\x36');
opad.resize(BLOCK_SIZE, '\x5c');
for (int i=0; i< BLOCK_SIZE; i++)
{
ipad[i] ^= SHA1_Key[i];
opad[i] ^= SHA1_Key[i];
}
/* STEP 3 */
std::copy(std::begin(message), std::end(message), std::back_inserter(ipad));
/* STEP 4 */
opad.resize(BLOCK_SIZE + digestSize);
hasher.hashUnsafe(ipad, reinterpret_cast<Byte*>(&opad[BLOCK_SIZE]));
/* STEP 5 */
// Moved XOR of opad to STEP 2
/* STEP 6 */
// Don't need to copy the hash of ipad onto opad as we hashed
// into the correct destination.
/*STEP 7 */
hasher.hash(opad, digest);
}
};
}
#endif
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid using the same type to store the results of plain digests and HMACs</h1>\n<p>You can't (or at least should never be able to) compare a HMAC to a plain digest. So would be good if the type system could catch that potential mistake. Instead of having a <code>DigestStore<Hash></code> class that is used both for plain digests and HMACs, I would just have <code>Digest<Hash></code> and <code>HMAC<Hash></code> each store their own result directly.</p>\n<h1>Allow adding data to the HMAC in multiple steps</h1>\n<p>As mentioned in the review for part 1, it is not uncommon to have to add multiple, discontiguous pieces of data to be added to the HMAC, so have a member function <code>add()</code> that can update the HMAC. This would mean splitting the creation of the HMAC in three parts:</p>\n<ol>\n<li>The key material is prepared as part of the constructor</li>\n<li>The message is added to the hash, either in one go or using multiple function calls</li>\n<li>The final value is calculated</li>\n</ol>\n<p>I would structure the class like so:</p>\n<pre><code>template<typename Hash>\nclass HMAC {\n Digest<Hash> outer_digest;\n Digest<Hash> inner_digest;\n\npublic:\n HMAC(std::string_view key) {\n // Add key XOR opad to outer_digest\n // Add key XOR ipad to inner_digest\n }\n\n // Convenience constructor to do a one-shot HMAC creation\n HMAC(std::string_view key, std::string_view message): HMAC(key) {\n add(message);\n finish();\n }\n\n void add(std::string_view message) {\n // Add message to inner_digest\n }\n\n void finish() {\n // Finish inner_digest, add it to outer_digest\n // Finish outer_digest\n }\n\n // Something to get the bits out\n const auto &get() {\n return outer_digest.get();\n }\n};\n</code></pre>\n<p>You might also want to add some way to prevent <code>finish()</code> from being called more than once.</p>\n<h1>Avoid unsafe operations</h1>\n<p>Your own words:</p>\n<blockquote>\n<p>I just hate reading these badly written C++ (which is why I started this hack) projects that are crappy wrappers around C rather than using good type safety and nice clean C++ interfaces and techniques.</p>\n</blockquote>\n<p>You want good type safety, but I also think you want good safety in general. Creating unsafe functions goes against that goal. If you store the results of a hash in a <code>Digest</code> object, and have a way to get a const reference to the data it stores, then you don't need a <code>hashUnsafe()</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T21:33:16.907",
"Id": "248484",
"ParentId": "248417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T17:01:04.740",
"Id": "248417",
"Score": "4",
"Tags": [
"c++",
"cryptography",
"authentication",
"server",
"client"
],
"Title": "C++ Crypto: Part 2- HMAC"
}
|
248417
|
<p>Looking around for modern Crypto libraries.<br />
Could not find anything good.</p>
<p>I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:</p>
<ol>
<li><a href="https://codereview.stackexchange.com/q/248416/507">Hashing</a></li>
<li><a href="https://codereview.stackexchange.com/q/248417/507">Hashed Key</a></li>
<li>Password Key</li>
<li><a href="https://codereview.stackexchange.com/q/248419/507">Salted Challenge Response</a></li>
</ol>
<p>This review is for an implementation of pbkdf2 implementation. This is a way of using HMAC that allows you to make incrementally more expensive to create the hash on failures. The idea is that you can slow down attacks by making it harder to make lots of guesses.</p>
<p>The data structures and implementation presented in these questions are based on <a href="https://www.rfc-editor.org/rfc/rfc2104" rel="nofollow noreferrer">RFC2104</a> and this post on <a href="https://www.codeproject.com/Articles/22118/C-Class-Implementation-of-HMAC-SHA" rel="nofollow noreferrer">codeproject</a>.</p>
<h2>Usage Example</h2>
<pre><code>Digest<Pbkdf2<HMac<Sha1>>> digest;
Pbkdf2<HMac<Sha1>> pbkdf2;
pbkdf2.hash("The password", "A Salt", 2048, digest);
</code></pre>
<h2>pbkdf2.h</h2>
<pre><code>#ifndef THORS_ANVIL_CRYPTO_PBKDF2_H
#define THORS_ANVIL_CRYPTO_PBKDF2_H
#include "hmac.h"
#include <string>
// RFC-2898 PKCS #5: Password-Based Cryptography Specification Version 2.0
namespace ThorsAnvil::Crypto
{
// Look in hmac.h for good examples of PRF
// ThorsAnvil::Crypto::HMac
template<typename PRF>
struct Pbkdf2
{
static constexpr std::size_t digestSize = PRF::digestSize;
using DigestStore = typename PRF::DigestStore;
void hash(std::string const& password, std::string const& salt, long iter, DigestStore& digest)
{
#pragma vera-pushoff
using namespace std::string_literals;
#pragma vera-pop
PRF prf;
DigestStore tmp;
prf.hash(password, salt + "\x00\x00\x00\x01"s, tmp);
std::copy(std::begin(tmp), std::end(tmp), std::begin(digest));
for (int loop = 1; loop < iter; ++loop)
{
prf.hash(password, tmp.view(), tmp);
for (std::size_t loop = 0; loop < digestSize; ++loop)
{
digest[loop] = digest[loop] ^ tmp[loop];
}
}
}
};
}
#endif
</code></pre>
|
[] |
[
{
"body": "<pre><code>void hash(std::string const& password, std::string const& salt, long iter, DigestStore& digest)\n...\nfor (int loop = 1; loop < iter; ++loop)\n ...\n for (std::size_t loop = 0; loop < digestSize; ++loop)\n</code></pre>\n<p>"A <code>long</code> an <code>int</code> and a <code>std::size_t</code> all walked into a bar..." couldn't they all be <code>std::size_t</code>?</p>\n<p>Also, overriding the <code>loop</code> variable is unnecessarily confusing.</p>\n<hr />\n<pre><code> std::copy(std::begin(tmp), std::end(tmp), std::begin(digest));\n</code></pre>\n<p>I feel like this could just be <code>digest = tmp;</code> with an appropriate assignment operator.</p>\n<hr />\n<pre><code>salt + "\\x00\\x00\\x00\\x01"s\n</code></pre>\n<p>Could this be a named constant (or even a named function)? Or maybe add a comment to explain why this is here.</p>\n<hr />\n<pre><code> digest[loop] = digest[loop] ^ tmp[loop];\n</code></pre>\n<p>Nitpick: could use <code>^=</code></p>\n<hr />\n<p>Perhaps the output should be a return value, not written to a reference?</p>\n<hr />\n<p>I don't know enough about cryptography / security to assess the algorithm / safety aspects of this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:47:31.470",
"Id": "252158",
"ParentId": "248418",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T17:02:31.430",
"Id": "248418",
"Score": "3",
"Tags": [
"c++",
"cryptography",
"authentication",
"server",
"client"
],
"Title": "C++ Crypto:Part 3-pbkdf2"
}
|
248418
|
<p>Looking around for modern Crypto libraries.<br />
Could not find anything good.</p>
<p>I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:</p>
<ol>
<li><a href="https://codereview.stackexchange.com/q/248416/507">Hashing</a></li>
<li><a href="https://codereview.stackexchange.com/q/248417/507">Hashed Key</a></li>
<li><a href="https://codereview.stackexchange.com/q/248418/507">Password Key</a></li>
<li>Salted Challenge Response</li>
</ol>
<p>This is an implementation of the scram protocol that makes sure we don't send the password across the wire. Underneath it uses pbkdf2 to make sure that multiple attempts are appropriately punished. This is a multi-phase verification:</p>
<ol>
<li>Client Sends message to service with username.</li>
<li>Server Sends a hashed message with a salt for the client.</li>
<li>Client computes a response based on the salt and the password it has sends it to server.</li>
<li>Server verifies Client and then generates a response to prove that it also knows the password.</li>
</ol>
<p>Note: There may be an optional part of communication between client and server to negotiate the protocol that is bing used. I have set the 'ClientScram' to use <code>Pbkdf2<HMac<Sha1>></code> if I get some experience on other protocols I may adjust these.</p>
<p>The data structures and implementation presented in these questions are based on <a href="https://www.rfc-editor.org/rfc/rfc2104" rel="nofollow noreferrer">RFC2104</a> and this post on <a href="https://www.codeproject.com/Articles/22118/C-Class-Implementation-of-HMAC-SHA" rel="nofollow noreferrer">codeproject</a>.</p>
<h2>Usage Example</h2>
<pre><code>MyPersonalNonceGenerator noncer;
ClientScram scram("Loki", noncer);
std::string clientFirstMessage = scram.getFirstMessage();
std::string serverFirstMessage = /* send client message to server and get response */;
std::string proof = scram.getProofMessage("password", serverFirstMessage);
std::string serverProof = /* send client prrof to server and get response *./
if (scram.verifyServer(serverProof))
{
// You have validated that you and the server know the same password for the user
}
</code></pre>
<h2>scram.h</h2>
<pre><code>#ifndef THORSANVIL_CRYPTO_SCRAM_H
#define THORSANVIL_CRYPTO_SCRAM_H
#include "hash.h"
#include "hmac.h"
#include "pbkdf2.h"
#include "base64.h"
// RFC-5801 Salted Challenge Response Authentication Mechanism (SCRAM) SASL and GSS-API Mechanisms
namespace ThorsAnvil::Crypto
{
enum class DBInfoType
{
Password,
Salt
};
using NonceGenerator = std::function<std::string()>;
using DBInfoAccess = std::function<std::string(DBInfoType, std::string const&)>;
// See below in ScramClient and SCramServer for examples of Hi/HMAC/H
// Hi = Pbkdf2<HMac<Sha1>>
// HMAC = HMac<Sha1>
// H = Sha1
template<typename Hi, typename HMAC, typename H>
class ScramBase
{
std::string getMessageBody(std::string const& section, std::string const& message) const
{
auto findSection = message.find(section);
if (findSection == std::string::npos || findSection + 2 >= message.size())
{
using std::literals::string_literals::operator""s;
return ""s;
}
findSection += 2;
auto sectionEnd = message.find(',', findSection);
if (sectionEnd == std::string::npos)
{
sectionEnd = message.size();
}
return message.substr(findSection, (sectionEnd - findSection));
}
std::string clientFirstMessageBare;
std::string serviceFirstMessage;
std::string serverSignature64;
std::string clientProof64;
NonceGenerator nonceGenerator;
public:
ScramBase(std::string const& clientFirstMessageBare, NonceGenerator&& nonceGenerator)
: clientFirstMessageBare(clientFirstMessageBare)
, nonceGenerator(std::move(nonceGenerator))
{}
protected:
std::size_t getServiceIteration() const {using std::literals::string_literals::operator""s;return std::stol(getMessageBody("i=", serviceFirstMessage));}
std::string getUserFromMessage() const {using std::literals::string_literals::operator""s;return getMessageBody("n="s, clientFirstMessageBare);}
std::string getServiceSalt() const {using std::literals::string_literals::operator""s;return getMessageBody("s="s, serviceFirstMessage);}
std::string getClientNonce() const {using std::literals::string_literals::operator""s;return getMessageBody("r="s, clientFirstMessageBare);}
std::string getServiceNonce() const {using std::literals::string_literals::operator""s;return getMessageBody("r="s, serviceFirstMessage);}
std::string getVerification(std::string const& message) const {using std::literals::string_literals::operator""s;return getMessageBody("v="s, message);}
std::string getProofFromClinet(std::string const& message) const {using std::literals::string_literals::operator""s;return getMessageBody("p="s, message);}
std::string normalize(std::string const& text) const {return text;}
std::string getClientFinalMessageWithoutProof() const {using std::literals::string_literals::operator""s;return "c=biws,r="s + getServiceNonce();}
std::string getAuthMessage() const {using std::literals::string_literals::operator""s;return clientFirstMessageBare + ","s + serviceFirstMessage + ","s + getClientFinalMessageWithoutProof();}
std::string const& getClientFirstMessageBare() const {return clientFirstMessageBare;}
std::string const& getClientProof() const {return clientProof64;}
std::string const& getServerSignature() const {return serverSignature64;}
bool validateNonce(std::string const& message) const {using std::literals::string_literals::operator""s;return getServiceNonce() == getMessageBody("r="s, message);}
void setServiceFirstMessage(std::string const& sfm) {serviceFirstMessage = sfm;}
std::string generateNonce() {return nonceGenerator();}
void calculateClientScramHash(std::string const& password)
{
Hi hi;
HMAC hmac;
H hasher;
Digest<Hi> saltedPassword;
Digest<HMAC> clientKey;
Digest<HMAC> serverKey;
Digest<HMAC> clientSignature;
Digest<HMAC> serverSignature;
Digest<H> storedKey;
using std::literals::string_literals::operator""s;
std::string saltBase64 = getServiceSalt();
std::string salt (make_decode64(std::begin(saltBase64)), make_decode64(std::end(saltBase64)));
std::string authMessage = getAuthMessage();
hi.hash(normalize(password), salt, getServiceIteration(), saltedPassword);
hmac.hash(saltedPassword.view(), "Client Key"s, clientKey);
hmac.hash(saltedPassword.view(), "Server Key"s, serverKey);
hasher.hash(clientKey, storedKey);
hmac.hash(storedKey.view(), authMessage, clientSignature);
hmac.hash(serverKey.view(), authMessage, serverSignature);
for (int loop = 0 ; loop < HMAC::digestSize; ++loop)
{
clientKey[loop] = clientKey[loop] ^ clientSignature[loop];
}
clientProof64 = std::string(make_encode64(std::begin(clientKey)), make_encode64(std::end(clientKey)));
serverSignature64 = std::string(make_encode64(std::begin(serverSignature)), make_encode64(std::end(serverSignature)));
}
};
class ScramClient: public ScramBase<Pbkdf2<HMac<Sha1>>, HMac<Sha1>, Sha1>
{
public:
ScramClient(std::string const& userName, NonceGenerator&& nonceGenerator = [](){using std::literals::string_literals::operator""s;return "fyko+d2lbbFgONRv9qkxdawL"s;})
: ScramBase(std::string("n=") + userName + ",r=" + nonceGenerator(), std::move(nonceGenerator))
{}
std::string getFirstMessage()
{
using std::literals::string_literals::operator""s;
return "n,,"s + getClientFirstMessageBare();;
}
std::string getProofMessage(std::string const& password, std::string const& sfm)
{
using std::literals::string_literals::operator""s;
setServiceFirstMessage(sfm);
calculateClientScramHash(password);
return getClientFinalMessageWithoutProof() + ",p="s + getClientProof();
}
bool verifyServer(std::string const& serverProof)
{
return getServerSignature() == getVerification(serverProof);
}
};
class ScramServer: public ScramBase<Pbkdf2<HMac<Sha1>>, HMac<Sha1>, Sha1>
{
long iterationCount;
DBInfoAccess dbInfo;
public:
ScramServer(std::string const& clientFirstMessage,
std::size_t iterationCount = 4096,
NonceGenerator&& nonceGenerator = [](){using std::literals::string_literals::operator""s;return "3rfcNHYJY1ZVvWVs7j"s;},
DBInfoAccess&& dbInfo = [](DBInfoType type, std::string const& /*user*/){using std::literals::string_literals::operator""s;return type == DBInfoType::Password ? "pencil"s : "QSXCR+Q6sek8bf92"s;})
: ScramBase(clientFirstMessage.substr(3), std::move(nonceGenerator))
, iterationCount(iterationCount)
, dbInfo(std::move(dbInfo))
{}
std::string getFirstMessage()
{
using std::literals::string_literals::operator""s;
std::string message = "r="s + getClientNonce() + generateNonce() + ",s="s + dbInfo(DBInfoType::Salt, getUserFromMessage()) + ",i="s + std::to_string(iterationCount);
setServiceFirstMessage(message);
return message;
}
std::string getProofMessage(std::string const& clientProof)
{
using std::literals::string_literals::operator""s;
calculateClientScramHash(normalize(dbInfo(DBInfoType::Password, getUserFromMessage())));
if (getClientProof() == getProofFromClinet(clientProof) && validateNonce(clientProof))
{
return "v="s + getServerSignature();
}
return "";
}
};
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T22:54:02.363",
"Id": "486629",
"Score": "1",
"body": "Why the negative vote?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T17:03:47.030",
"Id": "248419",
"Score": "2",
"Tags": [
"c++",
"cryptography",
"authentication",
"server",
"client"
],
"Title": "C++ Crypto: Part 4- Scram"
}
|
248419
|
<p>Is it better to validate and put an array value into a variable at the top of a file or to check the array value directly right before output in the file?</p>
<p>I work at a WordPress shop and we have a function that some developers commonly use to check the value of indexes in an array of custom field values:</p>
<pre><code>//Check if an array has a key and return its value if so
function pkav($arr,$key){
return isset($arr[$key]) ? $arr[$key] : false;
}
</code></pre>
<p>This leads to the following code in a template:</p>
<pre><code><?php
$options = get_fields('options');
$footer_text = pkav($options, 'footer_text');
$footer_button = pkav($options, 'footer_button');
?>
<!-- Other code here -->
<?php if ( $footer_text || $footer_button ) : ?>
<div class="col-12 col-lg-6">
<?php if( $footer_text ) : ?>
<h4><?php echo esc_html( $footer_text ); ?></h4>
<?php endif; ?>
<?php if( $footer_button ) : ?>
<?php pk_output_button( $footer_button ); ?>
<?php endif; ?>
</div>
<?php endif; ?>
</code></pre>
<p>Some devs think this is more readable and a better way to code and check values/variables. It also allows us to neatly declare all variables at the top of a file so we immediately know what variables are used in a given template/template part. We have other devs who think pkav is unnecessary and an incorrect way to use variables. They'd rather see code like this:</p>
<pre><code><?php
$options = get_fields('options');
?>
<!-- Other code here -->
<?php if ( ! empty( $options['footer_text'] ) || ! empty( $options['footer_button'] ) ) : ?>
<div class="col-12 col-lg-6">
<?php if( ! empty( $options['footer_text'] ) ) : ?>
<h4><?php echo esc_html( $options['footer_text'] ); ?></h4>
<?php endif; ?>
<?php if( ! empty( $options['footer_button'] ) ) : ?>
<?php pk_output_button( $options['footer_button'] ); ?>
<?php endif; ?>
</div>
<?php endif; ?>
</code></pre>
<p>Is there a right answer on what should be used in terms of php/wordpress/programming best practices/standards? The pkav functions seems to create more readable code by eliminating duplicate <code>empty()</code> checks and shortening each line but using only <code>empty()</code> checks seems to prevent creating extra variables.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T03:34:34.970",
"Id": "486638",
"Score": "0",
"body": "Either way, `pkav` is a terrible function name. Or abbreviated: ew, `pkav` is a trbl fnn. See how ridiculously difficult it Is for a reader to understand abbreviated text? Its the same with source codes..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T03:57:54.977",
"Id": "486639",
"Score": "0",
"body": "@slepic I completely agree, I'm just trying to get some direction on which approach to take before I worry about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:16:45.087",
"Id": "486640",
"Score": "0",
"body": "Is this from your job? Are there other templates already written? If you have to choose from the two, choose whichever approach is already used in the other templates. Staying consistent throughout entire codebase is often the best approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T04:21:25.007",
"Id": "486641",
"Score": "0",
"body": "I dont know how WordPress handles template variables, but it would be best if you had all the variables expanded like in your first snippet, but instead of doing it in the top of the template, do it wherever you choose the template file to render."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T08:45:40.983",
"Id": "487007",
"Score": "1",
"body": "The title of your question must uniquely describe what your script does, not what your concerns are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T13:50:38.737",
"Id": "489917",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which 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)."
}
] |
[
{
"body": "<p>I would not use the <code>pkav</code> function. Beside the fact that the name means nothing (which was stated in the comments) it also restricts the default value to <code>false</code>.<br />\nThis is wrong when you might expect strings or something else for a certain variable.<br />\nFrom the looks of it, the footer text and button vars look like strings.</p>\n<p>I would go with this</p>\n<pre><code><?php\n $options = get_fields('options');\n $footer_text = $options['footer_text'] ?? '';\n $footer_button = $options['footer_button'] ?? '';\n?>\n</code></pre>\n<p>I would also go with declaring all variables at the top of the file. It makes the code more readable and will allow a frontend developer to focus on the html part instead of trying to navigate in the <code>if</code> statements.</p>\n<pre><code><?php if ($something) :?>\n <div><?= esc_html($something) ;?></div>\n<?php endif;?>\n</code></pre>\n<p>is easier to read than</p>\n<pre><code><?php if (!empty( $options['footer_text'])) : ?>\n <h4><?php echo esc_html($options['footer_text']); ?></h4>\n<?php endif; ?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T11:28:10.850",
"Id": "248453",
"ParentId": "248420",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T17:20:24.320",
"Id": "248420",
"Score": "2",
"Tags": [
"php",
"comparative-review",
"wordpress"
],
"Title": "Efficiently use array values and variables in a WordPress template"
}
|
248420
|
<p>I normally program in a linux vm and decided to do some machine learning with my webcam when I realized the vm didn't have access to my camera hardware.</p>
<p>That kicked-off a mini project to create a plug-and-play module to access the webcam in a browser and redirect through a Go backend so I could work around the limitations of my vm but also reuse the code in future webapps. After a bit of research WebRTC seemed like the best way to handle a full video stream (as opposed to grabbing and posting frames from canvas)</p>
<p>Right now the code uses websockets to establish a webrtc Peer Connection between the browser and server and write the webcam video stream to disk. Next steps are replacing <code>saveToDisk</code> with a gRPC endpoint exposing the stream for processing via Python/Tensorflow but haven't gotten to that yet</p>
<p>Since I've never written in Javascript or used Websockets or WebRTC before any and all feedback is appreciated! I tried to keep the Go and JS APIs as similar as possible for ease of use. I also didn't include the basic server in <code>main.go</code> or <code>index.html</code> since they just call the functions below (hence plug-and-play; simply serve <code>webRTCHandle</code> and load <code>webRTCClient</code> however you want to automatically get access to the webcam stream) but can if anyone wants to see</p>
<p>JS:</p>
<pre><code>export function webRTCClient() {
var conn = new connHandler()
conn.startUserMedia()
conn.sendIceCandidates()
conn.startListener()
}
// Default ICEServers - Google provides public testing server
const defaultIceServers = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
}
const userMediaSettings = { video: true }
class connHandler {
constructor() {
// Establish websocket signalling channel and new webRTCPeerConnection
this.socket = new WebSocket("ws://" + window.location.hostname + ":8080/ws")
this.peerConnection = new RTCPeerConnection(defaultIceServers)
this.listener = null
// Server (offer) and client (answer) can't switch once established
// Client signals server when renegotiation is necessary
this.peerConnection.onnegotiationneeded = e => {
this.send("renegotiate")
}
}
send(payload) {
this.socket.send(JSON.stringify(payload))
}
startUserMedia() {
// Acces getUserMedia API and stream video track
// Add audio with "audio: true" and getAudioTracks()
let conn = this
const f = async function startStream() {
let source = await navigator.mediaDevices.getUserMedia(userMediaSettings)
for (const track of source.getVideoTracks()) {
conn.peerConnection.addTrack(track, source)
}
}
f()
}
sendIceCandidates() {
// Whenever there is a new ICECandidate send to server
this.peerConnection.onicecandidate = event => {
if (event.candidate != null) {
this.send(event.candidate)
}
}
}
startListener() {
// Client receives ICECandidates or Descriptions
this.socket.onmessage = event => {
var message = JSON.parse(event.data)
if (message.sdp) {
// Once local and remote descriptions are synced connection will be formed
this.peerConnection.setRemoteDescription(new RTCSessionDescription(message))
this.peerConnection.createAnswer()
.then(answer => {
this.peerConnection.setLocalDescription(answer)
this.send(answer)
})
} else if (message.candidate) {
this.peerConnection.addIceCandidate(message)
}
}
}
}
</code></pre>
<p>Go:</p>
<pre><code>package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/pion/rtcp"
"github.com/pion/webrtc"
"github.com/pion/webrtc/pkg/media"
"github.com/pion/webrtc/pkg/media/h264writer"
)
// Implements http.Handler interface so works with any server (httprouter, gorillca/mux, etc)
func webRTCHandle(w http.ResponseWriter, r *http.Request) {
conn, err := newConnHandler(w, r)
if err != nil {
fmt.Fprint(w, "Unable to connect: ", err)
}
conn.startUserMedia()
conn.sendIceCandidates()
conn.sendOffer()
conn.startListener()
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 512,
WriteBufferSize: 512,
}
var defaultIceServers = webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
}
type connHandler struct {
socket *websocket.Conn
peerConnection *webrtc.PeerConnection
}
func newConnHandler(w http.ResponseWriter, r *http.Request) (connHandler, error) {
conn := connHandler{}
// Upgrade http to websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return conn, err
}
// Create new webrtc peer connection obj
// Note: connection to client won't be formed until local and remote descriptions are set
pc, err := newPeerConnection()
if err != nil {
return conn, err
}
conn.socket = ws
conn.peerConnection = pc
return conn, nil
}
func newPeerConnection() (*webrtc.PeerConnection, error) {
m := webrtc.MediaEngine{}
m.RegisterCodec(webrtc.NewRTPH264Codec(webrtc.DefaultPayloadTypeH264, 90000))
api := webrtc.NewAPI(webrtc.WithMediaEngine(m))
peerConnection, err := api.NewPeerConnection(defaultIceServers)
if err != nil {
return nil, err
}
if _, err = peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo); err != nil {
return nil, err
}
return peerConnection, nil
}
func (conn *connHandler) send(message interface{}) {
payload, err := json.Marshal(message)
if err != nil {
log.Println(err)
}
err = conn.socket.WriteMessage(websocket.TextMessage, payload)
if err != nil {
log.Println("message not sent")
}
}
func (conn *connHandler) startUserMedia() {
h264File, err := h264writer.New("output.264")
if err != nil {
log.Println(err)
}
conn.peerConnection.OnTrack(func(track *webrtc.Track, receiver *webrtc.RTPReceiver) {
// Send heartbeat - copied from Pion example code
go func() {
ticker := time.NewTicker(time.Second * 3)
for range ticker.C {
errSend := conn.peerConnection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: track.SSRC()}})
if errSend != nil {
log.Println(errSend)
}
}
}()
codec := track.Codec()
if codec.Name == webrtc.H264 {
saveToDisk(h264File, track)
}
})
}
func (conn *connHandler) sendIceCandidates() {
conn.peerConnection.OnICECandidate(func(c *webrtc.ICECandidate) {
if c == nil {
return
}
conn.send(c.ToJSON())
})
}
func (conn *connHandler) sendOffer() {
offer, err := conn.peerConnection.CreateOffer(nil)
if err != nil {
log.Println(err)
}
if err = conn.peerConnection.SetLocalDescription(offer); err != nil {
log.Println(err)
}
conn.send(offer)
}
func (conn *connHandler) startListener() {
var renegotiate string
var candidate webrtc.ICECandidateInit
var sessDesc webrtc.SessionDescription
for {
_, p, err := conn.socket.ReadMessage()
if err != nil {
conn.peerConnection.Close()
return
}
if err = json.Unmarshal(p, &renegotiate); renegotiate == "renegotiate" {
conn.sendOffer()
renegotiate = ""
} else if err = json.Unmarshal(p, &sessDesc); sessDesc.Type == webrtc.SDPTypeAnswer {
conn.peerConnection.SetRemoteDescription(sessDesc)
sessDesc = webrtc.SessionDescription{}
} else if err = json.Unmarshal(p, &candidate); err != nil {
conn.peerConnection.AddICECandidate(candidate)
candidate = webrtc.ICECandidateInit{}
}
}
}
// Copied from Pion example code
// Replace with gRPC endpoint
func saveToDisk(i media.Writer, track *webrtc.Track) {
defer func() {
if err := i.Close(); err != nil {
log.Println(err)
}
}()
for {
rtpPacket, err := track.ReadRTP()
if err != nil {
log.Println(err)
}
if err := i.WriteRTP(rtpPacket); err != nil {
log.Println(err)
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T13:15:53.880",
"Id": "486670",
"Score": "0",
"body": "Your JavaScript WebRTC code looks great to me. I don't know golang but from inspection it looks great too."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T18:43:02.027",
"Id": "248425",
"Score": "2",
"Tags": [
"javascript",
"go",
"stream",
"websocket"
],
"Title": "Javascript / Go plug-and-play server-side WebRTC support for webcam streaming"
}
|
248425
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.